@12-apps/messaging 1.3.0 → 1.5.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/README.md +155 -0
- package/dist/chunk-RXJNLPY4.js +560 -0
- package/dist/chunk-RXJNLPY4.js.map +1 -0
- package/dist/inbound-guard/index.d.ts +254 -0
- package/dist/inbound-guard/index.js +913 -0
- package/dist/inbound-guard/index.js.map +1 -0
- package/dist/whatsapp/index.js +22 -536
- package/dist/whatsapp/index.js.map +1 -1
- package/dist/whatsapp-web/index.d.ts +369 -0
- package/dist/whatsapp-web/index.js +588 -0
- package/dist/whatsapp-web/index.js.map +1 -0
- package/package.json +9 -1
- package/src/inbound-guard/classification.ts +143 -0
- package/src/inbound-guard/decode.ts +128 -0
- package/src/inbound-guard/index.ts +55 -0
- package/src/inbound-guard/normalize.ts +164 -0
- package/src/inbound-guard/rules-infra.ts +200 -0
- package/src/inbound-guard/rules-phrases.ts +167 -0
- package/src/inbound-guard/rules-types.ts +61 -0
- package/src/inbound-guard/rules.ts +89 -0
- package/src/inbound-guard/screen.ts +165 -0
- package/src/inbound-guard/wrap.ts +163 -0
- package/src/whatsapp-web/adapter.ts +62 -0
- package/src/whatsapp-web/auth-state.ts +92 -0
- package/src/whatsapp-web/baileys-port.ts +146 -0
- package/src/whatsapp-web/envelope.ts +87 -0
- package/src/whatsapp-web/index.ts +36 -0
- package/src/whatsapp-web/media.ts +78 -0
- package/src/whatsapp-web/normalize.ts +183 -0
- package/src/whatsapp-web/session.ts +306 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/whatsapp/opt-out.ts","../../src/whatsapp/parse.ts","../../src/whatsapp/graph.ts","../../src/whatsapp/media.ts","../../src/whatsapp/signature.ts","../../src/whatsapp/signup.ts","../../src/whatsapp/index.ts"],"sourcesContent":["/**\n * The words that opt a contact out, by default: the Portuguese and English\n * stop words a WhatsApp user is told to send. A host replaces the list through\n * the adapter's config.\n */\nexport const DEFAULT_OPT_OUT_KEYWORDS: readonly string[] = [\"PARAR\", \"SAIR\", \"STOP\", \"CANCELAR\"];\n\n/** Upper case, accents stripped, surrounding space, punctuation and emoji trimmed. */\nfunction fold(text: string): string {\n return text\n .normalize(\"NFD\")\n .replace(/\\p{M}/gu, \"\")\n .replace(/^[^\\p{L}\\p{N}]+|[^\\p{L}\\p{N}]+$/gu, \"\")\n .toUpperCase();\n}\n\n/**\n * Is this text an opt-out? Only when the WHOLE message is one keyword —\n * case- and accent-insensitive, ignoring punctuation and emoji around it — so\n * \"parar\", \"PARAR.\" and \"Parar!\" opt out, and \"parar de enviar\" (a sentence,\n * maybe about something else) does not.\n */\nexport function isOptOutText(text: string, keywords: readonly string[] = DEFAULT_OPT_OUT_KEYWORDS): boolean {\n const folded = fold(text);\n return folded.length > 0 && keywords.some((keyword) => fold(keyword) === folded);\n}\n","import type {\n InboundContent,\n InboundMessageEvent,\n NormalizedEvent,\n OptOutEvent,\n ReceiptStatus,\n StatusEvent,\n} from \"../core/types\";\nimport { DEFAULT_OPT_OUT_KEYWORDS, isOptOutText } from \"./opt-out\";\n\n/**\n * The WhatsApp Cloud API webhook payload, read defensively: every field is\n * checked before it is trusted, an unknown shape is skipped rather than\n * thrown on, and only `JSON.parse` itself may throw (bytes that are not JSON).\n *\n * Shape: `{ object: \"whatsapp_business_account\", entry: [{ id, changes: [{\n * field, value: { metadata: { phone_number_id }, contacts, messages,\n * statuses, user_preferences } }] }] }`. Events come out in payload order.\n */\n\ntype Json = Record<string, unknown>;\n\nconst isObject = (value: unknown): value is Json => typeof value === \"object\" && value !== null && !Array.isArray(value);\nconst list = (value: unknown): Json[] => (Array.isArray(value) ? value.filter(isObject) : []);\nconst text = (value: unknown): string | null => (typeof value === \"string\" && value.length > 0 ? value : null);\n\n/** Meta's timestamps are Unix SECONDS, as a string. Null when absent or malformed. */\nfunction when(value: unknown): Date | null {\n const seconds = typeof value === \"string\" || typeof value === \"number\" ? Number(value) : Number.NaN;\n return Number.isFinite(seconds) && seconds > 0 ? new Date(seconds * 1000) : null;\n}\n\ninterface Change {\n value: Json;\n accountId: string;\n}\n\n/** Every `value` of every change, with the account it was delivered to. */\nfunction changes(payload: unknown): Change[] {\n if (!isObject(payload) || payload.object !== \"whatsapp_business_account\") return [];\n return list(payload.entry)\n .flatMap((entry) => list(entry.changes))\n .flatMap((change): Change[] => {\n const value = change.value;\n const accountId = isObject(value) && isObject(value.metadata) ? text(value.metadata.phone_number_id) : null;\n return isObject(value) && accountId ? [{ value, accountId }] : [];\n });\n}\n\n/** One reader per message `type`; null when the type's object is missing or malformed. */\nconst CONTENT_READERS: Readonly<Record<string, (message: Json) => InboundContent | null>> = {\n text: (message) => {\n const body = isObject(message.text) ? text(message.text.body) : null;\n return body ? { kind: \"TEXT\", text: body } : null;\n },\n interactive: (message) => {\n const interactive = isObject(message.interactive) ? message.interactive : {};\n const reply = interactive.button_reply ?? interactive.list_reply;\n const id = isObject(reply) ? text(reply.id) : null;\n return isObject(reply) && id ? { kind: \"INTERACTIVE\", replyId: id, title: text(reply.title) ?? \"\" } : null;\n },\n // A quick-reply button on a template message.\n button: (message) => {\n if (!isObject(message.button)) return null;\n const title = text(message.button.text) ?? \"\";\n return { kind: \"INTERACTIVE\", replyId: text(message.button.payload) ?? title, title };\n },\n audio: (message) => {\n const id = isObject(message.audio) ? text(message.audio.id) : null;\n return isObject(message.audio) && id ? { kind: \"AUDIO\", mediaId: id, mimeType: text(message.audio.mime_type) } : null;\n },\n};\n\n/** The content of one message, by its `type`; anything unread is OTHER. */\nfunction contentOf(message: Json): InboundContent {\n const type = text(message.type) ?? \"unknown\";\n return CONTENT_READERS[type]?.(message) ?? { kind: \"OTHER\", channelType: type };\n}\n\n/** The words a person typed or tapped, for the opt-out check. */\nfunction wordsOf(content: InboundContent): string | null {\n if (content.kind === \"TEXT\") return content.text;\n if (content.kind === \"INTERACTIVE\") return content.title;\n return null;\n}\n\n/** The profile name Meta sends per sender, keyed by wa_id. */\nfunction contactNames(value: Json): Map<string, string> {\n const names = new Map<string, string>();\n for (const contact of list(value.contacts)) {\n const waId = text(contact.wa_id);\n const name = isObject(contact.profile) ? text(contact.profile.name) : null;\n if (waId && name) names.set(waId, name);\n }\n return names;\n}\n\nfunction messageEvent(\n message: Json,\n accountId: string,\n names: Map<string, string>,\n keywords: readonly string[],\n): InboundMessageEvent | null {\n const contactId = text(message.from);\n const externalId = text(message.id);\n const sentAt = when(message.timestamp);\n if (!contactId || !externalId || !sentAt) return null;\n const content = contentOf(message);\n const words = wordsOf(content);\n return {\n type: \"message\",\n accountId,\n contactId,\n contactName: names.get(contactId) ?? null,\n externalId,\n sentAt,\n content,\n optOut: words !== null && isOptOutText(words, keywords),\n };\n}\n\nfunction messageEvents(value: Json, accountId: string, keywords: readonly string[]): InboundMessageEvent[] {\n const names = contactNames(value);\n return list(value.messages).flatMap((message) => messageEvent(message, accountId, names, keywords) ?? []);\n}\n\nconst RECEIPTS: Readonly<Record<string, ReceiptStatus>> = {\n sent: \"SENT\",\n delivered: \"DELIVERED\",\n read: \"READ\",\n failed: \"FAILED\",\n};\n\n/** The first error of a failed status, as `code: title`. */\nfunction errorOf(status: Json): string | null {\n const [first] = list(status.errors);\n if (!first) return null;\n const code = first.code === undefined ? \"\" : String(first.code);\n const title = text(first.title) ?? text(first.message) ?? \"\";\n return [code, title].filter(Boolean).join(\": \") || null;\n}\n\nfunction statusEvents(value: Json, accountId: string): StatusEvent[] {\n const out: StatusEvent[] = [];\n for (const status of list(value.statuses)) {\n const externalId = text(status.id);\n const receipt = RECEIPTS[text(status.status) ?? \"\"];\n const at = when(status.timestamp);\n if (!externalId || !receipt || !at) continue;\n out.push({\n type: \"status\",\n accountId,\n externalId,\n status: receipt,\n at,\n contactId: text(status.recipient_id),\n error: receipt === \"FAILED\" ? errorOf(status) : null,\n callbackData: text(status.biz_opaque_callback_data),\n });\n }\n return out;\n}\n\n/** Meta's own opt-out: a `user_preferences` change whose value is `stop`. */\nfunction preferenceEvents(value: Json, accountId: string): OptOutEvent[] {\n const out: OptOutEvent[] = [];\n for (const preference of list(value.user_preferences)) {\n const contactId = text(preference.wa_id);\n const at = when(preference.timestamp);\n if (contactId && at && text(preference.value)?.toLowerCase() === \"stop\") {\n out.push({ type: \"opt_out\", accountId, contactId, at });\n }\n }\n return out;\n}\n\n/**\n * Every event in a WhatsApp webhook payload (already `JSON.parse`d): inbound\n * messages (with the opt-out keyword check), delivery receipts, and Meta's\n * own opt-out signal.\n */\nexport function parseWhatsAppPayload(\n payload: unknown,\n options: { optOutKeywords?: readonly string[] } = {},\n): NormalizedEvent[] {\n const keywords = options.optOutKeywords ?? DEFAULT_OPT_OUT_KEYWORDS;\n const out: NormalizedEvent[] = [];\n for (const { value, accountId } of changes(payload)) {\n out.push(...messageEvents(value, accountId, keywords), ...statusEvents(value, accountId), ...preferenceEvents(value, accountId));\n }\n return out;\n}\n\n/**\n * Only the delivery receipts of a WhatsApp webhook payload — for a host that\n * tracks receipts of messages it sends some other way (a platform\n * notification number) without mounting the connector.\n */\nexport function parseWhatsAppStatuses(payload: unknown): StatusEvent[] {\n return changes(payload).flatMap(({ value, accountId }) => statusEvents(value, accountId));\n}\n","import { ChannelSendFailure } from \"../core/channel\";\nimport type { OutboundContent } from \"../core/types\";\n\n/**\n * The only way the adapter reaches Meta: an injected fetch. The global\n * `fetch` satisfies it; a test answers it with a recording fake.\n *\n * A JSON call reads `text()` only. A media download also asks for\n * `redirect: \"manual\"` (a 3xx comes back as itself, never followed) and reads\n * the binary body through `body` (a stream, read up to the size cap) or, when\n * there is none, `arrayBuffer()`. All three are optional so a text-only fake\n * still satisfies the port.\n */\nexport type FetchPort = (url: string, init: FetchInit) => Promise<FetchResponse>;\n\nexport interface FetchInit {\n method: string;\n headers: Record<string, string>;\n body?: string;\n /** `manual` for a media download: a redirect is answered, never followed. */\n redirect?: \"manual\" | \"follow\" | \"error\";\n /** Aborts the call at a media download's deadline. */\n signal?: AbortSignal;\n}\n\nexport interface FetchResponse {\n status: number;\n text(): Promise<string>;\n arrayBuffer?(): Promise<ArrayBuffer>;\n /** The body as a stream; read chunk by chunk so an oversized one is cut off early. */\n body?: { getReader(): FetchBodyReader; cancel?(reason?: unknown): Promise<void> } | null;\n headers?: { get(name: string): string | null };\n}\n\nexport interface FetchBodyReader {\n read(): Promise<{ done: boolean; value?: Uint8Array }>;\n cancel(reason?: unknown): Promise<void>;\n}\n\n/**\n * The hosts Meta serves WhatsApp media from: the URL a media lookup returns is\n * `https://lookaside.fbsbx.com/whatsapp_business/attachments/?mid=…`, and the\n * CDN families behind it. `*.` matches any subdomain (not the bare domain).\n */\nexport const DEFAULT_META_MEDIA_HOSTS: readonly string[] = [\"lookaside.fbsbx.com\", \"*.fbcdn.net\", \"*.whatsapp.net\"];\n\n/** Where the Graph API is, and through what. Both numbers are config, never constants in the adapter. */\nexport interface GraphConfig {\n fetch: FetchPort;\n /** `https://graph.facebook.com` — no trailing slash needed. */\n baseUrl: string;\n /** `v23.0` — the Graph API version every call is pinned to. */\n apiVersion: string;\n /**\n * The hosts a media URL may point at; any other is refused before the token\n * is sent to it. Exact names, or `*.domain` for its subdomains. Default\n * {@link DEFAULT_META_MEDIA_HOSTS}.\n */\n mediaHosts?: readonly string[];\n}\n\n/** A Graph call that did not answer 2xx. Carries Meta's error code; never the token. */\nexport class GraphError extends ChannelSendFailure {\n readonly status: number;\n constructor(status: number, code: string, message: string) {\n super(code, message);\n this.name = \"GraphError\";\n this.status = status;\n }\n}\n\ntype Json = Record<string, unknown>;\n\ninterface GraphCall {\n method: \"GET\" | \"POST\";\n path: string;\n token?: string;\n query?: Record<string, string>;\n body?: unknown;\n redirect?: FetchInit[\"redirect\"];\n signal?: AbortSignal;\n}\n\n/** Drops trailing \"/\" characters in one linear pass (a regex here backtracks quadratically on library input). */\nfunction trimTrailingSlashes(value: string): string {\n let end = value.length;\n while (end > 0 && value.charCodeAt(end - 1) === 47) end -= 1;\n return end === value.length ? value : value.slice(0, end);\n}\n\n/** The URL and the request init of one call. The token travels in a header, never in the URL. */\nfunction requestOf(graph: GraphConfig, call: GraphCall) {\n const base = trimTrailingSlashes(graph.baseUrl);\n const query = call.query ? `?${new URLSearchParams(call.query).toString()}` : \"\";\n const headers: Record<string, string> = { accept: \"application/json\" };\n if (call.token) headers.authorization = `Bearer ${call.token}`;\n if (call.body !== undefined) headers[\"content-type\"] = \"application/json\";\n return {\n url: `${base}/${graph.apiVersion}/${call.path}${query}`,\n init: {\n method: call.method,\n headers,\n ...(call.body !== undefined ? { body: JSON.stringify(call.body) } : {}),\n ...(call.redirect ? { redirect: call.redirect } : {}),\n ...(call.signal ? { signal: call.signal } : {}),\n } satisfies FetchInit,\n };\n}\n\n/** A body as a JSON object; anything else (empty, HTML, an array) as `{}`. */\nfunction objectOf(raw: string): Json {\n try {\n const parsed: unknown = raw ? JSON.parse(raw) : {};\n return typeof parsed === \"object\" && parsed !== null && !Array.isArray(parsed) ? (parsed as Json) : {};\n } catch {\n return {};\n }\n}\n\n/** Meta's error envelope (`{ error: { code, message } }`) as a {@link GraphError}. */\nfunction graphErrorOf(status: number, json: Json): GraphError {\n const error = typeof json.error === \"object\" && json.error !== null ? (json.error as Json) : {};\n const code = error.code === undefined ? `HTTP_${status}` : String(error.code);\n const message = typeof error.message === \"string\" ? error.message : `Graph answered ${status}`;\n return new GraphError(status, code, message.slice(0, 300));\n}\n\n/** One Graph call; resolves to the parsed JSON body, or throws {@link GraphError}. */\nexport async function graphRequest(graph: GraphConfig, call: GraphCall): Promise<Json> {\n const { url, init } = requestOf(graph, call);\n const response = await graph.fetch(url, init);\n const json = objectOf(await response.text());\n if (response.status < 200 || response.status >= 300) throw graphErrorOf(response.status, json);\n return json;\n}\n\n/** The Cloud API body for one outbound message. */\nexport function messageBody(to: string, content: OutboundContent): Json {\n const base = { messaging_product: \"whatsapp\", recipient_type: \"individual\", to };\n if (content.kind === \"TEXT\") return { ...base, type: \"text\", text: { body: content.text, preview_url: false } };\n if (content.kind === \"BUTTONS\") {\n return {\n ...base,\n type: \"interactive\",\n interactive: {\n type: \"button\",\n body: { text: content.text },\n action: { buttons: content.buttons.map((button) => ({ type: \"reply\", reply: { id: button.id, title: button.title } })) },\n },\n };\n }\n return {\n ...base,\n type: \"interactive\",\n interactive: {\n type: \"list\",\n body: { text: content.text },\n action: {\n button: content.buttonLabel,\n sections: content.sections.map((section) => ({\n ...(section.title ? { title: section.title } : {}),\n rows: section.rows.map((row) => ({ id: row.id, title: row.title, ...(row.description ? { description: row.description } : {}) })),\n })),\n },\n },\n };\n}\n\n/** Send one message from a phone number; resolves to its wamid. */\nexport async function sendWhatsAppMessage(\n graph: GraphConfig,\n input: { token: string; phoneNumberId: string; to: string; content: OutboundContent },\n): Promise<{ externalId: string }> {\n const json = await graphRequest(graph, {\n method: \"POST\",\n path: `${encodeURIComponent(input.phoneNumberId)}/messages`,\n token: input.token,\n body: messageBody(input.to, input.content),\n });\n const [first] = Array.isArray(json.messages) ? (json.messages as Json[]) : [];\n const id = first && typeof first.id === \"string\" ? first.id : null;\n if (!id) throw new GraphError(200, \"NO_MESSAGE_ID\", \"Graph accepted the message but returned no id\");\n return { externalId: id };\n}\n","import { ChannelMediaFailure, DEFAULT_MEDIA_TIMEOUT_MS, isPositiveSafeInteger, type ChannelMedia } from \"../core/channel\";\nimport { DEFAULT_META_MEDIA_HOSTS, graphRequest, type FetchResponse, type GraphConfig } from \"./graph\";\n\n/**\n * A WhatsApp media download, the Cloud API way: `GET /{version}/{media-id}`\n * with the business token answers `{ url, mime_type, file_size }`, and a\n * `GET` of that URL with the same token answers the bytes.\n *\n * The token travels in the Authorization header only, and only to a Meta\n * media host over https: the URL comes from Meta, but it is still checked\n * against the configured hosts before the token is sent to it, and a redirect\n * is refused rather than followed to wherever it points. The size is capped\n * twice — the declared `file_size` before the download, the bytes actually\n * read during it — the whole download has a deadline, and the media lives\n * only in the returned memory.\n */\n\nconst OCTET_STREAM = \"application/octet-stream\";\n\n/** Does `host` match one allowlist entry: an exact name, or `*.domain` for its subdomains. */\nfunction hostAllowed(host: string, allowed: readonly string[]): boolean {\n return allowed.some((entry) => {\n const pattern = entry.toLowerCase();\n // \"*.fbcdn.net\" matches \"x.fbcdn.net\" through its \".fbcdn.net\" suffix, never \"fbcdn.net\" or \"evilfbcdn.net\".\n return pattern.startsWith(\"*.\") ? host.endsWith(pattern.slice(1)) : host === pattern;\n });\n}\n\n/** The media URL Meta returned, checked: https, no userinfo, an allowed host. */\nfunction checkedMediaUrl(raw: unknown, allowed: readonly string[]): string {\n if (typeof raw !== \"string\" || raw === \"\") throw new ChannelMediaFailure(\"NO_MEDIA_URL\", \"Graph returned no media url\");\n let url: URL;\n try {\n url = new URL(raw);\n } catch {\n throw new ChannelMediaFailure(\"MEDIA_URL_INVALID\", \"Graph returned a media url that does not parse\");\n }\n if (url.protocol !== \"https:\") throw new ChannelMediaFailure(\"MEDIA_URL_REFUSED\", \"the media url is not https\");\n if (url.username || url.password) throw new ChannelMediaFailure(\"MEDIA_URL_REFUSED\", \"the media url carries credentials\");\n if (url.port !== \"\") throw new ChannelMediaFailure(\"MEDIA_URL_REFUSED\", \"the media url names an explicit port\");\n if (!hostAllowed(url.hostname.toLowerCase(), allowed)) {\n throw new ChannelMediaFailure(\"MEDIA_HOST_REFUSED\", `the media host ${url.hostname} is not a Meta media host`);\n }\n return url.toString();\n}\n\nconst tooLarge = (size: number, maxBytes: number) =>\n new ChannelMediaFailure(\"TOO_LARGE\", `the media is ${size} bytes, over the ${maxBytes}-byte cap`);\n\n/** A declared size over the cap refuses the download before it starts. */\nfunction checkDeclaredSize(declared: unknown, maxBytes: number): void {\n const size = typeof declared === \"number\" ? declared : typeof declared === \"string\" ? Number(declared) : NaN;\n if (Number.isFinite(size) && size > maxBytes) throw tooLarge(size, maxBytes);\n}\n\n/** Concatenate the chunks read so far. */\nfunction joined(chunks: Uint8Array[], total: number): Uint8Array {\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.length;\n }\n return bytes;\n}\n\n/** The download's deadline: one abort signal for both calls, and a race for every read. */\ninterface Deadline {\n signal: AbortSignal;\n /** `promise`, or a `TIMEOUT` failure once the deadline passes — whichever comes first. */\n race<T>(promise: Promise<T>): Promise<T>;\n clear(): void;\n}\n\nconst timedOut = (timeoutMs: number) =>\n new ChannelMediaFailure(\"TIMEOUT\", `the media download did not finish within ${timeoutMs} ms`);\n\nfunction deadlineOf(timeoutMs: number): Deadline {\n const controller = new AbortController();\n let timer: ReturnType<typeof setTimeout> | undefined;\n const expired = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n controller.abort();\n reject(timedOut(timeoutMs));\n }, timeoutMs);\n });\n // The race below observes it; this only keeps an unobserved expiry from being reported unhandled.\n expired.catch(() => undefined);\n return {\n signal: controller.signal,\n race: async (promise) => {\n try {\n return await Promise.race([promise, expired]);\n } catch (error) {\n // A port that honours the signal rejects with its own abort error: it is the deadline all the same.\n throw controller.signal.aborted ? timedOut(timeoutMs) : error;\n }\n },\n clear: () => clearTimeout(timer),\n };\n}\n\n/** Release a body that will not be read; never throws. */\nfunction discardBody(response: FetchResponse): void {\n try {\n void Promise.resolve(response.body?.cancel?.()).catch(() => undefined);\n } catch {\n // A body that cannot even be cancelled is left to the garbage collector.\n }\n}\n\n/** Read a stream, cancelling it the moment it passes the cap or the deadline. */\nasync function readStreamCapped(response: FetchResponse, maxBytes: number, deadline: Deadline): Promise<Uint8Array> {\n const reader = response.body!.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n try {\n for (;;) {\n const { done, value } = await deadline.race(reader.read());\n if (done) break;\n if (!value) continue;\n total += value.length;\n if (total > maxBytes) throw tooLarge(total, maxBytes);\n chunks.push(value);\n }\n } catch (error) {\n void reader.cancel().catch(() => undefined);\n throw error;\n }\n return joined(chunks, total);\n}\n\n/** The body's bytes, never more than `maxBytes` of them — whatever the headers declared. */\nasync function readBodyCapped(response: FetchResponse, maxBytes: number, deadline: Deadline): Promise<Uint8Array> {\n const declared = response.headers?.get(\"content-length\");\n if (declared) {\n try {\n checkDeclaredSize(declared, maxBytes);\n } catch (error) {\n discardBody(response);\n throw error;\n }\n }\n if (response.body && typeof response.body.getReader === \"function\") return readStreamCapped(response, maxBytes, deadline);\n if (!response.arrayBuffer) throw new ChannelMediaFailure(\"NO_BINARY_BODY\", \"the fetch port cannot read a binary body\");\n // Only for a port with no stream: it reads the WHOLE body before the cap can be checked.\n const bytes = new Uint8Array(await deadline.race(response.arrayBuffer()));\n if (bytes.length > maxBytes) throw tooLarge(bytes.length, maxBytes);\n return bytes;\n}\n\n/** GET the media URL with the token in a header; a redirect or a non-2xx is refused, its body discarded. */\nasync function downloadFrom(graph: GraphConfig, url: string, token: string, deadline: Deadline): Promise<FetchResponse> {\n const response = await deadline.race(\n graph.fetch(url, {\n method: \"GET\",\n headers: { authorization: `Bearer ${token}`, accept: \"*/*\" },\n redirect: \"manual\",\n signal: deadline.signal,\n }),\n );\n if (response.status >= 200 && response.status < 300) return response;\n discardBody(response);\n if (response.status >= 300 && response.status < 400) {\n throw new ChannelMediaFailure(\"REDIRECT_REFUSED\", `the media download answered ${response.status}; redirects are not followed`);\n }\n throw new ChannelMediaFailure(`HTTP_${response.status}`, `the media download answered ${response.status}`);\n}\n\n/** A cap or deadline that would not bound anything (NaN, Infinity, 0, negative, fractional) is refused. */\nfunction checkLimits(maxBytes: number, timeoutMs: number): void {\n if (!isPositiveSafeInteger(maxBytes) || !isPositiveSafeInteger(timeoutMs)) {\n throw new ChannelMediaFailure(\"BAD_OPTIONS\", \"maxBytes and timeoutMs must be positive safe integers\");\n }\n}\n\n/** Download one WhatsApp media object into memory. */\nexport async function downloadWhatsAppMedia(\n graph: GraphConfig,\n input: { token: string; mediaId: string; maxBytes: number; timeoutMs?: number },\n): Promise<ChannelMedia> {\n const timeoutMs = input.timeoutMs ?? DEFAULT_MEDIA_TIMEOUT_MS;\n checkLimits(input.maxBytes, timeoutMs);\n const deadline = deadlineOf(timeoutMs);\n try {\n const meta = await deadline.race(\n graphRequest(graph, {\n method: \"GET\",\n path: encodeURIComponent(input.mediaId),\n token: input.token,\n redirect: \"manual\",\n signal: deadline.signal,\n }),\n );\n const url = checkedMediaUrl(meta.url, graph.mediaHosts ?? DEFAULT_META_MEDIA_HOSTS);\n checkDeclaredSize(meta.file_size, input.maxBytes);\n const response = await downloadFrom(graph, url, input.token, deadline);\n const bytes = await readBodyCapped(response, input.maxBytes, deadline);\n const declaredType = typeof meta.mime_type === \"string\" && meta.mime_type ? meta.mime_type : null;\n const mimeType = declaredType ?? response.headers?.get(\"content-type\") ?? OCTET_STREAM;\n return { bytes, mimeType, size: bytes.length };\n } finally {\n deadline.clear();\n }\n}\n","import { createHash, createHmac, timingSafeEqual } from \"node:crypto\";\n\n/**\n * Meta's webhook proofs, as standalone functions: the connector's WhatsApp\n * adapter uses them, and so can any other WhatsApp webhook a host runs (a\n * platform notification number's receipts), without mounting the connector.\n */\n\n/** The header Meta signs every webhook POST with. */\nexport const META_SIGNATURE_HEADER = \"x-hub-signature-256\";\n\nconst SIGNATURE = /^sha256=([0-9a-f]{64})$/i;\n\n/**\n * Does `signatureHeader` prove `rawBody` was signed with `appSecret`?\n *\n * HMAC-SHA256 over the RAW body bytes exactly as received (a re-serialized\n * JSON body never matches; hand the bytes, not a decoded string, where the\n * framework gives them), compared in constant time. Fails CLOSED: an empty\n * secret, a missing header, a header in any other shape, or a digest of the\n * wrong length is `false` — never an exception, never `true`.\n */\nexport function verifyMetaSignature(rawBody: string | Uint8Array, signatureHeader: string | null | undefined, appSecret: string): boolean {\n if (!appSecret || !signatureHeader) return false;\n const match = SIGNATURE.exec(signatureHeader.trim());\n if (!match) return false;\n const expected = createHmac(\"sha256\", appSecret).update(rawBody).digest();\n const given = Buffer.from(match[1]!, \"hex\");\n return given.length === expected.length && timingSafeEqual(given, expected);\n}\n\n/** What the subscription handshake answers. */\nexport type MetaHandshake = { ok: true; challenge: string } | { ok: false };\n\n/**\n * Meta's `GET` subscription handshake: `hub.mode=subscribe`, the\n * `hub.verify_token` configured on the app, and a `hub.challenge` to echo.\n * The token is compared in constant time; an empty configured token refuses\n * every handshake.\n */\nexport function verifyMetaSubscription(\n query: Readonly<Record<string, string | undefined>>,\n verifyToken: string,\n): MetaHandshake {\n const mode = query[\"hub.mode\"];\n const token = query[\"hub.verify_token\"];\n const challenge = query[\"hub.challenge\"];\n if (!verifyToken || mode !== \"subscribe\" || !token || !challenge) return { ok: false };\n // Digests of equal length, so the comparison leaks neither content nor length.\n const digest = (value: string) => createHash(\"sha256\").update(value, \"utf8\").digest();\n return timingSafeEqual(digest(token), digest(verifyToken)) ? { ok: true, challenge } : { ok: false };\n}\n","import { GraphError, graphRequest, type GraphConfig } from \"./graph\";\n\n/**\n * Embedded Signup, server half. The browser half (Meta's SDK popup) hands the\n * host a short-lived `code`; these three calls turn it into a connection:\n *\n * 1. {@link exchangeSignupCode} — the code for a business token;\n * 2. {@link readSignupAccounts} — which WhatsApp Business Accounts the token\n * was granted, and each one's phone numbers (id + display number);\n * 3. {@link subscribeAppToWaba} — subscribe the app to the chosen account's\n * webhooks, so its messages reach the connector.\n *\n * Then the host calls `engine.connect(...)` with the phone number id, the\n * display number and the token, which the engine seals. None of these\n * functions logs or returns anything but what is named.\n */\n\ntype Json = Record<string, unknown>;\n\n/** The app's own identity on Meta. The secret is the host's, read where it keeps secrets. */\nexport interface MetaAppCredentials {\n appId: string;\n appSecret: string;\n}\n\n/** Exchange Embedded Signup's code for a business integration token. */\nexport async function exchangeSignupCode(\n graph: GraphConfig,\n input: MetaAppCredentials & { code: string; redirectUri?: string },\n): Promise<{ accessToken: string }> {\n const json = await graphRequest(graph, {\n method: \"GET\",\n path: \"oauth/access_token\",\n query: {\n client_id: input.appId,\n client_secret: input.appSecret,\n code: input.code,\n ...(input.redirectUri ? { redirect_uri: input.redirectUri } : {}),\n },\n });\n if (typeof json.access_token !== \"string\" || json.access_token.length === 0) {\n throw new GraphError(200, \"NO_ACCESS_TOKEN\", \"Graph answered the code exchange without a token\");\n }\n return { accessToken: json.access_token };\n}\n\n/** One phone number of a WhatsApp Business Account. */\nexport interface SignupPhoneNumber {\n /** The phone_number_id: the connection's external account id. */\n id: string;\n /** What a person reads (`+55 11 98765-4321`): the connection's display address. */\n displayPhoneNumber: string;\n verifiedName: string | null;\n}\n\nexport interface SignupAccount {\n /** The WABA id: the connection's external parent id. */\n wabaId: string;\n phoneNumbers: SignupPhoneNumber[];\n}\n\n/**\n * The WhatsApp Business Accounts the token was granted (read from the token's\n * own granular scopes, with the app's token), and each one's phone numbers.\n */\nexport async function readSignupAccounts(\n graph: GraphConfig,\n input: MetaAppCredentials & { accessToken: string },\n): Promise<SignupAccount[]> {\n const debug = await graphRequest(graph, {\n method: \"GET\",\n path: \"debug_token\",\n query: { input_token: input.accessToken },\n token: `${input.appId}|${input.appSecret}`,\n });\n const data = typeof debug.data === \"object\" && debug.data !== null ? (debug.data as Json) : {};\n const scopes = Array.isArray(data.granular_scopes) ? (data.granular_scopes as Json[]) : [];\n const wabaIds = new Set(\n scopes\n .filter((scope) => scope.scope === \"whatsapp_business_management\" && Array.isArray(scope.target_ids))\n .flatMap((scope) => (scope.target_ids as unknown[]).filter((id): id is string => typeof id === \"string\")),\n );\n const accounts: SignupAccount[] = [];\n for (const wabaId of wabaIds) {\n accounts.push({ wabaId, phoneNumbers: await readPhoneNumbers(graph, wabaId, input.accessToken) });\n }\n return accounts;\n}\n\nasync function readPhoneNumbers(graph: GraphConfig, wabaId: string, accessToken: string): Promise<SignupPhoneNumber[]> {\n const json = await graphRequest(graph, {\n method: \"GET\",\n path: `${encodeURIComponent(wabaId)}/phone_numbers`,\n query: { fields: \"id,display_phone_number,verified_name\" },\n token: accessToken,\n });\n const rows = Array.isArray(json.data) ? (json.data as Json[]) : [];\n return rows\n .filter((row) => typeof row.id === \"string\" && typeof row.display_phone_number === \"string\")\n .map((row) => ({\n id: row.id as string,\n displayPhoneNumber: row.display_phone_number as string,\n verifiedName: typeof row.verified_name === \"string\" ? row.verified_name : null,\n }));\n}\n\n/** Subscribe the app to a WABA's webhooks. Resolves when Meta answers `success: true`. */\nexport async function subscribeAppToWaba(graph: GraphConfig, input: { wabaId: string; accessToken: string }): Promise<void> {\n const json = await graphRequest(graph, {\n method: \"POST\",\n path: `${encodeURIComponent(input.wabaId)}/subscribed_apps`,\n token: input.accessToken,\n });\n if (json.success !== true) throw new GraphError(200, \"NOT_SUBSCRIBED\", \"Graph did not confirm the subscription\");\n}\n","/**\n * `@12-apps/messaging/whatsapp` — the WhatsApp Cloud API channel adapter.\n *\n * `createWhatsAppAdapter(config)` is what a host hands the engine. The pieces\n * are exported on their own too: the signature check and the receipt parser\n * serve any WhatsApp webhook (a platform notification number), and the\n * Embedded Signup helpers serve the host's connect flow.\n *\n * `@12-apps/notifications` has its own WhatsApp transport, for one-way\n * notification messages. It is deliberately NOT reused here: this adapter\n * carries a conversation (inbound, the service window, opt-out, receipts),\n * which that transport has no model for.\n */\n\nimport { serviceWindowPolicy, type ChannelAdapter } from \"../core/channel\";\nimport { parseWhatsAppPayload } from \"./parse\";\nimport { sendWhatsAppMessage, type GraphConfig } from \"./graph\";\nimport { downloadWhatsAppMedia } from \"./media\";\nimport { META_SIGNATURE_HEADER, verifyMetaSignature, verifyMetaSubscription } from \"./signature\";\n\n/** The channel key every WhatsApp row carries. */\nexport const WHATSAPP_CHANNEL = \"whatsapp\";\n\n/** WhatsApp's customer service window: free-form messages only within 24 h of the contact's last message. */\nexport const WHATSAPP_SERVICE_WINDOW_MS = 24 * 60 * 60 * 1000;\n\nexport interface WhatsAppAdapterConfig {\n /** The Meta app's secret: every webhook POST is signed with it. Empty refuses every delivery. */\n appSecret: string;\n /** The token configured on the app's webhook subscription. Empty refuses every handshake. */\n verifyToken: string;\n /** The Graph API: fetch, base URL and version. */\n graph: GraphConfig;\n /** The whole-message words that opt a contact out. Default: PARAR, SAIR, STOP, CANCELAR. */\n optOutKeywords?: readonly string[];\n}\n\n/** The WhatsApp Cloud adapter. */\nexport function createWhatsAppAdapter(config: WhatsAppAdapterConfig): ChannelAdapter {\n return {\n kind: WHATSAPP_CHANNEL,\n handshake: (query) => verifyMetaSubscription(query, config.verifyToken),\n verify: ({ rawBody, header }) => verifyMetaSignature(rawBody, header(META_SIGNATURE_HEADER), config.appSecret),\n parse: (rawBody) =>\n parseWhatsAppPayload(JSON.parse(rawBody) as unknown, {\n ...(config.optOutKeywords ? { optOutKeywords: config.optOutKeywords } : {}),\n }),\n send: ({ credential, accountId, to, content }) =>\n sendWhatsAppMessage(config.graph, { token: credential, phoneNumberId: accountId, to, content }),\n fetchMedia: ({ credential, mediaId, maxBytes, timeoutMs }) =>\n downloadWhatsAppMedia(config.graph, { token: credential, mediaId, maxBytes, ...(timeoutMs !== undefined ? { timeoutMs } : {}) }),\n policy: serviceWindowPolicy(WHATSAPP_SERVICE_WINDOW_MS),\n };\n}\n\nexport { META_SIGNATURE_HEADER, verifyMetaSignature, verifyMetaSubscription, type MetaHandshake } from \"./signature\";\nexport { parseWhatsAppPayload, parseWhatsAppStatuses } from \"./parse\";\nexport { DEFAULT_OPT_OUT_KEYWORDS, isOptOutText } from \"./opt-out\";\nexport {\n DEFAULT_META_MEDIA_HOSTS,\n GraphError,\n graphRequest,\n messageBody,\n sendWhatsAppMessage,\n type FetchBodyReader,\n type FetchInit,\n type FetchPort,\n type FetchResponse,\n type GraphConfig,\n} from \"./graph\";\nexport { downloadWhatsAppMedia } from \"./media\";\nexport {\n exchangeSignupCode,\n readSignupAccounts,\n subscribeAppToWaba,\n type MetaAppCredentials,\n type SignupAccount,\n type SignupPhoneNumber,\n} from \"./signup\";\n"],"mappings":";;;;;;;;;;;;AAKO,IAAM,2BAA8C,CAAC,SAAS,QAAQ,QAAQ,UAAU;AAG/F,SAAS,KAAKA,OAAsB;AAClC,SAAOA,MACJ,UAAU,KAAK,EACf,QAAQ,WAAW,EAAE,EACrB,QAAQ,qCAAqC,EAAE,EAC/C,YAAY;AACjB;AANS;AAcF,SAAS,aA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AAA,IACrC,QAAQ;AAAA,IACR,MAAM,GAAG,mBAAmB,MAAM,MAAM,CAAC;AAAA,IACzC,OAAO,MAAM;AAAA,EACf,CAAC;AACD,MAAI,KAAK,YAAY,KAAM,OAAM,IAAI,WAAW,KAAK,kBAAkB,wCAAwC;AACjH;AAPsB;;;ACtFf,IAAM,mBAAmB;AAGzB,IAAM,6BAA6B,KAAK,KAAK,KAAK;AAclD,SAAS,sBAAsB,QAA+C;AACnF,SAAO;AAAA,IACL,MAAM;AAAA,IACN,WAAW,wBAAC,UAAU,uBAAuB,OAAO,OAAO,WAAW,GAA3D;AAAA,IACX,QAAQ,wBAAC,EAAE,SAAS,OAAO,MAAM,oBAAoB,SAAS,OAAO,qBAAqB,GAAG,OAAO,SAAS,GAArG;AAAA,IACR,OAAO,wBAAC,YACN,qBAAqB,KAAK,MAAM,OAAO,GAAc;AAAA,MACnD,GAAI,OAAO,iBAAiB,EAAE,gBAAgB,OAAO,eAAe,IAAI,CAAC;AAAA,IAC3E,CAAC,GAHI;AAAA,IAIP,MAAM,wBAAC,EAAE,YAAY,WAAW,IAAI,QAAQ,MAC1C,oBAAoB,OAAO,OAAO,EAAE,OAAO,YAAY,eAAe,WAAW,IAAI,QAAQ,CAAC,GAD1F;AAAA,IAEN,YAAY,wBAAC,EAAE,YAAY,SAAS,UAAU,UAAU,MACtD,sBAAsB,OAAO,OAAO,EAAE,OAAO,YAAY,SAAS,UAAU,GAAI,cAAc,SAAY,EAAE,UAAU,IAAI,CAAC,EAAG,CAAC,GADrH;AAAA,IAEZ,QAAQ,oBAAoB,0BAA0B;AAAA,EACxD;AACF;AAfgB;","names":["text"]}
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
import { s as OutboundContent, c as ChannelMedia, S as SendPolicy, a as ChannelAdapter, N as NormalizedEvent, n as InboundContent, v as StatusEvent, R as ReceiptStatus } from '../channel-CZjNEBLC.js';
|
|
2
|
+
|
|
3
|
+
/** `WAMessageKey`: Baileys' `proto.IMessageKey` plus the v7 LID alternates. */
|
|
4
|
+
interface BaileysMessageKey {
|
|
5
|
+
remoteJid?: string | null;
|
|
6
|
+
/** The same chat's other address: the phone-number JID when `remoteJid` is a LID, and back. */
|
|
7
|
+
remoteJidAlt?: string | null;
|
|
8
|
+
fromMe?: boolean | null;
|
|
9
|
+
id?: string | null;
|
|
10
|
+
participant?: string | null;
|
|
11
|
+
}
|
|
12
|
+
/** `WAMessage` (`proto.IWebMessageInfo`), the fields read. `message` is the raw `proto.IMessage`. */
|
|
13
|
+
interface BaileysMessage {
|
|
14
|
+
key: BaileysMessageKey;
|
|
15
|
+
message?: object | null;
|
|
16
|
+
messageTimestamp?: number | {
|
|
17
|
+
low: number;
|
|
18
|
+
high: number;
|
|
19
|
+
} | null;
|
|
20
|
+
pushName?: string | null;
|
|
21
|
+
/** `proto.WebMessageInfo.Status`: 0 ERROR, 1 PENDING, 2 SERVER_ACK, 3 DELIVERY_ACK, 4 READ, 5 PLAYED. */
|
|
22
|
+
status?: number | null;
|
|
23
|
+
}
|
|
24
|
+
/** One `messages.update` entry. */
|
|
25
|
+
interface BaileysMessageUpdate {
|
|
26
|
+
key: BaileysMessageKey;
|
|
27
|
+
update: {
|
|
28
|
+
status?: number | null;
|
|
29
|
+
} & Record<string, unknown>;
|
|
30
|
+
}
|
|
31
|
+
/** The close reason Baileys reports: a Boom, whose `output.statusCode` is the `DisconnectReason`. */
|
|
32
|
+
interface BaileysDisconnect {
|
|
33
|
+
error?: {
|
|
34
|
+
output?: {
|
|
35
|
+
statusCode?: number;
|
|
36
|
+
};
|
|
37
|
+
message?: string;
|
|
38
|
+
} | Error | null | undefined;
|
|
39
|
+
date?: Date;
|
|
40
|
+
}
|
|
41
|
+
interface BaileysConnectionUpdate {
|
|
42
|
+
connection?: "open" | "connecting" | "close";
|
|
43
|
+
lastDisconnect?: BaileysDisconnect;
|
|
44
|
+
qr?: string;
|
|
45
|
+
}
|
|
46
|
+
/** The events this layer listens to, by Baileys' own names. */
|
|
47
|
+
interface BaileysEventMap<Msg extends BaileysMessage = BaileysMessage> {
|
|
48
|
+
"connection.update": BaileysConnectionUpdate;
|
|
49
|
+
"creds.update": Record<string, unknown>;
|
|
50
|
+
"messages.upsert": {
|
|
51
|
+
messages: Msg[];
|
|
52
|
+
type: "notify" | "append" | string;
|
|
53
|
+
};
|
|
54
|
+
"messages.update": BaileysMessageUpdate[];
|
|
55
|
+
}
|
|
56
|
+
/** `SignalKeyStore`: keyed by category, then id. A null value deletes. */
|
|
57
|
+
interface BaileysKeyStore {
|
|
58
|
+
get(type: string, ids: string[]): Promise<Record<string, unknown>>;
|
|
59
|
+
set(data: Record<string, Record<string, unknown>>): Promise<void>;
|
|
60
|
+
}
|
|
61
|
+
/** `AuthenticationState`, as this layer builds it. `creds` and every key are Baileys' own values, opaque here. */
|
|
62
|
+
interface BaileysAuthState {
|
|
63
|
+
creds: object;
|
|
64
|
+
keys: BaileysKeyStore;
|
|
65
|
+
}
|
|
66
|
+
/** The socket `makeWASocket` returns, the members used. */
|
|
67
|
+
/** `Msg` is Baileys' own `WAMessage`, inferred from the module: messages go back to Baileys as they came. */
|
|
68
|
+
interface BaileysSocket<Msg extends BaileysMessage = BaileysMessage> {
|
|
69
|
+
ev: {
|
|
70
|
+
on<E extends keyof BaileysEventMap>(event: E, listener: (data: BaileysEventMap<Msg>[E]) => void): void;
|
|
71
|
+
};
|
|
72
|
+
/** The linked account, once open: `id` is `5511999999999:12@s.whatsapp.net`. */
|
|
73
|
+
user?: {
|
|
74
|
+
id?: string | null | undefined;
|
|
75
|
+
} | null | undefined;
|
|
76
|
+
sendMessage(jid: string, content: {
|
|
77
|
+
text: string;
|
|
78
|
+
}): Promise<Msg | undefined>;
|
|
79
|
+
requestPairingCode(phoneNumber: string): Promise<string>;
|
|
80
|
+
logout(msg?: string): Promise<void>;
|
|
81
|
+
end(error: Error | undefined): Promise<void> | void;
|
|
82
|
+
/** Asks the phone to re-upload expired media; passed to `downloadMediaMessage`. */
|
|
83
|
+
updateMediaMessage?(message: Msg): Promise<Msg>;
|
|
84
|
+
}
|
|
85
|
+
/** Baileys' `ILogger`: pino satisfies it. */
|
|
86
|
+
interface BaileysLogger {
|
|
87
|
+
level: string;
|
|
88
|
+
child(obj: Record<string, unknown>): BaileysLogger;
|
|
89
|
+
trace(obj: unknown, msg?: string): void;
|
|
90
|
+
debug(obj: unknown, msg?: string): void;
|
|
91
|
+
info(obj: unknown, msg?: string): void;
|
|
92
|
+
warn(obj: unknown, msg?: string): void;
|
|
93
|
+
error(obj: unknown, msg?: string): void;
|
|
94
|
+
}
|
|
95
|
+
/** The members of the Baileys MODULE this layer calls. `import * as baileys from "baileys"` satisfies it. */
|
|
96
|
+
/**
|
|
97
|
+
* `Auth` is Baileys' own `AuthenticationState` and `Msg` its `WAMessage`, inferred from the module the
|
|
98
|
+
* host passes. The layer builds it from the host's store, where the values are
|
|
99
|
+
* Baileys' own, serialized by its `BufferJSON`.
|
|
100
|
+
*/
|
|
101
|
+
interface BaileysModule<Auth = BaileysAuthState, Msg extends BaileysMessage = BaileysMessage> {
|
|
102
|
+
makeWASocket(config: {
|
|
103
|
+
auth: Auth;
|
|
104
|
+
logger?: BaileysLogger;
|
|
105
|
+
browser?: [string, string, string];
|
|
106
|
+
markOnlineOnConnect?: boolean;
|
|
107
|
+
syncFullHistory?: boolean;
|
|
108
|
+
}): BaileysSocket<Msg>;
|
|
109
|
+
initAuthCreds(): object;
|
|
110
|
+
BufferJSON: {
|
|
111
|
+
replacer(key: string, value: unknown): unknown;
|
|
112
|
+
reviver(key: string, value: unknown): unknown;
|
|
113
|
+
};
|
|
114
|
+
downloadMediaMessage(message: Msg, type: "buffer", options: Record<string, unknown>, ctx?: {
|
|
115
|
+
logger?: BaileysLogger;
|
|
116
|
+
reuploadRequest?: (message: Msg) => Promise<Msg>;
|
|
117
|
+
}): Promise<Uint8Array>;
|
|
118
|
+
/** Optional: rebuilds an app-state sync key read back from storage (Baileys' own file store does). */
|
|
119
|
+
proto?: {
|
|
120
|
+
Message?: {
|
|
121
|
+
AppStateSyncKeyData?: {
|
|
122
|
+
fromObject(value: unknown): unknown;
|
|
123
|
+
};
|
|
124
|
+
};
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
/** Baileys' `DisconnectReason` values this layer acts on. */
|
|
128
|
+
declare const DISCONNECT: {
|
|
129
|
+
/** The phone unlinked this device, or the session was logged out: never reconnect. */
|
|
130
|
+
readonly loggedOut: 401;
|
|
131
|
+
/** Another client took the session over. Reconnecting would fight it: stop. */
|
|
132
|
+
readonly connectionReplaced: 440;
|
|
133
|
+
/** The account is banned or the session is unusable: stop. */
|
|
134
|
+
readonly forbidden: 403;
|
|
135
|
+
/** Baileys asks for a fresh socket right after pairing: reconnect at once. */
|
|
136
|
+
readonly restartRequired: 515;
|
|
137
|
+
};
|
|
138
|
+
/** The close's `DisconnectReason`, or null when Baileys gave none. */
|
|
139
|
+
declare function disconnectCode(disconnect: BaileysDisconnect | undefined): number | null;
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* WHERE A LINKED SESSION'S KEYS LIVE. The host's, never the package's.
|
|
143
|
+
*
|
|
144
|
+
* A Baileys session is a linked device: its auth state (the account's
|
|
145
|
+
* identity and Signal keys) gives whoever holds it full access to the
|
|
146
|
+
* account, every chat included. The package therefore writes NOTHING itself:
|
|
147
|
+
* the host passes a store, and decides where it lives and how it is sealed
|
|
148
|
+
* (an encrypted column, a secrets manager, a 0600 file on the owner's
|
|
149
|
+
* machine). The package never logs a value, never puts one in an error.
|
|
150
|
+
*
|
|
151
|
+
* Values are opaque JSON text (Baileys' `BufferJSON`); keys are
|
|
152
|
+
* `creds` and `<category>-<id>`.
|
|
153
|
+
*/
|
|
154
|
+
interface AuthStateStore {
|
|
155
|
+
read(key: string): Promise<string | null>;
|
|
156
|
+
write(key: string, value: string): Promise<void>;
|
|
157
|
+
remove(key: string): Promise<void>;
|
|
158
|
+
/** Remove every key of this session. Optional: without it, a logout removes only `creds`, which already unlinks it. */
|
|
159
|
+
clear?(): Promise<void>;
|
|
160
|
+
}
|
|
161
|
+
/** An in-memory store: for tests, and for a session that may be lost at restart (it must pair again). */
|
|
162
|
+
declare function createMemoryAuthStateStore(): AuthStateStore & {
|
|
163
|
+
keys(): string[];
|
|
164
|
+
clear(): Promise<void>;
|
|
165
|
+
};
|
|
166
|
+
/**
|
|
167
|
+
* Baileys' auth state over a host store: the same recipe as Baileys' own
|
|
168
|
+
* `useMultiFileAuthState`, with the store in place of the folder. A store with
|
|
169
|
+
* no creds yet starts a NEW device (the session pairs); `saveCreds` must run on
|
|
170
|
+
* every `creds.update`.
|
|
171
|
+
*/
|
|
172
|
+
declare function loadAuthState(baileys: Pick<BaileysModule<unknown>, "initAuthCreds" | "BufferJSON" | "proto">, store: AuthStateStore): Promise<{
|
|
173
|
+
state: BaileysAuthState;
|
|
174
|
+
saveCreds: () => Promise<void>;
|
|
175
|
+
isNew: boolean;
|
|
176
|
+
}>;
|
|
177
|
+
/** Forget a session's keys, after a logout: the next start pairs a NEW device. */
|
|
178
|
+
declare function clearAuthState(store: AuthStateStore): Promise<void>;
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* ONE linked WhatsApp account, over Baileys: the socket, its pairing, its
|
|
182
|
+
* reconnects, and the bridge to the engine.
|
|
183
|
+
*
|
|
184
|
+
* Inbound, the session normalizes every live socket event and hands the host
|
|
185
|
+
* a raw body (`deliver`) that the host stores through `engine.receive(channel,
|
|
186
|
+
* rawBody)`, exactly as the webhook edge does for the Cloud API: the inbox,
|
|
187
|
+
* the processing job and the reconciliation sweep are the same. Outbound,
|
|
188
|
+
* the adapter sends through the session's socket.
|
|
189
|
+
*/
|
|
190
|
+
/** Where the session stands. `qr` and `pairing-code` wait for the person to link the device on their phone. */
|
|
191
|
+
type WhatsAppWebStatus = {
|
|
192
|
+
state: "idle";
|
|
193
|
+
} | {
|
|
194
|
+
state: "connecting";
|
|
195
|
+
}
|
|
196
|
+
/** Show `qr` as a QR code; WhatsApp › Linked devices › Link a device. It rotates: a new status replaces it. */
|
|
197
|
+
| {
|
|
198
|
+
state: "qr";
|
|
199
|
+
qr: string;
|
|
200
|
+
}
|
|
201
|
+
/** Type `code` on the phone: WhatsApp › Linked devices › Link with phone number. */
|
|
202
|
+
| {
|
|
203
|
+
state: "pairing-code";
|
|
204
|
+
code: string;
|
|
205
|
+
} | {
|
|
206
|
+
state: "open";
|
|
207
|
+
accountId: string;
|
|
208
|
+
} | {
|
|
209
|
+
state: "reconnecting";
|
|
210
|
+
attempt: number;
|
|
211
|
+
code: number | null;
|
|
212
|
+
}
|
|
213
|
+
/** The phone unlinked this device (or WhatsApp logged it out). The keys were cleared: the next start pairs again. */
|
|
214
|
+
| {
|
|
215
|
+
state: "logged-out";
|
|
216
|
+
code: number | null;
|
|
217
|
+
}
|
|
218
|
+
/** Stopped for good: another client took the session (440), the account is refused (403), or reconnects ran out. */
|
|
219
|
+
| {
|
|
220
|
+
state: "failed";
|
|
221
|
+
code: number | null;
|
|
222
|
+
reason: "replaced" | "forbidden" | "reconnects-exhausted" | "start-failed";
|
|
223
|
+
} | {
|
|
224
|
+
state: "stopped";
|
|
225
|
+
};
|
|
226
|
+
interface WhatsAppWebSessionConfig<Auth = BaileysAuthState, Msg extends BaileysMessage = BaileysMessage> {
|
|
227
|
+
/** The Baileys module the host installed: `import * as baileys from "baileys"`. */
|
|
228
|
+
baileys: BaileysModule<Auth, Msg>;
|
|
229
|
+
/** Where the linked device's keys live. The host's: see {@link AuthStateStore}. */
|
|
230
|
+
authStore: AuthStateStore;
|
|
231
|
+
/**
|
|
232
|
+
* Store one inbound raw body: `(rawBody) => engine.receive(channel, rawBody)`.
|
|
233
|
+
* Called in socket order, one at a time. A socket does not redeliver, so a
|
|
234
|
+
* throw is reported through `onError` and that body is lost.
|
|
235
|
+
*/
|
|
236
|
+
deliver(rawBody: string): Promise<unknown>;
|
|
237
|
+
/** Every status change. Show the QR or the pairing code from here. */
|
|
238
|
+
onStatus?(status: WhatsAppWebStatus): void;
|
|
239
|
+
/** A failure the session could not hand to a caller: a delivery or a creds save. Never carries a key. */
|
|
240
|
+
onError?(error: unknown, where: "deliver" | "save-creds" | "pairing-code"): void;
|
|
241
|
+
/** Pair with a code typed on the phone instead of a QR: the account's number, digits with country code. */
|
|
242
|
+
pairingPhoneNumber?: string;
|
|
243
|
+
/** Opt-out words, as the Cloud adapter's `optOutKeywords`. */
|
|
244
|
+
optOutKeywords?: readonly string[];
|
|
245
|
+
/** A pino-compatible logger for Baileys. Default: Baileys' own. */
|
|
246
|
+
logger?: BaileysLogger;
|
|
247
|
+
/** How the linked device is named on the phone: `[client, browser, version]`. */
|
|
248
|
+
browser?: [string, string, string];
|
|
249
|
+
/** Reconnects after an unexpected close. Default 5 attempts, from 2 s, doubling. */
|
|
250
|
+
reconnect?: {
|
|
251
|
+
maxAttempts?: number;
|
|
252
|
+
delayMs?: number;
|
|
253
|
+
};
|
|
254
|
+
/** How many recent audio messages are kept in memory for `downloadMedia`. Default 200. */
|
|
255
|
+
mediaCacheSize?: number;
|
|
256
|
+
/** For tests. */
|
|
257
|
+
now?(): Date;
|
|
258
|
+
sleep?(ms: number): Promise<void>;
|
|
259
|
+
}
|
|
260
|
+
interface WhatsAppWebSession {
|
|
261
|
+
/** Open the socket: resume the stored device, or pair a new one. Idempotent while running. */
|
|
262
|
+
start(): Promise<void>;
|
|
263
|
+
/** Close the socket and keep the keys: `start` resumes without pairing. */
|
|
264
|
+
stop(): Promise<void>;
|
|
265
|
+
/** Unlink this device on WhatsApp and clear its keys. */
|
|
266
|
+
logout(): Promise<void>;
|
|
267
|
+
status(): WhatsAppWebStatus;
|
|
268
|
+
/** The linked account's digits once open (`5511987654321`), else null. */
|
|
269
|
+
accountId(): string | null;
|
|
270
|
+
/** Send one message. Throws `ChannelSendFailure`. */
|
|
271
|
+
send(to: string, content: OutboundContent): Promise<{
|
|
272
|
+
externalId: string;
|
|
273
|
+
}>;
|
|
274
|
+
/** Download a recent inbound audio by its media id (the message id). Throws `ChannelMediaFailure`. */
|
|
275
|
+
downloadMedia(mediaId: string, options: {
|
|
276
|
+
maxBytes: number;
|
|
277
|
+
timeoutMs?: number;
|
|
278
|
+
}): Promise<ChannelMedia>;
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* The text a personal account sends for an outbound message. Reply buttons
|
|
282
|
+
* and lists are a Business API feature: here their choices become numbered
|
|
283
|
+
* lines under the text, and the contact's answer arrives as TEXT.
|
|
284
|
+
*/
|
|
285
|
+
declare function renderOutboundText(content: OutboundContent): string;
|
|
286
|
+
/** One linked WhatsApp account over Baileys. Nothing connects until `start()`. */
|
|
287
|
+
declare function createWhatsAppWebSession<Auth, Msg extends BaileysMessage>(config: WhatsAppWebSessionConfig<Auth, Msg>): WhatsAppWebSession;
|
|
288
|
+
|
|
289
|
+
interface WhatsAppWebAdapterConfig {
|
|
290
|
+
/**
|
|
291
|
+
* The session that serves an account: one session, or a lookup by the
|
|
292
|
+
* connection's account id (the linked number's digits). A session serves
|
|
293
|
+
* only the account it is linked to.
|
|
294
|
+
*/
|
|
295
|
+
sessions: WhatsAppWebSession | ((accountId: string) => WhatsAppWebSession | undefined);
|
|
296
|
+
/**
|
|
297
|
+
* The channel key. Default `whatsapp`, the Cloud adapter's: a host switches a
|
|
298
|
+
* number between the two transports by mounting one adapter or the other,
|
|
299
|
+
* and its connections and conversations stay where they are. Give another
|
|
300
|
+
* key (`whatsapp-web`) to run both side by side.
|
|
301
|
+
*/
|
|
302
|
+
kind?: string;
|
|
303
|
+
/**
|
|
304
|
+
* When free-form sends are allowed. Default: always. A personal account has
|
|
305
|
+
* no service window; that window is a rule of the Business API.
|
|
306
|
+
*/
|
|
307
|
+
policy?: SendPolicy;
|
|
308
|
+
}
|
|
309
|
+
/**
|
|
310
|
+
* The WhatsApp Web adapter: the same `ChannelAdapter` as the Cloud one, over
|
|
311
|
+
* a Baileys session instead of the Graph API.
|
|
312
|
+
*
|
|
313
|
+
* - `handshake` and `verify`: there is no webhook. The verify FAILS CLOSED,
|
|
314
|
+
* so the webhook route refuses any POST to this channel: inbound arrives
|
|
315
|
+
* only from the session's own socket, through `engine.receive`.
|
|
316
|
+
* - `parse` reads the session's envelope (normalized events, never Baileys'
|
|
317
|
+
* raw objects).
|
|
318
|
+
* - `send` and `fetchMedia` go through the session. The connection's
|
|
319
|
+
* credential is not used: the linked device's keys live in the session's
|
|
320
|
+
* auth store.
|
|
321
|
+
*/
|
|
322
|
+
declare function createWhatsAppWebAdapter(config: WhatsAppWebAdapterConfig): ChannelAdapter;
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* The raw body a session hands the engine's inbox.
|
|
326
|
+
*
|
|
327
|
+
* The inbox stores every delivery raw before processing it, and re-parses it
|
|
328
|
+
* on a retry. A socket has no HTTP body, so the session writes one: its
|
|
329
|
+
* already-normalized events, as JSON. Never Baileys' own message objects —
|
|
330
|
+
* they carry media keys and the full protobuf, and the inbox keeps what it
|
|
331
|
+
* is given.
|
|
332
|
+
*
|
|
333
|
+
* `{ "format": "whatsapp-web/1", "events": [...] }`, dates as ISO strings.
|
|
334
|
+
*/
|
|
335
|
+
declare const ENVELOPE_FORMAT = "whatsapp-web/1";
|
|
336
|
+
declare function encodeEnvelope(events: readonly NormalizedEvent[]): string;
|
|
337
|
+
/**
|
|
338
|
+
* An envelope's events, in order. Another format, or an event of an unknown
|
|
339
|
+
* shape, yields nothing for it; only bytes that are not JSON throw.
|
|
340
|
+
*/
|
|
341
|
+
declare function parseEnvelope(rawBody: string): NormalizedEvent[];
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* The contact's address, as the engine stores it. A phone-number JID becomes
|
|
345
|
+
* its digits (`5511987654321`), the same address the Cloud API's `wa_id` is.
|
|
346
|
+
* A contact WhatsApp only names by a LID keeps the whole LID JID
|
|
347
|
+
* (`123456@lid`): the send path routes it back as is. Null for anything that
|
|
348
|
+
* is not one person.
|
|
349
|
+
*/
|
|
350
|
+
declare function contactAddress(key: BaileysMessageKey): string | null;
|
|
351
|
+
/** The JID a send goes to, for an address `contactAddress` produced (or plain digits). */
|
|
352
|
+
declare function addressJid(address: string): string;
|
|
353
|
+
/** The message's content, or null to skip it. */
|
|
354
|
+
declare function contentOf(raw: unknown): InboundContent | null;
|
|
355
|
+
interface NormalizeOptions {
|
|
356
|
+
/** The whole-message words that opt a contact out. Default: the Cloud adapter's. */
|
|
357
|
+
optOutKeywords?: readonly string[];
|
|
358
|
+
}
|
|
359
|
+
/** One live `messages.upsert` → inbound message events. `accountId` is the linked account's digits. */
|
|
360
|
+
declare function normalizeUpsert(accountId: string, upsert: {
|
|
361
|
+
messages: readonly BaileysMessage[];
|
|
362
|
+
type: string;
|
|
363
|
+
}, options?: NormalizeOptions): NormalizedEvent[];
|
|
364
|
+
/** `proto.WebMessageInfo.Status` → a receipt. PENDING (1) and unknown values are not receipts. */
|
|
365
|
+
declare function receiptOf(status: unknown): ReceiptStatus | null;
|
|
366
|
+
/** One `messages.update` → receipts for the messages this account sent. `at` is when the socket saw it. */
|
|
367
|
+
declare function normalizeUpdates(accountId: string, updates: readonly BaileysMessageUpdate[], at: Date): StatusEvent[];
|
|
368
|
+
|
|
369
|
+
export { type AuthStateStore, type BaileysAuthState, type BaileysConnectionUpdate, type BaileysLogger, type BaileysMessage, type BaileysMessageKey, type BaileysMessageUpdate, type BaileysModule, type BaileysSocket, DISCONNECT, ENVELOPE_FORMAT, type NormalizeOptions, type WhatsAppWebAdapterConfig, type WhatsAppWebSession, type WhatsAppWebSessionConfig, type WhatsAppWebStatus, addressJid, clearAuthState, contactAddress, contentOf, createMemoryAuthStateStore, createWhatsAppWebAdapter, createWhatsAppWebSession, disconnectCode, encodeEnvelope, loadAuthState, normalizeUpdates, normalizeUpsert, parseEnvelope, receiptOf, renderOutboundText };
|