@dhilzzkz/baileys 0.0.0-stage → 0.1.1

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 (241) hide show
  1. package/LICENSE +23 -0
  2. package/NOTICE.md +37 -0
  3. package/README.md +2083 -2
  4. package/WAProto/index.d.ts +22220 -0
  5. package/WAProto/index.js +5 -0
  6. package/lib/Addon/http-error.d.ts +18 -0
  7. package/lib/Addon/http-error.js +40 -0
  8. package/lib/Addon/index.d.ts +3 -0
  9. package/lib/Addon/index.js +4 -0
  10. package/lib/Addon/keyed-db.d.ts +14 -0
  11. package/lib/Addon/keyed-db.js +241 -0
  12. package/lib/Addon/link-preview.d.ts +15 -0
  13. package/lib/Addon/link-preview.js +79 -0
  14. package/lib/Defaults/index.d.ts +188 -0
  15. package/lib/Defaults/index.js +185 -0
  16. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  17. package/lib/Signal/Group/ciphertext-message.js +11 -0
  18. package/lib/Signal/Group/group-cipher.d.ts +10 -0
  19. package/lib/Signal/Group/group-cipher.js +81 -0
  20. package/lib/Signal/Group/group-session-builder.d.ts +7 -0
  21. package/lib/Signal/Group/group-session-builder.js +29 -0
  22. package/lib/Signal/Group/index.d.ts +11 -0
  23. package/lib/Signal/Group/index.js +11 -0
  24. package/lib/Signal/Group/keyhelper.d.ts +6 -0
  25. package/lib/Signal/Group/keyhelper.js +17 -0
  26. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  27. package/lib/Signal/Group/sender-chain-key.js +25 -0
  28. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  29. package/lib/Signal/Group/sender-key-distribution-message.js +62 -0
  30. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  31. package/lib/Signal/Group/sender-key-message.js +65 -0
  32. package/lib/Signal/Group/sender-key-name.d.ts +11 -0
  33. package/lib/Signal/Group/sender-key-name.js +47 -0
  34. package/lib/Signal/Group/sender-key-record.d.ts +12 -0
  35. package/lib/Signal/Group/sender-key-record.js +40 -0
  36. package/lib/Signal/Group/sender-key-state.d.ts +16 -0
  37. package/lib/Signal/Group/sender-key-state.js +83 -0
  38. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  39. package/lib/Signal/Group/sender-message-key.js +25 -0
  40. package/lib/Signal/Protocol/crypto.d.ts +6 -0
  41. package/lib/Signal/Protocol/crypto.js +61 -0
  42. package/lib/Signal/Protocol/curve.d.ts +8 -0
  43. package/lib/Signal/Protocol/curve.js +61 -0
  44. package/lib/Signal/Protocol/index.d.ts +16 -0
  45. package/lib/Signal/Protocol/index.js +9 -0
  46. package/lib/Signal/Protocol/internals.d.ts +57 -0
  47. package/lib/Signal/Protocol/internals.js +155 -0
  48. package/lib/Signal/Protocol/session-builder.d.ts +40 -0
  49. package/lib/Signal/Protocol/session-builder.js +143 -0
  50. package/lib/Signal/Protocol/session-cipher.d.ts +26 -0
  51. package/lib/Signal/Protocol/session-cipher.js +301 -0
  52. package/lib/Signal/Protocol/session-record.d.ts +55 -0
  53. package/lib/Signal/Protocol/session-record.js +272 -0
  54. package/lib/Signal/libsignal.d.ts +54 -0
  55. package/lib/Signal/libsignal.js +426 -0
  56. package/lib/Signal/lid-mapping.d.ts +20 -0
  57. package/lib/Signal/lid-mapping.js +274 -0
  58. package/lib/Socket/Client/index.d.ts +2 -0
  59. package/lib/Socket/Client/index.js +2 -0
  60. package/lib/Socket/Client/types.d.ts +5 -0
  61. package/lib/Socket/Client/types.js +10 -0
  62. package/lib/Socket/Client/websocket.d.ts +12 -0
  63. package/lib/Socket/Client/websocket.js +119 -0
  64. package/lib/Socket/business.d.ts +387 -0
  65. package/lib/Socket/business.js +380 -0
  66. package/lib/Socket/chats.d.ts +144 -0
  67. package/lib/Socket/chats.js +1216 -0
  68. package/lib/Socket/communities.d.ts +554 -0
  69. package/lib/Socket/communities.js +431 -0
  70. package/lib/Socket/groups.d.ts +286 -0
  71. package/lib/Socket/groups.js +347 -0
  72. package/lib/Socket/index.d.ts +522 -0
  73. package/lib/Socket/index.js +11 -0
  74. package/lib/Socket/messages-recv.d.ts +326 -0
  75. package/lib/Socket/messages-recv.js +1822 -0
  76. package/lib/Socket/messages-send.d.ts +321 -0
  77. package/lib/Socket/messages-send.js +1378 -0
  78. package/lib/Socket/mex.d.ts +1 -0
  79. package/lib/Socket/mex.js +41 -0
  80. package/lib/Socket/newsletter.d.ts +283 -0
  81. package/lib/Socket/newsletter.js +225 -0
  82. package/lib/Socket/socket.d.ts +61 -0
  83. package/lib/Socket/socket.js +992 -0
  84. package/lib/Store/index.d.ts +3 -0
  85. package/lib/Store/index.js +3 -0
  86. package/lib/Store/make-in-memory-store.d.ts +63 -0
  87. package/lib/Store/make-in-memory-store.js +418 -0
  88. package/lib/Store/make-ordered-dictionary.d.ts +12 -0
  89. package/lib/Store/make-ordered-dictionary.js +78 -0
  90. package/lib/Store/object-repository.d.ts +10 -0
  91. package/lib/Store/object-repository.js +23 -0
  92. package/lib/Types/Auth.d.ts +1 -0
  93. package/lib/Types/Auth.js +1 -0
  94. package/lib/Types/Business.d.ts +1 -0
  95. package/lib/Types/Business.js +1 -0
  96. package/lib/Types/Call.d.ts +1 -0
  97. package/lib/Types/Call.js +1 -0
  98. package/lib/Types/Chat.d.ts +1 -0
  99. package/lib/Types/Chat.js +7 -0
  100. package/lib/Types/Contact.d.ts +1 -0
  101. package/lib/Types/Contact.js +1 -0
  102. package/lib/Types/Events.d.ts +1 -0
  103. package/lib/Types/Events.js +1 -0
  104. package/lib/Types/GroupMetadata.d.ts +1 -0
  105. package/lib/Types/GroupMetadata.js +1 -0
  106. package/lib/Types/Label.d.ts +2 -0
  107. package/lib/Types/Label.js +24 -0
  108. package/lib/Types/LabelAssociation.d.ts +2 -0
  109. package/lib/Types/LabelAssociation.js +6 -0
  110. package/lib/Types/Message.d.ts +11 -0
  111. package/lib/Types/Message.js +17 -0
  112. package/lib/Types/Mex.d.ts +2 -0
  113. package/lib/Types/Mex.js +38 -0
  114. package/lib/Types/Product.d.ts +1 -0
  115. package/lib/Types/Product.js +1 -0
  116. package/lib/Types/RichType.d.ts +2 -0
  117. package/lib/Types/RichType.js +22 -0
  118. package/lib/Types/Signal.d.ts +1 -0
  119. package/lib/Types/Signal.js +1 -0
  120. package/lib/Types/Socket.d.ts +1 -0
  121. package/lib/Types/Socket.js +1 -0
  122. package/lib/Types/State.d.ts +5 -0
  123. package/lib/Types/State.js +54 -0
  124. package/lib/Types/USync.d.ts +1 -0
  125. package/lib/Types/USync.js +1 -0
  126. package/lib/Types/index.d.ts +13 -0
  127. package/lib/Types/index.js +25 -0
  128. package/lib/Utils/Auth/auth-utils.d.ts +58 -0
  129. package/lib/Utils/Auth/auth-utils.js +316 -0
  130. package/lib/Utils/Auth/companion-reg-client-utils.d.ts +4 -0
  131. package/lib/Utils/Auth/companion-reg-client-utils.js +39 -0
  132. package/lib/Utils/Auth/pre-key-manager.d.ts +25 -0
  133. package/lib/Utils/Auth/pre-key-manager.js +105 -0
  134. package/lib/Utils/Auth/use-multi-file-auth-state.d.ts +10 -0
  135. package/lib/Utils/Auth/use-multi-file-auth-state.js +116 -0
  136. package/lib/Utils/Auth/use-single-file-auth-state.d.ts +11 -0
  137. package/lib/Utils/Auth/use-single-file-auth-state.js +94 -0
  138. package/lib/Utils/Auth/use-sqlite-auth-state.d.ts +11 -0
  139. package/lib/Utils/Auth/use-sqlite-auth-state.js +109 -0
  140. package/lib/Utils/Auth/validate-connection.d.ts +44 -0
  141. package/lib/Utils/Auth/validate-connection.js +210 -0
  142. package/lib/Utils/Common/browser-utils.d.ts +9 -0
  143. package/lib/Utils/Common/browser-utils.js +28 -0
  144. package/lib/Utils/Common/generics.d.ts +63 -0
  145. package/lib/Utils/Common/generics.js +392 -0
  146. package/lib/Utils/Common/logger.d.ts +12 -0
  147. package/lib/Utils/Common/logger.js +12 -0
  148. package/lib/Utils/Common/make-mutex.d.ts +6 -0
  149. package/lib/Utils/Common/make-mutex.js +32 -0
  150. package/lib/Utils/Crypto/crypto.d.ts +39 -0
  151. package/lib/Utils/Crypto/crypto.js +117 -0
  152. package/lib/Utils/Crypto/lt-hash.d.ts +6 -0
  153. package/lib/Utils/Crypto/lt-hash.js +7 -0
  154. package/lib/Utils/Crypto/noise-handler.d.ts +20 -0
  155. package/lib/Utils/Crypto/noise-handler.js +200 -0
  156. package/lib/Utils/Crypto/signal.d.ts +82 -0
  157. package/lib/Utils/Crypto/signal.js +200 -0
  158. package/lib/Utils/Message/business.d.ts +49 -0
  159. package/lib/Utils/Message/business.js +230 -0
  160. package/lib/Utils/Message/decode-wa-message.d.ts +83 -0
  161. package/lib/Utils/Message/decode-wa-message.js +316 -0
  162. package/lib/Utils/Message/history.d.ts +75 -0
  163. package/lib/Utils/Message/history.js +133 -0
  164. package/lib/Utils/Message/link-preview.d.ts +13 -0
  165. package/lib/Utils/Message/link-preview.js +73 -0
  166. package/lib/Utils/Message/message-retry-manager.d.ts +79 -0
  167. package/lib/Utils/Message/message-retry-manager.js +259 -0
  168. package/lib/Utils/Message/messages-media.d.ts +134 -0
  169. package/lib/Utils/Message/messages-media.js +802 -0
  170. package/lib/Utils/Message/messages.d.ts +47 -0
  171. package/lib/Utils/Message/messages.js +1907 -0
  172. package/lib/Utils/Message/offline-node-processor.d.ts +10 -0
  173. package/lib/Utils/Message/offline-node-processor.js +40 -0
  174. package/lib/Utils/Message/process-message.d.ts +83 -0
  175. package/lib/Utils/Message/process-message.js +748 -0
  176. package/lib/Utils/Message/reporting-utils.d.ts +12 -0
  177. package/lib/Utils/Message/reporting-utils.js +257 -0
  178. package/lib/Utils/Message/rich-message-utils.d.ts +48 -0
  179. package/lib/Utils/Message/rich-message-utils.js +366 -0
  180. package/lib/Utils/Message/stanza-ack.d.ts +16 -0
  181. package/lib/Utils/Message/stanza-ack.js +37 -0
  182. package/lib/Utils/State/chat-utils.d.ts +408 -0
  183. package/lib/Utils/State/chat-utils.js +871 -0
  184. package/lib/Utils/State/event-buffer.d.ts +12 -0
  185. package/lib/Utils/State/event-buffer.js +621 -0
  186. package/lib/Utils/State/identity-change-handler.d.ts +13 -0
  187. package/lib/Utils/State/identity-change-handler.js +48 -0
  188. package/lib/Utils/State/sync-action-utils.d.ts +2 -0
  189. package/lib/Utils/State/sync-action-utils.js +48 -0
  190. package/lib/Utils/State/tc-token-utils.d.ts +29 -0
  191. package/lib/Utils/State/tc-token-utils.js +163 -0
  192. package/lib/Utils/index.d.ts +24 -0
  193. package/lib/Utils/index.js +24 -0
  194. package/lib/WABinary/constants.d.ts +61 -0
  195. package/lib/WABinary/constants.js +1466 -0
  196. package/lib/WABinary/decode.d.ts +9 -0
  197. package/lib/WABinary/decode.js +261 -0
  198. package/lib/WABinary/encode.d.ts +2 -0
  199. package/lib/WABinary/encode.js +219 -0
  200. package/lib/WABinary/generic-utils.d.ts +79 -0
  201. package/lib/WABinary/generic-utils.js +226 -0
  202. package/lib/WABinary/index.d.ts +5 -0
  203. package/lib/WABinary/index.js +5 -0
  204. package/lib/WABinary/jid-utils.d.ts +28 -0
  205. package/lib/WABinary/jid-utils.js +95 -0
  206. package/lib/WABinary/types.d.ts +1 -0
  207. package/lib/WABinary/types.js +1 -0
  208. package/lib/WAM/BinaryInfo.d.ts +7 -0
  209. package/lib/WAM/BinaryInfo.js +9 -0
  210. package/lib/WAM/constants.d.ts +34926 -0
  211. package/lib/WAM/constants.js +22852 -0
  212. package/lib/WAM/encode.d.ts +1 -0
  213. package/lib/WAM/encode.js +149 -0
  214. package/lib/WAM/index.d.ts +3 -0
  215. package/lib/WAM/index.js +3 -0
  216. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.d.ts +38 -0
  217. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +50 -0
  218. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +36 -0
  219. package/lib/WAUSync/Protocols/USyncContactProtocol.js +51 -0
  220. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  221. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
  222. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  223. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  224. package/lib/WAUSync/Protocols/USyncLIDProtocol.d.ts +14 -0
  225. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +28 -0
  226. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  227. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  228. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +9 -0
  229. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  230. package/lib/WAUSync/Protocols/index.d.ts +5 -0
  231. package/lib/WAUSync/Protocols/index.js +5 -0
  232. package/lib/WAUSync/USyncQuery.d.ts +20 -0
  233. package/lib/WAUSync/USyncQuery.js +97 -0
  234. package/lib/WAUSync/USyncUser.d.ts +16 -0
  235. package/lib/WAUSync/USyncUser.js +30 -0
  236. package/lib/WAUSync/index.d.ts +3 -0
  237. package/lib/WAUSync/index.js +3 -0
  238. package/lib/index.d.ts +11 -0
  239. package/lib/index.js +11 -0
  240. package/package.json +120 -5
  241. package/scripts/engine-requirements.js +16 -0
@@ -0,0 +1,392 @@
1
+ import { createHash, randomBytes, randomFillSync } from 'node:crypto';
2
+ import { proto } from '../../../WAProto/index.js';
3
+ import { HttpError } from '../../Addon/index.js';
4
+ import { DisconnectReason } from '../../Types/index.js';
5
+ import { getAllBinaryNodeChildren, jidDecode } from '../../WABinary/index.js';
6
+ import { sha256 } from '../Crypto/crypto.js';
7
+ const baileysVersion = [2, 3000, 1054623785];
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()) => date.getTime() / 1000 | 0;
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 HttpError('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 HttpError('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
+ // inspired from whatsmeow code
133
+ // https://github.com/tulir/whatsmeow/blob/64bc969fbe78d31ae0dd443b8d4c80a5d026d07a/send.go#L42
134
+ export const generateMessageIDV2 = (userId) => {
135
+ const data = Buffer.allocUnsafe(44);
136
+ data.writeBigUInt64BE(BigInt(Date.now() / 1000 | 0), 0);
137
+ if (userId) {
138
+ const userStr = userId.split('@')[0].split(':')[0];
139
+ if (userStr) {
140
+ const len = data.write(userStr, 8);
141
+ data.write('@c.us', 8 + len);
142
+ }
143
+ }
144
+ randomFillSync(data, 28, 16);
145
+ const hash = createHash('sha256').update(data).digest();
146
+ const hex = hash.toString('hex', 0, 9).toUpperCase();
147
+ const baseId = '3EB0' + hex;
148
+ const pos = 4 + (hash[0] & 15);
149
+ return baseId.slice(0, pos) + 'STARFALL' + baseId.slice(pos);
150
+ };
151
+ // generate a random ID to attach to a message
152
+ export const generateMessageID = () => '3EB0' + randomBytes(18).toString('hex').toUpperCase();
153
+ export function bindWaitForEvent(ev, event) {
154
+ return async (check, timeoutMs) => {
155
+ let listener;
156
+ let closeListener;
157
+ await promiseTimeout(timeoutMs, (resolve, reject) => {
158
+ closeListener = ({ connection, lastDisconnect }) => {
159
+ if (connection === 'close') {
160
+ reject(lastDisconnect?.error || new HttpError('Connection Closed', { statusCode: DisconnectReason.connectionClosed }));
161
+ }
162
+ };
163
+ ev.on('connection.update', closeListener);
164
+ listener = async (update) => {
165
+ if (await check(update)) {
166
+ resolve();
167
+ }
168
+ };
169
+ ev.on(event, listener);
170
+ }).finally(() => {
171
+ ev.off(event, listener);
172
+ ev.off('connection.update', closeListener);
173
+ });
174
+ };
175
+ }
176
+ export const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, 'connection.update');
177
+ /**
178
+ * utility that fetches latest baileys version from the master branch.
179
+ * Use to ensure your WA connection is always on the latest version
180
+ */
181
+ export const fetchLatestBaileysVersion = async (options = {}) => {
182
+ const URL = 'https://raw.githubusercontent.com/kazamaofficial-git/baileys/main/lib/Defaults/index.js';
183
+ try {
184
+ const response = await fetch(URL, {
185
+ dispatcher: options.dispatcher,
186
+ method: 'GET',
187
+ headers: options.headers
188
+ });
189
+ if (!response.ok) {
190
+ throw new HttpError(`Failed to fetch latest Baileys version: ${response.statusText}`, { statusCode: response.status });
191
+ }
192
+ const text = await response.text();
193
+ // Extract the `const version = [a, b, c]` declaration, wherever it sits in the file
194
+ const versionMatch = text.match(/const version = \[(\d+),\s*(\d+),\s*(\d+)\]/);
195
+ if (versionMatch) {
196
+ const version = [parseInt(versionMatch[1]), parseInt(versionMatch[2]), parseInt(versionMatch[3])];
197
+ return {
198
+ version,
199
+ isLatest: true
200
+ };
201
+ }
202
+ else {
203
+ throw new Error('Could not parse version from Defaults/index.js');
204
+ }
205
+ }
206
+ catch (error) {
207
+ return {
208
+ version: baileysVersion,
209
+ isLatest: false,
210
+ error
211
+ };
212
+ }
213
+ };
214
+ /**
215
+ * A utility that fetches the latest web version of whatsapp.
216
+ * Use to ensure your WA connection is always on the latest version
217
+ */
218
+ export const fetchLatestWaWebVersion = async (options = {}) => {
219
+ try {
220
+ // Absolute minimal headers required to bypass anti-bot detection
221
+ const defaultHeaders = {
222
+ 'sec-fetch-site': 'none',
223
+ 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
224
+ };
225
+ const headers = { ...defaultHeaders, ...options.headers };
226
+ const response = await fetch('https://web.whatsapp.com/sw.js', {
227
+ ...options,
228
+ method: 'GET',
229
+ headers
230
+ });
231
+ if (!response.ok) {
232
+ throw new HttpError(`Failed to fetch sw.js: ${response.statusText}`, { statusCode: response.status });
233
+ }
234
+ const data = await response.text();
235
+ const regex = /\\?"client_revision\\?":\s*(\d+)/;
236
+ const match = data.match(regex);
237
+ if (!match?.[1]) {
238
+ return {
239
+ version: baileysVersion,
240
+ isLatest: false,
241
+ error: {
242
+ message: 'Could not find client revision in the fetched content'
243
+ }
244
+ };
245
+ }
246
+ const clientRevision = match[1];
247
+ return {
248
+ version: [2, 3000, +clientRevision],
249
+ isLatest: true
250
+ };
251
+ }
252
+ catch (error) {
253
+ return {
254
+ version: baileysVersion,
255
+ isLatest: false,
256
+ error
257
+ };
258
+ }
259
+ };
260
+ /** unique message tag prefix for MD clients */
261
+ export const generateMdTagPrefix = () => {
262
+ const bytes = randomBytes(4);
263
+ return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`;
264
+ };
265
+ const STATUS_MAP = {
266
+ sender: proto.WebMessageInfo.Status.SERVER_ACK,
267
+ played: proto.WebMessageInfo.Status.PLAYED,
268
+ read: proto.WebMessageInfo.Status.READ,
269
+ 'read-self': proto.WebMessageInfo.Status.READ
270
+ };
271
+ /**
272
+ * Given a type of receipt, returns what the new status of the message should be
273
+ * @param type type from receipt
274
+ */
275
+ export const getStatusFromReceiptType = (type) => {
276
+ const status = STATUS_MAP[type];
277
+ if (typeof type === 'undefined') {
278
+ return proto.WebMessageInfo.Status.DELIVERY_ACK;
279
+ }
280
+ return status;
281
+ };
282
+ const CODE_MAP = {
283
+ conflict: DisconnectReason.connectionReplaced
284
+ };
285
+ /**
286
+ * Stream errors generally provide a reason, map that to a baileys DisconnectReason
287
+ * @param reason the string reason given, eg. "conflict"
288
+ */
289
+ export const getErrorCodeFromStreamError = (node) => {
290
+ const [reasonNode] = getAllBinaryNodeChildren(node);
291
+ let reason = reasonNode?.tag || 'unknown';
292
+ const statusCode = +(node.attrs.code || CODE_MAP[reason] || DisconnectReason.badSession);
293
+ if (statusCode === DisconnectReason.restartRequired) {
294
+ reason = 'restart required';
295
+ }
296
+ return {
297
+ reason,
298
+ statusCode
299
+ };
300
+ };
301
+ export const getCallStatusFromNode = ({ tag, attrs }) => {
302
+ let status;
303
+ switch (tag) {
304
+ case 'offer':
305
+ case 'offer_notice':
306
+ status = 'offer';
307
+ break;
308
+ case 'terminate':
309
+ if (attrs.reason === 'timeout') {
310
+ status = 'timeout';
311
+ }
312
+ else {
313
+ //fired when accepted/rejected/timeout/caller hangs up
314
+ status = 'terminate';
315
+ }
316
+ break;
317
+ case 'preaccept':
318
+ status = 'preaccept';
319
+ break;
320
+ case 'transport':
321
+ status = 'transport';
322
+ break;
323
+ case 'relaylatency':
324
+ status = 'relaylatency';
325
+ break;
326
+ case 'reject':
327
+ status = 'reject';
328
+ break;
329
+ case 'accept':
330
+ status = 'accept';
331
+ break;
332
+ default:
333
+ status = 'ringing';
334
+ break;
335
+ }
336
+ return status;
337
+ };
338
+ const UNEXPECTED_SERVER_CODE_TEXT = 'Unexpected server response: ';
339
+ export const getCodeFromWSError = (error) => {
340
+ let statusCode = 500;
341
+ if (error?.message?.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
342
+ const code = +error?.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length);
343
+ if (!Number.isNaN(code) && code >= 400) {
344
+ statusCode = code;
345
+ }
346
+ }
347
+ else if (
348
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
349
+ error?.code?.startsWith('E') ||
350
+ error?.message?.includes('timed out')) {
351
+ // handle ETIMEOUT, ENOTFOUND etc
352
+ statusCode = 408;
353
+ }
354
+ return statusCode;
355
+ };
356
+ /**
357
+ * Is the given platform WA business
358
+ * @param platform AuthenticationCreds.platform
359
+ */
360
+ export const isWABusinessPlatform = (platform) => {
361
+ return platform === 'smbi' || platform === 'smba';
362
+ };
363
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
364
+ export function trimUndefined(obj) {
365
+ for (const key in obj) {
366
+ if (typeof obj[key] === 'undefined') {
367
+ delete obj[key];
368
+ }
369
+ }
370
+ return obj;
371
+ }
372
+ const CROCKFORD_CHARACTERS = '123456789ABCDEFGHJKLMNPQRSTVWXYZ';
373
+ export function bytesToCrockford(buffer) {
374
+ let value = 0;
375
+ let bitCount = 0;
376
+ const crockford = [];
377
+ for (const element of buffer) {
378
+ value = (value << 8) | (element & 0xff);
379
+ bitCount += 8;
380
+ while (bitCount >= 5) {
381
+ crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31));
382
+ bitCount -= 5;
383
+ }
384
+ }
385
+ if (bitCount > 0) {
386
+ crockford.push(CROCKFORD_CHARACTERS.charAt((value << (5 - bitCount)) & 31));
387
+ }
388
+ return crockford.join('');
389
+ }
390
+ export function encodeNewsletterMessage(message) {
391
+ return proto.Message.encode(message).finish();
392
+ }
@@ -0,0 +1,12 @@
1
+ export default SILENT_LOGGER;
2
+ declare const SILENT_LOGGER: Readonly<{
3
+ level: "silent";
4
+ debug: () => void;
5
+ info: () => void;
6
+ warn: () => void;
7
+ error: () => void;
8
+ fatal: () => void;
9
+ trace: () => void;
10
+ child: () => Readonly</*elided*/ any>;
11
+ isLevelEnabled: () => false;
12
+ }>;
@@ -0,0 +1,12 @@
1
+ const SILENT_LOGGER = Object.freeze({
2
+ level: 'silent',
3
+ debug: () => { },
4
+ info: () => { },
5
+ warn: () => { },
6
+ error: () => { },
7
+ fatal: () => { },
8
+ trace: () => { },
9
+ child: () => SILENT_LOGGER,
10
+ isLevelEnabled: () => false
11
+ });
12
+ export default SILENT_LOGGER;
@@ -0,0 +1,6 @@
1
+ export function makeMutex(): {
2
+ mutex(code: any): any;
3
+ };
4
+ export function makeKeyedMutex(): {
5
+ mutex(key: any, task: any): Promise<any>;
6
+ };
@@ -0,0 +1,32 @@
1
+ import { createMutex } from '../../Addon/index.js';
2
+ export const makeMutex = () => {
3
+ const mutex = createMutex();
4
+ return {
5
+ mutex(code) {
6
+ return mutex.runExclusive(code);
7
+ }
8
+ };
9
+ };
10
+ export const makeKeyedMutex = () => {
11
+ const map = new Map();
12
+ return {
13
+ async mutex(key, task) {
14
+ let entry = map.get(key);
15
+ if (!entry) {
16
+ entry = { mutex: createMutex(), refCount: 0 };
17
+ map.set(key, entry);
18
+ }
19
+ entry.refCount++;
20
+ try {
21
+ return await entry.mutex.runExclusive(task);
22
+ }
23
+ finally {
24
+ entry.refCount--;
25
+ // only delete it if this is still the current entry
26
+ if (entry.refCount === 0 && map.get(key) === entry) {
27
+ map.delete(key);
28
+ }
29
+ }
30
+ }
31
+ };
32
+ };
@@ -0,0 +1,39 @@
1
+ /**
2
+ * encrypt AES 256 GCM;
3
+ * where the tag tag is suffixed to the ciphertext
4
+ * */
5
+ export function aesEncryptGCM(plaintext: any, key: any, iv: any, additionalData: any): any;
6
+ /**
7
+ * decrypt AES 256 GCM;
8
+ * where the auth tag is suffixed to the ciphertext
9
+ * */
10
+ export function aesDecryptGCM(ciphertext: any, key: any, iv: any, additionalData: any): any;
11
+ export function aesEncryptCTR(plaintext: any, key: any, iv: any): any;
12
+ export function aesDecryptCTR(ciphertext: any, key: any, iv: any): any;
13
+ /** decrypt AES 256 CBC; where the IV is prefixed to the buffer */
14
+ export function aesDecrypt(buffer: any, key: any): any;
15
+ /** decrypt AES 256 CBC */
16
+ export function aesDecryptWithIV(buffer: any, key: any, IV: any): any;
17
+ export function aesEncrypt(buffer: any, key: any): any;
18
+ export function aesEncrypWithIV(buffer: any, key: any, IV: any): any;
19
+ export function hmacSign(buffer: any, key: any, variant?: string): any;
20
+ export function sha256(buffer: any): any;
21
+ export function derivePairingCodeKey(pairingCode: any, salt: any): Promise<any>;
22
+ export function generateSignalPubKey(pubKey: any): any;
23
+ export namespace Curve {
24
+ function generateKeyPair(): {
25
+ private: any;
26
+ public: any;
27
+ };
28
+ function sharedKey(privateKey: any, publicKey: any): any;
29
+ function sign(privateKey: any, buf: any): any;
30
+ function verify(pubKey: any, message: any, signature: any): boolean;
31
+ }
32
+ export function signedKeyPair(identityKeyPair: any, keyId: any): {
33
+ keyPair: {
34
+ private: any;
35
+ public: any;
36
+ };
37
+ signature: any;
38
+ keyId: any;
39
+ };
@@ -0,0 +1,117 @@
1
+ import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes } from 'node:crypto';
2
+ import { KEY_BUNDLE_TYPE } from '../../Defaults/index.js';
3
+ import { curve } from '../../Signal/Protocol/index.js';
4
+ export { md5, hkdf } from 'whatsapp-rust-bridge';
5
+ // insure browser & node compatibility
6
+ const { subtle } = globalThis.crypto;
7
+ /** prefix version byte to the pub keys, required for some curve crypto functions */
8
+ export const generateSignalPubKey = (pubKey) => pubKey.length === 33 ? pubKey : Buffer.concat([KEY_BUNDLE_TYPE, pubKey]);
9
+ export const Curve = {
10
+ generateKeyPair: () => {
11
+ const { pubKey, privKey } = curve.generateKeyPair();
12
+ return {
13
+ private: Buffer.from(privKey),
14
+ // remove version byte
15
+ public: Buffer.from(pubKey.slice(1))
16
+ };
17
+ },
18
+ sharedKey: (privateKey, publicKey) => {
19
+ const shared = curve.calculateAgreement(generateSignalPubKey(publicKey), privateKey);
20
+ return Buffer.from(shared);
21
+ },
22
+ sign: (privateKey, buf) => curve.calculateSignature(privateKey, buf),
23
+ verify: (pubKey, message, signature) => {
24
+ try {
25
+ curve.verifySignature(generateSignalPubKey(pubKey), message, signature);
26
+ return true;
27
+ }
28
+ catch (error) {
29
+ return false;
30
+ }
31
+ }
32
+ };
33
+ export const signedKeyPair = (identityKeyPair, keyId) => {
34
+ const preKey = Curve.generateKeyPair();
35
+ const pubKey = generateSignalPubKey(preKey.public);
36
+ const signature = Curve.sign(identityKeyPair.private, pubKey);
37
+ return { keyPair: preKey, signature, keyId };
38
+ };
39
+ const GCM_TAG_LENGTH = 128 >> 3;
40
+ /**
41
+ * encrypt AES 256 GCM;
42
+ * where the tag tag is suffixed to the ciphertext
43
+ * */
44
+ export function aesEncryptGCM(plaintext, key, iv, additionalData) {
45
+ const cipher = createCipheriv('aes-256-gcm', key, iv);
46
+ cipher.setAAD(additionalData);
47
+ return Buffer.concat([cipher.update(plaintext), cipher.final(), cipher.getAuthTag()]);
48
+ }
49
+ /**
50
+ * decrypt AES 256 GCM;
51
+ * where the auth tag is suffixed to the ciphertext
52
+ * */
53
+ export function aesDecryptGCM(ciphertext, key, iv, additionalData) {
54
+ const decipher = createDecipheriv('aes-256-gcm', key, iv);
55
+ // decrypt additional adata
56
+ const enc = ciphertext.slice(0, ciphertext.length - GCM_TAG_LENGTH);
57
+ const tag = ciphertext.slice(ciphertext.length - GCM_TAG_LENGTH);
58
+ // set additional data
59
+ decipher.setAAD(additionalData);
60
+ decipher.setAuthTag(tag);
61
+ return Buffer.concat([decipher.update(enc), decipher.final()]);
62
+ }
63
+ export function aesEncryptCTR(plaintext, key, iv) {
64
+ const cipher = createCipheriv('aes-256-ctr', key, iv);
65
+ return Buffer.concat([cipher.update(plaintext), cipher.final()]);
66
+ }
67
+ export function aesDecryptCTR(ciphertext, key, iv) {
68
+ const decipher = createDecipheriv('aes-256-ctr', key, iv);
69
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
70
+ }
71
+ /** decrypt AES 256 CBC; where the IV is prefixed to the buffer */
72
+ export function aesDecrypt(buffer, key) {
73
+ return aesDecryptWithIV(buffer.subarray(16), key, buffer.subarray(0, 16));
74
+ }
75
+ /** decrypt AES 256 CBC */
76
+ export function aesDecryptWithIV(buffer, key, IV) {
77
+ const aes = createDecipheriv('aes-256-cbc', key, IV);
78
+ return Buffer.concat([aes.update(buffer), aes.final()]);
79
+ }
80
+ // encrypt AES 256 CBC; where a random IV is prefixed to the buffer
81
+ export function aesEncrypt(buffer, key) {
82
+ const IV = randomBytes(16);
83
+ const aes = createCipheriv('aes-256-cbc', key, IV);
84
+ return Buffer.concat([IV, aes.update(buffer), aes.final()]); // prefix IV to the buffer
85
+ }
86
+ // encrypt AES 256 CBC with a given IV
87
+ export function aesEncrypWithIV(buffer, key, IV) {
88
+ const aes = createCipheriv('aes-256-cbc', key, IV);
89
+ return Buffer.concat([aes.update(buffer), aes.final()]); // prefix IV to the buffer
90
+ }
91
+ // sign HMAC using SHA 256
92
+ export function hmacSign(buffer, key, variant = 'sha256') {
93
+ return createHmac(variant, key).update(buffer).digest();
94
+ }
95
+ export function sha256(buffer) {
96
+ return createHash('sha256').update(buffer).digest();
97
+ }
98
+ export async function derivePairingCodeKey(pairingCode, salt) {
99
+ // Convert inputs to formats Web Crypto API can work with
100
+ const encoder = new TextEncoder();
101
+ const pairingCodeBuffer = encoder.encode(pairingCode);
102
+ const saltBuffer = new Uint8Array(salt instanceof Uint8Array ? salt : new Uint8Array(salt));
103
+ // Import the pairing code as key material
104
+ const keyMaterial = await subtle.importKey('raw', pairingCodeBuffer, { name: 'PBKDF2' }, false, [
105
+ 'deriveBits'
106
+ ]);
107
+ // Derive bits using PBKDF2 with the same parameters
108
+ // 2 << 16 = 131,072 iterations
109
+ const derivedBits = await subtle.deriveBits({
110
+ name: 'PBKDF2',
111
+ salt: saltBuffer,
112
+ iterations: 2 << 16,
113
+ hash: 'SHA-256'
114
+ }, keyMaterial, 32 * 8 // 32 bytes * 8 = 256 bits
115
+ );
116
+ return Buffer.from(derivedBits);
117
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * LT Hash is a summation based hash algorithm that maintains the integrity of a piece of data
3
+ * over a series of mutations. You can add/remove mutations and it'll return a hash equal to
4
+ * if the same series of mutations was made sequentially.
5
+ */
6
+ export const LT_HASH_ANTI_TAMPERING: any;
@@ -0,0 +1,7 @@
1
+ import { LTHashAntiTampering } from 'whatsapp-rust-bridge';
2
+ /**
3
+ * LT Hash is a summation based hash algorithm that maintains the integrity of a piece of data
4
+ * over a series of mutations. You can add/remove mutations and it'll return a hash equal to
5
+ * if the same series of mutations was made sequentially.
6
+ */
7
+ export const LT_HASH_ANTI_TAMPERING = new LTHashAntiTampering();
@@ -0,0 +1,20 @@
1
+ export function makeNoiseHandler({ keyPair: { private: privateKey, public: publicKey }, NOISE_HEADER, logger, routingInfo }: {
2
+ keyPair: {
3
+ private: any;
4
+ public: any;
5
+ };
6
+ NOISE_HEADER: any;
7
+ logger: any;
8
+ routingInfo: any;
9
+ }): {
10
+ encrypt: (plaintext: any) => any;
11
+ decrypt: (ciphertext: any) => any;
12
+ authenticate: (data: any) => void;
13
+ mixIntoKey: (data: any) => void;
14
+ finishInit: () => Promise<void>;
15
+ processHandshake: ({ serverHello }: {
16
+ serverHello: any;
17
+ }, noiseKey: any) => any;
18
+ encodeFrame: (data: any) => any;
19
+ decodeFrame: (newData: any, onFrame: any) => Promise<void>;
20
+ };