@theokit/gateway-whatsapp 0.5.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +43 -0
- package/README.md +10 -3
- package/dist/index.cjs +47 -26
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +31 -32
- package/dist/index.d.ts +31 -32
- package/dist/index.js +47 -26
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/allowlist.ts","../src/backend/baileys/normalize.ts","../src/errors.ts","../src/backend/baileys/socket.ts","../src/backend/baileys/index.ts","../src/inbound-rules.ts","../src/backend/cloud/client.ts","../src/backend/cloud/signature.ts","../src/backend/cloud/webhook.ts","../src/backend/cloud/index.ts","../src/backend/web/ipc.ts","../src/backend/web/lifecycle.ts","../src/backend/web/index.ts","../src/own-number.ts","../src/split.ts","../src/adapter.ts"],"names":["GatewayConfigurationError","resolve","crypto","path","fs","execSync","spawn","DEFAULT_CONNECT_TIMEOUT_MS","DEFAULT_SEND_TIMEOUT_MS","path2","fileURLToPath","existsSync","chunkText","BasePlatformAdapter"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,IAAM,QAAA,GAAW,GAAA;AAcV,SAAS,oBAAoB,KAAA,EAAuB;AACzD,EAAA,MAAM,aAAA,GAAgB,KAAA,CAAM,OAAA,CAAQ,aAAA,EAAe,EAAE,CAAA;AACrD,EAAA,MAAM,aAAA,GAAgB,aAAA,CAAc,OAAA,CAAQ,MAAA,EAAQ,EAAE,CAAA;AACtD,EAAA,OAAO,aAAA,CAAc,OAAA,CAAQ,KAAA,EAAO,EAAE,CAAA;AACxC;AASO,SAAS,oBAAoB,GAAA,EAA8C;AAChF,EAAA,MAAM,OAAA,GAAA,CAAW,GAAA,IAAO,EAAA,EACrB,KAAA,CAAM,GAAG,CAAA,CACT,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AAA,MAAM,SAAiC,EAAC;AACxC,IAAA,KAAA,MAAW,OAAA,IAAW,wBAAA,CAAyB,QAAQ,CAAA,EAAG;AACxD,MAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,kBAAA,CAAmB,OAAO,CAAA;AAC7C,MAAA,IAAI,KAAA,KAAU,MAAA,EAAW,MAAA,CAAO,IAAA,CAAK,KAAK,CAAA;AAAA,IAC5C;AACA,IAAA,OAAO,MAAA;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,gBAAgB,OAAA,EAAwE;AACtF,IAAA,IAAA,CAAK,iBAAA,IAAoB;AACzB,IAAA,IAAA,CAAK,aAAA,GAAgB,OAAA;AACrB,IAAA,MAAM,GAAA,GAAM,IAAA,CAAK,WAAA,CAAY,eAAA,CAAgB,OAAO,CAAA,KAAM;AACxD,MAAA,IAAI,mBAAmB,CAAA,EAAG,IAAA,CAAK,gBAAA,EAAkB,IAAA,CAAK,sBAAsB,CAAA,EAAG;AAC/E,MAAA,MAAM,IAAA,CAAK,gBAAgB,CAAC,CAAA;AAAA,IAC9B,CAAC,CAAA;AACD,IAAA,IAAA,CAAK,iBAAA,GAAoB,GAAA;AACzB,IAAA,OAAO,MAAM;AAEX,MAAA,IAAI,IAAA,CAAK,kBAAkB,OAAA,EAAS;AAClC,QAAA,IAAA,CAAK,aAAA,GAAgB,MAAA;AACrB,QAAA,GAAA,EAAI;AACJ,QAAA,IAAA,CAAK,iBAAA,GAAoB,MAAA;AAAA,MAC3B;AAAA,IACF,CAAA;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAe,QACb,KAAA,EACgD;AAChD,IAAA,OAAO,IAAA,CAAK,UAAA,CAAW,IAAA,CAAK,OAAA,EAAS,KAAK,CAAA;AAAA,EAC5C;AACF","file":"index.cjs","sourcesContent":["/**\n * Who is allowed to reach the handler — a fail-closed sender allowlist.\n *\n * Until this existed the package had no sender filter. `shouldDropGroupMessage` fires only for\n * *groups* with `requireMention`, so any stranger who sent a direct message reached the agent.\n *\n * That is two problems wearing one coat. A number that answers strangers accumulates blocks and\n * reports, which is what WhatsApp's enforcement runs on — so an open gateway is a slow route to a\n * banned number. And an agent wired to tools acts on what arrives, so an unfiltered inbound is an\n * instruction channel for anyone who knows the number. Baileys' own `GHSA-qvv5-jq5g-4cgg` — a\n * crafted `protocolMessage` that forges a `messages.upsert` — is the same hazard reached through\n * the library rather than through the phone, and an allowlist narrows both.\n *\n * Pure by construction: no socket, no I/O, no clock. The decision is the part worth testing, and\n * it can be tested exhaustively without a phone number, which the transport around it cannot.\n *\n * @public\n */\n\n/** Allows every identified sender. Must be set deliberately; it is never the default. */\nconst WILDCARD = \"*\";\n\n/**\n * Reduce a WhatsApp identifier to the digits that identify the account.\n *\n * WhatsApp addresses carry two things that are not part of the number: a device suffix\n * (`:12`) and a domain (`@s.whatsapp.net`, `@g.us`, `@lid`). Stripping non-digits without\n * removing the suffix first merges the device id into the number —\n * `5511999999999:12@s.whatsapp.net` becomes `551199999999912`, which matches no allowlist entry,\n * so the filter silently stops recognising that sender the moment they use a second device.\n *\n * Returns `\"\"` when the input carries no identifier at all. Callers must treat that as\n * unidentified, never as a match.\n */\nexport function normalizeWhatsAppId(value: string): string {\n const withoutDevice = value.replace(/:[^@]*(?=@)/, \"\");\n const withoutDomain = withoutDevice.replace(/@.*$/, \"\");\n return withoutDomain.replace(/\\D/g, \"\");\n}\n\n/**\n * Parse a comma-separated allowlist into normalised entries.\n *\n * Blank entries are dropped rather than kept: an empty string is what an unreadable identifier\n * normalises to, so admitting `\"\"` to the set would admit precisely the senders whose id could\n * not be read. The wildcard is preserved verbatim, since normalising it would erase it.\n */\nexport function parseAllowedSenders(raw: string | undefined): ReadonlySet<string> {\n const entries = (raw ?? \"\")\n .split(\",\")\n .map((entry) => entry.trim())\n .map((entry) => (entry === WILDCARD ? WILDCARD : normalizeWhatsAppId(entry)))\n .filter((entry) => entry.length > 0);\n return new Set(entries);\n}\n\n/**\n * May `senderId` reach the handler?\n *\n * **Fail-closed.** An empty allowlist admits nobody. An operator who has not configured one has\n * not decided who may drive the agent, and the safe reading of \"has not decided\" is \"not yet\" —\n * not \"everyone\". The inverse default is a mistake worth naming: it makes the safest-looking\n * configuration, the empty one, the most open.\n *\n * An unidentifiable sender is refused even under the wildcard. `*` means \"any sender\", and\n * something whose sender cannot be named is not a sender; letting it through would make the\n * wildcard the single path that skips identification altogether.\n */\nexport function isSenderAllowed(senderId: string, allowed: ReadonlySet<string>): boolean {\n const normalized = normalizeWhatsAppId(senderId);\n if (normalized.length === 0) return false;\n if (allowed.size === 0) return false;\n if (allowed.has(WILDCARD)) return true;\n return allowed.has(normalized);\n}\n","/**\n * Baileys envelope → `WhatsAppInboundEvent`. Pure: no socket, no clock, no I/O.\n *\n * Purity is the point rather than a preference. Nothing in this repository can exercise the\n * WhatsApp protocol — pairing needs a human with a phone — so the only part of this backend\n * that can be tested exhaustively is the part that does not touch the network. Every decision\n * that can live here does.\n *\n * It returns `undefined` rather than throwing for anything it will not accept. The input\n * arrives straight off a socket from a library that has shipped a message-spoofing advisory\n * (`GHSA-qvv5-jq5g-4cgg`), so a malformed or hostile envelope is an expected case, not an\n * exceptional one — and a throw here would take down whatever is dispatching.\n *\n * @internal\n */\n\nimport { normalizeWhatsAppId } from \"../../allowlist.js\";\nimport type { WhatsAppInboundEvent } from \"../../backend-types.js\";\n\n/** WhatsApp's status feed. Never a conversation, always noise for a bot. */\nconst STATUS_BROADCAST_JID = \"status@broadcast\";\n\n/** Envelopes that carry the real message one level down. */\nconst WRAPPER_KEYS = [\n \"ephemeralMessage\",\n \"viewOnceMessage\",\n \"viewOnceMessageV2\",\n \"documentWithCaptionMessage\",\n] as const;\n\n/** How deep to follow nested wrappers before giving up. Hostile input must not recurse forever. */\nconst MAX_WRAPPER_DEPTH = 3;\n\n/** The subset of a Baileys `WAMessage` this normaliser reads. */\ninterface RawEnvelope {\n key?: {\n remoteJid?: unknown;\n participant?: unknown;\n fromMe?: unknown;\n id?: unknown;\n };\n message?: Record<string, unknown>;\n messageTimestamp?: unknown;\n pushName?: unknown;\n}\n\n/** Narrow an unknown to an object without asserting anything about its members. */\nfunction asObject(value: unknown): Record<string, unknown> | undefined {\n return typeof value === \"object\" && value !== null\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\n/** A non-empty string, or undefined. */\nfunction asText(value: unknown): string | undefined {\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\n/**\n * The plain text of a message, from either shape Baileys uses.\n *\n * `conversation` carries a bare message; `extendedTextMessage` carries one with context — a\n * reply, a link preview, a mention. v1 is text-only, like the two sibling backends, so any\n * other content type yields undefined and the message is dropped.\n */\nfunction extractText(message: Record<string, unknown> | undefined, depth = 0): string | undefined {\n if (message === undefined || depth > MAX_WRAPPER_DEPTH) return undefined;\n\n const direct = asText(message.conversation);\n if (direct !== undefined) return direct;\n\n const extended = asObject(message.extendedTextMessage);\n const fromExtended = extended === undefined ? undefined : asText(extended.text);\n if (fromExtended !== undefined) return fromExtended;\n\n // Baileys nests the real message inside a wrapper for disappearing messages and view-once.\n // Without unwrapping, every text sent in a chat with disappearing messages turned on was\n // dropped in silence — indistinguishable from an image, which the \"v1 is text-only\"\n // rationale was covering for.\n for (const wrapper of WRAPPER_KEYS) {\n const inner = asObject(message[wrapper]);\n const nested = inner === undefined ? undefined : asObject(inner.message);\n const text = extractText(nested, depth + 1);\n if (text !== undefined) return text;\n }\n return undefined;\n}\n\n/**\n * The message's timestamp in seconds, or `undefined` when it cannot be read.\n *\n * Baileys reports seconds; every other backend here reports milliseconds, which is why the\n * caller multiplies.\n *\n * Returning `undefined` — which makes the caller drop the envelope — is this module's uniform\n * contract, not a special rule: it refuses anything it cannot fully read, exactly as it refuses\n * an unidentifiable sender or a non-text body. An earlier version of this comment justified the\n * drop by a \"freshness window\" that would reject stale messages. **No such window exists** —\n * `receivedAt` is declared in `@theokit/gateway` and read by nothing. A review caught the claim.\n * The replay defence in this backend is the `type !== \"notify\"` filter on `messages.upsert`.\n *\n * Worth knowing when comparing backends: `backend/cloud/webhook.ts` takes the opposite branch,\n * substituting the current time for an unreadable stamp. Neither is wrong given that nobody\n * reads the field; they are inconsistent, and that is recorded rather than quietly aligned.\n */\nfunction toSeconds(timestamp: unknown): number | undefined {\n if (typeof timestamp === \"number\") return timestamp;\n if (typeof timestamp === \"string\") {\n const parsed = Number(timestamp);\n return Number.isFinite(parsed) ? parsed : undefined;\n }\n // Baileys' generated protobuf types permit a `Long`. Read as unparseable, a perfectly good\n // message from a real user would be dropped for a field nobody reads — so the shape is\n // handled rather than refused.\n const asLong = asObject(timestamp);\n if (asLong !== undefined && typeof asLong.toNumber === \"function\") {\n const parsed = (asLong.toNumber as () => unknown)();\n return typeof parsed === \"number\" && Number.isFinite(parsed) ? parsed : undefined;\n }\n return undefined;\n}\n\n/**\n * Who sent this, and where does it belong?\n *\n * In a group the channel is the group and the sender is the participant; in a DM both are\n * `remoteJid`. Reading `remoteJid` as the sender in a group would attribute every group\n * message to the group itself, which breaks the allowlist and any per-sender session key at\n * once. Returns `undefined` when either cannot be identified — and \"we do not know who sent\n * this\" must never resolve to \"let it through\".\n */\nfunction resolveParties(\n key: Record<string, unknown>,\n remoteJid: string,\n): { fromPhone: string; channelId: string; channelJid: string; isGroup: boolean } | undefined {\n const isGroup = remoteJid.endsWith(\"@g.us\");\n const senderJid = isGroup ? asText(key.participant) : remoteJid;\n if (senderJid === undefined) return undefined;\n\n const fromPhone = normalizeWhatsAppId(senderJid);\n const channelId = normalizeWhatsAppId(remoteJid);\n if (fromPhone.length === 0 || channelId.length === 0) return undefined;\n // `remoteJid` is carried out UNCHANGED beside the normalised id. The normalisation is what the\n // allowlist compares; the raw form is the only thing a reply can be addressed to, and the two are\n // not interchangeable — stripping the domain loses which KIND of address it was (#84).\n return { fromPhone, channelId, channelJid: remoteJid, isGroup };\n}\n\n/**\n * What the backend knows that a single envelope cannot carry.\n *\n * Both fields are optional and an absent one means \"unknown\", never \"anything goes\": with no\n * context the guard below behaves exactly as it did before this type existed.\n *\n * @public\n */\nexport interface BaileysDispatchContext {\n /**\n * The JIDs that ARE this account, normalised — its phone JID and its LID.\n *\n * A set rather than one id because the self-chat is addressed by LID, not by phone JID, and\n * both forms reach the socket. An EMPTY set means the backend has not learned them yet, and\n * the safe reading of \"we do not know which chat is the self-chat\" is not \"every chat is\".\n */\n readonly selfJids?: ReadonlySet<string>;\n /** Message ids this backend sent. Its own echoes — the thing that must never be answered. */\n readonly sentWamids?: ReadonlySet<string>;\n}\n\n/**\n * Should this envelope reach a handler at all?\n *\n * Refused: the status feed, which is never a conversation, and the replies THIS BACKEND sent —\n * or the bot answers itself, forever, a lesson every backend in this package learned separately.\n *\n * The second refusal used to be spelled `fromMe`, and that was broader than the reason written\n * beside it. `fromMe` does not mean \"we sent it\"; it means \"this ACCOUNT sent it\", which includes\n * the human typing on their own phone. Measured against a real paired account on 2026-08-30: a\n * note-to-self arrives as live traffic (`upsert type=notify`, with content) and was discarded for\n * that reason alone — foreclosing the note-to-self agent, which is what this gateway family exists\n * for. Every other gateway here answers it, because there the bot is a separate identity; on\n * WhatsApp the paired account IS the person.\n *\n * So the refusal now aims at what actually causes the loop — an id we sent — and stays inside the\n * self-chat. A message the owner sent to SOMEBODY ELSE is still refused: answering there would put\n * the agent into a third party's conversation, in the owner's name, triggered by the owner's own\n * words.\n */\nfunction isDispatchable(\n key: Record<string, unknown>,\n remoteJid: string,\n wamid: string,\n ctx: BaileysDispatchContext | undefined,\n): \"no\" | \"yes\" | \"yes-from-self\" {\n if (remoteJid === STATUS_BROADCAST_JID) return \"no\";\n if (key.fromMe !== true) return \"yes\";\n\n const selfJids = ctx?.selfJids;\n if (selfJids === undefined || selfJids.size === 0) return \"no\";\n if (!selfJids.has(normalizeWhatsAppId(remoteJid))) return \"no\";\n return ctx?.sentWamids?.has(wamid) === true ? \"no\" : \"yes-from-self\";\n}\n\n/** The envelope's addressing, once every field it needs has been read and none was missing. */\ninterface Addressed {\n readonly key: Record<string, unknown>;\n readonly remoteJid: string;\n readonly wamid: string;\n}\n\n/**\n * Read the envelope's addressing, or refuse it.\n *\n * Split from {@link normalizeBaileysMessage} because the two halves answer different questions:\n * this one asks whether the envelope IS one — has a key, a chat, an id — and the caller asks\n * whether it should be delivered. Together they read as one ladder of early returns, which is\n * what pushed the function past its complexity budget when the dispatch verdict grew a third\n * outcome.\n */\nfunction addressingOf(envelope: RawEnvelope | undefined): Addressed | undefined {\n const key = envelope === undefined ? undefined : asObject(envelope.key);\n if (key === undefined) return undefined;\n const remoteJid = asText(key.remoteJid);\n const wamid = asText(key.id);\n if (remoteJid === undefined || wamid === undefined) return undefined;\n return { key, remoteJid, wamid };\n}\n\n/**\n * Normalise one inbound envelope, or refuse it.\n *\n * Refused: the replies this backend sent, messages this account sent OUTSIDE its own self-chat,\n * the status feed, any content that is not text, and anything whose sender cannot be identified.\n * That last one matters most — an event with an unidentifiable sender would reach an allowlist\n * with nothing to match against, and the safe reading of \"we do not know who sent this\" is not\n * \"let it through\". See {@link BaileysDispatchContext} for what the backend must supply before a\n * note-to-self can be answered at all.\n */\nexport function normalizeBaileysMessage(\n raw: unknown,\n ctx?: BaileysDispatchContext,\n): WhatsAppInboundEvent | undefined {\n const envelope = asObject(raw) as RawEnvelope | undefined;\n const addressed = addressingOf(envelope);\n if (addressed === undefined) return undefined;\n\n const { key, remoteJid, wamid } = addressed;\n const verdict = isDispatchable(key, remoteJid, wamid, ctx);\n if (verdict === \"no\") return undefined;\n\n const text = extractText(envelope?.message);\n if (text === undefined) return undefined;\n\n const parties = resolveParties(key, remoteJid);\n if (parties === undefined) return undefined;\n\n const seconds = toSeconds(envelope?.messageTimestamp);\n if (seconds === undefined) return undefined;\n\n const contactName = asText(envelope?.pushName);\n\n return {\n wamid,\n fromPhone: parties.fromPhone,\n conversationType: parties.isGroup ? \"group\" : \"dm\",\n channelId: parties.channelId,\n channelJid: parties.channelJid,\n text,\n receivedAt: seconds * 1_000,\n backend: \"baileys\",\n raw,\n ...(verdict === \"yes-from-self\" ? { fromSelf: true } : {}),\n ...(contactName !== undefined ? { contactName } : {}),\n };\n}\n","/**\n * Per-backend HTTP/IPC error → canonical `WhatsAppSendResult.error` shape.\n *\n * Cloud follows Meta error codes (https://developers.facebook.com/docs/graph-api/guides/error-handling).\n * Web follows whatsapp-web.js error strings.\n *\n * @internal\n */\n\nimport { GatewayConfigurationError, type GatewayConfigurationErrorOptions } from \"@theokit/gateway\";\n\nimport type { WhatsAppError, WhatsAppSendResult } from \"./backend-types.js\";\n\ntype ErrorPayload = Required<WhatsAppSendResult>[\"error\"];\n\ninterface MetaErrorBody {\n error?: {\n code?: number;\n message?: string;\n error_subcode?: number;\n };\n}\n\n/**\n * Public input shape for the {@link ConfigurationError} constructor.\n *\n * Aliased from the core rather than redeclared. The base type exists precisely so every\n * adapter stops writing its own copy of the same three fields, and a redeclaration means a\n * field added to the core silently never reaches this package. Four siblings alias it the\n * same way.\n */\nexport type ConfigurationErrorOptions = GatewayConfigurationErrorOptions;\n\n/**\n * A required option is missing or empty.\n *\n * Raised where a consumer hands us configuration — the factories — rather than later, when\n * the value is finally used against the network. A factory that returns an adapter which\n * cannot authenticate has moved the error away from its cause: the stack then names a send,\n * and the mistake was in construction.\n *\n * Matches the shape every sibling adapter uses (`gateway-line`, `gateway-email`, …), which\n * is what makes one `catch (e) { if (e instanceof GatewayConfigurationError) }` work across\n * all of them.\n *\n * @public\n */\nexport class ConfigurationError extends GatewayConfigurationError {\n override readonly name = \"ConfigurationError\";\n constructor(opts: ConfigurationErrorOptions) {\n super(\"gateway-whatsapp\", opts);\n }\n}\n\n/**\n * The bridge reported, on its own protocol, that it cannot start.\n *\n * Distinct from {@link WhatsAppConnectTimeoutError}, which says only that nothing arrived in\n * time. This one carries what the bridge said — and, when it could classify itself, a\n * machine-readable `code` such as `peer_missing`, `peer_incompatible` or `peer_load_failed`.\n * The difference matters to a caller: a timeout may be worth retrying, and a peer dependency\n * that does not export what we need never will be.\n *\n * @public\n */\nexport class WhatsAppBridgeError extends Error {\n override readonly name = \"WhatsAppBridgeError\";\n /** Cause as named by the bridge, when it could name one. */\n readonly code: string | undefined;\n\n constructor(message: string, code?: string) {\n super(`WhatsApp web bridge could not start: ${message}`);\n this.code = code;\n }\n}\n\n/** Custom error: `connect()` timed out waiting for \"ready\" (EC-6). */\nexport class WhatsAppConnectTimeoutError extends Error {\n constructor(timeoutMs: number) {\n super(`WhatsApp web bridge connect timed out after ${timeoutMs}ms (QR code not scanned?)`);\n this.name = \"WhatsAppConnectTimeoutError\";\n }\n}\n\n/**\n * Meta's published error codes, by consequence for the caller.\n *\n * These are six-digit codes, and the mapper used to test `errCode === 130 || errCode === 131`\n * — a condition no Cloud API response can satisfy. The rate-limit branch was dead, every real\n * throttle arrived as `invalid_request`, and a consumer's backoff never fired (#46). The unit\n * test that claimed to cover it passed on the HTTP status while feeding a fabricated code.\n *\n * Numbers verified against Meta's error-code table rather than recalled.\n */\nconst RATE_LIMIT_CODES = new Set([\n 4, // the app reached its API call rate limit\n 80007, // the WhatsApp Business Account reached its rate limit\n 130429, // Cloud API message throughput reached\n]);\nconst UNDELIVERABLE_CODES = new Set([\n 130403, // the business has blocked this user\n 131026, // no WhatsApp account, terms not accepted, or an outdated client\n]);\n/** More than 24h since the recipient last replied. Remedy: resend as a template. */\nconst SESSION_WINDOW_EXPIRED_CODE = 131047;\n/**\n * The recipient was never registered against this number. Remedy: a console step, not a payload.\n *\n * Its own code for the same reason 131047 has one — the remedy is specific and different from\n * every other error here. And it is the error most Cloud API integrations meet first: every app\n * starts on a free test number whose recipients must be registered one by one, so a developer\n * whose payload is correct gets told `invalid_request` and goes to re-read the payload.\n */\nconst RECIPIENT_NOT_ALLOWLISTED_CODE = 131030;\n\n/**\n * Which canonical code this failure is, derived from Meta's status and error number.\n *\n * The return type is `WhatsAppError[\"code\"]` rather than a hand-listed union. It WAS hand-listed,\n * and a review caught that: the commit extracting `WhatsAppError` claimed to have removed the\n * second declaration that would \"drift the moment somebody adds a code to one of them\", and left\n * this one — already drifted, missing `timeout`. One vocabulary, one declaration.\n */\nfunction cloudErrorCode(status: number, errCode: number): WhatsAppError[\"code\"] {\n if (errCode === 190 || status === 401) return \"auth_failed\";\n if (RATE_LIMIT_CODES.has(errCode) || status === 429) return \"rate_limit\";\n // Ordered before the generic 400 branch: all three arrive as HTTP 400, and the\n // specific code is the only thing separating \"fix your payload\" from \"send a\n // template\" and from \"this recipient will never receive it\".\n if (errCode === SESSION_WINDOW_EXPIRED_CODE) return \"session_window_expired\";\n if (errCode === RECIPIENT_NOT_ALLOWLISTED_CODE) return \"recipient_not_allowlisted\";\n if (UNDELIVERABLE_CODES.has(errCode)) return \"undeliverable\";\n if (status === 400 || errCode === 100) return \"invalid_request\";\n if (status >= 500) return \"server_error\";\n return \"unknown\";\n}\n\n/**\n * Map a Cloud API HTTP failure into the canonical `{ code, message }` payload.\n *\n * Takes the status alongside the body because Meta returns the same envelope shape for very\n * different faults, and the status is what separates a rejected payload from an expired token.\n */\nexport function mapWhatsAppCloudError(status: number, body: unknown): ErrorPayload {\n const parsed = (body !== null && typeof body === \"object\" ? body : {}) as MetaErrorBody;\n const errCode = parsed.error?.code ?? 0;\n const errMsg = parsed.error?.message ?? `HTTP ${status}`;\n const code = cloudErrorCode(status, errCode);\n if (code === \"auth_failed\") return { code, message: `Bearer token rejected: ${errMsg}` };\n if (code === \"rate_limit\") return { code, message: `Throttled: ${errMsg}` };\n if (code === \"recipient_not_allowlisted\") {\n // The remedy travels with the error, like its sibling above. Naming where the list lives is\n // the difference between a one-minute fix and an afternoon spent on a correct payload.\n return {\n code,\n message:\n `Recipient is not on this number's allowed list — register it under the phone number in ` +\n `the app's WhatsApp API setup before sending: ${errMsg}`,\n };\n }\n if (code === \"session_window_expired\") {\n // The remedy travels with the error. A caller reading only the code knows to\n // switch to a template; a human reading a log should not have to look it up.\n return {\n code,\n message: `Outside the 24-hour service window — send an approved template instead: ${errMsg}`,\n };\n }\n return { code, message: errMsg };\n}\n\n/**\n * Map an error string from the `whatsapp-web.js` bridge into the canonical payload.\n *\n * The bridge speaks over IPC and can only send text, so this is the boundary where a line of stderr\n * becomes a structured error. `undefined` maps to an `unknown` code rather than throwing.\n */\nexport function mapWhatsAppWebError(ipcError: string | undefined): ErrorPayload {\n const msg = ipcError ?? \"unknown bridge error\";\n if (msg.includes(\"AUTHENTICATION\") || msg.includes(\"UNAUTHORIZED\")) {\n return { code: \"auth_failed\", message: msg };\n }\n if (msg.includes(\"RATE\") || msg.includes(\"THROTTLE\")) {\n return { code: \"rate_limit\", message: msg };\n }\n if (msg.includes(\"PROTOCOL\") || msg.includes(\"DISCONNECT\")) {\n return { code: \"server_error\", message: msg };\n }\n if (msg.includes(\"TIMEOUT\")) {\n return { code: \"timeout\", message: msg };\n }\n return { code: \"unknown\", message: msg };\n}\n","/**\n * The socket contract this backend depends on, and the real factory behind it (ADR D319).\n *\n * Three members, not Baileys' whole `WASocket`. Two things follow, and both are the reason\n * the contract is ours rather than the library's.\n *\n * It was five, and two rounds of review took two members off it, both declared and called by\n * nothing. `logout()` went first and mattered most: on WhatsApp it UNPAIRS the device, the\n * opposite of what `disconnect()` means here, so the next person needing a teardown would find\n * it, call it, and lose the session the whole `sessionDir` exists to keep. `ev.off()` went for\n * the plain reason — nothing removed a listener, because a socket is discarded whole rather\n * than unsubscribed from. Neither was a capability we had; both read as one.\n *\n * **The backend is testable with `baileys` absent.** It is an optional peer dependency, so\n * CI does not install it — and a backend that could only be exercised with the real library\n * installed would be exercised by nothing, which is how the `web` backend reached production\n * unable to start (B-002).\n *\n * **The library stays an implementation detail of this file.** A breaking change upstream\n * lands in one place instead of wherever its types had spread. Depending on all of `WASocket`\n * to call three of its members is the interface-segregation problem stated plainly\n * (`rules/architecture.md`).\n *\n * @internal\n */\n\nimport { ConfigurationError } from \"../../errors.js\";\n\n/** A Baileys connection-state update, narrowed to what the lifecycle reads. */\nexport interface BaileysConnectionUpdate {\n readonly connection?: \"close\" | \"connecting\" | \"open\";\n readonly qr?: string;\n readonly lastDisconnect?: { readonly error?: unknown };\n}\n\n/** The events this backend subscribes to. Anything else Baileys emits is ignored. */\nexport interface BaileysEventMap {\n \"connection.update\": BaileysConnectionUpdate;\n \"messages.upsert\": { readonly messages: readonly unknown[]; readonly type?: string };\n \"creds.update\": unknown;\n}\n\n/**\n * What this backend needs a socket to be.\n *\n * Deliberately structural: any object with these members satisfies it, which is what lets a\n * test hand over a fake without importing anything from Baileys.\n */\nexport interface BaileysSocketLike {\n readonly ev: {\n on<K extends keyof BaileysEventMap>(\n event: K,\n listener: (payload: BaileysEventMap[K]) => void,\n ): void;\n };\n sendMessage(\n jid: string,\n content: { text: string },\n ): Promise<{ key?: { id?: string } } | undefined>;\n /**\n * Ask the server which numbers are registered, and under which JID it routes them.\n *\n * Optional because an older Baileys, or a fake in a test that predates this, may not have it.\n * When it is absent the backend sends to the number as given — the behaviour before #82 — rather\n * than refusing everything, because refusing on a missing capability would turn an upgrade\n * problem into an outage.\n */\n onWhatsApp?(...numbers: string[]): Promise<Array<{ exists?: boolean; jid?: string }> | undefined>;\n /**\n * Who this socket logged in as — present once the connection opens.\n *\n * Optional because a socket that never opened has no identity to report, and because tests\n * replace this object wholesale. The backend reads BOTH ids: the self-chat is addressed by\n * `lid`, not by `id`, so knowing only one leaves it unrecognised.\n */\n readonly user?: { readonly id?: string; readonly lid?: string };\n end?(error?: Error): void;\n}\n\n/** How a socket comes into being. Replaced wholesale in tests. */\nexport type BaileysSocketFactory = (opts: BaileysSocketOptions) => Promise<BaileysSocketLike>;\n\n/** What the real factory needs to build a socket. */\nexport interface BaileysSocketOptions {\n /** Directory holding the multi-file auth state — the pairing, persisted. */\n readonly sessionDir: string;\n /** Overrides the module the factory loads. Tests point it at a stub; production never sets it. */\n readonly specifier?: string;\n /**\n * Called with the pairing QR, as often as WhatsApp reissues it.\n *\n * Without somewhere for this to go, a fresh `sessionDir` can only ever time out: there is\n * no other way to pair, and `printQRInTerminal` is off because a library writing to stdout\n * is a library deciding where a host application's output goes. Defaults to writing the\n * code to **stderr**, which is what the `web` bridge does and what keeps stdout free for a\n * host that is using it for something.\n */\n readonly onQr?: (qr: string) => void;\n}\n\n/** Shape of the `baileys` module surface this factory uses. */\ninterface BaileysModule {\n makeWASocket?: (config: Record<string, unknown>) => BaileysSocketLike;\n default?: ((config: Record<string, unknown>) => BaileysSocketLike) | BaileysModule;\n useMultiFileAuthState?: (\n dir: string,\n ) => Promise<{ state: unknown; saveCreds: () => Promise<void> }>;\n fetchLatestBaileysVersion?: () => Promise<{ version: unknown }>;\n}\n\n/** Read a member off the default export first, then the namespace. */\nfunction member<T>(mod: BaileysModule, name: keyof BaileysModule): T | undefined {\n const asDefault = mod.default as BaileysModule | undefined;\n const fromDefault =\n asDefault !== undefined && typeof asDefault === \"object\" ? asDefault[name] : undefined;\n return (fromDefault ?? mod[name]) as T | undefined;\n}\n\n/**\n * Build a real Baileys socket.\n *\n * The import shape follows what B-002 cost this repository to learn: read the API off the\n * default export first, check each member is callable, and report a structured error naming\n * the one that is missing. A `try/catch` around the import guards the package being absent,\n * not a member being undefined — and that gap is what killed the `web` bridge for months\n * behind a friendly \"not installed\" message that was false.\n *\n * The socket settings are ADR D322, each for a stated consequence rather than a precedent:\n * `markOnlineOnConnect: false` so the account does not read as permanently online and\n * suppress push notifications on the owner's real phone; `syncFullHistory: false` so a\n * connect does not pull the entire history; an honest `browser` triple; and the protocol\n * version fetched at connect, because a stale one is refused by the server.\n */\nexport async function createBaileysSocket(opts: BaileysSocketOptions): Promise<BaileysSocketLike> {\n const specifier = opts.specifier ?? \"baileys\";\n\n let mod: BaileysModule;\n try {\n mod = (await import(/* @vite-ignore */ specifier)) as BaileysModule;\n } catch (err) {\n throw new ConfigurationError({\n code: \"peer_missing\",\n message:\n `gateway-whatsapp: ${specifier} is not installed. ` +\n \"Run `pnpm add baileys` to use the baileys backend. \" +\n `(${err instanceof Error ? err.message : String(err)})`,\n });\n }\n\n const makeSocket = member<(config: Record<string, unknown>) => BaileysSocketLike>(\n mod,\n \"makeWASocket\",\n );\n const useAuthState = member<\n (dir: string) => Promise<{ state: unknown; saveCreds: () => Promise<void> }>\n >(mod, \"useMultiFileAuthState\");\n const fetchVersion = member<() => Promise<{ version: unknown }>>(\n mod,\n \"fetchLatestBaileysVersion\",\n );\n\n for (const [name, value] of [\n [\"makeWASocket\", makeSocket],\n [\"useMultiFileAuthState\", useAuthState],\n ] as const) {\n if (typeof value !== \"function\") {\n throw new ConfigurationError({\n code: \"peer_incompatible\",\n message:\n `gateway-whatsapp: ${specifier} is installed but does not export ${name} as a function. ` +\n `Expected a function, got ${typeof value}. The baileys backend expects the peer range ` +\n \"declared in @theokit/gateway-whatsapp.\",\n });\n }\n }\n\n // Non-null after the loop above, which exits the process path on anything else.\n const { state, saveCreds } = await (\n useAuthState as (dir: string) => Promise<{ state: unknown; saveCreds: () => Promise<void> }>\n )(opts.sessionDir);\n\n // A stale protocol version is refused by the server. Absent this export we still connect;\n // Baileys then uses its bundled default, which is a worse guess but not a failure.\n const version = typeof fetchVersion === \"function\" ? (await fetchVersion()).version : undefined;\n\n const socket = (makeSocket as (config: Record<string, unknown>) => BaileysSocketLike)({\n auth: state,\n printQRInTerminal: false,\n markOnlineOnConnect: false,\n syncFullHistory: false,\n browser: [\"theokit-gateway\", \"chrome\", \"1.0.0\"],\n ...(version !== undefined ? { version } : {}),\n });\n\n // The pairing surface (F4). `printQRInTerminal` stays false — a library writing to stdout\n // decides where a host's output goes — so the code is handed to the caller, defaulting to\n // stderr. Without this a fresh session directory has no path to a pairing at all.\n const onQr =\n opts.onQr ??\n ((qr: string) => {\n process.stderr.write(\n `\\n[whatsapp-baileys] Scan this QR with WhatsApp — Settings, Linked devices, Link a device:\\n${qr}\\n\\n`,\n );\n });\n socket.ev.on(\"connection.update\", (update) => {\n if (typeof update.qr === \"string\" && update.qr.length > 0) onQr(update.qr);\n });\n\n socket.ev.on(\"creds.update\", () => {\n // Persisting credentials is what makes a pairing survive a restart. The callback is\n // sync, so the promise is deliberately floated — with a catch, because an unhandled\n // rejection here would end the process (the defect fixed across the adapters in #41).\n void saveCreds().catch((err: unknown) => {\n const message = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[whatsapp-baileys] could not persist credentials: ${message}\\n`);\n });\n });\n\n return socket;\n}\n","/**\n * `WhatsAppBaileysBackend` — the third implementation of `WhatsAppBackend` (B-001).\n *\n * Baileys speaks the WhatsApp Web multi-device protocol over a WebSocket, with no browser.\n * That is the whole difference from the `web` backend, which drives a headless Chromium.\n *\n * **Unofficial, and no amount of code changes that.** It automates a WhatsApp Web session,\n * which Meta's terms do not sanction and which can get a number banned. Use a number created\n * for this, never a personal one. Prefer {@link WhatsAppCloudBackend} unless the number has\n * no Cloud API access.\n *\n * **Added rather than replacing**, for three reasons that a substitution would not give:\n * nobody loses a paired session (a Puppeteer profile and a multi-file auth state are not\n * interchangeable), the comparison against the incumbent becomes measurable rather than\n * asserted, and retreat stays cheap because nobody is forced onto it.\n *\n * @public\n */\n\nimport { normalizeWhatsAppId } from \"../../allowlist.js\";\nimport type {\n WhatsAppBackend,\n WhatsAppInboundEvent,\n WhatsAppOutboundMessage,\n WhatsAppSendResult,\n WhatsAppStatusReceipt,\n} from \"../../backend-types.js\";\nimport { normalizeBaileysMessage } from \"./normalize.js\";\nimport {\n type BaileysSocketFactory,\n type BaileysSocketLike,\n createBaileysSocket,\n} from \"./socket.js\";\n\n/**\n * Close a socket without caring whether it was already gone.\n *\n * Tearing down something that has already closed is not a failure worth reporting: the\n * caller asked for it closed, and it is closed.\n */\nfunction endQuietly(socket: BaileysSocketLike): void {\n try {\n socket.end?.();\n } catch {\n // Deliberately empty — see the docblock.\n }\n}\n\n/** How long to wait for the socket to report `open` before giving up. */\nconst DEFAULT_CONNECT_TIMEOUT_MS = 60_000;\n/** How long to wait for one send to be acknowledged. */\nconst DEFAULT_SEND_TIMEOUT_MS = 30_000;\n\n/**\n * The answer \"WhatsApp routes this to nobody\", carried through the send chain.\n *\n * A sentinel rather than `undefined` because `sendMessage` itself resolves to `undefined` for an\n * acknowledgement with no id, and the two mean opposite things: one is a message that went out\n * without a wamid, the other is a message that was never sent.\n */\nconst UNROUTABLE = \"__unroutable__\" as const;\n\n/**\n * What one send attempt resolves to before the timeout race: the socket's acknowledgement, an\n * acknowledgement with no id, or the recipient having no route at all.\n */\ntype SendOutcome = { key?: { id?: string } } | undefined | typeof UNROUTABLE;\n/**\n * How many of our own message ids to keep, as an echo guard.\n *\n * A window rather than a log: WhatsApp delivers our own message back within seconds or not at\n * all, so recognising one from an hour ago buys nothing and an unbounded set on a long-lived\n * socket is a leak.\n */\nconst SENT_WAMID_WINDOW = 256;\n\n/**\n * What the pairing is doing, for a caller that must ASK rather than be told.\n *\n * {@link WhatsAppBaileysBackendOptions.onQr} is push: it fires when WhatsApp issues a code, at a\n * moment the caller does not choose. A screen is pull — it loads when someone opens it and has to\n * ask what is true right now. With only the callback, showing a QR anywhere means every consumer\n * keeping its own copy of the latest code and its own notion of whether pairing already succeeded,\n * which is this backend's bookkeeping copied into each of them.\n *\n * @public\n */\nexport interface WhatsAppPairingState {\n /**\n * `idle` before `connect()`, `awaiting_scan` while a code is outstanding, `connected` once the\n * socket opens, `closed` when it dies without a scan.\n */\n readonly status: \"idle\" | \"awaiting_scan\" | \"connected\" | \"closed\";\n /**\n * The most recent code, present only while `awaiting_scan`.\n *\n * WhatsApp reissues roughly every 20 seconds and the previous one stops working, so a screen\n * holding the old square shows something that cannot be scanned. It is cleared on `connected`\n * and on `closed` for the same reason: offering a code that leads nowhere is worse than\n * offering none.\n */\n readonly qr?: string;\n /** When that code arrived, so a UI can show its age instead of a stale square. */\n readonly qrAt?: number;\n}\n\n/** Construction options. @public */\nexport interface WhatsAppBaileysBackendOptions {\n /**\n * Directory holding the multi-file auth state — the pairing, persisted.\n *\n * Treat it like a credential: it is the session, and anyone holding it is the account.\n */\n readonly sessionDir: string;\n /** Give up on `connect()` after this long. Default 60s. */\n readonly connectTimeoutMs?: number;\n /** Give up on one send after this long. Default 30s. */\n readonly sendTimeoutMs?: number;\n /** Test seam: build the socket some other way. Production leaves it unset. */\n readonly socketFactory?: BaileysSocketFactory;\n /**\n * Where the pairing QR goes, as often as WhatsApp reissues it.\n *\n * **QR IS THE ONLY WAY IN.** Baileys exposes `requestPairingCode`, and WhatsApp refuses the codes\n * this backend asks for — measured 2026-08-30 across three attempts, on both the 12- and 13-digit\n * forms of a Brazilian number. The reference implementation of this same transport documents the\n * same conclusion in one line (\"Login is QR-only\") while sending a custom `browser` triple exactly\n * as this one does, so the triple is NOT established as the cause and no cause is claimed here.\n * What is established is the outcome: a caller with no route to display a QR has no route to pair.\n *\n * Defaults to stderr. It is exposed here because a host that is not a terminal — a service, a\n * container, a web app — has no way to read stderr back to the person holding the phone, and\n * without a route out the QR the session can never be paired.\n */\n readonly onQr?: (qr: string) => void;\n}\n\n/**\n * A WhatsApp backend that speaks the multi-device protocol directly.\n *\n * No browser: where {@link WhatsAppWebBackend} drives a headless Chromium through\n * `whatsapp-web.js`, this holds a WebSocket. That is the whole difference in kind.\n *\n * **Unofficial, and no amount of code changes that.** It automates a WhatsApp Web session,\n * which Meta's terms do not sanction and which can get a number banned. Use a number created\n * for this and nothing else — never a personal one. Prefer the Cloud API backend unless the\n * number has no Cloud API access.\n *\n * `baileys` is an optional peer dependency, loaded lazily at connect, so a consumer who never\n * constructs this never needs it installed.\n *\n * @public\n */\nexport class WhatsAppBaileysBackend implements WhatsAppBackend {\n readonly kind = \"baileys\" as const;\n\n private socket?: BaileysSocketLike;\n private connected = false;\n /** Guards a concurrent second `connect()` from opening a second live session. */\n private connecting?: Promise<boolean>;\n /**\n * Which connection attempt is current.\n *\n * Bumped by every `connect()` and every `disconnect()`. A socket from a superseded attempt\n * checks it before touching any state, which is what stops an abandoned socket delivering\n * inbound or flipping `connected` under a live one.\n */\n private generation = 0;\n /**\n * How to end a connection attempt that is still awaiting `open`.\n *\n * Retirement by generation makes an attempt's listeners silent, which is not the same as\n * making the attempt finish. One entry per in-flight attempt; `disconnect()` calls them so\n * the attempt settles now instead of at its timeout.\n */\n private readonly pendingAttempts = new Set<() => void>();\n /**\n * Why the socket last closed, as Baileys reported it.\n *\n * Kept because `connect()` returning `false` cannot distinguish a network blip from a\n * session the operator unlinked from their phone — and only one of those is worth retrying.\n * `rules/error-handling.md` § 3: fail clear, and log with enough context to act.\n */\n private lastCloseError?: unknown;\n /** The pairing, as a caller may ask for it. Never handed out mutable. */\n private pairingState: WhatsAppPairingState = { status: \"idle\" };\n\n /**\n * The JIDs that ARE this account, normalised. Empty until a socket reports who it logged in as.\n *\n * Empty means \"not learned yet\", and `isDispatchable` reads that as refusing everything this\n * account sent — the same behaviour as before self-chat support existed. A backend that\n * guessed here would answer in a stranger's conversation.\n */\n private selfJids: ReadonlySet<string> = new Set();\n\n /**\n * Ids this backend sent, most recent last. This is what stops the agent answering itself.\n *\n * Bounded because it is a loop guard, not a log: an unbounded set on a long-lived socket is a\n * leak, and nothing needs to recognise an echo from an hour ago — WhatsApp delivers our own\n * message back within seconds or not at all.\n */\n private sentWamids = new Set<string>();\n\n /** Record one id we sent, evicting the oldest once the window is full. @internal */\n private rememberSent(wamid: string): void {\n this.sentWamids.add(wamid);\n while (this.sentWamids.size > SENT_WAMID_WINDOW) {\n const oldest = this.sentWamids.values().next();\n if (oldest.done === true) break;\n this.sentWamids.delete(oldest.value);\n }\n }\n\n /**\n * Learn which JIDs are this account, from the socket that just logged in.\n *\n * Both forms are recorded: the phone JID and the LID. The self-chat is addressed by LID —\n * measured on a real account, where a note-to-self arrived on `231116569108705@lid` while the\n * account's phone JID was `553598838687` — so recording only one leaves the self-chat\n * unrecognised and the feature silently off.\n *\n * @internal\n */\n private learnSelfJids(socket: BaileysSocketLike): void {\n const user = socket.user;\n const ids = [user?.id, user?.lid]\n .filter((id): id is string => typeof id === \"string\" && id.length > 0)\n .map((id) => normalizeWhatsAppId(id))\n .filter((id) => id.length > 0);\n this.selfJids = new Set(ids);\n if (process.env.THEOKIT_WHATSAPP_TRACE === \"1\") {\n // Whether the real library populates `user` at all is the one thing a fake socket cannot\n // answer, and an empty set here means self-notes are refused with nothing logged.\n process.stderr.write(\n `[whatsapp-baileys][trace] selfJids learned: ${ids.length === 0 ? \"(none)\" : ids.join(\", \")}\\n`,\n );\n }\n }\n private inboundHandler?: (event: WhatsAppInboundEvent) => Promise<void>;\n private statusHandler?: (receipt: WhatsAppStatusReceipt) => Promise<void>;\n /**\n * Serialises outbound sends (ADR D320).\n *\n * Both peer gateways studied do this, and one records that concurrent sends on a single\n * socket can misdeliver to the wrong chat. We have NOT measured that in our own code — we\n * have never run a Baileys socket — so this is precaution rather than a reproduction of our\n * own bug, and saying so is the point. It is kept because the cost is one promise chain and\n * the failure it guards against is a message delivered to the wrong person.\n */\n private sendQueue: Promise<unknown> = Promise.resolve();\n\n /**\n * What WhatsApp answered about each recipient, for the life of the session.\n *\n * Holds the routable JID, or {@link UNROUTABLE} for a number the server does not know. Both are\n * worth remembering: a second send to a number that does not exist should refuse as fast as the\n * first, without another round-trip.\n */\n private readonly jidCache = new Map<string, string>();\n\n constructor(private readonly opts: WhatsAppBaileysBackendOptions) {}\n\n /**\n * Open the socket and wait for it to report `open`.\n *\n * Idempotent, and safe against a concurrent second call: the in-flight promise is shared\n * rather than a second socket being built. WhatsApp's own adapter shipped without that\n * guard once and opened two live sessions.\n */\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n if (this.connecting !== undefined) return this.connecting;\n\n const attempt = this.openSocket();\n this.connecting = attempt;\n try {\n return await attempt;\n } finally {\n // Only clear what is still ours. `disconnect()` clears it too, and a later `connect()`\n // may already have installed its own — a bare assignment here would erase that one and\n // let a third caller open a parallel socket.\n if (this.connecting === attempt) this.connecting = undefined;\n }\n }\n\n /** @internal */\n private async openSocket(): Promise<boolean> {\n // Every attempt carries a generation. A socket from an abandoned attempt must not be able\n // to speak for the backend afterwards — not to deliver inbound, not to flip `connected`,\n // and not to be left running.\n const generation = ++this.generation;\n const socket = await this.buildSocket();\n const isCurrent = (): boolean => this.generation === generation;\n\n // A `disconnect()` that landed while the factory was still resolving cannot see this\n // attempt: it is not yet in `pendingAttempts` and `this.socket` is still undefined, so the\n // teardown ends nothing. The window is not theoretical — the real factory awaits a dynamic\n // import, the auth state off disk and a network round-trip for the protocol version before\n // a socket exists. Without this check, stop-then-start in that window left a live session\n // running until the connect timeout fired.\n if (!isCurrent()) {\n endQuietly(socket);\n return false;\n }\n\n this.subscribeInbound(socket, isCurrent);\n const timeoutMs = this.opts.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;\n const openedOk = await this.raceOpen(socket, isCurrent, timeoutMs);\n\n // A `disconnect()` that arrived while this was opening wins. Adopting the socket now would\n // leave `connected` true over a backend whose socket was already cleared, and every later\n // `connect()` would short-circuit on it while every `send` was refused — the\n // teardown-during-connect wedge fixed in the Slack adapter.\n if (!isCurrent()) {\n endQuietly(socket);\n return false;\n }\n\n if (!openedOk) {\n this.reportConnectFailure(timeoutMs);\n // A failed attempt must not leave a live socket behind. It would keep feeding inbound\n // into the handler, and the retry would open a SECOND live session — which on an\n // unofficial automation is ban surface, not only a leak.\n //\n // Bumping the generation is what actually silences it: `end()` asks the socket to close,\n // and a socket mid-teardown can still emit. Retiring the generation makes every listener\n // from this attempt a no-op regardless.\n this.generation += 1;\n endQuietly(socket);\n this.socket = undefined;\n this.connected = false;\n return false;\n }\n\n // Nothing should still be here, but a socket that closed and was replaced without going\n // through the close branch would be stranded by this assignment — and a stranded Baileys\n // socket is a live session, not an unreferenced object.\n if (this.socket !== undefined && this.socket !== socket) endQuietly(this.socket);\n this.socket = socket;\n this.learnSelfJids(socket);\n this.connected = true;\n return true;\n }\n\n /**\n * What the pairing is doing right now.\n *\n * Read it as often as a screen needs; it is a snapshot, not a subscription.\n */\n get pairing(): WhatsAppPairingState {\n return this.pairingState;\n }\n\n /** Build a socket through the injected factory, or the real one. @internal */\n private async buildSocket(): Promise<BaileysSocketLike> {\n const factory = this.opts.socketFactory ?? createBaileysSocket;\n return factory({\n sessionDir: this.opts.sessionDir,\n // ALWAYS supplied, even when the caller wants none: a backend that only forwards cannot\n // answer `pairing`, and the caller's own handler still runs, so wiring one costs nothing.\n onQr: (qr: string) => {\n this.pairingState = { status: \"awaiting_scan\", qr, qrAt: Date.now() };\n this.opts.onQr?.(qr);\n },\n });\n }\n\n /**\n * Trace one inbound batch BEFORE any filter, when `THEOKIT_WHATSAPP_TRACE=1`.\n *\n * Two independent filters can discard an envelope — the batch `type` here and `fromMe` inside\n * `normalizeBaileysMessage` — and from outside, both look identical: nothing happens. Telling\n * them apart by reading the code is guessing; this is how you find out which one fired.\n *\n * Deliberately content-free. A Baileys session pairs a REAL account carrying real\n * conversations, so the trace records shape (type, direction, group, has-text) and the last\n * four digits of the jid, never the message and never a full contact number.\n *\n * @internal\n */\n private traceBatch(payload: { type?: string; messages?: unknown[] }): void {\n if (process.env.THEOKIT_WHATSAPP_TRACE !== \"1\") return;\n const messages = payload.messages ?? [];\n const rows = messages.map((raw) => {\n const key = (raw as { key?: Record<string, unknown> } | undefined)?.key ?? {};\n const jid = typeof key.remoteJid === \"string\" ? key.remoteJid : \"\";\n const message = (raw as { message?: unknown } | undefined)?.message;\n return [\n `fromMe=${String(key.fromMe === true)}`,\n `jid=…${jid.replace(/\\D/g, \"\").slice(-4)}`,\n `group=${String(jid.endsWith(\"@g.us\"))}`,\n `hasMessage=${String(message !== null && message !== undefined)}`,\n ].join(\" \");\n });\n process.stderr.write(\n `[whatsapp-baileys][trace] upsert type=${payload.type ?? \"(none)\"} n=${messages.length}` +\n (rows.length === 0 ? \"\\n\" : `\\n ${rows.join(\"\\n \")}\\n`),\n );\n }\n\n /** Route this socket's inbound batches into the handler, while it is still current. @internal */\n private subscribeInbound(socket: BaileysSocketLike, isCurrent: () => boolean): void {\n socket.ev.on(\"messages.upsert\", (payload) => {\n this.traceBatch(payload as { type?: string; messages?: unknown[] });\n // A batch typed anything other than `notify` is history being replayed, not live\n // traffic. Answering replayed history is the defect #11 records in the email backend.\n if (payload.type !== undefined && payload.type !== \"notify\") return;\n if (!isCurrent()) return;\n for (const raw of payload.messages ?? []) this.dispatchInbound(raw);\n });\n }\n\n /**\n * Wait for this socket to report `open`, or for something to end the attempt.\n *\n * Three things can settle it: the socket opens, the socket closes, or the timeout fires — and\n * a fourth, `disconnect()`, reaches it through `pendingAttempts`. That last one is why the\n * resolver is registered rather than merely closed over: retiring an attempt by generation\n * makes its listeners no-ops, INCLUDING the one that would settle this, so without a way in\n * from outside the only thing left able to finish it was the timeout.\n *\n * @internal\n */\n private async raceOpen(\n socket: BaileysSocketLike,\n isCurrent: () => boolean,\n timeoutMs: number,\n ): Promise<boolean> {\n // The executor runs synchronously, so `settle` is assigned before the next statement.\n let settle: (ok: boolean) => void = () => undefined;\n const opened = new Promise<boolean>((resolve) => {\n settle = resolve;\n });\n\n const abandon = (): void => settle(false);\n this.pendingAttempts.add(abandon);\n\n socket.ev.on(\"connection.update\", (update) => {\n if (!isCurrent()) return;\n if (update.connection === \"open\") {\n // The code is dropped, not kept: a scanned QR is spent, and a UI holding it would offer\n // something that no longer pairs anything.\n this.pairingState = { status: \"connected\" };\n settle(true);\n return;\n }\n if (update.connection !== \"close\") return;\n this.lastCloseError = update.lastDisconnect?.error;\n this.connected = false;\n this.pairingState = { status: \"closed\" };\n // A closed socket is finished, and Baileys carries its own reconnect machinery: left\n // alone it keeps dialling under a backend that believes it is disconnected. Clearing the\n // reference too is what stops the next `connect()` overwriting it and stranding this one\n // beyond the reach of any later `disconnect()`.\n if (this.socket === socket) this.socket = undefined;\n endQuietly(socket);\n settle(false);\n });\n\n // Never hanging matters more than succeeding: a caller has nothing to time out against if\n // this promise simply never settles.\n const timer = setTimeout(() => settle(false), timeoutMs);\n try {\n return await opened;\n } finally {\n // The loser of the race stays scheduled otherwise, and a scheduled timer keeps Node's\n // event loop alive — the defect fixed in the core runner (#37).\n clearTimeout(timer);\n this.pendingAttempts.delete(abandon);\n }\n }\n\n /**\n * Say why the connection did not open.\n *\n * A bare `false` tells an operator nothing, and the two causes want opposite responses: a\n * blip is worth retrying, an unlinked device can only be fixed by re-pairing, and a\n * supervisor that cannot tell them apart retries forever against a dead session.\n *\n * @internal\n */\n private reportConnectFailure(timeoutMs: number): void {\n const error = this.lastCloseError;\n const cause =\n error === undefined\n ? `no 'open' within ${timeoutMs}ms`\n : error instanceof Error\n ? error.message\n : String(error);\n process.stderr.write(`[whatsapp-baileys] connect failed: ${cause}\\n`);\n }\n\n /** Close the socket. Idempotent, and safe when never connected. */\n async disconnect(): Promise<void> {\n // Bumping first is what makes an in-flight `connect()` lose: whatever it opens will see a\n // stale generation and tear itself down rather than adopting itself into a backend the\n // caller has already closed.\n this.generation += 1;\n this.connected = false;\n // Without this the guard in `connect()` hands the next caller the promise of the attempt\n // this call just doomed: it opens nothing, waits out that attempt's timeout, and returns\n // false. A supervisor doing stop-then-start reads that as an unexplained failure.\n this.connecting = undefined;\n for (const abandon of this.pendingAttempts) abandon();\n this.pendingAttempts.clear();\n const socket = this.socket;\n this.socket = undefined;\n this.inboundHandler = undefined;\n this.statusHandler = undefined;\n if (socket !== undefined) endQuietly(socket);\n }\n\n /**\n * Send one text message.\n *\n * Queued behind any send already in flight (D320), and raced against a timeout whose\n * expiry reports **undetermined** delivery rather than failure (D321). A local timeout says\n * the acknowledgement did not arrive, not that the message did not — so this never\n * retries, because a retry after a slow ack duplicates the message.\n */\n async send(message: WhatsAppOutboundMessage): Promise<WhatsAppSendResult> {\n // The queue advances on the UNDERLYING send, not on what the caller is told.\n //\n // Chaining on the raced result looked right and broke the invariant it exists to keep: a\n // timeout returns to the caller while `socket.sendMessage` is still in flight — nothing\n // cancels it — so the next send started on a socket that already had one running. That is\n // precisely the concurrent-send hazard D320 exists to prevent, reached through D321.\n let settled: Promise<unknown> = Promise.resolve();\n const run = this.sendQueue.then(\n () => {\n const attempt = this.sendNow(message);\n settled = attempt.inFlight;\n return attempt.result;\n },\n () => {\n const attempt = this.sendNow(message);\n settled = attempt.inFlight;\n return attempt.result;\n },\n );\n this.sendQueue = run.then(\n () => settled.catch(() => undefined),\n () => settled.catch(() => undefined),\n );\n return run;\n }\n\n /**\n * Race one send against the send timeout.\n *\n * Separated so `sendNow` reads as the three outcomes it has — delivered, undetermined,\n * refused — rather than as promise plumbing.\n *\n * @internal\n */\n private async raceSend(\n inFlight: Promise<SendOutcome>,\n timeoutMs: number,\n ): Promise<SendOutcome | \"timeout\"> {\n let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<\"timeout\">((resolve) => {\n timer = setTimeout(() => resolve(\"timeout\"), timeoutMs);\n });\n try {\n return await Promise.race([inFlight, timeout]);\n } finally {\n // The loser of the race stays scheduled otherwise, and a scheduled timer keeps Node's\n // event loop alive — the defect fixed in the core runner (#37).\n if (timer !== undefined) clearTimeout(timer);\n }\n }\n\n /**\n * One send attempt.\n *\n * Returns two promises deliberately. `result` is what the caller is told — it settles on\n * the timeout. `inFlight` settles when the socket is actually free again, which is what the\n * queue must wait for: a timeout does not cancel `sendMessage`, so releasing the queue on\n * the timeout would put two sends on one socket.\n *\n * @internal\n */\n private sendNow(message: WhatsAppOutboundMessage): {\n result: Promise<WhatsAppSendResult>;\n inFlight: Promise<unknown>;\n } {\n const socket = this.socket;\n if (!this.connected || socket === undefined) {\n return {\n result: Promise.resolve({\n ok: false,\n error: { code: \"not_connected\", message: \"Baileys backend is not connected.\" },\n }),\n inFlight: Promise.resolve(),\n };\n }\n\n const timeoutMs = this.opts.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS;\n\n // Resolve BEFORE sending, and let the server's answer decide the address.\n //\n // Baileys hands back a locally-generated wamid whether or not the JID routes anywhere, so\n // building one from the caller's string and reporting that id as proof of delivery loses the\n // message in silence — the caller's log, its metrics and its retry logic all record a success\n // for something nobody received (#82).\n //\n // Measured on a real account: `5535998838687` and `553598838687` are the same Brazilian line,\n // both answered `ok: true`, and only the second arrived. Asking WhatsApp which form it routes\n // to fixes the ninth digit without a Brazil-specific rule anywhere in this package — the answer\n // is whatever the server says, for any country.\n const send: Promise<SendOutcome> = this.resolveJid(socket, message).then(\n async (jid): Promise<SendOutcome> =>\n jid === undefined ? UNROUTABLE : await socket.sendMessage(jid, { text: message.text }),\n );\n\n const result = this.raceSend(send, timeoutMs)\n .then((outcome) => {\n if (outcome === UNROUTABLE) {\n return {\n ok: false,\n error: {\n code: \"undeliverable\" as const,\n message:\n `WhatsApp does not route to \"${message.to}\" — the number is not registered, or ` +\n \"not in the form this account can reach. Nothing was sent.\",\n },\n };\n }\n if (outcome === \"timeout\") {\n return {\n ok: false,\n error: {\n code: \"timeout\" as const,\n message:\n `No acknowledgement after ${timeoutMs}ms — delivery is undetermined. ` +\n \"Not retried: the message may already have been delivered.\",\n },\n };\n }\n const wamid = outcome?.key?.id;\n if (wamid !== undefined) this.rememberSent(wamid);\n return wamid !== undefined ? { ok: true, wamid } : { ok: true };\n })\n .catch((err: unknown) => ({\n ok: false,\n error: {\n code: \"server_error\" as const,\n message: err instanceof Error ? err.message : String(err),\n },\n }));\n\n return { result, inFlight: send };\n }\n\n /**\n * The JID WhatsApp routes this message to, or `undefined` when it routes to nobody.\n *\n * A group id is not a phone number and `onWhatsApp` answers about numbers, so groups pass\n * straight through — asking would refuse every group message.\n *\n * The answer is cached for the life of the session. It is a fact about a number's registration,\n * which does not change while a socket lives, and paying a round-trip per message would make\n * every send slower for something already known.\n *\n * A socket without `onWhatsApp` — an older Baileys, or a fake predating this — sends to the\n * number as given, which is the behaviour from before #82. Refusing on a missing capability\n * would turn an upgrade problem into an outage.\n */\n private async resolveJid(\n socket: BaileysSocketLike,\n message: WhatsAppOutboundMessage,\n ): Promise<string | undefined> {\n // Already an address: pass it through untouched. `channelJid` on an inbound event is exactly\n // this, and appending a domain to it produced `231116569108705@lid@s.whatsapp.net` — a string\n // that routes nowhere and reports ok (#84). Asking `onWhatsApp` about it is equally wrong: that\n // call answers about phone NUMBERS, and a LID is not one, so it would refuse a valid address.\n if (message.to.includes(\"@\")) return message.to;\n if (message.isGroup) return `${message.to}@g.us`;\n if (socket.onWhatsApp === undefined) return `${message.to}@s.whatsapp.net`;\n\n const cached = this.jidCache.get(message.to);\n if (cached !== undefined) return cached === UNROUTABLE ? undefined : cached;\n\n let answer: Array<{ exists?: boolean; jid?: string }> | undefined;\n try {\n answer = await socket.onWhatsApp(message.to);\n } catch {\n // The lookup failing is not the same as the number not existing, and refusing here would\n // turn a transient server hiccup into a permanent-looking `undeliverable`. Send as given.\n return `${message.to}@s.whatsapp.net`;\n }\n\n const entry = answer?.[0];\n if (entry?.exists !== true || entry.jid === undefined || entry.jid === \"\") {\n this.jidCache.set(message.to, UNROUTABLE);\n return undefined;\n }\n this.jidCache.set(message.to, entry.jid);\n return entry.jid;\n }\n\n /** Subscribe to inbound events. EC-H: a second call REPLACES the first. */\n onInbound(handler: (event: WhatsAppInboundEvent) => Promise<void>): () => void {\n this.inboundHandler = handler;\n return () => {\n if (this.inboundHandler === handler) this.inboundHandler = undefined;\n };\n }\n\n /**\n * Subscribe to delivery receipts. EC-H: a second call REPLACES the first.\n *\n * Declared for the interface; Baileys reports receipts on `messages.update`, which v1 does\n * not consume. Registering a handler is accepted and it is never called — stated here\n * rather than left for a consumer to discover from silence.\n */\n onStatusReceipt(handler: (receipt: WhatsAppStatusReceipt) => Promise<void>): () => void {\n this.statusHandler = handler;\n return () => {\n if (this.statusHandler === handler) this.statusHandler = undefined;\n };\n }\n\n /**\n * Normalise one envelope and hand it to the handler.\n *\n * The promise is floated because the Baileys listener is synchronous — but with a `catch`,\n * because a bare `void` on a rejecting promise ends the process under Node's default, which\n * is what killed two adapters in this package (#41). A handler is user code; its failure is\n * named as the handler's and delivery continues.\n *\n * @internal\n */\n private dispatchInbound(raw: unknown): void {\n const handler = this.inboundHandler;\n if (handler === undefined) return;\n const event = normalizeBaileysMessage(raw, {\n selfJids: this.selfJids,\n sentWamids: this.sentWamids,\n });\n if (event === undefined) return;\n void handler(event).catch((err: unknown) => {\n const message = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[whatsapp-baileys] handler threw: ${message}\\n`);\n });\n }\n}\n","/**\n * Does an inbound WhatsApp message reach the agent, and as what?\n *\n * The addressed-number check, the sender allowlist, the group-mention rule and the conversion to\n * the gateway's event shape, as functions of their inputs (the only state is the set of foreign\n * numbers already reported, which the caller owns). `WhatsAppAdapter` holds the configuration and\n * passes it in; every adapter path that decides an inbound message goes through\n * `decideForOwnNumber` (own-number.ts), which calls `isForAnotherNumber` and `decideInbound`, so\n * there is one rule set to keep. `WhatsAppCloudBackend.handleWebhookPayload` calls `isForAnotherNumber` as well, for\n * messages and for status receipts, so a route built on the backend alone is scoped to its number\n * too.\n */\n\nimport type { WhatsAppMessageEvent } from \"@theokit/gateway\";\n\nimport { isSenderAllowed } from \"./allowlist.js\";\nimport type { WhatsAppInboundEvent, WhatsAppStatusReceipt } from \"./backend-types.js\";\n\n/** The configuration the inbound rules read, held by the adapter. */\nexport interface InboundRules {\n /** `undefined` = no allowlist configured; a set = configured, and enforced fail-closed. */\n readonly allowedSenders: ReadonlySet<string> | undefined;\n /** Drop a group message that does not mention the bot. */\n readonly requireMention: boolean;\n /** The bot's number, digits only; `\"\"` when unset. */\n readonly botPhoneId: string;\n}\n\n/** EC-7: digit-only normalizer for mention comparison (handles `+`, `-`, `()`, spaces). */\nexport function digitsOnly(s: string): string {\n return s.replace(/[^\\d]/g, \"\");\n}\n\n/**\n * Characters that may appear INSIDE a written phone number: digits and the\n * separators people type around them. Anything else — a letter, a comma, a\n * newline — ends the run.\n */\nconst PHONE_RUN = /[\\d][\\d+\\-(). ]*[\\d]|[\\d]/g;\n\n/**\n * EC-7: the phone-like runs in a message, each normalized to digits.\n *\n * The filter used to normalize the WHOLE message and ask whether the result\n * contained the bot's number. That accepts the four documented formats, but it\n * also concatenates digits from unrelated words: with a bot at 5511999999999,\n * `\"pedido 55 chegou 11, ref 99999-9999 ok\"` normalized to a string containing\n * exactly that number, and the bot answered a message about an order. Every\n * group message carrying scattered digits woke it.\n *\n * Scanning runs instead keeps the separators irrelevant WITHIN a number — which\n * is what EC-7 asks for, and what `\"+55 (11) 99999-9999\"` needs — while letting\n * a letter or a comma do what it visually does: end the number.\n */\nfunction phoneRuns(s: string): string[] {\n // Every match starts and ends with a digit, so no run normalizes to \"\".\n return (s.match(PHONE_RUN) ?? []).map(digitsOnly);\n}\n\n/**\n * Is this sender refused by a configured allowlist?\n *\n * Runs before the group/mention filter because it answers a different question: that one asks\n * whether a message was meant for us, this one asks whether the sender may reach us at all.\n *\n * The refusal is logged, with the sender's address reduced to its last four digits. A silent drop\n * is indistinguishable from a broken gateway, and the first thing a mistyped allowlist causes is\n * an operator wondering why the bot went mute.\n */\nfunction isRefusedBySenderAllowlist(\n inbound: WhatsAppInboundEvent,\n allowedSenders: ReadonlySet<string> | undefined,\n): boolean {\n // The allowlist answers \"may this STRANGER reach the agent?\", and the account owner writing\n // in their own self-chat is not one. It also cannot answer it here: the self-chat reports the\n // account's LID as the sender, while an operator writes a phone number — measured on a real\n // paired session. Reading the flag rather than the address keeps the exemption tied to the\n // backend's own decision, so a stranger arriving on a LID is still refused.\n if (inbound.fromSelf === true) return false;\n if (allowedSenders === undefined) return false;\n if (isSenderAllowed(inbound.fromPhone, allowedSenders)) return false;\n process.stderr.write(\n `[whatsapp] dropped inbound from ${redactedSender(inbound.fromPhone)}: not in the configured allowlist\\n`,\n );\n return true;\n}\n\n/**\n * A refused sender as the log names it: the last four digits of the address, enough to match a\n * mistyped allowlist entry by eye. The full number is personal data of someone who never agreed\n * to reach this bot, and every unsolicited message would otherwise write it to the host's logs.\n */\nfunction redactedSender(fromPhone: string): string {\n const tail = lastFourDigits(fromPhone);\n return tail.length > 0 ? `a sender ending in ${tail}` : \"a sender with no number\";\n}\n\n/** The last four digits of `value`, `\"\"` when it has none. Every other character is dropped. */\nfunction lastFourDigits(value: string): string {\n return digitsOnly(value).slice(-4);\n}\n\n/**\n * A foreign phone number id as the log names it, cut the way `redactedSender` cuts a sender: its\n * last four digits. The id comes from an envelope, and `toDeliverableEvents` does not verify the\n * signature, so a route that skips verification hands this function text anyone wrote. Keeping\n * digits only means no newline or quote reaches stderr.\n */\nfunction redactedNumberId(phoneNumberId: string | undefined): string {\n if (phoneNumberId === undefined) return \"no phone number id\";\n const tail = lastFourDigits(phoneNumberId);\n return tail.length > 0\n ? `a phone number id ending in ${tail}`\n : \"a phone number id with no digits\";\n}\n\n/**\n * Is this message, or status receipt, addressed to a Cloud number other than `ownPhoneNumberId`?\n *\n * Meta signs every number of one app with one secret, so a valid signature does not say which\n * number an envelope was for. `undefined` means the adapter has no Cloud number to compare, and\n * nothing is dropped. A message with no phone number id is not provably this number's, and is\n * dropped too.\n *\n * The foreign id reaches stderr only as its last four digits (see `redactedNumberId`), once per\n * label: `reported` holds the labels already written, and this function adds to it. Keyed by the\n * label rather than the raw id, the set is bounded: 10,000 endings plus the two labels for an id\n * with no digit and for no id, however many distinct ids an unverified caller sends. Two foreign\n * ids sharing an ending are named once, which is the cost of that bound.\n */\nexport function isForAnotherNumber(\n inbound: Pick<WhatsAppInboundEvent | WhatsAppStatusReceipt, \"phoneNumberId\">,\n ownPhoneNumberId: string | undefined,\n reported: Set<string>,\n): boolean {\n if (ownPhoneNumberId === undefined || inbound.phoneNumberId === ownPhoneNumberId) return false;\n const other = redactedNumberId(inbound.phoneNumberId);\n if (!reported.has(other)) {\n reported.add(other);\n process.stderr.write(\n `[whatsapp] dropped inbound addressed to ${other}: this adapter answers for \"${ownPhoneNumberId}\". Logged once per id ending.\\n`,\n );\n }\n return true;\n}\n\n/** D309 + EC-7: group filter with digit-only normalization. */\nfunction shouldDropGroupMessage(\n inbound: WhatsAppInboundEvent,\n requireMention: boolean,\n botPhoneId: string,\n): boolean {\n if (inbound.conversationType !== \"group\" || !requireMention) return false;\n if (botPhoneId.length === 0) {\n // Misconfigured: with no id to look for, every group message looks unaddressed. Saying\n // so matters more here than anywhere: the allowlist check above (isRefusedBySenderAllowlist)\n // makes the same point, and a gateway that answers no group message and explains nothing\n // is indistinguishable from a broken one. Common with `fromWeb`, which has no phone\n // number id to default from.\n process.stderr.write(\n \"[whatsapp] dropping every group message: requireMention is on and botPhoneId is unset\\n\",\n );\n return true;\n }\n return !phoneRuns(inbound.text).some((run) => run.includes(botPhoneId));\n}\n\nfunction toMessageEvent(inbound: WhatsAppInboundEvent): WhatsAppMessageEvent {\n return {\n id: inbound.wamid,\n platform: \"whatsapp\",\n sender: { id: inbound.fromPhone, displayName: inbound.contactName },\n channel: { id: inbound.channelId, type: inbound.conversationType },\n text: inbound.text,\n receivedAt: inbound.receivedAt,\n whatsapp: {\n wamid: inbound.wamid,\n phoneNumberId: inbound.phoneNumberId,\n contactName: inbound.contactName,\n channelJid: inbound.channelJid,\n backend: inbound.backend,\n raw: inbound.raw,\n },\n };\n}\n\n/**\n * Decide one inbound message: the event the agent receives, or `undefined` when a rule drops it.\n *\n * The allowlist runs first, then the group rule, then the conversion, so a refused sender is\n * named once and never reaches the group logging. A drop writes its reason to stderr.\n */\nexport function decideInbound(\n inbound: WhatsAppInboundEvent,\n rules: InboundRules,\n): WhatsAppMessageEvent | undefined {\n if (isRefusedBySenderAllowlist(inbound, rules.allowedSenders)) return undefined;\n if (shouldDropGroupMessage(inbound, rules.requireMention, rules.botPhoneId)) return undefined;\n return toMessageEvent(inbound);\n}\n","/**\n * `WhatsAppCloudClient` — typed `fetch` wrapper for Meta WhatsApp Business\n * Cloud API (ADR D304). No Meta SDK; we own the wire.\n *\n * @internal\n */\n\nimport type { WhatsAppCredentialCheck, WhatsAppSendResult } from \"../../backend-types.js\";\nimport { mapWhatsAppCloudError } from \"../../errors.js\";\nimport type {\n MetaErrorEnvelope,\n MetaMarkReadRequest,\n MetaSendResponse,\n MetaSendTemplateRequest,\n MetaSendTextRequest,\n MetaTemplateComponent,\n} from \"./types.js\";\n\ninterface WhatsAppCloudClientOptions {\n readonly accessToken: string;\n readonly phoneNumberId: string;\n readonly apiVersion?: string;\n /** Test seam. */\n readonly fetch?: typeof fetch;\n}\n\nexport class WhatsAppCloudClient {\n private readonly fetchImpl: typeof fetch;\n private readonly baseUrl: string;\n\n constructor(private readonly opts: WhatsAppCloudClientOptions) {\n this.fetchImpl = opts.fetch ?? fetch;\n const apiVersion = opts.apiVersion ?? \"v18.0\";\n this.baseUrl = `https://graph.facebook.com/${apiVersion}/${opts.phoneNumberId}`;\n }\n\n /** Send a text message. v1 scope — no media (D286 deferred). */\n async sendText(to: string, body: string, isGroup: boolean): Promise<WhatsAppSendResult> {\n const req: MetaSendTextRequest = isGroup\n ? {\n messaging_product: \"whatsapp\",\n to,\n type: \"text\",\n text: { body, preview_url: false },\n }\n : {\n messaging_product: \"whatsapp\",\n recipient_type: \"individual\",\n to,\n type: \"text\",\n text: { body, preview_url: false },\n };\n\n return this.postMessage(req);\n }\n\n /**\n * Send an approved template.\n *\n * The only message type Meta accepts outside the 24-hour service window, and so the only way to\n * reach someone who has not written first — every notification, and every unattended check of\n * whether this integration still works. Free-form text to a cold recipient is refused with\n * `131047`, which the error mapper now surfaces as `session_window_expired`.\n *\n * `components` is omitted from the payload when absent rather than sent empty: Meta rejects\n * `components: []` on a template that declares no variables, so the two are not equivalent.\n *\n * Deliberately NOT on the `WhatsAppBackend` interface. The web backend drives WhatsApp Web,\n * which has no concept of templates, and widening the shared contract would hand it a method it\n * can only throw from.\n */\n async sendTemplate(\n to: string,\n templateName: string,\n languageCode: string,\n components?: ReadonlyArray<MetaTemplateComponent>,\n ): Promise<WhatsAppSendResult> {\n const req: MetaSendTemplateRequest = {\n messaging_product: \"whatsapp\",\n recipient_type: \"individual\",\n to,\n type: \"template\",\n template: {\n name: templateName,\n language: { code: languageCode },\n ...(components !== undefined && components.length > 0 ? { components } : {}),\n },\n };\n return this.postMessage(req);\n }\n\n /**\n * Ask Meta whether this credential can actually act as this phone number.\n *\n * `connect()` used to answer that question with `return true`, so a wrong, expired or revoked\n * token reported success at startup and surfaced as messages that silently never arrived —\n * the worst failure mode a gateway has, because there is nothing in a log to see. The first\n * live run of the WhatsApp suite caught it (#58); 209 unit tests could not, because a fake\n * backend always accepts.\n *\n * It reads the phone number itself rather than `/me`, and that choice is the point: a token\n * can be perfectly valid and still have no access to THIS phone number id, which is the\n * likelier misconfiguration of the two. Checking only the token would wave it through.\n *\n * Returns a result rather than a boolean, and never throws — `connect()` is specified to\n * return false rather than throw, and the reason has to survive the trip: `auth_failed` and\n * `rate_limit` ask a supervisor for opposite responses.\n */\n async verifyCredentials(): Promise<WhatsAppCredentialCheck> {\n let response: Response;\n try {\n response = await this.fetchImpl(this.baseUrl, {\n method: \"GET\",\n headers: { authorization: `Bearer ${this.opts.accessToken}` },\n });\n } catch (cause) {\n return {\n ok: false,\n error: {\n code: \"server_error\",\n message: `Network error: ${cause instanceof Error ? cause.message : String(cause)}`,\n },\n };\n }\n\n const body = (await response.json().catch(() => undefined)) as\n | (MetaErrorEnvelope & { id?: unknown })\n | undefined;\n\n if (!response.ok) {\n return { ok: false, error: mapWhatsAppCloudError(response.status, body ?? {}) };\n }\n // A 200 is not a yes. Meta answers some failures with an error envelope under a 200, and a\n // captive portal or proxy answers everything with one — so the status line is the weakest\n // evidence in the response.\n // `null`, an array, a string and a number are all valid JSON and none of them is a node\n // description. `response.json()` resolves `null` for the literal, which is neither\n // `undefined` nor an object — the undefined-only guard let it through and the next line\n // dereferenced it, so a proxy answering `null` made `connect()` THROW. That is precisely the\n // clause this method is written to uphold.\n if (body === null || typeof body !== \"object\" || Array.isArray(body)) {\n return {\n ok: false,\n error: {\n code: \"unknown\",\n message: `Meta answered ${response.status} with a body this client could not read.`,\n },\n };\n }\n if (body.error !== undefined) {\n return { ok: false, error: mapWhatsAppCloudError(response.status, body) };\n }\n // IDENTITY, not access — the distinction this method exists for, and the one its first\n // version claimed while checking only the other. `GET /{waba_id}` with a management-scoped\n // token also answers 200, so pasting the WABA id where the phone number id belongs sails\n // through an access check and fails on every send afterwards. It is the likeliest\n // misconfiguration in Cloud API setup, and the response names the node it actually reached.\n // Compared as strings: Graph returns ids as strings, but a numeric one under strict `!==`\n // produced \"resolves to node 12345, not the configured phoneNumberId 12345\" — a refusal that\n // contradicts itself and sends someone hunting a mixup its own text rules out.\n if (String(body.id) !== this.opts.phoneNumberId) {\n return {\n ok: false,\n error: {\n code: \"invalid_request\",\n message:\n `Credential is valid but resolves to node ${String(body.id)}, not the configured ` +\n `phoneNumberId ${this.opts.phoneNumberId}. A WhatsApp Business Account id in place ` +\n `of a phone number id looks exactly like this.`,\n },\n };\n }\n return { ok: true };\n }\n\n /**\n * POST one message envelope and turn Meta's answer into a `WhatsAppSendResult`.\n *\n * Shared by every send: how to reach the endpoint, how to authenticate, and how to read the\n * reply is one piece of knowledge, and it was about to have a second copy.\n */\n private async postMessage(\n req: MetaSendTextRequest | MetaSendTemplateRequest,\n ): Promise<WhatsAppSendResult> {\n let response: Response;\n try {\n response = await this.fetchImpl(`${this.baseUrl}/messages`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n authorization: `Bearer ${this.opts.accessToken}`,\n },\n body: JSON.stringify(req),\n });\n } catch (cause) {\n return {\n ok: false,\n error: {\n code: \"server_error\",\n message: `Network error: ${cause instanceof Error ? cause.message : String(cause)}`,\n },\n };\n }\n\n if (!response.ok) {\n const errBody = (await response.json().catch(() => ({}))) as MetaErrorEnvelope | unknown;\n return { ok: false, error: mapWhatsAppCloudError(response.status, errBody) };\n }\n\n const data = (await response.json()) as MetaSendResponse;\n const wamid = data.messages?.[0]?.id;\n if (wamid === undefined) {\n return { ok: false, error: { code: \"unknown\", message: \"Meta returned no wamid.\" } };\n }\n return { ok: true, wamid };\n }\n\n /** Mark an inbound message as read (status receipt back to user). */\n async markAsRead(wamid: string): Promise<boolean> {\n const body: MetaMarkReadRequest = {\n messaging_product: \"whatsapp\",\n status: \"read\",\n message_id: wamid,\n };\n try {\n const response = await this.fetchImpl(`${this.baseUrl}/messages`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n authorization: `Bearer ${this.opts.accessToken}`,\n },\n body: JSON.stringify(body),\n });\n return response.ok;\n } catch {\n return false;\n }\n }\n}\n","/**\n * Meta's `X-Hub-Signature-256` check for a Cloud webhook body (ADR D312).\n *\n * Its own module, apart from the envelope normalizers in `webhook.ts`, because this is the line\n * between a signed webhook and anyone's POST, and mutation testing measures it file by file.\n *\n * @public\n */\n\nimport * as crypto from \"node:crypto\";\n\nimport { ConfigurationError } from \"../../errors.js\";\n\n/**\n * Verify the `X-Hub-Signature-256` HMAC-SHA256 against the app secret (D312).\n *\n * EC-3 absorbed: length-guard BEFORE `timingSafeEqual` so a malformed header\n * (e.g. `sha256=ab`) returns `false` instead of throwing `RangeError` (DoS).\n *\n * An empty or whitespace-only `appSecret` throws rather than answering: an HMAC under an empty\n * key is computable by anyone, so a match would prove nothing about Meta. `fromCloud` accepts an\n * empty secret for an adapter that only sends; such an adapter cannot verify a webhook.\n *\n * @returns `true` iff the signature matches.\n * @throws {ConfigurationError} `missing_option` when `appSecret` is empty or whitespace only.\n */\nexport function verifyWebhookSignature(\n rawBody: Buffer | string,\n signatureHeader: string | undefined,\n appSecret: string,\n): boolean {\n if (appSecret.trim().length === 0) {\n throw new ConfigurationError({\n code: \"missing_option\",\n message:\n \"gateway-whatsapp: appSecret is required to verify a webhook signature and must not be empty; an HMAC under an empty key is computable by anyone.\",\n });\n }\n if (signatureHeader === undefined) return false;\n if (!signatureHeader.startsWith(\"sha256=\")) return false;\n const receivedHex = signatureHeader.slice(7);\n if (!/^[0-9a-f]+$/i.test(receivedHex)) return false;\n const received = Buffer.from(receivedHex, \"hex\");\n // `update` reads a string as UTF-8 and a Buffer as its bytes, which is what Meta signed.\n const expected = crypto.createHmac(\"sha256\", appSecret).update(rawBody).digest();\n // EC-3: length guard before timingSafeEqual.\n if (received.length !== expected.length) return false;\n return crypto.timingSafeEqual(received, expected);\n}\n","/**\n * Webhook helpers for Meta WhatsApp Business Cloud API (ADR D306, D312).\n *\n * Two boundaries:\n * 1. GET handshake — `verifyWebhookSubscription` (EC-1).\n * 2. POST callbacks — `verifyWebhookSignature` (EC-3 length guard) +\n * `normalizeInboundMessages` (EC-4 text-only filter) +\n * `normalizeStatusReceipts`.\n *\n * The user owns the HTTP route; we expose pure helpers they call from inside it.\n *\n * @public\n */\n\nimport type { WhatsAppInboundEvent, WhatsAppStatusReceipt } from \"../../backend-types.js\";\nimport type { MetaIncomingMessage, MetaStatusUpdate, MetaWebhookEnvelope } from \"./types.js\";\n\n/**\n * The Meta message types a log line may name. Anything else, including a type a forged envelope\n * made up, is named \"an unknown type\".\n */\nconst KNOWN_NON_TEXT_TYPES: ReadonlySet<string> = new Set([\n \"audio\",\n \"button\",\n \"contacts\",\n \"document\",\n \"image\",\n \"interactive\",\n \"location\",\n \"order\",\n \"reaction\",\n \"request_welcome\",\n \"sticker\",\n \"system\",\n \"unsupported\",\n \"video\",\n]);\n\n/**\n * Labels already written to stderr. Keyed by `nonTextTypeLabel`, not by the raw type, so it holds\n * at most one entry per known type plus one for \"an unknown type\".\n */\nconst warnedNonTextTypes = new Set<string>();\n\n/**\n * A non-text message type as the log names it. `msg.type` comes from the envelope, and\n * `toDeliverableEvents` does not verify the signature, so the raw value is text anyone wrote: it\n * could carry a newline that forges a log line. Only a type from a fixed list is named.\n */\nfunction nonTextTypeLabel(type: unknown): string {\n return typeof type === \"string\" && KNOWN_NON_TEXT_TYPES.has(type) ? type : \"an unknown type\";\n}\n\n/**\n * Verify Meta's GET `/webhook?hub.mode=subscribe&hub.challenge=...&hub.verify_token=...`\n * handshake (EC-1 absorbed).\n *\n * @returns `query[\"hub.challenge\"]` when valid, `null` otherwise. The caller\n * echoes the challenge as `text/plain` on success.\n */\nexport function verifyWebhookSubscription(\n query: Record<string, string | undefined>,\n expectedVerifyToken: string,\n): string | null {\n const mode = query[\"hub.mode\"];\n const token = query[\"hub.verify_token\"];\n const challenge = query[\"hub.challenge\"];\n if (mode !== \"subscribe\") return null;\n if (token === undefined || token !== expectedVerifyToken) return null;\n if (challenge === undefined || challenge.length === 0) return null;\n return challenge;\n}\n\n// The signature check lives in its own module so mutation testing can measure it without the\n// normalizers below (see tests/MUTATION.md); it is re-exported so the import path is unchanged.\nexport { verifyWebhookSignature } from \"./signature.js\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\";\n}\n\n/** Absent, or an array whose every item is an object: what the normalizers iterate. */\nfunction isOptionalRecordArray(value: unknown): boolean {\n return value === undefined || (Array.isArray(value) && value.every(isRecord));\n}\n\n/**\n * `metadata`: absent, or an object whose `phone_number_id` is absent or a string. The inbound rules\n * compare and redact that id with string methods, so a number or `null` there would throw past the\n * boundary.\n */\nfunction isWellFormedMetadata(metadata: unknown): boolean {\n if (metadata === undefined || metadata === null) return true;\n if (!isRecord(metadata)) return false;\n return metadata.phone_number_id === undefined || typeof metadata.phone_number_id === \"string\";\n}\n\n/**\n * A text message's fields the normalizer and the inbound rules read: `id` and `from` are strings,\n * and `text` is absent or carries a string `body`. Other types are dropped before any field is read.\n */\nfunction isReadableMessage(message: Record<string, unknown>): boolean {\n if (message.type !== \"text\") return true;\n if (typeof message.id !== \"string\" || typeof message.from !== \"string\") return false;\n const text = message.text;\n return text === undefined || (isRecord(text) && typeof text.body === \"string\");\n}\n\n/**\n * A contact the normalizer copies into a message: a string `wa_id`, and a `profile` that is absent\n * or carries a `name` that is absent or a string. That name becomes `sender.displayName`.\n */\nfunction isReadableContact(contact: Record<string, unknown>): boolean {\n if (typeof contact.wa_id !== \"string\") return false;\n const profile = contact.profile;\n if (profile === undefined) return true;\n return isRecord(profile) && (profile.name === undefined || typeof profile.name === \"string\");\n}\n\n/** A status the normalizer turns into a receipt: string `id`, `status` and `recipient_id`. */\nfunction isReadableStatus(status: Record<string, unknown>): boolean {\n return (\n typeof status.id === \"string\" &&\n typeof status.status === \"string\" &&\n typeof status.recipient_id === \"string\"\n );\n}\n\n/** Absent, or a list of objects that each pass `isReadable`. */\nfunction isOptionalReadableList(\n list: unknown,\n isReadable: (item: Record<string, unknown>) => boolean,\n): boolean {\n if (!isOptionalRecordArray(list)) return false;\n return list === undefined || (list as Record<string, unknown>[]).every(isReadable);\n}\n\n/** A change's `value`: absent, or an object whose lists hold items the normalizers can read. */\nfunction isWellFormedValue(value: unknown): boolean {\n if (value === undefined || value === null) return true;\n if (!isRecord(value)) return false;\n return (\n isWellFormedMetadata(value.metadata) &&\n isOptionalReadableList(value.contacts, isReadableContact) &&\n isOptionalReadableList(value.messages, isReadableMessage) &&\n isOptionalReadableList(value.statuses, isReadableStatus)\n );\n}\n\nfunction isWellFormedEntry(entry: unknown): boolean {\n if (!isRecord(entry) || !Array.isArray(entry.changes)) return false;\n return entry.changes.every((change) => isRecord(change) && isWellFormedValue(change.value));\n}\n\n/**\n * Parse the raw JSON payload into a typed envelope, or `null` when its shape is not one the\n * normalizers can read: no `object`, an `entry` that is not an array, or any entry, change or\n * listed contact, message or status that is not an object (an entry with no `changes` array, a\n * `null` change, `messages: 5`). The whole body is refused rather than its bad entries skipped, so\n * nothing in a batch is dropped without the route seeing it. A body is also refused when a field the\n * inbound rules read with string methods is not a string: a `metadata.phone_number_id` that is not\n * absent or a string, a text message whose `id`, `from` or `text.body` is not a string, a contact\n * whose `wa_id` or `profile.name` is not a string, or a status whose `id`, `status` or\n * `recipient_id` is not a string. Past a non-null result neither normalizer throws, and every\n * string field of an event or receipt holds a string. Timestamps are not checked here.\n */\nexport function parseWebhookPayload(json: unknown): MetaWebhookEnvelope | null {\n if (!isRecord(json)) return null;\n if (json.object === undefined || !Array.isArray(json.entry)) return null;\n if (!json.entry.every(isWellFormedEntry)) return null;\n return json as unknown as MetaWebhookEnvelope;\n}\n\n/**\n * Normalize inbound messages → `WhatsAppInboundEvent[]`.\n *\n * EC-4 absorbed: filters `message.type !== \"text\"` (v1 text-only). Non-text\n * types emit a one-shot stderr warn per type.\n */\nfunction buildContactMap(\n value: NonNullable<MetaWebhookEnvelope[\"entry\"][number][\"changes\"][number][\"value\"]>,\n): Map<string, string | undefined> {\n const map = new Map<string, string | undefined>();\n for (const c of value.contacts ?? []) map.set(c.wa_id, c.profile?.name);\n return map;\n}\n\nfunction processChange(\n change: MetaWebhookEnvelope[\"entry\"][number][\"changes\"][number],\n out: WhatsAppInboundEvent[],\n): void {\n const value = change.value;\n if (value === undefined || value === null) return;\n const phoneNumberId = value.metadata?.phone_number_id;\n const contactByWaId = buildContactMap(value);\n for (const msg of value.messages ?? []) {\n const normalized = normalizeOneMessage(msg, phoneNumberId, contactByWaId);\n if (normalized !== null) out.push(normalized);\n }\n}\n\n/**\n * Extract the inbound messages from one Meta webhook envelope.\n *\n * A single delivery batches entries, changes and messages, and may carry none at all — a\n * status-only delivery is normal. Returns an array, empty when there is nothing to hand on.\n */\nexport function normalizeInboundMessages(envelope: MetaWebhookEnvelope): WhatsAppInboundEvent[] {\n const out: WhatsAppInboundEvent[] = [];\n for (const entry of envelope.entry) {\n for (const change of entry.changes) processChange(change, out);\n }\n return out;\n}\n\nfunction normalizeOneMessage(\n msg: MetaIncomingMessage,\n phoneNumberId: string | undefined,\n contactByWaId: Map<string, string | undefined>,\n): WhatsAppInboundEvent | null {\n // EC-4: text-only in v1.\n if (msg.type !== \"text\") {\n const label = nonTextTypeLabel(msg.type);\n if (!warnedNonTextTypes.has(label)) {\n warnedNonTextTypes.add(label);\n process.stderr.write(\n `[whatsapp] ignoring ${label} message — v1 text-only (will be supported in v0.2+).\\n`,\n );\n }\n return null;\n }\n const body = msg.text?.body ?? \"\";\n // Cloud API doesn't distinguish DM vs group at the message level — `from`\n // is the sender. We don't have a reliable group-detection signal in cloud\n // (groups need a different webhook subscription). v1 treats all inbound\n // as DM. If the user enables group webhooks, the `conversationType` heuristic\n // here is a future-extension point.\n return {\n wamid: msg.id,\n fromPhone: msg.from,\n phoneNumberId,\n contactName: contactByWaId.get(msg.from),\n conversationType: \"dm\",\n channelId: msg.from,\n text: body,\n receivedAt: Number(msg.timestamp) * 1000 || Date.now(),\n backend: \"cloud\",\n raw: msg,\n };\n}\n\n/** Normalize status updates → `WhatsAppStatusReceipt[]`. */\nexport function normalizeStatusReceipts(envelope: MetaWebhookEnvelope): WhatsAppStatusReceipt[] {\n const out: WhatsAppStatusReceipt[] = [];\n for (const entry of envelope.entry) {\n for (const change of entry.changes) {\n const phoneNumberId = change.value?.metadata?.phone_number_id;\n for (const s of change.value?.statuses ?? []) {\n out.push(metaStatusToReceipt(s, phoneNumberId));\n }\n }\n }\n return out;\n}\n\nfunction metaStatusToReceipt(\n s: MetaStatusUpdate,\n phoneNumberId: string | undefined,\n): WhatsAppStatusReceipt {\n const receipt = {\n wamid: s.id,\n status: s.status,\n recipient: s.recipient_id,\n timestamp: Number(s.timestamp) * 1000 || Date.now(),\n };\n return phoneNumberId === undefined ? receipt : { ...receipt, phoneNumberId };\n}\n\n/** @internal — test seam to reset the one-shot warn de-dup. */\nexport function __resetNonTextWarnings(): void {\n warnedNonTextTypes.clear();\n}\n","/**\n * `WhatsAppCloudBackend` — Meta WhatsApp Business Cloud API backend (ADR D304).\n *\n * `connect()` verifies the credential against Meta and caches the result; `disconnect()` clears\n * it. This header used to say both were no-ops, which is what the code did and what the first\n * live run of the WhatsApp suite refuted (#58): a wrong or revoked token reported success at\n * startup and surfaced as messages that silently never arrived.\n *\n * There is still no session to open — HTTP push via webhook is the only inbound channel, and\n * outbound is a stateless POST. What `connect()` buys is the startup answer to \"can this\n * credential act as this number?\", which is the question every sibling adapter answers and this\n * one did not. Outbound delegates to `WhatsAppCloudClient`. Inbound dispatch is driven by the\n * user calling `handleWebhookPayload(rawBody, sig)` from inside their HTTP route.\n *\n * @public\n */\n\nimport type {\n WhatsAppBackend,\n WhatsAppInboundEvent,\n WhatsAppOutboundMessage,\n WhatsAppSendResult,\n WhatsAppStatusReceipt,\n} from \"../../backend-types.js\";\nimport { isForAnotherNumber } from \"../../inbound-rules.js\";\nimport { WhatsAppCloudClient } from \"./client.js\";\nimport type { MetaTemplateComponent, MetaWebhookEnvelope } from \"./types.js\";\nimport {\n normalizeInboundMessages,\n normalizeStatusReceipts,\n parseWebhookPayload,\n verifyWebhookSignature,\n} from \"./webhook.js\";\n\nexport interface WhatsAppCloudBackendOptions {\n readonly accessToken: string;\n readonly phoneNumberId: string;\n readonly appSecret: string;\n readonly apiVersion?: string;\n /** Test seam. */\n readonly fetch?: typeof fetch;\n}\n\n/**\n * WhatsApp backend over Meta's official Cloud API.\n *\n * The supported path: Meta dials in with webhook deliveries, so inbound needs a publicly reachable\n * HTTPS endpoint registered in the Meta console. Outbound is a plain HTTPS call and works anywhere.\n * Business-initiated messages outside the 24-hour customer service window must use an approved\n * template — a plain text send to a cold contact is rejected by the platform, not by this code.\n */\nexport class WhatsAppCloudBackend implements WhatsAppBackend {\n readonly kind = \"cloud\" as const;\n private readonly client: WhatsAppCloudClient;\n /** Verified once by `connect()`; cleared by `disconnect()`. */\n private connected = false;\n /**\n * The verification currently in flight, shared by every caller that arrives during it.\n *\n * A flag alone only guards callers that arrive AFTER one finished — two simultaneous\n * `connect()` calls would each ask Meta, which is one wasted round-trip at startup and a\n * rate-limit source under a supervisor that health-checks on a schedule. Cleared when it\n * settles, so a failed attempt does not become a permanent refusal: a transient blip must stay\n * distinguishable from a revoked token.\n */\n private connecting?: Promise<boolean>;\n /**\n * Which connection attempt is current.\n *\n * Bumped by every `connect()` and every `disconnect()`. Without it a verify that was still in\n * flight when `disconnect()` ran would set `connected` back to true as it resolved, and every\n * later `connect()` would short-circuit on a flag no live check stands behind — the field's own\n * comment claims `disconnect()` clears it, and it did not. Same guard the Baileys backend\n * carries, for the same reason.\n */\n private generation = 0;\n private readonly appSecret: string;\n /**\n * The Meta phone number id this backend sends as and answers for. Declared through\n * `WhatsAppBackend.phoneNumberId`, so an adapter holding this backend can refuse a signed message\n * addressed to another number of the same app.\n */\n readonly phoneNumberId: string;\n /** Foreign phone number id endings already named on stderr, so each is reported once. */\n private readonly reportedForeignNumbers = new Set<string>();\n private inboundHandler?: (event: WhatsAppInboundEvent) => Promise<void>;\n private statusHandler?: (receipt: WhatsAppStatusReceipt) => Promise<void>;\n\n constructor(opts: WhatsAppCloudBackendOptions) {\n this.client = new WhatsAppCloudClient({\n accessToken: opts.accessToken,\n phoneNumberId: opts.phoneNumberId,\n apiVersion: opts.apiVersion,\n ...(opts.fetch !== undefined ? { fetch: opts.fetch } : {}),\n });\n this.appSecret = opts.appSecret;\n this.phoneNumberId = opts.phoneNumberId;\n }\n\n // Cloud has no persistent connection — webhook is push, send is HTTP.\n /**\n * Confirm with Meta that this credential can act as this phone number.\n *\n * This used to be `return true`. A consumer with a wrong, expired or revoked token got success\n * at startup and found out from messages that silently never arrived — no error, no log,\n * nothing to alert on, which is the worst failure mode a gateway has. The first live run of the\n * WhatsApp suite caught it (#58); no unit test could, because a fake backend always accepts.\n *\n * Idempotent, like every sibling: verified once, then cached. Re-asking on every call would\n * turn a supervisor's health check into a rate-limit source against Meta.\n *\n * Returns false rather than throwing — the contract each sibling adapter is tested against,\n * because a throw at startup takes the whole runner down with it. The reason goes to stderr\n * first: told only \"false\", a supervisor cannot tell a revoked token, which needs a human,\n * from a rate limit, which needs a wait.\n */\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n if (this.connecting !== undefined) return this.connecting;\n\n const attempt = this.verifyOnce(++this.generation);\n this.connecting = attempt;\n try {\n return await attempt;\n } finally {\n // Only clear what is still ours: `disconnect()` clears it too, and a later `connect()` may\n // already have installed its own.\n if (this.connecting === attempt) this.connecting = undefined;\n }\n }\n\n /** One credential check, mapped to the boolean `connect()` is contracted to return. @internal */\n private async verifyOnce(generation: number): Promise<boolean> {\n const check = await this.client.verifyCredentials();\n if (!check.ok) {\n process.stderr.write(\n `[whatsapp-cloud] connect failed: ${check.error?.code ?? \"unknown\"} — ` +\n `${check.error?.message ?? \"no reason given\"}\\n`,\n );\n return false;\n }\n // A `disconnect()` that arrived while this was in flight wins: adopting now would leave a\n // flag standing over a backend the caller has already closed.\n if (this.generation !== generation) return false;\n this.connected = true;\n return true;\n }\n\n async disconnect(): Promise<void> {\n this.generation += 1;\n this.connected = false;\n this.connecting = undefined;\n this.inboundHandler = undefined;\n this.statusHandler = undefined;\n }\n\n async send(message: WhatsAppOutboundMessage): Promise<WhatsAppSendResult> {\n // Cloud is stateless HTTP, so there is no session to be outside of — and that was the reason\n // this posted regardless while web and Baileys refused. It was the wrong reason. Since\n // `connect()` started verifying the credential, `connected === false` means the credential\n // was rejected or never checked, and sending anyway spends a request that cannot succeed\n // while making this backend behave differently from its siblings under one interface.\n if (!this.connected) {\n return {\n ok: false,\n error: {\n code: \"not_connected\",\n message: \"Cloud backend is not connected — call connect().\",\n },\n };\n }\n return this.client.sendText(message.to, message.text, message.isGroup);\n }\n\n /**\n * Send an approved template to `to`.\n *\n * Cloud-only, and deliberately absent from the `WhatsAppBackend` interface: WhatsApp Web has no\n * concept of templates, so putting this on the shared contract would hand the web backend a\n * method it could only throw from. A consumer reaches it by holding the backend directly.\n *\n * This is the only way to message someone outside the 24-hour service window — every\n * notification, and every unattended check that this integration still works. Free-form text to\n * a cold recipient comes back as `session_window_expired`.\n *\n * @param templateName Name of a template already approved on the WhatsApp Business account.\n * @param languageCode Locale of the approved template, e.g. `en_US`, `pt_BR`.\n * @param components Values for the template's variables; omit for a template that takes none.\n */\n async sendTemplate(\n to: string,\n templateName: string,\n languageCode: string,\n components?: ReadonlyArray<MetaTemplateComponent>,\n ): Promise<WhatsAppSendResult> {\n // Same rule as `send()`, and it needs saying separately because this method is off the\n // `WhatsAppBackend` interface — WhatsApp Web has no templates — so the conformance suite that\n // enforces it there structurally cannot see it here. Being outside the shared contract is\n // why it needs its own guard, not a reason to be exempt from the rule.\n if (!this.connected) {\n return {\n ok: false,\n error: {\n code: \"not_connected\",\n message: \"Cloud backend is not connected — call connect().\",\n },\n };\n }\n return this.client.sendTemplate(to, templateName, languageCode, components);\n }\n\n onInbound(handler: (event: WhatsAppInboundEvent) => Promise<void>): () => void {\n this.inboundHandler = handler;\n return () => {\n // Identity-guarded: a stale unsubscribe must be a no-op. Without it,\n // `onInbound(A)` → `onInbound(B)` → `A.off()` clears B's handler and the backend goes\n // silent with no error — nothing to see in a log, nothing to alert on. This is a public\n // export implementing an exported interface, so a consumer holding the backend directly\n // reaches it without going through `WhatsAppAdapter`.\n if (this.inboundHandler === handler) this.inboundHandler = undefined;\n };\n }\n\n onStatusReceipt(handler: (receipt: WhatsAppStatusReceipt) => Promise<void>): () => void {\n this.statusHandler = handler;\n return () => {\n if (this.statusHandler === handler) this.statusHandler = undefined;\n };\n }\n\n /**\n * Webhook entrypoint. The user calls this from inside their POST /webhook\n * route after `verifyWebhookSubscription` on GET.\n *\n * Only messages addressed to this backend's `phoneNumberId` reach the inbound handler, and only\n * status receipts addressed to it reach the status handler. Meta signs every number of one app\n * with one secret and an app-level webhook URL receives every subscribed number, so a valid\n * signature does not say which number a message or receipt was for; one for another number, or\n * naming none, is dropped and its id written to stderr once (`isForAnotherNumber`, the rule\n * `WhatsAppAdapter` applies too).\n *\n * @returns `true` if the signature is valid and the body was dispatched (or held nothing to\n * dispatch). `false` if the signature is invalid, if the signed body is not JSON or\n * has a shape {@link parseWebhookPayload} refuses, or if it holds a message for this\n * number while no inbound handler is subscribed (before `onInbound`, or after\n * `disconnect()`): the whole body is refused, never a part of it dropped, and one line\n * on stderr says which. Answer `false` with a non-2xx (401 for a bad signature) so the\n * drop is seen and Meta redelivers. Status receipts with no status handler subscribed\n * are discarded on purpose: subscribing to receipts is optional, and refusing them\n * would make Meta redeliver every receipt to a route that never wants one.\n * @throws {ConfigurationError} `missing_option` when this backend's `appSecret` is empty or\n * whitespace only: a signature under an empty key proves nothing.\n */\n async handleWebhookPayload(\n rawBody: Buffer | string,\n signatureHeader: string | undefined,\n ): Promise<boolean> {\n if (!verifyWebhookSignature(rawBody, signatureHeader, this.appSecret)) {\n return false;\n }\n const json = this.parseBody(rawBody);\n if (json === undefined) return false;\n const envelope = parseWebhookPayload(json);\n if (envelope === null) {\n // Answering true would let the route say 200 and Meta never redeliver the batch.\n process.stderr.write(\n \"[whatsapp-cloud] signed webhook body has a shape the parser refuses (no object, no entry array, or a malformed entry, change or list); refused whole, nothing dispatched\\n\",\n );\n return false;\n }\n const messages = normalizeInboundMessages(envelope).filter(\n (event) => !isForAnotherNumber(event, this.phoneNumberId, this.reportedForeignNumbers),\n );\n const inboundHandler = this.inboundHandler;\n if (messages.length > 0 && inboundHandler === undefined) {\n // Answering true would let the route say 200 and Meta never redeliver these messages.\n process.stderr.write(\n `[whatsapp-cloud] signed webhook body holds ${messages.length} message(s) for this number and no inbound handler is subscribed; refused whole, nothing dispatched\\n`,\n );\n return false;\n }\n // The handler that accepted the batch receives all of it. Re-reading it per message let a\n // `disconnect()` or unsubscribe inside the first message's handler skip the rest while this\n // still answered true; refusing mid-batch instead would make Meta redeliver the messages\n // already handled.\n if (inboundHandler !== undefined) await this.dispatchInbound(messages, inboundHandler);\n await this.dispatchStatusReceipts(envelope);\n return true;\n }\n\n /**\n * Hand each status receipt addressed to this backend's number to the status handler.\n *\n * Same rule as messages: a receipt names the recipient's phone number, so one number's receipts\n * reaching another number's handler hands one tenant's customer numbers to another tenant.\n */\n private async dispatchStatusReceipts(envelope: MetaWebhookEnvelope): Promise<void> {\n for (const receipt of normalizeStatusReceipts(envelope)) {\n if (this.statusHandler === undefined) continue;\n if (isForAnotherNumber(receipt, this.phoneNumberId, this.reportedForeignNumbers)) continue;\n await this.dispatchContained(() => this.statusHandler?.(receipt), \"status handler\");\n }\n }\n\n /** Hand each message, already scoped to this backend's number, to the inbound handler. */\n private async dispatchInbound(\n messages: readonly WhatsAppInboundEvent[],\n handler: (event: WhatsAppInboundEvent) => Promise<void>,\n ): Promise<void> {\n for (const event of messages) {\n await this.dispatchContained(() => handler(event), \"handler\");\n }\n }\n\n /**\n * Parse a signed webhook body, or report `undefined` when it is not JSON.\n *\n * The method's contract is true/false; the route calling it has no reason to expect a throw.\n */\n private parseBody(rawBody: Buffer | string): unknown | undefined {\n try {\n return JSON.parse(typeof rawBody === \"string\" ? rawBody : rawBody.toString(\"utf8\"));\n } catch (err) {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[whatsapp-cloud] webhook body is not JSON: ${m}\\n`);\n return undefined;\n }\n }\n\n /**\n * Run one user callback and contain its failure.\n *\n * Meta batches several messages, and their delivery receipts, into a single webhook. Awaiting a\n * handler with nothing around it made one throw skip every remaining message in the payload —\n * and reject `handleWebhookPayload`, so the caller's route answered 500 and Meta redelivered the\n * whole batch, replaying the messages that HAD succeeded (#41).\n */\n private async dispatchContained(\n run: () => Promise<void> | undefined,\n what: string,\n ): Promise<void> {\n try {\n await run();\n } catch (err) {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[whatsapp-cloud] ${what} threw: ${m}\\n`);\n }\n }\n}\n","/**\n * IPC protocol between adapter and `whatsapp-web.js` subprocess bridge.\n *\n * Wire: stdin/stdout JSON-lines (each message terminated by `\\n`).\n *\n * @internal\n */\n\n/**\n * Sentinel runtime export — see `backend-types.ts` for rationale.\n *\n * @knipignore\n */\nexport const __ipcMarker: unique symbol = Symbol(\"ipc\");\n\n/** Commands the adapter sends to the bridge. */\nexport type IpcCommand =\n | { readonly cmd: \"send\"; readonly msgId: string; readonly to: string; readonly text: string }\n | { readonly cmd: \"shutdown\" };\n\n/** Events the bridge emits to the adapter. */\nexport type IpcEvent =\n | { readonly event: \"ready\"; readonly botPhone: string }\n | {\n readonly event: \"message\";\n readonly msgId: string;\n readonly from: string;\n readonly body: string;\n readonly isGroup: boolean;\n readonly chatId: string;\n readonly contactName?: string;\n readonly timestamp: number;\n }\n | {\n readonly event: \"send_ack\";\n readonly msgId: string;\n readonly success: boolean;\n readonly wamid?: string;\n readonly error?: string;\n }\n | {\n readonly event: \"status\";\n readonly msgId: string;\n readonly status: \"sent\" | \"delivered\" | \"read\" | \"failed\";\n readonly recipient: string;\n readonly timestamp: number;\n }\n | {\n readonly event: \"error\";\n readonly message: string;\n /**\n * Machine-readable cause, when the bridge could name one. Absent on older bridges and\n * on failures it cannot classify, which is why every consumer must tolerate it being\n * undefined rather than switching exhaustively.\n */\n readonly code?: string;\n };\n\n/** Parse one JSON-line. Returns null on malformed. */\nexport function parseEvent(line: string): IpcEvent | null {\n if (line.length === 0) return null;\n try {\n const parsed = JSON.parse(line) as unknown;\n if (parsed === null || typeof parsed !== \"object\") return null;\n if (typeof (parsed as { event?: unknown }).event !== \"string\") return null;\n return parsed as IpcEvent;\n } catch {\n return null;\n }\n}\n\n/** Format an outbound command as JSON + newline. */\nexport function formatCommand(cmd: IpcCommand): string {\n return `${JSON.stringify(cmd)}\\n`;\n}\n\n/**\n * Line buffer — accumulates stdout chunks until `\\n` boundaries, yields\n * complete lines. Addresses EC-11 (chunked stdout across multiple reads).\n */\nexport class LineBuffer {\n private buffer = \"\";\n\n push(chunk: string): string[] {\n this.buffer += chunk;\n const out: string[] = [];\n let idx = this.buffer.indexOf(\"\\n\");\n while (idx !== -1) {\n out.push(this.buffer.slice(0, idx));\n this.buffer = this.buffer.slice(idx + 1);\n idx = this.buffer.indexOf(\"\\n\");\n }\n return out;\n }\n\n /** Test seam — current pending bytes. */\n get pending(): string {\n return this.buffer;\n }\n}\n","/**\n * Bridge subprocess lifecycle (ADR D305, D313). PID file lock + stale-process\n * cleanup. EC-5 absorbed: verifies cmdline before killing (otherwise we may\n * kill an unrelated process the OS recycled the PID for).\n *\n * @internal\n */\n\nimport { type ChildProcess, execSync, spawn } from \"node:child_process\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\n/** Marker substring our bridge process MUST carry in its argv (EC-5). */\nexport const BRIDGE_PROCESS_TAG = \"whatsapp-web-bridge\";\n\ninterface SpawnBridgeOptions {\n readonly sessionId: string;\n readonly bridgeScriptPath: string;\n readonly theokitHome?: string;\n}\n\nexport interface BridgeHandle {\n readonly child: ChildProcess;\n readonly pidFilePath: string;\n}\n\nfunction pidFilePath(theokitHome: string, sessionId: string): string {\n return path.join(theokitHome, `whatsapp-bridge-${sessionId}.pid`);\n}\n\nfunction defaultTheokitHome(): string {\n return process.env.THEOKIT_HOME ?? path.join(process.env.HOME ?? \"/tmp\", \".theokit\");\n}\n\n/**\n * Verify whether `pid` belongs to a process whose argv contains our tag (EC-5).\n *\n * Without this guard, OS may have recycled the PID to e.g. `vim` and our\n * cleanup would terminate the user's editor.\n *\n * @internal\n */\nexport function pidBelongsToOurBridge(pid: number): boolean {\n try {\n // Linux: /proc/<pid>/cmdline (NUL-separated argv).\n const cmdline = fs.readFileSync(`/proc/${pid}/cmdline`, \"utf8\");\n return cmdline.includes(BRIDGE_PROCESS_TAG);\n } catch {\n // macOS / BSD fallback: ps -p <pid> -o args=\n try {\n const out = execSync(`ps -p ${pid} -o args=`, {\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n }).toString();\n return out.includes(BRIDGE_PROCESS_TAG);\n } catch {\n return false;\n }\n }\n}\n\n/** EC-5: kill `stalePid` ONLY if cmdline confirms ownership. */\nfunction killIfOurBridge(stalePid: number): void {\n if (!Number.isFinite(stalePid) || stalePid <= 0) return;\n if (!pidBelongsToOurBridge(stalePid)) return;\n try {\n process.kill(stalePid, \"SIGTERM\");\n } catch {\n // Process already gone — fine.\n }\n}\n\nfunction cleanupStaleLock(lockFile: string): void {\n const raw = fs.readFileSync(lockFile, \"utf8\").trim();\n killIfOurBridge(Number.parseInt(raw, 10));\n try {\n fs.unlinkSync(lockFile);\n } catch {\n /* ignore */\n }\n}\n\n/**\n * Acquire the PID lock for a session — kill any stale bridge (cmdline-verified),\n * then return the lock-file path (caller writes its own PID after spawn).\n */\nexport function acquirePidLock(sessionId: string, theokitHome?: string): string {\n const home = theokitHome ?? defaultTheokitHome();\n fs.mkdirSync(home, { recursive: true });\n const lockFile = pidFilePath(home, sessionId);\n if (fs.existsSync(lockFile)) cleanupStaleLock(lockFile);\n return lockFile;\n}\n\n/** Spawn the bridge subprocess, write PID file. */\nexport function spawnBridge(opts: SpawnBridgeOptions): BridgeHandle {\n const home = opts.theokitHome ?? defaultTheokitHome();\n const lockFile = acquirePidLock(opts.sessionId, home);\n\n const child = spawn(\n \"node\",\n [opts.bridgeScriptPath, \"--tag\", BRIDGE_PROCESS_TAG, \"--session\", opts.sessionId],\n {\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n detached: false,\n },\n );\n\n if (child.pid !== undefined) {\n fs.writeFileSync(lockFile, String(child.pid), { mode: 0o600 });\n }\n\n // EC-12: pipe stderr so the buffer never fills.\n if (child.stderr !== null) {\n child.stderr.pipe(process.stderr);\n }\n\n return { child, pidFilePath: lockFile };\n}\n\n/** Terminate the bridge: SIGTERM → wait 3s → SIGKILL. Removes PID file. */\nexport async function terminateBridge(handle: BridgeHandle): Promise<void> {\n const { child, pidFilePath: lockFile } = handle;\n if (child.pid !== undefined && !child.killed) {\n try {\n child.kill(\"SIGTERM\");\n } catch {\n /* ignore */\n }\n const exited = await waitForExit(child, 3000);\n if (!exited) {\n try {\n child.kill(\"SIGKILL\");\n } catch {\n /* ignore */\n }\n await waitForExit(child, 1000);\n }\n }\n try {\n fs.unlinkSync(lockFile);\n } catch {\n /* ignore */\n }\n}\n\nfunction waitForExit(child: ChildProcess, timeoutMs: number): Promise<boolean> {\n return new Promise((resolve) => {\n if (child.exitCode !== null || child.signalCode !== null) {\n resolve(true);\n return;\n }\n let resolved = false;\n const onExit = () => {\n if (resolved) return;\n resolved = true;\n resolve(true);\n };\n child.once(\"exit\", onExit);\n setTimeout(() => {\n if (resolved) return;\n resolved = true;\n child.removeListener(\"exit\", onExit);\n resolve(false);\n }, timeoutMs).unref();\n });\n}\n","/**\n * `WhatsAppWebBackend` — `whatsapp-web.js` subprocess bridge backend (ADR D305).\n *\n * Lifecycle (T3.1) + IPC (T3.2) wired behind the `WhatsAppBackend` interface.\n * EC-6 absorbed: `connect()` races against a 120s timeout so unattended QR\n * pairings fail fast instead of hanging the app.\n *\n * **THE CONSUMER MUST PROVIDE A BROWSER.** `whatsapp-web.js` drives a real Chrome through\n * Puppeteer, and this package ships none: the repository leaves `puppeteer` out of\n * `pnpm.onlyBuiltDependencies`, so its postinstall never downloads one. Without a browser the\n * bridge starts, cannot find Chrome, and says so in its own protocol rather than crashing —\n * which is the whole of the B-002 fix, and is still not a connection. Set\n * `PUPPETEER_EXECUTABLE_PATH` to a Chrome or Chromium you already have; the bridge is spawned\n * without an explicit `env`, so it inherits yours.\n *\n * B-002 asked for exactly this sentence or for a buildable `puppeteer`, and shipped with\n * neither. Measured 2026-08-29: with the variable set, the bridge reaches WhatsApp and issues\n * a pairing QR. {@link WhatsAppBaileysBackend} needs no browser, which is why it exists.\n *\n * @public\n */\n\nimport { existsSync } from \"node:fs\";\nimport * as path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type {\n WhatsAppBackend,\n WhatsAppInboundEvent,\n WhatsAppOutboundMessage,\n WhatsAppSendResult,\n WhatsAppStatusReceipt,\n} from \"../../backend-types.js\";\nimport {\n mapWhatsAppWebError,\n WhatsAppBridgeError,\n WhatsAppConnectTimeoutError,\n} from \"../../errors.js\";\nimport { formatCommand, type IpcEvent, LineBuffer, parseEvent } from \"./ipc.js\";\nimport { type BridgeHandle, spawnBridge, terminateBridge } from \"./lifecycle.js\";\n\nexport interface WhatsAppWebBackendOptions {\n readonly sessionId: string;\n /** Override the default bridge script path. Defaults to bundled script. */\n readonly bridgeScriptPath?: string;\n /** EC-6 connect timeout in ms. Default 120000. */\n readonly connectTimeoutMs?: number;\n /** Per-send timeout in ms. Default 30000. */\n readonly sendTimeoutMs?: number;\n /** Test seam: override the spawned child via a factory. */\n readonly spawnFactory?: () => BridgeHandle;\n /** Test seam: theokit home for PID locks. */\n readonly theokitHome?: string;\n}\n\ninterface PendingSend {\n readonly resolve: (r: WhatsAppSendResult) => void;\n readonly timer: NodeJS.Timeout;\n}\n\nconst DEFAULT_CONNECT_TIMEOUT_MS = 120_000;\nconst DEFAULT_SEND_TIMEOUT_MS = 30_000;\n\n/**\n * WhatsApp backend driving `whatsapp-web.js` in a child process.\n *\n * Unofficial: it automates a WhatsApp Web session, which Meta's terms do not sanction and which can\n * get a number banned. It exists for a personal number that has no Cloud API access. The browser\n * runs out-of-process behind a PID lock so a crashed or orphaned bridge cannot be left holding the\n * session.\n */\nexport class WhatsAppWebBackend implements WhatsAppBackend {\n readonly kind = \"web\" as const;\n private handle?: BridgeHandle;\n private readonly buffer = new LineBuffer();\n private inboundHandler?: (event: WhatsAppInboundEvent) => Promise<void>;\n private statusHandler?: (receipt: WhatsAppStatusReceipt) => Promise<void>;\n private readonly pending = new Map<string, PendingSend>();\n /** Rejects an in-flight `connect()` when the bridge reports it cannot start. */\n private connectRejectors: Array<(reason: Error) => void> = [];\n private msgIdCounter = 0;\n private botPhone?: string;\n private connected = false;\n // EC-6: emitter resolvers for `event: \"ready\"`.\n private readyResolvers: Array<(phone: string) => void> = [];\n\n constructor(private readonly opts: WhatsAppWebBackendOptions) {}\n\n private spawnBridgeHandle(): NonNullable<typeof this.handle> {\n return this.opts.spawnFactory\n ? this.opts.spawnFactory()\n : spawnBridge({\n sessionId: this.opts.sessionId,\n bridgeScriptPath: this.opts.bridgeScriptPath ?? defaultBridgeScriptPath(),\n ...(this.opts.theokitHome !== undefined ? { theokitHome: this.opts.theokitHome } : {}),\n });\n }\n\n private wireStdout(): void {\n if (this.handle?.child.stdout === null || this.handle === undefined) return;\n this.handle.child.stdout.setEncoding(\"utf8\");\n this.handle.child.stdout.on(\"data\", (chunk: string) => {\n for (const line of this.buffer.push(chunk)) {\n const event = parseEvent(line);\n if (event !== null) this.dispatch(event);\n }\n });\n }\n\n private async cleanupHandle(): Promise<void> {\n if (this.handle === undefined) return;\n await terminateBridge(this.handle).catch(() => {});\n this.handle = undefined;\n }\n\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n this.handle = this.spawnBridgeHandle();\n this.wireStdout();\n\n const timeoutMs = this.opts.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;\n const ready = new Promise<string>((resolve, reject) => {\n this.readyResolvers.push(resolve);\n // The bridge reporting a startup failure resolves the race immediately, so the caller\n // learns the cause instead of waiting out the timeout.\n this.connectRejectors.push(reject);\n });\n let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => reject(new WhatsAppConnectTimeoutError(timeoutMs)), timeoutMs);\n });\n\n try {\n const phone = await Promise.race([ready, timeout]);\n this.botPhone = phone;\n this.connected = true;\n return true;\n } catch (err) {\n await this.cleanupHandle();\n throw err;\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n // Both arrays hold settled callbacks once the race is decided, and neither was cleared\n // on the path that fails by timeout — `handleBridgeError` never ran, and `disconnect()`\n // returns early while `connected` is false. A reconnect loop therefore grew them by one\n // per attempt forever. `readyResolvers` had the same leak before this method learned to\n // reject; clearing them together is the whole fix.\n this.readyResolvers = [];\n this.connectRejectors = [];\n }\n }\n\n async disconnect(): Promise<void> {\n if (!this.connected || this.handle === undefined) return;\n try {\n if (this.handle.child.stdin !== null && !this.handle.child.stdin.destroyed) {\n this.handle.child.stdin.write(formatCommand({ cmd: \"shutdown\" }));\n }\n } catch {\n /* ignore */\n }\n await terminateBridge(this.handle);\n this.handle = undefined;\n this.connected = false;\n // Reject any pending sends.\n for (const [_, p] of this.pending) {\n clearTimeout(p.timer);\n p.resolve({ ok: false, error: { code: \"server_error\", message: \"Bridge disconnected.\" } });\n }\n this.pending.clear();\n this.readyResolvers = [];\n this.connectRejectors = [];\n }\n\n async send(message: WhatsAppOutboundMessage): Promise<WhatsAppSendResult> {\n if (!this.connected || this.handle === undefined || this.handle.child.stdin === null) {\n return { ok: false, error: { code: \"not_connected\", message: \"Bridge not connected.\" } };\n }\n const msgId = `out-${++this.msgIdCounter}`;\n const timeoutMs = this.opts.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS;\n return new Promise<WhatsAppSendResult>((resolve) => {\n const timer = setTimeout(() => {\n this.pending.delete(msgId);\n resolve({\n ok: false,\n error: { code: \"timeout\", message: `Bridge send timed out after ${timeoutMs}ms.` },\n });\n }, timeoutMs);\n this.pending.set(msgId, { resolve, timer });\n try {\n this.handle!.child.stdin!.write(\n formatCommand({ cmd: \"send\", msgId, to: message.to, text: message.text }),\n );\n } catch (err) {\n clearTimeout(timer);\n this.pending.delete(msgId);\n resolve({\n ok: false,\n error: mapWhatsAppWebError(err instanceof Error ? err.message : String(err)),\n });\n }\n });\n }\n\n onInbound(handler: (event: WhatsAppInboundEvent) => Promise<void>): () => void {\n this.inboundHandler = handler;\n return () => {\n // Identity-guarded: a stale unsubscribe must be a no-op. Without it,\n // `onInbound(A)` → `onInbound(B)` → `A.off()` clears B's handler and the backend goes\n // silent with no error — nothing to see in a log, nothing to alert on. This is a public\n // export implementing an exported interface, so a consumer holding the backend directly\n // reaches it without going through `WhatsAppAdapter`.\n if (this.inboundHandler === handler) this.inboundHandler = undefined;\n };\n }\n\n onStatusReceipt(handler: (receipt: WhatsAppStatusReceipt) => Promise<void>): () => void {\n this.statusHandler = handler;\n return () => {\n if (this.statusHandler === handler) this.statusHandler = undefined;\n };\n }\n\n private handleReady(event: Extract<IpcEvent, { event: \"ready\" }>): void {\n for (const r of this.readyResolvers) r(event.botPhone);\n this.readyResolvers = [];\n }\n\n private handleMessage(event: Extract<IpcEvent, { event: \"message\" }>): void {\n if (this.inboundHandler === undefined) return;\n const normalized: WhatsAppInboundEvent = {\n wamid: event.msgId,\n fromPhone: event.from,\n contactName: event.contactName,\n conversationType: event.isGroup ? \"group\" : \"dm\",\n channelId: event.chatId,\n text: event.body,\n receivedAt: event.timestamp || Date.now(),\n backend: \"web\",\n raw: event,\n };\n // The bridge's stdout listener is synchronous and does not await this, so the promise has to be\n // terminated here. `void` alone left the rejection unhandled, and under Node 22's default that\n // ends the process — one message with a throwing handler killed the bot (#41). A handler is\n // user code; its failure is contained and named, and the bridge keeps delivering.\n void this.inboundHandler(normalized).catch((err: unknown) => {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[whatsapp-web] handler threw: ${m}\\n`);\n });\n }\n\n /**\n * A bridge that reported a failure has failed — say so now, not in two minutes.\n *\n * This used to write the message to stderr and return. `connect()` races only the `ready`\n * promise against the timeout, so a bridge that told us exactly what was wrong and exited\n * still cost the caller the full `connectTimeoutMs` and surfaced as a timeout — the one\n * error that carries no information. The diagnosis was printed where nothing could act on\n * it, which is the swallowing `rules/error-handling.md` § 5 names.\n */\n private handleBridgeError(event: Extract<IpcEvent, { event: \"error\" }>): void {\n process.stderr.write(`[whatsapp-web bridge] ${event.message}\\n`);\n const failure = new WhatsAppBridgeError(event.message, event.code);\n // Unblocks an in-flight connect(). Harmless once connected: nobody is waiting.\n for (const reject of this.connectRejectors) reject(failure);\n this.connectRejectors = [];\n }\n\n private handleSendAck(event: Extract<IpcEvent, { event: \"send_ack\" }>): void {\n const pending = this.pending.get(event.msgId);\n if (pending === undefined) return;\n this.pending.delete(event.msgId);\n clearTimeout(pending.timer);\n if (event.success) {\n pending.resolve(event.wamid !== undefined ? { ok: true, wamid: event.wamid } : { ok: true });\n } else {\n pending.resolve({ ok: false, error: mapWhatsAppWebError(event.error) });\n }\n }\n\n private handleStatus(event: Extract<IpcEvent, { event: \"status\" }>): void {\n if (this.statusHandler === undefined) return;\n // Same boundary as handleMessage: nothing awaits this, so an unhandled rejection here is fatal.\n void this.statusHandler({\n wamid: event.msgId,\n status: event.status,\n recipient: event.recipient,\n timestamp: event.timestamp || Date.now(),\n }).catch((err: unknown) => {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[whatsapp-web] status handler threw: ${m}\\n`);\n });\n }\n\n private dispatch(event: IpcEvent): void {\n switch (event.event) {\n case \"ready\":\n this.handleReady(event);\n return;\n case \"message\":\n this.handleMessage(event);\n return;\n case \"send_ack\":\n this.handleSendAck(event);\n return;\n case \"status\":\n this.handleStatus(event);\n return;\n case \"error\":\n this.handleBridgeError(event);\n return;\n }\n }\n}\n\n/**\n * Where the bridge script lives, for the layout this module is running from.\n *\n * The single hard-coded `../../bridge/...` this replaced was written against the SOURCE\n * tree — `src/backend/web/` up two is `src/`, which is right. The bundle is one flat file\n * at `dist/index.js`, so the same relative path resolved to `packages/bridge/...`, one\n * directory above the package. Nothing caught it: every test injects `spawnFactory`, so the\n * real spawn had never run, and when it did the child died with `MODULE_NOT_FOUND` and\n * `connect()` reported a 120-second timeout — the one error carrying no information about\n * what actually happened.\n *\n * Both layouts are checked, and neither existing is an error rather than a guess: a path\n * that does not exist can only fail later, further from the cause.\n */\nexport function defaultBridgeScriptPath(): string {\n const here = path.dirname(fileURLToPath(import.meta.url));\n const candidates = [\n // Bundled: dist/index.js beside dist/bridge/\n path.resolve(here, \"bridge/whatsapp-web-bridge.mjs\"),\n // Source: src/backend/web/index.ts up two to src/\n path.resolve(here, \"../../bridge/whatsapp-web-bridge.mjs\"),\n ];\n const found = candidates.find((candidate) => existsSync(candidate));\n if (found === undefined) {\n throw new WhatsAppBridgeError(\n `bridge script not found. Looked in: ${candidates.join(\", \")}. ` +\n \"Pass `bridgeScriptPath` explicitly if the package layout differs.\",\n \"bridge_script_missing\",\n );\n }\n return found;\n}\n","/**\n * The fail-closed precondition of the adapter methods a route calls with an unfiltered Cloud\n * envelope (docs/adr/0006).\n *\n * @internal\n */\n\nimport type { WhatsAppMessageEvent } from \"@theokit/gateway\";\n\nimport type { WhatsAppInboundEvent } from \"./backend-types.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { decideInbound, type InboundRules, isForAnotherNumber } from \"./inbound-rules.js\";\n\n/**\n * The event the agent receives for `inbound`, or `undefined` when it is addressed to another number\n * than `ownPhoneNumberId` or a rule of `decideInbound` drops it.\n *\n * `onInbound` calls this without `requireOwnPhoneNumberId`: a backend that declares no number and\n * still delivers Cloud messages filtered them by its own number first (a wrapped\n * `WhatsAppCloudBackend` does), so only the methods a route hands an unfiltered envelope fail closed.\n */\nexport function decideForOwnNumber(\n inbound: WhatsAppInboundEvent,\n ownPhoneNumberId: string | undefined,\n reported: Set<string>,\n rules: InboundRules,\n): WhatsAppMessageEvent | undefined {\n if (isForAnotherNumber(inbound, ownPhoneNumberId, reported)) return undefined;\n return decideInbound(inbound, rules);\n}\n\n/**\n * The phone number id the adapter's backend declares, or a `missing_phone_number_id`\n * `ConfigurationError` naming `method` when it declares none. One Meta app signs every number's\n * webhooks with one secret, so with no number to compare, every number's messages would reach the\n * adapter's agent.\n */\nexport function requireOwnPhoneNumberId(\n ownPhoneNumberId: string | undefined,\n method: string,\n): string {\n if (ownPhoneNumberId !== undefined) return ownPhoneNumberId;\n throw new ConfigurationError({\n code: \"missing_phone_number_id\",\n message:\n `gateway-whatsapp: ${method} needs the backend to declare its phoneNumberId. ` +\n \"One Meta app signs every number's webhooks with one secret, so without it this adapter \" +\n \"would deliver every number's messages. Use fromCloud, or expose phoneNumberId on a \" +\n \"backend that wraps WhatsAppCloudBackend.\",\n });\n}\n","/**\n * Split a long string into ≤4096-char chunks for WhatsApp messages (ADR D310).\n *\n * Thin wrapper over core `chunkText` (roadmap M1). WhatsApp family: fixed 4096\n * window, `\\n\\n` → `\\n` → ` ` boundary preference, UTF-16 surrogate-pair guard,\n * leading-whitespace strip. `trimParts` reproduces EC-8 (empty parts filtered\n * so consecutive newlines don't yield empty `sendMessage` calls Meta rejects).\n * Output is byte-identical to the previous implementation (pinned by\n * `tests/split.test.ts`).\n *\n * @internal\n */\n\nimport { chunkText } from \"@theokit/gateway\";\n\nconst WHATSAPP_MAX_TEXT = 4096;\n\nexport function splitForWhatsApp(text: string): string[] {\n return chunkText(text, {\n limit: WHATSAPP_MAX_TEXT,\n boundaries: [\"\\n\\n\", \"\\n\", \" \"],\n lastResort: \"last-boundary\",\n surrogateGuard: true,\n stripLeading: /^\\s+/,\n trimParts: true,\n });\n}\n","/**\n * `WhatsAppAdapter` — WhatsApp platform adapter for `@theokit/gateway`\n * (Adoption Roadmap v1.4 #2; ADRs D303-D314).\n *\n * Multi-backend (Cloud + Web) — backend chosen via `WhatsAppAdapterOptions.backend`.\n * Backend-agnostic adapter delegates lifecycle + send + subscribe through the\n * `WhatsAppBackend` seam (D303).\n *\n * @public\n */\n\nimport {\n BasePlatformAdapter,\n type MessageEvent as GatewayMessageEvent,\n type OutboundMessage,\n type SendResult,\n type WhatsAppMessageEvent,\n} from \"@theokit/gateway\";\n\nimport { parseAllowedSenders } from \"./allowlist.js\";\nimport { WhatsAppBaileysBackend } from \"./backend/baileys/index.js\";\nimport { WhatsAppCloudBackend } from \"./backend/cloud/index.js\";\nimport type { MetaWebhookEnvelope } from \"./backend/cloud/types.js\";\nimport { normalizeInboundMessages } from \"./backend/cloud/webhook.js\";\nimport { WhatsAppWebBackend } from \"./backend/web/index.js\";\nimport type {\n WhatsAppBackend,\n WhatsAppInboundEvent,\n WhatsAppStatusReceipt,\n} from \"./backend-types.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { digitsOnly, type InboundRules, isForAnotherNumber } from \"./inbound-rules.js\";\nimport { decideForOwnNumber, requireOwnPhoneNumberId } from \"./own-number.js\";\nimport { splitForWhatsApp } from \"./split.js\";\n\nexport { digitsOnly };\n\n/** Cloud (Meta WhatsApp Business Cloud API) backend config (ADR D304). */\nexport interface WhatsAppCloudConfig {\n /**\n * The Meta system user's access token for the WhatsApp Business account.\n *\n * @platform-term Meta calls this an **access token**. Unlike the other adapters' terms, this one\n * is NOT pinned to a package under `node_modules` — the Cloud backend calls the Graph API with\n * `fetch`, so there is no Meta SDK in the dependency graph to check against. It rests on Meta's\n * own documentation, and our client sends it as `authorization: Bearer …`, never as an\n * `access_token` parameter.\n * @issued-at Meta Business Manager, under System Users → Generate token, scoped to the WhatsApp\n * Business account.\n */\n readonly accessToken: string;\n /** Meta-issued phone-number-id (NOT the user-facing phone). */\n readonly phoneNumberId: string;\n /**\n * The Meta app secret, used to verify `X-Hub-Signature-256` on inbound WhatsApp webhooks.\n *\n * @platform-term Meta calls this an **app secret** — note it belongs to the Meta app, not to the\n * WhatsApp Business account, which is why it is issued somewhere different from the access token\n * above. It signs inbound payloads and never\n * authenticates outbound calls, which is why it may be empty: an adapter that only sends does\n * not need it. Verifying a webhook needs it: `verifyWebhookSignature` throws\n * `ConfigurationError` for an empty or whitespace-only secret, because anyone can compute an\n * HMAC under an empty key.\n * @issued-at Meta for Developers, under the app's Settings → Basic.\n */\n readonly appSecret: string;\n /** Graph API version. Defaults to `v18.0`. */\n readonly apiVersion?: string;\n}\n\n/**\n * Baileys backend config (ADR D319-D322).\n *\n * Unofficial, like the `web` backend: it automates a WhatsApp Web session, which Meta's terms\n * do not sanction and which can get a number banned. Unlike `web` it needs no browser.\n *\n * @public\n */\nexport interface WhatsAppBaileysConfig {\n /**\n * Directory holding the multi-file auth state — the pairing, persisted.\n *\n * Treat it like a credential: it IS the session, and anyone holding it is the account.\n */\n readonly sessionDir: string;\n /** Give up on `connect()` after this long. Default 60s. */\n readonly connectTimeoutMs?: number;\n /** Give up on one send after this long. Default 30s. */\n readonly sendTimeoutMs?: number;\n /**\n * Where the pairing QR goes, as often as WhatsApp reissues it. Defaults to stderr.\n *\n * The backend has always accepted this; it was reachable only by constructing the backend by\n * hand, which is the path this class exists to replace. A host that is not a terminal — a\n * service, a container, a web app — cannot read stderr back to the person holding the phone,\n * and without a route out the QR a fresh `sessionDir` can only ever time out.\n */\n readonly onQr?: (qr: string) => void;\n}\n\n/** Web (whatsapp-web.js subprocess bridge) backend config (ADR D305). */\nexport interface WhatsAppWebConfig {\n /** Stable session id used to lock the bridge per-workspace. */\n readonly sessionId: string;\n /** Optional override of the bridge script path (defaults to packaged bridge). */\n readonly bridgeScriptPath?: string;\n}\n\n/**\n * Which backend to build, and its configuration.\n *\n * The union carries only what DIFFERS between backends. Options that mean the same thing on\n * either one — `requireMention`, `botPhoneId`, `allowedSenders` — live in\n * {@link WhatsAppAdapterCommonOptions} instead, so there is one copy rather than one per arm\n * for the two copies to drift apart (ADR D318).\n *\n * @public\n */\nexport type WhatsAppAdapterOptions =\n | { readonly backend: \"cloud\"; readonly cloud: WhatsAppCloudConfig }\n | { readonly backend: \"web\"; readonly web: WhatsAppWebConfig }\n | { readonly backend: \"baileys\"; readonly baileys: WhatsAppBaileysConfig };\n\n/**\n * Options that apply whichever backend is in use.\n *\n * @public\n */\nexport interface WhatsAppAdapterCommonOptions {\n /** D309: require an @mention in groups. Default `true`. */\n readonly requireMention?: boolean;\n /**\n * Phone id to detect mentions of (digits only).\n *\n * `fromCloud` defaults it to the phone number id. **The web backend has nothing to default\n * from**, so leaving it unset there while `requireMention` is on (its default) drops every\n * group message — the adapter cannot tell whether it was mentioned. That drop is now\n * logged rather than silent.\n */\n readonly botPhoneId?: string;\n /**\n * Comma-separated senders allowed to reach the handler. Absent leaves delivery unchanged;\n * an empty string admits nobody. See `allowlist.ts` for why those differ.\n */\n readonly allowedSenders?: string;\n}\n\n/**\n * Fail at the boundary when a required option is missing or blank.\n *\n * A factory that returns an adapter with an empty token has moved the error away from its\n * cause: the stack then names a send, and the mistake was in construction\n * (`rules/error-handling.md` § 2).\n */\nfunction requireNonEmpty(entries: ReadonlyArray<readonly [string, string | undefined]>): void {\n for (const [name, value] of entries) {\n if (value === undefined || value.trim().length === 0) {\n throw new ConfigurationError({\n code: \"missing_option\",\n message: `gateway-whatsapp: ${name} is required and must not be empty.`,\n });\n }\n }\n}\n\n/**\n * Adapter facade. Implements `BasePlatformAdapter` (D172).\n *\n * Use `WhatsAppAdapter.fromCloud(config)` or `WhatsAppAdapter.fromWeb(config)`. The\n * constructor stays available for tests and for a backend of your own.\n */\nexport class WhatsAppAdapter extends BasePlatformAdapter {\n readonly platform = \"whatsapp\" as const;\n private readonly backendImpl: WhatsAppBackend;\n /**\n * The bot's number, digits only. Kept as its own field because the documented construction\n * path is tested by reading it (`fromCloud` defaulting it to the phone number id).\n */\n private readonly botPhoneId: string;\n /** The sender allowlist and group rule the inbound path decides by. */\n private readonly rules: InboundRules;\n /**\n * The Cloud phone number id this adapter answers for, read from the backend's declared\n * `phoneNumberId` at construction (so `fromCloud`, `new WhatsAppAdapter(new WhatsAppCloudBackend(...))`\n * and any backend declaring the field decide alike), `undefined` for a backend that declares none.\n * Meta signs every number of one app with one secret, so a signed message is only this adapter's\n * when its `phoneNumberId` is this one.\n */\n private readonly ownPhoneNumberId: string | undefined;\n /** Foreign phone number id endings already named on stderr, so each is reported once. */\n private readonly reportedForeignNumbers = new Set<string>();\n /** The rules both inbound paths share; `onInbound` skips the precondition (see `decideForOwnNumber`). */\n private readonly decide = (inbound: WhatsAppInboundEvent): WhatsAppMessageEvent | undefined =>\n decideForOwnNumber(inbound, this.ownPhoneNumberId, this.reportedForeignNumbers, this.rules);\n /** Mirrors the sibling adapters: guards connect() against opening a second session. */\n private connected = false;\n private handler?: (event: GatewayMessageEvent) => Promise<void>;\n private statusHandler?: (receipt: WhatsAppStatusReceipt) => Promise<void>;\n\n /** Whether the \"this platform carries no format flag\" warning has already been emitted. */\n private warnedAboutFormat = false;\n\n /**\n * Say, once, that a declared `format` has nowhere to go on this platform.\n *\n * WhatsApp's emphasis is INLINE — `*bold*`, `_italic_` — carried in the message text itself,\n * with no field on the request to set and no escape sequence to suppress it. So a caller\n * declaring `markdown` has already put the syntax in the text, and one declaring `html` is\n * asking for something the platform does not have.\n *\n * Reading the field is what turns a silent discard into a stated one — the swallowed-error\n * shape `rules/error-handling.md` refuses.\n *\n * @internal\n */\n private warnFormatUnsupported(format: string | undefined): void {\n // The \"is there anything to say\" question lives here rather than at the call site: a\n // `sendMessage` already at its complexity limit should ask one thing, not three.\n if (format === undefined || format === \"plain\") return;\n if (this.warnedAboutFormat) return;\n this.warnedAboutFormat = true;\n process.stderr.write(\n `[whatsapp] format=\"${format}\" was declared, and WhatsApp cannot carry it as a flag — ` +\n \"its emphasis is inline in the text. Sending as-is; this is logged once.\\n\",\n );\n }\n\n // EC-H: track unsubscribe handles so onInbound REPLACES instead of stacks.\n private inboundUnsubscribe?: () => void;\n private statusUnsubscribe?: () => void;\n\n /**\n * Build an adapter from a discriminated configuration.\n *\n * The entry point for configuration that arrives as **data** — read from a file, an\n * environment, or a tenant record — where the backend is a string rather than a decision\n * made in code. `fromCloud` / `fromWeb` are the direct forms when the choice is already\n * known at the call site.\n *\n * This is what `WhatsAppAdapterOptions` exists for. Until it had this consumer the union\n * was exported, documented and inert, which is the defect #47 was filed about, and the\n * first attempt at closing that issue left it inert — the factories took the config halves\n * directly and never the union.\n *\n * @throws {ConfigurationError} when a required option is missing or empty.\n * @public\n */\n static from(\n options: WhatsAppAdapterOptions,\n common: WhatsAppAdapterCommonOptions = {},\n ): WhatsAppAdapter {\n switch (options.backend) {\n case \"cloud\":\n return WhatsAppAdapter.fromCloud(options.cloud, common);\n case \"web\":\n return WhatsAppAdapter.fromWeb(options.web, common);\n case \"baileys\":\n return WhatsAppAdapter.fromBaileys(options.baileys, common);\n }\n }\n\n /**\n * Build a Baileys adapter.\n *\n * Unofficial, and no amount of code changes that: it automates a WhatsApp Web session,\n * which Meta's terms do not sanction and which can get a number banned. Use a number\n * created for this, never a personal one. Prefer {@link WhatsAppAdapter.fromCloud} unless\n * the number has no Cloud API access.\n *\n * Unlike {@link WhatsAppAdapter.fromWeb} it embeds no browser — it speaks the multi-device\n * protocol over a WebSocket. `baileys` is an optional peer dependency; it is loaded lazily\n * at connect, so a consumer who never calls this never needs it installed.\n *\n * `botPhoneId` has nothing to default from here, so leaving it unset while `requireMention`\n * is on (its default) drops every group message. The adapter logs when it does.\n *\n * @throws {ConfigurationError} when `sessionDir` is missing or empty.\n * @public\n */\n static fromBaileys(\n baileys: WhatsAppBaileysConfig,\n opts: WhatsAppAdapterCommonOptions = {},\n ): WhatsAppAdapter {\n requireNonEmpty([[\"sessionDir\", baileys.sessionDir]]);\n return new WhatsAppAdapter(\n new WhatsAppBaileysBackend({\n sessionDir: baileys.sessionDir,\n ...(baileys.connectTimeoutMs !== undefined\n ? { connectTimeoutMs: baileys.connectTimeoutMs }\n : {}),\n ...(baileys.sendTimeoutMs !== undefined ? { sendTimeoutMs: baileys.sendTimeoutMs } : {}),\n ...(baileys.onQr !== undefined ? { onQr: baileys.onQr } : {}),\n }),\n opts,\n );\n }\n\n /**\n * Build a Cloud-API adapter.\n *\n * The construction path this package's docblock has named since it was written, and which\n * did not exist until #47 — a consumer following the only guidance the package gave wrote\n * code that would not compile.\n *\n * Prefer it over the constructor: it keeps `WhatsAppCloudBackend` an implementation detail\n * of this package rather than something every consumer imports and assembles.\n *\n * @throws {ConfigurationError} when a required credential is missing or empty.\n * @public\n */\n static fromCloud(\n cloud: WhatsAppCloudConfig,\n opts: WhatsAppAdapterCommonOptions = {},\n ): WhatsAppAdapter {\n // `appSecret` is deliberately NOT required: it verifies inbound webhook signatures\n // (`backend/cloud/index.ts`) and outbound never reads it. This repository's own\n // integration suite passes `\"\"` for exactly that reason, so requiring it would have\n // locked an outbound-only consumer out of the path this factory exists to offer.\n requireNonEmpty([\n [\"accessToken\", cloud.accessToken],\n [\"phoneNumberId\", cloud.phoneNumberId],\n ]);\n // INFO-10: an empty apiVersion yields `https://graph.facebook.com//<id>`, because the\n // client's `?? \"v18.0\"` does not catch `\"\"`. Absent is fine; blank is a mistake.\n if (cloud.apiVersion !== undefined) {\n requireNonEmpty([[\"apiVersion\", cloud.apiVersion]]);\n }\n return new WhatsAppAdapter(\n new WhatsAppCloudBackend({\n accessToken: cloud.accessToken,\n phoneNumberId: cloud.phoneNumberId,\n appSecret: cloud.appSecret,\n ...(cloud.apiVersion !== undefined ? { apiVersion: cloud.apiVersion } : {}),\n }),\n { ...opts, botPhoneId: opts.botPhoneId ?? cloud.phoneNumberId },\n );\n }\n\n /**\n * Build a WhatsApp-Web adapter.\n *\n * Unofficial: it drives a real WhatsApp Web session through a browser, which Meta's terms\n * do not sanction and which can get a number banned. It also needs a browser this package\n * does not install. Prefer {@link WhatsAppAdapter.fromCloud} unless the number has no\n * Cloud API access.\n *\n * @throws {ConfigurationError} when `sessionId` is missing or empty.\n * @public\n */\n static fromWeb(web: WhatsAppWebConfig, opts: WhatsAppAdapterCommonOptions = {}): WhatsAppAdapter {\n requireNonEmpty([[\"sessionId\", web.sessionId]]);\n return new WhatsAppAdapter(\n new WhatsAppWebBackend({\n sessionId: web.sessionId,\n ...(web.bridgeScriptPath !== undefined ? { bridgeScriptPath: web.bridgeScriptPath } : {}),\n }),\n opts,\n );\n }\n\n /** Construct from a pre-built backend. Prefer the factories; this is for tests and for a custom backend. */\n constructor(backendImpl: WhatsAppBackend, opts: WhatsAppAdapterCommonOptions = {}) {\n super();\n this.backendImpl = backendImpl;\n this.ownPhoneNumberId = backendImpl.phoneNumberId;\n this.botPhoneId = digitsOnly(opts.botPhoneId ?? \"\");\n this.rules = {\n requireMention: opts.requireMention ?? true,\n botPhoneId: this.botPhoneId,\n // Absent and empty are different answers. Absent means the operator has not adopted the\n // filter, and delivery is unchanged. Empty means they configured one and named nobody, which\n // is a decision — `parseAllowedSenders` is fail-closed and honours it.\n allowedSenders:\n opts.allowedSenders === undefined ? undefined : parseAllowedSenders(opts.allowedSenders),\n };\n }\n\n /** Escape hatch (D180-style) for advanced features. */\n getBackend(): WhatsAppBackend {\n return this.backendImpl;\n }\n\n async connect(): Promise<boolean> {\n // Guard added 2026-08-17: this was the only adapter without one, so a second\n // connect() opened a second live WhatsApp session. Teams, SMS and Slack all\n // short-circuit here. Note it latches on SUCCESS only — a refused connect\n // must stay retryable, or one network blip becomes permanent.\n if (this.connected) return true;\n const ok = await this.backendImpl.connect();\n this.connected = ok;\n return ok;\n }\n\n async disconnect(): Promise<void> {\n this.connected = false;\n this.inboundUnsubscribe?.();\n this.inboundUnsubscribe = undefined;\n this.statusUnsubscribe?.();\n this.statusUnsubscribe = undefined;\n this.handler = undefined;\n this.statusHandler = undefined;\n await this.backendImpl.disconnect();\n }\n\n async sendMessage(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"Empty text rejected.\" } };\n }\n // EC-8: split filters empty parts internally.\n // WhatsApp has no formatting flag: emphasis is inline in the text. Reading the field\n // is what makes the discard visible rather than silent.\n this.warnFormatUnsupported(out.format);\n const parts = splitForWhatsApp(out.text);\n if (parts.length === 0) {\n return {\n ok: false,\n error: { code: \"empty_text\", message: \"Text reduced to zero parts after splitting.\" },\n };\n }\n let lastWamid: string | undefined;\n const isGroup = out.channel.type === \"group\";\n for (const part of parts) {\n const r = await this.backendImpl.send({ to: out.channel.id, isGroup, text: part });\n if (!r.ok) {\n return {\n ok: false,\n error: { code: r.error?.code ?? \"unknown\", message: r.error?.message ?? \"Send failed.\" },\n };\n }\n lastWamid = r.wamid;\n }\n return lastWamid !== undefined ? { ok: true, messageId: lastWamid } : { ok: true };\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace any previous subscription.\n this.inboundUnsubscribe?.();\n this.handler = handler;\n\n // The bridge calls the handler it was created for, never `this.handler`: the backend hands a\n // signed batch whole to the bridge that accepted it, and re-reading the current handler per\n // message let a disconnect or unsubscribe inside the first message drop the rest of a batch\n // already answered 200. New batches stop at the backend, because `off()` removes the bridge.\n const off = this.backendImpl.onInbound(async (inbound) => {\n const event = this.decide(inbound);\n if (event === undefined) return;\n await handler(event);\n });\n this.inboundUnsubscribe = off;\n\n return () => {\n // Identity-guarded, like every sibling adapter. Without the guard this closure tore down\n // whatever subscription was CURRENT: `onInbound(A)` → `onInbound(B)` → A's stale `off()`\n // killed B's and nulled the handler, and the gateway went silent with no error. That is\n // the defect the cross-adapter contract exists to catch, and this adapter was exempted\n // from it by a comment claiming its mechanism gave \"the same guarantee\" — it had no\n // guard at all.\n if (this.handler === handler) {\n this.handler = undefined;\n off();\n this.inboundUnsubscribe = undefined;\n }\n };\n }\n\n /**\n * The event `onInbound` would hand its handler for this inbound message, or `undefined` when the\n * sender allowlist refuses it or the group rule drops it. A refusal writes the same stderr line\n * `onInbound` writes.\n *\n * It also drops a message addressed to another phone number id than the one the backend\n * declares (one app may serve several numbers under one secret), naming that id on stderr once.\n * A Cloud message on an adapter whose backend declares no `phoneNumberId` throws, as in\n * `toDeliverableEvents`; a WhatsApp Web or Baileys message has no number to compare.\n *\n * Pass the result to `deliver()`. Neither the backend nor the network is called.\n *\n * @throws {ConfigurationError} (`missing_phone_number_id`) for a Cloud message when the backend\n * declares no `phoneNumberId`.\n * @public\n */\n toDeliverableEvent(inbound: WhatsAppInboundEvent): WhatsAppMessageEvent | undefined {\n if (inbound.backend === \"cloud\") {\n requireOwnPhoneNumberId(this.ownPhoneNumberId, \"toDeliverableEvent\");\n }\n return this.decide(inbound);\n }\n\n /**\n * The events of one Meta Cloud webhook envelope that may reach the agent, in envelope order, with\n * the sender allowlist and the group rule applied. Status receipts and non-text messages yield no\n * event, so a status-only envelope returns `[]`. Each refused or dropped message writes the\n * same stderr line `onInbound` writes. Messages addressed to another `phone_number_id` are\n * dropped (see `toDeliverableEvent`).\n *\n * The adapter's backend must declare its `phoneNumberId`. `fromCloud` and any\n * `WhatsAppCloudBackend` do; a backend that wraps one by delegation must expose the field too.\n * Without it there is no number to compare, and every number of the Meta app would reach this\n * adapter's agent, so this method fails closed instead (docs/adr/0006).\n *\n * The route that receives the webhook verifies `X-Hub-Signature-256` first (with\n * `verifyWebhookSignature`, or theokit's `whatsapp()` route validator); this method does not. Meta redelivers on timeout, and\n * `event.whatsapp.wamid` is the key a route can use to ignore a repeat. Neither the backend nor\n * the network is called.\n *\n * @throws {ConfigurationError} (`missing_phone_number_id`) when the backend declares no\n * `phoneNumberId`.\n * @public\n */\n toDeliverableEvents(envelope: MetaWebhookEnvelope): WhatsAppMessageEvent[] {\n requireOwnPhoneNumberId(this.ownPhoneNumberId, \"toDeliverableEvents\");\n const events: WhatsAppMessageEvent[] = [];\n for (const inbound of normalizeInboundMessages(envelope)) {\n const event = this.toDeliverableEvent(inbound);\n if (event !== undefined) events.push(event);\n }\n return events;\n }\n\n /**\n * Status receipts (sent/delivered/read/failed). Adapter-specific (D307). A receipt names the\n * customer's number, so one addressed to another phone number id is dropped, as messages are.\n */\n onStatusReceipt(handler: (receipt: WhatsAppStatusReceipt) => Promise<void>): () => void {\n this.statusUnsubscribe?.();\n this.statusHandler = handler;\n const off = this.backendImpl.onStatusReceipt(async (r) => {\n if (isForAnotherNumber(r, this.ownPhoneNumberId, this.reportedForeignNumbers)) return;\n await this.statusHandler?.(r);\n });\n this.statusUnsubscribe = off;\n return () => {\n // Same identity guard, same reason. A stale unsubscribe must be a no-op.\n if (this.statusHandler === handler) {\n this.statusHandler = undefined;\n off();\n this.statusUnsubscribe = undefined;\n }\n };\n }\n\n /**\n * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).\n *\n * One line over `runHandler`, which owns the containment: a handler is user code, its throw is\n * named as the handler's failure rather than the platform's, and delivery continues.\n */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n return this.runHandler(this.handler, event);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/allowlist.ts","../src/backend/baileys/normalize.ts","../src/errors.ts","../src/backend/baileys/socket.ts","../src/backend/baileys/index.ts","../src/inbound-rules.ts","../src/foreign-number.ts","../src/backend/cloud/client.ts","../src/backend/cloud/signature.ts","../src/backend/cloud/webhook.ts","../src/backend/cloud/index.ts","../src/backend/web/ipc.ts","../src/backend/web/lifecycle.ts","../src/backend/web/index.ts","../src/own-number.ts","../src/refuse-attachments.ts","../src/split.ts","../src/adapter.ts"],"names":["GatewayConfigurationError","resolve","crypto","path","fs","execSync","spawn","DEFAULT_CONNECT_TIMEOUT_MS","DEFAULT_SEND_TIMEOUT_MS","path2","fileURLToPath","existsSync","chunkText","BasePlatformAdapter"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,IAAM,QAAA,GAAW,GAAA;AAcV,SAAS,oBAAoB,KAAA,EAAuB;AACzD,EAAA,MAAM,aAAA,GAAgB,KAAA,CAAM,OAAA,CAAQ,aAAA,EAAe,EAAE,CAAA;AACrD,EAAA,MAAM,aAAA,GAAgB,aAAA,CAAc,OAAA,CAAQ,MAAA,EAAQ,EAAE,CAAA;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A,GAAM,IAAA,CAAK,WAAA,CAAY,eAAA,CAAgB,OAAO,CAAA,KAAM;AACxD,MAAA,IAAI,mBAAmB,CAAA,EAAG,IAAA,CAAK,gBAAA,EAAkB,IAAA,CAAK,sBAAsB,CAAA,EAAG;AAC/E,MAAA,MAAM,IAAA,CAAK,gBAAgB,CAAC,CAAA;AAAA,IAC9B,CAAC,CAAA;AACD,IAAA,IAAA,CAAK,iBAAA,GAAoB,GAAA;AACzB,IAAA,OAAO,MAAM;AAEX,MAAA,IAAI,IAAA,CAAK,kBAAkB,OAAA,EAAS;AAClC,QAAA,IAAA,CAAK,aAAA,GAAgB,MAAA;AACrB,QAAA,GAAA,EAAI;AACJ,QAAA,IAAA,CAAK,iBAAA,GAAoB,MAAA;AAAA,MAC3B;AAAA,IACF,CAAA;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAe,QACb,KAAA,EACgD;AAChD,IAAA,OAAO,IAAA,CAAK,UAAA,CAAW,IAAA,CAAK,OAAA,EAAS,KAAK,CAAA;AAAA,EAC5C;AACF","file":"index.cjs","sourcesContent":["/**\n * Who is allowed to reach the handler — a fail-closed sender allowlist.\n *\n * Until this existed the package had no sender filter. `shouldDropGroupMessage` fires only for\n * *groups* with `requireMention`, so any stranger who sent a direct message reached the agent.\n *\n * That is two problems wearing one coat. A number that answers strangers accumulates blocks and\n * reports, which is what WhatsApp's enforcement runs on — so an open gateway is a slow route to a\n * banned number. And an agent wired to tools acts on what arrives, so an unfiltered inbound is an\n * instruction channel for anyone who knows the number. Baileys' own `GHSA-qvv5-jq5g-4cgg` — a\n * crafted `protocolMessage` that forges a `messages.upsert` — is the same hazard reached through\n * the library rather than through the phone, and an allowlist narrows both.\n *\n * Pure by construction: no socket, no I/O, no clock. The decision is the part worth testing, and\n * it can be tested exhaustively without a phone number, which the transport around it cannot.\n *\n * @public\n */\n\n/** Allows every identified sender. Must be set deliberately; it is never the default. */\nconst WILDCARD = \"*\";\n\n/**\n * Reduce a WhatsApp identifier to the digits that identify the account.\n *\n * WhatsApp addresses carry two things that are not part of the number: a device suffix\n * (`:12`) and a domain (`@s.whatsapp.net`, `@g.us`, `@lid`). Stripping non-digits without\n * removing the suffix first merges the device id into the number —\n * `5511999999999:12@s.whatsapp.net` becomes `551199999999912`, which matches no allowlist entry,\n * so the filter silently stops recognising that sender the moment they use a second device.\n *\n * Returns `\"\"` when the input carries no identifier at all. Callers must treat that as\n * unidentified, never as a match.\n */\nexport function normalizeWhatsAppId(value: string): string {\n const withoutDevice = value.replace(/:[^@]*(?=@)/, \"\");\n const withoutDomain = withoutDevice.replace(/@.*$/, \"\");\n return withoutDomain.replace(/\\D/g, \"\");\n}\n\n/**\n * Parse a comma-separated allowlist into normalised entries.\n *\n * Blank entries are dropped rather than kept: an empty string is what an unreadable identifier\n * normalises to, so admitting `\"\"` to the set would admit precisely the senders whose id could\n * not be read. The wildcard is preserved verbatim, since normalising it would erase it.\n */\nexport function parseAllowedSenders(raw: string | undefined): ReadonlySet<string> {\n const entries = (raw ?? \"\")\n .split(\",\")\n .map((entry) => entry.trim())\n .map((entry) => (entry === WILDCARD ? WILDCARD : normalizeWhatsAppId(entry)))\n .filter((entry) => entry.length > 0);\n return new Set(entries);\n}\n\n/**\n * May `senderId` reach the handler?\n *\n * **Fail-closed.** An empty allowlist admits nobody. An operator who has not configured one has\n * not decided who may drive the agent, and the safe reading of \"has not decided\" is \"not yet\" —\n * not \"everyone\". The inverse default is a mistake worth naming: it makes the safest-looking\n * configuration, the empty one, the most open.\n *\n * An unidentifiable sender is refused even under the wildcard. `*` means \"any sender\", and\n * something whose sender cannot be named is not a sender; letting it through would make the\n * wildcard the single path that skips identification altogether.\n */\nexport function isSenderAllowed(senderId: string, allowed: ReadonlySet<string>): boolean {\n const normalized = normalizeWhatsAppId(senderId);\n if (normalized.length === 0) return false;\n if (allowed.size === 0) return false;\n if (allowed.has(WILDCARD)) return true;\n return allowed.has(normalized);\n}\n","/**\n * Baileys envelope → `WhatsAppInboundEvent`. Pure: no socket, no clock, no I/O.\n *\n * Purity is the point rather than a preference. Nothing in this repository can exercise the\n * WhatsApp protocol — pairing needs a human with a phone — so the only part of this backend\n * that can be tested exhaustively is the part that does not touch the network. Every decision\n * that can live here does.\n *\n * It returns `undefined` rather than throwing for anything it will not accept. The input\n * arrives straight off a socket from a library that has shipped a message-spoofing advisory\n * (`GHSA-qvv5-jq5g-4cgg`), so a malformed or hostile envelope is an expected case, not an\n * exceptional one — and a throw here would take down whatever is dispatching.\n *\n * @internal\n */\n\nimport { normalizeWhatsAppId } from \"../../allowlist.js\";\nimport type { WhatsAppInboundEvent } from \"../../backend-types.js\";\n\n/** WhatsApp's status feed. Never a conversation, always noise for a bot. */\nconst STATUS_BROADCAST_JID = \"status@broadcast\";\n\n/** Envelopes that carry the real message one level down. */\nconst WRAPPER_KEYS = [\n \"ephemeralMessage\",\n \"viewOnceMessage\",\n \"viewOnceMessageV2\",\n \"documentWithCaptionMessage\",\n] as const;\n\n/** How deep to follow nested wrappers before giving up. Hostile input must not recurse forever. */\nconst MAX_WRAPPER_DEPTH = 3;\n\n/** The subset of a Baileys `WAMessage` this normaliser reads. */\ninterface RawEnvelope {\n key?: {\n remoteJid?: unknown;\n participant?: unknown;\n fromMe?: unknown;\n id?: unknown;\n };\n message?: Record<string, unknown>;\n messageTimestamp?: unknown;\n pushName?: unknown;\n}\n\n/** Narrow an unknown to an object without asserting anything about its members. */\nfunction asObject(value: unknown): Record<string, unknown> | undefined {\n return typeof value === \"object\" && value !== null\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\n/** A non-empty string, or undefined. */\nfunction asText(value: unknown): string | undefined {\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\n/**\n * The plain text of a message, from either shape Baileys uses.\n *\n * `conversation` carries a bare message; `extendedTextMessage` carries one with context — a\n * reply, a link preview, a mention. v1 is text-only, like the two sibling backends, so any\n * other content type yields undefined and the message is dropped.\n */\nfunction extractText(message: Record<string, unknown> | undefined, depth = 0): string | undefined {\n if (message === undefined || depth > MAX_WRAPPER_DEPTH) return undefined;\n\n const direct = asText(message.conversation);\n if (direct !== undefined) return direct;\n\n const extended = asObject(message.extendedTextMessage);\n const fromExtended = extended === undefined ? undefined : asText(extended.text);\n if (fromExtended !== undefined) return fromExtended;\n\n // Baileys nests the real message inside a wrapper for disappearing messages and view-once.\n // Without unwrapping, every text sent in a chat with disappearing messages turned on was\n // dropped in silence — indistinguishable from an image, which the \"v1 is text-only\"\n // rationale was covering for.\n for (const wrapper of WRAPPER_KEYS) {\n const inner = asObject(message[wrapper]);\n const nested = inner === undefined ? undefined : asObject(inner.message);\n const text = extractText(nested, depth + 1);\n if (text !== undefined) return text;\n }\n return undefined;\n}\n\n/**\n * The message's timestamp in seconds, or `undefined` when it cannot be read.\n *\n * Baileys reports seconds; every other backend here reports milliseconds, which is why the\n * caller multiplies.\n *\n * Returning `undefined` — which makes the caller drop the envelope — is this module's uniform\n * contract, not a special rule: it refuses anything it cannot fully read, exactly as it refuses\n * an unidentifiable sender or a non-text body. An earlier version of this comment justified the\n * drop by a \"freshness window\" that would reject stale messages. **No such window exists** —\n * `receivedAt` is declared in `@theokit/gateway` and read by nothing. A review caught the claim.\n * The replay defence in this backend is the `type !== \"notify\"` filter on `messages.upsert`.\n *\n * Worth knowing when comparing backends: `backend/cloud/webhook.ts` takes the opposite branch,\n * substituting the current time for an unreadable stamp. Neither is wrong given that nobody\n * reads the field; they are inconsistent, and that is recorded rather than quietly aligned.\n */\nfunction toSeconds(timestamp: unknown): number | undefined {\n if (typeof timestamp === \"number\") return timestamp;\n if (typeof timestamp === \"string\") {\n const parsed = Number(timestamp);\n return Number.isFinite(parsed) ? parsed : undefined;\n }\n // Baileys' generated protobuf types permit a `Long`. Read as unparseable, a perfectly good\n // message from a real user would be dropped for a field nobody reads — so the shape is\n // handled rather than refused.\n const asLong = asObject(timestamp);\n if (asLong !== undefined && typeof asLong.toNumber === \"function\") {\n const parsed = (asLong.toNumber as () => unknown)();\n return typeof parsed === \"number\" && Number.isFinite(parsed) ? parsed : undefined;\n }\n return undefined;\n}\n\n/**\n * Who sent this, and where does it belong?\n *\n * In a group the channel is the group and the sender is the participant; in a DM both are\n * `remoteJid`. Reading `remoteJid` as the sender in a group would attribute every group\n * message to the group itself, which breaks the allowlist and any per-sender session key at\n * once. Returns `undefined` when either cannot be identified — and \"we do not know who sent\n * this\" must never resolve to \"let it through\".\n */\nfunction resolveParties(\n key: Record<string, unknown>,\n remoteJid: string,\n): { fromPhone: string; channelId: string; channelJid: string; isGroup: boolean } | undefined {\n const isGroup = remoteJid.endsWith(\"@g.us\");\n const senderJid = isGroup ? asText(key.participant) : remoteJid;\n if (senderJid === undefined) return undefined;\n\n const fromPhone = normalizeWhatsAppId(senderJid);\n const channelId = normalizeWhatsAppId(remoteJid);\n if (fromPhone.length === 0 || channelId.length === 0) return undefined;\n // `remoteJid` is carried out UNCHANGED beside the normalised id. The normalisation is what the\n // allowlist compares; the raw form is the only thing a reply can be addressed to, and the two are\n // not interchangeable — stripping the domain loses which KIND of address it was (#84).\n return { fromPhone, channelId, channelJid: remoteJid, isGroup };\n}\n\n/**\n * What the backend knows that a single envelope cannot carry.\n *\n * Both fields are optional and an absent one means \"unknown\", never \"anything goes\": with no\n * context the guard below behaves exactly as it did before this type existed.\n *\n * @public\n */\nexport interface BaileysDispatchContext {\n /**\n * The JIDs that ARE this account, normalised — its phone JID and its LID.\n *\n * A set rather than one id because the self-chat is addressed by LID, not by phone JID, and\n * both forms reach the socket. An EMPTY set means the backend has not learned them yet, and\n * the safe reading of \"we do not know which chat is the self-chat\" is not \"every chat is\".\n */\n readonly selfJids?: ReadonlySet<string>;\n /** Message ids this backend sent. Its own echoes — the thing that must never be answered. */\n readonly sentWamids?: ReadonlySet<string>;\n}\n\n/**\n * Should this envelope reach a handler at all?\n *\n * Refused: the status feed, which is never a conversation, and the replies THIS BACKEND sent —\n * or the bot answers itself, forever, a lesson every backend in this package learned separately.\n *\n * The second refusal used to be spelled `fromMe`, and that was broader than the reason written\n * beside it. `fromMe` does not mean \"we sent it\"; it means \"this ACCOUNT sent it\", which includes\n * the human typing on their own phone. Measured against a real paired account on 2026-08-30: a\n * note-to-self arrives as live traffic (`upsert type=notify`, with content) and was discarded for\n * that reason alone — foreclosing the note-to-self agent, which is what this gateway family exists\n * for. Every other gateway here answers it, because there the bot is a separate identity; on\n * WhatsApp the paired account IS the person.\n *\n * So the refusal now aims at what actually causes the loop — an id we sent — and stays inside the\n * self-chat. A message the owner sent to SOMEBODY ELSE is still refused: answering there would put\n * the agent into a third party's conversation, in the owner's name, triggered by the owner's own\n * words.\n */\nfunction isDispatchable(\n key: Record<string, unknown>,\n remoteJid: string,\n wamid: string,\n ctx: BaileysDispatchContext | undefined,\n): \"no\" | \"yes\" | \"yes-from-self\" {\n if (remoteJid === STATUS_BROADCAST_JID) return \"no\";\n if (key.fromMe !== true) return \"yes\";\n\n const selfJids = ctx?.selfJids;\n if (selfJids === undefined || selfJids.size === 0) return \"no\";\n if (!selfJids.has(normalizeWhatsAppId(remoteJid))) return \"no\";\n return ctx?.sentWamids?.has(wamid) === true ? \"no\" : \"yes-from-self\";\n}\n\n/** The envelope's addressing, once every field it needs has been read and none was missing. */\ninterface Addressed {\n readonly key: Record<string, unknown>;\n readonly remoteJid: string;\n readonly wamid: string;\n}\n\n/**\n * Read the envelope's addressing, or refuse it.\n *\n * Split from {@link normalizeBaileysMessage} because the two halves answer different questions:\n * this one asks whether the envelope IS one — has a key, a chat, an id — and the caller asks\n * whether it should be delivered. Together they read as one ladder of early returns, which is\n * what pushed the function past its complexity budget when the dispatch verdict grew a third\n * outcome.\n */\nfunction addressingOf(envelope: RawEnvelope | undefined): Addressed | undefined {\n const key = envelope === undefined ? undefined : asObject(envelope.key);\n if (key === undefined) return undefined;\n const remoteJid = asText(key.remoteJid);\n const wamid = asText(key.id);\n if (remoteJid === undefined || wamid === undefined) return undefined;\n return { key, remoteJid, wamid };\n}\n\n/**\n * Normalise one inbound envelope, or refuse it.\n *\n * Refused: the replies this backend sent, messages this account sent OUTSIDE its own self-chat,\n * the status feed, any content that is not text, and anything whose sender cannot be identified.\n * That last one matters most — an event with an unidentifiable sender would reach an allowlist\n * with nothing to match against, and the safe reading of \"we do not know who sent this\" is not\n * \"let it through\". See {@link BaileysDispatchContext} for what the backend must supply before a\n * note-to-self can be answered at all.\n */\nexport function normalizeBaileysMessage(\n raw: unknown,\n ctx?: BaileysDispatchContext,\n): WhatsAppInboundEvent | undefined {\n const envelope = asObject(raw) as RawEnvelope | undefined;\n const addressed = addressingOf(envelope);\n if (addressed === undefined) return undefined;\n\n const { key, remoteJid, wamid } = addressed;\n const verdict = isDispatchable(key, remoteJid, wamid, ctx);\n if (verdict === \"no\") return undefined;\n\n const text = extractText(envelope?.message);\n if (text === undefined) return undefined;\n\n const parties = resolveParties(key, remoteJid);\n if (parties === undefined) return undefined;\n\n const seconds = toSeconds(envelope?.messageTimestamp);\n if (seconds === undefined) return undefined;\n\n const contactName = asText(envelope?.pushName);\n\n return {\n wamid,\n fromPhone: parties.fromPhone,\n conversationType: parties.isGroup ? \"group\" : \"dm\",\n channelId: parties.channelId,\n channelJid: parties.channelJid,\n text,\n receivedAt: seconds * 1_000,\n backend: \"baileys\",\n raw,\n ...(verdict === \"yes-from-self\" ? { fromSelf: true } : {}),\n ...(contactName !== undefined ? { contactName } : {}),\n };\n}\n","/**\n * Per-backend HTTP/IPC error → canonical `WhatsAppSendResult.error` shape.\n *\n * Cloud follows Meta error codes (https://developers.facebook.com/docs/graph-api/guides/error-handling).\n * Web follows whatsapp-web.js error strings.\n *\n * @internal\n */\n\nimport { GatewayConfigurationError, type GatewayConfigurationErrorOptions } from \"@theokit/gateway\";\n\nimport type { WhatsAppError, WhatsAppSendResult } from \"./backend-types.js\";\n\ntype ErrorPayload = Required<WhatsAppSendResult>[\"error\"];\n\ninterface MetaErrorBody {\n error?: {\n code?: number;\n message?: string;\n error_subcode?: number;\n };\n}\n\n/**\n * Public input shape for the {@link ConfigurationError} constructor.\n *\n * Aliased from the core rather than redeclared. The base type exists precisely so every\n * adapter stops writing its own copy of the same three fields, and a redeclaration means a\n * field added to the core silently never reaches this package. Four siblings alias it the\n * same way.\n */\nexport type ConfigurationErrorOptions = GatewayConfigurationErrorOptions;\n\n/**\n * A required option is missing or empty.\n *\n * Raised where a consumer hands us configuration — the factories — rather than later, when\n * the value is finally used against the network. A factory that returns an adapter which\n * cannot authenticate has moved the error away from its cause: the stack then names a send,\n * and the mistake was in construction.\n *\n * Matches the shape every sibling adapter uses (`gateway-line`, `gateway-email`, …), which\n * is what makes one `catch (e) { if (e instanceof GatewayConfigurationError) }` work across\n * all of them.\n *\n * @public\n */\nexport class ConfigurationError extends GatewayConfigurationError {\n override readonly name = \"ConfigurationError\";\n constructor(opts: ConfigurationErrorOptions) {\n super(\"gateway-whatsapp\", opts);\n }\n}\n\n/**\n * The bridge reported, on its own protocol, that it cannot start.\n *\n * Distinct from {@link WhatsAppConnectTimeoutError}, which says only that nothing arrived in\n * time. This one carries what the bridge said — and, when it could classify itself, a\n * machine-readable `code` such as `peer_missing`, `peer_incompatible` or `peer_load_failed`.\n * The difference matters to a caller: a timeout may be worth retrying, and a peer dependency\n * that does not export what we need never will be.\n *\n * @public\n */\nexport class WhatsAppBridgeError extends Error {\n override readonly name = \"WhatsAppBridgeError\";\n /** Cause as named by the bridge, when it could name one. */\n readonly code: string | undefined;\n\n constructor(message: string, code?: string) {\n super(`WhatsApp web bridge could not start: ${message}`);\n this.code = code;\n }\n}\n\n/** Custom error: `connect()` timed out waiting for \"ready\" (EC-6). */\nexport class WhatsAppConnectTimeoutError extends Error {\n constructor(timeoutMs: number) {\n super(`WhatsApp web bridge connect timed out after ${timeoutMs}ms (QR code not scanned?)`);\n this.name = \"WhatsAppConnectTimeoutError\";\n }\n}\n\n/**\n * Meta's published error codes, by consequence for the caller.\n *\n * These are six-digit codes, and the mapper used to test `errCode === 130 || errCode === 131`\n * — a condition no Cloud API response can satisfy. The rate-limit branch was dead, every real\n * throttle arrived as `invalid_request`, and a consumer's backoff never fired (#46). The unit\n * test that claimed to cover it passed on the HTTP status while feeding a fabricated code.\n *\n * Numbers verified against Meta's error-code table rather than recalled.\n */\nconst RATE_LIMIT_CODES = new Set([\n 4, // the app reached its API call rate limit\n 80007, // the WhatsApp Business Account reached its rate limit\n 130429, // Cloud API message throughput reached\n]);\nconst UNDELIVERABLE_CODES = new Set([\n 130403, // the business has blocked this user\n 131026, // no WhatsApp account, terms not accepted, or an outdated client\n]);\n/** More than 24h since the recipient last replied. Remedy: resend as a template. */\nconst SESSION_WINDOW_EXPIRED_CODE = 131047;\n/**\n * The recipient was never registered against this number. Remedy: a console step, not a payload.\n *\n * Its own code for the same reason 131047 has one — the remedy is specific and different from\n * every other error here. And it is the error most Cloud API integrations meet first: every app\n * starts on a free test number whose recipients must be registered one by one, so a developer\n * whose payload is correct gets told `invalid_request` and goes to re-read the payload.\n */\nconst RECIPIENT_NOT_ALLOWLISTED_CODE = 131030;\n\n/**\n * Which canonical code this failure is, derived from Meta's status and error number.\n *\n * The return type is `WhatsAppError[\"code\"]` rather than a hand-listed union. It WAS hand-listed,\n * and a review caught that: the commit extracting `WhatsAppError` claimed to have removed the\n * second declaration that would \"drift the moment somebody adds a code to one of them\", and left\n * this one — already drifted, missing `timeout`. One vocabulary, one declaration.\n */\nfunction cloudErrorCode(status: number, errCode: number): WhatsAppError[\"code\"] {\n if (errCode === 190 || status === 401) return \"auth_failed\";\n if (RATE_LIMIT_CODES.has(errCode) || status === 429) return \"rate_limit\";\n // Ordered before the generic 400 branch: all three arrive as HTTP 400, and the\n // specific code is the only thing separating \"fix your payload\" from \"send a\n // template\" and from \"this recipient will never receive it\".\n if (errCode === SESSION_WINDOW_EXPIRED_CODE) return \"session_window_expired\";\n if (errCode === RECIPIENT_NOT_ALLOWLISTED_CODE) return \"recipient_not_allowlisted\";\n if (UNDELIVERABLE_CODES.has(errCode)) return \"undeliverable\";\n if (status === 400 || errCode === 100) return \"invalid_request\";\n if (status >= 500) return \"server_error\";\n return \"unknown\";\n}\n\n/**\n * Map a Cloud API HTTP failure into the canonical `{ code, message }` payload.\n *\n * Takes the status alongside the body because Meta returns the same envelope shape for very\n * different faults, and the status is what separates a rejected payload from an expired token.\n */\nexport function mapWhatsAppCloudError(status: number, body: unknown): ErrorPayload {\n const parsed = (body !== null && typeof body === \"object\" ? body : {}) as MetaErrorBody;\n const errCode = parsed.error?.code ?? 0;\n const errMsg = parsed.error?.message ?? `HTTP ${status}`;\n const code = cloudErrorCode(status, errCode);\n if (code === \"auth_failed\") return { code, message: `Bearer token rejected: ${errMsg}` };\n if (code === \"rate_limit\") return { code, message: `Throttled: ${errMsg}` };\n if (code === \"recipient_not_allowlisted\") {\n // The remedy travels with the error, like its sibling above. Naming where the list lives is\n // the difference between a one-minute fix and an afternoon spent on a correct payload.\n return {\n code,\n message:\n `Recipient is not on this number's allowed list — register it under the phone number in ` +\n `the app's WhatsApp API setup before sending: ${errMsg}`,\n };\n }\n if (code === \"session_window_expired\") {\n // The remedy travels with the error. A caller reading only the code knows to\n // switch to a template; a human reading a log should not have to look it up.\n return {\n code,\n message: `Outside the 24-hour service window — send an approved template instead: ${errMsg}`,\n };\n }\n return { code, message: errMsg };\n}\n\n/**\n * Map an error string from the `whatsapp-web.js` bridge into the canonical payload.\n *\n * The bridge speaks over IPC and can only send text, so this is the boundary where a line of stderr\n * becomes a structured error. `undefined` maps to an `unknown` code rather than throwing.\n */\nexport function mapWhatsAppWebError(ipcError: string | undefined): ErrorPayload {\n const msg = ipcError ?? \"unknown bridge error\";\n if (msg.includes(\"AUTHENTICATION\") || msg.includes(\"UNAUTHORIZED\")) {\n return { code: \"auth_failed\", message: msg };\n }\n if (msg.includes(\"RATE\") || msg.includes(\"THROTTLE\")) {\n return { code: \"rate_limit\", message: msg };\n }\n if (msg.includes(\"PROTOCOL\") || msg.includes(\"DISCONNECT\")) {\n return { code: \"server_error\", message: msg };\n }\n if (msg.includes(\"TIMEOUT\")) {\n return { code: \"timeout\", message: msg };\n }\n return { code: \"unknown\", message: msg };\n}\n","/**\n * The socket contract this backend depends on, and the real factory behind it (ADR D319).\n *\n * Three members, not Baileys' whole `WASocket`. Two things follow, and both are the reason\n * the contract is ours rather than the library's.\n *\n * It was five, and two rounds of review took two members off it, both declared and called by\n * nothing. `logout()` went first and mattered most: on WhatsApp it UNPAIRS the device, the\n * opposite of what `disconnect()` means here, so the next person needing a teardown would find\n * it, call it, and lose the session the whole `sessionDir` exists to keep. `ev.off()` went for\n * the plain reason — nothing removed a listener, because a socket is discarded whole rather\n * than unsubscribed from. Neither was a capability we had; both read as one.\n *\n * **The backend is testable with `baileys` absent.** It is an optional peer dependency, so\n * CI does not install it — and a backend that could only be exercised with the real library\n * installed would be exercised by nothing, which is how the `web` backend reached production\n * unable to start (B-002).\n *\n * **The library stays an implementation detail of this file.** A breaking change upstream\n * lands in one place instead of wherever its types had spread. Depending on all of `WASocket`\n * to call three of its members is the interface-segregation problem stated plainly\n * (`rules/architecture.md`).\n *\n * @internal\n */\n\nimport { ConfigurationError } from \"../../errors.js\";\n\n/** A Baileys connection-state update, narrowed to what the lifecycle reads. */\nexport interface BaileysConnectionUpdate {\n readonly connection?: \"close\" | \"connecting\" | \"open\";\n readonly qr?: string;\n readonly lastDisconnect?: { readonly error?: unknown };\n}\n\n/** The events this backend subscribes to. Anything else Baileys emits is ignored. */\nexport interface BaileysEventMap {\n \"connection.update\": BaileysConnectionUpdate;\n \"messages.upsert\": { readonly messages: readonly unknown[]; readonly type?: string };\n \"creds.update\": unknown;\n}\n\n/**\n * What this backend needs a socket to be.\n *\n * Deliberately structural: any object with these members satisfies it, which is what lets a\n * test hand over a fake without importing anything from Baileys.\n */\nexport interface BaileysSocketLike {\n readonly ev: {\n on<K extends keyof BaileysEventMap>(\n event: K,\n listener: (payload: BaileysEventMap[K]) => void,\n ): void;\n };\n sendMessage(\n jid: string,\n content: { text: string },\n ): Promise<{ key?: { id?: string } } | undefined>;\n /**\n * Ask the server which numbers are registered, and under which JID it routes them.\n *\n * Optional because an older Baileys, or a fake in a test that predates this, may not have it.\n * When it is absent the backend sends to the number as given — the behaviour before #82 — rather\n * than refusing everything, because refusing on a missing capability would turn an upgrade\n * problem into an outage.\n */\n onWhatsApp?(...numbers: string[]): Promise<Array<{ exists?: boolean; jid?: string }> | undefined>;\n /**\n * Who this socket logged in as — present once the connection opens.\n *\n * Optional because a socket that never opened has no identity to report, and because tests\n * replace this object wholesale. The backend reads BOTH ids: the self-chat is addressed by\n * `lid`, not by `id`, so knowing only one leaves it unrecognised.\n */\n readonly user?: { readonly id?: string; readonly lid?: string };\n end?(error?: Error): void;\n}\n\n/** How a socket comes into being. Replaced wholesale in tests. */\nexport type BaileysSocketFactory = (opts: BaileysSocketOptions) => Promise<BaileysSocketLike>;\n\n/** What the real factory needs to build a socket. */\nexport interface BaileysSocketOptions {\n /** Directory holding the multi-file auth state — the pairing, persisted. */\n readonly sessionDir: string;\n /** Overrides the module the factory loads. Tests point it at a stub; production never sets it. */\n readonly specifier?: string;\n /**\n * Called with the pairing QR, as often as WhatsApp reissues it.\n *\n * Without somewhere for this to go, a fresh `sessionDir` can only ever time out: there is\n * no other way to pair, and `printQRInTerminal` is off because a library writing to stdout\n * is a library deciding where a host application's output goes. Defaults to writing the\n * code to **stderr**, which is what the `web` bridge does and what keeps stdout free for a\n * host that is using it for something.\n */\n readonly onQr?: (qr: string) => void;\n}\n\n/** Shape of the `baileys` module surface this factory uses. */\ninterface BaileysModule {\n makeWASocket?: (config: Record<string, unknown>) => BaileysSocketLike;\n default?: ((config: Record<string, unknown>) => BaileysSocketLike) | BaileysModule;\n useMultiFileAuthState?: (\n dir: string,\n ) => Promise<{ state: unknown; saveCreds: () => Promise<void> }>;\n fetchLatestBaileysVersion?: () => Promise<{ version: unknown }>;\n}\n\n/** Read a member off the default export first, then the namespace. */\nfunction member<T>(mod: BaileysModule, name: keyof BaileysModule): T | undefined {\n const asDefault = mod.default as BaileysModule | undefined;\n const fromDefault =\n asDefault !== undefined && typeof asDefault === \"object\" ? asDefault[name] : undefined;\n return (fromDefault ?? mod[name]) as T | undefined;\n}\n\n/**\n * Build a real Baileys socket.\n *\n * The import shape follows what B-002 cost this repository to learn: read the API off the\n * default export first, check each member is callable, and report a structured error naming\n * the one that is missing. A `try/catch` around the import guards the package being absent,\n * not a member being undefined — and that gap is what killed the `web` bridge for months\n * behind a friendly \"not installed\" message that was false.\n *\n * The socket settings are ADR D322, each for a stated consequence rather than a precedent:\n * `markOnlineOnConnect: false` so the account does not read as permanently online and\n * suppress push notifications on the owner's real phone; `syncFullHistory: false` so a\n * connect does not pull the entire history; an honest `browser` triple; and the protocol\n * version fetched at connect, because a stale one is refused by the server.\n */\nexport async function createBaileysSocket(opts: BaileysSocketOptions): Promise<BaileysSocketLike> {\n const specifier = opts.specifier ?? \"baileys\";\n\n let mod: BaileysModule;\n try {\n mod = (await import(/* @vite-ignore */ specifier)) as BaileysModule;\n } catch (err) {\n throw new ConfigurationError({\n code: \"peer_missing\",\n message:\n `gateway-whatsapp: ${specifier} is not installed. ` +\n \"Run `pnpm add baileys` to use the baileys backend. \" +\n `(${err instanceof Error ? err.message : String(err)})`,\n });\n }\n\n const makeSocket = member<(config: Record<string, unknown>) => BaileysSocketLike>(\n mod,\n \"makeWASocket\",\n );\n const useAuthState = member<\n (dir: string) => Promise<{ state: unknown; saveCreds: () => Promise<void> }>\n >(mod, \"useMultiFileAuthState\");\n const fetchVersion = member<() => Promise<{ version: unknown }>>(\n mod,\n \"fetchLatestBaileysVersion\",\n );\n\n for (const [name, value] of [\n [\"makeWASocket\", makeSocket],\n [\"useMultiFileAuthState\", useAuthState],\n ] as const) {\n if (typeof value !== \"function\") {\n throw new ConfigurationError({\n code: \"peer_incompatible\",\n message:\n `gateway-whatsapp: ${specifier} is installed but does not export ${name} as a function. ` +\n `Expected a function, got ${typeof value}. The baileys backend expects the peer range ` +\n \"declared in @theokit/gateway-whatsapp.\",\n });\n }\n }\n\n // Non-null after the loop above, which exits the process path on anything else.\n const { state, saveCreds } = await (\n useAuthState as (dir: string) => Promise<{ state: unknown; saveCreds: () => Promise<void> }>\n )(opts.sessionDir);\n\n // A stale protocol version is refused by the server. Absent this export we still connect;\n // Baileys then uses its bundled default, which is a worse guess but not a failure.\n const version = typeof fetchVersion === \"function\" ? (await fetchVersion()).version : undefined;\n\n const socket = (makeSocket as (config: Record<string, unknown>) => BaileysSocketLike)({\n auth: state,\n printQRInTerminal: false,\n markOnlineOnConnect: false,\n syncFullHistory: false,\n browser: [\"theokit-gateway\", \"chrome\", \"1.0.0\"],\n ...(version !== undefined ? { version } : {}),\n });\n\n // The pairing surface (F4). `printQRInTerminal` stays false — a library writing to stdout\n // decides where a host's output goes — so the code is handed to the caller, defaulting to\n // stderr. Without this a fresh session directory has no path to a pairing at all.\n const onQr =\n opts.onQr ??\n ((qr: string) => {\n process.stderr.write(\n `\\n[whatsapp-baileys] Scan this QR with WhatsApp — Settings, Linked devices, Link a device:\\n${qr}\\n\\n`,\n );\n });\n socket.ev.on(\"connection.update\", (update) => {\n if (typeof update.qr === \"string\" && update.qr.length > 0) onQr(update.qr);\n });\n\n socket.ev.on(\"creds.update\", () => {\n // Persisting credentials is what makes a pairing survive a restart. The callback is\n // sync, so the promise is deliberately floated — with a catch, because an unhandled\n // rejection here would end the process (the defect fixed across the adapters in #41).\n void saveCreds().catch((err: unknown) => {\n const message = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[whatsapp-baileys] could not persist credentials: ${message}\\n`);\n });\n });\n\n return socket;\n}\n","/**\n * `WhatsAppBaileysBackend` — the third implementation of `WhatsAppBackend` (B-001).\n *\n * Baileys speaks the WhatsApp Web multi-device protocol over a WebSocket, with no browser.\n * That is the whole difference from the `web` backend, which drives a headless Chromium.\n *\n * **Unofficial, and no amount of code changes that.** It automates a WhatsApp Web session,\n * which Meta's terms do not sanction and which can get a number banned. Use a number created\n * for this, never a personal one. Prefer {@link WhatsAppCloudBackend} unless the number has\n * no Cloud API access.\n *\n * **Added rather than replacing**, for three reasons that a substitution would not give:\n * nobody loses a paired session (a Puppeteer profile and a multi-file auth state are not\n * interchangeable), the comparison against the incumbent becomes measurable rather than\n * asserted, and retreat stays cheap because nobody is forced onto it.\n *\n * @public\n */\n\nimport { normalizeWhatsAppId } from \"../../allowlist.js\";\nimport type {\n WhatsAppBackend,\n WhatsAppInboundEvent,\n WhatsAppOutboundMessage,\n WhatsAppSendResult,\n WhatsAppStatusReceipt,\n} from \"../../backend-types.js\";\nimport { normalizeBaileysMessage } from \"./normalize.js\";\nimport {\n type BaileysSocketFactory,\n type BaileysSocketLike,\n createBaileysSocket,\n} from \"./socket.js\";\n\n/**\n * Close a socket without caring whether it was already gone.\n *\n * Tearing down something that has already closed is not a failure worth reporting: the\n * caller asked for it closed, and it is closed.\n */\nfunction endQuietly(socket: BaileysSocketLike): void {\n try {\n socket.end?.();\n } catch {\n // Deliberately empty — see the docblock.\n }\n}\n\n/** How long to wait for the socket to report `open` before giving up. */\nconst DEFAULT_CONNECT_TIMEOUT_MS = 60_000;\n/** How long to wait for one send to be acknowledged. */\nconst DEFAULT_SEND_TIMEOUT_MS = 30_000;\n\n/**\n * The answer \"WhatsApp routes this to nobody\", carried through the send chain.\n *\n * A sentinel rather than `undefined` because `sendMessage` itself resolves to `undefined` for an\n * acknowledgement with no id, and the two mean opposite things: one is a message that went out\n * without a wamid, the other is a message that was never sent.\n */\nconst UNROUTABLE = \"__unroutable__\" as const;\n\n/**\n * What one send attempt resolves to before the timeout race: the socket's acknowledgement, an\n * acknowledgement with no id, or the recipient having no route at all.\n */\ntype SendOutcome = { key?: { id?: string } } | undefined | typeof UNROUTABLE;\n/**\n * How many of our own message ids to keep, as an echo guard.\n *\n * A window rather than a log: WhatsApp delivers our own message back within seconds or not at\n * all, so recognising one from an hour ago buys nothing and an unbounded set on a long-lived\n * socket is a leak.\n */\nconst SENT_WAMID_WINDOW = 256;\n\n/**\n * What the pairing is doing, for a caller that must ASK rather than be told.\n *\n * {@link WhatsAppBaileysBackendOptions.onQr} is push: it fires when WhatsApp issues a code, at a\n * moment the caller does not choose. A screen is pull — it loads when someone opens it and has to\n * ask what is true right now. With only the callback, showing a QR anywhere means every consumer\n * keeping its own copy of the latest code and its own notion of whether pairing already succeeded,\n * which is this backend's bookkeeping copied into each of them.\n *\n * @public\n */\nexport interface WhatsAppPairingState {\n /**\n * `idle` before `connect()`, `awaiting_scan` while a code is outstanding, `connected` once the\n * socket opens, `closed` when it dies without a scan.\n */\n readonly status: \"idle\" | \"awaiting_scan\" | \"connected\" | \"closed\";\n /**\n * The most recent code, present only while `awaiting_scan`.\n *\n * WhatsApp reissues roughly every 20 seconds and the previous one stops working, so a screen\n * holding the old square shows something that cannot be scanned. It is cleared on `connected`\n * and on `closed` for the same reason: offering a code that leads nowhere is worse than\n * offering none.\n */\n readonly qr?: string;\n /** When that code arrived, so a UI can show its age instead of a stale square. */\n readonly qrAt?: number;\n}\n\n/** Construction options. @public */\nexport interface WhatsAppBaileysBackendOptions {\n /**\n * Directory holding the multi-file auth state — the pairing, persisted.\n *\n * Treat it like a credential: it is the session, and anyone holding it is the account.\n */\n readonly sessionDir: string;\n /** Give up on `connect()` after this long. Default 60s. */\n readonly connectTimeoutMs?: number;\n /** Give up on one send after this long. Default 30s. */\n readonly sendTimeoutMs?: number;\n /** Test seam: build the socket some other way. Production leaves it unset. */\n readonly socketFactory?: BaileysSocketFactory;\n /**\n * Where the pairing QR goes, as often as WhatsApp reissues it.\n *\n * **QR IS THE ONLY WAY IN.** Baileys exposes `requestPairingCode`, and WhatsApp refuses the codes\n * this backend asks for — measured 2026-08-30 across three attempts, on both the 12- and 13-digit\n * forms of a Brazilian number. The reference implementation of this same transport documents the\n * same conclusion in one line (\"Login is QR-only\") while sending a custom `browser` triple exactly\n * as this one does, so the triple is NOT established as the cause and no cause is claimed here.\n * What is established is the outcome: a caller with no route to display a QR has no route to pair.\n *\n * Defaults to stderr. It is exposed here because a host that is not a terminal — a service, a\n * container, a web app — has no way to read stderr back to the person holding the phone, and\n * without a route out the QR the session can never be paired.\n */\n readonly onQr?: (qr: string) => void;\n}\n\n/**\n * A WhatsApp backend that speaks the multi-device protocol directly.\n *\n * No browser: where {@link WhatsAppWebBackend} drives a headless Chromium through\n * `whatsapp-web.js`, this holds a WebSocket. That is the whole difference in kind.\n *\n * **Unofficial, and no amount of code changes that.** It automates a WhatsApp Web session,\n * which Meta's terms do not sanction and which can get a number banned. Use a number created\n * for this and nothing else — never a personal one. Prefer the Cloud API backend unless the\n * number has no Cloud API access.\n *\n * `baileys` is an optional peer dependency, loaded lazily at connect, so a consumer who never\n * constructs this never needs it installed.\n *\n * @public\n */\nexport class WhatsAppBaileysBackend implements WhatsAppBackend {\n readonly kind = \"baileys\" as const;\n\n private socket?: BaileysSocketLike;\n private connected = false;\n /** Guards a concurrent second `connect()` from opening a second live session. */\n private connecting?: Promise<boolean>;\n /**\n * Which connection attempt is current.\n *\n * Bumped by every `connect()` and every `disconnect()`. A socket from a superseded attempt\n * checks it before touching any state, which is what stops an abandoned socket delivering\n * inbound or flipping `connected` under a live one.\n */\n private generation = 0;\n /**\n * How to end a connection attempt that is still awaiting `open`.\n *\n * Retirement by generation makes an attempt's listeners silent, which is not the same as\n * making the attempt finish. One entry per in-flight attempt; `disconnect()` calls them so\n * the attempt settles now instead of at its timeout.\n */\n private readonly pendingAttempts = new Set<() => void>();\n /**\n * Why the socket last closed, as Baileys reported it.\n *\n * Kept because `connect()` returning `false` cannot distinguish a network blip from a\n * session the operator unlinked from their phone — and only one of those is worth retrying.\n * `rules/error-handling.md` § 3: fail clear, and log with enough context to act.\n */\n private lastCloseError?: unknown;\n /** The pairing, as a caller may ask for it. Never handed out mutable. */\n private pairingState: WhatsAppPairingState = { status: \"idle\" };\n\n /**\n * The JIDs that ARE this account, normalised. Empty until a socket reports who it logged in as.\n *\n * Empty means \"not learned yet\", and `isDispatchable` reads that as refusing everything this\n * account sent — the same behaviour as before self-chat support existed. A backend that\n * guessed here would answer in a stranger's conversation.\n */\n private selfJids: ReadonlySet<string> = new Set();\n\n /**\n * Ids this backend sent, most recent last. This is what stops the agent answering itself.\n *\n * Bounded because it is a loop guard, not a log: an unbounded set on a long-lived socket is a\n * leak, and nothing needs to recognise an echo from an hour ago — WhatsApp delivers our own\n * message back within seconds or not at all.\n */\n private sentWamids = new Set<string>();\n\n /** Record one id we sent, evicting the oldest once the window is full. @internal */\n private rememberSent(wamid: string): void {\n this.sentWamids.add(wamid);\n while (this.sentWamids.size > SENT_WAMID_WINDOW) {\n const oldest = this.sentWamids.values().next();\n if (oldest.done === true) break;\n this.sentWamids.delete(oldest.value);\n }\n }\n\n /**\n * Learn which JIDs are this account, from the socket that just logged in.\n *\n * Both forms are recorded: the phone JID and the LID. The self-chat is addressed by LID —\n * measured on a real account, where a note-to-self arrived on `231116569108705@lid` while the\n * account's phone JID was `553598838687` — so recording only one leaves the self-chat\n * unrecognised and the feature silently off.\n *\n * @internal\n */\n private learnSelfJids(socket: BaileysSocketLike): void {\n const user = socket.user;\n const ids = [user?.id, user?.lid]\n .filter((id): id is string => typeof id === \"string\" && id.length > 0)\n .map((id) => normalizeWhatsAppId(id))\n .filter((id) => id.length > 0);\n this.selfJids = new Set(ids);\n if (process.env.THEOKIT_WHATSAPP_TRACE === \"1\") {\n // Whether the real library populates `user` at all is the one thing a fake socket cannot\n // answer, and an empty set here means self-notes are refused with nothing logged.\n process.stderr.write(\n `[whatsapp-baileys][trace] selfJids learned: ${ids.length === 0 ? \"(none)\" : ids.join(\", \")}\\n`,\n );\n }\n }\n private inboundHandler?: (event: WhatsAppInboundEvent) => Promise<void>;\n private statusHandler?: (receipt: WhatsAppStatusReceipt) => Promise<void>;\n /**\n * Serialises outbound sends (ADR D320).\n *\n * Both peer gateways studied do this, and one records that concurrent sends on a single\n * socket can misdeliver to the wrong chat. We have NOT measured that in our own code — we\n * have never run a Baileys socket — so this is precaution rather than a reproduction of our\n * own bug, and saying so is the point. It is kept because the cost is one promise chain and\n * the failure it guards against is a message delivered to the wrong person.\n */\n private sendQueue: Promise<unknown> = Promise.resolve();\n\n /**\n * What WhatsApp answered about each recipient, for the life of the session.\n *\n * Holds the routable JID, or {@link UNROUTABLE} for a number the server does not know. Both are\n * worth remembering: a second send to a number that does not exist should refuse as fast as the\n * first, without another round-trip.\n */\n private readonly jidCache = new Map<string, string>();\n\n constructor(private readonly opts: WhatsAppBaileysBackendOptions) {}\n\n /**\n * Open the socket and wait for it to report `open`.\n *\n * Idempotent, and safe against a concurrent second call: the in-flight promise is shared\n * rather than a second socket being built. WhatsApp's own adapter shipped without that\n * guard once and opened two live sessions.\n */\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n if (this.connecting !== undefined) return this.connecting;\n\n const attempt = this.openSocket();\n this.connecting = attempt;\n try {\n return await attempt;\n } finally {\n // Only clear what is still ours. `disconnect()` clears it too, and a later `connect()`\n // may already have installed its own — a bare assignment here would erase that one and\n // let a third caller open a parallel socket.\n if (this.connecting === attempt) this.connecting = undefined;\n }\n }\n\n /** @internal */\n private async openSocket(): Promise<boolean> {\n // Every attempt carries a generation. A socket from an abandoned attempt must not be able\n // to speak for the backend afterwards — not to deliver inbound, not to flip `connected`,\n // and not to be left running.\n const generation = ++this.generation;\n const socket = await this.buildSocket();\n const isCurrent = (): boolean => this.generation === generation;\n\n // A `disconnect()` that landed while the factory was still resolving cannot see this\n // attempt: it is not yet in `pendingAttempts` and `this.socket` is still undefined, so the\n // teardown ends nothing. The window is not theoretical — the real factory awaits a dynamic\n // import, the auth state off disk and a network round-trip for the protocol version before\n // a socket exists. Without this check, stop-then-start in that window left a live session\n // running until the connect timeout fired.\n if (!isCurrent()) {\n endQuietly(socket);\n return false;\n }\n\n this.subscribeInbound(socket, isCurrent);\n const timeoutMs = this.opts.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;\n const openedOk = await this.raceOpen(socket, isCurrent, timeoutMs);\n\n // A `disconnect()` that arrived while this was opening wins. Adopting the socket now would\n // leave `connected` true over a backend whose socket was already cleared, and every later\n // `connect()` would short-circuit on it while every `send` was refused — the\n // teardown-during-connect wedge fixed in the Slack adapter.\n if (!isCurrent()) {\n endQuietly(socket);\n return false;\n }\n\n if (!openedOk) {\n this.reportConnectFailure(timeoutMs);\n // A failed attempt must not leave a live socket behind. It would keep feeding inbound\n // into the handler, and the retry would open a SECOND live session — which on an\n // unofficial automation is ban surface, not only a leak.\n //\n // Bumping the generation is what actually silences it: `end()` asks the socket to close,\n // and a socket mid-teardown can still emit. Retiring the generation makes every listener\n // from this attempt a no-op regardless.\n this.generation += 1;\n endQuietly(socket);\n this.socket = undefined;\n this.connected = false;\n return false;\n }\n\n // Nothing should still be here, but a socket that closed and was replaced without going\n // through the close branch would be stranded by this assignment — and a stranded Baileys\n // socket is a live session, not an unreferenced object.\n if (this.socket !== undefined && this.socket !== socket) endQuietly(this.socket);\n this.socket = socket;\n this.learnSelfJids(socket);\n this.connected = true;\n return true;\n }\n\n /**\n * What the pairing is doing right now.\n *\n * Read it as often as a screen needs; it is a snapshot, not a subscription.\n */\n get pairing(): WhatsAppPairingState {\n return this.pairingState;\n }\n\n /** Build a socket through the injected factory, or the real one. @internal */\n private async buildSocket(): Promise<BaileysSocketLike> {\n const factory = this.opts.socketFactory ?? createBaileysSocket;\n return factory({\n sessionDir: this.opts.sessionDir,\n // ALWAYS supplied, even when the caller wants none: a backend that only forwards cannot\n // answer `pairing`, and the caller's own handler still runs, so wiring one costs nothing.\n onQr: (qr: string) => {\n this.pairingState = { status: \"awaiting_scan\", qr, qrAt: Date.now() };\n this.opts.onQr?.(qr);\n },\n });\n }\n\n /**\n * Trace one inbound batch BEFORE any filter, when `THEOKIT_WHATSAPP_TRACE=1`.\n *\n * Two independent filters can discard an envelope — the batch `type` here and `fromMe` inside\n * `normalizeBaileysMessage` — and from outside, both look identical: nothing happens. Telling\n * them apart by reading the code is guessing; this is how you find out which one fired.\n *\n * Deliberately content-free. A Baileys session pairs a REAL account carrying real\n * conversations, so the trace records shape (type, direction, group, has-text) and the last\n * four digits of the jid, never the message and never a full contact number.\n *\n * @internal\n */\n private traceBatch(payload: { type?: string; messages?: unknown[] }): void {\n if (process.env.THEOKIT_WHATSAPP_TRACE !== \"1\") return;\n const messages = payload.messages ?? [];\n const rows = messages.map((raw) => {\n const key = (raw as { key?: Record<string, unknown> } | undefined)?.key ?? {};\n const jid = typeof key.remoteJid === \"string\" ? key.remoteJid : \"\";\n const message = (raw as { message?: unknown } | undefined)?.message;\n return [\n `fromMe=${String(key.fromMe === true)}`,\n `jid=…${jid.replace(/\\D/g, \"\").slice(-4)}`,\n `group=${String(jid.endsWith(\"@g.us\"))}`,\n `hasMessage=${String(message !== null && message !== undefined)}`,\n ].join(\" \");\n });\n process.stderr.write(\n `[whatsapp-baileys][trace] upsert type=${payload.type ?? \"(none)\"} n=${messages.length}` +\n (rows.length === 0 ? \"\\n\" : `\\n ${rows.join(\"\\n \")}\\n`),\n );\n }\n\n /** Route this socket's inbound batches into the handler, while it is still current. @internal */\n private subscribeInbound(socket: BaileysSocketLike, isCurrent: () => boolean): void {\n socket.ev.on(\"messages.upsert\", (payload) => {\n this.traceBatch(payload as { type?: string; messages?: unknown[] });\n // A batch typed anything other than `notify` is history being replayed, not live\n // traffic. Answering replayed history is the defect #11 records in the email backend.\n if (payload.type !== undefined && payload.type !== \"notify\") return;\n if (!isCurrent()) return;\n for (const raw of payload.messages ?? []) this.dispatchInbound(raw);\n });\n }\n\n /**\n * Wait for this socket to report `open`, or for something to end the attempt.\n *\n * Three things can settle it: the socket opens, the socket closes, or the timeout fires — and\n * a fourth, `disconnect()`, reaches it through `pendingAttempts`. That last one is why the\n * resolver is registered rather than merely closed over: retiring an attempt by generation\n * makes its listeners no-ops, INCLUDING the one that would settle this, so without a way in\n * from outside the only thing left able to finish it was the timeout.\n *\n * @internal\n */\n private async raceOpen(\n socket: BaileysSocketLike,\n isCurrent: () => boolean,\n timeoutMs: number,\n ): Promise<boolean> {\n // The executor runs synchronously, so `settle` is assigned before the next statement.\n let settle: (ok: boolean) => void = () => undefined;\n const opened = new Promise<boolean>((resolve) => {\n settle = resolve;\n });\n\n const abandon = (): void => settle(false);\n this.pendingAttempts.add(abandon);\n\n socket.ev.on(\"connection.update\", (update) => {\n if (!isCurrent()) return;\n if (update.connection === \"open\") {\n // The code is dropped, not kept: a scanned QR is spent, and a UI holding it would offer\n // something that no longer pairs anything.\n this.pairingState = { status: \"connected\" };\n settle(true);\n return;\n }\n if (update.connection !== \"close\") return;\n this.lastCloseError = update.lastDisconnect?.error;\n this.connected = false;\n this.pairingState = { status: \"closed\" };\n // A closed socket is finished, and Baileys carries its own reconnect machinery: left\n // alone it keeps dialling under a backend that believes it is disconnected. Clearing the\n // reference too is what stops the next `connect()` overwriting it and stranding this one\n // beyond the reach of any later `disconnect()`.\n if (this.socket === socket) this.socket = undefined;\n endQuietly(socket);\n settle(false);\n });\n\n // Never hanging matters more than succeeding: a caller has nothing to time out against if\n // this promise simply never settles.\n const timer = setTimeout(() => settle(false), timeoutMs);\n try {\n return await opened;\n } finally {\n // The loser of the race stays scheduled otherwise, and a scheduled timer keeps Node's\n // event loop alive — the defect fixed in the core runner (#37).\n clearTimeout(timer);\n this.pendingAttempts.delete(abandon);\n }\n }\n\n /**\n * Say why the connection did not open.\n *\n * A bare `false` tells an operator nothing, and the two causes want opposite responses: a\n * blip is worth retrying, an unlinked device can only be fixed by re-pairing, and a\n * supervisor that cannot tell them apart retries forever against a dead session.\n *\n * @internal\n */\n private reportConnectFailure(timeoutMs: number): void {\n const error = this.lastCloseError;\n const cause =\n error === undefined\n ? `no 'open' within ${timeoutMs}ms`\n : error instanceof Error\n ? error.message\n : String(error);\n process.stderr.write(`[whatsapp-baileys] connect failed: ${cause}\\n`);\n }\n\n /** Close the socket. Idempotent, and safe when never connected. */\n async disconnect(): Promise<void> {\n // Bumping first is what makes an in-flight `connect()` lose: whatever it opens will see a\n // stale generation and tear itself down rather than adopting itself into a backend the\n // caller has already closed.\n this.generation += 1;\n this.connected = false;\n // Without this the guard in `connect()` hands the next caller the promise of the attempt\n // this call just doomed: it opens nothing, waits out that attempt's timeout, and returns\n // false. A supervisor doing stop-then-start reads that as an unexplained failure.\n this.connecting = undefined;\n for (const abandon of this.pendingAttempts) abandon();\n this.pendingAttempts.clear();\n const socket = this.socket;\n this.socket = undefined;\n this.inboundHandler = undefined;\n this.statusHandler = undefined;\n if (socket !== undefined) endQuietly(socket);\n }\n\n /**\n * Send one text message.\n *\n * Queued behind any send already in flight (D320), and raced against a timeout whose\n * expiry reports **undetermined** delivery rather than failure (D321). A local timeout says\n * the acknowledgement did not arrive, not that the message did not — so this never\n * retries, because a retry after a slow ack duplicates the message.\n */\n async send(message: WhatsAppOutboundMessage): Promise<WhatsAppSendResult> {\n // The queue advances on the UNDERLYING send, not on what the caller is told.\n //\n // Chaining on the raced result looked right and broke the invariant it exists to keep: a\n // timeout returns to the caller while `socket.sendMessage` is still in flight — nothing\n // cancels it — so the next send started on a socket that already had one running. That is\n // precisely the concurrent-send hazard D320 exists to prevent, reached through D321.\n let settled: Promise<unknown> = Promise.resolve();\n const run = this.sendQueue.then(\n () => {\n const attempt = this.sendNow(message);\n settled = attempt.inFlight;\n return attempt.result;\n },\n () => {\n const attempt = this.sendNow(message);\n settled = attempt.inFlight;\n return attempt.result;\n },\n );\n this.sendQueue = run.then(\n () => settled.catch(() => undefined),\n () => settled.catch(() => undefined),\n );\n return run;\n }\n\n /**\n * Race one send against the send timeout.\n *\n * Separated so `sendNow` reads as the three outcomes it has — delivered, undetermined,\n * refused — rather than as promise plumbing.\n *\n * @internal\n */\n private async raceSend(\n inFlight: Promise<SendOutcome>,\n timeoutMs: number,\n ): Promise<SendOutcome | \"timeout\"> {\n let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<\"timeout\">((resolve) => {\n timer = setTimeout(() => resolve(\"timeout\"), timeoutMs);\n });\n try {\n return await Promise.race([inFlight, timeout]);\n } finally {\n // The loser of the race stays scheduled otherwise, and a scheduled timer keeps Node's\n // event loop alive — the defect fixed in the core runner (#37).\n if (timer !== undefined) clearTimeout(timer);\n }\n }\n\n /**\n * One send attempt.\n *\n * Returns two promises deliberately. `result` is what the caller is told — it settles on\n * the timeout. `inFlight` settles when the socket is actually free again, which is what the\n * queue must wait for: a timeout does not cancel `sendMessage`, so releasing the queue on\n * the timeout would put two sends on one socket.\n *\n * @internal\n */\n private sendNow(message: WhatsAppOutboundMessage): {\n result: Promise<WhatsAppSendResult>;\n inFlight: Promise<unknown>;\n } {\n const socket = this.socket;\n if (!this.connected || socket === undefined) {\n return {\n result: Promise.resolve({\n ok: false,\n error: { code: \"not_connected\", message: \"Baileys backend is not connected.\" },\n }),\n inFlight: Promise.resolve(),\n };\n }\n\n const timeoutMs = this.opts.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS;\n\n // Resolve BEFORE sending, and let the server's answer decide the address.\n //\n // Baileys hands back a locally-generated wamid whether or not the JID routes anywhere, so\n // building one from the caller's string and reporting that id as proof of delivery loses the\n // message in silence — the caller's log, its metrics and its retry logic all record a success\n // for something nobody received (#82).\n //\n // Measured on a real account: `5535998838687` and `553598838687` are the same Brazilian line,\n // both answered `ok: true`, and only the second arrived. Asking WhatsApp which form it routes\n // to fixes the ninth digit without a Brazil-specific rule anywhere in this package — the answer\n // is whatever the server says, for any country.\n const send: Promise<SendOutcome> = this.resolveJid(socket, message).then(\n async (jid): Promise<SendOutcome> =>\n jid === undefined ? UNROUTABLE : await socket.sendMessage(jid, { text: message.text }),\n );\n\n const result = this.raceSend(send, timeoutMs)\n .then((outcome) => {\n if (outcome === UNROUTABLE) {\n return {\n ok: false,\n error: {\n code: \"undeliverable\" as const,\n message:\n `WhatsApp does not route to \"${message.to}\" — the number is not registered, or ` +\n \"not in the form this account can reach. Nothing was sent.\",\n },\n };\n }\n if (outcome === \"timeout\") {\n return {\n ok: false,\n error: {\n code: \"timeout\" as const,\n message:\n `No acknowledgement after ${timeoutMs}ms — delivery is undetermined. ` +\n \"Not retried: the message may already have been delivered.\",\n },\n };\n }\n const wamid = outcome?.key?.id;\n if (wamid !== undefined) this.rememberSent(wamid);\n return wamid !== undefined ? { ok: true, wamid } : { ok: true };\n })\n .catch((err: unknown) => ({\n ok: false,\n error: {\n code: \"server_error\" as const,\n message: err instanceof Error ? err.message : String(err),\n },\n }));\n\n return { result, inFlight: send };\n }\n\n /**\n * The JID WhatsApp routes this message to, or `undefined` when it routes to nobody.\n *\n * A group id is not a phone number and `onWhatsApp` answers about numbers, so groups pass\n * straight through — asking would refuse every group message.\n *\n * The answer is cached for the life of the session. It is a fact about a number's registration,\n * which does not change while a socket lives, and paying a round-trip per message would make\n * every send slower for something already known.\n *\n * A socket without `onWhatsApp` — an older Baileys, or a fake predating this — sends to the\n * number as given, which is the behaviour from before #82. Refusing on a missing capability\n * would turn an upgrade problem into an outage.\n */\n private async resolveJid(\n socket: BaileysSocketLike,\n message: WhatsAppOutboundMessage,\n ): Promise<string | undefined> {\n // Already an address: pass it through untouched. `channelJid` on an inbound event is exactly\n // this, and appending a domain to it produced `231116569108705@lid@s.whatsapp.net` — a string\n // that routes nowhere and reports ok (#84). Asking `onWhatsApp` about it is equally wrong: that\n // call answers about phone NUMBERS, and a LID is not one, so it would refuse a valid address.\n if (message.to.includes(\"@\")) return message.to;\n if (message.isGroup) return `${message.to}@g.us`;\n if (socket.onWhatsApp === undefined) return `${message.to}@s.whatsapp.net`;\n\n const cached = this.jidCache.get(message.to);\n if (cached !== undefined) return cached === UNROUTABLE ? undefined : cached;\n\n let answer: Array<{ exists?: boolean; jid?: string }> | undefined;\n try {\n answer = await socket.onWhatsApp(message.to);\n } catch {\n // The lookup failing is not the same as the number not existing, and refusing here would\n // turn a transient server hiccup into a permanent-looking `undeliverable`. Send as given.\n return `${message.to}@s.whatsapp.net`;\n }\n\n const entry = answer?.[0];\n if (entry?.exists !== true || entry.jid === undefined || entry.jid === \"\") {\n this.jidCache.set(message.to, UNROUTABLE);\n return undefined;\n }\n this.jidCache.set(message.to, entry.jid);\n return entry.jid;\n }\n\n /** Subscribe to inbound events. EC-H: a second call REPLACES the first. */\n onInbound(handler: (event: WhatsAppInboundEvent) => Promise<void>): () => void {\n this.inboundHandler = handler;\n return () => {\n if (this.inboundHandler === handler) this.inboundHandler = undefined;\n };\n }\n\n /**\n * Subscribe to delivery receipts. EC-H: a second call REPLACES the first.\n *\n * Declared for the interface; Baileys reports receipts on `messages.update`, which v1 does\n * not consume. Registering a handler is accepted and it is never called — stated here\n * rather than left for a consumer to discover from silence.\n */\n onStatusReceipt(handler: (receipt: WhatsAppStatusReceipt) => Promise<void>): () => void {\n this.statusHandler = handler;\n return () => {\n if (this.statusHandler === handler) this.statusHandler = undefined;\n };\n }\n\n /**\n * Normalise one envelope and hand it to the handler.\n *\n * The promise is floated because the Baileys listener is synchronous — but with a `catch`,\n * because a bare `void` on a rejecting promise ends the process under Node's default, which\n * is what killed two adapters in this package (#41). A handler is user code; its failure is\n * named as the handler's and delivery continues.\n *\n * @internal\n */\n private dispatchInbound(raw: unknown): void {\n const handler = this.inboundHandler;\n if (handler === undefined) return;\n const event = normalizeBaileysMessage(raw, {\n selfJids: this.selfJids,\n sentWamids: this.sentWamids,\n });\n if (event === undefined) return;\n void handler(event).catch((err: unknown) => {\n const message = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[whatsapp-baileys] handler threw: ${message}\\n`);\n });\n }\n}\n","/**\n * Does an inbound WhatsApp message reach the agent, and as what?\n *\n * The addressed-number check, the sender allowlist, the group-mention rule and the conversion to\n * the gateway's event shape, as functions of their inputs (the only state is the set of foreign\n * numbers already reported, which the caller owns). `WhatsAppAdapter` holds the configuration and\n * passes it in; every adapter path that decides an inbound message goes through\n * `decideForOwnNumber` (own-number.ts), which calls `isForAnotherNumber` (foreign-number.ts) and\n * `decideInbound`, so there is one rule set to keep.\n */\n\nimport type { WhatsAppMessageEvent } from \"@theokit/gateway\";\n\nimport { isSenderAllowed } from \"./allowlist.js\";\nimport type { WhatsAppInboundEvent } from \"./backend-types.js\";\n\n/** The configuration the inbound rules read, held by the adapter. */\nexport interface InboundRules {\n /** `undefined` = no allowlist configured; a set = configured, and enforced fail-closed. */\n readonly allowedSenders: ReadonlySet<string> | undefined;\n /** Drop a group message that does not mention the bot. */\n readonly requireMention: boolean;\n /** The bot's number, digits only; `\"\"` when unset. */\n readonly botPhoneId: string;\n}\n\n/** EC-7: digit-only normalizer for mention comparison (handles `+`, `-`, `()`, spaces). */\nexport function digitsOnly(s: string): string {\n return s.replace(/[^\\d]/g, \"\");\n}\n\n/**\n * Characters that may appear INSIDE a written phone number: digits and the\n * separators people type around them. Anything else — a letter, a comma, a\n * newline — ends the run.\n */\nconst PHONE_RUN = /[\\d][\\d+\\-(). ]*[\\d]|[\\d]/g;\n\n/**\n * EC-7: the phone-like runs in a message, each normalized to digits.\n *\n * The filter used to normalize the WHOLE message and ask whether the result\n * contained the bot's number. That accepts the four documented formats, but it\n * also concatenates digits from unrelated words: with a bot at 5511999999999,\n * `\"pedido 55 chegou 11, ref 99999-9999 ok\"` normalized to a string containing\n * exactly that number, and the bot answered a message about an order. Every\n * group message carrying scattered digits woke it.\n *\n * Scanning runs instead keeps the separators irrelevant WITHIN a number — which\n * is what EC-7 asks for, and what `\"+55 (11) 99999-9999\"` needs — while letting\n * a letter or a comma do what it visually does: end the number.\n */\nfunction phoneRuns(s: string): string[] {\n // Every match starts and ends with a digit, so no run normalizes to \"\".\n return (s.match(PHONE_RUN) ?? []).map(digitsOnly);\n}\n\n/**\n * Is this sender refused by a configured allowlist?\n *\n * Runs before the group/mention filter because it answers a different question: that one asks\n * whether a message was meant for us, this one asks whether the sender may reach us at all.\n *\n * The refusal is logged, with the sender's address reduced to its last four digits. A silent drop\n * is indistinguishable from a broken gateway, and the first thing a mistyped allowlist causes is\n * an operator wondering why the bot went mute.\n */\nfunction isRefusedBySenderAllowlist(\n inbound: WhatsAppInboundEvent,\n allowedSenders: ReadonlySet<string> | undefined,\n): boolean {\n // The allowlist answers \"may this STRANGER reach the agent?\", and the account owner writing\n // in their own self-chat is not one. It also cannot answer it here: the self-chat reports the\n // account's LID as the sender, while an operator writes a phone number — measured on a real\n // paired session. Reading the flag rather than the address keeps the exemption tied to the\n // backend's own decision, so a stranger arriving on a LID is still refused.\n if (inbound.fromSelf === true) return false;\n if (allowedSenders === undefined) return false;\n if (isSenderAllowed(inbound.fromPhone, allowedSenders)) return false;\n process.stderr.write(\n `[whatsapp] dropped inbound from ${redactedSender(inbound.fromPhone)}: not in the configured allowlist\\n`,\n );\n return true;\n}\n\n/**\n * A refused sender as the log names it: the last four digits of the address, enough to match a\n * mistyped allowlist entry by eye. The full number is personal data of someone who never agreed\n * to reach this bot, and every unsolicited message would otherwise write it to the host's logs.\n */\nfunction redactedSender(fromPhone: string): string {\n const tail = lastFourDigits(fromPhone);\n return tail.length > 0 ? `a sender ending in ${tail}` : \"a sender with no number\";\n}\n\n/** The last four digits of `value`, `\"\"` when it has none. Every other character is dropped. */\nexport function lastFourDigits(value: string): string {\n return digitsOnly(value).slice(-4);\n}\n\n/** D309 + EC-7: group filter with digit-only normalization. */\nfunction shouldDropGroupMessage(\n inbound: WhatsAppInboundEvent,\n requireMention: boolean,\n botPhoneId: string,\n): boolean {\n if (inbound.conversationType !== \"group\" || !requireMention) return false;\n if (botPhoneId.length === 0) {\n // Misconfigured: with no id to look for, every group message looks unaddressed. Saying\n // so matters more here than anywhere: the allowlist check above (isRefusedBySenderAllowlist)\n // makes the same point, and a gateway that answers no group message and explains nothing\n // is indistinguishable from a broken one. Common with `fromWeb`, which has no phone\n // number id to default from.\n process.stderr.write(\n \"[whatsapp] dropping every group message: requireMention is on and botPhoneId is unset\\n\",\n );\n return true;\n }\n return !phoneRuns(inbound.text).some((run) => run.includes(botPhoneId));\n}\n\nfunction toMessageEvent(inbound: WhatsAppInboundEvent): WhatsAppMessageEvent {\n return {\n id: inbound.wamid,\n platform: \"whatsapp\",\n sender: { id: inbound.fromPhone, displayName: inbound.contactName },\n channel: { id: inbound.channelId, type: inbound.conversationType },\n text: inbound.text,\n receivedAt: inbound.receivedAt,\n whatsapp: {\n wamid: inbound.wamid,\n phoneNumberId: inbound.phoneNumberId,\n contactName: inbound.contactName,\n channelJid: inbound.channelJid,\n backend: inbound.backend,\n raw: inbound.raw,\n },\n };\n}\n\n/**\n * Decide one inbound message: the event the agent receives, or `undefined` when a rule drops it.\n *\n * The allowlist runs first, then the group rule, then the conversion, so a refused sender is\n * named once and never reaches the group logging. A drop writes its reason to stderr.\n */\nexport function decideInbound(\n inbound: WhatsAppInboundEvent,\n rules: InboundRules,\n): WhatsAppMessageEvent | undefined {\n if (isRefusedBySenderAllowlist(inbound, rules.allowedSenders)) return undefined;\n if (shouldDropGroupMessage(inbound, rules.requireMention, rules.botPhoneId)) return undefined;\n return toMessageEvent(inbound);\n}\n","/**\n * Multi-number scoping: is an inbound message, or status receipt, addressed to another Cloud number?\n *\n * Kept apart from inbound-rules.ts (the sender rules) because it answers a different question.\n * `WhatsAppCloudBackend.handleWebhookPayload` and the adapter both call it, so a route built on\n * the backend alone is scoped to its number too.\n */\n\nimport type { WhatsAppInboundEvent, WhatsAppStatusReceipt } from \"./backend-types.js\";\nimport { lastFourDigits } from \"./inbound-rules.js\";\n\n/**\n * A foreign phone number id as the log names it, cut the way `redactedSender` cuts a sender: its\n * last four digits. The id comes from an envelope, and `toDeliverableEvents` does not verify the\n * signature, so a route that skips verification hands this function text anyone wrote. Keeping\n * digits only means no newline or quote reaches stderr.\n */\nfunction redactedNumberId(phoneNumberId: string | undefined): string {\n if (phoneNumberId === undefined) return \"no phone number id\";\n const tail = lastFourDigits(phoneNumberId);\n return tail.length > 0\n ? `a phone number id ending in ${tail}`\n : \"a phone number id with no digits\";\n}\n\n/**\n * Is this message, or status receipt, addressed to a Cloud number other than `ownPhoneNumberId`?\n *\n * Meta signs every number of one app with one secret, so a valid signature does not say which\n * number an envelope was for. `undefined` means the adapter has no Cloud number to compare, and\n * nothing is dropped. A message with no phone number id is not provably this number's, and is\n * dropped too.\n *\n * The foreign id reaches stderr only as its last four digits (see `redactedNumberId`), once per\n * label: `reported` holds the labels already written, and this function adds to it. Keyed by the\n * label rather than the raw id, the set is bounded: 10,000 endings plus the two labels for an id\n * with no digit and for no id, however many distinct ids an unverified caller sends. Two foreign\n * ids sharing an ending are named once, which is the cost of that bound.\n */\nexport function isForAnotherNumber(\n inbound: Pick<WhatsAppInboundEvent | WhatsAppStatusReceipt, \"phoneNumberId\">,\n ownPhoneNumberId: string | undefined,\n reported: Set<string>,\n): boolean {\n if (ownPhoneNumberId === undefined || inbound.phoneNumberId === ownPhoneNumberId) return false;\n const other = redactedNumberId(inbound.phoneNumberId);\n if (!reported.has(other)) {\n reported.add(other);\n process.stderr.write(\n `[whatsapp] dropped inbound addressed to ${other}: this adapter answers for \"${ownPhoneNumberId}\". Logged once per id ending.\\n`,\n );\n }\n return true;\n}\n","/**\n * `WhatsAppCloudClient` — typed `fetch` wrapper for Meta WhatsApp Business\n * Cloud API (ADR D304). No Meta SDK; we own the wire.\n *\n * @internal\n */\n\nimport type { WhatsAppCredentialCheck, WhatsAppSendResult } from \"../../backend-types.js\";\nimport { mapWhatsAppCloudError } from \"../../errors.js\";\nimport type {\n MetaErrorEnvelope,\n MetaMarkReadRequest,\n MetaSendResponse,\n MetaSendTemplateRequest,\n MetaSendTextRequest,\n MetaTemplateComponent,\n} from \"./types.js\";\n\ninterface WhatsAppCloudClientOptions {\n readonly accessToken: string;\n readonly phoneNumberId: string;\n readonly apiVersion?: string;\n /** Test seam. */\n readonly fetch?: typeof fetch;\n}\n\nexport class WhatsAppCloudClient {\n private readonly fetchImpl: typeof fetch;\n private readonly baseUrl: string;\n\n constructor(private readonly opts: WhatsAppCloudClientOptions) {\n this.fetchImpl = opts.fetch ?? fetch;\n const apiVersion = opts.apiVersion ?? \"v18.0\";\n this.baseUrl = `https://graph.facebook.com/${apiVersion}/${opts.phoneNumberId}`;\n }\n\n /** Send a text message. v1 scope — no media (D286 deferred). */\n async sendText(to: string, body: string, isGroup: boolean): Promise<WhatsAppSendResult> {\n const req: MetaSendTextRequest = isGroup\n ? {\n messaging_product: \"whatsapp\",\n to,\n type: \"text\",\n text: { body, preview_url: false },\n }\n : {\n messaging_product: \"whatsapp\",\n recipient_type: \"individual\",\n to,\n type: \"text\",\n text: { body, preview_url: false },\n };\n\n return this.postMessage(req);\n }\n\n /**\n * Send an approved template.\n *\n * The only message type Meta accepts outside the 24-hour service window, and so the only way to\n * reach someone who has not written first — every notification, and every unattended check of\n * whether this integration still works. Free-form text to a cold recipient is refused with\n * `131047`, which the error mapper now surfaces as `session_window_expired`.\n *\n * `components` is omitted from the payload when absent rather than sent empty: Meta rejects\n * `components: []` on a template that declares no variables, so the two are not equivalent.\n *\n * Deliberately NOT on the `WhatsAppBackend` interface. The web backend drives WhatsApp Web,\n * which has no concept of templates, and widening the shared contract would hand it a method it\n * can only throw from.\n */\n async sendTemplate(\n to: string,\n templateName: string,\n languageCode: string,\n components?: ReadonlyArray<MetaTemplateComponent>,\n ): Promise<WhatsAppSendResult> {\n const req: MetaSendTemplateRequest = {\n messaging_product: \"whatsapp\",\n recipient_type: \"individual\",\n to,\n type: \"template\",\n template: {\n name: templateName,\n language: { code: languageCode },\n ...(components !== undefined && components.length > 0 ? { components } : {}),\n },\n };\n return this.postMessage(req);\n }\n\n /**\n * Ask Meta whether this credential can actually act as this phone number.\n *\n * `connect()` used to answer that question with `return true`, so a wrong, expired or revoked\n * token reported success at startup and surfaced as messages that silently never arrived —\n * the worst failure mode a gateway has, because there is nothing in a log to see. The first\n * live run of the WhatsApp suite caught it (#58); 209 unit tests could not, because a fake\n * backend always accepts.\n *\n * It reads the phone number itself rather than `/me`, and that choice is the point: a token\n * can be perfectly valid and still have no access to THIS phone number id, which is the\n * likelier misconfiguration of the two. Checking only the token would wave it through.\n *\n * Returns a result rather than a boolean, and never throws — `connect()` is specified to\n * return false rather than throw, and the reason has to survive the trip: `auth_failed` and\n * `rate_limit` ask a supervisor for opposite responses.\n */\n async verifyCredentials(): Promise<WhatsAppCredentialCheck> {\n let response: Response;\n try {\n response = await this.fetchImpl(this.baseUrl, {\n method: \"GET\",\n headers: { authorization: `Bearer ${this.opts.accessToken}` },\n });\n } catch (cause) {\n return {\n ok: false,\n error: {\n code: \"server_error\",\n message: `Network error: ${cause instanceof Error ? cause.message : String(cause)}`,\n },\n };\n }\n\n const body = (await response.json().catch(() => undefined)) as\n | (MetaErrorEnvelope & { id?: unknown })\n | undefined;\n\n if (!response.ok) {\n return { ok: false, error: mapWhatsAppCloudError(response.status, body ?? {}) };\n }\n // A 200 is not a yes. Meta answers some failures with an error envelope under a 200, and a\n // captive portal or proxy answers everything with one — so the status line is the weakest\n // evidence in the response.\n // `null`, an array, a string and a number are all valid JSON and none of them is a node\n // description. `response.json()` resolves `null` for the literal, which is neither\n // `undefined` nor an object — the undefined-only guard let it through and the next line\n // dereferenced it, so a proxy answering `null` made `connect()` THROW. That is precisely the\n // clause this method is written to uphold.\n if (body === null || typeof body !== \"object\" || Array.isArray(body)) {\n return {\n ok: false,\n error: {\n code: \"unknown\",\n message: `Meta answered ${response.status} with a body this client could not read.`,\n },\n };\n }\n if (body.error !== undefined) {\n return { ok: false, error: mapWhatsAppCloudError(response.status, body) };\n }\n // IDENTITY, not access — the distinction this method exists for, and the one its first\n // version claimed while checking only the other. `GET /{waba_id}` with a management-scoped\n // token also answers 200, so pasting the WABA id where the phone number id belongs sails\n // through an access check and fails on every send afterwards. It is the likeliest\n // misconfiguration in Cloud API setup, and the response names the node it actually reached.\n // Compared as strings: Graph returns ids as strings, but a numeric one under strict `!==`\n // produced \"resolves to node 12345, not the configured phoneNumberId 12345\" — a refusal that\n // contradicts itself and sends someone hunting a mixup its own text rules out.\n if (String(body.id) !== this.opts.phoneNumberId) {\n return {\n ok: false,\n error: {\n code: \"invalid_request\",\n message:\n `Credential is valid but resolves to node ${String(body.id)}, not the configured ` +\n `phoneNumberId ${this.opts.phoneNumberId}. A WhatsApp Business Account id in place ` +\n `of a phone number id looks exactly like this.`,\n },\n };\n }\n return { ok: true };\n }\n\n /**\n * POST one message envelope and turn Meta's answer into a `WhatsAppSendResult`.\n *\n * Shared by every send: how to reach the endpoint, how to authenticate, and how to read the\n * reply is one piece of knowledge, and it was about to have a second copy.\n */\n private async postMessage(\n req: MetaSendTextRequest | MetaSendTemplateRequest,\n ): Promise<WhatsAppSendResult> {\n let response: Response;\n try {\n response = await this.fetchImpl(`${this.baseUrl}/messages`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n authorization: `Bearer ${this.opts.accessToken}`,\n },\n body: JSON.stringify(req),\n });\n } catch (cause) {\n return {\n ok: false,\n error: {\n code: \"server_error\",\n message: `Network error: ${cause instanceof Error ? cause.message : String(cause)}`,\n },\n };\n }\n\n if (!response.ok) {\n const errBody = (await response.json().catch(() => ({}))) as MetaErrorEnvelope | unknown;\n return { ok: false, error: mapWhatsAppCloudError(response.status, errBody) };\n }\n\n const data = (await response.json()) as MetaSendResponse;\n const wamid = data.messages?.[0]?.id;\n if (wamid === undefined) {\n return { ok: false, error: { code: \"unknown\", message: \"Meta returned no wamid.\" } };\n }\n return { ok: true, wamid };\n }\n\n /** Mark an inbound message as read (status receipt back to user). */\n async markAsRead(wamid: string): Promise<boolean> {\n const body: MetaMarkReadRequest = {\n messaging_product: \"whatsapp\",\n status: \"read\",\n message_id: wamid,\n };\n try {\n const response = await this.fetchImpl(`${this.baseUrl}/messages`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n authorization: `Bearer ${this.opts.accessToken}`,\n },\n body: JSON.stringify(body),\n });\n return response.ok;\n } catch {\n return false;\n }\n }\n}\n","/**\n * Meta's `X-Hub-Signature-256` check for a Cloud webhook body (ADR D312).\n *\n * Its own module, apart from the envelope normalizers in `webhook.ts`, because this is the line\n * between a signed webhook and anyone's POST, and mutation testing measures it file by file.\n *\n * @public\n */\n\nimport * as crypto from \"node:crypto\";\n\nimport { ConfigurationError } from \"../../errors.js\";\n\n/**\n * Verify the `X-Hub-Signature-256` HMAC-SHA256 against the app secret (D312).\n *\n * EC-3 absorbed: length-guard BEFORE `timingSafeEqual` so a malformed header\n * (e.g. `sha256=ab`) returns `false` instead of throwing `RangeError` (DoS).\n *\n * An empty or whitespace-only `appSecret` throws rather than answering: an HMAC under an empty\n * key is computable by anyone, so a match would prove nothing about Meta. `fromCloud` accepts an\n * empty secret for an adapter that only sends; such an adapter cannot verify a webhook.\n *\n * @returns `true` iff the signature matches.\n * @throws {ConfigurationError} `missing_option` when `appSecret` is empty or whitespace only.\n */\nexport function verifyWebhookSignature(\n rawBody: Buffer | string,\n signatureHeader: string | undefined,\n appSecret: string,\n): boolean {\n if (appSecret.trim().length === 0) {\n throw new ConfigurationError({\n code: \"missing_option\",\n message:\n \"gateway-whatsapp: appSecret is required to verify a webhook signature and must not be empty; an HMAC under an empty key is computable by anyone.\",\n });\n }\n if (signatureHeader === undefined) return false;\n if (!signatureHeader.startsWith(\"sha256=\")) return false;\n const receivedHex = signatureHeader.slice(7);\n if (!/^[0-9a-f]+$/i.test(receivedHex)) return false;\n const received = Buffer.from(receivedHex, \"hex\");\n // `update` reads a string as UTF-8 and a Buffer as its bytes, which is what Meta signed.\n const expected = crypto.createHmac(\"sha256\", appSecret).update(rawBody).digest();\n // EC-3: length guard before timingSafeEqual.\n if (received.length !== expected.length) return false;\n return crypto.timingSafeEqual(received, expected);\n}\n","/**\n * Webhook helpers for Meta WhatsApp Business Cloud API (ADR D306, D312).\n *\n * Two boundaries:\n * 1. GET handshake — `verifyWebhookSubscription` (EC-1).\n * 2. POST callbacks — `verifyWebhookSignature` (EC-3 length guard) +\n * `normalizeInboundMessages` (EC-4 text-only filter) +\n * `normalizeStatusReceipts`.\n *\n * The user owns the HTTP route; we expose pure helpers they call from inside it.\n *\n * @public\n */\n\nimport type { WhatsAppInboundEvent, WhatsAppStatusReceipt } from \"../../backend-types.js\";\nimport type { MetaIncomingMessage, MetaStatusUpdate, MetaWebhookEnvelope } from \"./types.js\";\n\n/**\n * The Meta message types a log line may name. Anything else, including a type a forged envelope\n * made up, is named \"an unknown type\".\n */\nconst KNOWN_NON_TEXT_TYPES: ReadonlySet<string> = new Set([\n \"audio\",\n \"button\",\n \"contacts\",\n \"document\",\n \"image\",\n \"interactive\",\n \"location\",\n \"order\",\n \"reaction\",\n \"request_welcome\",\n \"sticker\",\n \"system\",\n \"unsupported\",\n \"video\",\n]);\n\n/**\n * Labels already written to stderr. Keyed by `nonTextTypeLabel`, not by the raw type, so it holds\n * at most one entry per known type plus one for \"an unknown type\".\n */\nconst warnedNonTextTypes = new Set<string>();\n\n/**\n * A non-text message type as the log names it. `msg.type` comes from the envelope, and\n * `toDeliverableEvents` does not verify the signature, so the raw value is text anyone wrote: it\n * could carry a newline that forges a log line. Only a type from a fixed list is named.\n */\nfunction nonTextTypeLabel(type: unknown): string {\n return typeof type === \"string\" && KNOWN_NON_TEXT_TYPES.has(type) ? type : \"an unknown type\";\n}\n\n/**\n * Verify Meta's GET `/webhook?hub.mode=subscribe&hub.challenge=...&hub.verify_token=...`\n * handshake (EC-1 absorbed).\n *\n * @returns `query[\"hub.challenge\"]` when valid, `null` otherwise. The caller\n * echoes the challenge as `text/plain` on success.\n */\nexport function verifyWebhookSubscription(\n query: Record<string, string | undefined>,\n expectedVerifyToken: string,\n): string | null {\n const mode = query[\"hub.mode\"];\n const token = query[\"hub.verify_token\"];\n const challenge = query[\"hub.challenge\"];\n if (mode !== \"subscribe\") return null;\n if (token === undefined || token !== expectedVerifyToken) return null;\n if (challenge === undefined || challenge.length === 0) return null;\n return challenge;\n}\n\n// The signature check lives in its own module so mutation testing can measure it without the\n// normalizers below (see tests/MUTATION.md); it is re-exported so the import path is unchanged.\nexport { verifyWebhookSignature } from \"./signature.js\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\";\n}\n\n/** Absent, or an array whose every item is an object: what the normalizers iterate. */\nfunction isOptionalRecordArray(value: unknown): boolean {\n return value === undefined || (Array.isArray(value) && value.every(isRecord));\n}\n\n/**\n * `metadata`: absent, or an object whose `phone_number_id` is absent or a string. The inbound rules\n * compare and redact that id with string methods, so a number or `null` there would throw past the\n * boundary.\n */\nfunction isWellFormedMetadata(metadata: unknown): boolean {\n if (metadata === undefined || metadata === null) return true;\n if (!isRecord(metadata)) return false;\n return metadata.phone_number_id === undefined || typeof metadata.phone_number_id === \"string\";\n}\n\n/**\n * A text message's fields the normalizer and the inbound rules read: `id` and `from` are strings,\n * and `text` is absent or carries a string `body`. Other types are dropped before any field is read.\n */\nfunction isReadableMessage(message: Record<string, unknown>): boolean {\n if (message.type !== \"text\") return true;\n if (typeof message.id !== \"string\" || typeof message.from !== \"string\") return false;\n const text = message.text;\n return text === undefined || (isRecord(text) && typeof text.body === \"string\");\n}\n\n/**\n * A contact the normalizer copies into a message: a string `wa_id`, and a `profile` that is absent\n * or carries a `name` that is absent or a string. That name becomes `sender.displayName`.\n */\nfunction isReadableContact(contact: Record<string, unknown>): boolean {\n if (typeof contact.wa_id !== \"string\") return false;\n const profile = contact.profile;\n if (profile === undefined) return true;\n return isRecord(profile) && (profile.name === undefined || typeof profile.name === \"string\");\n}\n\n/** A status the normalizer turns into a receipt: string `id`, `status` and `recipient_id`. */\nfunction isReadableStatus(status: Record<string, unknown>): boolean {\n return (\n typeof status.id === \"string\" &&\n typeof status.status === \"string\" &&\n typeof status.recipient_id === \"string\"\n );\n}\n\n/** Absent, or a list of objects that each pass `isReadable`. */\nfunction isOptionalReadableList(\n list: unknown,\n isReadable: (item: Record<string, unknown>) => boolean,\n): boolean {\n if (!isOptionalRecordArray(list)) return false;\n return list === undefined || (list as Record<string, unknown>[]).every(isReadable);\n}\n\n/** A change's `value`: absent, or an object whose lists hold items the normalizers can read. */\nfunction isWellFormedValue(value: unknown): boolean {\n if (value === undefined || value === null) return true;\n if (!isRecord(value)) return false;\n return (\n isWellFormedMetadata(value.metadata) &&\n isOptionalReadableList(value.contacts, isReadableContact) &&\n isOptionalReadableList(value.messages, isReadableMessage) &&\n isOptionalReadableList(value.statuses, isReadableStatus)\n );\n}\n\nfunction isWellFormedEntry(entry: unknown): boolean {\n if (!isRecord(entry) || !Array.isArray(entry.changes)) return false;\n return entry.changes.every((change) => isRecord(change) && isWellFormedValue(change.value));\n}\n\n/**\n * Parse the raw JSON payload into a typed envelope, or `null` when its shape is not one the\n * normalizers can read: no `object`, an `entry` that is not an array, or any entry, change or\n * listed contact, message or status that is not an object (an entry with no `changes` array, a\n * `null` change, `messages: 5`). The whole body is refused rather than its bad entries skipped, so\n * nothing in a batch is dropped without the route seeing it. A body is also refused when a field the\n * inbound rules read with string methods is not a string: a `metadata.phone_number_id` that is not\n * absent or a string, a text message whose `id`, `from` or `text.body` is not a string, a contact\n * whose `wa_id` or `profile.name` is not a string, or a status whose `id`, `status` or\n * `recipient_id` is not a string. Past a non-null result neither normalizer throws, and every\n * string field of an event or receipt holds a string. Timestamps are not checked here.\n */\nexport function parseWebhookPayload(json: unknown): MetaWebhookEnvelope | null {\n if (!isRecord(json)) return null;\n if (json.object === undefined || !Array.isArray(json.entry)) return null;\n if (!json.entry.every(isWellFormedEntry)) return null;\n return json as unknown as MetaWebhookEnvelope;\n}\n\n/**\n * Normalize inbound messages → `WhatsAppInboundEvent[]`.\n *\n * EC-4 absorbed: filters `message.type !== \"text\"` (v1 text-only). Non-text\n * types emit a one-shot stderr warn per type.\n */\nfunction buildContactMap(\n value: NonNullable<MetaWebhookEnvelope[\"entry\"][number][\"changes\"][number][\"value\"]>,\n): Map<string, string | undefined> {\n const map = new Map<string, string | undefined>();\n for (const c of value.contacts ?? []) map.set(c.wa_id, c.profile?.name);\n return map;\n}\n\nfunction processChange(\n change: MetaWebhookEnvelope[\"entry\"][number][\"changes\"][number],\n out: WhatsAppInboundEvent[],\n): void {\n const value = change.value;\n if (value === undefined || value === null) return;\n const phoneNumberId = value.metadata?.phone_number_id;\n const contactByWaId = buildContactMap(value);\n for (const msg of value.messages ?? []) {\n const normalized = normalizeOneMessage(msg, phoneNumberId, contactByWaId);\n if (normalized !== null) out.push(normalized);\n }\n}\n\n/**\n * Extract the inbound messages from one Meta webhook envelope.\n *\n * A single delivery batches entries, changes and messages, and may carry none at all — a\n * status-only delivery is normal. Returns an array, empty when there is nothing to hand on.\n */\nexport function normalizeInboundMessages(envelope: MetaWebhookEnvelope): WhatsAppInboundEvent[] {\n const out: WhatsAppInboundEvent[] = [];\n for (const entry of envelope.entry) {\n for (const change of entry.changes) processChange(change, out);\n }\n return out;\n}\n\nfunction normalizeOneMessage(\n msg: MetaIncomingMessage,\n phoneNumberId: string | undefined,\n contactByWaId: Map<string, string | undefined>,\n): WhatsAppInboundEvent | null {\n // EC-4: text-only in v1.\n if (msg.type !== \"text\") {\n const label = nonTextTypeLabel(msg.type);\n if (!warnedNonTextTypes.has(label)) {\n warnedNonTextTypes.add(label);\n process.stderr.write(\n `[whatsapp] ignoring ${label} message — v1 text-only (will be supported in v0.2+).\\n`,\n );\n }\n return null;\n }\n const body = msg.text?.body ?? \"\";\n // Cloud API doesn't distinguish DM vs group at the message level — `from`\n // is the sender. We don't have a reliable group-detection signal in cloud\n // (groups need a different webhook subscription). v1 treats all inbound\n // as DM. If the user enables group webhooks, the `conversationType` heuristic\n // here is a future-extension point.\n return {\n wamid: msg.id,\n fromPhone: msg.from,\n phoneNumberId,\n contactName: contactByWaId.get(msg.from),\n conversationType: \"dm\",\n channelId: msg.from,\n text: body,\n receivedAt: Number(msg.timestamp) * 1000 || Date.now(),\n backend: \"cloud\",\n raw: msg,\n };\n}\n\n/** Normalize status updates → `WhatsAppStatusReceipt[]`. */\nexport function normalizeStatusReceipts(envelope: MetaWebhookEnvelope): WhatsAppStatusReceipt[] {\n const out: WhatsAppStatusReceipt[] = [];\n for (const entry of envelope.entry) {\n for (const change of entry.changes) {\n const phoneNumberId = change.value?.metadata?.phone_number_id;\n for (const s of change.value?.statuses ?? []) {\n out.push(metaStatusToReceipt(s, phoneNumberId));\n }\n }\n }\n return out;\n}\n\nfunction metaStatusToReceipt(\n s: MetaStatusUpdate,\n phoneNumberId: string | undefined,\n): WhatsAppStatusReceipt {\n const receipt = {\n wamid: s.id,\n status: s.status,\n recipient: s.recipient_id,\n timestamp: Number(s.timestamp) * 1000 || Date.now(),\n };\n return phoneNumberId === undefined ? receipt : { ...receipt, phoneNumberId };\n}\n\n/** @internal — test seam to reset the one-shot warn de-dup. */\nexport function __resetNonTextWarnings(): void {\n warnedNonTextTypes.clear();\n}\n","/**\n * `WhatsAppCloudBackend` — Meta WhatsApp Business Cloud API backend (ADR D304).\n *\n * `connect()` verifies the credential against Meta and caches the result; `disconnect()` clears\n * it. This header used to say both were no-ops, which is what the code did and what the first\n * live run of the WhatsApp suite refuted (#58): a wrong or revoked token reported success at\n * startup and surfaced as messages that silently never arrived.\n *\n * There is still no session to open — HTTP push via webhook is the only inbound channel, and\n * outbound is a stateless POST. What `connect()` buys is the startup answer to \"can this\n * credential act as this number?\", which is the question every sibling adapter answers and this\n * one did not. Outbound delegates to `WhatsAppCloudClient`. Inbound dispatch is driven by the\n * user calling `handleWebhookPayload(rawBody, sig)` from inside their HTTP route.\n *\n * @public\n */\n\nimport type {\n WhatsAppBackend,\n WhatsAppInboundEvent,\n WhatsAppOutboundMessage,\n WhatsAppSendResult,\n WhatsAppStatusReceipt,\n} from \"../../backend-types.js\";\nimport { isForAnotherNumber } from \"../../foreign-number.js\";\nimport { WhatsAppCloudClient } from \"./client.js\";\nimport type { MetaTemplateComponent, MetaWebhookEnvelope } from \"./types.js\";\nimport {\n normalizeInboundMessages,\n normalizeStatusReceipts,\n parseWebhookPayload,\n verifyWebhookSignature,\n} from \"./webhook.js\";\n\nexport interface WhatsAppCloudBackendOptions {\n readonly accessToken: string;\n readonly phoneNumberId: string;\n readonly appSecret: string;\n readonly apiVersion?: string;\n /** Test seam. */\n readonly fetch?: typeof fetch;\n}\n\n/**\n * WhatsApp backend over Meta's official Cloud API.\n *\n * The supported path: Meta dials in with webhook deliveries, so inbound needs a publicly reachable\n * HTTPS endpoint registered in the Meta console. Outbound is a plain HTTPS call and works anywhere.\n * Business-initiated messages outside the 24-hour customer service window must use an approved\n * template — a plain text send to a cold contact is rejected by the platform, not by this code.\n */\nexport class WhatsAppCloudBackend implements WhatsAppBackend {\n readonly kind = \"cloud\" as const;\n private readonly client: WhatsAppCloudClient;\n /** Verified once by `connect()`; cleared by `disconnect()`. */\n private connected = false;\n /**\n * The verification currently in flight, shared by every caller that arrives during it.\n *\n * A flag alone only guards callers that arrive AFTER one finished — two simultaneous\n * `connect()` calls would each ask Meta, which is one wasted round-trip at startup and a\n * rate-limit source under a supervisor that health-checks on a schedule. Cleared when it\n * settles, so a failed attempt does not become a permanent refusal: a transient blip must stay\n * distinguishable from a revoked token.\n */\n private connecting?: Promise<boolean>;\n /**\n * Which connection attempt is current.\n *\n * Bumped by every `connect()` and every `disconnect()`. Without it a verify that was still in\n * flight when `disconnect()` ran would set `connected` back to true as it resolved, and every\n * later `connect()` would short-circuit on a flag no live check stands behind — the field's own\n * comment claims `disconnect()` clears it, and it did not. Same guard the Baileys backend\n * carries, for the same reason.\n */\n private generation = 0;\n private readonly appSecret: string;\n /**\n * The Meta phone number id this backend sends as and answers for. Declared through\n * `WhatsAppBackend.phoneNumberId`, so an adapter holding this backend can refuse a signed message\n * addressed to another number of the same app.\n */\n readonly phoneNumberId: string;\n /** Foreign phone number id endings already named on stderr, so each is reported once. */\n private readonly reportedForeignNumbers = new Set<string>();\n private inboundHandler?: (event: WhatsAppInboundEvent) => Promise<void>;\n private statusHandler?: (receipt: WhatsAppStatusReceipt) => Promise<void>;\n\n constructor(opts: WhatsAppCloudBackendOptions) {\n this.client = new WhatsAppCloudClient({\n accessToken: opts.accessToken,\n phoneNumberId: opts.phoneNumberId,\n apiVersion: opts.apiVersion,\n ...(opts.fetch !== undefined ? { fetch: opts.fetch } : {}),\n });\n this.appSecret = opts.appSecret;\n this.phoneNumberId = opts.phoneNumberId;\n }\n\n // Cloud has no persistent connection — webhook is push, send is HTTP.\n /**\n * Confirm with Meta that this credential can act as this phone number.\n *\n * This used to be `return true`. A consumer with a wrong, expired or revoked token got success\n * at startup and found out from messages that silently never arrived — no error, no log,\n * nothing to alert on, which is the worst failure mode a gateway has. The first live run of the\n * WhatsApp suite caught it (#58); no unit test could, because a fake backend always accepts.\n *\n * Idempotent, like every sibling: verified once, then cached. Re-asking on every call would\n * turn a supervisor's health check into a rate-limit source against Meta.\n *\n * Returns false rather than throwing — the contract each sibling adapter is tested against,\n * because a throw at startup takes the whole runner down with it. The reason goes to stderr\n * first: told only \"false\", a supervisor cannot tell a revoked token, which needs a human,\n * from a rate limit, which needs a wait.\n */\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n if (this.connecting !== undefined) return this.connecting;\n\n const attempt = this.verifyOnce(++this.generation);\n this.connecting = attempt;\n try {\n return await attempt;\n } finally {\n // Only clear what is still ours: `disconnect()` clears it too, and a later `connect()` may\n // already have installed its own.\n if (this.connecting === attempt) this.connecting = undefined;\n }\n }\n\n /** One credential check, mapped to the boolean `connect()` is contracted to return. @internal */\n private async verifyOnce(generation: number): Promise<boolean> {\n const check = await this.client.verifyCredentials();\n if (!check.ok) {\n process.stderr.write(\n `[whatsapp-cloud] connect failed: ${check.error?.code ?? \"unknown\"} — ` +\n `${check.error?.message ?? \"no reason given\"}\\n`,\n );\n return false;\n }\n // A `disconnect()` that arrived while this was in flight wins: adopting now would leave a\n // flag standing over a backend the caller has already closed.\n if (this.generation !== generation) return false;\n this.connected = true;\n return true;\n }\n\n async disconnect(): Promise<void> {\n this.generation += 1;\n this.connected = false;\n this.connecting = undefined;\n this.inboundHandler = undefined;\n this.statusHandler = undefined;\n }\n\n async send(message: WhatsAppOutboundMessage): Promise<WhatsAppSendResult> {\n // Cloud is stateless HTTP, so there is no session to be outside of — and that was the reason\n // this posted regardless while web and Baileys refused. It was the wrong reason. Since\n // `connect()` started verifying the credential, `connected === false` means the credential\n // was rejected or never checked, and sending anyway spends a request that cannot succeed\n // while making this backend behave differently from its siblings under one interface.\n if (!this.connected) {\n return {\n ok: false,\n error: {\n code: \"not_connected\",\n message: \"Cloud backend is not connected — call connect().\",\n },\n };\n }\n return this.client.sendText(message.to, message.text, message.isGroup);\n }\n\n /**\n * Send an approved template to `to`.\n *\n * Cloud-only, and deliberately absent from the `WhatsAppBackend` interface: WhatsApp Web has no\n * concept of templates, so putting this on the shared contract would hand the web backend a\n * method it could only throw from. A consumer reaches it by holding the backend directly.\n *\n * This is the only way to message someone outside the 24-hour service window — every\n * notification, and every unattended check that this integration still works. Free-form text to\n * a cold recipient comes back as `session_window_expired`.\n *\n * @param templateName Name of a template already approved on the WhatsApp Business account.\n * @param languageCode Locale of the approved template, e.g. `en_US`, `pt_BR`.\n * @param components Values for the template's variables; omit for a template that takes none.\n */\n async sendTemplate(\n to: string,\n templateName: string,\n languageCode: string,\n components?: ReadonlyArray<MetaTemplateComponent>,\n ): Promise<WhatsAppSendResult> {\n // Same rule as `send()`, and it needs saying separately because this method is off the\n // `WhatsAppBackend` interface — WhatsApp Web has no templates — so the conformance suite that\n // enforces it there structurally cannot see it here. Being outside the shared contract is\n // why it needs its own guard, not a reason to be exempt from the rule.\n if (!this.connected) {\n return {\n ok: false,\n error: {\n code: \"not_connected\",\n message: \"Cloud backend is not connected — call connect().\",\n },\n };\n }\n return this.client.sendTemplate(to, templateName, languageCode, components);\n }\n\n onInbound(handler: (event: WhatsAppInboundEvent) => Promise<void>): () => void {\n this.inboundHandler = handler;\n return () => {\n // Identity-guarded: a stale unsubscribe must be a no-op. Without it,\n // `onInbound(A)` → `onInbound(B)` → `A.off()` clears B's handler and the backend goes\n // silent with no error — nothing to see in a log, nothing to alert on. This is a public\n // export implementing an exported interface, so a consumer holding the backend directly\n // reaches it without going through `WhatsAppAdapter`.\n if (this.inboundHandler === handler) this.inboundHandler = undefined;\n };\n }\n\n onStatusReceipt(handler: (receipt: WhatsAppStatusReceipt) => Promise<void>): () => void {\n this.statusHandler = handler;\n return () => {\n if (this.statusHandler === handler) this.statusHandler = undefined;\n };\n }\n\n /**\n * Webhook entrypoint. The user calls this from inside their POST /webhook\n * route after `verifyWebhookSubscription` on GET.\n *\n * Only messages addressed to this backend's `phoneNumberId` reach the inbound handler, and only\n * status receipts addressed to it reach the status handler. Meta signs every number of one app\n * with one secret and an app-level webhook URL receives every subscribed number, so a valid\n * signature does not say which number a message or receipt was for; one for another number, or\n * naming none, is dropped and its id written to stderr once (`isForAnotherNumber`, the rule\n * `WhatsAppAdapter` applies too).\n *\n * @returns `true` if the signature is valid and the body was dispatched (or held nothing to\n * dispatch). `false` if the signature is invalid (answer 401), or if the body holds a\n * message for this number while no inbound handler is subscribed (before `onInbound`,\n * or after `disconnect()`): the whole body is refused, never a part of it dropped, and\n * one line on stderr says which; answer non-2xx so Meta redelivers once a handler is\n * subscribed. `\"unreadable_body\"` if the signature is valid but the body is not JSON\n * or has a shape {@link parseWebhookPayload} refuses: nothing is dispatched and one\n * line on stderr says why. This is not forgery, and redelivery cannot recover it:\n * Meta resends the same bytes, which are refused again. Answer it differently from a\n * bad signature (the README example answers 200 so Meta stops retrying). Status receipts with no status handler subscribed\n * are discarded on purpose: subscribing to receipts is optional, and refusing them\n * would make Meta redeliver every receipt to a route that never wants one.\n * @throws {ConfigurationError} `missing_option` when this backend's `appSecret` is empty or\n * whitespace only: a signature under an empty key proves nothing.\n */\n async handleWebhookPayload(\n rawBody: Buffer | string,\n signatureHeader: string | undefined,\n ): Promise<boolean | \"unreadable_body\"> {\n if (!verifyWebhookSignature(rawBody, signatureHeader, this.appSecret)) {\n return false;\n }\n const json = this.parseBody(rawBody);\n if (json === undefined) return \"unreadable_body\";\n const envelope = parseWebhookPayload(json);\n if (envelope === null) {\n // Answering true would let the route say 200 and Meta never redeliver the batch.\n process.stderr.write(\n \"[whatsapp-cloud] signed webhook body has a shape the parser refuses (no object, no entry array, or a malformed entry, change or list); refused whole, nothing dispatched\\n\",\n );\n return \"unreadable_body\";\n }\n const messages = normalizeInboundMessages(envelope).filter(\n (event) => !isForAnotherNumber(event, this.phoneNumberId, this.reportedForeignNumbers),\n );\n const inboundHandler = this.inboundHandler;\n if (messages.length > 0 && inboundHandler === undefined) {\n // Answering true would let the route say 200 and Meta never redeliver these messages.\n process.stderr.write(\n `[whatsapp-cloud] signed webhook body holds ${messages.length} message(s) for this number and no inbound handler is subscribed; refused whole, nothing dispatched\\n`,\n );\n return false;\n }\n // The handler that accepted the batch receives all of it. Re-reading it per message let a\n // `disconnect()` or unsubscribe inside the first message's handler skip the rest while this\n // still answered true; refusing mid-batch instead would make Meta redeliver the messages\n // already handled.\n if (inboundHandler !== undefined) await this.dispatchInbound(messages, inboundHandler);\n await this.dispatchStatusReceipts(envelope);\n return true;\n }\n\n /**\n * Hand each status receipt addressed to this backend's number to the status handler.\n *\n * Same rule as messages: a receipt names the recipient's phone number, so one number's receipts\n * reaching another number's handler hands one tenant's customer numbers to another tenant.\n */\n private async dispatchStatusReceipts(envelope: MetaWebhookEnvelope): Promise<void> {\n for (const receipt of normalizeStatusReceipts(envelope)) {\n if (this.statusHandler === undefined) continue;\n if (isForAnotherNumber(receipt, this.phoneNumberId, this.reportedForeignNumbers)) continue;\n await this.dispatchContained(() => this.statusHandler?.(receipt), \"status handler\");\n }\n }\n\n /** Hand each message, already scoped to this backend's number, to the inbound handler. */\n private async dispatchInbound(\n messages: readonly WhatsAppInboundEvent[],\n handler: (event: WhatsAppInboundEvent) => Promise<void>,\n ): Promise<void> {\n for (const event of messages) {\n await this.dispatchContained(() => handler(event), \"handler\");\n }\n }\n\n /**\n * Parse a signed webhook body, or report `undefined` when it is not JSON.\n *\n * The method's contract is true/false; the route calling it has no reason to expect a throw.\n */\n private parseBody(rawBody: Buffer | string): unknown | undefined {\n try {\n return JSON.parse(typeof rawBody === \"string\" ? rawBody : rawBody.toString(\"utf8\"));\n } catch (err) {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[whatsapp-cloud] webhook body is not JSON: ${m}\\n`);\n return undefined;\n }\n }\n\n /**\n * Run one user callback and contain its failure.\n *\n * Meta batches several messages, and their delivery receipts, into a single webhook. Awaiting a\n * handler with nothing around it made one throw skip every remaining message in the payload —\n * and reject `handleWebhookPayload`, so the caller's route answered 500 and Meta redelivered the\n * whole batch, replaying the messages that HAD succeeded (#41).\n */\n private async dispatchContained(\n run: () => Promise<void> | undefined,\n what: string,\n ): Promise<void> {\n try {\n await run();\n } catch (err) {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[whatsapp-cloud] ${what} threw: ${m}\\n`);\n }\n }\n}\n","/**\n * IPC protocol between adapter and `whatsapp-web.js` subprocess bridge.\n *\n * Wire: stdin/stdout JSON-lines (each message terminated by `\\n`).\n *\n * @internal\n */\n\n/**\n * Sentinel runtime export — see `backend-types.ts` for rationale.\n *\n * @knipignore\n */\nexport const __ipcMarker: unique symbol = Symbol(\"ipc\");\n\n/** Commands the adapter sends to the bridge. */\nexport type IpcCommand =\n | { readonly cmd: \"send\"; readonly msgId: string; readonly to: string; readonly text: string }\n | { readonly cmd: \"shutdown\" };\n\n/** Events the bridge emits to the adapter. */\nexport type IpcEvent =\n | { readonly event: \"ready\"; readonly botPhone: string }\n | {\n readonly event: \"message\";\n readonly msgId: string;\n readonly from: string;\n readonly body: string;\n readonly isGroup: boolean;\n readonly chatId: string;\n readonly contactName?: string;\n readonly timestamp: number;\n }\n | {\n readonly event: \"send_ack\";\n readonly msgId: string;\n readonly success: boolean;\n readonly wamid?: string;\n readonly error?: string;\n }\n | {\n readonly event: \"status\";\n readonly msgId: string;\n readonly status: \"sent\" | \"delivered\" | \"read\" | \"failed\";\n readonly recipient: string;\n readonly timestamp: number;\n }\n | {\n readonly event: \"error\";\n readonly message: string;\n /**\n * Machine-readable cause, when the bridge could name one. Absent on older bridges and\n * on failures it cannot classify, which is why every consumer must tolerate it being\n * undefined rather than switching exhaustively.\n */\n readonly code?: string;\n };\n\n/** Parse one JSON-line. Returns null on malformed. */\nexport function parseEvent(line: string): IpcEvent | null {\n if (line.length === 0) return null;\n try {\n const parsed = JSON.parse(line) as unknown;\n if (parsed === null || typeof parsed !== \"object\") return null;\n if (typeof (parsed as { event?: unknown }).event !== \"string\") return null;\n return parsed as IpcEvent;\n } catch {\n return null;\n }\n}\n\n/** Format an outbound command as JSON + newline. */\nexport function formatCommand(cmd: IpcCommand): string {\n return `${JSON.stringify(cmd)}\\n`;\n}\n\n/**\n * Line buffer — accumulates stdout chunks until `\\n` boundaries, yields\n * complete lines. Addresses EC-11 (chunked stdout across multiple reads).\n */\nexport class LineBuffer {\n private buffer = \"\";\n\n push(chunk: string): string[] {\n this.buffer += chunk;\n const out: string[] = [];\n let idx = this.buffer.indexOf(\"\\n\");\n while (idx !== -1) {\n out.push(this.buffer.slice(0, idx));\n this.buffer = this.buffer.slice(idx + 1);\n idx = this.buffer.indexOf(\"\\n\");\n }\n return out;\n }\n\n /** Test seam — current pending bytes. */\n get pending(): string {\n return this.buffer;\n }\n}\n","/**\n * Bridge subprocess lifecycle (ADR D305, D313). PID file lock + stale-process\n * cleanup. EC-5 absorbed: verifies cmdline before killing (otherwise we may\n * kill an unrelated process the OS recycled the PID for).\n *\n * @internal\n */\n\nimport { type ChildProcess, execSync, spawn } from \"node:child_process\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\n/** Marker substring our bridge process MUST carry in its argv (EC-5). */\nexport const BRIDGE_PROCESS_TAG = \"whatsapp-web-bridge\";\n\ninterface SpawnBridgeOptions {\n readonly sessionId: string;\n readonly bridgeScriptPath: string;\n readonly theokitHome?: string;\n}\n\nexport interface BridgeHandle {\n readonly child: ChildProcess;\n readonly pidFilePath: string;\n}\n\nfunction pidFilePath(theokitHome: string, sessionId: string): string {\n return path.join(theokitHome, `whatsapp-bridge-${sessionId}.pid`);\n}\n\nfunction defaultTheokitHome(): string {\n return process.env.THEOKIT_HOME ?? path.join(process.env.HOME ?? \"/tmp\", \".theokit\");\n}\n\n/**\n * Verify whether `pid` belongs to a process whose argv contains our tag (EC-5).\n *\n * Without this guard, OS may have recycled the PID to e.g. `vim` and our\n * cleanup would terminate the user's editor.\n *\n * @internal\n */\nexport function pidBelongsToOurBridge(pid: number): boolean {\n try {\n // Linux: /proc/<pid>/cmdline (NUL-separated argv).\n const cmdline = fs.readFileSync(`/proc/${pid}/cmdline`, \"utf8\");\n return cmdline.includes(BRIDGE_PROCESS_TAG);\n } catch {\n // macOS / BSD fallback: ps -p <pid> -o args=\n try {\n const out = execSync(`ps -p ${pid} -o args=`, {\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n }).toString();\n return out.includes(BRIDGE_PROCESS_TAG);\n } catch {\n return false;\n }\n }\n}\n\n/** EC-5: kill `stalePid` ONLY if cmdline confirms ownership. */\nfunction killIfOurBridge(stalePid: number): void {\n if (!Number.isFinite(stalePid) || stalePid <= 0) return;\n if (!pidBelongsToOurBridge(stalePid)) return;\n try {\n process.kill(stalePid, \"SIGTERM\");\n } catch {\n // Process already gone — fine.\n }\n}\n\nfunction cleanupStaleLock(lockFile: string): void {\n const raw = fs.readFileSync(lockFile, \"utf8\").trim();\n killIfOurBridge(Number.parseInt(raw, 10));\n try {\n fs.unlinkSync(lockFile);\n } catch {\n /* ignore */\n }\n}\n\n/**\n * Acquire the PID lock for a session — kill any stale bridge (cmdline-verified),\n * then return the lock-file path (caller writes its own PID after spawn).\n */\nexport function acquirePidLock(sessionId: string, theokitHome?: string): string {\n const home = theokitHome ?? defaultTheokitHome();\n fs.mkdirSync(home, { recursive: true });\n const lockFile = pidFilePath(home, sessionId);\n if (fs.existsSync(lockFile)) cleanupStaleLock(lockFile);\n return lockFile;\n}\n\n/** Spawn the bridge subprocess, write PID file. */\nexport function spawnBridge(opts: SpawnBridgeOptions): BridgeHandle {\n const home = opts.theokitHome ?? defaultTheokitHome();\n const lockFile = acquirePidLock(opts.sessionId, home);\n\n const child = spawn(\n \"node\",\n [opts.bridgeScriptPath, \"--tag\", BRIDGE_PROCESS_TAG, \"--session\", opts.sessionId],\n {\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n detached: false,\n },\n );\n\n if (child.pid !== undefined) {\n fs.writeFileSync(lockFile, String(child.pid), { mode: 0o600 });\n }\n\n // EC-12: pipe stderr so the buffer never fills.\n if (child.stderr !== null) {\n child.stderr.pipe(process.stderr);\n }\n\n return { child, pidFilePath: lockFile };\n}\n\n/** Terminate the bridge: SIGTERM → wait 3s → SIGKILL. Removes PID file. */\nexport async function terminateBridge(handle: BridgeHandle): Promise<void> {\n const { child, pidFilePath: lockFile } = handle;\n if (child.pid !== undefined && !child.killed) {\n try {\n child.kill(\"SIGTERM\");\n } catch {\n /* ignore */\n }\n const exited = await waitForExit(child, 3000);\n if (!exited) {\n try {\n child.kill(\"SIGKILL\");\n } catch {\n /* ignore */\n }\n await waitForExit(child, 1000);\n }\n }\n try {\n fs.unlinkSync(lockFile);\n } catch {\n /* ignore */\n }\n}\n\nfunction waitForExit(child: ChildProcess, timeoutMs: number): Promise<boolean> {\n return new Promise((resolve) => {\n if (child.exitCode !== null || child.signalCode !== null) {\n resolve(true);\n return;\n }\n let resolved = false;\n const onExit = () => {\n if (resolved) return;\n resolved = true;\n resolve(true);\n };\n child.once(\"exit\", onExit);\n setTimeout(() => {\n if (resolved) return;\n resolved = true;\n child.removeListener(\"exit\", onExit);\n resolve(false);\n }, timeoutMs).unref();\n });\n}\n","/**\n * `WhatsAppWebBackend` — `whatsapp-web.js` subprocess bridge backend (ADR D305).\n *\n * Lifecycle (T3.1) + IPC (T3.2) wired behind the `WhatsAppBackend` interface.\n * EC-6 absorbed: `connect()` races against a 120s timeout so unattended QR\n * pairings fail fast instead of hanging the app.\n *\n * **THE CONSUMER MUST PROVIDE A BROWSER.** `whatsapp-web.js` drives a real Chrome through\n * Puppeteer, and this package ships none: the repository leaves `puppeteer` out of\n * `pnpm.onlyBuiltDependencies`, so its postinstall never downloads one. Without a browser the\n * bridge starts, cannot find Chrome, and says so in its own protocol rather than crashing —\n * which is the whole of the B-002 fix, and is still not a connection. Set\n * `PUPPETEER_EXECUTABLE_PATH` to a Chrome or Chromium you already have; the bridge is spawned\n * without an explicit `env`, so it inherits yours.\n *\n * B-002 asked for exactly this sentence or for a buildable `puppeteer`, and shipped with\n * neither. Measured 2026-08-29: with the variable set, the bridge reaches WhatsApp and issues\n * a pairing QR. {@link WhatsAppBaileysBackend} needs no browser, which is why it exists.\n *\n * @public\n */\n\nimport { existsSync } from \"node:fs\";\nimport * as path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type {\n WhatsAppBackend,\n WhatsAppInboundEvent,\n WhatsAppOutboundMessage,\n WhatsAppSendResult,\n WhatsAppStatusReceipt,\n} from \"../../backend-types.js\";\nimport {\n mapWhatsAppWebError,\n WhatsAppBridgeError,\n WhatsAppConnectTimeoutError,\n} from \"../../errors.js\";\nimport { formatCommand, type IpcEvent, LineBuffer, parseEvent } from \"./ipc.js\";\nimport { type BridgeHandle, spawnBridge, terminateBridge } from \"./lifecycle.js\";\n\nexport interface WhatsAppWebBackendOptions {\n readonly sessionId: string;\n /** Override the default bridge script path. Defaults to bundled script. */\n readonly bridgeScriptPath?: string;\n /** EC-6 connect timeout in ms. Default 120000. */\n readonly connectTimeoutMs?: number;\n /** Per-send timeout in ms. Default 30000. */\n readonly sendTimeoutMs?: number;\n /** Test seam: override the spawned child via a factory. */\n readonly spawnFactory?: () => BridgeHandle;\n /** Test seam: theokit home for PID locks. */\n readonly theokitHome?: string;\n}\n\ninterface PendingSend {\n readonly resolve: (r: WhatsAppSendResult) => void;\n readonly timer: NodeJS.Timeout;\n}\n\nconst DEFAULT_CONNECT_TIMEOUT_MS = 120_000;\nconst DEFAULT_SEND_TIMEOUT_MS = 30_000;\n\n/**\n * WhatsApp backend driving `whatsapp-web.js` in a child process.\n *\n * Unofficial: it automates a WhatsApp Web session, which Meta's terms do not sanction and which can\n * get a number banned. It exists for a personal number that has no Cloud API access. The browser\n * runs out-of-process behind a PID lock so a crashed or orphaned bridge cannot be left holding the\n * session.\n */\nexport class WhatsAppWebBackend implements WhatsAppBackend {\n readonly kind = \"web\" as const;\n private handle?: BridgeHandle;\n private readonly buffer = new LineBuffer();\n private inboundHandler?: (event: WhatsAppInboundEvent) => Promise<void>;\n private statusHandler?: (receipt: WhatsAppStatusReceipt) => Promise<void>;\n private readonly pending = new Map<string, PendingSend>();\n /** Rejects an in-flight `connect()` when the bridge reports it cannot start. */\n private connectRejectors: Array<(reason: Error) => void> = [];\n private msgIdCounter = 0;\n private botPhone?: string;\n private connected = false;\n // EC-6: emitter resolvers for `event: \"ready\"`.\n private readyResolvers: Array<(phone: string) => void> = [];\n\n constructor(private readonly opts: WhatsAppWebBackendOptions) {}\n\n private spawnBridgeHandle(): NonNullable<typeof this.handle> {\n return this.opts.spawnFactory\n ? this.opts.spawnFactory()\n : spawnBridge({\n sessionId: this.opts.sessionId,\n bridgeScriptPath: this.opts.bridgeScriptPath ?? defaultBridgeScriptPath(),\n ...(this.opts.theokitHome !== undefined ? { theokitHome: this.opts.theokitHome } : {}),\n });\n }\n\n private wireStdout(): void {\n if (this.handle?.child.stdout === null || this.handle === undefined) return;\n this.handle.child.stdout.setEncoding(\"utf8\");\n this.handle.child.stdout.on(\"data\", (chunk: string) => {\n for (const line of this.buffer.push(chunk)) {\n const event = parseEvent(line);\n if (event !== null) this.dispatch(event);\n }\n });\n }\n\n private async cleanupHandle(): Promise<void> {\n if (this.handle === undefined) return;\n await terminateBridge(this.handle).catch(() => {});\n this.handle = undefined;\n }\n\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n this.handle = this.spawnBridgeHandle();\n this.wireStdout();\n\n const timeoutMs = this.opts.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;\n const ready = new Promise<string>((resolve, reject) => {\n this.readyResolvers.push(resolve);\n // The bridge reporting a startup failure resolves the race immediately, so the caller\n // learns the cause instead of waiting out the timeout.\n this.connectRejectors.push(reject);\n });\n let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => reject(new WhatsAppConnectTimeoutError(timeoutMs)), timeoutMs);\n });\n\n try {\n const phone = await Promise.race([ready, timeout]);\n this.botPhone = phone;\n this.connected = true;\n return true;\n } catch (err) {\n await this.cleanupHandle();\n throw err;\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n // Both arrays hold settled callbacks once the race is decided, and neither was cleared\n // on the path that fails by timeout — `handleBridgeError` never ran, and `disconnect()`\n // returns early while `connected` is false. A reconnect loop therefore grew them by one\n // per attempt forever. `readyResolvers` had the same leak before this method learned to\n // reject; clearing them together is the whole fix.\n this.readyResolvers = [];\n this.connectRejectors = [];\n }\n }\n\n async disconnect(): Promise<void> {\n if (!this.connected || this.handle === undefined) return;\n try {\n if (this.handle.child.stdin !== null && !this.handle.child.stdin.destroyed) {\n this.handle.child.stdin.write(formatCommand({ cmd: \"shutdown\" }));\n }\n } catch {\n /* ignore */\n }\n await terminateBridge(this.handle);\n this.handle = undefined;\n this.connected = false;\n // Reject any pending sends.\n for (const [_, p] of this.pending) {\n clearTimeout(p.timer);\n p.resolve({ ok: false, error: { code: \"server_error\", message: \"Bridge disconnected.\" } });\n }\n this.pending.clear();\n this.readyResolvers = [];\n this.connectRejectors = [];\n }\n\n async send(message: WhatsAppOutboundMessage): Promise<WhatsAppSendResult> {\n if (!this.connected || this.handle === undefined || this.handle.child.stdin === null) {\n return { ok: false, error: { code: \"not_connected\", message: \"Bridge not connected.\" } };\n }\n const msgId = `out-${++this.msgIdCounter}`;\n const timeoutMs = this.opts.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS;\n return new Promise<WhatsAppSendResult>((resolve) => {\n const timer = setTimeout(() => {\n this.pending.delete(msgId);\n resolve({\n ok: false,\n error: { code: \"timeout\", message: `Bridge send timed out after ${timeoutMs}ms.` },\n });\n }, timeoutMs);\n this.pending.set(msgId, { resolve, timer });\n try {\n this.handle!.child.stdin!.write(\n formatCommand({ cmd: \"send\", msgId, to: message.to, text: message.text }),\n );\n } catch (err) {\n clearTimeout(timer);\n this.pending.delete(msgId);\n resolve({\n ok: false,\n error: mapWhatsAppWebError(err instanceof Error ? err.message : String(err)),\n });\n }\n });\n }\n\n onInbound(handler: (event: WhatsAppInboundEvent) => Promise<void>): () => void {\n this.inboundHandler = handler;\n return () => {\n // Identity-guarded: a stale unsubscribe must be a no-op. Without it,\n // `onInbound(A)` → `onInbound(B)` → `A.off()` clears B's handler and the backend goes\n // silent with no error — nothing to see in a log, nothing to alert on. This is a public\n // export implementing an exported interface, so a consumer holding the backend directly\n // reaches it without going through `WhatsAppAdapter`.\n if (this.inboundHandler === handler) this.inboundHandler = undefined;\n };\n }\n\n onStatusReceipt(handler: (receipt: WhatsAppStatusReceipt) => Promise<void>): () => void {\n this.statusHandler = handler;\n return () => {\n if (this.statusHandler === handler) this.statusHandler = undefined;\n };\n }\n\n private handleReady(event: Extract<IpcEvent, { event: \"ready\" }>): void {\n for (const r of this.readyResolvers) r(event.botPhone);\n this.readyResolvers = [];\n }\n\n private handleMessage(event: Extract<IpcEvent, { event: \"message\" }>): void {\n if (this.inboundHandler === undefined) return;\n const normalized: WhatsAppInboundEvent = {\n wamid: event.msgId,\n fromPhone: event.from,\n contactName: event.contactName,\n conversationType: event.isGroup ? \"group\" : \"dm\",\n channelId: event.chatId,\n text: event.body,\n receivedAt: event.timestamp || Date.now(),\n backend: \"web\",\n raw: event,\n };\n // The bridge's stdout listener is synchronous and does not await this, so the promise has to be\n // terminated here. `void` alone left the rejection unhandled, and under Node 22's default that\n // ends the process — one message with a throwing handler killed the bot (#41). A handler is\n // user code; its failure is contained and named, and the bridge keeps delivering.\n void this.inboundHandler(normalized).catch((err: unknown) => {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[whatsapp-web] handler threw: ${m}\\n`);\n });\n }\n\n /**\n * A bridge that reported a failure has failed — say so now, not in two minutes.\n *\n * This used to write the message to stderr and return. `connect()` races only the `ready`\n * promise against the timeout, so a bridge that told us exactly what was wrong and exited\n * still cost the caller the full `connectTimeoutMs` and surfaced as a timeout — the one\n * error that carries no information. The diagnosis was printed where nothing could act on\n * it, which is the swallowing `rules/error-handling.md` § 5 names.\n */\n private handleBridgeError(event: Extract<IpcEvent, { event: \"error\" }>): void {\n process.stderr.write(`[whatsapp-web bridge] ${event.message}\\n`);\n const failure = new WhatsAppBridgeError(event.message, event.code);\n // Unblocks an in-flight connect(). Harmless once connected: nobody is waiting.\n for (const reject of this.connectRejectors) reject(failure);\n this.connectRejectors = [];\n }\n\n private handleSendAck(event: Extract<IpcEvent, { event: \"send_ack\" }>): void {\n const pending = this.pending.get(event.msgId);\n if (pending === undefined) return;\n this.pending.delete(event.msgId);\n clearTimeout(pending.timer);\n if (event.success) {\n pending.resolve(event.wamid !== undefined ? { ok: true, wamid: event.wamid } : { ok: true });\n } else {\n pending.resolve({ ok: false, error: mapWhatsAppWebError(event.error) });\n }\n }\n\n private handleStatus(event: Extract<IpcEvent, { event: \"status\" }>): void {\n if (this.statusHandler === undefined) return;\n // Same boundary as handleMessage: nothing awaits this, so an unhandled rejection here is fatal.\n void this.statusHandler({\n wamid: event.msgId,\n status: event.status,\n recipient: event.recipient,\n timestamp: event.timestamp || Date.now(),\n }).catch((err: unknown) => {\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[whatsapp-web] status handler threw: ${m}\\n`);\n });\n }\n\n private dispatch(event: IpcEvent): void {\n switch (event.event) {\n case \"ready\":\n this.handleReady(event);\n return;\n case \"message\":\n this.handleMessage(event);\n return;\n case \"send_ack\":\n this.handleSendAck(event);\n return;\n case \"status\":\n this.handleStatus(event);\n return;\n case \"error\":\n this.handleBridgeError(event);\n return;\n }\n }\n}\n\n/**\n * Where the bridge script lives, for the layout this module is running from.\n *\n * The single hard-coded `../../bridge/...` this replaced was written against the SOURCE\n * tree — `src/backend/web/` up two is `src/`, which is right. The bundle is one flat file\n * at `dist/index.js`, so the same relative path resolved to `packages/bridge/...`, one\n * directory above the package. Nothing caught it: every test injects `spawnFactory`, so the\n * real spawn had never run, and when it did the child died with `MODULE_NOT_FOUND` and\n * `connect()` reported a 120-second timeout — the one error carrying no information about\n * what actually happened.\n *\n * Both layouts are checked, and neither existing is an error rather than a guess: a path\n * that does not exist can only fail later, further from the cause.\n */\nexport function defaultBridgeScriptPath(): string {\n const here = path.dirname(fileURLToPath(import.meta.url));\n const candidates = [\n // Bundled: dist/index.js beside dist/bridge/\n path.resolve(here, \"bridge/whatsapp-web-bridge.mjs\"),\n // Source: src/backend/web/index.ts up two to src/\n path.resolve(here, \"../../bridge/whatsapp-web-bridge.mjs\"),\n ];\n const found = candidates.find((candidate) => existsSync(candidate));\n if (found === undefined) {\n throw new WhatsAppBridgeError(\n `bridge script not found. Looked in: ${candidates.join(\", \")}. ` +\n \"Pass `bridgeScriptPath` explicitly if the package layout differs.\",\n \"bridge_script_missing\",\n );\n }\n return found;\n}\n","/**\n * The fail-closed precondition of the adapter methods a route calls with an unfiltered Cloud\n * envelope (docs/adr/0006).\n *\n * @internal\n */\n\nimport type { WhatsAppMessageEvent } from \"@theokit/gateway\";\n\nimport type { WhatsAppInboundEvent } from \"./backend-types.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { isForAnotherNumber } from \"./foreign-number.js\";\nimport { decideInbound, type InboundRules } from \"./inbound-rules.js\";\n\n/**\n * The event the agent receives for `inbound`, or `undefined` when it is addressed to another number\n * than `ownPhoneNumberId` or a rule of `decideInbound` drops it.\n *\n * `onInbound` calls this without `requireOwnPhoneNumberId`: a backend that declares no number and\n * still delivers Cloud messages filtered them by its own number first (a wrapped\n * `WhatsAppCloudBackend` does), so only the methods a route hands an unfiltered envelope fail closed.\n */\nexport function decideForOwnNumber(\n inbound: WhatsAppInboundEvent,\n ownPhoneNumberId: string | undefined,\n reported: Set<string>,\n rules: InboundRules,\n): WhatsAppMessageEvent | undefined {\n if (isForAnotherNumber(inbound, ownPhoneNumberId, reported)) return undefined;\n return decideInbound(inbound, rules);\n}\n\n/**\n * The phone number id the adapter's backend declares, or a `missing_phone_number_id`\n * `ConfigurationError` naming `method` when it declares none. One Meta app signs every number's\n * webhooks with one secret, so with no number to compare, every number's messages would reach the\n * adapter's agent.\n */\nexport function requireOwnPhoneNumberId(\n ownPhoneNumberId: string | undefined,\n method: string,\n): string {\n if (ownPhoneNumberId !== undefined) return ownPhoneNumberId;\n throw new ConfigurationError({\n code: \"missing_phone_number_id\",\n message:\n `gateway-whatsapp: ${method} needs the backend to declare its phoneNumberId. ` +\n \"One Meta app signs every number's webhooks with one secret, so without it this adapter \" +\n \"would deliver every number's messages. Use fromCloud, or expose phoneNumberId on a \" +\n \"backend that wraps WhatsAppCloudBackend.\",\n });\n}\n","/**\n * The refusal this adapter answers for an outbound that carries attachments (B-674).\n *\n * This adapter sends text only, so an outbound carrying attachments is refused rather than sent without its images.\n *\n * The check runs before any other, so a refusal makes no platform call. It lives in this package\n * rather than in `@theokit/gateway` so that the adapter calls nothing its declared core floor\n * lacks; only the `OutboundMessage` type is imported.\n */\n\nimport type { OutboundMessage, SendResult } from \"@theokit/gateway\";\n\n/**\n * `attachments_unsupported` when `out` carries attachments, otherwise `undefined`.\n *\n * Absent, `null` and an empty list carry nothing. `!== 0`, not `> 0`: any other non-array value\n * from a JavaScript caller has no numeric length and is refused rather than taken for an empty\n * list (EC-1).\n */\nexport function refuseAttachments(out: OutboundMessage): SendResult | undefined {\n if (out.attachments == null || out.attachments.length === 0) return undefined;\n return {\n ok: false,\n error: { code: \"attachments_unsupported\", message: \"whatsapp adapter cannot send attachments\" },\n };\n}\n","/**\n * Split a long string into ≤4096-char chunks for WhatsApp messages (ADR D310).\n *\n * Thin wrapper over core `chunkText` (roadmap M1). WhatsApp family: fixed 4096\n * window, `\\n\\n` → `\\n` → ` ` boundary preference, UTF-16 surrogate-pair guard,\n * leading-whitespace strip. `trimParts` reproduces EC-8 (empty parts filtered\n * so consecutive newlines don't yield empty `sendMessage` calls Meta rejects).\n * Output is byte-identical to the previous implementation (pinned by\n * `tests/split.test.ts`).\n *\n * @internal\n */\n\nimport { chunkText } from \"@theokit/gateway\";\n\n/** The most characters one WhatsApp message carries here; also the splitter window. */\nexport const WHATSAPP_MAX_TEXT = 4096;\n\n/** Split `text` into chunks of at most `WHATSAPP_MAX_TEXT` characters. */\nexport function splitForWhatsApp(text: string): string[] {\n return chunkText(text, {\n limit: WHATSAPP_MAX_TEXT,\n boundaries: [\"\\n\\n\", \"\\n\", \" \"],\n lastResort: \"last-boundary\",\n surrogateGuard: true,\n stripLeading: /^\\s+/,\n trimParts: true,\n keepTableRows: true,\n });\n}\n","/**\n * `WhatsAppAdapter` — WhatsApp platform adapter for `@theokit/gateway`\n * (Adoption Roadmap v1.4 #2; ADRs D303-D314).\n *\n * Multi-backend (Cloud + Web) — backend chosen via `WhatsAppAdapterOptions.backend`.\n * Backend-agnostic adapter delegates lifecycle + send + subscribe through the\n * `WhatsAppBackend` seam (D303).\n *\n * @public\n */\n\nimport {\n type AdapterCapabilities,\n BasePlatformAdapter,\n type MessageEvent as GatewayMessageEvent,\n type OutboundMessage,\n type SendResult,\n type WhatsAppMessageEvent,\n} from \"@theokit/gateway\";\nimport { parseAllowedSenders } from \"./allowlist.js\";\nimport { WhatsAppBaileysBackend } from \"./backend/baileys/index.js\";\nimport { WhatsAppCloudBackend } from \"./backend/cloud/index.js\";\nimport type { MetaWebhookEnvelope } from \"./backend/cloud/types.js\";\nimport { normalizeInboundMessages } from \"./backend/cloud/webhook.js\";\nimport { WhatsAppWebBackend } from \"./backend/web/index.js\";\nimport type {\n WhatsAppBackend,\n WhatsAppInboundEvent,\n WhatsAppStatusReceipt,\n} from \"./backend-types.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { isForAnotherNumber } from \"./foreign-number.js\";\nimport { digitsOnly, type InboundRules } from \"./inbound-rules.js\";\nimport { decideForOwnNumber, requireOwnPhoneNumberId } from \"./own-number.js\";\nimport { refuseAttachments } from \"./refuse-attachments.js\";\nimport { splitForWhatsApp, WHATSAPP_MAX_TEXT } from \"./split.js\";\nimport type {\n WhatsAppAdapterCommonOptions,\n WhatsAppAdapterOptions,\n WhatsAppBaileysConfig,\n WhatsAppCloudConfig,\n WhatsAppWebConfig,\n} from \"./types.js\";\n\nexport type {\n WhatsAppAdapterCommonOptions,\n WhatsAppAdapterOptions,\n WhatsAppBaileysConfig,\n WhatsAppCloudConfig,\n WhatsAppWebConfig,\n} from \"./types.js\";\nexport { digitsOnly };\n\n/**\n * Fail at the boundary when a required option is missing or blank.\n *\n * A factory that returns an adapter with an empty token has moved the error away from its\n * cause: the stack then names a send, and the mistake was in construction\n * (`rules/error-handling.md` § 2).\n */\nfunction requireNonEmpty(entries: ReadonlyArray<readonly [string, string | undefined]>): void {\n for (const [name, value] of entries) {\n if (value === undefined || value.trim().length === 0) {\n throw new ConfigurationError({\n code: \"missing_option\",\n message: `gateway-whatsapp: ${name} is required and must not be empty.`,\n });\n }\n }\n}\n\n/**\n * Adapter facade. Implements `BasePlatformAdapter` (D172).\n *\n * Use `WhatsAppAdapter.fromCloud(config)` or `WhatsAppAdapter.fromWeb(config)`. The\n * constructor stays available for tests and for a backend of your own.\n */\nexport class WhatsAppAdapter extends BasePlatformAdapter {\n override get capabilities(): AdapterCapabilities {\n return { ...super.capabilities, maxMessageChars: WHATSAPP_MAX_TEXT, threads: false };\n }\n\n readonly platform = \"whatsapp\" as const;\n private readonly backendImpl: WhatsAppBackend;\n /**\n * The bot's number, digits only. Kept as its own field because the documented construction\n * path is tested by reading it (`fromCloud` defaulting it to the phone number id).\n */\n private readonly botPhoneId: string;\n /** The sender allowlist and group rule the inbound path decides by. */\n private readonly rules: InboundRules;\n /**\n * The Cloud phone number id this adapter answers for, read from the backend's declared\n * `phoneNumberId` at construction (so `fromCloud`, `new WhatsAppAdapter(new WhatsAppCloudBackend(...))`\n * and any backend declaring the field decide alike), `undefined` for a backend that declares none.\n * Meta signs every number of one app with one secret, so a signed message is only this adapter's\n * when its `phoneNumberId` is this one.\n */\n private readonly ownPhoneNumberId: string | undefined;\n /** Foreign phone number id endings already named on stderr, so each is reported once. */\n private readonly reportedForeignNumbers = new Set<string>();\n /** The rules both inbound paths share; `onInbound` skips the precondition (see `decideForOwnNumber`). */\n private readonly decide = (inbound: WhatsAppInboundEvent): WhatsAppMessageEvent | undefined =>\n decideForOwnNumber(inbound, this.ownPhoneNumberId, this.reportedForeignNumbers, this.rules);\n /** Mirrors the sibling adapters: guards connect() against opening a second session. */\n private connected = false;\n private handler?: (event: GatewayMessageEvent) => Promise<void>;\n private statusHandler?: (receipt: WhatsAppStatusReceipt) => Promise<void>;\n\n /** Whether the \"this platform carries no format flag\" warning has already been emitted. */\n private warnedAboutFormat = false;\n\n /**\n * Say, once, that a declared `format` has nowhere to go on this platform.\n *\n * WhatsApp's emphasis is INLINE — `*bold*`, `_italic_` — carried in the message text itself,\n * with no field on the request to set and no escape sequence to suppress it. So a caller\n * declaring `markdown` has already put the syntax in the text, and one declaring `html` is\n * asking for something the platform does not have.\n *\n * Reading the field is what turns a silent discard into a stated one — the swallowed-error\n * shape `rules/error-handling.md` refuses.\n *\n * @internal\n */\n private warnFormatUnsupported(format: string | undefined): void {\n // The \"is there anything to say\" question lives here rather than at the call site: a\n // `sendMessage` already at its complexity limit should ask one thing, not three.\n if (format === undefined || format === \"plain\") return;\n if (this.warnedAboutFormat) return;\n this.warnedAboutFormat = true;\n process.stderr.write(\n `[whatsapp] format=\"${format}\" was declared, and WhatsApp cannot carry it as a flag — ` +\n \"its emphasis is inline in the text. Sending as-is; this is logged once.\\n\",\n );\n }\n\n // EC-H: track unsubscribe handles so onInbound REPLACES instead of stacks.\n private inboundUnsubscribe?: () => void;\n private statusUnsubscribe?: () => void;\n\n /**\n * Build an adapter from a discriminated configuration.\n *\n * The entry point for configuration that arrives as **data** — read from a file, an\n * environment, or a tenant record — where the backend is a string rather than a decision\n * made in code. `fromCloud` / `fromWeb` are the direct forms when the choice is already\n * known at the call site.\n *\n * This is what `WhatsAppAdapterOptions` exists for. Until it had this consumer the union\n * was exported, documented and inert, which is the defect #47 was filed about, and the\n * first attempt at closing that issue left it inert — the factories took the config halves\n * directly and never the union.\n *\n * @throws {ConfigurationError} when a required option is missing or empty.\n * @public\n */\n static from(\n options: WhatsAppAdapterOptions,\n common: WhatsAppAdapterCommonOptions = {},\n ): WhatsAppAdapter {\n switch (options.backend) {\n case \"cloud\":\n return WhatsAppAdapter.fromCloud(options.cloud, common);\n case \"web\":\n return WhatsAppAdapter.fromWeb(options.web, common);\n case \"baileys\":\n return WhatsAppAdapter.fromBaileys(options.baileys, common);\n }\n }\n\n /**\n * Build a Baileys adapter.\n *\n * Unofficial, and no amount of code changes that: it automates a WhatsApp Web session,\n * which Meta's terms do not sanction and which can get a number banned. Use a number\n * created for this, never a personal one. Prefer {@link WhatsAppAdapter.fromCloud} unless\n * the number has no Cloud API access.\n *\n * Unlike {@link WhatsAppAdapter.fromWeb} it embeds no browser — it speaks the multi-device\n * protocol over a WebSocket. `baileys` is an optional peer dependency; it is loaded lazily\n * at connect, so a consumer who never calls this never needs it installed.\n *\n * `botPhoneId` has nothing to default from here, so leaving it unset while `requireMention`\n * is on (its default) drops every group message. The adapter logs when it does.\n *\n * @throws {ConfigurationError} when `sessionDir` is missing or empty.\n * @public\n */\n static fromBaileys(\n baileys: WhatsAppBaileysConfig,\n opts: WhatsAppAdapterCommonOptions = {},\n ): WhatsAppAdapter {\n requireNonEmpty([[\"sessionDir\", baileys.sessionDir]]);\n return new WhatsAppAdapter(\n new WhatsAppBaileysBackend({\n sessionDir: baileys.sessionDir,\n ...(baileys.connectTimeoutMs !== undefined\n ? { connectTimeoutMs: baileys.connectTimeoutMs }\n : {}),\n ...(baileys.sendTimeoutMs !== undefined ? { sendTimeoutMs: baileys.sendTimeoutMs } : {}),\n ...(baileys.onQr !== undefined ? { onQr: baileys.onQr } : {}),\n }),\n opts,\n );\n }\n\n /**\n * Build a Cloud-API adapter.\n *\n * The construction path this package's docblock has named since it was written, and which\n * did not exist until #47 — a consumer following the only guidance the package gave wrote\n * code that would not compile.\n *\n * Prefer it over the constructor: it keeps `WhatsAppCloudBackend` an implementation detail\n * of this package rather than something every consumer imports and assembles.\n *\n * @throws {ConfigurationError} when a required credential is missing or empty.\n * @public\n */\n static fromCloud(\n cloud: WhatsAppCloudConfig,\n opts: WhatsAppAdapterCommonOptions = {},\n ): WhatsAppAdapter {\n // `appSecret` is deliberately NOT required: it verifies inbound webhook signatures\n // (`backend/cloud/index.ts`) and outbound never reads it. This repository's own\n // integration suite passes `\"\"` for exactly that reason, so requiring it would have\n // locked an outbound-only consumer out of the path this factory exists to offer.\n requireNonEmpty([\n [\"accessToken\", cloud.accessToken],\n [\"phoneNumberId\", cloud.phoneNumberId],\n ]);\n // INFO-10: an empty apiVersion yields `https://graph.facebook.com//<id>`, because the\n // client's `?? \"v18.0\"` does not catch `\"\"`. Absent is fine; blank is a mistake.\n if (cloud.apiVersion !== undefined) {\n requireNonEmpty([[\"apiVersion\", cloud.apiVersion]]);\n }\n return new WhatsAppAdapter(\n new WhatsAppCloudBackend({\n accessToken: cloud.accessToken,\n phoneNumberId: cloud.phoneNumberId,\n appSecret: cloud.appSecret,\n ...(cloud.apiVersion !== undefined ? { apiVersion: cloud.apiVersion } : {}),\n }),\n { ...opts, botPhoneId: opts.botPhoneId ?? cloud.phoneNumberId },\n );\n }\n\n /**\n * Build a WhatsApp-Web adapter.\n *\n * Unofficial: it drives a real WhatsApp Web session through a browser, which Meta's terms\n * do not sanction and which can get a number banned. It also needs a browser this package\n * does not install. Prefer {@link WhatsAppAdapter.fromCloud} unless the number has no\n * Cloud API access.\n *\n * @throws {ConfigurationError} when `sessionId` is missing or empty.\n * @public\n */\n static fromWeb(web: WhatsAppWebConfig, opts: WhatsAppAdapterCommonOptions = {}): WhatsAppAdapter {\n requireNonEmpty([[\"sessionId\", web.sessionId]]);\n return new WhatsAppAdapter(\n new WhatsAppWebBackend({\n sessionId: web.sessionId,\n ...(web.bridgeScriptPath !== undefined ? { bridgeScriptPath: web.bridgeScriptPath } : {}),\n }),\n opts,\n );\n }\n\n /** Construct from a pre-built backend. Prefer the factories; this is for tests and for a custom backend. */\n constructor(backendImpl: WhatsAppBackend, opts: WhatsAppAdapterCommonOptions = {}) {\n super();\n this.backendImpl = backendImpl;\n this.ownPhoneNumberId = backendImpl.phoneNumberId;\n this.botPhoneId = digitsOnly(opts.botPhoneId ?? \"\");\n this.rules = {\n requireMention: opts.requireMention ?? true,\n botPhoneId: this.botPhoneId,\n // Absent and empty are different answers. Absent means the operator has not adopted the\n // filter, and delivery is unchanged. Empty means they configured one and named nobody, which\n // is a decision — `parseAllowedSenders` is fail-closed and honours it.\n allowedSenders:\n opts.allowedSenders === undefined ? undefined : parseAllowedSenders(opts.allowedSenders),\n };\n }\n\n /** Escape hatch (D180-style) for advanced features. */\n getBackend(): WhatsAppBackend {\n return this.backendImpl;\n }\n\n async connect(): Promise<boolean> {\n // Guard added 2026-08-17: this was the only adapter without one, so a second\n // connect() opened a second live WhatsApp session. Teams, SMS and Slack all\n // short-circuit here. Note it latches on SUCCESS only — a refused connect\n // must stay retryable, or one network blip becomes permanent.\n if (this.connected) return true;\n const ok = await this.backendImpl.connect();\n this.connected = ok;\n return ok;\n }\n\n async disconnect(): Promise<void> {\n this.connected = false;\n this.inboundUnsubscribe?.();\n this.inboundUnsubscribe = undefined;\n this.statusUnsubscribe?.();\n this.statusUnsubscribe = undefined;\n this.handler = undefined;\n this.statusHandler = undefined;\n await this.backendImpl.disconnect();\n }\n\n async sendMessage(out: OutboundMessage): Promise<SendResult> {\n return refuseAttachments(out) ?? this.sendText(out);\n }\n\n private async sendText(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"Empty text rejected.\" } };\n }\n // EC-8: split filters empty parts internally.\n // WhatsApp has no formatting flag: emphasis is inline in the text. Reading the field\n // is what makes the discard visible rather than silent.\n this.warnFormatUnsupported(out.format);\n const parts = splitForWhatsApp(out.text);\n if (parts.length === 0) {\n return {\n ok: false,\n error: { code: \"empty_text\", message: \"Text reduced to zero parts after splitting.\" },\n };\n }\n let lastWamid: string | undefined;\n const isGroup = out.channel.type === \"group\";\n for (const part of parts) {\n const r = await this.backendImpl.send({ to: out.channel.id, isGroup, text: part });\n if (!r.ok) {\n return {\n ok: false,\n error: { code: r.error?.code ?? \"unknown\", message: r.error?.message ?? \"Send failed.\" },\n };\n }\n lastWamid = r.wamid;\n }\n return lastWamid !== undefined ? { ok: true, messageId: lastWamid } : { ok: true };\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace any previous subscription.\n this.inboundUnsubscribe?.();\n this.handler = handler;\n\n // The bridge calls the handler it was created for, never `this.handler`: the backend hands a\n // signed batch whole to the bridge that accepted it, and re-reading the current handler per\n // message let a disconnect or unsubscribe inside the first message drop the rest of a batch\n // already answered 200. New batches stop at the backend, because `off()` removes the bridge.\n const off = this.backendImpl.onInbound(async (inbound) => {\n const event = this.decide(inbound);\n if (event === undefined) return;\n await handler(event);\n });\n this.inboundUnsubscribe = off;\n\n return () => {\n // Identity-guarded, like every sibling adapter. Without the guard this closure tore down\n // whatever subscription was CURRENT: `onInbound(A)` → `onInbound(B)` → A's stale `off()`\n // killed B's and nulled the handler, and the gateway went silent with no error. That is\n // the defect the cross-adapter contract exists to catch, and this adapter was exempted\n // from it by a comment claiming its mechanism gave \"the same guarantee\" — it had no\n // guard at all.\n if (this.handler === handler) {\n this.handler = undefined;\n off();\n this.inboundUnsubscribe = undefined;\n }\n };\n }\n\n /**\n * The event `onInbound` would hand its handler for this inbound message, or `undefined` when the\n * sender allowlist refuses it or the group rule drops it. A refusal writes the same stderr line\n * `onInbound` writes.\n *\n * It also drops a message addressed to another phone number id than the one the backend\n * declares (one app may serve several numbers under one secret), naming that id on stderr once.\n * A Cloud message on an adapter whose backend declares no `phoneNumberId` throws, as in\n * `toDeliverableEvents`; a WhatsApp Web or Baileys message has no number to compare.\n *\n * Pass the result to `deliver()`. Neither the backend nor the network is called.\n *\n * @throws {ConfigurationError} (`missing_phone_number_id`) for a Cloud message when the backend\n * declares no `phoneNumberId`.\n * @public\n */\n toDeliverableEvent(inbound: WhatsAppInboundEvent): WhatsAppMessageEvent | undefined {\n if (inbound.backend === \"cloud\") {\n requireOwnPhoneNumberId(this.ownPhoneNumberId, \"toDeliverableEvent\");\n }\n return this.decide(inbound);\n }\n\n /**\n * The events of one Meta Cloud webhook envelope that may reach the agent, in envelope order, with\n * the sender allowlist and the group rule applied. Status receipts and non-text messages yield no\n * event, so a status-only envelope returns `[]`. Each refused or dropped message writes the\n * same stderr line `onInbound` writes. Messages addressed to another `phone_number_id` are\n * dropped (see `toDeliverableEvent`).\n *\n * The adapter's backend must declare its `phoneNumberId`. `fromCloud` and any\n * `WhatsAppCloudBackend` do; a backend that wraps one by delegation must expose the field too.\n * Without it there is no number to compare, and every number of the Meta app would reach this\n * adapter's agent, so this method fails closed instead (docs/adr/0006).\n *\n * The route that receives the webhook verifies `X-Hub-Signature-256` first (with\n * `verifyWebhookSignature`, or theokit's `whatsapp()` route validator); this method does not. Meta redelivers on timeout, and\n * `event.whatsapp.wamid` is the key a route can use to ignore a repeat. Neither the backend nor\n * the network is called.\n *\n * @throws {ConfigurationError} (`missing_phone_number_id`) when the backend declares no\n * `phoneNumberId`.\n * @public\n */\n toDeliverableEvents(envelope: MetaWebhookEnvelope): WhatsAppMessageEvent[] {\n requireOwnPhoneNumberId(this.ownPhoneNumberId, \"toDeliverableEvents\");\n const events: WhatsAppMessageEvent[] = [];\n for (const inbound of normalizeInboundMessages(envelope)) {\n const event = this.toDeliverableEvent(inbound);\n if (event !== undefined) events.push(event);\n }\n return events;\n }\n\n /**\n * Status receipts (sent/delivered/read/failed). Adapter-specific (D307). A receipt names the\n * customer's number, so one addressed to another phone number id is dropped, as messages are.\n */\n onStatusReceipt(handler: (receipt: WhatsAppStatusReceipt) => Promise<void>): () => void {\n this.statusUnsubscribe?.();\n this.statusHandler = handler;\n const off = this.backendImpl.onStatusReceipt(async (r) => {\n if (isForAnotherNumber(r, this.ownPhoneNumberId, this.reportedForeignNumbers)) return;\n await this.statusHandler?.(r);\n });\n this.statusUnsubscribe = off;\n return () => {\n // Same identity guard, same reason. A stale unsubscribe must be a no-op.\n if (this.statusHandler === handler) {\n this.statusHandler = undefined;\n off();\n this.statusUnsubscribe = undefined;\n }\n };\n }\n\n /**\n * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).\n *\n * One line over `runHandler`, which owns the containment: a handler is user code, its throw is\n * named as the handler's failure rather than the platform's, and delivery continues.\n */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n return this.runHandler(this.handler, event);\n }\n}\n"]}
|