@xbibzlibrary/whatsbibz 1.3.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 (260) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/LICENSE +22 -0
  3. package/LICENSE.upstream +21 -0
  4. package/README.md +280 -0
  5. package/VERIFIKASI-IDENTITAS-2026-09-03.md +138 -0
  6. package/WAProto/GenerateStatics.sh +3 -0
  7. package/WAProto/WAProto.proto +6035 -0
  8. package/WAProto/fix-imports.js +81 -0
  9. package/WAProto/index.d.ts +15314 -0
  10. package/WAProto/index.js +132326 -0
  11. package/assets/logo/README.md +21 -0
  12. package/assets/logo/png/banner-1200x360.png +0 -0
  13. package/assets/logo/png/icon-1024.png +0 -0
  14. package/assets/logo/png/icon-128.png +0 -0
  15. package/assets/logo/png/icon-16.png +0 -0
  16. package/assets/logo/png/icon-24.png +0 -0
  17. package/assets/logo/png/icon-256.png +0 -0
  18. package/assets/logo/png/icon-32.png +0 -0
  19. package/assets/logo/png/icon-48.png +0 -0
  20. package/assets/logo/png/icon-512.png +0 -0
  21. package/assets/logo/png/icon-64.png +0 -0
  22. package/assets/logo/png/mark-512.png +0 -0
  23. package/assets/logo/preview.png +0 -0
  24. package/assets/logo/whatsbibz.ico +0 -0
  25. package/lib/BibzWhats/client.d.ts +95 -0
  26. package/lib/BibzWhats/client.js +501 -0
  27. package/lib/BibzWhats/device-identity.d.ts +60 -0
  28. package/lib/BibzWhats/device-identity.js +234 -0
  29. package/lib/BibzWhats/extract.d.ts +29 -0
  30. package/lib/BibzWhats/extract.js +115 -0
  31. package/lib/BibzWhats/index.d.ts +7 -0
  32. package/lib/BibzWhats/index.js +8 -0
  33. package/lib/BibzWhats/jid.d.ts +22 -0
  34. package/lib/BibzWhats/jid.js +98 -0
  35. package/lib/BibzWhats/pairing.d.ts +35 -0
  36. package/lib/BibzWhats/pairing.js +186 -0
  37. package/lib/BibzWhats/send.d.ts +9 -0
  38. package/lib/BibzWhats/send.js +107 -0
  39. package/lib/BibzWhats/version.d.ts +6 -0
  40. package/lib/BibzWhats/version.js +7 -0
  41. package/lib/Defaults/index.d.ts +73 -0
  42. package/lib/Defaults/index.js +141 -0
  43. package/lib/Modded/message_builder.d.ts +15 -0
  44. package/lib/Modded/message_builder.js +2330 -0
  45. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  46. package/lib/Signal/Group/ciphertext-message.js +11 -0
  47. package/lib/Signal/Group/group-session-builder.d.ts +14 -0
  48. package/lib/Signal/Group/group-session-builder.js +29 -0
  49. package/lib/Signal/Group/group_cipher.d.ts +16 -0
  50. package/lib/Signal/Group/group_cipher.js +81 -0
  51. package/lib/Signal/Group/index.d.ts +11 -0
  52. package/lib/Signal/Group/index.js +11 -0
  53. package/lib/Signal/Group/keyhelper.d.ts +10 -0
  54. package/lib/Signal/Group/keyhelper.js +17 -0
  55. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  56. package/lib/Signal/Group/sender-chain-key.js +25 -0
  57. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  58. package/lib/Signal/Group/sender-key-distribution-message.js +62 -0
  59. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  60. package/lib/Signal/Group/sender-key-message.js +65 -0
  61. package/lib/Signal/Group/sender-key-name.d.ts +17 -0
  62. package/lib/Signal/Group/sender-key-name.js +47 -0
  63. package/lib/Signal/Group/sender-key-record.d.ts +30 -0
  64. package/lib/Signal/Group/sender-key-record.js +40 -0
  65. package/lib/Signal/Group/sender-key-state.d.ts +38 -0
  66. package/lib/Signal/Group/sender-key-state.js +83 -0
  67. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  68. package/lib/Signal/Group/sender-message-key.js +25 -0
  69. package/lib/Signal/libsignal.d.ts +4 -0
  70. package/lib/Signal/libsignal.js +406 -0
  71. package/lib/Signal/lid-mapping.d.ts +18 -0
  72. package/lib/Signal/lid-mapping.js +276 -0
  73. package/lib/Socket/Client/index.d.ts +2 -0
  74. package/lib/Socket/Client/index.js +2 -0
  75. package/lib/Socket/Client/types.d.ts +15 -0
  76. package/lib/Socket/Client/types.js +10 -0
  77. package/lib/Socket/Client/websocket.d.ts +12 -0
  78. package/lib/Socket/Client/websocket.js +53 -0
  79. package/lib/Socket/business.d.ts +537 -0
  80. package/lib/Socket/business.js +421 -0
  81. package/lib/Socket/chats.d.ts +110 -0
  82. package/lib/Socket/chats.js +1006 -0
  83. package/lib/Socket/communities.d.ts +646 -0
  84. package/lib/Socket/communities.js +430 -0
  85. package/lib/Socket/engine.d.ts +129 -0
  86. package/lib/Socket/engine.js +767 -0
  87. package/lib/Socket/groups.d.ts +149 -0
  88. package/lib/Socket/groups.js +326 -0
  89. package/lib/Socket/index.d.ts +637 -0
  90. package/lib/Socket/index.js +14 -0
  91. package/lib/Socket/messages-recv.d.ts +239 -0
  92. package/lib/Socket/messages-recv.js +1307 -0
  93. package/lib/Socket/messages-send.d.ts +580 -0
  94. package/lib/Socket/messages-send.js +1639 -0
  95. package/lib/Socket/mex.d.ts +2 -0
  96. package/lib/Socket/mex.js +47 -0
  97. package/lib/Socket/newsletter.d.ts +176 -0
  98. package/lib/Socket/newsletter.js +456 -0
  99. package/lib/Socket/socket.d.ts +56 -0
  100. package/lib/Socket/socket.js +998 -0
  101. package/lib/Types/Auth.d.ts +115 -0
  102. package/lib/Types/Auth.js +1 -0
  103. package/lib/Types/Bussines.d.ts +36 -0
  104. package/lib/Types/Bussines.js +1 -0
  105. package/lib/Types/Call.d.ts +14 -0
  106. package/lib/Types/Call.js +1 -0
  107. package/lib/Types/Chat.d.ts +124 -0
  108. package/lib/Types/Chat.js +7 -0
  109. package/lib/Types/Contact.d.ts +23 -0
  110. package/lib/Types/Contact.js +1 -0
  111. package/lib/Types/Events.d.ts +241 -0
  112. package/lib/Types/Events.js +1 -0
  113. package/lib/Types/GroupMetadata.d.ts +67 -0
  114. package/lib/Types/GroupMetadata.js +1 -0
  115. package/lib/Types/Label.d.ts +46 -0
  116. package/lib/Types/Label.js +24 -0
  117. package/lib/Types/LabelAssociation.d.ts +29 -0
  118. package/lib/Types/LabelAssociation.js +6 -0
  119. package/lib/Types/Message.d.ts +427 -0
  120. package/lib/Types/Message.js +10 -0
  121. package/lib/Types/Newsletter.d.ts +134 -0
  122. package/lib/Types/Newsletter.js +30 -0
  123. package/lib/Types/Product.d.ts +78 -0
  124. package/lib/Types/Product.js +1 -0
  125. package/lib/Types/Signal.d.ts +77 -0
  126. package/lib/Types/Signal.js +1 -0
  127. package/lib/Types/Socket.d.ts +173 -0
  128. package/lib/Types/Socket.js +2 -0
  129. package/lib/Types/State.d.ts +38 -0
  130. package/lib/Types/State.js +12 -0
  131. package/lib/Types/USync.d.ts +25 -0
  132. package/lib/Types/USync.js +1 -0
  133. package/lib/Types/index.d.ts +75 -0
  134. package/lib/Types/index.js +32 -0
  135. package/lib/Utils/auth-utils.d.ts +18 -0
  136. package/lib/Utils/auth-utils.js +289 -0
  137. package/lib/Utils/browser-utils.d.ts +3 -0
  138. package/lib/Utils/browser-utils.js +47 -0
  139. package/lib/Utils/business.d.ts +22 -0
  140. package/lib/Utils/business.js +230 -0
  141. package/lib/Utils/chat-utils.d.ts +69 -0
  142. package/lib/Utils/chat-utils.js +811 -0
  143. package/lib/Utils/companion-reg-client-utils.d.ts +20 -0
  144. package/lib/Utils/companion-reg-client-utils.js +66 -0
  145. package/lib/Utils/crypto.d.ts +41 -0
  146. package/lib/Utils/crypto.js +117 -0
  147. package/lib/Utils/decode-wa-message.d.ts +47 -0
  148. package/lib/Utils/decode-wa-message.js +282 -0
  149. package/lib/Utils/event-buffer.d.ts +35 -0
  150. package/lib/Utils/event-buffer.js +590 -0
  151. package/lib/Utils/generics.d.ts +90 -0
  152. package/lib/Utils/generics.js +384 -0
  153. package/lib/Utils/history.d.ts +21 -0
  154. package/lib/Utils/history.js +130 -0
  155. package/lib/Utils/identity-change-handler.d.ts +36 -0
  156. package/lib/Utils/identity-change-handler.js +48 -0
  157. package/lib/Utils/index.d.ts +25 -0
  158. package/lib/Utils/index.js +24 -0
  159. package/lib/Utils/link-preview.d.ts +20 -0
  160. package/lib/Utils/link-preview.js +84 -0
  161. package/lib/Utils/logger.d.ts +12 -0
  162. package/lib/Utils/logger.js +2 -0
  163. package/lib/Utils/lt-hash.d.ts +10 -0
  164. package/lib/Utils/lt-hash.js +7 -0
  165. package/lib/Utils/make-mutex.d.ts +8 -0
  166. package/lib/Utils/make-mutex.js +32 -0
  167. package/lib/Utils/message-retry-manager.d.ts +109 -0
  168. package/lib/Utils/message-retry-manager.js +224 -0
  169. package/lib/Utils/messages-media.d.ts +129 -0
  170. package/lib/Utils/messages-media.js +784 -0
  171. package/lib/Utils/messages.d.ts +90 -0
  172. package/lib/Utils/messages.js +1240 -0
  173. package/lib/Utils/noise-handler.d.ts +19 -0
  174. package/lib/Utils/noise-handler.js +200 -0
  175. package/lib/Utils/offline-node-processor.d.ts +16 -0
  176. package/lib/Utils/offline-node-processor.js +39 -0
  177. package/lib/Utils/platform-identity.d.ts +14 -0
  178. package/lib/Utils/platform-identity.js +148 -0
  179. package/lib/Utils/pre-key-manager.d.ts +27 -0
  180. package/lib/Utils/pre-key-manager.js +105 -0
  181. package/lib/Utils/process-message.d.ts +59 -0
  182. package/lib/Utils/process-message.js +544 -0
  183. package/lib/Utils/reporting-utils.d.ts +10 -0
  184. package/lib/Utils/reporting-utils.js +257 -0
  185. package/lib/Utils/rich-messages.d.ts +276 -0
  186. package/lib/Utils/rich-messages.js +1143 -0
  187. package/lib/Utils/signal.d.ts +33 -0
  188. package/lib/Utils/signal.js +158 -0
  189. package/lib/Utils/stanza-ack.d.ts +10 -0
  190. package/lib/Utils/stanza-ack.js +37 -0
  191. package/lib/Utils/sticker-pack.d.ts +10 -0
  192. package/lib/Utils/sticker-pack.js +111 -0
  193. package/lib/Utils/sync-action-utils.d.ts +18 -0
  194. package/lib/Utils/sync-action-utils.js +47 -0
  195. package/lib/Utils/tc-token-utils.d.ts +8 -0
  196. package/lib/Utils/tc-token-utils.js +45 -0
  197. package/lib/Utils/use-multi-file-auth-state.d.ts +12 -0
  198. package/lib/Utils/use-multi-file-auth-state.js +120 -0
  199. package/lib/Utils/validate-connection.d.ts +10 -0
  200. package/lib/Utils/validate-connection.js +222 -0
  201. package/lib/VoIP/audio-feeder.d.ts +15 -0
  202. package/lib/VoIP/audio-feeder.js +136 -0
  203. package/lib/VoIP/index.d.ts +12 -0
  204. package/lib/VoIP/index.js +282 -0
  205. package/lib/VoIP/relay-transport.d.ts +43 -0
  206. package/lib/VoIP/relay-transport.js +559 -0
  207. package/lib/VoIP/signaling.js +603 -0
  208. package/lib/VoIP/types.d.ts +69 -0
  209. package/lib/VoIP/types.js +17 -0
  210. package/lib/VoIP/wasm-engine.d.ts +103 -0
  211. package/lib/VoIP/wasm-engine.js +1214 -0
  212. package/lib/VoIP/worker-bootstrap.js +1042 -0
  213. package/lib/WABinary/constants.d.ts +27 -0
  214. package/lib/WABinary/constants.js +1300 -0
  215. package/lib/WABinary/decode.d.ts +6 -0
  216. package/lib/WABinary/decode.js +261 -0
  217. package/lib/WABinary/encode.d.ts +2 -0
  218. package/lib/WABinary/encode.js +219 -0
  219. package/lib/WABinary/generic-utils.d.ts +16 -0
  220. package/lib/WABinary/generic-utils.js +190 -0
  221. package/lib/WABinary/index.d.ts +5 -0
  222. package/lib/WABinary/index.js +5 -0
  223. package/lib/WABinary/jid-utils.d.ts +47 -0
  224. package/lib/WABinary/jid-utils.js +95 -0
  225. package/lib/WABinary/types.d.ts +18 -0
  226. package/lib/WABinary/types.js +1 -0
  227. package/lib/WAM/BinaryInfo.d.ts +8 -0
  228. package/lib/WAM/BinaryInfo.js +9 -0
  229. package/lib/WAM/constants.d.ts +39 -0
  230. package/lib/WAM/constants.js +22852 -0
  231. package/lib/WAM/encode.d.ts +2 -0
  232. package/lib/WAM/encode.js +149 -0
  233. package/lib/WAM/index.d.ts +3 -0
  234. package/lib/WAM/index.js +3 -0
  235. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  236. package/lib/WAUSync/Protocols/USyncContactProtocol.js +28 -0
  237. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  238. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
  239. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  240. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  241. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  242. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  243. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +25 -0
  244. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +50 -0
  245. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +9 -0
  246. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  247. package/lib/WAUSync/Protocols/index.d.ts +4 -0
  248. package/lib/WAUSync/Protocols/index.js +4 -0
  249. package/lib/WAUSync/USyncQuery.d.ts +28 -0
  250. package/lib/WAUSync/USyncQuery.js +93 -0
  251. package/lib/WAUSync/USyncUser.d.ts +12 -0
  252. package/lib/WAUSync/USyncUser.js +22 -0
  253. package/lib/WAUSync/index.d.ts +3 -0
  254. package/lib/WAUSync/index.js +3 -0
  255. package/lib/assets/wasm/loader.js +5 -0
  256. package/lib/assets/wasm/whatsapp.wasm +0 -0
  257. package/lib/assets/wasm/worker-modules.js +273 -0
  258. package/lib/index.d.ts +21 -0
  259. package/lib/index.js +22 -0
  260. package/package.json +111 -0
@@ -0,0 +1,384 @@
1
+ import { Boom } from '@hapi/boom';
2
+ import { createHash, randomBytes } from 'crypto';
3
+ import { proto } from '../../WAProto/index.js';
4
+ const bibzWhatsVersion = [2, 3000, 1046721733];
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
+ // inspired from whatsmeow code
133
+ // https://github.com/tulir/whatsmeow/blob/64bc969fbe78d31ae0dd443b8d4c80a5d026d07a/send.go#L42
134
+ export const generateMessageIDV2 = (userId) => {
135
+ const data = Buffer.alloc(8 + 20 + 16);
136
+ data.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000)));
137
+ if (userId) {
138
+ const id = jidDecode(userId);
139
+ if (id?.user) {
140
+ data.write(id.user, 8);
141
+ data.write('@c.us', 8 + id.user.length);
142
+ }
143
+ }
144
+ const random = randomBytes(16);
145
+ random.copy(data, 28);
146
+ const hash = createHash('sha256').update(data).digest();
147
+ return '3EB0' + hash.toString('hex').toUpperCase().substring(0, 18);
148
+ };
149
+ // generate a random ID to attach to a message
150
+ export const generateMessageID = () => '3EB0' + randomBytes(18).toString('hex').toUpperCase();
151
+ export function bindWaitForEvent(ev, event) {
152
+ return async (check, timeoutMs) => {
153
+ let listener;
154
+ let closeListener;
155
+ await promiseTimeout(timeoutMs, (resolve, reject) => {
156
+ closeListener = ({ connection, lastDisconnect }) => {
157
+ if (connection === 'close') {
158
+ reject(lastDisconnect?.error || new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed }));
159
+ }
160
+ };
161
+ ev.on('connection.update', closeListener);
162
+ listener = async (update) => {
163
+ if (await check(update)) {
164
+ resolve();
165
+ }
166
+ };
167
+ ev.on(event, listener);
168
+ }).finally(() => {
169
+ ev.off(event, listener);
170
+ ev.off('connection.update', closeListener);
171
+ });
172
+ };
173
+ }
174
+ export const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, 'connection.update');
175
+ /**
176
+ * utility that fetches latest upstream (WhiskeySockets/Baileys) version from the master branch.
177
+ * BibzWhats: gunakan fetchLatestWaWebVersion() untuk versi WA Web terkini.
178
+ * Use to ensure your WA connection is always on the latest version
179
+ */
180
+ export const fetchLatestBaileysVersion = async (options = {}) => {
181
+ const URL = 'https://raw.githubusercontent.com/WhiskeySockets/Baileys/master/src/Defaults/index.ts';
182
+ try {
183
+ const response = await fetch(URL, {
184
+ dispatcher: options.dispatcher,
185
+ method: 'GET',
186
+ headers: options.headers
187
+ });
188
+ if (!response.ok) {
189
+ throw new Boom(`Failed to fetch latest Baileys version: ${response.statusText}`, { statusCode: response.status });
190
+ }
191
+ const text = await response.text();
192
+ // Extract version from line 7 (const version = [...])
193
+ const lines = text.split('\n');
194
+ const versionLine = lines[6]; // Line 7 (0-indexed)
195
+ const versionMatch = versionLine.match(/const version = \[(\d+),\s*(\d+),\s*(\d+)\]/);
196
+ if (versionMatch) {
197
+ const version = [parseInt(versionMatch[1]), parseInt(versionMatch[2]), parseInt(versionMatch[3])];
198
+ return {
199
+ version,
200
+ isLatest: true
201
+ };
202
+ }
203
+ else {
204
+ throw new Error('Could not parse version from Defaults/index.ts');
205
+ }
206
+ }
207
+ catch (error) {
208
+ return {
209
+ version: bibzWhatsVersion,
210
+ isLatest: false,
211
+ error
212
+ };
213
+ }
214
+ };
215
+ /**
216
+ * A utility that fetches the latest web version of whatsapp.
217
+ * Use to ensure your WA connection is always on the latest version
218
+ */
219
+ export const fetchLatestWaWebVersion = async (options = {}) => {
220
+ try {
221
+ // Absolute minimal headers required to bypass anti-bot detection
222
+ const defaultHeaders = {
223
+ 'sec-fetch-site': 'none',
224
+ 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
225
+ };
226
+ const headers = { ...defaultHeaders, ...options.headers };
227
+ const response = await fetch('https://web.whatsapp.com/sw.js', {
228
+ ...options,
229
+ method: 'GET',
230
+ headers
231
+ });
232
+ if (!response.ok) {
233
+ throw new Boom(`Failed to fetch sw.js: ${response.statusText}`, { statusCode: response.status });
234
+ }
235
+ const data = await response.text();
236
+ const regex = /\\?"client_revision\\?":\s*(\d+)/;
237
+ const match = data.match(regex);
238
+ if (!match?.[1]) {
239
+ return {
240
+ version: bibzWhatsVersion,
241
+ isLatest: false,
242
+ error: {
243
+ message: 'Could not find client revision in the fetched content'
244
+ }
245
+ };
246
+ }
247
+ const clientRevision = match[1];
248
+ return {
249
+ version: [2, 3000, +clientRevision],
250
+ isLatest: true
251
+ };
252
+ }
253
+ catch (error) {
254
+ return {
255
+ version: bibzWhatsVersion,
256
+ isLatest: false,
257
+ error
258
+ };
259
+ }
260
+ };
261
+ /** unique message tag prefix for MD clients */
262
+ export const generateMdTagPrefix = () => {
263
+ const bytes = randomBytes(4);
264
+ return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`;
265
+ };
266
+ const STATUS_MAP = {
267
+ sender: proto.WebMessageInfo.Status.SERVER_ACK,
268
+ played: proto.WebMessageInfo.Status.PLAYED,
269
+ read: proto.WebMessageInfo.Status.READ,
270
+ 'read-self': proto.WebMessageInfo.Status.READ
271
+ };
272
+ /**
273
+ * Given a type of receipt, returns what the new status of the message should be
274
+ * @param type type from receipt
275
+ */
276
+ export const getStatusFromReceiptType = (type) => {
277
+ const status = STATUS_MAP[type];
278
+ if (typeof type === 'undefined') {
279
+ return proto.WebMessageInfo.Status.DELIVERY_ACK;
280
+ }
281
+ return status;
282
+ };
283
+ const CODE_MAP = {
284
+ conflict: DisconnectReason.connectionReplaced
285
+ };
286
+ /**
287
+ * Stream errors generally provide a reason, map that to a baileys DisconnectReason
288
+ * @param reason the string reason given, eg. "conflict"
289
+ */
290
+ export const getErrorCodeFromStreamError = (node) => {
291
+ const [reasonNode] = getAllBinaryNodeChildren(node);
292
+ let reason = reasonNode?.tag || 'unknown';
293
+ const statusCode = +(node.attrs.code || CODE_MAP[reason] || DisconnectReason.badSession);
294
+ if (statusCode === DisconnectReason.restartRequired) {
295
+ reason = 'restart required';
296
+ }
297
+ return {
298
+ reason,
299
+ statusCode
300
+ };
301
+ };
302
+ export const getCallStatusFromNode = ({ tag, attrs }) => {
303
+ let status;
304
+ switch (tag) {
305
+ case 'offer':
306
+ case 'offer_notice':
307
+ status = 'offer';
308
+ break;
309
+ case 'terminate':
310
+ if (attrs.reason === 'timeout') {
311
+ status = 'timeout';
312
+ }
313
+ else {
314
+ //fired when accepted/rejected/timeout/caller hangs up
315
+ status = 'terminate';
316
+ }
317
+ break;
318
+ case 'reject':
319
+ status = 'reject';
320
+ break;
321
+ case 'accept':
322
+ status = 'accept';
323
+ break;
324
+ default:
325
+ status = 'ringing';
326
+ break;
327
+ }
328
+ return status;
329
+ };
330
+ const UNEXPECTED_SERVER_CODE_TEXT = 'Unexpected server response: ';
331
+ export const getCodeFromWSError = (error) => {
332
+ let statusCode = 500;
333
+ if (error?.message?.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
334
+ const code = +error?.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length);
335
+ if (!Number.isNaN(code) && code >= 400) {
336
+ statusCode = code;
337
+ }
338
+ }
339
+ else if (
340
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
341
+ error?.code?.startsWith('E') ||
342
+ error?.message?.includes('timed out')) {
343
+ // handle ETIMEOUT, ENOTFOUND etc
344
+ statusCode = 408;
345
+ }
346
+ return statusCode;
347
+ };
348
+ /**
349
+ * Is the given platform WA business
350
+ * @param platform AuthenticationCreds.platform
351
+ */
352
+ export const isWABusinessPlatform = (platform) => {
353
+ return platform === 'smbi' || platform === 'smba';
354
+ };
355
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
356
+ export function trimUndefined(obj) {
357
+ for (const key in obj) {
358
+ if (typeof obj[key] === 'undefined') {
359
+ delete obj[key];
360
+ }
361
+ }
362
+ return obj;
363
+ }
364
+ const CROCKFORD_CHARACTERS = '123456789ABCDEFGHJKLMNPQRSTVWXYZ';
365
+ export function bytesToCrockford(buffer) {
366
+ let value = 0;
367
+ let bitCount = 0;
368
+ const crockford = [];
369
+ for (const element of buffer) {
370
+ value = (value << 8) | (element & 0xff);
371
+ bitCount += 8;
372
+ while (bitCount >= 5) {
373
+ crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31));
374
+ bitCount -= 5;
375
+ }
376
+ }
377
+ if (bitCount > 0) {
378
+ crockford.push(CROCKFORD_CHARACTERS.charAt((value << (5 - bitCount)) & 31));
379
+ }
380
+ return crockford.join('');
381
+ }
382
+ export function encodeNewsletterMessage(message) {
383
+ return proto.Message.encode(message).finish();
384
+ }
@@ -0,0 +1,21 @@
1
+ import { proto } from '../../WAProto/index.js';
2
+ import type { Chat, Contact, LIDMapping, WAMessage } from '../Types/index.js';
3
+ import type { ILogger } from './logger.js';
4
+ export declare const downloadHistory: (msg: proto.Message.IHistorySyncNotification, options: RequestInit) => Promise<proto.HistorySync>;
5
+ export declare const processHistoryMessage: (item: proto.IHistorySync, logger?: ILogger) => {
6
+ chats: Chat[];
7
+ contacts: Contact[];
8
+ messages: WAMessage[];
9
+ lidPnMappings: LIDMapping[];
10
+ syncType: proto.HistorySync.HistorySyncType | null | undefined;
11
+ progress: number | null | undefined;
12
+ };
13
+ export declare const downloadAndProcessHistorySyncNotification: (msg: proto.Message.IHistorySyncNotification, options: RequestInit, logger?: ILogger) => Promise<{
14
+ chats: Chat[];
15
+ contacts: Contact[];
16
+ messages: WAMessage[];
17
+ lidPnMappings: LIDMapping[];
18
+ syncType: proto.HistorySync.HistorySyncType | null | undefined;
19
+ progress: number | null | undefined;
20
+ }>;
21
+ export declare const getHistoryMsg: (message: proto.IMessage) => proto.Message.IHistorySyncNotification;
@@ -0,0 +1,130 @@
1
+ import { promisify } from 'util';
2
+ import { inflate } from 'zlib';
3
+ import { proto } from '../../WAProto/index.js';
4
+ import { WAMessageStubType } from '../Types/index.js';
5
+ import { isHostedLidUser, isHostedPnUser, isLidUser, isPnUser } from '../WABinary/index.js';
6
+ import { toNumber } from './generics.js';
7
+ import { normalizeMessageContent } from './messages.js';
8
+ import { downloadContentFromMessage } from './messages-media.js';
9
+ const inflatePromise = promisify(inflate);
10
+ const extractPnFromMessages = (messages) => {
11
+ for (const msgItem of messages) {
12
+ const message = msgItem.message;
13
+ // Only extract from outgoing messages (fromMe: true) in 1:1 chats
14
+ // because userReceipt.userJid is the recipient's JID
15
+ if (!message?.key?.fromMe || !message.userReceipt?.length) {
16
+ continue;
17
+ }
18
+ const userJid = message.userReceipt[0]?.userJid;
19
+ if (userJid && (isPnUser(userJid) || isHostedPnUser(userJid))) {
20
+ return userJid;
21
+ }
22
+ }
23
+ return undefined;
24
+ };
25
+ export const downloadHistory = async (msg, options) => {
26
+ const stream = await downloadContentFromMessage(msg, 'md-msg-hist', { options });
27
+ const bufferArray = [];
28
+ for await (const chunk of stream) {
29
+ bufferArray.push(chunk);
30
+ }
31
+ let buffer = Buffer.concat(bufferArray);
32
+ // decompress buffer
33
+ buffer = await inflatePromise(buffer);
34
+ const syncData = proto.HistorySync.decode(buffer);
35
+ return syncData;
36
+ };
37
+ export const processHistoryMessage = (item, logger) => {
38
+ const messages = [];
39
+ const contacts = [];
40
+ const chats = [];
41
+ const lidPnMappings = [];
42
+ logger?.trace({ progress: item.progress }, 'processing history of type ' + item.syncType?.toString());
43
+ // Extract LID-PN mappings for all sync types
44
+ for (const m of item.phoneNumberToLidMappings || []) {
45
+ if (m.lidJid && m.pnJid) {
46
+ lidPnMappings.push({ lid: m.lidJid, pn: m.pnJid });
47
+ }
48
+ }
49
+ switch (item.syncType) {
50
+ case proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:
51
+ case proto.HistorySync.HistorySyncType.RECENT:
52
+ case proto.HistorySync.HistorySyncType.FULL:
53
+ case proto.HistorySync.HistorySyncType.ON_DEMAND:
54
+ for (const chat of item.conversations) {
55
+ contacts.push({
56
+ id: chat.id,
57
+ name: chat.displayName || chat.name || chat.username || undefined,
58
+ lid: chat.lidJid || chat.accountLid || undefined,
59
+ phoneNumber: chat.pnJid || undefined
60
+ });
61
+ const chatId = chat.id;
62
+ const isLid = isLidUser(chatId) || isHostedLidUser(chatId);
63
+ const isPn = isPnUser(chatId) || isHostedPnUser(chatId);
64
+ if (isLid && chat.pnJid) {
65
+ lidPnMappings.push({ lid: chatId, pn: chat.pnJid });
66
+ }
67
+ else if (isPn && chat.lidJid) {
68
+ lidPnMappings.push({ lid: chat.lidJid, pn: chatId });
69
+ }
70
+ else if (isLid && !chat.pnJid) {
71
+ // Fallback: extract PN from userReceipt in messages when pnJid is missing
72
+ const pnFromReceipt = extractPnFromMessages(chat.messages || []);
73
+ if (pnFromReceipt) {
74
+ lidPnMappings.push({ lid: chatId, pn: pnFromReceipt });
75
+ }
76
+ }
77
+ const msgs = chat.messages || [];
78
+ delete chat.messages;
79
+ for (const item of msgs) {
80
+ const message = item.message;
81
+ messages.push(message);
82
+ if (!chat.messages?.length) {
83
+ // keep only the most recent message in the chat array
84
+ chat.messages = [{ message }];
85
+ }
86
+ if (!message.key.fromMe && !chat.lastMessageRecvTimestamp) {
87
+ chat.lastMessageRecvTimestamp = toNumber(message.messageTimestamp);
88
+ }
89
+ if ((message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP ||
90
+ message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB) &&
91
+ message.messageStubParameters?.[0]) {
92
+ contacts.push({
93
+ id: message.key.participant || message.key.remoteJid,
94
+ verifiedName: message.messageStubParameters?.[0]
95
+ });
96
+ }
97
+ }
98
+ chats.push({ ...chat });
99
+ }
100
+ break;
101
+ case proto.HistorySync.HistorySyncType.PUSH_NAME:
102
+ for (const c of item.pushnames) {
103
+ contacts.push({ id: c.id, notify: c.pushname });
104
+ }
105
+ break;
106
+ }
107
+ return {
108
+ chats,
109
+ contacts,
110
+ messages,
111
+ lidPnMappings,
112
+ syncType: item.syncType,
113
+ progress: item.progress
114
+ };
115
+ };
116
+ export const downloadAndProcessHistorySyncNotification = async (msg, options, logger) => {
117
+ let historyMsg;
118
+ if (msg.initialHistBootstrapInlinePayload) {
119
+ historyMsg = proto.HistorySync.decode(await inflatePromise(msg.initialHistBootstrapInlinePayload));
120
+ }
121
+ else {
122
+ historyMsg = await downloadHistory(msg, options);
123
+ }
124
+ return processHistoryMessage(historyMsg, logger);
125
+ };
126
+ export const getHistoryMsg = (message) => {
127
+ const normalizedContent = !!message ? normalizeMessageContent(message) : undefined;
128
+ const anyHistoryMsg = normalizedContent?.protocolMessage?.historySyncNotification;
129
+ return anyHistoryMsg;
130
+ };
@@ -0,0 +1,36 @@
1
+ import NodeCache from '@cacheable/node-cache';
2
+ import { type BinaryNode } from '../WABinary/index.js';
3
+ import type { ILogger } from './logger.js';
4
+ export type IdentityChangeResult = {
5
+ action: 'no_identity_node';
6
+ } | {
7
+ action: 'invalid_notification';
8
+ } | {
9
+ action: 'skipped_companion_device';
10
+ device: number;
11
+ } | {
12
+ action: 'skipped_self_primary';
13
+ } | {
14
+ action: 'debounced';
15
+ } | {
16
+ action: 'skipped_offline';
17
+ } | {
18
+ action: 'skipped_no_session';
19
+ } | {
20
+ action: 'session_refreshed';
21
+ } | {
22
+ action: 'session_refresh_failed';
23
+ error: unknown;
24
+ };
25
+ export type IdentityChangeContext = {
26
+ meId: string | undefined;
27
+ meLid: string | undefined;
28
+ validateSession: (jid: string) => Promise<{
29
+ exists: boolean;
30
+ reason?: string;
31
+ }>;
32
+ assertSessions: (jids: string[], force?: boolean) => Promise<boolean>;
33
+ debounceCache: NodeCache<boolean>;
34
+ logger: ILogger;
35
+ };
36
+ export declare function handleIdentityChange(node: BinaryNode, ctx: IdentityChangeContext): Promise<IdentityChangeResult>;
@@ -0,0 +1,48 @@
1
+ import NodeCache from '@cacheable/node-cache';
2
+ import { areJidsSameUser, getBinaryNodeChild, jidDecode } from '../WABinary/index.js';
3
+ import { isStringNullOrEmpty } from './generics.js';
4
+ export async function handleIdentityChange(node, ctx) {
5
+ const from = node.attrs.from;
6
+ if (!from) {
7
+ return { action: 'invalid_notification' };
8
+ }
9
+ const identityNode = getBinaryNodeChild(node, 'identity');
10
+ if (!identityNode) {
11
+ return { action: 'no_identity_node' };
12
+ }
13
+ ctx.logger.info({ jid: from }, 'identity changed');
14
+ const decoded = jidDecode(from);
15
+ if (decoded?.device && decoded.device !== 0) {
16
+ ctx.logger.debug({ jid: from, device: decoded.device }, 'ignoring identity change from companion device');
17
+ return { action: 'skipped_companion_device', device: decoded.device };
18
+ }
19
+ const isSelfPrimary = ctx.meId && (areJidsSameUser(from, ctx.meId) || (ctx.meLid && areJidsSameUser(from, ctx.meLid)));
20
+ if (isSelfPrimary) {
21
+ ctx.logger.info({ jid: from }, 'self primary identity changed');
22
+ return { action: 'skipped_self_primary' };
23
+ }
24
+ if (ctx.debounceCache.get(from)) {
25
+ ctx.logger.debug({ jid: from }, 'skipping identity assert (debounced)');
26
+ return { action: 'debounced' };
27
+ }
28
+ ctx.debounceCache.set(from, true);
29
+ const isOfflineNotification = !isStringNullOrEmpty(node.attrs.offline);
30
+ const hasExistingSession = await ctx.validateSession(from);
31
+ if (!hasExistingSession.exists) {
32
+ ctx.logger.debug({ jid: from }, 'no old session, skipping session refresh');
33
+ return { action: 'skipped_no_session' };
34
+ }
35
+ ctx.logger.debug({ jid: from }, 'old session exists, will refresh session');
36
+ if (isOfflineNotification) {
37
+ ctx.logger.debug({ jid: from }, 'skipping session refresh during offline processing');
38
+ return { action: 'skipped_offline' };
39
+ }
40
+ try {
41
+ await ctx.assertSessions([from], true);
42
+ return { action: 'session_refreshed' };
43
+ }
44
+ catch (error) {
45
+ ctx.logger.warn({ error, jid: from }, 'failed to assert sessions after identity change');
46
+ return { action: 'session_refresh_failed', error };
47
+ }
48
+ }
@@ -0,0 +1,25 @@
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 "./identity-change-handler.js";
20
+ export * from "./stanza-ack.js";
21
+ export * from "./rich-messages.js";
22
+ export * from "./sticker-pack.js";
23
+ export * from './companion-reg-client-utils.js';
24
+
25
+ export * from "./platform-identity.js";
@@ -0,0 +1,24 @@
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 './platform-identity.js';
20
+ export * from './identity-change-handler.js';
21
+ export * from './stanza-ack.js';
22
+ export * from './rich-messages.js';
23
+ export * from './sticker-pack.js';
24
+ export * from './companion-reg-client-utils.js';