@rizzxdc/baileys 8.0.10 → 8.1.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 (220) hide show
  1. package/LICENSE +4 -2
  2. package/README.md +107 -245
  3. package/WAProto/index.d.ts +15795 -0
  4. package/WAProto/index.js +25587 -4867
  5. package/lib/Defaults/index.d.ts +147 -0
  6. package/lib/Defaults/index.js +134 -104
  7. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  8. package/lib/Signal/Group/ciphertext-message.js +9 -11
  9. package/lib/Signal/Group/group-session-builder.d.ts +8 -0
  10. package/lib/Signal/Group/group-session-builder.js +5 -8
  11. package/lib/Signal/Group/group_cipher.d.ts +11 -0
  12. package/lib/Signal/Group/group_cipher.js +72 -75
  13. package/lib/Signal/Group/index.d.ts +12 -0
  14. package/lib/Signal/Group/index.js +11 -13
  15. package/lib/Signal/Group/keyhelper.d.ts +7 -0
  16. package/lib/Signal/Group/keyhelper.js +11 -14
  17. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  18. package/lib/Signal/Group/sender-chain-key.js +23 -26
  19. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  20. package/lib/Signal/Group/sender-key-distribution-message.js +58 -61
  21. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  22. package/lib/Signal/Group/sender-key-message.js +61 -64
  23. package/lib/Signal/Group/sender-key-name.d.ts +12 -0
  24. package/lib/Signal/Group/sender-key-name.js +39 -44
  25. package/lib/Signal/Group/sender-key-record.d.ts +13 -0
  26. package/lib/Signal/Group/sender-key-record.js +35 -38
  27. package/lib/Signal/Group/sender-key-state.d.ts +17 -0
  28. package/lib/Signal/Group/sender-key-state.js +76 -79
  29. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  30. package/lib/Signal/Group/sender-message-key.js +23 -26
  31. package/lib/Signal/libsignal.d.ts +55 -0
  32. package/lib/Signal/libsignal.js +414 -308
  33. package/lib/Signal/lid-mapping.d.ts +21 -0
  34. package/lib/Signal/lid-mapping.js +270 -149
  35. package/lib/Socket/Client/index.d.ts +3 -0
  36. package/lib/Socket/Client/index.js +2 -4
  37. package/lib/Socket/Client/types.d.ts +6 -0
  38. package/lib/Socket/Client/types.js +8 -11
  39. package/lib/Socket/Client/websocket.d.ts +13 -0
  40. package/lib/Socket/Client/websocket.js +51 -50
  41. package/lib/Socket/business.d.ts +395 -0
  42. package/lib/Socket/business.js +357 -355
  43. package/lib/Socket/chats.d.ts +137 -0
  44. package/lib/Socket/chats.js +1195 -867
  45. package/lib/Socket/communities.d.ts +562 -0
  46. package/lib/Socket/communities.js +416 -398
  47. package/lib/Socket/dugong.js +8 -1
  48. package/lib/Socket/groups.d.ts +286 -0
  49. package/lib/Socket/groups.js +336 -301
  50. package/lib/Socket/index.d.ts +530 -0
  51. package/lib/Socket/index.js +8 -13
  52. package/lib/Socket/messages-recv.d.ts +334 -0
  53. package/lib/Socket/messages-recv.js +1729 -1121
  54. package/lib/Socket/messages-send.d.ts +330 -0
  55. package/lib/Socket/messages-send.js +684 -462
  56. package/lib/Socket/mex.d.ts +2 -0
  57. package/lib/Socket/mex.js +36 -40
  58. package/lib/Socket/newsletter.d.ts +284 -0
  59. package/lib/Socket/newsletter.js +247 -237
  60. package/lib/Socket/socket.d.ts +61 -0
  61. package/lib/Socket/socket.js +968 -790
  62. package/lib/Store/index.d.ts +4 -0
  63. package/lib/Store/index.js +4 -6
  64. package/lib/Store/make-cache-manager-store.js +2 -2
  65. package/lib/Store/make-in-memory-store.d.ts +63 -0
  66. package/lib/Store/make-in-memory-store.js +414 -284
  67. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  68. package/lib/Store/make-ordered-dictionary.js +75 -76
  69. package/lib/Store/object-repository.d.ts +11 -0
  70. package/lib/Store/object-repository.js +21 -23
  71. package/lib/Types/Auth.d.ts +2 -0
  72. package/lib/Types/Auth.js +0 -2
  73. package/lib/Types/Bussines.d.ts +2 -0
  74. package/lib/Types/Bussines.js +0 -2
  75. package/lib/Types/Call.d.ts +2 -0
  76. package/lib/Types/Call.js +0 -2
  77. package/lib/Types/Chat.d.ts +2 -0
  78. package/lib/Types/Chat.js +5 -7
  79. package/lib/Types/Contact.d.ts +2 -0
  80. package/lib/Types/Contact.js +0 -2
  81. package/lib/Types/Events.d.ts +2 -0
  82. package/lib/Types/Events.js +1 -3
  83. package/lib/Types/GroupMetadata.d.ts +2 -0
  84. package/lib/Types/GroupMetadata.js +0 -2
  85. package/lib/Types/Label.d.ts +3 -0
  86. package/lib/Types/Label.js +21 -22
  87. package/lib/Types/LabelAssociation.d.ts +3 -0
  88. package/lib/Types/LabelAssociation.js +3 -4
  89. package/lib/Types/Message.d.ts +12 -0
  90. package/lib/Types/Message.js +11 -6
  91. package/lib/Types/Mex.d.ts +3 -0
  92. package/lib/Types/Mex.js +38 -0
  93. package/lib/Types/Product.d.ts +2 -0
  94. package/lib/Types/Product.js +0 -2
  95. package/lib/Types/RichType.d.ts +3 -0
  96. package/lib/Types/RichType.js +22 -0
  97. package/lib/Types/Signal.d.ts +2 -0
  98. package/lib/Types/Signal.js +1 -3
  99. package/lib/Types/Socket.d.ts +2 -0
  100. package/lib/Types/Socket.js +1 -4
  101. package/lib/Types/State.d.ts +6 -0
  102. package/lib/Types/State.js +52 -8
  103. package/lib/Types/USync.d.ts +2 -0
  104. package/lib/Types/USync.js +1 -3
  105. package/lib/Types/index.d.ts +14 -0
  106. package/lib/Types/index.js +22 -25
  107. package/lib/Utils/auth-utils.d.ts +58 -0
  108. package/lib/Utils/auth-utils.js +285 -203
  109. package/lib/Utils/browser-utils.d.ts +9 -0
  110. package/lib/Utils/browser-utils.js +21 -19
  111. package/lib/Utils/business.d.ts +50 -0
  112. package/lib/Utils/business.js +206 -209
  113. package/lib/Utils/chat-utils.d.ts +409 -0
  114. package/lib/Utils/chat-utils.js +825 -706
  115. package/lib/Utils/companion-reg-client-utils.d.ts +5 -0
  116. package/lib/Utils/companion-reg-client-utils.js +39 -0
  117. package/lib/Utils/crypto.d.ts +40 -0
  118. package/lib/Utils/crypto.js +88 -101
  119. package/lib/Utils/decode-wa-message.d.ts +84 -0
  120. package/lib/Utils/decode-wa-message.js +287 -238
  121. package/lib/Utils/event-buffer.d.ts +13 -0
  122. package/lib/Utils/event-buffer.js +602 -509
  123. package/lib/Utils/generics.d.ts +64 -0
  124. package/lib/Utils/generics.js +334 -295
  125. package/lib/Utils/history.d.ts +76 -0
  126. package/lib/Utils/history.js +125 -79
  127. package/lib/Utils/identity-change-handler.d.ts +14 -0
  128. package/lib/Utils/identity-change-handler.js +49 -0
  129. package/lib/Utils/index.d.ts +25 -0
  130. package/lib/Utils/index.js +25 -21
  131. package/lib/Utils/link-preview.d.ts +13 -0
  132. package/lib/Utils/link-preview.js +73 -70
  133. package/lib/Utils/logger.d.ts +3 -0
  134. package/lib/Utils/logger.js +1 -4
  135. package/lib/Utils/lt-hash.d.ts +7 -0
  136. package/lib/Utils/lt-hash.js +7 -45
  137. package/lib/Utils/make-mutex.d.ts +7 -0
  138. package/lib/Utils/make-mutex.js +27 -31
  139. package/lib/Utils/message-retry-manager.d.ts +80 -0
  140. package/lib/Utils/message-retry-manager.js +165 -14
  141. package/lib/Utils/messages-media.d.ts +137 -0
  142. package/lib/Utils/messages-media.js +768 -572
  143. package/lib/Utils/messages.d.ts +46 -0
  144. package/lib/Utils/messages.js +1082 -130
  145. package/lib/Utils/noise-handler.d.ts +21 -0
  146. package/lib/Utils/noise-handler.js +191 -135
  147. package/lib/Utils/offline-node-processor.d.ts +10 -0
  148. package/lib/Utils/offline-node-processor.js +39 -0
  149. package/lib/Utils/pre-key-manager.d.ts +26 -0
  150. package/lib/Utils/pre-key-manager.js +96 -76
  151. package/lib/Utils/process-message.d.ts +84 -0
  152. package/lib/Utils/process-message.js +718 -311
  153. package/lib/Utils/reporting-utils.d.ts +13 -0
  154. package/lib/Utils/reporting-utils.js +257 -0
  155. package/lib/Utils/rich-message-utils.d.ts +49 -0
  156. package/lib/Utils/rich-message-utils.js +257 -0
  157. package/lib/Utils/signal.d.ts +83 -0
  158. package/lib/Utils/signal.js +174 -135
  159. package/lib/Utils/stanza-ack.d.ts +17 -0
  160. package/lib/Utils/stanza-ack.js +37 -0
  161. package/lib/Utils/sync-action-utils.d.ts +3 -0
  162. package/lib/Utils/sync-action-utils.js +48 -0
  163. package/lib/Utils/tc-token-utils.d.ts +30 -0
  164. package/lib/Utils/tc-token-utils.js +162 -0
  165. package/lib/Utils/use-multi-file-auth-state.d.ts +11 -0
  166. package/lib/Utils/use-multi-file-auth-state.js +104 -95
  167. package/lib/Utils/use-single-file-auth-state.d.ts +11 -0
  168. package/lib/Utils/use-single-file-auth-state.js +108 -0
  169. package/lib/Utils/use-sqlite-auth-state.d.ts +11 -0
  170. package/lib/Utils/use-sqlite-auth-state.js +108 -0
  171. package/lib/Utils/validate-connection.d.ts +44 -0
  172. package/lib/Utils/validate-connection.js +182 -180
  173. package/lib/WABinary/constants.d.ts +62 -0
  174. package/lib/WABinary/constants.js +1455 -1292
  175. package/lib/WABinary/decode.d.ts +10 -0
  176. package/lib/WABinary/decode.js +249 -228
  177. package/lib/WABinary/encode.d.ts +3 -0
  178. package/lib/WABinary/encode.js +207 -206
  179. package/lib/WABinary/generic-utils.d.ts +77 -0
  180. package/lib/WABinary/generic-utils.js +135 -99
  181. package/lib/WABinary/index.d.ts +6 -0
  182. package/lib/WABinary/index.js +5 -7
  183. package/lib/WABinary/jid-utils.d.ts +29 -0
  184. package/lib/WABinary/jid-utils.js +80 -78
  185. package/lib/WABinary/types.d.ts +2 -0
  186. package/lib/WABinary/types.js +1 -3
  187. package/lib/WAM/BinaryInfo.d.ts +8 -0
  188. package/lib/WAM/BinaryInfo.js +7 -9
  189. package/lib/WAM/constants.d.ts +34927 -0
  190. package/lib/WAM/constants.js +22847 -22848
  191. package/lib/WAM/encode.d.ts +2 -0
  192. package/lib/WAM/encode.js +129 -134
  193. package/lib/WAM/index.d.ts +4 -0
  194. package/lib/WAM/index.js +3 -5
  195. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +37 -0
  196. package/lib/WAUSync/Protocols/USyncContactProtocol.js +48 -27
  197. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  198. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +48 -48
  199. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  200. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +23 -26
  201. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  202. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +33 -35
  203. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
  204. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  205. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +39 -0
  206. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +46 -49
  207. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +15 -0
  208. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +23 -25
  209. package/lib/WAUSync/Protocols/index.d.ts +6 -0
  210. package/lib/WAUSync/Protocols/index.js +5 -6
  211. package/lib/WAUSync/USyncQuery.d.ts +21 -0
  212. package/lib/WAUSync/USyncQuery.js +92 -85
  213. package/lib/WAUSync/USyncUser.d.ts +17 -0
  214. package/lib/WAUSync/USyncUser.js +28 -22
  215. package/lib/WAUSync/index.d.ts +4 -0
  216. package/lib/WAUSync/index.js +3 -5
  217. package/lib/index.d.ts +12 -0
  218. package/lib/index.js +31 -19
  219. package/package.json +12 -6
  220. package/lib/Types/Newsletter.js +0 -33
@@ -1,355 +1,394 @@
1
- //=======================================================//
2
- import { getAllBinaryNodeChildren, jidDecode } from "../WABinary/index.js";
3
- import { DisconnectReason } from "../Types/index.js";
4
- import { createHash, randomBytes } from "crypto";
5
- import { proto } from "../../WAProto/index.js";
6
- import { version } from "../Defaults/index.js"
7
- import { sha256 } from "./crypto.js";
8
- import { Boom } from "@hapi/boom";
9
- //=======================================================//
1
+ import { Boom } from '@hapi/boom';
2
+ import { createHash, randomBytes, randomFillSync } from 'crypto';
3
+ import { proto } from '../../WAProto/index.js';
4
+ const baileysVersion = [2, 3000, 1049236237];
5
+ import { DisconnectReason } from '../Types/index.js';
6
+ import { getAllBinaryNodeChildren, jidDecode } from '../WABinary/index.js';
7
+ import { sha256 } from './crypto.js';
10
8
  export const BufferJSON = {
11
- replacer: (k, value) => {
12
- if (Buffer.isBuffer(value) || value instanceof Uint8Array || value?.type === "Buffer") {
13
- return { type: "Buffer", data: Buffer.from(value?.data || value).toString("base64") };
14
- }
15
- return value;
16
- },
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);
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
+ }
27
29
  }
28
- }
30
+ return value;
29
31
  }
30
- return value;
31
- }
32
32
  };
33
- //=======================================================//
34
- export const getKeyAuthor = (key, meId = "me") => (key?.fromMe ? meId : key?.participant || key?.remoteJid) || "";
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 === '';
35
37
  export const writeRandomPadMax16 = (msg) => {
36
- const pad = randomBytes(1);
37
- const padLength = (pad[0] & 0x0f) + 1;
38
- return Buffer.concat([msg, Buffer.alloc(padLength, padLength)]);
38
+ const pad = randomBytes(1);
39
+ const padLength = (pad[0] & 0x0f) + 1;
40
+ return Buffer.concat([msg, Buffer.alloc(padLength, padLength)]);
39
41
  };
40
- //=======================================================//
41
42
  export const unpadRandomMax16 = (e) => {
42
- const t = new Uint8Array(e);
43
- if (0 === t.length) {
44
- throw new Error("unpadPkcs7 given empty bytes");
45
- }
46
- var r = t[t.length - 1];
47
- if (r > t.length) {
48
- throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`);
49
- }
50
- return new Uint8Array(t.buffer, t.byteOffset, t.length - r);
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);
51
52
  };
52
- //=======================================================//
53
+ // code is inspired by whatsmeow
53
54
  export const generateParticipantHashV2 = (participants) => {
54
- participants.sort();
55
- const sha256Hash = sha256(Buffer.from(participants.join(""))).toString("base64");
56
- return "2:" + sha256Hash.slice(0, 6);
55
+ participants.sort();
56
+ const sha256Hash = sha256(Buffer.from(participants.join(''))).toString('base64');
57
+ return '2:' + sha256Hash.slice(0, 6);
57
58
  };
58
- //=======================================================//
59
59
  export const encodeWAMessage = (message) => writeRandomPadMax16(proto.Message.encode(message).finish());
60
60
  export const generateRegistrationId = () => {
61
- return Uint16Array.from(randomBytes(2))[0] & 16383;
61
+ return Uint16Array.from(randomBytes(2))[0] & 16383;
62
62
  };
63
- //=======================================================//
64
63
  export const encodeBigEndian = (e, t = 4) => {
65
- let r = e;
66
- const a = new Uint8Array(t);
67
- for (let i = t - 1; i >= 0; i--) {
68
- a[i] = 255 & r;
69
- r >>>= 8;
70
- }
71
- return a;
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;
72
71
  };
73
- export const toNumber = (t) => typeof t === "object" && t ? ("toNumber" in t ? t.toNumber() : t.low) : t || 0;
74
- //=======================================================//
75
- export const unixTimestampSeconds = (date = new Date()) => Math.floor(date.getTime() / 1000);
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;
76
75
  export const debouncedTimeout = (intervalMs = 1000, task) => {
77
- let timeout;
78
- return {
79
- start: (newIntervalMs, newTask) => {
80
- task = newTask || task;
81
- intervalMs = newIntervalMs || intervalMs;
82
- timeout && clearTimeout(timeout);
83
- timeout = setTimeout(() => task?.(), intervalMs);
84
- },
85
- cancel: () => {
86
- timeout && clearTimeout(timeout);
87
- timeout = undefined;
88
- },
89
- setTask: (newTask) => (task = newTask),
90
- setInterval: (newInterval) => (intervalMs = newInterval)
91
- };
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
+ };
92
91
  };
93
- //=======================================================//
94
92
  export const delay = (ms) => delayCancellable(ms).delay;
95
93
  export const delayCancellable = (ms) => {
96
- const stack = new Error().stack;
97
- let timeout;
98
- let reject;
99
- const delay = new Promise((resolve, _reject) => {
100
- timeout = setTimeout(resolve, ms);
101
- reject = _reject;
102
- });
103
- const cancel = () => {
104
- clearTimeout(timeout);
105
- reject(new Boom("Cancelled", {
106
- statusCode: 500,
107
- data: {
108
- stack
109
- }
110
- }));
111
- };
112
- return { delay, cancel };
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 };
113
111
  };
114
- //=======================================================//
115
112
  export async function promiseTimeout(ms, promise) {
116
- return new Promise(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;
117
131
  }
118
- //=======================================================//
132
+ // inspired from whatsmeow code
133
+ // https://github.com/tulir/whatsmeow/blob/64bc969fbe78d31ae0dd443b8d4c80a5d026d07a/send.go#L42
119
134
  export const generateMessageIDV2 = (userId) => {
120
- const data = Buffer.alloc(8 + 20 + 16);
121
- data.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000)));
122
- if (userId) {
123
- const id = jidDecode(userId);
124
- if (id?.user) {
125
- data.write(id.user, 8);
126
- data.write("@c.us", 8 + id.user.length);
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
+ }
127
143
  }
128
- }
129
- const random = randomBytes(16);
130
- random.copy(data, 28);
131
- const hash = createHash("sha256").update(data).digest();
132
- return "3EB0" + hash.toString("hex").toUpperCase().substring(0, 18);
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);
133
150
  };
134
- //=======================================================//
135
- export const generateMessageID = () => "3EB0" + randomBytes(18).toString("hex").toUpperCase();
151
+ // generate a random ID to attach to a message
152
+ export const generateMessageID = () => '3EB0' + randomBytes(18).toString('hex').toUpperCase();
136
153
  export function bindWaitForEvent(ev, event) {
137
- return async (check, timeoutMs) => {
138
- let listener;
139
- let closeListener;
140
- await promiseTimeout(timeoutMs, (resolve, reject) => {
141
- closeListener = ({ connection, lastDisconnect }) => {
142
- if (connection === "close") {
143
- reject(lastDisconnect?.error || new Boom("Connection Closed", { statusCode: DisconnectReason.connectionClosed }));
144
- }
145
- };
146
- ev.on("connection.update", closeListener);
147
- listener = async (update) => {
148
- if (await check(update)) {
149
- resolve();
150
- }
151
- };
152
- ev.on(event, listener);
153
- }).finally(() => {
154
- ev.off(event, listener);
155
- ev.off("connection.update", closeListener);
156
- });
157
- };
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 Boom('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
+ };
158
175
  }
159
- export const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, "connection.update");
160
- //=======================================================//
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
+ */
161
181
  export const fetchLatestBaileysVersion = async (options = {}) => {
162
- const URL = "https://raw.githubusercontent.com/WhiskeySockets/Baileys/master/src/Defaults/index.ts";
163
- try {
164
- const response = await fetch(URL, {
165
- dispatcher: options.dispatcher,
166
- method: "GET",
167
- headers: options.headers
168
- });
169
- if (!response.ok) {
170
- throw new Boom(`Failed to fetch latest Baileys version: ${response.statusText}`, { statusCode: response.status });
171
- }
172
- const text = await response.text();
173
- const lines = text.split("\n");
174
- const versionLine = lines[6];
175
- const versionMatch = versionLine.match(/const version = \[(\d+),\s*(\d+),\s*(\d+)\]/);
176
- if (versionMatch) {
177
- const version = [parseInt(versionMatch[1]), parseInt(versionMatch[2]), parseInt(versionMatch[3])];
178
- return {
179
- version,
180
- isLatest: true
181
- };
182
+ const URL = 'https://raw.githubusercontent.com/namamu/alwaysrizz/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 Boom(`Failed to fetch latest Baileys version: ${response.statusText}`, { statusCode: response.status });
191
+ }
192
+ const text = await response.text();
193
+ // Extract version from line 5 (const version = [...])
194
+ const lines = text.split('\n');
195
+ const versionLine = lines[4]; // Line 5 (0-indexed)
196
+ const versionMatch = versionLine.match(/const version = \[(\d+),\s*(\d+),\s*(\d+)\]/);
197
+ if (versionMatch) {
198
+ const version = [parseInt(versionMatch[1]), parseInt(versionMatch[2]), parseInt(versionMatch[3])];
199
+ return {
200
+ version,
201
+ isLatest: true
202
+ };
203
+ }
204
+ else {
205
+ throw new Error('Could not parse version from Defaults/index.ts');
206
+ }
182
207
  }
183
- else {
184
- throw new Error("Could not parse version from Defaults/index.ts");
208
+ catch (error) {
209
+ return {
210
+ version: baileysVersion,
211
+ isLatest: false,
212
+ error
213
+ };
185
214
  }
186
- }
187
- catch (error) {
188
- return {
189
- version: version,
190
- isLatest: false,
191
- error
192
- };
193
- }
194
215
  };
195
- //=======================================================//
216
+ /**
217
+ * A utility that fetches the latest web version of whatsapp.
218
+ * Use to ensure your WA connection is always on the latest version
219
+ */
196
220
  export const fetchLatestWaWebVersion = async (options = {}) => {
197
- try {
198
- const defaultHeaders = {
199
- "sec-fetch-site": "none",
200
- "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
201
- };
202
- const headers = { ...defaultHeaders, ...options.headers };
203
- const response = await fetch("https://web.whatsapp.com/sw.js", {
204
- ...options,
205
- method: "GET",
206
- headers
207
- });
208
- if (!response.ok) {
209
- throw new Boom(`Failed to fetch sw.js: ${response.statusText}`, { statusCode: response.status });
210
- }
211
- const data = await response.text();
212
- const regex = /\\?"client_revision\\?":\s*(\d+)/;
213
- const match = data.match(regex);
214
- if (!match?.[1]) {
215
- return {
216
- version: version,
217
- isLatest: false,
218
- error: {
219
- message: "Could not find client revision in the fetched content"
221
+ try {
222
+ // Absolute minimal headers required to bypass anti-bot detection
223
+ const defaultHeaders = {
224
+ 'sec-fetch-site': 'none',
225
+ 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
226
+ };
227
+ const headers = { ...defaultHeaders, ...options.headers };
228
+ const response = await fetch('https://web.whatsapp.com/sw.js', {
229
+ ...options,
230
+ method: 'GET',
231
+ headers
232
+ });
233
+ if (!response.ok) {
234
+ throw new Boom(`Failed to fetch sw.js: ${response.statusText}`, { statusCode: response.status });
235
+ }
236
+ const data = await response.text();
237
+ const regex = /\\?"client_revision\\?":\s*(\d+)/;
238
+ const match = data.match(regex);
239
+ if (!match?.[1]) {
240
+ return {
241
+ version: baileysVersion,
242
+ isLatest: false,
243
+ error: {
244
+ message: 'Could not find client revision in the fetched content'
245
+ }
246
+ };
220
247
  }
221
- };
248
+ const clientRevision = match[1];
249
+ return {
250
+ version: [2, 3000, +clientRevision],
251
+ isLatest: true
252
+ };
253
+ }
254
+ catch (error) {
255
+ return {
256
+ version: baileysVersion,
257
+ isLatest: false,
258
+ error
259
+ };
222
260
  }
223
- const clientRevision = match[1];
224
- return {
225
- version: [2, 3000, +clientRevision],
226
- isLatest: true
227
- };
228
- }
229
- catch (error) {
230
- return {
231
- version: version,
232
- isLatest: false,
233
- error
234
- };
235
- }
236
261
  };
237
- //=======================================================//
262
+ /** unique message tag prefix for MD clients */
238
263
  export const generateMdTagPrefix = () => {
239
- const bytes = randomBytes(4);
240
- return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`;
264
+ const bytes = randomBytes(4);
265
+ return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`;
241
266
  };
242
- //=======================================================//
243
267
  const STATUS_MAP = {
244
- "sender": proto.WebMessageInfo.Status.SERVER_ACK,
245
- "played": proto.WebMessageInfo.Status.PLAYED,
246
- "read": proto.WebMessageInfo.Status.READ,
247
- "read-self": proto.WebMessageInfo.Status.READ
268
+ sender: proto.WebMessageInfo.Status.SERVER_ACK,
269
+ played: proto.WebMessageInfo.Status.PLAYED,
270
+ read: proto.WebMessageInfo.Status.READ,
271
+ 'read-self': proto.WebMessageInfo.Status.READ
248
272
  };
249
- //=======================================================//
273
+ /**
274
+ * Given a type of receipt, returns what the new status of the message should be
275
+ * @param type type from receipt
276
+ */
250
277
  export const getStatusFromReceiptType = (type) => {
251
- const status = STATUS_MAP[type];
252
- if (typeof type === "undefined") {
253
- return proto.WebMessageInfo.Status.DELIVERY_ACK;
254
- }
255
- return status;
278
+ const status = STATUS_MAP[type];
279
+ if (typeof type === 'undefined') {
280
+ return proto.WebMessageInfo.Status.DELIVERY_ACK;
281
+ }
282
+ return status;
256
283
  };
257
- //=======================================================//
258
284
  const CODE_MAP = {
259
- conflict: DisconnectReason.connectionReplaced
285
+ conflict: DisconnectReason.connectionReplaced
260
286
  };
261
- //=======================================================//
287
+ /**
288
+ * Stream errors generally provide a reason, map that to a baileys DisconnectReason
289
+ * @param reason the string reason given, eg. "conflict"
290
+ */
262
291
  export const getErrorCodeFromStreamError = (node) => {
263
- const [reasonNode] = getAllBinaryNodeChildren(node);
264
- let reason = reasonNode?.tag || "unknown";
265
- const statusCode = +(node.attrs.code || CODE_MAP[reason] || DisconnectReason.badSession);
266
- if (statusCode === DisconnectReason.restartRequired) {
267
- reason = "restart required";
268
- }
269
- return {
270
- reason,
271
- statusCode
272
- };
292
+ const [reasonNode] = getAllBinaryNodeChildren(node);
293
+ let reason = reasonNode?.tag || 'unknown';
294
+ const statusCode = +(node.attrs.code || CODE_MAP[reason] || DisconnectReason.badSession);
295
+ if (statusCode === DisconnectReason.restartRequired) {
296
+ reason = 'restart required';
297
+ }
298
+ return {
299
+ reason,
300
+ statusCode
301
+ };
273
302
  };
274
- //=======================================================//
275
303
  export const getCallStatusFromNode = ({ tag, attrs }) => {
276
- let status;
277
- switch (tag) {
278
- case "offer":
279
- case "offer_notice":
280
- status = "offer";
281
- break;
282
- case "terminate":
283
- if (attrs.reason === "timeout") {
284
- status = "timeout";
285
- }
286
- else {
287
- status = "terminate";
288
- }
289
- break;
290
- case "reject":
291
- status = "reject";
292
- break;
293
- case "accept":
294
- status = "accept";
295
- break;
296
- default:
297
- status = "ringing";
298
- break;
299
- }
300
- return status;
304
+ let status;
305
+ switch (tag) {
306
+ case 'offer':
307
+ case 'offer_notice':
308
+ status = 'offer';
309
+ break;
310
+ case 'terminate':
311
+ if (attrs.reason === 'timeout') {
312
+ status = 'timeout';
313
+ }
314
+ else {
315
+ //fired when accepted/rejected/timeout/caller hangs up
316
+ status = 'terminate';
317
+ }
318
+ break;
319
+ case 'preaccept':
320
+ status = 'preaccept';
321
+ break;
322
+ case 'transport':
323
+ status = 'transport';
324
+ break;
325
+ case 'relaylatency':
326
+ status = 'relaylatency';
327
+ break;
328
+ case 'reject':
329
+ status = 'reject';
330
+ break;
331
+ case 'accept':
332
+ status = 'accept';
333
+ break;
334
+ default:
335
+ status = 'ringing';
336
+ break;
337
+ }
338
+ return status;
301
339
  };
302
- //=======================================================//
303
- const UNEXPECTED_SERVER_CODE_TEXT = "Unexpected server response: ";
340
+ const UNEXPECTED_SERVER_CODE_TEXT = 'Unexpected server response: ';
304
341
  export const getCodeFromWSError = (error) => {
305
- let statusCode = 500;
306
- if (error?.message?.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
307
- const code = +error?.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length);
308
- if (!Number.isNaN(code) && code >= 400) {
309
- statusCode = code;
342
+ let statusCode = 500;
343
+ if (error?.message?.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
344
+ const code = +error?.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length);
345
+ if (!Number.isNaN(code) && code >= 400) {
346
+ statusCode = code;
347
+ }
348
+ }
349
+ else if (
350
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
351
+ error?.code?.startsWith('E') ||
352
+ error?.message?.includes('timed out')) {
353
+ // handle ETIMEOUT, ENOTFOUND etc
354
+ statusCode = 408;
310
355
  }
311
- }
312
- else if (
313
- error?.code?.startsWith("E") ||
314
- error?.message?.includes("timed out")) {
315
- statusCode = 408;
316
- }
317
- return statusCode;
356
+ return statusCode;
318
357
  };
319
- //=======================================================//
358
+ /**
359
+ * Is the given platform WA business
360
+ * @param platform AuthenticationCreds.platform
361
+ */
320
362
  export const isWABusinessPlatform = (platform) => {
321
- return platform === "smbi" || platform === "smba";
363
+ return platform === 'smbi' || platform === 'smba';
322
364
  };
323
- //=======================================================//
365
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
324
366
  export function trimUndefined(obj) {
325
- for (const key in obj) {
326
- if (typeof obj[key] === "undefined") {
327
- delete obj[key];
367
+ for (const key in obj) {
368
+ if (typeof obj[key] === 'undefined') {
369
+ delete obj[key];
370
+ }
328
371
  }
329
- }
330
- return obj;
372
+ return obj;
331
373
  }
332
- //=======================================================//
333
- const CROCKFORD_CHARACTERS = "123456789ABCDEFGHJKLMNPQRSTVWXYZ";
374
+ const CROCKFORD_CHARACTERS = '123456789ABCDEFGHJKLMNPQRSTVWXYZ';
334
375
  export function bytesToCrockford(buffer) {
335
- let value = 0;
336
- let bitCount = 0;
337
- const crockford = [];
338
- for (const element of buffer) {
339
- value = (value << 8) | (element & 0xff);
340
- bitCount += 8;
341
- while (bitCount >= 5) {
342
- crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31));
343
- bitCount -= 5;
376
+ let value = 0;
377
+ let bitCount = 0;
378
+ const crockford = [];
379
+ for (const element of buffer) {
380
+ value = (value << 8) | (element & 0xff);
381
+ bitCount += 8;
382
+ while (bitCount >= 5) {
383
+ crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31));
384
+ bitCount -= 5;
385
+ }
386
+ }
387
+ if (bitCount > 0) {
388
+ crockford.push(CROCKFORD_CHARACTERS.charAt((value << (5 - bitCount)) & 31));
344
389
  }
345
- }
346
- if (bitCount > 0) {
347
- crockford.push(CROCKFORD_CHARACTERS.charAt((value << (5 - bitCount)) & 31));
348
- }
349
- return crockford.join("");
390
+ return crockford.join('');
350
391
  }
351
- //=======================================================//
352
392
  export function encodeNewsletterMessage(message) {
353
- return proto.Message.encode(message).finish();
393
+ return proto.Message.encode(message).finish();
354
394
  }
355
- //=======================================================//