@badzz88/baileys 8.4.6 → 8.4.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (250) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1055 -337
  3. package/WAProto/WAProto.proto +850 -32
  4. package/WAProto/index.d.ts +4913 -25
  5. package/WAProto/index.js +14074 -98
  6. package/package.json +96 -131
  7. package/src/Defaults/index.js +201 -0
  8. package/src/Defaults/phonenumber-mcc.json +223 -0
  9. package/src/Signal/Group/ciphertext-message.js +15 -0
  10. package/src/Signal/Group/group-session-builder.js +92 -0
  11. package/src/Signal/Group/group_cipher.js +89 -0
  12. package/src/Signal/Group/index.js +136 -0
  13. package/src/Signal/Group/keyhelper.js +73 -0
  14. package/src/Signal/Group/sender-chain-key.js +32 -0
  15. package/src/Signal/Group/sender-key-distribution-message.js +66 -0
  16. package/src/Signal/Group/sender-key-message.js +69 -0
  17. package/src/Signal/Group/sender-key-name.js +50 -0
  18. package/src/Signal/Group/sender-key-record.js +44 -0
  19. package/src/Signal/Group/sender-key-state.js +97 -0
  20. package/src/Signal/Group/sender-message-key.js +30 -0
  21. package/src/Signal/libsignal.js +470 -0
  22. package/src/Signal/lid-mapping.js +262 -0
  23. package/src/Socket/Client/index.js +30 -0
  24. package/src/Socket/Client/types.js +13 -0
  25. package/src/Socket/Client/websocket.js +62 -0
  26. package/src/Socket/aigroups.js +240 -0
  27. package/src/Socket/business.js +422 -0
  28. package/src/Socket/chats.js +2374 -0
  29. package/src/Socket/communities.js +580 -0
  30. package/src/Socket/graphql.js +915 -0
  31. package/src/Socket/groups.js +812 -0
  32. package/src/Socket/index.js +37 -0
  33. package/src/Socket/interactive-handler.js +579 -0
  34. package/src/Socket/interop.js +566 -0
  35. package/src/Socket/managed-account.js +214 -0
  36. package/src/Socket/messages-recv.js +3012 -0
  37. package/src/Socket/messages-send.js +2163 -0
  38. package/{lib → src}/Socket/mex.js +11 -5
  39. package/src/Socket/newsletter.js +1057 -0
  40. package/src/Socket/privacy.js +452 -0
  41. package/src/Socket/registration.js +434 -0
  42. package/src/Socket/socket.js +1079 -0
  43. package/src/Socket/text-router.js +67 -0
  44. package/src/Socket/username.js +234 -0
  45. package/src/Store/index.js +36 -0
  46. package/src/Store/make-cache-manager-store.js +90 -0
  47. package/src/Store/make-in-memory-store.js +506 -0
  48. package/src/Store/make-ordered-dictionary.js +81 -0
  49. package/src/Store/object-repository.js +29 -0
  50. package/src/Types/Auth.js +38 -0
  51. package/src/Types/Bussines.js +2 -0
  52. package/src/Types/Call.js +2 -0
  53. package/src/Types/Chat.js +4 -0
  54. package/src/Types/Contact.js +2 -0
  55. package/src/Types/Events.js +2 -0
  56. package/src/Types/GroupMetadata.js +2 -0
  57. package/src/Types/Label.js +27 -0
  58. package/src/Types/LabelAssociation.js +9 -0
  59. package/src/Types/Message.js +95 -0
  60. package/src/Types/Newsletter.js +152 -0
  61. package/src/Types/Product.js +2 -0
  62. package/src/Types/Signal.js +2 -0
  63. package/src/Types/Socket.js +2 -0
  64. package/src/Types/State.js +70 -0
  65. package/src/Types/USync.js +2 -0
  66. package/src/Types/index.js +54 -0
  67. package/src/Utils/auth-utils.js +306 -0
  68. package/src/Utils/browser-utils.js +114 -0
  69. package/src/Utils/business.js +247 -0
  70. package/src/Utils/chat-utils.js +1272 -0
  71. package/src/Utils/consumer-application.js +107 -0
  72. package/src/Utils/crypto.js +125 -0
  73. package/src/Utils/decode-wa-message.js +808 -0
  74. package/src/Utils/event-buffer.js +586 -0
  75. package/src/Utils/generics.js +640 -0
  76. package/src/Utils/group-history.js +60 -0
  77. package/src/Utils/history.js +244 -0
  78. package/src/Utils/identity-change-handler.js +52 -0
  79. package/src/Utils/index.js +53 -0
  80. package/src/Utils/jid-display-normalization.js +218 -0
  81. package/src/Utils/link-preview.js +143 -0
  82. package/src/Utils/logger.js +9 -0
  83. package/src/Utils/lt-hash.js +10 -0
  84. package/src/Utils/make-mutex.js +36 -0
  85. package/src/Utils/message-composer.js +479 -0
  86. package/src/Utils/message-inspect.js +400 -0
  87. package/src/Utils/message-retry-manager.js +231 -0
  88. package/src/Utils/messages-media.js +943 -0
  89. package/src/Utils/messages.js +2490 -0
  90. package/src/Utils/meta-ai-msmsg.js +133 -0
  91. package/src/Utils/noise-handler.js +194 -0
  92. package/src/Utils/offline-node-processor.js +42 -0
  93. package/src/Utils/pre-key-manager.js +107 -0
  94. package/src/Utils/process-message.js +1047 -0
  95. package/src/Utils/reporting-utils.js +262 -0
  96. package/src/Utils/signal.js +192 -0
  97. package/src/Utils/stanza-ack.js +74 -0
  98. package/src/Utils/sync-action-utils.js +54 -0
  99. package/src/Utils/tc-token-utils.js +161 -0
  100. package/src/Utils/use-multi-file-auth-state.js +121 -0
  101. package/src/Utils/validate-connection.js +248 -0
  102. package/src/Utils/voip-rekey.js +22 -0
  103. package/src/WABinary/constants.js +1304 -0
  104. package/src/WABinary/decode.js +377 -0
  105. package/src/WABinary/encode.js +58 -0
  106. package/src/WABinary/generic-utils.js +148 -0
  107. package/src/WABinary/index.js +33 -0
  108. package/src/WABinary/jid-utils.js +374 -0
  109. package/src/WABinary/types.js +2 -0
  110. package/src/WAM/BinaryInfo.js +13 -0
  111. package/src/WAM/constants.js +39486 -0
  112. package/src/WAM/encode.js +142 -0
  113. package/src/WAM/index.js +31 -0
  114. package/src/WAUSync/Protocols/USyncBotProfileProtocol.js +55 -0
  115. package/src/WAUSync/Protocols/USyncBusinessProtocol.js +100 -0
  116. package/src/WAUSync/Protocols/USyncContactProtocol.js +60 -0
  117. package/src/WAUSync/Protocols/USyncDeviceProtocol.js +65 -0
  118. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  119. package/src/WAUSync/Protocols/USyncFeatureProtocol.js +74 -0
  120. package/src/WAUSync/Protocols/USyncLIDProtocol.js +31 -0
  121. package/src/WAUSync/Protocols/USyncPictureProtocol.js +32 -0
  122. package/src/WAUSync/Protocols/USyncSidelistProtocol.js +29 -0
  123. package/src/WAUSync/Protocols/USyncStatusProtocol.js +44 -0
  124. package/src/WAUSync/Protocols/USyncTextStatusProtocol.js +38 -0
  125. package/src/WAUSync/Protocols/USyncUsernameProtocol.js +28 -0
  126. package/src/WAUSync/Protocols/index.js +40 -0
  127. package/src/WAUSync/USyncBackoff.js +31 -0
  128. package/src/WAUSync/USyncQuery.js +204 -0
  129. package/src/WAUSync/USyncUser.js +58 -0
  130. package/src/WAUSync/index.js +32 -0
  131. package/src/antiban.js +4726 -0
  132. package/{lib → src}/index.js +48 -16
  133. package/lib/Defaults/baileys-version.json +0 -3
  134. package/lib/Defaults/index.js +0 -137
  135. package/lib/Defaults/phonenumber-mcc.json +0 -223
  136. package/lib/Signal/Group/Protocols.js +0 -269
  137. package/lib/Signal/Group/ciphertext-message.js +0 -12
  138. package/lib/Signal/Group/group-session-builder.js +0 -30
  139. package/lib/Signal/Group/group_cipher.js +0 -82
  140. package/lib/Signal/Group/index.js +0 -12
  141. package/lib/Signal/Group/keyhelper.js +0 -18
  142. package/lib/Signal/Group/queue-job.js +0 -57
  143. package/lib/Signal/Group/sender-chain-key.js +0 -26
  144. package/lib/Signal/Group/sender-key-distribution-message.js +0 -63
  145. package/lib/Signal/Group/sender-key-message.js +0 -66
  146. package/lib/Signal/Group/sender-key-name.js +0 -48
  147. package/lib/Signal/Group/sender-key-record.js +0 -41
  148. package/lib/Signal/Group/sender-key-state.js +0 -84
  149. package/lib/Signal/Group/sender-message-key.js +0 -26
  150. package/lib/Signal/libsignal.js +0 -432
  151. package/lib/Signal/lid-mapping.js +0 -277
  152. package/lib/Socket/Client/abstract-socket-client.js +0 -13
  153. package/lib/Socket/Client/index.js +0 -3
  154. package/lib/Socket/Client/mobile-socket-client.js +0 -65
  155. package/lib/Socket/Client/types.js +0 -11
  156. package/lib/Socket/Client/web-socket-client.js +0 -62
  157. package/lib/Socket/Client/websocket.js +0 -54
  158. package/lib/Socket/business.js +0 -379
  159. package/lib/Socket/chats.js +0 -1193
  160. package/lib/Socket/communities.js +0 -431
  161. package/lib/Socket/community.js +0 -392
  162. package/lib/Socket/dugong.js +0 -637
  163. package/lib/Socket/groups.js +0 -374
  164. package/lib/Socket/index.js +0 -12
  165. package/lib/Socket/luxu.js +0 -387
  166. package/lib/Socket/messages-recv.js +0 -1916
  167. package/lib/Socket/messages-send.js +0 -1459
  168. package/lib/Socket/newsletter.js +0 -253
  169. package/lib/Socket/registration.js +0 -167
  170. package/lib/Socket/socket.js +0 -950
  171. package/lib/Socket/username.js +0 -146
  172. package/lib/Socket/usync.js +0 -69
  173. package/lib/Store/index.js +0 -10
  174. package/lib/Store/keyed-db.js +0 -108
  175. package/lib/Store/make-cache-manager-store.js +0 -85
  176. package/lib/Store/make-in-memory-store.js +0 -198
  177. package/lib/Store/make-ordered-dictionary.js +0 -75
  178. package/lib/Store/object-repository.js +0 -32
  179. package/lib/Types/Auth.js +0 -2
  180. package/lib/Types/Bussines.js +0 -2
  181. package/lib/Types/Call.js +0 -2
  182. package/lib/Types/Chat.js +0 -8
  183. package/lib/Types/Contact.js +0 -2
  184. package/lib/Types/Events.js +0 -2
  185. package/lib/Types/GroupMetadata.js +0 -2
  186. package/lib/Types/Label.js +0 -25
  187. package/lib/Types/LabelAssociation.js +0 -7
  188. package/lib/Types/Message.js +0 -11
  189. package/lib/Types/Mex.js +0 -37
  190. package/lib/Types/Newsletter.js +0 -38
  191. package/lib/Types/Product.js +0 -2
  192. package/lib/Types/Signal.js +0 -2
  193. package/lib/Types/Socket.js +0 -3
  194. package/lib/Types/State.js +0 -56
  195. package/lib/Types/USync.js +0 -2
  196. package/lib/Types/index.js +0 -26
  197. package/lib/Utils/auth-utils.js +0 -302
  198. package/lib/Utils/baileys-event-stream.js +0 -63
  199. package/lib/Utils/browser-utils.js +0 -48
  200. package/lib/Utils/business.js +0 -231
  201. package/lib/Utils/chat-utils.js +0 -873
  202. package/lib/Utils/companion-reg-client-utils.js +0 -35
  203. package/lib/Utils/crypto.js +0 -118
  204. package/lib/Utils/decode-wa-message.js +0 -350
  205. package/lib/Utils/event-buffer.js +0 -622
  206. package/lib/Utils/generics.js +0 -399
  207. package/lib/Utils/history.js +0 -134
  208. package/lib/Utils/identity-change-handler.js +0 -50
  209. package/lib/Utils/index.js +0 -23
  210. package/lib/Utils/link-preview.js +0 -85
  211. package/lib/Utils/logger.js +0 -3
  212. package/lib/Utils/lt-hash.js +0 -8
  213. package/lib/Utils/make-mutex.js +0 -33
  214. package/lib/Utils/message-composer.js +0 -273
  215. package/lib/Utils/message-retry-manager.js +0 -265
  216. package/lib/Utils/messages-media.js +0 -788
  217. package/lib/Utils/messages.js +0 -1260
  218. package/lib/Utils/noise-handler.js +0 -201
  219. package/lib/Utils/offline-node-processor.js +0 -40
  220. package/lib/Utils/pre-key-manager.js +0 -106
  221. package/lib/Utils/process-message.js +0 -630
  222. package/lib/Utils/reporting-utils.js +0 -258
  223. package/lib/Utils/signal.js +0 -202
  224. package/lib/Utils/stanza-ack.js +0 -38
  225. package/lib/Utils/sync-action-utils.js +0 -49
  226. package/lib/Utils/tc-token-utils.js +0 -163
  227. package/lib/Utils/use-multi-file-auth-state.js +0 -121
  228. package/lib/Utils/validate-connection.js +0 -204
  229. package/lib/WABinary/constants.js +0 -1301
  230. package/lib/WABinary/decode.js +0 -262
  231. package/lib/WABinary/encode.js +0 -220
  232. package/lib/WABinary/generic-utils.js +0 -204
  233. package/lib/WABinary/index.js +0 -6
  234. package/lib/WABinary/jid-utils.js +0 -98
  235. package/lib/WABinary/types.js +0 -2
  236. package/lib/WAM/BinaryInfo.js +0 -10
  237. package/lib/WAM/constants.js +0 -22853
  238. package/lib/WAM/encode.js +0 -150
  239. package/lib/WAM/index.js +0 -4
  240. package/lib/WAUSync/Protocols/USyncContactProtocol.js +0 -52
  241. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +0 -54
  242. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +0 -27
  243. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +0 -38
  244. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +0 -25
  245. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +0 -51
  246. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +0 -29
  247. package/lib/WAUSync/Protocols/index.js +0 -6
  248. package/lib/WAUSync/USyncQuery.js +0 -98
  249. package/lib/WAUSync/USyncUser.js +0 -31
  250. package/lib/WAUSync/index.js +0 -4
@@ -1,163 +0,0 @@
1
- import { getBinaryNodeChild, getBinaryNodeChildren, isHostedLidUser, isHostedPnUser, isJidMetaAI, isLidUser, isPnUser, jidNormalizedUser } from '../WABinary/index.js';
2
- // Same phone-number pattern as WABinary's isJidBot, applied against the user
3
- // part so the check is invariant to @c.us ↔ @s.whatsapp.net normalization.
4
- const BOT_PHONE_REGEX = /^1313555\d{4}$|^131655500\d{2}$/;
5
- /**
6
- * Mirrors WA Web's `Wid.isRegularUser()` (user ∧ ¬PSA ∧ ¬Bot). Used to gate tctoken
7
- * storage against malformed notifications — WA Web filters server-side but we
8
- * defend here for parity with `WAWebSetTcTokenChatAction.handleIncomingTcToken`.
9
- * Works for both pre- and post-normalized JIDs (`@c.us` vs `@s.whatsapp.net`).
10
- */
11
- function isRegularUser(jid) {
12
- if (!jid)
13
- return false;
14
- const user = jid.split('@')[0] ?? '';
15
- if (user === '0')
16
- return false; // PSA
17
- if (BOT_PHONE_REGEX.test(user))
18
- return false; // Bot by phone pattern
19
- if (isJidMetaAI(jid))
20
- return false; // MetaAI (@bot server)
21
- return !!(isPnUser(jid) || isLidUser(jid) || isHostedPnUser(jid) || isHostedLidUser(jid) || jid.endsWith('@c.us'));
22
- }
23
- const TC_TOKEN_BUCKET_DURATION = 604800; // 7 days
24
- const TC_TOKEN_NUM_BUCKETS = 4; // ~28-day rolling window
25
- /** Sentinel key under `tctoken` store holding a JSON array of tracked storage JIDs for cross-session pruning. */
26
- export const TC_TOKEN_INDEX_KEY = '__index';
27
- /** Read the persisted tctoken JID index and return its entries (never contains the sentinel key itself). */
28
- export async function readTcTokenIndex(keys) {
29
- const data = await keys.get('tctoken', [TC_TOKEN_INDEX_KEY]);
30
- const entry = data[TC_TOKEN_INDEX_KEY];
31
- if (!entry?.token?.length)
32
- return [];
33
- try {
34
- const parsed = JSON.parse(Buffer.from(entry.token).toString());
35
- if (!Array.isArray(parsed))
36
- return [];
37
- return parsed.filter((j) => typeof j === 'string' && j.length > 0 && j !== TC_TOKEN_INDEX_KEY);
38
- }
39
- catch {
40
- return [];
41
- }
42
- }
43
- /** Build a SignalDataSet fragment that writes the merged index (persisted ∪ added) under the sentinel key. */
44
- export async function buildMergedTcTokenIndexWrite(keys, addedJids) {
45
- const persisted = await readTcTokenIndex(keys);
46
- const merged = new Set(persisted);
47
- for (const jid of addedJids) {
48
- if (jid && jid !== TC_TOKEN_INDEX_KEY)
49
- merged.add(jid);
50
- }
51
- return {
52
- [TC_TOKEN_INDEX_KEY]: { token: Buffer.from(JSON.stringify([...merged])) }
53
- };
54
- }
55
- // WA Web has separate sender/receiver AB props for these but they're identical today
56
- export function isTcTokenExpired(timestamp) {
57
- if (timestamp === null || timestamp === undefined)
58
- return true;
59
- const ts = typeof timestamp === 'string' ? parseInt(timestamp) : timestamp;
60
- if (isNaN(ts))
61
- return true;
62
- const now = Math.floor(Date.now() / 1000);
63
- const currentBucket = Math.floor(now / TC_TOKEN_BUCKET_DURATION);
64
- const cutoffBucket = currentBucket - (TC_TOKEN_NUM_BUCKETS - 1);
65
- const cutoffTimestamp = cutoffBucket * TC_TOKEN_BUCKET_DURATION;
66
- return ts < cutoffTimestamp;
67
- }
68
- export function shouldSendNewTcToken(senderTimestamp) {
69
- if (senderTimestamp === undefined)
70
- return true;
71
- const now = Math.floor(Date.now() / 1000);
72
- const currentBucket = Math.floor(now / TC_TOKEN_BUCKET_DURATION);
73
- const senderBucket = Math.floor(senderTimestamp / TC_TOKEN_BUCKET_DURATION);
74
- return currentBucket > senderBucket;
75
- }
76
- /** Resolve JID to LID for tctoken storage (WA Web stores under LID) */
77
- export async function resolveTcTokenJid(jid, getLIDForPN) {
78
- if (isLidUser(jid))
79
- return jid;
80
- const lid = await getLIDForPN(jid);
81
- return lid ?? jid;
82
- }
83
- /** Resolve target JID for issuing privacy token based on AB prop 14303 */
84
- export async function resolveIssuanceJid(jid, issueToLid, getLIDForPN, getPNForLID) {
85
- if (issueToLid) {
86
- if (isLidUser(jid))
87
- return jid;
88
- const lid = await getLIDForPN(jid);
89
- return lid ?? jid;
90
- }
91
- if (!isLidUser(jid))
92
- return jid;
93
- if (getPNForLID) {
94
- const pn = await getPNForLID(jid);
95
- return pn ?? jid;
96
- }
97
- return jid;
98
- }
99
- export async function buildTcTokenFromJid({ authState, jid, baseContent = [], getLIDForPN }) {
100
- try {
101
- const storageJid = await resolveTcTokenJid(jid, getLIDForPN);
102
- const tcTokenData = await authState.keys.get('tctoken', [storageJid]);
103
- const entry = tcTokenData?.[storageJid];
104
- const tcTokenBuffer = entry?.token;
105
- if (!tcTokenBuffer?.length || isTcTokenExpired(entry?.timestamp)) {
106
- if (tcTokenBuffer) {
107
- // Preserve senderTimestamp so shouldSendNewTcToken() keeps its dedupe state
108
- // after we drop the unusable peer token. Only wipe the record entirely when
109
- // there's nothing worth keeping.
110
- const cleared = entry?.senderTimestamp !== undefined
111
- ? { token: Buffer.alloc(0), senderTimestamp: entry.senderTimestamp }
112
- : null;
113
- await authState.keys.set({ tctoken: { [storageJid]: cleared } });
114
- }
115
- return baseContent.length > 0 ? baseContent : undefined;
116
- }
117
- baseContent.push({
118
- tag: 'tctoken',
119
- attrs: {},
120
- content: tcTokenBuffer
121
- });
122
- return baseContent;
123
- }
124
- catch (error) {
125
- return baseContent.length > 0 ? baseContent : undefined;
126
- }
127
- }
128
- export async function storeTcTokensFromIqResult({ result, fallbackJid, keys, getLIDForPN, onNewJidStored }) {
129
- const tokensNode = getBinaryNodeChild(result, 'tokens');
130
- if (!tokensNode)
131
- return;
132
- const tokenNodes = getBinaryNodeChildren(tokensNode, 'token');
133
- for (const tokenNode of tokenNodes) {
134
- if (tokenNode.attrs.type !== 'trusted_contact' || !(tokenNode.content instanceof Uint8Array)) {
135
- continue;
136
- }
137
- // In notifications tokenNode.attrs.jid is your own device JID, not the sender's
138
- const rawJid = jidNormalizedUser(fallbackJid || tokenNode.attrs.jid);
139
- if (!isRegularUser(rawJid))
140
- continue;
141
- const storageJid = await resolveTcTokenJid(rawJid, getLIDForPN);
142
- const existingTcData = await keys.get('tctoken', [storageJid]);
143
- const existingEntry = existingTcData[storageJid];
144
- const existingTs = existingEntry?.timestamp ? Number(existingEntry.timestamp) : 0;
145
- const incomingTs = tokenNode.attrs.t ? Number(tokenNode.attrs.t) : 0;
146
- // timestamp-less tokens would be immediately expired
147
- if (!incomingTs)
148
- continue;
149
- if (existingTs > 0 && existingTs > incomingTs)
150
- continue;
151
- await keys.set({
152
- tctoken: {
153
- [storageJid]: {
154
- ...existingEntry,
155
- token: Buffer.from(tokenNode.content),
156
- timestamp: tokenNode.attrs.t
157
- }
158
- }
159
- });
160
- onNewJidStored?.(storageJid);
161
- }
162
- }
163
- //# sourceMappingURL=tc-token-utils.js.map
@@ -1,121 +0,0 @@
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
- };
121
- //# sourceMappingURL=use-multi-file-auth-state.js.map
@@ -1,204 +0,0 @@
1
- import { Boom } from '@hapi/boom';
2
- import { createHash } from 'crypto';
3
- import { proto } from '../../WAProto/index.js';
4
- import { KEY_BUNDLE_TYPE, WA_ADV_ACCOUNT_SIG_PREFIX, WA_ADV_DEVICE_SIG_PREFIX, WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX } from '../Defaults/index.js';
5
- import { getBinaryNodeChild, jidDecode, S_WHATSAPP_NET } from '../WABinary/index.js';
6
- import { Curve, hmacSign } from './crypto.js';
7
- import { encodeBigEndian } from './generics.js';
8
- import { createSignalIdentity } from './signal.js';
9
- const getUserAgent = (config) => {
10
- return {
11
- appVersion: {
12
- primary: config.version[0],
13
- secondary: config.version[1],
14
- tertiary: config.version[2]
15
- },
16
- platform: proto.ClientPayload.UserAgent.Platform.MACOS,
17
- releaseChannel: proto.ClientPayload.UserAgent.ReleaseChannel.RELEASE,
18
- osVersion: '0.1',
19
- device: 'Desktop',
20
- osBuildNumber: '0.1',
21
- localeLanguageIso6391: 'en',
22
- mnc: '000',
23
- mcc: '000',
24
- localeCountryIso31661Alpha2: config.countryCode
25
- };
26
- };
27
- const PLATFORM_MAP = {
28
- 'Mac OS': proto.ClientPayload.WebInfo.WebSubPlatform.DARWIN,
29
- Windows: proto.ClientPayload.WebInfo.WebSubPlatform.WIN32
30
- };
31
- const getWebInfo = (config) => {
32
- let webSubPlatform = proto.ClientPayload.WebInfo.WebSubPlatform.WEB_BROWSER;
33
- if (config.syncFullHistory &&
34
- PLATFORM_MAP[config.browser[0]] &&
35
- config.browser[1] === 'Desktop') {
36
- webSubPlatform = PLATFORM_MAP[config.browser[0]];
37
- }
38
- return { webSubPlatform };
39
- };
40
- const getClientPayload = (config) => {
41
- const payload = {
42
- connectType: proto.ClientPayload.ConnectType.WIFI_UNKNOWN,
43
- connectReason: proto.ClientPayload.ConnectReason.USER_ACTIVATED,
44
- userAgent: getUserAgent(config)
45
- };
46
- payload.webInfo = getWebInfo(config);
47
- if (config.pushName) {
48
- payload.pushName = config.pushName;
49
- }
50
- return payload;
51
- };
52
- export const generateLoginNode = (userJid, config) => {
53
- const { user, device } = jidDecode(userJid);
54
- const payload = {
55
- ...getClientPayload(config),
56
- passive: true,
57
- pull: true,
58
- username: +user,
59
- device: device,
60
- // TODO: investigate (hard set as false atm)
61
- lidDbMigrated: false
62
- };
63
- return proto.ClientPayload.fromObject(payload);
64
- };
65
- const getPlatformType = (platform) => {
66
- const platformType = platform.toUpperCase();
67
- return (proto.DeviceProps.PlatformType[platformType] ||
68
- proto.DeviceProps.PlatformType.CHROME);
69
- };
70
- export const generateRegistrationNode = ({ registrationId, signedPreKey, signedIdentityKey }, config) => {
71
- // the app version needs to be md5 hashed
72
- // and passed in
73
- const appVersionBuf = createHash('md5')
74
- .update(config.version.join('.')) // join as string
75
- .digest();
76
- const companion = {
77
- os: config.browser[0],
78
- platformType: getPlatformType(config.browser[1]),
79
- requireFullSync: config.syncFullHistory,
80
- historySyncConfig: {
81
- storageQuotaMb: 10240,
82
- inlineInitialPayloadInE2EeMsg: true,
83
- recentSyncDaysLimit: undefined,
84
- supportCallLogHistory: false,
85
- supportBotUserAgentChatHistory: true,
86
- supportCagReactionsAndPolls: true,
87
- supportBizHostedMsg: true,
88
- supportRecentSyncChunkMessageCountTuning: true,
89
- supportHostedGroupMsg: true,
90
- supportFbidBotChatHistory: true,
91
- supportAddOnHistorySyncMigration: undefined,
92
- supportMessageAssociation: true,
93
- supportGroupHistory: false,
94
- onDemandReady: undefined,
95
- supportGuestChat: undefined
96
- },
97
- version: {
98
- primary: 10,
99
- secondary: 15,
100
- tertiary: 7
101
- }
102
- };
103
- const companionProto = proto.DeviceProps.encode(companion).finish();
104
- const registerPayload = {
105
- ...getClientPayload(config),
106
- passive: false,
107
- pull: false,
108
- devicePairingData: {
109
- buildHash: appVersionBuf,
110
- deviceProps: companionProto,
111
- eRegid: encodeBigEndian(registrationId),
112
- eKeytype: KEY_BUNDLE_TYPE,
113
- eIdent: signedIdentityKey.public,
114
- eSkeyId: encodeBigEndian(signedPreKey.keyId, 3),
115
- eSkeyVal: signedPreKey.keyPair.public,
116
- eSkeySig: signedPreKey.signature
117
- }
118
- };
119
- return proto.ClientPayload.fromObject(registerPayload);
120
- };
121
- export const configureSuccessfulPairing = (stanza, { advSecretKey, signedIdentityKey, signalIdentities }) => {
122
- const msgId = stanza.attrs.id;
123
- const pairSuccessNode = getBinaryNodeChild(stanza, 'pair-success');
124
- const deviceIdentityNode = getBinaryNodeChild(pairSuccessNode, 'device-identity');
125
- const platformNode = getBinaryNodeChild(pairSuccessNode, 'platform');
126
- const deviceNode = getBinaryNodeChild(pairSuccessNode, 'device');
127
- const businessNode = getBinaryNodeChild(pairSuccessNode, 'biz');
128
- if (!deviceIdentityNode || !deviceNode) {
129
- throw new Boom('Missing device-identity or device in pair success node', { data: stanza });
130
- }
131
- const bizName = businessNode?.attrs.name;
132
- const jid = deviceNode.attrs.jid;
133
- const lid = deviceNode.attrs.lid;
134
- const { details, hmac, accountType } = proto.ADVSignedDeviceIdentityHMAC.decode(deviceIdentityNode.content);
135
- let hmacPrefix = Buffer.from([]);
136
- if (accountType !== undefined && accountType === proto.ADVEncryptionType.HOSTED) {
137
- hmacPrefix = WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX;
138
- }
139
- const advSign = hmacSign(Buffer.concat([hmacPrefix, details]), Buffer.from(advSecretKey, 'base64'));
140
- if (Buffer.compare(hmac, advSign) !== 0) {
141
- throw new Boom('Invalid account signature');
142
- }
143
- const account = proto.ADVSignedDeviceIdentity.decode(details);
144
- const { accountSignatureKey, accountSignature, details: deviceDetails } = account;
145
- const deviceIdentity = proto.ADVDeviceIdentity.decode(deviceDetails);
146
- const accountSignaturePrefix = deviceIdentity.deviceType === proto.ADVEncryptionType.HOSTED
147
- ? WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX
148
- : WA_ADV_ACCOUNT_SIG_PREFIX;
149
- const accountMsg = Buffer.concat([accountSignaturePrefix, deviceDetails, signedIdentityKey.public]);
150
- if (!Curve.verify(accountSignatureKey, accountMsg, accountSignature)) {
151
- throw new Boom('Failed to verify account signature');
152
- }
153
- const deviceMsg = Buffer.concat([
154
- WA_ADV_DEVICE_SIG_PREFIX,
155
- deviceDetails,
156
- signedIdentityKey.public,
157
- accountSignatureKey
158
- ]);
159
- account.deviceSignature = Curve.sign(signedIdentityKey.private, deviceMsg);
160
- const identity = createSignalIdentity(lid, accountSignatureKey);
161
- const accountEnc = encodeSignedDeviceIdentity(account, false);
162
- const reply = {
163
- tag: 'iq',
164
- attrs: {
165
- to: S_WHATSAPP_NET,
166
- type: 'result',
167
- id: msgId
168
- },
169
- content: [
170
- {
171
- tag: 'pair-device-sign',
172
- attrs: {},
173
- content: [
174
- {
175
- tag: 'device-identity',
176
- attrs: { 'key-index': deviceIdentity.keyIndex.toString() },
177
- content: accountEnc
178
- }
179
- ]
180
- }
181
- ]
182
- };
183
- const authUpdate = {
184
- account,
185
- me: { id: jid, name: bizName, lid },
186
- signalIdentities: [...(signalIdentities || []), identity],
187
- platform: platformNode?.attrs.name
188
- };
189
- return {
190
- creds: authUpdate,
191
- reply
192
- };
193
- };
194
- export const encodeSignedDeviceIdentity = (account, includeSignatureKey) => {
195
- account = { ...account };
196
- // set to null if we are not to include the signature key
197
- // or if we are including the signature key but it is empty
198
- if (!includeSignatureKey || !account.accountSignatureKey?.length) {
199
- account.accountSignatureKey = null;
200
- }
201
- return proto.ADVSignedDeviceIdentity.encode(account).finish();
202
- };
203
- //# sourceMappingURL=validate-connection.js.map
204
- //source baileys github.com/Badzz88/baileys