@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,33 @@
1
+ import type { SignalRepositoryWithLIDStore } from '../Types/index.js';
2
+ import type { AuthenticationCreds, AuthenticationState, KeyPair, SignalIdentity, SignalKeyStore, SignedKeyPair } from '../Types/Auth.js';
3
+ import { type BinaryNode, type FullJid } from '../WABinary/index.js';
4
+ import type { USyncQueryResultList } from '../WAUSync/index.js';
5
+ export declare const createSignalIdentity: (wid: string, accountSignatureKey: Uint8Array) => SignalIdentity;
6
+ export declare const getPreKeys: ({ get }: SignalKeyStore, min: number, limit: number) => Promise<{
7
+ [id: string]: KeyPair;
8
+ }>;
9
+ export declare const generateOrGetPreKeys: (creds: AuthenticationCreds, range: number) => {
10
+ newPreKeys: {
11
+ [id: number]: KeyPair;
12
+ };
13
+ lastPreKeyId: number;
14
+ preKeysRange: readonly [number, number];
15
+ };
16
+ export declare const xmppSignedPreKey: (key: SignedKeyPair) => BinaryNode;
17
+ export declare const xmppPreKey: (pair: KeyPair, id: number) => BinaryNode;
18
+ export declare const parseAndInjectE2ESessions: (node: BinaryNode, repository: SignalRepositoryWithLIDStore) => Promise<void>;
19
+ export declare const extractDeviceJids: (result: USyncQueryResultList[], myJid: string, myLid: string, excludeZeroDevices: boolean) => FullJid[];
20
+ /**
21
+ * get the next N keys for upload or processing
22
+ * @param count number of pre-keys to get or generate
23
+ */
24
+ export declare const getNextPreKeys: ({ creds, keys }: AuthenticationState, count: number) => Promise<{
25
+ update: Partial<AuthenticationCreds>;
26
+ preKeys: {
27
+ [id: string]: KeyPair;
28
+ };
29
+ }>;
30
+ export declare const getNextPreKeysNode: (state: AuthenticationState, count: number) => Promise<{
31
+ update: Partial<AuthenticationCreds>;
32
+ node: BinaryNode;
33
+ }>;
@@ -0,0 +1,158 @@
1
+ import { KEY_BUNDLE_TYPE } from '../Defaults/index.js';
2
+ import { assertNodeErrorFree, getBinaryNodeChild, getBinaryNodeChildBuffer, getBinaryNodeChildren, getBinaryNodeChildUInt, getServerFromDomainType, jidDecode, S_WHATSAPP_NET, WAJIDDomains } from '../WABinary/index.js';
3
+ import { Curve, generateSignalPubKey } from './crypto.js';
4
+ import { encodeBigEndian } from './generics.js';
5
+ function chunk(array, size) {
6
+ const chunks = [];
7
+ for (let i = 0; i < array.length; i += size) {
8
+ chunks.push(array.slice(i, i + size));
9
+ }
10
+ return chunks;
11
+ }
12
+ export const createSignalIdentity = (wid, accountSignatureKey) => {
13
+ return {
14
+ identifier: { name: wid, deviceId: 0 },
15
+ identifierKey: generateSignalPubKey(accountSignatureKey)
16
+ };
17
+ };
18
+ export const getPreKeys = async ({ get }, min, limit) => {
19
+ const idList = [];
20
+ for (let id = min; id < limit; id++) {
21
+ idList.push(id.toString());
22
+ }
23
+ return get('pre-key', idList);
24
+ };
25
+ export const generateOrGetPreKeys = (creds, range) => {
26
+ const avaliable = creds.nextPreKeyId - creds.firstUnuploadedPreKeyId;
27
+ const remaining = range - avaliable;
28
+ const lastPreKeyId = creds.nextPreKeyId + remaining - 1;
29
+ const newPreKeys = {};
30
+ if (remaining > 0) {
31
+ for (let i = creds.nextPreKeyId; i <= lastPreKeyId; i++) {
32
+ newPreKeys[i] = Curve.generateKeyPair();
33
+ }
34
+ }
35
+ return {
36
+ newPreKeys,
37
+ lastPreKeyId,
38
+ preKeysRange: [creds.firstUnuploadedPreKeyId, range]
39
+ };
40
+ };
41
+ export const xmppSignedPreKey = (key) => ({
42
+ tag: 'skey',
43
+ attrs: {},
44
+ content: [
45
+ { tag: 'id', attrs: {}, content: encodeBigEndian(key.keyId, 3) },
46
+ { tag: 'value', attrs: {}, content: key.keyPair.public },
47
+ { tag: 'signature', attrs: {}, content: key.signature }
48
+ ]
49
+ });
50
+ export const xmppPreKey = (pair, id) => ({
51
+ tag: 'key',
52
+ attrs: {},
53
+ content: [
54
+ { tag: 'id', attrs: {}, content: encodeBigEndian(id, 3) },
55
+ { tag: 'value', attrs: {}, content: pair.public }
56
+ ]
57
+ });
58
+ export const parseAndInjectE2ESessions = async (node, repository) => {
59
+ const extractKey = (key) => key
60
+ ? {
61
+ keyId: getBinaryNodeChildUInt(key, 'id', 3),
62
+ publicKey: generateSignalPubKey(getBinaryNodeChildBuffer(key, 'value')),
63
+ signature: getBinaryNodeChildBuffer(key, 'signature')
64
+ }
65
+ : undefined;
66
+ const nodes = getBinaryNodeChildren(getBinaryNodeChild(node, 'list'), 'user');
67
+ for (const node of nodes) {
68
+ assertNodeErrorFree(node);
69
+ }
70
+ // Most of the work in repository.injectE2ESession is CPU intensive, not IO
71
+ // So Promise.all doesn't really help here,
72
+ // but blocks even loop if we're using it inside keys.transaction, and it makes it "sync" actually
73
+ // This way we chunk it in smaller parts and between those parts we can yield to the event loop
74
+ // It's rare case when you need to E2E sessions for so many users, but it's possible
75
+ const chunkSize = 100;
76
+ const chunks = chunk(nodes, chunkSize);
77
+ for (const nodesChunk of chunks) {
78
+ for (const node of nodesChunk) {
79
+ const signedKey = getBinaryNodeChild(node, 'skey');
80
+ const key = getBinaryNodeChild(node, 'key');
81
+ const identity = getBinaryNodeChildBuffer(node, 'identity');
82
+ const jid = node.attrs.jid;
83
+ const registrationId = getBinaryNodeChildUInt(node, 'registration', 4);
84
+ await repository.injectE2ESession({
85
+ jid,
86
+ session: {
87
+ registrationId: registrationId,
88
+ identityKey: generateSignalPubKey(identity),
89
+ signedPreKey: extractKey(signedKey),
90
+ preKey: extractKey(key)
91
+ }
92
+ });
93
+ }
94
+ }
95
+ };
96
+ export const extractDeviceJids = (result, myJid, myLid, excludeZeroDevices) => {
97
+ const { user: myUser, device: myDevice } = jidDecode(myJid);
98
+ const extracted = [];
99
+ for (const userResult of result) {
100
+ const { devices, id } = userResult;
101
+ const decoded = jidDecode(id), { user, server } = decoded;
102
+ let { domainType } = decoded;
103
+ const deviceList = devices?.deviceList;
104
+ if (!Array.isArray(deviceList))
105
+ continue;
106
+ for (const { id: device, keyIndex, isHosted } of deviceList) {
107
+ if ((!excludeZeroDevices || device !== 0) && // if zero devices are not-excluded, or device is non zero
108
+ ((myUser !== user && myLid !== user) || myDevice !== device) && // either different user or if me user, not this device
109
+ (device === 0 || !!keyIndex) // ensure that "key-index" is specified for "non-zero" devices, produces a bad req otherwise
110
+ ) {
111
+ if (isHosted) {
112
+ domainType = domainType === WAJIDDomains.LID ? WAJIDDomains.HOSTED_LID : WAJIDDomains.HOSTED;
113
+ }
114
+ extracted.push({
115
+ user,
116
+ device,
117
+ domainType,
118
+ server: getServerFromDomainType(server, domainType)
119
+ });
120
+ }
121
+ }
122
+ }
123
+ return extracted;
124
+ };
125
+ /**
126
+ * get the next N keys for upload or processing
127
+ * @param count number of pre-keys to get or generate
128
+ */
129
+ export const getNextPreKeys = async ({ creds, keys }, count) => {
130
+ const { newPreKeys, lastPreKeyId, preKeysRange } = generateOrGetPreKeys(creds, count);
131
+ const update = {
132
+ nextPreKeyId: Math.max(lastPreKeyId + 1, creds.nextPreKeyId),
133
+ firstUnuploadedPreKeyId: Math.max(creds.firstUnuploadedPreKeyId, lastPreKeyId + 1)
134
+ };
135
+ await keys.set({ 'pre-key': newPreKeys });
136
+ const preKeys = await getPreKeys(keys, preKeysRange[0], preKeysRange[0] + preKeysRange[1]);
137
+ return { update, preKeys };
138
+ };
139
+ export const getNextPreKeysNode = async (state, count) => {
140
+ const { creds } = state;
141
+ const { update, preKeys } = await getNextPreKeys(state, count);
142
+ const node = {
143
+ tag: 'iq',
144
+ attrs: {
145
+ xmlns: 'encrypt',
146
+ type: 'set',
147
+ to: S_WHATSAPP_NET
148
+ },
149
+ content: [
150
+ { tag: 'registration', attrs: {}, content: encodeBigEndian(creds.registrationId) },
151
+ { tag: 'type', attrs: {}, content: KEY_BUNDLE_TYPE },
152
+ { tag: 'identity', attrs: {}, content: creds.signedIdentityKey.public },
153
+ { tag: 'list', attrs: {}, content: Object.keys(preKeys).map(k => xmppPreKey(preKeys[+k], +k)) },
154
+ xmppSignedPreKey(creds.signedPreKey)
155
+ ]
156
+ };
157
+ return { update, node };
158
+ };
@@ -0,0 +1,10 @@
1
+ import type { BinaryNode } from '../WABinary/index.js';
2
+ /**
3
+ * Builds an ACK stanza for a received node.
4
+ * Pure function -- no I/O, no side effects.
5
+ *
6
+ * Mirrors WhatsApp Web's ACK construction:
7
+ * - WAWebHandleMsgSendAck.sendAck / sendNack
8
+ * - WAWebCreateNackFromStanza.createNackFromStanza
9
+ */
10
+ export declare function buildAckStanza(node: BinaryNode, errorCode?: number, meId?: string): BinaryNode;
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Builds an ACK stanza for a received node.
3
+ * Pure function -- no I/O, no side effects.
4
+ *
5
+ * Mirrors WhatsApp Web's ACK construction:
6
+ * - WAWebHandleMsgSendAck.sendAck / sendNack
7
+ * - WAWebCreateNackFromStanza.createNackFromStanza
8
+ */
9
+ export function buildAckStanza(node, errorCode, meId) {
10
+ const { tag, attrs } = node;
11
+ const stanza = {
12
+ tag: 'ack',
13
+ attrs: {
14
+ id: attrs.id,
15
+ to: attrs.from,
16
+ class: tag
17
+ }
18
+ };
19
+ if (errorCode) {
20
+ stanza.attrs.error = errorCode.toString();
21
+ }
22
+ if (attrs.participant) {
23
+ stanza.attrs.participant = attrs.participant;
24
+ }
25
+ if (attrs.recipient) {
26
+ stanza.attrs.recipient = attrs.recipient;
27
+ }
28
+ // WA Web always includes type when present: `n.type || DROP_ATTR`
29
+ if (attrs.type) {
30
+ stanza.attrs.type = attrs.type;
31
+ }
32
+ // WA Web WAWebHandleMsgSendAck.sendAck/sendNack always include `from` for message-class ACKs
33
+ if (tag === 'message' && meId) {
34
+ stanza.attrs.from = meId;
35
+ }
36
+ return stanza;
37
+ }
@@ -0,0 +1,10 @@
1
+ import type { StickerPackContent } from '../Types/Message.js';
2
+ export type MakeStickerPackOptions = StickerPackContent & {
3
+ contextInfo?: any;
4
+ };
5
+ export declare const makeStickerPack: (
6
+ options?: MakeStickerPackOptions,
7
+ ) => {
8
+ stickerPack: StickerPackContent;
9
+ contextInfo?: any;
10
+ };
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Default emojis assigned to stickers when none are provided.
3
+ * Rotates through this list by sticker index.
4
+ */
5
+ const DEFAULT_EMOJIS = [
6
+ "😀",
7
+ "😂",
8
+ "😍",
9
+ "🔥",
10
+ "👍",
11
+ "🎉",
12
+ "😎",
13
+ "🤩",
14
+ "💯",
15
+ "🥳",
16
+ ];
17
+
18
+ /**
19
+ * Normalize a single sticker entry.
20
+ * Input can be:
21
+ * - Buffer
22
+ * - { url: string }
23
+ * - { sticker: Buffer | { url: string }, emojis?: string[], accessibilityLabel?: string }
24
+ *
25
+ * @param {Buffer | { url: string } | object} entry
26
+ * @param {number} index
27
+ * @returns {{ sticker: Buffer | { url: string }, emojis: string[], accessibilityLabel: string }}
28
+ */
29
+ const normalizeSticker = (entry, index) => {
30
+ if (
31
+ Buffer.isBuffer(entry) ||
32
+ (entry &&
33
+ typeof entry === "object" &&
34
+ "url" in entry &&
35
+ !("sticker" in entry))
36
+ ) {
37
+ return {
38
+ sticker: entry,
39
+ emojis: [DEFAULT_EMOJIS[index % DEFAULT_EMOJIS.length]],
40
+ accessibilityLabel: "",
41
+ };
42
+ }
43
+ return {
44
+ sticker: entry.sticker || entry.data,
45
+ emojis: entry.emojis || [DEFAULT_EMOJIS[index % DEFAULT_EMOJIS.length]],
46
+ accessibilityLabel: entry.accessibilityLabel || "",
47
+ };
48
+ };
49
+
50
+ /**
51
+ * Build a stickerPack message object ready to pass to sock.sendMessage.
52
+ *
53
+ * @param {object} options
54
+ * @param {string} options.name - Pack display name
55
+ * @param {string} [options.publisher] - Pack publisher/author name
56
+ * @param {string} [options.description] - Pack description
57
+ * @param {string} [options.packId] - Custom pack ID (auto-generated if omitted)
58
+ * @param {Array<Buffer | { url: string } | { sticker: Buffer | { url: string }, emojis?: string[] }>} options.stickers
59
+ * List of stickers — accepts raw buffers, URL objects, or full sticker descriptor objects.
60
+ * @param {Buffer | { url: string }} [options.cover]
61
+ * Tray/cover image. Defaults to the first sticker if omitted.
62
+ * @param {object} [options.contextInfo] - Optional context info (mentions, forwarding, etc.)
63
+ * @returns {{ stickerPack: object }}
64
+ *
65
+ * @example
66
+ * // With buffers
67
+ * await sock.sendMessage(jid, makeStickerPack({
68
+ * name: 'My Pack',
69
+ * stickers: [buf1, buf2, buf3]
70
+ * }));
71
+ *
72
+ * @example
73
+ * // With URLs
74
+ * await sock.sendMessage(jid, makeStickerPack({
75
+ * name: 'Anime Pack',
76
+ * publisher: 'WhatsBibz',
77
+ * stickers: [
78
+ * { url: 'https://example.com/s1.webp', emojis: ['😀'] },
79
+ * { url: 'https://example.com/s2.webp' }
80
+ * ],
81
+ * cover: { url: 'https://example.com/cover.jpg' }
82
+ * }));
83
+ */
84
+ export const makeStickerPack = ({
85
+ name,
86
+ publisher = "WhatsBibz",
87
+ description = "",
88
+ packId,
89
+ stickers = [],
90
+ cover,
91
+ contextInfo,
92
+ } = {}) => {
93
+ if (!name) throw new Error("makeStickerPack: name is required");
94
+ if (!stickers.length)
95
+ throw new Error("makeStickerPack: at least one sticker is required");
96
+
97
+ const normalizedStickers = stickers.map(normalizeSticker);
98
+ const resolvedCover = cover ?? normalizedStickers[0].sticker;
99
+
100
+ return {
101
+ stickerPack: {
102
+ name,
103
+ publisher,
104
+ description,
105
+ ...(packId ? { packId } : {}),
106
+ stickers: normalizedStickers,
107
+ cover: resolvedCover,
108
+ },
109
+ ...(contextInfo ? { contextInfo } : {}),
110
+ };
111
+ };
@@ -0,0 +1,18 @@
1
+ import { proto } from '../../WAProto/index.js';
2
+ import type { BaileysEventEmitter, BaileysEventMap, Contact } from '../Types/index.js';
3
+ import type { ILogger } from './logger.js';
4
+ export type ContactsUpsertResult = {
5
+ event: 'contacts.upsert';
6
+ data: Contact[];
7
+ };
8
+ export type LidMappingUpdateResult = {
9
+ event: 'lid-mapping.update';
10
+ data: BaileysEventMap['lid-mapping.update'];
11
+ };
12
+ export type SyncActionResult = ContactsUpsertResult | LidMappingUpdateResult;
13
+ /**
14
+ * Process contactAction and return events to emit.
15
+ * Pure function - no side effects.
16
+ */
17
+ export declare const processContactAction: (action: proto.SyncActionValue.IContactAction, id: string | undefined, logger?: ILogger) => SyncActionResult[];
18
+ export declare const emitSyncActionResults: (ev: BaileysEventEmitter, results: SyncActionResult[]) => void;
@@ -0,0 +1,47 @@
1
+ import { proto } from '../../WAProto/index.js';
2
+ import { isLidUser, isPnUser } from '../WABinary/index.js';
3
+ /**
4
+ * Process contactAction and return events to emit.
5
+ * Pure function - no side effects.
6
+ */
7
+ export const processContactAction = (action, id, logger) => {
8
+ const results = [];
9
+ if (!id) {
10
+ logger?.warn({ hasFullName: !!action.fullName, hasLidJid: !!action.lidJid, hasPnJid: !!action.pnJid }, 'contactAction sync: missing id in index');
11
+ return results;
12
+ }
13
+ const lidJid = action.lidJid;
14
+ const idIsPn = isPnUser(id);
15
+ // PN is in index[1], not in contactAction.pnJid which is usually null
16
+ const phoneNumber = idIsPn ? id : action.pnJid || undefined;
17
+ // Always emit contacts.upsert
18
+ results.push({
19
+ event: 'contacts.upsert',
20
+ data: [
21
+ {
22
+ id,
23
+ name: action.fullName || action.firstName || action.username || undefined,
24
+ lid: lidJid || undefined,
25
+ phoneNumber
26
+ }
27
+ ]
28
+ });
29
+ // Emit lid-mapping.update if we have valid LID-PN pair
30
+ if (lidJid && isLidUser(lidJid) && idIsPn) {
31
+ results.push({
32
+ event: 'lid-mapping.update',
33
+ data: { lid: lidJid, pn: id }
34
+ });
35
+ }
36
+ return results;
37
+ };
38
+ export const emitSyncActionResults = (ev, results) => {
39
+ for (const result of results) {
40
+ if (result.event === 'contacts.upsert') {
41
+ ev.emit('contacts.upsert', result.data);
42
+ }
43
+ else {
44
+ ev.emit('lid-mapping.update', result.data);
45
+ }
46
+ }
47
+ };
@@ -0,0 +1,8 @@
1
+ import type { AuthenticationState } from '../Types/index.js';
2
+ import type { BinaryNode } from '../WABinary/index.js';
3
+ export declare function isTcTokenExpired(timestamp: number | string | null | undefined): boolean;
4
+ export declare function buildTcTokenFromJid({ authState, jid, baseContent }: {
5
+ authState: AuthenticationState;
6
+ jid: string;
7
+ baseContent?: BinaryNode[];
8
+ }): Promise<BinaryNode[] | undefined>;
@@ -0,0 +1,45 @@
1
+ const TC_TOKEN_BUCKET_DURATION = 604800; // 7 hari
2
+ const TC_TOKEN_NUM_BUCKETS = 4; // jendela bergulir ~28 hari
3
+ /** true bila timestamp (detik unix) token sudah di luar jendela ~28 hari WA Web */
4
+ export function isTcTokenExpired(timestamp) {
5
+ if (timestamp === null || timestamp === undefined)
6
+ return true;
7
+ const ts = typeof timestamp === 'string' ? parseInt(timestamp) : timestamp;
8
+ if (isNaN(ts))
9
+ return true;
10
+ const now = Math.floor(Date.now() / 1000);
11
+ const currentBucket = Math.floor(now / TC_TOKEN_BUCKET_DURATION);
12
+ const cutoffBucket = currentBucket - (TC_TOKEN_NUM_BUCKETS - 1);
13
+ return ts < cutoffBucket * TC_TOKEN_BUCKET_DURATION;
14
+ }
15
+ /**
16
+ * Sisipkan node <tctoken t="..."> milik `jid` ke `baseContent` bila ada & masih berlaku.
17
+ * BibzWhats (upstream rc11+): atribut `t` WAJIB; token tanpa timestamp atau
18
+ * kedaluwarsa dianggap tidak ada (dan dibersihkan dari store).
19
+ */
20
+ export async function buildTcTokenFromJid({ authState, jid, baseContent = [] }) {
21
+ try {
22
+ const tcTokenData = await authState.keys.get('tctoken', [jid]);
23
+ const entry = tcTokenData?.[jid];
24
+ const tcTokenBuffer = entry?.token;
25
+ const timestamp = entry?.timestamp;
26
+ if (!tcTokenBuffer?.length || timestamp === undefined || isTcTokenExpired(timestamp)) {
27
+ if (tcTokenBuffer) {
28
+ try {
29
+ await authState.keys.set({ tctoken: { [jid]: null } });
30
+ }
31
+ catch { }
32
+ }
33
+ return baseContent.length > 0 ? baseContent : undefined;
34
+ }
35
+ baseContent.push({
36
+ tag: 'tctoken',
37
+ attrs: { t: String(timestamp) },
38
+ content: tcTokenBuffer
39
+ });
40
+ return baseContent;
41
+ }
42
+ catch (error) {
43
+ return baseContent.length > 0 ? baseContent : undefined;
44
+ }
45
+ }
@@ -0,0 +1,12 @@
1
+ import type { AuthenticationState } from '../Types/index.js';
2
+ /**
3
+ * stores the full authentication state in a single folder.
4
+ * Far more efficient than singlefileauthstate
5
+ *
6
+ * Again, I wouldn't endorse this for any production level use other than perhaps a bot.
7
+ * Would recommend writing an auth state for use with a proper SQL or No-SQL DB
8
+ * */
9
+ export declare const useMultiFileAuthState: (folder: string) => Promise<{
10
+ state: AuthenticationState;
11
+ saveCreds: () => Promise<void>;
12
+ }>;
@@ -0,0 +1,120 @@
1
+ import { Mutex } from 'async-mutex';
2
+ import { mkdir, readFile, stat, unlink, writeFile } from 'fs/promises';
3
+ import { join } from 'path';
4
+ import { proto } from '../../WAProto/index.js';
5
+ import { initAuthCreds } from './auth-utils.js';
6
+ import { BufferJSON } from './generics.js';
7
+ // We need to lock files due to the fact that we are using async functions to read and write files
8
+ // https://github.com/WhiskeySockets/Baileys/issues/794
9
+ // https://github.com/nodejs/node/issues/26338
10
+ // Use a Map to store mutexes for each file path
11
+ const fileLocks = new Map();
12
+ // Get or create a mutex for a specific file path
13
+ const getFileLock = (path) => {
14
+ let mutex = fileLocks.get(path);
15
+ if (!mutex) {
16
+ mutex = new Mutex();
17
+ fileLocks.set(path, mutex);
18
+ }
19
+ return mutex;
20
+ };
21
+ /**
22
+ * stores the full authentication state in a single folder.
23
+ * Far more efficient than singlefileauthstate
24
+ *
25
+ * Again, I wouldn't endorse this for any production level use other than perhaps a bot.
26
+ * Would recommend writing an auth state for use with a proper SQL or No-SQL DB
27
+ * */
28
+ export const useMultiFileAuthState = async (folder) => {
29
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
30
+ const writeData = async (data, file) => {
31
+ const filePath = join(folder, fixFileName(file));
32
+ const mutex = getFileLock(filePath);
33
+ return mutex.acquire().then(async (release) => {
34
+ try {
35
+ await writeFile(filePath, JSON.stringify(data, BufferJSON.replacer));
36
+ }
37
+ finally {
38
+ release();
39
+ }
40
+ });
41
+ };
42
+ const readData = async (file) => {
43
+ try {
44
+ const filePath = join(folder, fixFileName(file));
45
+ const mutex = getFileLock(filePath);
46
+ return await mutex.acquire().then(async (release) => {
47
+ try {
48
+ const data = await readFile(filePath, { encoding: 'utf-8' });
49
+ return JSON.parse(data, BufferJSON.reviver);
50
+ }
51
+ finally {
52
+ release();
53
+ }
54
+ });
55
+ }
56
+ catch (error) {
57
+ return null;
58
+ }
59
+ };
60
+ const removeData = async (file) => {
61
+ try {
62
+ const filePath = join(folder, fixFileName(file));
63
+ const mutex = getFileLock(filePath);
64
+ return mutex.acquire().then(async (release) => {
65
+ try {
66
+ await unlink(filePath);
67
+ }
68
+ catch {
69
+ }
70
+ finally {
71
+ release();
72
+ }
73
+ });
74
+ }
75
+ catch { }
76
+ };
77
+ const folderInfo = await stat(folder).catch(() => { });
78
+ if (folderInfo) {
79
+ if (!folderInfo.isDirectory()) {
80
+ throw new Error(`found something that is not a directory at ${folder}, either delete it or specify a different location`);
81
+ }
82
+ }
83
+ else {
84
+ await mkdir(folder, { recursive: true });
85
+ }
86
+ const fixFileName = (file) => file?.replace(/\//g, '__')?.replace(/:/g, '-');
87
+ const creds = (await readData('creds.json')) || initAuthCreds();
88
+ return {
89
+ state: {
90
+ creds,
91
+ keys: {
92
+ get: async (type, ids) => {
93
+ const data = {};
94
+ await Promise.all(ids.map(async (id) => {
95
+ let value = await readData(`${type}-${id}.json`);
96
+ if (type === 'app-state-sync-key' && value) {
97
+ value = proto.Message.AppStateSyncKeyData.fromObject(value);
98
+ }
99
+ data[id] = value;
100
+ }));
101
+ return data;
102
+ },
103
+ set: async (data) => {
104
+ const tasks = [];
105
+ for (const category in data) {
106
+ for (const id in data[category]) {
107
+ const value = data[category][id];
108
+ const file = `${category}-${id}.json`;
109
+ tasks.push(value ? writeData(value, file) : removeData(file));
110
+ }
111
+ }
112
+ await Promise.all(tasks);
113
+ }
114
+ }
115
+ },
116
+ saveCreds: async () => {
117
+ return writeData(creds, 'creds.json');
118
+ }
119
+ };
120
+ };
@@ -0,0 +1,10 @@
1
+ import { proto } from '../../WAProto/index.js';
2
+ import type { AuthenticationCreds, SignalCreds, SocketConfig } from '../Types/index.js';
3
+ import { type BinaryNode } from '../WABinary/index.js';
4
+ export declare const generateLoginNode: (userJid: string, config: SocketConfig) => proto.IClientPayload;
5
+ export declare const generateRegistrationNode: ({ registrationId, signedPreKey, signedIdentityKey }: SignalCreds, config: SocketConfig) => proto.ClientPayload;
6
+ export declare const configureSuccessfulPairing: (stanza: BinaryNode, { advSecretKey, signedIdentityKey, signalIdentities }: Pick<AuthenticationCreds, "advSecretKey" | "signedIdentityKey" | "signalIdentities">) => {
7
+ creds: Partial<AuthenticationCreds>;
8
+ reply: BinaryNode;
9
+ };
10
+ export declare const encodeSignedDeviceIdentity: (account: proto.IADVSignedDeviceIdentity, includeSignatureKey: boolean) => Uint8Array<ArrayBufferLike>;