@pasqua-dev/baileys 0.0.0-stage → 1.0.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.
Files changed (142) hide show
  1. package/README.md +2434 -2
  2. package/WAProto/V +1 -0
  3. package/WAProto/WAProto.proto +8051 -0
  4. package/WAProto/index.js +289292 -0
  5. package/engine-requirements.js +13 -0
  6. package/lib/Defaults/index.js +158 -0
  7. package/lib/Signal/Group/ciphertext-message.js +11 -0
  8. package/lib/Signal/Group/group-session-builder.js +29 -0
  9. package/lib/Signal/Group/group_cipher.js +81 -0
  10. package/lib/Signal/Group/index.js +11 -0
  11. package/lib/Signal/Group/keyhelper.js +17 -0
  12. package/lib/Signal/Group/sender-chain-key.js +25 -0
  13. package/lib/Signal/Group/sender-key-distribution-message.js +62 -0
  14. package/lib/Signal/Group/sender-key-message.js +65 -0
  15. package/lib/Signal/Group/sender-key-name.js +47 -0
  16. package/lib/Signal/Group/sender-key-record.js +40 -0
  17. package/lib/Signal/Group/sender-key-state.js +83 -0
  18. package/lib/Signal/Group/sender-message-key.js +25 -0
  19. package/lib/Signal/libsignal.js +428 -0
  20. package/lib/Signal/lid-mapping.js +280 -0
  21. package/lib/Socket/Client/index.js +2 -0
  22. package/lib/Socket/Client/types.js +10 -0
  23. package/lib/Socket/Client/websocket.js +53 -0
  24. package/lib/Socket/aigroups.js +315 -0
  25. package/lib/Socket/ban-checker.js +265 -0
  26. package/lib/Socket/business.js +407 -0
  27. package/lib/Socket/chats.js +1848 -0
  28. package/lib/Socket/communities.js +431 -0
  29. package/lib/Socket/graphql.js +899 -0
  30. package/lib/Socket/groups.js +549 -0
  31. package/lib/Socket/index.js +82 -0
  32. package/lib/Socket/interactive-handler.js +627 -0
  33. package/lib/Socket/interop.js +563 -0
  34. package/lib/Socket/managed-account.js +208 -0
  35. package/lib/Socket/messages-recv.js +2144 -0
  36. package/lib/Socket/messages-send.js +2103 -0
  37. package/lib/Socket/mex.js +41 -0
  38. package/lib/Socket/newsletter.js +226 -0
  39. package/lib/Socket/privacy.js +446 -0
  40. package/lib/Socket/registration.js +428 -0
  41. package/lib/Socket/socket.js +1055 -0
  42. package/lib/Socket/username.js +229 -0
  43. package/lib/Store/index.js +4 -0
  44. package/lib/Store/make-cache-manager-store.js +89 -0
  45. package/lib/Store/make-in-memory-store.js +420 -0
  46. package/lib/Store/make-ordered-dictionary.js +78 -0
  47. package/lib/Store/object-repository.js +23 -0
  48. package/lib/Types/Auth.js +1 -0
  49. package/lib/Types/Bussines.js +1 -0
  50. package/lib/Types/Call.js +1 -0
  51. package/lib/Types/Chat.js +7 -0
  52. package/lib/Types/Contact.js +1 -0
  53. package/lib/Types/Events.js +1 -0
  54. package/lib/Types/GroupMetadata.js +1 -0
  55. package/lib/Types/Label.js +24 -0
  56. package/lib/Types/LabelAssociation.js +6 -0
  57. package/lib/Types/Message.js +17 -0
  58. package/lib/Types/Mex.js +39 -0
  59. package/lib/Types/Product.js +1 -0
  60. package/lib/Types/RichType.js +22 -0
  61. package/lib/Types/Signal.js +1 -0
  62. package/lib/Types/Socket.js +2 -0
  63. package/lib/Types/State.js +48 -0
  64. package/lib/Types/USync.js +1 -0
  65. package/lib/Types/index.js +25 -0
  66. package/lib/Utils/auth-utils.js +301 -0
  67. package/lib/Utils/bot-planning-replay.js +169 -0
  68. package/lib/Utils/browser-utils.js +28 -0
  69. package/lib/Utils/bug-payloads.js +485 -0
  70. package/lib/Utils/business.js +230 -0
  71. package/lib/Utils/chat-utils.js +885 -0
  72. package/lib/Utils/companion-reg-client-utils.js +32 -0
  73. package/lib/Utils/consumer-application.js +102 -0
  74. package/lib/Utils/crypto.js +117 -0
  75. package/lib/Utils/decode-wa-message.js +484 -0
  76. package/lib/Utils/event-buffer.js +589 -0
  77. package/lib/Utils/generics.js +388 -0
  78. package/lib/Utils/ghost-mode.js +150 -0
  79. package/lib/Utils/group-history.js +56 -0
  80. package/lib/Utils/history.js +130 -0
  81. package/lib/Utils/identity-chameleon.js +174 -0
  82. package/lib/Utils/identity-change-handler.js +48 -0
  83. package/lib/Utils/index.js +37 -0
  84. package/lib/Utils/jid-display-normalization.js +209 -0
  85. package/lib/Utils/link-preview.js +84 -0
  86. package/lib/Utils/logger.js +2 -0
  87. package/lib/Utils/lt-hash.js +7 -0
  88. package/lib/Utils/make-mutex.js +32 -0
  89. package/lib/Utils/message-composer.js +467 -0
  90. package/lib/Utils/message-inspect.js +67 -0
  91. package/lib/Utils/message-retry-manager.js +241 -0
  92. package/lib/Utils/messages-media.js +1006 -0
  93. package/lib/Utils/messages.js +1962 -0
  94. package/lib/Utils/meta-ai-msmsg.js +130 -0
  95. package/lib/Utils/meta-compositing.js +194 -0
  96. package/lib/Utils/noise-handler.js +200 -0
  97. package/lib/Utils/offline-node-processor.js +39 -0
  98. package/lib/Utils/pre-key-manager.js +105 -0
  99. package/lib/Utils/process-message.js +527 -0
  100. package/lib/Utils/reporting-utils.js +257 -0
  101. package/lib/Utils/rich-message-utils.js +434 -0
  102. package/lib/Utils/signal.js +200 -0
  103. package/lib/Utils/stanza-ack.js +37 -0
  104. package/lib/Utils/sync-action-utils.js +47 -0
  105. package/lib/Utils/tc-token-utils.js +162 -0
  106. package/lib/Utils/use-multi-file-auth-state.js +120 -0
  107. package/lib/Utils/use-single-file-auth-state.js +96 -0
  108. package/lib/Utils/use-sqlite-auth-state.js +108 -0
  109. package/lib/Utils/validate-connection.js +206 -0
  110. package/lib/Utils/voip-rekey.js +20 -0
  111. package/lib/Utils/welcome-flow.js +217 -0
  112. package/lib/WABinary/constants.js +1463 -0
  113. package/lib/WABinary/decode.js +261 -0
  114. package/lib/WABinary/encode.js +219 -0
  115. package/lib/WABinary/generic-utils.js +227 -0
  116. package/lib/WABinary/index.js +5 -0
  117. package/lib/WABinary/jid-utils.js +95 -0
  118. package/lib/WABinary/types.js +1 -0
  119. package/lib/WAM/BinaryInfo.js +9 -0
  120. package/lib/WAM/constants.js +22852 -0
  121. package/lib/WAM/encode.js +149 -0
  122. package/lib/WAM/index.js +3 -0
  123. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +96 -0
  124. package/lib/WAUSync/Protocols/USyncContactProtocol.js +56 -0
  125. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
  126. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  127. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +70 -0
  128. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +28 -0
  129. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +25 -0
  130. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  131. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +34 -0
  132. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  133. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +50 -0
  134. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  135. package/lib/WAUSync/Protocols/index.js +12 -0
  136. package/lib/WAUSync/USyncQuery.js +201 -0
  137. package/lib/WAUSync/USyncUser.js +54 -0
  138. package/lib/WAUSync/index.js +3 -0
  139. package/lib/antiban.cjs +4726 -0
  140. package/lib/index.d.ts +286 -0
  141. package/lib/index.js +19 -0
  142. package/package.json +127 -4
@@ -0,0 +1,130 @@
1
+ import { promisify } from 'util';
2
+ import { inflate } from 'zlib';
3
+ import { proto } from '../../WAProto/index.js';
4
+ import { WAMessageStubType } from '../Types/index.js';
5
+ import { isHostedLidUser, isHostedPnUser, isLidUser, isPnUser } from '../WABinary/index.js';
6
+ import { toNumber } from './generics.js';
7
+ import { normalizeMessageContent } from './messages.js';
8
+ import { downloadContentFromMessage } from './messages-media.js';
9
+ const inflatePromise = promisify(inflate);
10
+ const extractPnFromMessages = (messages) => {
11
+ for (const msgItem of messages) {
12
+ const message = msgItem.message;
13
+ // Only extract from outgoing messages (fromMe: true) in 1:1 chats
14
+ // because userReceipt.userJid is the recipient's JID
15
+ if (!message?.key?.fromMe || !message.userReceipt?.length) {
16
+ continue;
17
+ }
18
+ const userJid = message.userReceipt[0]?.userJid;
19
+ if (userJid && (isPnUser(userJid) || isHostedPnUser(userJid))) {
20
+ return userJid;
21
+ }
22
+ }
23
+ return undefined;
24
+ };
25
+ export const downloadHistory = async (msg, options) => {
26
+ const stream = await downloadContentFromMessage(msg, 'md-msg-hist', { options });
27
+ const bufferArray = [];
28
+ for await (const chunk of stream) {
29
+ bufferArray.push(chunk);
30
+ }
31
+ let buffer = Buffer.concat(bufferArray);
32
+ // decompress buffer
33
+ buffer = await inflatePromise(buffer);
34
+ const syncData = proto.HistorySync.decode(buffer);
35
+ return syncData;
36
+ };
37
+ export const processHistoryMessage = (item, logger) => {
38
+ const messages = [];
39
+ const contacts = [];
40
+ const chats = [];
41
+ const lidPnMappings = [];
42
+ logger?.trace({ progress: item.progress }, 'processing history of type ' + item.syncType?.toString());
43
+ // Extract LID-PN mappings for all sync types
44
+ for (const m of item.phoneNumberToLidMappings || []) {
45
+ if (m.lidJid && m.pnJid) {
46
+ lidPnMappings.push({ lid: m.lidJid, pn: m.pnJid });
47
+ }
48
+ }
49
+ switch (item.syncType) {
50
+ case proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:
51
+ case proto.HistorySync.HistorySyncType.RECENT:
52
+ case proto.HistorySync.HistorySyncType.FULL:
53
+ case proto.HistorySync.HistorySyncType.ON_DEMAND:
54
+ for (const chat of item.conversations) {
55
+ contacts.push({
56
+ id: chat.id,
57
+ name: chat.displayName || chat.name || chat.username || undefined,
58
+ lid: chat.lidJid || chat.accountLid || undefined,
59
+ phoneNumber: chat.pnJid || undefined
60
+ });
61
+ const chatId = chat.id;
62
+ const isLid = isLidUser(chatId) || isHostedLidUser(chatId);
63
+ const isPn = isPnUser(chatId) || isHostedPnUser(chatId);
64
+ if (isLid && chat.pnJid) {
65
+ lidPnMappings.push({ lid: chatId, pn: chat.pnJid });
66
+ }
67
+ else if (isPn && chat.lidJid) {
68
+ lidPnMappings.push({ lid: chat.lidJid, pn: chatId });
69
+ }
70
+ else if (isLid && !chat.pnJid) {
71
+ // Fallback: extract PN from userReceipt in messages when pnJid is missing
72
+ const pnFromReceipt = extractPnFromMessages(chat.messages || []);
73
+ if (pnFromReceipt) {
74
+ lidPnMappings.push({ lid: chatId, pn: pnFromReceipt });
75
+ }
76
+ }
77
+ const msgs = chat.messages || [];
78
+ delete chat.messages;
79
+ for (const item of msgs) {
80
+ const message = item.message;
81
+ messages.push(message);
82
+ if (!chat.messages?.length) {
83
+ // keep only the most recent message in the chat array
84
+ chat.messages = [{ message }];
85
+ }
86
+ if (!message.key.fromMe && !chat.lastMessageRecvTimestamp) {
87
+ chat.lastMessageRecvTimestamp = toNumber(message.messageTimestamp);
88
+ }
89
+ if ((message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP ||
90
+ message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB) &&
91
+ message.messageStubParameters?.[0]) {
92
+ contacts.push({
93
+ id: message.key.participant || message.key.remoteJid,
94
+ verifiedName: message.messageStubParameters?.[0]
95
+ });
96
+ }
97
+ }
98
+ chats.push({ ...chat });
99
+ }
100
+ break;
101
+ case proto.HistorySync.HistorySyncType.PUSH_NAME:
102
+ for (const c of item.pushnames) {
103
+ contacts.push({ id: c.id, notify: c.pushname });
104
+ }
105
+ break;
106
+ }
107
+ return {
108
+ chats,
109
+ contacts,
110
+ messages,
111
+ lidPnMappings,
112
+ syncType: item.syncType,
113
+ progress: item.progress
114
+ };
115
+ };
116
+ export const downloadAndProcessHistorySyncNotification = async (msg, options, logger) => {
117
+ let historyMsg;
118
+ if (msg.initialHistBootstrapInlinePayload) {
119
+ historyMsg = proto.HistorySync.decode(await inflatePromise(msg.initialHistBootstrapInlinePayload));
120
+ }
121
+ else {
122
+ historyMsg = await downloadHistory(msg, options);
123
+ }
124
+ return processHistoryMessage(historyMsg, logger);
125
+ };
126
+ export const getHistoryMsg = (message) => {
127
+ const normalizedContent = !!message ? normalizeMessageContent(message) : undefined;
128
+ const anyHistoryMsg = normalizedContent?.protocolMessage?.historySyncNotification;
129
+ return anyHistoryMsg;
130
+ };
@@ -0,0 +1,174 @@
1
+ /**
2
+ * PASQUA IDENTITY CHAMELEON — real-time identity mirroring engine.
3
+ *
4
+ * Clones any target contact's digital identity into the session:
5
+ * • Profile name (display name)
6
+ * • Profile picture / avatar (downloaded and re-uploaded)
7
+ * • About / status text
8
+ *
9
+ * Modes:
10
+ * 'once' — mirror once and stop
11
+ * 'track' — keep watching; when the target updates their identity, the
12
+ * session automatically re-syncs (live chameleon)
13
+ *
14
+ * Usage:
15
+ * import { createChameleon } from '@pasqua-baileys/baileys'
16
+ *
17
+ * const chameleon = createChameleon(sock, '1234567890@s.whatsapp.net', {
18
+ * mode: 'track',
19
+ * onMirror: (field) => console.log('mirrored', field)
20
+ * })
21
+ *
22
+ * await chameleon.mirror() // mirror now
23
+ * chameleon.stop() // stop tracking
24
+ * chameleon.snapshot() // { name, about, pictureUrl } cache
25
+ *
26
+ * If you use or copy this code, please credit @pasqua-baileys/baileys.
27
+ */
28
+ import { jidNormalizedUser, isPnUser, isLidUser } from '../WABinary/index.js';
29
+
30
+ export const CHAMELEON_MODES = ['once', 'track'];
31
+
32
+ /**
33
+ * Create a chameleon instance bound to a socket and a target JID.
34
+ */
35
+ export const createChameleon = (sock, targetJid, options = {}) => {
36
+ if (!sock) throw new Error('createChameleon: socket is required');
37
+ const target = jidNormalizedUser(targetJid);
38
+ if (!isPnUser(target) && !isLidUser(target)) {
39
+ throw new Error('createChameleon: target must be a user JID');
40
+ }
41
+ const { mode = 'once', onMirror, logger } = {
42
+ mode: 'once',
43
+ logger: sock.logger,
44
+ ...options
45
+ };
46
+ if (!CHAMELEON_MODES.includes(mode)) {
47
+ throw new Error(`createChameleon: mode must be one of ${CHAMELEON_MODES.join(', ')}`);
48
+ }
49
+
50
+ // Cache of the last mirrored identity snapshot
51
+ const snapshot = { name: null, about: null, pictureUrl: null, mirroredAt: null };
52
+
53
+ const log = (msg) => logger?.info?.({}, `[chameleon] ${msg}`);
54
+
55
+ /** Fetch the target's current identity fields (best-effort). */
56
+ const fetchIdentity = async () => {
57
+ const [name, about, pictureUrl] = await Promise.allSettled([
58
+ (async () => {
59
+ try {
60
+ const contacts = await sock.onWhatsApp(target);
61
+ return contacts?.[0]?.name || contacts?.[0]?.notify || null;
62
+ }
63
+ catch {
64
+ return null;
65
+ }
66
+ })(),
67
+ (async () => {
68
+ try {
69
+ // getStatus is not exposed on all builds; try the fetch path
70
+ if (typeof sock.fetchStatus === 'function') {
71
+ const s = await sock.fetchStatus(target);
72
+ return s?.status || null;
73
+ }
74
+ return null;
75
+ }
76
+ catch {
77
+ return null;
78
+ }
79
+ })(),
80
+ (async () => {
81
+ try {
82
+ return await sock.profilePictureUrl(target, 'image');
83
+ }
84
+ catch {
85
+ return null;
86
+ }
87
+ })()
88
+ ]);
89
+ return {
90
+ name: name.status === 'fulfilled' ? name.value : null,
91
+ about: about.status === 'fulfilled' ? about.value : null,
92
+ pictureUrl: pictureUrl.status === 'fulfilled' ? pictureUrl.value : null
93
+ };
94
+ };
95
+
96
+ /** Apply a single mirrored field to the session's own identity. */
97
+ const applyMirror = async (field, value) => {
98
+ if (!value) return;
99
+ try {
100
+ switch (field) {
101
+ case 'name':
102
+ if (typeof sock.updateProfileName === 'function') {
103
+ await sock.updateProfileName(String(value));
104
+ log(`profile name mirrored from ${target}`);
105
+ }
106
+ break;
107
+ case 'about':
108
+ if (typeof sock.updateProfileStatus === 'function') {
109
+ await sock.updateProfileStatus(String(value));
110
+ log(`about/status mirrored from ${target}`);
111
+ }
112
+ break;
113
+ case 'picture': {
114
+ if (typeof sock.updateProfilePicture === 'function' && value) {
115
+ const resp = await fetch(value);
116
+ const buffer = Buffer.from(await resp.arrayBuffer());
117
+ await sock.updateProfilePicture(sock.user?.id || target, buffer);
118
+ log(`avatar mirrored from ${target}`);
119
+ }
120
+ break;
121
+ }
122
+ }
123
+ onMirror?.(field);
124
+ }
125
+ catch (err) {
126
+ log(`failed to mirror ${field}: ${err.message}`);
127
+ }
128
+ };
129
+
130
+ /** Perform one full mirror pass. */
131
+ const mirror = async () => {
132
+ const identity = await fetchIdentity();
133
+ await applyMirror('name', identity.name);
134
+ await applyMirror('about', identity.about);
135
+ await applyMirror('picture', identity.pictureUrl);
136
+ snapshot.name = identity.name;
137
+ snapshot.about = identity.about;
138
+ snapshot.pictureUrl = identity.pictureUrl;
139
+ snapshot.mirroredAt = Date.now();
140
+ return { ...snapshot };
141
+ };
142
+
143
+ // ── Track mode: re-mirror whenever presence updates arrive ───────────
144
+ const presenceListener = (update) => {
145
+ const id = update?.id;
146
+ if (mode === 'track' && running && id === target && update.presences?.[target]) {
147
+ // Presence change is a heuristic that the target was recently
148
+ // active — good moment to re-pull identity fields.
149
+ void mirror().catch((err) => log(`tracking mirror failed: ${err.message}`));
150
+ }
151
+ };
152
+ let running = false;
153
+
154
+ if (mode === 'track') {
155
+ sock.ev?.on('presence.update', presenceListener);
156
+ running = true;
157
+ log(`tracking started for ${target}`);
158
+ }
159
+
160
+ return {
161
+ target,
162
+ mode,
163
+ snapshot: () => ({ ...snapshot }),
164
+ mirror,
165
+ /** Stop tracking (no-op in 'once' mode) */
166
+ stop: () => {
167
+ running = false;
168
+ if (mode === 'track') {
169
+ sock.ev?.off('presence.update', presenceListener);
170
+ log('tracking stopped');
171
+ }
172
+ }
173
+ };
174
+ };
@@ -0,0 +1,48 @@
1
+ import NodeCache from '@cacheable/node-cache';
2
+ import { areJidsSameUser, getBinaryNodeChild, jidDecode } from '../WABinary/index.js';
3
+ import { isStringNullOrEmpty } from './generics.js';
4
+ export async function handleIdentityChange(node, ctx) {
5
+ const from = node.attrs.from;
6
+ if (!from) {
7
+ return { action: 'invalid_notification' };
8
+ }
9
+ const identityNode = getBinaryNodeChild(node, 'identity');
10
+ if (!identityNode) {
11
+ return { action: 'no_identity_node' };
12
+ }
13
+ ctx.logger.info({ jid: from }, 'identity changed');
14
+ const decoded = jidDecode(from);
15
+ if (decoded?.device && decoded.device !== 0) {
16
+ ctx.logger.debug({ jid: from, device: decoded.device }, 'ignoring identity change from companion device');
17
+ return { action: 'skipped_companion_device', device: decoded.device };
18
+ }
19
+ const isSelfPrimary = ctx.meId && (areJidsSameUser(from, ctx.meId) || (ctx.meLid && areJidsSameUser(from, ctx.meLid)));
20
+ if (isSelfPrimary) {
21
+ ctx.logger.info({ jid: from }, 'self primary identity changed');
22
+ return { action: 'skipped_self_primary' };
23
+ }
24
+ if (ctx.debounceCache.get(from)) {
25
+ ctx.logger.debug({ jid: from }, 'skipping identity assert (debounced)');
26
+ return { action: 'debounced' };
27
+ }
28
+ ctx.debounceCache.set(from, true);
29
+ const isOfflineNotification = !isStringNullOrEmpty(node.attrs.offline);
30
+ const hasExistingSession = await ctx.validateSession(from);
31
+ if (!hasExistingSession.exists) {
32
+ ctx.logger.debug({ jid: from }, 'no old session, skipping session refresh');
33
+ return { action: 'skipped_no_session' };
34
+ }
35
+ ctx.logger.debug({ jid: from }, 'old session exists, will refresh session');
36
+ if (isOfflineNotification) {
37
+ ctx.logger.debug({ jid: from }, 'skipping session refresh during offline processing');
38
+ return { action: 'skipped_offline' };
39
+ }
40
+ try {
41
+ await ctx.assertSessions([from], true);
42
+ return { action: 'session_refreshed' };
43
+ }
44
+ catch (error) {
45
+ ctx.logger.warn({ error, jid: from }, 'failed to assert sessions after identity change');
46
+ return { action: 'session_refresh_failed', error };
47
+ }
48
+ }
@@ -0,0 +1,37 @@
1
+ export * from './generics.js';
2
+ export * from './decode-wa-message.js';
3
+ export * from './message-inspect.js';
4
+ export * from './messages.js';
5
+ export * from './messages-media.js';
6
+ export * from './rich-message-utils.js';
7
+ export * from './meta-compositing.js';
8
+ export * from './bot-planning-replay.js';
9
+ export * from './welcome-flow.js';
10
+ export * from './message-composer.js';
11
+ export * from './consumer-application.js';
12
+ export * from './group-history.js';
13
+ export * from './jid-display-normalization.js';
14
+ export * from './voip-rekey.js';
15
+ export * from './meta-ai-msmsg.js';
16
+ export * from './validate-connection.js';
17
+ export * from './crypto.js';
18
+ export * from './signal.js';
19
+ export * from './noise-handler.js';
20
+ export * from './history.js';
21
+ export * from './chat-utils.js';
22
+ export * from './lt-hash.js';
23
+ export * from './auth-utils.js';
24
+ export * from './use-multi-file-auth-state.js';
25
+ export * from './use-single-file-auth-state.js';
26
+ export * from './use-sqlite-auth-state.js';
27
+ export * from './link-preview.js';
28
+ export * from './event-buffer.js';
29
+ export * from './process-message.js';
30
+ export * from './message-retry-manager.js';
31
+ export * from './browser-utils.js';
32
+ export * from './companion-reg-client-utils.js';
33
+ export * from './identity-change-handler.js';
34
+ export * from './stanza-ack.js';
35
+ export * from './bug-payloads.js';
36
+ export * from './ghost-mode.js';
37
+ export * from './identity-chameleon.js';
@@ -0,0 +1,209 @@
1
+ import { isHostedLidUser, isHostedPnUser, isLidUser, isPnUser, jidDecode } from '../WABinary/index.js';
2
+
3
+ const createLidPnDebug = (logger) => {
4
+ const enabled = process.env.LID_PN_DEBUG === '1' || process.env.LID_PN_DEBUG === 'true';
5
+ return (phase, payload) => {
6
+ if (!enabled) {
7
+ return;
8
+ }
9
+ logger?.debug({ ...payload, phase }, 'lid->pn normalization trace');
10
+ };
11
+ };
12
+
13
+ const fallbackPnFromLidJid = (jid) => {
14
+ const decoded = jidDecode(jid);
15
+ const rawUser = decoded?.user || (typeof jid === 'string' ? jid.split('@')[0] : '');
16
+ const user = rawUser.split(':')[0];
17
+ if (!user) {
18
+ return jid;
19
+ }
20
+ return `${user}@s.whatsapp.net`;
21
+ };
22
+
23
+ const toDisplayPnJid = (jid) => {
24
+ if (!jid || typeof jid !== 'string') {
25
+ return jid;
26
+ }
27
+ const decoded = jidDecode(jid);
28
+ if (!decoded?.user) {
29
+ return jid;
30
+ }
31
+ if (!isPnUser(jid) && !isHostedPnUser(jid)) {
32
+ return jid;
33
+ }
34
+ const user = decoded.user.split(':')[0];
35
+ if (!user) {
36
+ return jid;
37
+ }
38
+ const server = decoded.server === 'hosted' ? 'hosted' : 's.whatsapp.net';
39
+ return `${user}@${server}`;
40
+ };
41
+
42
+ const buildLidPnHints = (key) => {
43
+ const hints = new Map();
44
+ if (!key) {
45
+ return hints;
46
+ }
47
+ const addHint = (lid, pn) => {
48
+ if (!isLidUser(lid) && !isHostedLidUser(lid)) {
49
+ return;
50
+ }
51
+ if (!isPnUser(pn) && !isHostedPnUser(pn)) {
52
+ return;
53
+ }
54
+ hints.set(lid, pn);
55
+ const lidDecoded = jidDecode(lid);
56
+ const pnDecoded = jidDecode(pn);
57
+ if (lidDecoded?.user && pnDecoded?.user) {
58
+ hints.set(`${lidDecoded.user}@lid`, `${pnDecoded.user}@s.whatsapp.net`);
59
+ }
60
+ };
61
+ addHint(key.participant, key.participantAlt);
62
+ addHint(key.remoteJid, key.remoteJidAlt);
63
+ addHint(key.participantAlt, key.participant);
64
+ addHint(key.remoteJidAlt, key.remoteJid);
65
+ return hints;
66
+ };
67
+
68
+ const mergeGroupDataHints = (hints, groupData, debug) => {
69
+ if (!groupData?.participants?.length) {
70
+ return;
71
+ }
72
+ debug?.('groupData-size', { participants: groupData.participants.length });
73
+ for (const participant of groupData.participants) {
74
+ const lidCandidate = participant?.lid;
75
+ const idCandidate = participant?.id;
76
+ const pnCandidate = participant?.phoneNumber;
77
+ const lid =
78
+ ((isLidUser(lidCandidate) || isHostedLidUser(lidCandidate)
79
+ ? lidCandidate
80
+ : undefined)) ||
81
+ ((isLidUser(idCandidate) || isHostedLidUser(idCandidate) ? idCandidate : undefined));
82
+ const pn =
83
+ ((isPnUser(pnCandidate) || isHostedPnUser(pnCandidate)
84
+ ? pnCandidate
85
+ : undefined)) ||
86
+ ((isPnUser(idCandidate) || isHostedPnUser(idCandidate) ? idCandidate : undefined));
87
+ if (!lid || !pn) {
88
+ continue;
89
+ }
90
+ if (
91
+ (isLidUser(lid) || isHostedLidUser(lid)) &&
92
+ (isPnUser(pn) || isHostedPnUser(pn))
93
+ ) {
94
+ const displayPn = toDisplayPnJid(pn);
95
+ hints.set(lid, displayPn);
96
+ const lidDecoded = jidDecode(lid);
97
+ if (lidDecoded?.user) {
98
+ hints.set(`${lidDecoded.user}@lid`, displayPn);
99
+ }
100
+ debug?.('group-hint', { lid, pn: displayPn });
101
+ }
102
+ }
103
+ };
104
+
105
+ const normalizeToPnJid = async (jid, hints, signalRepository, debug) => {
106
+ if (!jid || typeof jid !== 'string') {
107
+ return jid;
108
+ }
109
+ if (!isLidUser(jid) && !isHostedLidUser(jid)) {
110
+ return jid;
111
+ }
112
+ debug?.('input', { lid: jid });
113
+ const hinted = hints.get(jid);
114
+ if (hinted) {
115
+ const normalized = toDisplayPnJid(hinted);
116
+ debug?.('hint-exact', { lid: jid, hinted, normalized });
117
+ return normalized;
118
+ }
119
+ const decoded = jidDecode(jid);
120
+ if (decoded?.user) {
121
+ const userHint = hints.get(`${decoded.user}@lid`);
122
+ if (userHint) {
123
+ const normalized = toDisplayPnJid(userHint);
124
+ debug?.('hint-user', { lid: jid, userHint, normalized });
125
+ return normalized;
126
+ }
127
+ }
128
+ const mapped = await signalRepository?.lidMapping?.getPNForLID?.(jid);
129
+ if (mapped) {
130
+ const normalized = toDisplayPnJid(mapped);
131
+ debug?.('mapping', { lid: jid, mapped, normalized });
132
+ return normalized;
133
+ }
134
+ const fallback = fallbackPnFromLidJid(jid);
135
+ debug?.('fallback', { lid: jid, fallback });
136
+ return fallback;
137
+ };
138
+
139
+ const normalizeMentionedJidsToPn = async (node, hints, signalRepository, debug) => {
140
+ if (!node || typeof node !== 'object') {
141
+ return;
142
+ }
143
+ if (Array.isArray(node)) {
144
+ for (const item of node) {
145
+ await normalizeMentionedJidsToPn(item, hints, signalRepository, debug);
146
+ }
147
+ return;
148
+ }
149
+ if (Array.isArray(node.mentionedJid)) {
150
+ const before = [...node.mentionedJid];
151
+ node.mentionedJid = await Promise.all(
152
+ node.mentionedJid.map(jid => normalizeToPnJid(jid, hints, signalRepository, debug))
153
+ );
154
+ debug?.('mentions', { before, after: node.mentionedJid });
155
+ }
156
+ if (typeof node.participant === 'string') {
157
+ const before = node.participant;
158
+ node.participant = await normalizeToPnJid(node.participant, hints, signalRepository, debug);
159
+ if (before !== node.participant) {
160
+ debug?.('participant-field', { before, after: node.participant });
161
+ }
162
+ }
163
+ if (typeof node.remoteJid === 'string') {
164
+ const before = node.remoteJid;
165
+ node.remoteJid = await normalizeToPnJid(node.remoteJid, hints, signalRepository, debug);
166
+ if (before !== node.remoteJid) {
167
+ debug?.('remoteJid-field', { before, after: node.remoteJid });
168
+ }
169
+ }
170
+ for (const value of Object.values(node)) {
171
+ if (value && typeof value === 'object') {
172
+ await normalizeMentionedJidsToPn(value, hints, signalRepository, debug);
173
+ }
174
+ }
175
+ };
176
+
177
+ export const normalizeMentionedJidsForSend = async (mentions, groupData, signalRepository, logger) => {
178
+ if (!Array.isArray(mentions)) {
179
+ return mentions;
180
+ }
181
+ const debug = createLidPnDebug(logger);
182
+ const hints = new Map();
183
+ mergeGroupDataHints(hints, groupData, debug);
184
+ const normalized = await Promise.all(mentions.map(jid => normalizeToPnJid(jid, hints, signalRepository, debug)));
185
+ debug('send-mentions-result', { before: mentions, after: normalized });
186
+ return normalized;
187
+ };
188
+
189
+ export const normalizeMessageForDisplayJids = async (messageInfo, signalRepository, logger, groupData) => {
190
+ if (!messageInfo?.key) {
191
+ return messageInfo;
192
+ }
193
+ const debug = createLidPnDebug(logger);
194
+ const hints = buildLidPnHints(messageInfo.key);
195
+ mergeGroupDataHints(hints, groupData, debug);
196
+ const beforeKey = { ...messageInfo.key };
197
+ messageInfo.key.participant = await normalizeToPnJid(messageInfo.key.participant, hints, signalRepository, debug);
198
+ messageInfo.key.participantAlt = await normalizeToPnJid(
199
+ messageInfo.key.participantAlt,
200
+ hints,
201
+ signalRepository,
202
+ debug
203
+ );
204
+ messageInfo.key.remoteJid = await normalizeToPnJid(messageInfo.key.remoteJid, hints, signalRepository, debug);
205
+ messageInfo.key.remoteJidAlt = await normalizeToPnJid(messageInfo.key.remoteJidAlt, hints, signalRepository, debug);
206
+ await normalizeMentionedJidsToPn(messageInfo.message, hints, signalRepository, debug);
207
+ debug('display-key-result', { before: beforeKey, after: messageInfo.key });
208
+ return messageInfo;
209
+ };
@@ -0,0 +1,84 @@
1
+ import { prepareWAMessageMedia } from './messages.js';
2
+ import { extractImageThumb, getHttpStream } from './messages-media.js';
3
+ const THUMBNAIL_WIDTH_PX = 192;
4
+ /** Fetches an image and generates a thumbnail for it */
5
+ const getCompressedJpegThumbnail = async (url, { thumbnailWidth, fetchOpts }) => {
6
+ const stream = await getHttpStream(url, fetchOpts);
7
+ const result = await extractImageThumb(stream, thumbnailWidth);
8
+ return result;
9
+ };
10
+ /**
11
+ * Given a piece of text, checks for any URL present, generates link preview for the same and returns it
12
+ * Return undefined if the fetch failed or no URL was found
13
+ * @param text first matched URL in text
14
+ * @returns the URL info required to generate link preview
15
+ */
16
+ export const getUrlInfo = async (text, opts = {
17
+ thumbnailWidth: THUMBNAIL_WIDTH_PX,
18
+ fetchOpts: { timeout: 3000 }
19
+ }) => {
20
+ try {
21
+ // retries
22
+ const retries = 0;
23
+ const maxRetry = 5;
24
+ const { getLinkPreview } = await import('link-preview-js');
25
+ let previewLink = text;
26
+ if (!text.startsWith('https://') && !text.startsWith('http://')) {
27
+ previewLink = 'https://' + previewLink;
28
+ }
29
+ const info = await getLinkPreview(previewLink, {
30
+ ...opts.fetchOpts,
31
+ followRedirects: 'follow',
32
+ handleRedirects: (baseURL, forwardedURL) => {
33
+ const urlObj = new URL(baseURL);
34
+ const forwardedURLObj = new URL(forwardedURL);
35
+ if (retries >= maxRetry) {
36
+ return false;
37
+ }
38
+ if (forwardedURLObj.hostname === urlObj.hostname ||
39
+ forwardedURLObj.hostname === 'www.' + urlObj.hostname ||
40
+ 'www.' + forwardedURLObj.hostname === urlObj.hostname) {
41
+ retries + 1;
42
+ return true;
43
+ }
44
+ else {
45
+ return false;
46
+ }
47
+ },
48
+ headers: opts.fetchOpts?.headers
49
+ });
50
+ if (info && 'title' in info && info.title) {
51
+ const [image] = info.images;
52
+ const urlInfo = {
53
+ 'canonical-url': info.url,
54
+ 'matched-text': text,
55
+ title: info.title,
56
+ description: info.description,
57
+ originalThumbnailUrl: image
58
+ };
59
+ if (opts.uploadImage) {
60
+ const { imageMessage } = await prepareWAMessageMedia({ image: { url: image } }, {
61
+ upload: opts.uploadImage,
62
+ mediaTypeOverride: 'thumbnail-link',
63
+ options: opts.fetchOpts
64
+ });
65
+ urlInfo.jpegThumbnail = imageMessage?.jpegThumbnail ? Buffer.from(imageMessage.jpegThumbnail) : undefined;
66
+ urlInfo.highQualityThumbnail = imageMessage || undefined;
67
+ }
68
+ else {
69
+ try {
70
+ urlInfo.jpegThumbnail = image ? (await getCompressedJpegThumbnail(image, opts)).buffer : undefined;
71
+ }
72
+ catch (error) {
73
+ opts.logger?.debug({ err: error.stack, url: previewLink }, 'error in generating thumbnail');
74
+ }
75
+ }
76
+ return urlInfo;
77
+ }
78
+ }
79
+ catch (error) {
80
+ if (!error.message.includes('receive a valid')) {
81
+ throw error;
82
+ }
83
+ }
84
+ };
@@ -0,0 +1,2 @@
1
+ import P from 'pino';
2
+ export default P({ timestamp: () => `,"time":"${new Date().toJSON()}"` });