@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.
@@ -0,0 +1,87 @@
1
+ import type { InboundContent, NormalizedEvent, ReceiptStatus } from "../core/types";
2
+
3
+ /**
4
+ * The raw body a session hands the engine's inbox.
5
+ *
6
+ * The inbox stores every delivery raw before processing it, and re-parses it
7
+ * on a retry. A socket has no HTTP body, so the session writes one: its
8
+ * already-normalized events, as JSON. Never Baileys' own message objects —
9
+ * they carry media keys and the full protobuf, and the inbox keeps what it
10
+ * is given.
11
+ *
12
+ * `{ "format": "whatsapp-web/1", "events": [...] }`, dates as ISO strings.
13
+ */
14
+ export const ENVELOPE_FORMAT = "whatsapp-web/1";
15
+
16
+ export function encodeEnvelope(events: readonly NormalizedEvent[]): string {
17
+ return JSON.stringify({ format: ENVELOPE_FORMAT, events });
18
+ }
19
+
20
+ type Json = Record<string, unknown>;
21
+ const isObject = (value: unknown): value is Json => typeof value === "object" && value !== null && !Array.isArray(value);
22
+ const str = (value: unknown): string | null => (typeof value === "string" && value.length > 0 ? value : null);
23
+ const strOrNull = (value: unknown): string | null => (typeof value === "string" ? value : null);
24
+ const date = (value: unknown): Date | null => {
25
+ const parsed = typeof value === "string" ? new Date(value) : null;
26
+ return parsed && Number.isFinite(parsed.getTime()) ? parsed : null;
27
+ };
28
+
29
+ const RECEIPTS: readonly ReceiptStatus[] = ["SENT", "DELIVERED", "READ", "FAILED"];
30
+
31
+ const CONTENT: Readonly<Record<string, (value: Json) => InboundContent | null>> = {
32
+ TEXT: (value) => (typeof value.text === "string" ? { kind: "TEXT", text: value.text } : null),
33
+ INTERACTIVE: (value) => (str(value.replyId) ? { kind: "INTERACTIVE", replyId: value.replyId as string, title: strOrNull(value.title) ?? "" } : null),
34
+ AUDIO: (value) => (str(value.mediaId) ? { kind: "AUDIO", mediaId: value.mediaId as string, mimeType: strOrNull(value.mimeType) } : null),
35
+ OTHER: (value) => (str(value.channelType) ? { kind: "OTHER", channelType: value.channelType as string } : null),
36
+ };
37
+
38
+ function content(value: unknown): InboundContent | null {
39
+ if (!isObject(value) || typeof value.kind !== "string") return null;
40
+ return CONTENT[value.kind]?.(value) ?? null;
41
+ }
42
+
43
+ function messageEvent(value: Json, accountId: string): NormalizedEvent | null {
44
+ const contactId = str(value.contactId);
45
+ const externalId = str(value.externalId);
46
+ const sentAt = date(value.sentAt);
47
+ const body = content(value.content);
48
+ if (!contactId || !externalId || !sentAt || !body) return null;
49
+ return { type: "message", accountId, contactId, contactName: strOrNull(value.contactName), externalId, sentAt, content: body, optOut: value.optOut === true };
50
+ }
51
+
52
+ function statusEvent(value: Json, accountId: string): NormalizedEvent | null {
53
+ const externalId = str(value.externalId);
54
+ const at = date(value.at);
55
+ const status = RECEIPTS.find((receipt) => receipt === value.status);
56
+ if (!externalId || !at || !status) return null;
57
+ const optional = { contactId: strOrNull(value.contactId), error: strOrNull(value.error), callbackData: strOrNull(value.callbackData) };
58
+ return { type: "status", accountId, externalId, status, at, ...optional };
59
+ }
60
+
61
+ function optOutEvent(value: Json, accountId: string): NormalizedEvent | null {
62
+ const contactId = str(value.contactId);
63
+ const at = date(value.at);
64
+ return contactId && at ? { type: "opt_out", accountId, contactId, at } : null;
65
+ }
66
+
67
+ const EVENTS: Readonly<Record<string, (value: Json, accountId: string) => NormalizedEvent | null>> = {
68
+ message: messageEvent,
69
+ status: statusEvent,
70
+ opt_out: optOutEvent,
71
+ };
72
+
73
+ function event(value: unknown): NormalizedEvent | null {
74
+ if (!isObject(value) || typeof value.type !== "string") return null;
75
+ const accountId = str(value.accountId);
76
+ return accountId ? (EVENTS[value.type]?.(value, accountId) ?? null) : null;
77
+ }
78
+
79
+ /**
80
+ * An envelope's events, in order. Another format, or an event of an unknown
81
+ * shape, yields nothing for it; only bytes that are not JSON throw.
82
+ */
83
+ export function parseEnvelope(rawBody: string): NormalizedEvent[] {
84
+ const payload = JSON.parse(rawBody) as unknown;
85
+ if (!isObject(payload) || payload.format !== ENVELOPE_FORMAT || !Array.isArray(payload.events)) return [];
86
+ return payload.events.map(event).filter((parsed): parsed is NormalizedEvent => parsed !== null);
87
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * `@12-apps/messaging/whatsapp-web` — WhatsApp over the WhatsApp Web protocol
3
+ * (a linked device, through Baileys), as an alternative transport to the
4
+ * official Cloud API adapter at `@12-apps/messaging/whatsapp`.
5
+ *
6
+ * UNOFFICIAL. WhatsApp's terms forbid unofficial clients and the number used
7
+ * may be banned. A linked session's keys give full access to the account:
8
+ * where they live is the host's decision (`AuthStateStore`), and the package
9
+ * never logs them. See the README's "WhatsApp Web (unofficial)" section.
10
+ *
11
+ * Baileys is NOT a dependency: the host installs `baileys` and passes the
12
+ * module in. Nothing here loads it.
13
+ */
14
+ export { createWhatsAppWebAdapter, type WhatsAppWebAdapterConfig } from "./adapter";
15
+ export {
16
+ createWhatsAppWebSession,
17
+ renderOutboundText,
18
+ type WhatsAppWebSession,
19
+ type WhatsAppWebSessionConfig,
20
+ type WhatsAppWebStatus,
21
+ } from "./session";
22
+ export { clearAuthState, createMemoryAuthStateStore, loadAuthState, type AuthStateStore } from "./auth-state";
23
+ export { ENVELOPE_FORMAT, encodeEnvelope, parseEnvelope } from "./envelope";
24
+ export { addressJid, contactAddress, contentOf, normalizeUpdates, normalizeUpsert, receiptOf, type NormalizeOptions } from "./normalize";
25
+ export {
26
+ DISCONNECT,
27
+ disconnectCode,
28
+ type BaileysAuthState,
29
+ type BaileysConnectionUpdate,
30
+ type BaileysLogger,
31
+ type BaileysMessage,
32
+ type BaileysMessageKey,
33
+ type BaileysMessageUpdate,
34
+ type BaileysModule,
35
+ type BaileysSocket,
36
+ } from "./baileys-port";
@@ -0,0 +1,78 @@
1
+ import { ChannelMediaFailure, DEFAULT_MEDIA_TIMEOUT_MS, type ChannelMedia } from "../core/channel";
2
+ import type { BaileysLogger, BaileysMessage, BaileysModule } from "./baileys-port";
3
+ import { longNumber, unwrapMessage } from "./normalize";
4
+
5
+ /**
6
+ * Inbound audio, for `fetchMedia`. A Baileys media message is downloaded from
7
+ * the message itself (its URL and media key), so the session keeps the most
8
+ * recent audio messages IN MEMORY, by message id, and nothing else: the media
9
+ * key never reaches the inbox or the host's database. After a restart an
10
+ * older audio is `NOT_FOUND`.
11
+ */
12
+ export class AudioCache<Msg extends BaileysMessage> {
13
+ private readonly messages = new Map<string, Msg>();
14
+
15
+ constructor(private readonly size: number) {}
16
+
17
+ /** Keep `message` if it is an audio. The oldest is dropped past the size. */
18
+ remember(message: Msg): void {
19
+ const id = message.key?.id;
20
+ if (!id || !audioOf(message)) return;
21
+ this.messages.set(id, message);
22
+ while (this.messages.size > this.size) this.messages.delete(this.messages.keys().next().value as string);
23
+ }
24
+
25
+ get(id: string): Msg | undefined {
26
+ return this.messages.get(id);
27
+ }
28
+ }
29
+
30
+ /** The audio content of a message, unwrapped, or null. */
31
+ export function audioOf(message: BaileysMessage): Record<string, unknown> | null {
32
+ const audio = unwrapMessage(message.message).audioMessage;
33
+ return typeof audio === "object" && audio !== null ? (audio as Record<string, unknown>) : null;
34
+ }
35
+
36
+ async function withDeadline<T>(work: Promise<T>, ms: number): Promise<T> {
37
+ let timer: ReturnType<typeof setTimeout> | undefined;
38
+ const deadline = new Promise<never>((_, reject) => {
39
+ timer = setTimeout(() => reject(new ChannelMediaFailure("TIMEOUT", `media download passed its ${ms} ms deadline`)), ms);
40
+ });
41
+ try {
42
+ return await Promise.race([work, deadline]);
43
+ } finally {
44
+ clearTimeout(timer);
45
+ }
46
+ }
47
+
48
+ function refuseOverCap(size: number | null, maxBytes: number, what: "declares" | "is"): void {
49
+ if (size !== null && size > maxBytes) throw new ChannelMediaFailure("TOO_LARGE", `the media ${what} ${size} bytes, over ${maxBytes}`);
50
+ }
51
+
52
+ export interface DownloadAudioInput<Msg extends BaileysMessage> {
53
+ baileys: Pick<BaileysModule<unknown, Msg>, "downloadMediaMessage">;
54
+ message: Msg | undefined;
55
+ maxBytes: number;
56
+ timeoutMs?: number | undefined;
57
+ logger?: BaileysLogger | undefined;
58
+ reupload?: ((message: Msg) => Promise<Msg>) | undefined;
59
+ }
60
+
61
+ /** Download one cached audio into memory. Throws `ChannelMediaFailure`; never stores anything. */
62
+ export async function downloadAudio<Msg extends BaileysMessage>(input: DownloadAudioInput<Msg>): Promise<ChannelMedia> {
63
+ const audio = input.message ? audioOf(input.message) : null;
64
+ if (!input.message || !audio) throw new ChannelMediaFailure("NOT_FOUND", "no recent audio with this id in this session");
65
+ refuseOverCap(longNumber(audio.fileLength as number | null), input.maxBytes, "declares");
66
+ const ctx = {
67
+ ...(input.logger ? { logger: input.logger } : {}),
68
+ ...(input.reupload ? { reuploadRequest: input.reupload } : {}),
69
+ };
70
+ const bytes = await withDeadline(input.baileys.downloadMediaMessage(input.message, "buffer", {}, ctx), input.timeoutMs ?? DEFAULT_MEDIA_TIMEOUT_MS).catch(
71
+ (error: unknown) => {
72
+ throw error instanceof ChannelMediaFailure ? error : new ChannelMediaFailure("DOWNLOAD_FAILED", "the media could not be downloaded");
73
+ },
74
+ );
75
+ refuseOverCap(bytes.length, input.maxBytes, "is");
76
+ const mimeType = typeof audio.mimetype === "string" && audio.mimetype ? audio.mimetype : "application/octet-stream";
77
+ return { bytes: new Uint8Array(bytes), mimeType, size: bytes.length };
78
+ }
@@ -0,0 +1,183 @@
1
+ import type { InboundContent, NormalizedEvent, ReceiptStatus, StatusEvent } from "../core/types";
2
+ import { DEFAULT_OPT_OUT_KEYWORDS, isOptOutText } from "../whatsapp/opt-out";
3
+ import type { BaileysMessage, BaileysMessageKey, BaileysMessageUpdate, LongLike } from "./baileys-port";
4
+
5
+ /**
6
+ * Baileys' socket events → the engine's normalized events: the SAME
7
+ * `NormalizedEvent`s the Cloud webhook's parser produces, so the inbox, the
8
+ * dedupe, the conversations and the retention cannot tell the transports apart.
9
+ *
10
+ * Read defensively: an unknown shape is skipped, never thrown on. What is
11
+ * left out, on purpose:
12
+ * - groups, broadcast lists, Status and channels (`@g.us`, `@broadcast`,
13
+ * `@newsletter`): the engine's conversation is one contact;
14
+ * - messages the account sent itself (`fromMe`): from another linked device,
15
+ * or the echo of a send of ours, which the engine already recorded;
16
+ * - history sync (`messages.upsert` of type `append`): only live messages;
17
+ * - protocol messages (a deletion, an edit, a key distribution).
18
+ */
19
+
20
+ type Json = Record<string, unknown>;
21
+ const isObject = (value: unknown): value is Json => typeof value === "object" && value !== null && !Array.isArray(value);
22
+ const text = (value: unknown): string | null => (typeof value === "string" && value.length > 0 ? value : null);
23
+
24
+ const PN_SUFFIX = "@s.whatsapp.net";
25
+ const LID_SUFFIX = "@lid";
26
+
27
+ /** A JID's user part, without the device (`5511…:12@s.whatsapp.net` → `5511…`). */
28
+ export function jidUser(jid: string): string {
29
+ const user = jid.slice(0, jid.indexOf("@") >= 0 ? jid.indexOf("@") : jid.length);
30
+ const colon = user.indexOf(":");
31
+ return colon >= 0 ? user.slice(0, colon) : user;
32
+ }
33
+
34
+ /**
35
+ * The contact's address, as the engine stores it. A phone-number JID becomes
36
+ * its digits (`5511987654321`), the same address the Cloud API's `wa_id` is.
37
+ * A contact WhatsApp only names by a LID keeps the whole LID JID
38
+ * (`123456@lid`): the send path routes it back as is. Null for anything that
39
+ * is not one person.
40
+ */
41
+ export function contactAddress(key: BaileysMessageKey): string | null {
42
+ const candidates = [key.remoteJid, key.remoteJidAlt].filter((jid): jid is string => typeof jid === "string");
43
+ const pn = candidates.find((jid) => jid.endsWith(PN_SUFFIX));
44
+ if (pn) return jidUser(pn) || null;
45
+ const lid = candidates.find((jid) => jid.endsWith(LID_SUFFIX));
46
+ return lid ? `${jidUser(lid)}${LID_SUFFIX}` : null;
47
+ }
48
+
49
+ /** The JID a send goes to, for an address `contactAddress` produced (or plain digits). */
50
+ export function addressJid(address: string): string {
51
+ if (address.includes("@")) return address;
52
+ const digits = address.replace(/\D/g, "");
53
+ return `${digits}${PN_SUFFIX}`;
54
+ }
55
+
56
+ /** A protobuf Long (a timestamp in seconds, a byte length) as a positive number, or null. */
57
+ export function longNumber(value: LongLike): number | null {
58
+ if (typeof value === "number") return Number.isFinite(value) && value > 0 ? value : null;
59
+ if (typeof value === "string") return longNumber(Number(value));
60
+ if (isObject(value) && typeof value.low === "number" && typeof value.high === "number") {
61
+ return longNumber(value.high * 2 ** 32 + (value.low >>> 0));
62
+ }
63
+ return null;
64
+ }
65
+
66
+ /** Wrappers whose inner `message` is the real content. */
67
+ const WRAPPERS = ["ephemeralMessage", "viewOnceMessage", "viewOnceMessageV2", "viewOnceMessageV2Extension", "documentWithCaptionMessage", "editedMessage"];
68
+ /** Fields of a message that are never its content. */
69
+ const NOT_CONTENT = new Set(["messageContextInfo", "senderKeyDistributionMessage"]);
70
+ /** Content that is not a message a person reads: skipped whole. */
71
+ const SKIPPED = new Set(["protocolMessage", "reactionMessage", "pollUpdateMessage", "keepInChatMessage"]);
72
+
73
+ /** A message's real content, out of its ephemeral, view-once or edit wrappers. `{}` for anything else. */
74
+ export function unwrapMessage(message: unknown): Json {
75
+ if (!isObject(message)) return {};
76
+ for (const wrapper of WRAPPERS) {
77
+ const inner = message[wrapper];
78
+ if (isObject(inner) && isObject(inner.message)) return unwrapMessage(inner.message);
79
+ }
80
+ return message;
81
+ }
82
+
83
+ type Reader = (body: unknown) => InboundContent | null;
84
+
85
+ const interactive = (replyId: unknown, title: unknown): InboundContent | null =>
86
+ text(replyId) ? { kind: "INTERACTIVE", replyId: replyId as string, title: text(title) ?? "" } : null;
87
+
88
+ /** How each content type a person reads is read. A type not listed is OTHER. */
89
+ const READERS: Readonly<Record<string, Reader>> = {
90
+ conversation: (body) => (text(body) ? { kind: "TEXT", text: body as string } : null),
91
+ extendedTextMessage: (body) => (isObject(body) && text(body.text) ? { kind: "TEXT", text: body.text as string } : null),
92
+ buttonsResponseMessage: (body) => (isObject(body) ? interactive(body.selectedButtonId, body.selectedDisplayText) : null),
93
+ templateButtonReplyMessage: (body) => (isObject(body) ? interactive(body.selectedId, body.selectedDisplayText) : null),
94
+ listResponseMessage: (body) =>
95
+ isObject(body) && isObject(body.singleSelectReply) ? interactive(body.singleSelectReply.selectedRowId, body.title) : null,
96
+ // The media id is filled with the message id by the caller.
97
+ audioMessage: (body) => (isObject(body) ? { kind: "AUDIO", mediaId: "", mimeType: text(body.mimetype) } : null),
98
+ };
99
+
100
+ /** The message's content, or null to skip it. */
101
+ export function contentOf(raw: unknown): InboundContent | null {
102
+ const message = unwrapMessage(raw);
103
+ const type = Object.keys(message).find((key) => !NOT_CONTENT.has(key) && message[key] !== null && message[key] !== undefined);
104
+ if (!type || SKIPPED.has(type)) return null;
105
+ const reader = READERS[type];
106
+ return reader ? reader(message[type]) : { kind: "OTHER", channelType: type.replace(/Message$/, "") || type };
107
+ }
108
+
109
+ export interface NormalizeOptions {
110
+ /** The whole-message words that opt a contact out. Default: the Cloud adapter's. */
111
+ optOutKeywords?: readonly string[];
112
+ }
113
+
114
+ /** One message → its inbound event, or null when it is not one a contact sent to this account. */
115
+ function inboundEvent(accountId: string, message: BaileysMessage, keywords: readonly string[]): NormalizedEvent | null {
116
+ if (!isObject(message) || !isObject(message.key) || message.key.fromMe) return null;
117
+ const id = text(message.key.id);
118
+ const contactId = contactAddress(message.key);
119
+ const seconds = longNumber(message.messageTimestamp);
120
+ const content = contentOf(message.message);
121
+ if (!id || !contactId || seconds === null || !content) return null;
122
+ return {
123
+ type: "message",
124
+ accountId,
125
+ contactId,
126
+ contactName: text(message.pushName),
127
+ externalId: id,
128
+ sentAt: new Date(seconds * 1000),
129
+ // An audio's media id is the message's own id: the session keeps the message to download it.
130
+ content: content.kind === "AUDIO" ? { ...content, mediaId: id } : content,
131
+ optOut: content.kind === "TEXT" && isOptOutText(content.text, keywords),
132
+ };
133
+ }
134
+
135
+ /** One live `messages.upsert` → inbound message events. `accountId` is the linked account's digits. */
136
+ export function normalizeUpsert(
137
+ accountId: string,
138
+ upsert: { messages: readonly BaileysMessage[]; type: string },
139
+ options: NormalizeOptions = {},
140
+ ): NormalizedEvent[] {
141
+ if (upsert.type !== "notify") return [];
142
+ const keywords = options.optOutKeywords ?? DEFAULT_OPT_OUT_KEYWORDS;
143
+ return upsert.messages.map((message) => inboundEvent(accountId, message, keywords)).filter((event): event is NormalizedEvent => event !== null);
144
+ }
145
+
146
+ /** `proto.WebMessageInfo.Status` → a receipt. PENDING (1) and unknown values are not receipts. */
147
+ export function receiptOf(status: unknown): ReceiptStatus | null {
148
+ switch (status) {
149
+ case 0:
150
+ return "FAILED";
151
+ case 2:
152
+ return "SENT";
153
+ case 3:
154
+ return "DELIVERED";
155
+ case 4:
156
+ case 5:
157
+ return "READ";
158
+ default:
159
+ return null;
160
+ }
161
+ }
162
+
163
+ /** One `messages.update` → receipts for the messages this account sent. `at` is when the socket saw it. */
164
+ export function normalizeUpdates(accountId: string, updates: readonly BaileysMessageUpdate[], at: Date): StatusEvent[] {
165
+ const events: StatusEvent[] = [];
166
+ for (const entry of updates) {
167
+ if (!isObject(entry) || !isObject(entry.key) || !entry.key.fromMe || !isObject(entry.update)) continue;
168
+ const id = text(entry.key.id);
169
+ const status = receiptOf(entry.update.status);
170
+ if (!id || !status) continue;
171
+ events.push({
172
+ type: "status",
173
+ accountId,
174
+ externalId: id,
175
+ status,
176
+ at,
177
+ contactId: contactAddress(entry.key),
178
+ error: status === "FAILED" ? "ERROR" : null,
179
+ callbackData: null,
180
+ });
181
+ }
182
+ return events;
183
+ }