@badzz88/baileys 8.4.6 → 8.4.9

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 (250) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1055 -337
  3. package/WAProto/WAProto.proto +850 -32
  4. package/WAProto/index.d.ts +4913 -25
  5. package/WAProto/index.js +14074 -98
  6. package/package.json +96 -131
  7. package/src/Defaults/index.js +201 -0
  8. package/src/Defaults/phonenumber-mcc.json +223 -0
  9. package/src/Signal/Group/ciphertext-message.js +15 -0
  10. package/src/Signal/Group/group-session-builder.js +92 -0
  11. package/src/Signal/Group/group_cipher.js +89 -0
  12. package/src/Signal/Group/index.js +136 -0
  13. package/src/Signal/Group/keyhelper.js +73 -0
  14. package/src/Signal/Group/sender-chain-key.js +32 -0
  15. package/src/Signal/Group/sender-key-distribution-message.js +66 -0
  16. package/src/Signal/Group/sender-key-message.js +69 -0
  17. package/src/Signal/Group/sender-key-name.js +50 -0
  18. package/src/Signal/Group/sender-key-record.js +44 -0
  19. package/src/Signal/Group/sender-key-state.js +97 -0
  20. package/src/Signal/Group/sender-message-key.js +30 -0
  21. package/src/Signal/libsignal.js +470 -0
  22. package/src/Signal/lid-mapping.js +262 -0
  23. package/src/Socket/Client/index.js +30 -0
  24. package/src/Socket/Client/types.js +13 -0
  25. package/src/Socket/Client/websocket.js +62 -0
  26. package/src/Socket/aigroups.js +240 -0
  27. package/src/Socket/business.js +422 -0
  28. package/src/Socket/chats.js +2374 -0
  29. package/src/Socket/communities.js +580 -0
  30. package/src/Socket/graphql.js +915 -0
  31. package/src/Socket/groups.js +812 -0
  32. package/src/Socket/index.js +37 -0
  33. package/src/Socket/interactive-handler.js +579 -0
  34. package/src/Socket/interop.js +566 -0
  35. package/src/Socket/managed-account.js +214 -0
  36. package/src/Socket/messages-recv.js +3012 -0
  37. package/src/Socket/messages-send.js +2163 -0
  38. package/{lib → src}/Socket/mex.js +11 -5
  39. package/src/Socket/newsletter.js +1057 -0
  40. package/src/Socket/privacy.js +452 -0
  41. package/src/Socket/registration.js +434 -0
  42. package/src/Socket/socket.js +1079 -0
  43. package/src/Socket/text-router.js +67 -0
  44. package/src/Socket/username.js +234 -0
  45. package/src/Store/index.js +36 -0
  46. package/src/Store/make-cache-manager-store.js +90 -0
  47. package/src/Store/make-in-memory-store.js +506 -0
  48. package/src/Store/make-ordered-dictionary.js +81 -0
  49. package/src/Store/object-repository.js +29 -0
  50. package/src/Types/Auth.js +38 -0
  51. package/src/Types/Bussines.js +2 -0
  52. package/src/Types/Call.js +2 -0
  53. package/src/Types/Chat.js +4 -0
  54. package/src/Types/Contact.js +2 -0
  55. package/src/Types/Events.js +2 -0
  56. package/src/Types/GroupMetadata.js +2 -0
  57. package/src/Types/Label.js +27 -0
  58. package/src/Types/LabelAssociation.js +9 -0
  59. package/src/Types/Message.js +95 -0
  60. package/src/Types/Newsletter.js +152 -0
  61. package/src/Types/Product.js +2 -0
  62. package/src/Types/Signal.js +2 -0
  63. package/src/Types/Socket.js +2 -0
  64. package/src/Types/State.js +70 -0
  65. package/src/Types/USync.js +2 -0
  66. package/src/Types/index.js +54 -0
  67. package/src/Utils/auth-utils.js +306 -0
  68. package/src/Utils/browser-utils.js +114 -0
  69. package/src/Utils/business.js +247 -0
  70. package/src/Utils/chat-utils.js +1272 -0
  71. package/src/Utils/consumer-application.js +107 -0
  72. package/src/Utils/crypto.js +125 -0
  73. package/src/Utils/decode-wa-message.js +808 -0
  74. package/src/Utils/event-buffer.js +586 -0
  75. package/src/Utils/generics.js +640 -0
  76. package/src/Utils/group-history.js +60 -0
  77. package/src/Utils/history.js +244 -0
  78. package/src/Utils/identity-change-handler.js +52 -0
  79. package/src/Utils/index.js +53 -0
  80. package/src/Utils/jid-display-normalization.js +218 -0
  81. package/src/Utils/link-preview.js +143 -0
  82. package/src/Utils/logger.js +9 -0
  83. package/src/Utils/lt-hash.js +10 -0
  84. package/src/Utils/make-mutex.js +36 -0
  85. package/src/Utils/message-composer.js +479 -0
  86. package/src/Utils/message-inspect.js +400 -0
  87. package/src/Utils/message-retry-manager.js +231 -0
  88. package/src/Utils/messages-media.js +943 -0
  89. package/src/Utils/messages.js +2490 -0
  90. package/src/Utils/meta-ai-msmsg.js +133 -0
  91. package/src/Utils/noise-handler.js +194 -0
  92. package/src/Utils/offline-node-processor.js +42 -0
  93. package/src/Utils/pre-key-manager.js +107 -0
  94. package/src/Utils/process-message.js +1047 -0
  95. package/src/Utils/reporting-utils.js +262 -0
  96. package/src/Utils/signal.js +192 -0
  97. package/src/Utils/stanza-ack.js +74 -0
  98. package/src/Utils/sync-action-utils.js +54 -0
  99. package/src/Utils/tc-token-utils.js +161 -0
  100. package/src/Utils/use-multi-file-auth-state.js +121 -0
  101. package/src/Utils/validate-connection.js +248 -0
  102. package/src/Utils/voip-rekey.js +22 -0
  103. package/src/WABinary/constants.js +1304 -0
  104. package/src/WABinary/decode.js +377 -0
  105. package/src/WABinary/encode.js +58 -0
  106. package/src/WABinary/generic-utils.js +148 -0
  107. package/src/WABinary/index.js +33 -0
  108. package/src/WABinary/jid-utils.js +374 -0
  109. package/src/WABinary/types.js +2 -0
  110. package/src/WAM/BinaryInfo.js +13 -0
  111. package/src/WAM/constants.js +39486 -0
  112. package/src/WAM/encode.js +142 -0
  113. package/src/WAM/index.js +31 -0
  114. package/src/WAUSync/Protocols/USyncBotProfileProtocol.js +55 -0
  115. package/src/WAUSync/Protocols/USyncBusinessProtocol.js +100 -0
  116. package/src/WAUSync/Protocols/USyncContactProtocol.js +60 -0
  117. package/src/WAUSync/Protocols/USyncDeviceProtocol.js +65 -0
  118. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  119. package/src/WAUSync/Protocols/USyncFeatureProtocol.js +74 -0
  120. package/src/WAUSync/Protocols/USyncLIDProtocol.js +31 -0
  121. package/src/WAUSync/Protocols/USyncPictureProtocol.js +32 -0
  122. package/src/WAUSync/Protocols/USyncSidelistProtocol.js +29 -0
  123. package/src/WAUSync/Protocols/USyncStatusProtocol.js +44 -0
  124. package/src/WAUSync/Protocols/USyncTextStatusProtocol.js +38 -0
  125. package/src/WAUSync/Protocols/USyncUsernameProtocol.js +28 -0
  126. package/src/WAUSync/Protocols/index.js +40 -0
  127. package/src/WAUSync/USyncBackoff.js +31 -0
  128. package/src/WAUSync/USyncQuery.js +204 -0
  129. package/src/WAUSync/USyncUser.js +58 -0
  130. package/src/WAUSync/index.js +32 -0
  131. package/src/antiban.js +4726 -0
  132. package/{lib → src}/index.js +48 -16
  133. package/lib/Defaults/baileys-version.json +0 -3
  134. package/lib/Defaults/index.js +0 -137
  135. package/lib/Defaults/phonenumber-mcc.json +0 -223
  136. package/lib/Signal/Group/Protocols.js +0 -269
  137. package/lib/Signal/Group/ciphertext-message.js +0 -12
  138. package/lib/Signal/Group/group-session-builder.js +0 -30
  139. package/lib/Signal/Group/group_cipher.js +0 -82
  140. package/lib/Signal/Group/index.js +0 -12
  141. package/lib/Signal/Group/keyhelper.js +0 -18
  142. package/lib/Signal/Group/queue-job.js +0 -57
  143. package/lib/Signal/Group/sender-chain-key.js +0 -26
  144. package/lib/Signal/Group/sender-key-distribution-message.js +0 -63
  145. package/lib/Signal/Group/sender-key-message.js +0 -66
  146. package/lib/Signal/Group/sender-key-name.js +0 -48
  147. package/lib/Signal/Group/sender-key-record.js +0 -41
  148. package/lib/Signal/Group/sender-key-state.js +0 -84
  149. package/lib/Signal/Group/sender-message-key.js +0 -26
  150. package/lib/Signal/libsignal.js +0 -432
  151. package/lib/Signal/lid-mapping.js +0 -277
  152. package/lib/Socket/Client/abstract-socket-client.js +0 -13
  153. package/lib/Socket/Client/index.js +0 -3
  154. package/lib/Socket/Client/mobile-socket-client.js +0 -65
  155. package/lib/Socket/Client/types.js +0 -11
  156. package/lib/Socket/Client/web-socket-client.js +0 -62
  157. package/lib/Socket/Client/websocket.js +0 -54
  158. package/lib/Socket/business.js +0 -379
  159. package/lib/Socket/chats.js +0 -1193
  160. package/lib/Socket/communities.js +0 -431
  161. package/lib/Socket/community.js +0 -392
  162. package/lib/Socket/dugong.js +0 -637
  163. package/lib/Socket/groups.js +0 -374
  164. package/lib/Socket/index.js +0 -12
  165. package/lib/Socket/luxu.js +0 -387
  166. package/lib/Socket/messages-recv.js +0 -1916
  167. package/lib/Socket/messages-send.js +0 -1459
  168. package/lib/Socket/newsletter.js +0 -253
  169. package/lib/Socket/registration.js +0 -167
  170. package/lib/Socket/socket.js +0 -950
  171. package/lib/Socket/username.js +0 -146
  172. package/lib/Socket/usync.js +0 -69
  173. package/lib/Store/index.js +0 -10
  174. package/lib/Store/keyed-db.js +0 -108
  175. package/lib/Store/make-cache-manager-store.js +0 -85
  176. package/lib/Store/make-in-memory-store.js +0 -198
  177. package/lib/Store/make-ordered-dictionary.js +0 -75
  178. package/lib/Store/object-repository.js +0 -32
  179. package/lib/Types/Auth.js +0 -2
  180. package/lib/Types/Bussines.js +0 -2
  181. package/lib/Types/Call.js +0 -2
  182. package/lib/Types/Chat.js +0 -8
  183. package/lib/Types/Contact.js +0 -2
  184. package/lib/Types/Events.js +0 -2
  185. package/lib/Types/GroupMetadata.js +0 -2
  186. package/lib/Types/Label.js +0 -25
  187. package/lib/Types/LabelAssociation.js +0 -7
  188. package/lib/Types/Message.js +0 -11
  189. package/lib/Types/Mex.js +0 -37
  190. package/lib/Types/Newsletter.js +0 -38
  191. package/lib/Types/Product.js +0 -2
  192. package/lib/Types/Signal.js +0 -2
  193. package/lib/Types/Socket.js +0 -3
  194. package/lib/Types/State.js +0 -56
  195. package/lib/Types/USync.js +0 -2
  196. package/lib/Types/index.js +0 -26
  197. package/lib/Utils/auth-utils.js +0 -302
  198. package/lib/Utils/baileys-event-stream.js +0 -63
  199. package/lib/Utils/browser-utils.js +0 -48
  200. package/lib/Utils/business.js +0 -231
  201. package/lib/Utils/chat-utils.js +0 -873
  202. package/lib/Utils/companion-reg-client-utils.js +0 -35
  203. package/lib/Utils/crypto.js +0 -118
  204. package/lib/Utils/decode-wa-message.js +0 -350
  205. package/lib/Utils/event-buffer.js +0 -622
  206. package/lib/Utils/generics.js +0 -399
  207. package/lib/Utils/history.js +0 -134
  208. package/lib/Utils/identity-change-handler.js +0 -50
  209. package/lib/Utils/index.js +0 -23
  210. package/lib/Utils/link-preview.js +0 -85
  211. package/lib/Utils/logger.js +0 -3
  212. package/lib/Utils/lt-hash.js +0 -8
  213. package/lib/Utils/make-mutex.js +0 -33
  214. package/lib/Utils/message-composer.js +0 -273
  215. package/lib/Utils/message-retry-manager.js +0 -265
  216. package/lib/Utils/messages-media.js +0 -788
  217. package/lib/Utils/messages.js +0 -1260
  218. package/lib/Utils/noise-handler.js +0 -201
  219. package/lib/Utils/offline-node-processor.js +0 -40
  220. package/lib/Utils/pre-key-manager.js +0 -106
  221. package/lib/Utils/process-message.js +0 -630
  222. package/lib/Utils/reporting-utils.js +0 -258
  223. package/lib/Utils/signal.js +0 -202
  224. package/lib/Utils/stanza-ack.js +0 -38
  225. package/lib/Utils/sync-action-utils.js +0 -49
  226. package/lib/Utils/tc-token-utils.js +0 -163
  227. package/lib/Utils/use-multi-file-auth-state.js +0 -121
  228. package/lib/Utils/validate-connection.js +0 -204
  229. package/lib/WABinary/constants.js +0 -1301
  230. package/lib/WABinary/decode.js +0 -262
  231. package/lib/WABinary/encode.js +0 -220
  232. package/lib/WABinary/generic-utils.js +0 -204
  233. package/lib/WABinary/index.js +0 -6
  234. package/lib/WABinary/jid-utils.js +0 -98
  235. package/lib/WABinary/types.js +0 -2
  236. package/lib/WAM/BinaryInfo.js +0 -10
  237. package/lib/WAM/constants.js +0 -22853
  238. package/lib/WAM/encode.js +0 -150
  239. package/lib/WAM/index.js +0 -4
  240. package/lib/WAUSync/Protocols/USyncContactProtocol.js +0 -52
  241. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +0 -54
  242. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +0 -27
  243. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +0 -38
  244. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +0 -25
  245. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +0 -51
  246. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +0 -29
  247. package/lib/WAUSync/Protocols/index.js +0 -6
  248. package/lib/WAUSync/USyncQuery.js +0 -98
  249. package/lib/WAUSync/USyncUser.js +0 -31
  250. package/lib/WAUSync/index.js +0 -4
@@ -1,399 +0,0 @@
1
- import { Boom } from '@hapi/boom';
2
- import { createHash, randomBytes } from 'crypto';
3
- import { proto } from '../../WAProto/index.js';
4
- const baileysVersion = [2, 3000, 1035194821];
5
- import { DisconnectReason } from '../Types/index.js';
6
- import { getAllBinaryNodeChildren, jidDecode } from '../WABinary/index.js';
7
- import { sha256 } from './crypto.js';
8
- export const BufferJSON = {
9
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
10
- replacer: (k, value) => {
11
- if (Buffer.isBuffer(value) || value instanceof Uint8Array || value?.type === 'Buffer') {
12
- return { type: 'Buffer', data: Buffer.from(value?.data || value).toString('base64') };
13
- }
14
- return value;
15
- },
16
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
17
- reviver: (_, value) => {
18
- if (typeof value === 'object' && value !== null && value.type === 'Buffer' && typeof value.data === 'string') {
19
- return Buffer.from(value.data, 'base64');
20
- }
21
- if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
22
- const keys = Object.keys(value);
23
- if (keys.length > 0 && keys.every(k => !isNaN(parseInt(k, 10)))) {
24
- const values = Object.values(value);
25
- if (values.every(v => typeof v === 'number')) {
26
- return Buffer.from(values);
27
- }
28
- }
29
- }
30
- return value;
31
- }
32
- };
33
- export const getKeyAuthor = (key, meId = 'me') => (key?.fromMe ? meId : key?.participantAlt || key?.remoteJidAlt || key?.participant || key?.remoteJid) || '';
34
- export const isStringNullOrEmpty = (value) =>
35
- // eslint-disable-next-line eqeqeq
36
- value == null || value === '';
37
- export const writeRandomPadMax16 = (msg) => {
38
- const pad = randomBytes(1);
39
- const padLength = (pad[0] & 0x0f) + 1;
40
- return Buffer.concat([msg, Buffer.alloc(padLength, padLength)]);
41
- };
42
- export const unpadRandomMax16 = (e) => {
43
- const t = new Uint8Array(e);
44
- if (0 === t.length) {
45
- throw new Error('unpadPkcs7 given empty bytes');
46
- }
47
- var r = t[t.length - 1];
48
- if (r > t.length) {
49
- throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`);
50
- }
51
- return new Uint8Array(t.buffer, t.byteOffset, t.length - r);
52
- };
53
- // code is inspired by whatsmeow
54
- export const generateParticipantHashV2 = (participants) => {
55
- participants.sort();
56
- const sha256Hash = sha256(Buffer.from(participants.join(''))).toString('base64');
57
- return '2:' + sha256Hash.slice(0, 6);
58
- };
59
- export const encodeWAMessage = (message) => writeRandomPadMax16(proto.Message.encode(message).finish());
60
- export const generateRegistrationId = () => {
61
- return Uint16Array.from(randomBytes(2))[0] & 16383;
62
- };
63
- export const encodeBigEndian = (e, t = 4) => {
64
- let r = e;
65
- const a = new Uint8Array(t);
66
- for (let i = t - 1; i >= 0; i--) {
67
- a[i] = 255 & r;
68
- r >>>= 8;
69
- }
70
- return a;
71
- };
72
- export const toNumber = (t) => typeof t === 'object' && t ? ('toNumber' in t ? t.toNumber() : t.low) : t || 0;
73
- /** unix timestamp of a date in seconds */
74
- export const unixTimestampSeconds = (date = new Date()) => Math.floor(date.getTime() / 1000);
75
- export const debouncedTimeout = (intervalMs = 1000, task) => {
76
- let timeout;
77
- return {
78
- start: (newIntervalMs, newTask) => {
79
- task = newTask || task;
80
- intervalMs = newIntervalMs || intervalMs;
81
- timeout && clearTimeout(timeout);
82
- timeout = setTimeout(() => task?.(), intervalMs);
83
- },
84
- cancel: () => {
85
- timeout && clearTimeout(timeout);
86
- timeout = undefined;
87
- },
88
- setTask: (newTask) => (task = newTask),
89
- setInterval: (newInterval) => (intervalMs = newInterval)
90
- };
91
- };
92
- export const delay = (ms) => delayCancellable(ms).delay;
93
- export const delayCancellable = (ms) => {
94
- const stack = new Error().stack;
95
- let timeout;
96
- let reject;
97
- const delay = new Promise((resolve, _reject) => {
98
- timeout = setTimeout(resolve, ms);
99
- reject = _reject;
100
- });
101
- const cancel = () => {
102
- clearTimeout(timeout);
103
- reject(new Boom('Cancelled', {
104
- statusCode: 500,
105
- data: {
106
- stack
107
- }
108
- }));
109
- };
110
- return { delay, cancel };
111
- };
112
- export async function promiseTimeout(ms, promise) {
113
- if (!ms) {
114
- return new Promise(promise);
115
- }
116
- const stack = new Error().stack;
117
- // Create a promise that rejects in <ms> milliseconds
118
- const { delay, cancel } = delayCancellable(ms);
119
- const p = new Promise((resolve, reject) => {
120
- delay
121
- .then(() => reject(new Boom('Timed Out', {
122
- statusCode: DisconnectReason.timedOut,
123
- data: {
124
- stack
125
- }
126
- })))
127
- .catch(err => reject(err));
128
- promise(resolve, reject);
129
- }).finally(cancel);
130
- return p;
131
- }
132
-
133
- export const generateMessageIDV2 = (userId) => {
134
- const data = Buffer.alloc(8 + 20 + 16);
135
- data.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000)));
136
- if (userId) {
137
- const id = jidDecode(userId);
138
- if (id?.user) {
139
- data.write(id.user, 8);
140
- data.write('@c.us', 8 + id.user.length);
141
- }
142
- }
143
- const random = randomBytes(16);
144
- random.copy(data, 28);
145
- const hash = createHash('sha256').update(data).digest();
146
- return 'B4DZZN3-' + hash.toString('hex').toUpperCase().substring(0, 18);
147
- };
148
-
149
- export const generateMessageID = () => 'B4DZZN3-' + randomBytes(18).toString('hex').toUpperCase();
150
- export function bindWaitForEvent(ev, event) {
151
- return async (check, timeoutMs) => {
152
- let listener;
153
- let closeListener;
154
- await promiseTimeout(timeoutMs, (resolve, reject) => {
155
- closeListener = ({ connection, lastDisconnect }) => {
156
- if (connection === 'close') {
157
- reject(lastDisconnect?.error || new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed }));
158
- }
159
- };
160
- ev.on('connection.update', closeListener);
161
- listener = async (update) => {
162
- if (await check(update)) {
163
- resolve();
164
- }
165
- };
166
- ev.on(event, listener);
167
- }).finally(() => {
168
- ev.off(event, listener);
169
- ev.off('connection.update', closeListener);
170
- });
171
- };
172
- }
173
- export const generateIOSMessageID = () => {
174
- const prefix = '3A';
175
- const random = randomBytes(10);
176
- return (prefix + random.toString('hex')).toUpperCase().substring(0, 21);
177
- };
178
- export const generateAndroMessageID = () => {
179
- const prefix = '3A';
180
- const random = randomBytes(16);
181
- return (random.toString('hex')).toUpperCase().substring(0, 21);
182
- };
183
- export const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, 'connection.update');
184
-
185
- export const fetchLatestBaileysVersion = async (options = {}) => {
186
- const URL = 'https://raw.githubusercontent.com/WhiskeySockets/Baileys/master/src/Defaults/index.ts';
187
- try {
188
- const response = await fetch(URL, {
189
- dispatcher: options.dispatcher,
190
- method: 'GET',
191
- headers: options.headers
192
- });
193
- if (!response.ok) {
194
- throw new Boom(`Failed to fetch latest Baileys version: ${response.statusText}`, { statusCode: response.status });
195
- }
196
- const text = await response.text();
197
- // Extract version from line 7 (const version = [...])
198
- const lines = text.split('\n');
199
- const versionLine = lines[6]; // Line 7 (0-indexed)
200
- const versionMatch = versionLine.match(/const version = \[(\d+),\s*(\d+),\s*(\d+)\]/);
201
- if (versionMatch) {
202
- const version = [parseInt(versionMatch[1]), parseInt(versionMatch[2]), parseInt(versionMatch[3])];
203
- return {
204
- version,
205
- isLatest: true
206
- };
207
- }
208
- else {
209
- throw new Error('Could not parse version from Defaults/index.ts');
210
- }
211
- }
212
- catch (error) {
213
- return {
214
- version: baileysVersion,
215
- isLatest: false,
216
- error
217
- };
218
- }
219
- };
220
- /**
221
- * A utility that fetches the latest web version of whatsapp.
222
- * Use to ensure your WA connection is always on the latest version
223
- */
224
- export const fetchLatestWaWebVersion = async (options = {}) => {
225
- try {
226
- // Absolute minimal headers required to bypass anti-bot detection
227
- const defaultHeaders = {
228
- 'sec-fetch-site': 'none',
229
- 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
230
- };
231
- const headers = { ...defaultHeaders, ...options.headers };
232
- const response = await fetch('https://web.whatsapp.com/sw.js', {
233
- ...options,
234
- method: 'GET',
235
- headers
236
- });
237
- if (!response.ok) {
238
- throw new Boom(`Failed to fetch sw.js: ${response.statusText}`, { statusCode: response.status });
239
- }
240
- const data = await response.text();
241
- const regex = /\\?"client_revision\\?":\s*(\d+)/;
242
- const match = data.match(regex);
243
- if (!match?.[1]) {
244
- return {
245
- version: baileysVersion,
246
- isLatest: false,
247
- error: {
248
- message: 'Could not find client revision in the fetched content'
249
- }
250
- };
251
- }
252
- const clientRevision = match[1];
253
- return {
254
- version: [2, 3000, +clientRevision],
255
- isLatest: true
256
- };
257
- }
258
- catch (error) {
259
- return {
260
- version: baileysVersion,
261
- isLatest: false,
262
- error
263
- };
264
- }
265
- };
266
- /** unique message tag prefix for MD clients */
267
- export const generateMdTagPrefix = () => {
268
- const bytes = randomBytes(4);
269
- return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`;
270
- };
271
- const STATUS_MAP = {
272
- sender: proto.WebMessageInfo.Status.SERVER_ACK,
273
- played: proto.WebMessageInfo.Status.PLAYED,
274
- read: proto.WebMessageInfo.Status.READ,
275
- 'read-self': proto.WebMessageInfo.Status.READ
276
- };
277
- /**
278
- * Given a type of receipt, returns what the new status of the message should be
279
- * @param type type from receipt
280
- */
281
- export const getStatusFromReceiptType = (type) => {
282
- const status = STATUS_MAP[type];
283
- if (typeof type === 'undefined') {
284
- return proto.WebMessageInfo.Status.DELIVERY_ACK;
285
- }
286
- return status;
287
- };
288
- const CODE_MAP = {
289
- conflict: DisconnectReason.connectionReplaced
290
- };
291
- /**
292
- * Stream errors generally provide a reason, map that to a baileys DisconnectReason
293
- * @param reason the string reason given, eg. "conflict"
294
- */
295
- export const getErrorCodeFromStreamError = (node) => {
296
- const [reasonNode] = getAllBinaryNodeChildren(node);
297
- let reason = reasonNode?.tag || 'unknown';
298
- const statusCode = +(node.attrs.code || CODE_MAP[reason] || DisconnectReason.badSession);
299
- if (statusCode === DisconnectReason.restartRequired) {
300
- reason = 'restart required';
301
- }
302
- return {
303
- reason,
304
- statusCode
305
- };
306
- };
307
- export const getCallStatusFromNode = ({ tag, attrs }) => {
308
- let status;
309
- switch (tag) {
310
- case 'offer':
311
- case 'offer_notice':
312
- status = 'offer';
313
- break;
314
- case 'terminate':
315
- if (attrs.reason === 'timeout') {
316
- status = 'timeout';
317
- }
318
- else {
319
- //fired when accepted/rejected/timeout/caller hangs up
320
- status = 'terminate';
321
- }
322
- break;
323
- case 'preaccept':
324
- status = 'preaccept';
325
- break;
326
- case 'transport':
327
- status = 'transport';
328
- break;
329
- case 'relaylatency':
330
- status = 'relaylatency';
331
- break;
332
- case 'reject':
333
- status = 'reject';
334
- break;
335
- case 'accept':
336
- status = 'accept';
337
- break;
338
- default:
339
- status = 'ringing';
340
- break;
341
- }
342
- return status;
343
- };
344
- const UNEXPECTED_SERVER_CODE_TEXT = 'Unexpected server response: ';
345
- export const getCodeFromWSError = (error) => {
346
- let statusCode = 500;
347
- if (error?.message?.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
348
- const code = +error?.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length);
349
- if (!Number.isNaN(code) && code >= 400) {
350
- statusCode = code;
351
- }
352
- }
353
- else if (
354
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
355
- error?.code?.startsWith('E') ||
356
- error?.message?.includes('timed out')) {
357
- // handle ETIMEOUT, ENOTFOUND etc
358
- statusCode = 408;
359
- }
360
- return statusCode;
361
- };
362
- /**
363
- * Is the given platform WA business
364
- * @param platform AuthenticationCreds.platform
365
- */
366
- export const isWABusinessPlatform = (platform) => {
367
- return platform === 'smbi' || platform === 'smba';
368
- };
369
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
370
- export function trimUndefined(obj) {
371
- for (const key in obj) {
372
- if (typeof obj[key] === 'undefined') {
373
- delete obj[key];
374
- }
375
- }
376
- return obj;
377
- }
378
- const CROCKFORD_CHARACTERS = '123456789ABCDEFGHJKLMNPQRSTVWXYZ';
379
- export function bytesToCrockford(buffer) {
380
- let value = 0;
381
- let bitCount = 0;
382
- const crockford = [];
383
- for (const element of buffer) {
384
- value = (value << 8) | (element & 0xff);
385
- bitCount += 8;
386
- while (bitCount >= 5) {
387
- crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31));
388
- bitCount -= 5;
389
- }
390
- }
391
- if (bitCount > 0) {
392
- crockford.push(CROCKFORD_CHARACTERS.charAt((value << (5 - bitCount)) & 31));
393
- }
394
- return crockford.join('');
395
- }
396
- export function encodeNewsletterMessage(message) {
397
- return proto.Message.encode(message).finish();
398
- }
399
- //# sourceMappingURL=generics.js.map
@@ -1,134 +0,0 @@
1
- import { pipeline } from 'stream/promises';
2
- import { promisify } from 'util';
3
- import { createInflate, inflate } from 'zlib';
4
- import { proto } from '../../WAProto/index.js';
5
- import { WAMessageStubType } from '../Types/index.js';
6
- import { isHostedLidUser, isHostedPnUser, isLidUser, isPnUser } from '../WABinary/index.js';
7
- import { toNumber } from './generics.js';
8
- import { normalizeMessageContent } from './messages.js';
9
- import { downloadContentFromMessage } from './messages-media.js';
10
- const inflatePromise = promisify(inflate);
11
- const extractPnFromMessages = (messages) => {
12
- for (const msgItem of messages) {
13
- const message = msgItem.message;
14
- // Only extract from outgoing messages (fromMe: true) in 1:1 chats
15
- // because userReceipt.userJid is the recipient's JID
16
- if (!message?.key?.fromMe || !message.userReceipt?.length) {
17
- continue;
18
- }
19
- const userJid = message.userReceipt[0]?.userJid;
20
- if (userJid && (isPnUser(userJid) || isHostedPnUser(userJid))) {
21
- return userJid;
22
- }
23
- }
24
- return undefined;
25
- };
26
- export const downloadHistory = async (msg, options) => {
27
- const stream = await downloadContentFromMessage(msg, 'md-msg-hist', { options });
28
- // Pipe decrypted stream directly through zlib inflate
29
- // This avoids allocating an intermediate buffer for the compressed data
30
- const inflater = createInflate();
31
- const chunks = [];
32
- inflater.on('data', (chunk) => chunks.push(chunk));
33
- await pipeline(stream, inflater);
34
- const buffer = Buffer.concat(chunks);
35
- const syncData = proto.HistorySync.decode(buffer);
36
- return syncData;
37
- };
38
- export const processHistoryMessage = (item, logger) => {
39
- const messages = [];
40
- const contacts = [];
41
- const chats = [];
42
- const lidPnMappings = [];
43
- logger?.trace({ progress: item.progress }, 'processing history of type ' + item.syncType?.toString());
44
- // Extract LID-PN mappings for all sync types
45
- for (const m of item.phoneNumberToLidMappings || []) {
46
- if (m.lidJid && m.pnJid) {
47
- lidPnMappings.push({ lid: m.lidJid, pn: m.pnJid });
48
- }
49
- }
50
- switch (item.syncType) {
51
- case proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:
52
- case proto.HistorySync.HistorySyncType.RECENT:
53
- case proto.HistorySync.HistorySyncType.FULL:
54
- case proto.HistorySync.HistorySyncType.ON_DEMAND:
55
- for (const chat of item.conversations) {
56
- contacts.push({
57
- id: chat.id,
58
- name: chat.displayName || chat.name || chat.username || undefined,
59
- username: chat.username || undefined,
60
- lid: chat.lidJid || chat.accountLid || undefined,
61
- phoneNumber: chat.pnJid || undefined
62
- });
63
- const chatId = chat.id;
64
- const isLid = isLidUser(chatId) || isHostedLidUser(chatId);
65
- const isPn = isPnUser(chatId) || isHostedPnUser(chatId);
66
- if (isLid && chat.pnJid) {
67
- lidPnMappings.push({ lid: chatId, pn: chat.pnJid });
68
- }
69
- else if (isPn && chat.lidJid) {
70
- lidPnMappings.push({ lid: chat.lidJid, pn: chatId });
71
- }
72
- else if (isLid && !chat.pnJid) {
73
- // Fallback: extract PN from userReceipt in messages when pnJid is missing
74
- const pnFromReceipt = extractPnFromMessages(chat.messages || []);
75
- if (pnFromReceipt) {
76
- lidPnMappings.push({ lid: chatId, pn: pnFromReceipt });
77
- }
78
- }
79
- const msgs = chat.messages || [];
80
- delete chat.messages;
81
- for (const item of msgs) {
82
- const message = item.message;
83
- messages.push(message);
84
- if (!chat.messages?.length) {
85
- // keep only the most recent message in the chat array
86
- chat.messages = [{ message }];
87
- }
88
- if (!message.key.fromMe && !chat.lastMessageRecvTimestamp) {
89
- chat.lastMessageRecvTimestamp = toNumber(message.messageTimestamp);
90
- }
91
- if ((message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP ||
92
- message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB) &&
93
- message.messageStubParameters?.[0]) {
94
- contacts.push({
95
- id: message.key.participant || message.key.remoteJid,
96
- verifiedName: message.messageStubParameters?.[0]
97
- });
98
- }
99
- }
100
- chats.push(chat);
101
- }
102
- break;
103
- case proto.HistorySync.HistorySyncType.PUSH_NAME:
104
- for (const c of item.pushnames) {
105
- contacts.push({ id: c.id, notify: c.pushname });
106
- }
107
- break;
108
- }
109
- return {
110
- chats,
111
- contacts,
112
- messages,
113
- lidPnMappings,
114
- pastParticipants: item.pastParticipants,
115
- syncType: item.syncType,
116
- progress: item.progress
117
- };
118
- };
119
- export const downloadAndProcessHistorySyncNotification = async (msg, options, logger) => {
120
- let historyMsg;
121
- if (msg.initialHistBootstrapInlinePayload) {
122
- historyMsg = proto.HistorySync.decode(await inflatePromise(msg.initialHistBootstrapInlinePayload));
123
- }
124
- else {
125
- historyMsg = await downloadHistory(msg, options);
126
- }
127
- return processHistoryMessage(historyMsg, logger);
128
- };
129
- export const getHistoryMsg = (message) => {
130
- const normalizedContent = !!message ? normalizeMessageContent(message) : undefined;
131
- const anyHistoryMsg = normalizedContent?.protocolMessage?.historySyncNotification;
132
- return anyHistoryMsg;
133
- };
134
- //# sourceMappingURL=history.js.map
@@ -1,50 +0,0 @@
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
- ctx.onBeforeSessionRefresh?.(from);
41
- try {
42
- await ctx.assertSessions([from], true);
43
- return { action: 'session_refreshed' };
44
- }
45
- catch (error) {
46
- ctx.logger.warn({ error, jid: from }, 'failed to assert sessions after identity change');
47
- return { action: 'session_refresh_failed', error };
48
- }
49
- }
50
- //# sourceMappingURL=identity-change-handler.js.map
@@ -1,23 +0,0 @@
1
- export * from './generics.js';
2
- export * from './decode-wa-message.js';
3
- export * from './messages.js';
4
- export * from './messages-media.js';
5
- export * from './validate-connection.js';
6
- export * from './crypto.js';
7
- export * from './signal.js';
8
- export * from './noise-handler.js';
9
- export * from './history.js';
10
- export * from './chat-utils.js';
11
- export * from './lt-hash.js';
12
- export * from './auth-utils.js';
13
- export * from './use-multi-file-auth-state.js';
14
- export * from './link-preview.js';
15
- export * from './event-buffer.js';
16
- export * from './process-message.js';
17
- export * from './message-retry-manager.js';
18
- export * from './browser-utils.js';
19
- export * from './companion-reg-client-utils.js';
20
- export * from './identity-change-handler.js';
21
- export * from './stanza-ack.js';
22
- export * from './message-composer.js';
23
- //# sourceMappingURL=index.js.map
@@ -1,85 +0,0 @@
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
- let 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
- };
85
- //# sourceMappingURL=link-preview.js.map