@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
@@ -0,0 +1,161 @@
1
+ 'use strict'
2
+ Object.defineProperty(exports, '__esModule', { value: true })
3
+ exports.TC_TOKEN_INDEX_KEY = void 0
4
+ exports.readTcTokenIndex = readTcTokenIndex
5
+ exports.buildMergedTcTokenIndexWrite = buildMergedTcTokenIndexWrite
6
+ exports.isTcTokenExpired = isTcTokenExpired
7
+ exports.shouldSendNewTcToken = shouldSendNewTcToken
8
+ exports.resolveTcTokenJid = resolveTcTokenJid
9
+ exports.resolveIssuanceJid = resolveIssuanceJid
10
+ exports.buildTcTokenFromJid = buildTcTokenFromJid
11
+ exports.storeTcTokensFromIqResult = storeTcTokensFromIqResult
12
+ const WABinary_1 = require('../WABinary')
13
+ // Same phone-number pattern as WABinary's isJidBot, applied against the user
14
+ // part so the check is invariant to @c.us ↔ @s.whatsapp.net normalization.
15
+ const BOT_PHONE_REGEX = /^1313555\d{4}$|^131655500\d{2}$/
16
+ /**
17
+ * Mirrors WA Web's `Wid.isRegularUser()` (user ∧ ¬PSA ∧ ¬Bot). Used to gate tctoken
18
+ * storage against malformed notifications — WA Web filters server-side but we
19
+ * defend here for parity with `WAWebSetTcTokenChatAction.handleIncomingTcToken`.
20
+ * Works for both pre- and post-normalized JIDs (`@c.us` vs `@s.whatsapp.net`).
21
+ */
22
+ function isRegularUser(jid) {
23
+ if (!jid) return false
24
+ const user = jid.split('@')[0] ?? ''
25
+ if (user === '0') return false // PSA
26
+ if (BOT_PHONE_REGEX.test(user)) return false // Bot by phone pattern
27
+ if ((0, WABinary_1.isJidMetaAI)(jid)) return false // MetaAI (@bot server)
28
+ return !!(
29
+ (0, WABinary_1.isPnUser)(jid) ||
30
+ (0, WABinary_1.isLidUser)(jid) ||
31
+ (0, WABinary_1.isHostedPnUser)(jid) ||
32
+ (0, WABinary_1.isHostedLidUser)(jid) ||
33
+ jid.endsWith('@c.us')
34
+ )
35
+ }
36
+ const TC_TOKEN_BUCKET_DURATION = 604800 // 7 days
37
+ const TC_TOKEN_NUM_BUCKETS = 4 // ~28-day rolling window
38
+ /** Sentinel key under `tctoken` store holding a JSON array of tracked storage JIDs for cross-session pruning. */
39
+ exports.TC_TOKEN_INDEX_KEY = '__index'
40
+ /** Read the persisted tctoken JID index and return its entries (never contains the sentinel key itself). */
41
+ async function readTcTokenIndex(keys) {
42
+ const data = await keys.get('tctoken', [exports.TC_TOKEN_INDEX_KEY])
43
+ const entry = data[exports.TC_TOKEN_INDEX_KEY]
44
+ if (!entry?.token?.length) return []
45
+ try {
46
+ const parsed = JSON.parse(Buffer.from(entry.token).toString())
47
+ if (!Array.isArray(parsed)) return []
48
+ return parsed.filter(j => typeof j === 'string' && j.length > 0 && j !== exports.TC_TOKEN_INDEX_KEY)
49
+ } catch {
50
+ return []
51
+ }
52
+ }
53
+ /** Build a SignalDataSet fragment that writes the merged index (persisted ∪ added) under the sentinel key. */
54
+ async function buildMergedTcTokenIndexWrite(keys, addedJids) {
55
+ const persisted = await readTcTokenIndex(keys)
56
+ const merged = new Set(persisted)
57
+ for (const jid of addedJids) {
58
+ if (jid && jid !== exports.TC_TOKEN_INDEX_KEY) merged.add(jid)
59
+ }
60
+ return {
61
+ [exports.TC_TOKEN_INDEX_KEY]: { token: Buffer.from(JSON.stringify([...merged])) }
62
+ }
63
+ }
64
+ // WA Web has separate sender/receiver AB props for these but they're identical today
65
+ function isTcTokenExpired(timestamp) {
66
+ if (timestamp === null || timestamp === undefined) return true
67
+ const ts = typeof timestamp === 'string' ? parseInt(timestamp, 10) : timestamp
68
+ if (isNaN(ts)) return true
69
+ const now = Math.floor(Date.now() / 1000)
70
+ const currentBucket = Math.floor(now / TC_TOKEN_BUCKET_DURATION)
71
+ const cutoffBucket = currentBucket - (TC_TOKEN_NUM_BUCKETS - 1)
72
+ const cutoffTimestamp = cutoffBucket * TC_TOKEN_BUCKET_DURATION
73
+ return ts < cutoffTimestamp
74
+ }
75
+ function shouldSendNewTcToken(senderTimestamp) {
76
+ if (senderTimestamp === undefined) return true
77
+ const now = Math.floor(Date.now() / 1000)
78
+ const currentBucket = Math.floor(now / TC_TOKEN_BUCKET_DURATION)
79
+ const senderBucket = Math.floor(senderTimestamp / TC_TOKEN_BUCKET_DURATION)
80
+ return currentBucket > senderBucket
81
+ }
82
+ /** Resolve JID to LID for tctoken storage (WA Web stores under LID) */
83
+ async function resolveTcTokenJid(jid, getLIDForPN) {
84
+ if ((0, WABinary_1.isLidUser)(jid)) return jid
85
+ const lid = await getLIDForPN(jid)
86
+ return lid ?? jid
87
+ }
88
+ /** Resolve target JID for issuing privacy token based on AB prop 14303 */
89
+ async function resolveIssuanceJid(jid, issueToLid, getLIDForPN, getPNForLID) {
90
+ if (issueToLid) {
91
+ if ((0, WABinary_1.isLidUser)(jid)) return jid
92
+ const lid = await getLIDForPN(jid)
93
+ return lid ?? jid
94
+ }
95
+ if (!(0, WABinary_1.isLidUser)(jid)) return jid
96
+ if (getPNForLID) {
97
+ const pn = await getPNForLID(jid)
98
+ return pn ?? jid
99
+ }
100
+ return jid
101
+ }
102
+ async function buildTcTokenFromJid({ authState, jid, baseContent = [], getLIDForPN }) {
103
+ try {
104
+ const storageJid = await resolveTcTokenJid(jid, getLIDForPN)
105
+ const tcTokenData = await authState.keys.get('tctoken', [storageJid])
106
+ const entry = tcTokenData?.[storageJid]
107
+ const tcTokenBuffer = entry?.token
108
+ if (!tcTokenBuffer?.length || isTcTokenExpired(entry?.timestamp)) {
109
+ if (tcTokenBuffer) {
110
+ // Preserve senderTimestamp so shouldSendNewTcToken() keeps its dedupe state
111
+ // after we drop the unusable peer token. Only wipe the record entirely when
112
+ // there's nothing worth keeping.
113
+ const cleared =
114
+ entry?.senderTimestamp !== undefined
115
+ ? { token: Buffer.alloc(0), senderTimestamp: entry.senderTimestamp }
116
+ : null
117
+ await authState.keys.set({ tctoken: { [storageJid]: cleared } })
118
+ }
119
+ return baseContent.length > 0 ? baseContent : undefined
120
+ }
121
+ baseContent.push({
122
+ tag: 'tctoken',
123
+ attrs: {},
124
+ content: tcTokenBuffer
125
+ })
126
+ return baseContent
127
+ } catch (error) {
128
+ return baseContent.length > 0 ? baseContent : undefined
129
+ }
130
+ }
131
+ async function storeTcTokensFromIqResult({ result, fallbackJid, keys, getLIDForPN, onNewJidStored }) {
132
+ const tokensNode = (0, WABinary_1.getBinaryNodeChild)(result, 'tokens')
133
+ if (!tokensNode) return
134
+ const tokenNodes = (0, WABinary_1.getBinaryNodeChildren)(tokensNode, 'token')
135
+ for (const tokenNode of tokenNodes) {
136
+ if (tokenNode.attrs.type !== 'trusted_contact' || !(tokenNode.content instanceof Uint8Array)) {
137
+ continue
138
+ }
139
+ // In notifications tokenNode.attrs.jid is your own device JID, not the sender's
140
+ const rawJid = (0, WABinary_1.jidNormalizedUser)(fallbackJid || tokenNode.attrs.jid)
141
+ if (!isRegularUser(rawJid)) continue
142
+ const storageJid = await resolveTcTokenJid(rawJid, getLIDForPN)
143
+ const existingTcData = await keys.get('tctoken', [storageJid])
144
+ const existingEntry = existingTcData[storageJid]
145
+ const existingTs = existingEntry?.timestamp ? Number(existingEntry.timestamp) : 0
146
+ const incomingTs = tokenNode.attrs.t ? Number(tokenNode.attrs.t) : 0
147
+ // timestamp-less tokens would be immediately expired
148
+ if (!incomingTs) continue
149
+ if (existingTs > 0 && existingTs > incomingTs) continue
150
+ await keys.set({
151
+ tctoken: {
152
+ [storageJid]: {
153
+ ...existingEntry,
154
+ token: Buffer.from(tokenNode.content),
155
+ timestamp: tokenNode.attrs.t
156
+ }
157
+ }
158
+ })
159
+ onNewJidStored?.(storageJid)
160
+ }
161
+ }
@@ -0,0 +1,121 @@
1
+ 'use strict'
2
+ Object.defineProperty(exports, '__esModule', { value: true })
3
+ exports.useMultiFileAuthState = void 0
4
+ const async_mutex_1 = require('async-mutex')
5
+ const promises_1 = require('fs/promises')
6
+ const path_1 = require('path')
7
+ const index_js_1 = require('../../WAProto/index.js')
8
+ const auth_utils_1 = require('./auth-utils')
9
+ const generics_1 = require('./generics')
10
+ // We need to lock files due to the fact that we are using async functions to read and write files
11
+ // https://github.com/WhiskeySockets/Baileys/issues/794
12
+ // https://github.com/nodejs/node/issues/26338
13
+ // Use a Map to store mutexes for each file path
14
+ const fileLocks = new Map()
15
+ // Get or create a mutex for a specific file path
16
+ const getFileLock = path => {
17
+ let mutex = fileLocks.get(path)
18
+ if (!mutex) {
19
+ mutex = new async_mutex_1.Mutex()
20
+ fileLocks.set(path, mutex)
21
+ }
22
+ return mutex
23
+ }
24
+ /**
25
+ * stores the full authentication state in a single folder.
26
+ * Far more efficient than singlefileauthstate
27
+ *
28
+ * Again, I wouldn't endorse this for any production level use other than perhaps a bot.
29
+ * Would recommend writing an auth state for use with a proper SQL or No-SQL DB
30
+ * */
31
+ const useMultiFileAuthState = async folder => {
32
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
33
+ const writeData = async (data, file) => {
34
+ const filePath = (0, path_1.join)(folder, fixFileName(file))
35
+ const mutex = getFileLock(filePath)
36
+ return mutex.acquire().then(async release => {
37
+ try {
38
+ await (0, promises_1.writeFile)(filePath, JSON.stringify(data, generics_1.BufferJSON.replacer))
39
+ } finally {
40
+ release()
41
+ }
42
+ })
43
+ }
44
+ const readData = async file => {
45
+ try {
46
+ const filePath = (0, path_1.join)(folder, fixFileName(file))
47
+ const mutex = getFileLock(filePath)
48
+ return await mutex.acquire().then(async release => {
49
+ try {
50
+ const data = await (0, promises_1.readFile)(filePath, { encoding: 'utf-8' })
51
+ return JSON.parse(data, generics_1.BufferJSON.reviver)
52
+ } finally {
53
+ release()
54
+ }
55
+ })
56
+ } catch (error) {
57
+ return null
58
+ }
59
+ }
60
+ const removeData = async file => {
61
+ try {
62
+ const filePath = (0, path_1.join)(folder, fixFileName(file))
63
+ const mutex = getFileLock(filePath)
64
+ return mutex.acquire().then(async release => {
65
+ try {
66
+ await (0, promises_1.unlink)(filePath)
67
+ } catch {
68
+ } finally {
69
+ release()
70
+ }
71
+ })
72
+ } catch {}
73
+ }
74
+ const folderInfo = await (0, promises_1.stat)(folder).catch(() => {})
75
+ if (folderInfo) {
76
+ if (!folderInfo.isDirectory()) {
77
+ throw new Error(
78
+ `found something that is not a directory at ${folder}, either delete it or specify a different location`
79
+ )
80
+ }
81
+ } else {
82
+ await (0, promises_1.mkdir)(folder, { recursive: true })
83
+ }
84
+ const fixFileName = file => file?.replace(/\//g, '__')?.replace(/:/g, '-')
85
+ const creds = (await readData('creds.json')) || (0, auth_utils_1.initAuthCreds)()
86
+ return {
87
+ state: {
88
+ creds,
89
+ keys: {
90
+ get: async (type, ids) => {
91
+ const data = {}
92
+ await Promise.all(
93
+ ids.map(async id => {
94
+ let value = await readData(`${type}-${id}.json`)
95
+ if (type === 'app-state-sync-key' && value) {
96
+ value = index_js_1.proto.Message.AppStateSyncKeyData.fromObject(value)
97
+ }
98
+ data[id] = value
99
+ })
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
+ exports.useMultiFileAuthState = useMultiFileAuthState
@@ -0,0 +1,248 @@
1
+ 'use strict'
2
+ Object.defineProperty(exports, '__esModule', { value: true })
3
+ exports.encodeSignedDeviceIdentity =
4
+ exports.configureSuccessfulPairing =
5
+ exports.generateRegistrationNode =
6
+ exports.generateLoginNode =
7
+ void 0
8
+ const boom_1 = require('@hapi/boom')
9
+ const crypto_1 = require('crypto')
10
+ const rb = require('whatsapp-rust-bridge-baron')
11
+ const index_js_1 = require('../../WAProto/index.js')
12
+ const Defaults_1 = require('../Defaults')
13
+ const WABinary_1 = require('../WABinary')
14
+ const crypto_2 = require('./crypto')
15
+ const generics_1 = require('./generics')
16
+ const signal_1 = require('./signal')
17
+ const MOBILE_PLATFORMS = new Set(['Android', 'iOS'])
18
+ const getUserAgent = config => {
19
+ const os = config.browser[0]
20
+ let platform, device, osVersion
21
+ if (os === 'Android') {
22
+ platform = index_js_1.proto.ClientPayload.UserAgent.Platform.ANDROID
23
+ device = 'Android'
24
+ osVersion = config.browser[2] || '15.0.0'
25
+ } else if (os === 'iOS') {
26
+ platform = index_js_1.proto.ClientPayload.UserAgent.Platform.IOS
27
+ device = 'iPhone'
28
+ osVersion = config.browser[2] || '18.0'
29
+ } else {
30
+ platform = index_js_1.proto.ClientPayload.UserAgent.Platform.WEB
31
+ device = 'Desktop'
32
+ osVersion = '0.1'
33
+ }
34
+ return {
35
+ appVersion: {
36
+ primary: config.version[0],
37
+ secondary: config.version[1],
38
+ tertiary: config.version[2]
39
+ },
40
+ platform,
41
+ releaseChannel: index_js_1.proto.ClientPayload.UserAgent.ReleaseChannel.DEBUG,
42
+ osVersion,
43
+ device,
44
+ osBuildNumber: '0.1',
45
+ localeLanguageIso6391: 'en',
46
+ mnc: '000',
47
+ mcc: '000',
48
+ localeCountryIso31661Alpha2: config.countryCode
49
+ }
50
+ }
51
+ const PLATFORM_MAP = {
52
+ 'Mac OS': index_js_1.proto.ClientPayload.WebInfo.WebSubPlatform.DARWIN,
53
+ Windows: index_js_1.proto.ClientPayload.WebInfo.WebSubPlatform.WIN32,
54
+ Android: index_js_1.proto.ClientPayload.WebInfo.WebSubPlatform.WEB_BROWSER,
55
+ iOS: index_js_1.proto.ClientPayload.WebInfo.WebSubPlatform.WEB_BROWSER
56
+ }
57
+ const getWebInfo = config => {
58
+ let webSubPlatform = index_js_1.proto.ClientPayload.WebInfo.WebSubPlatform.WEB_BROWSER
59
+ if (config.syncFullHistory && PLATFORM_MAP[config.browser[0]] && config.browser[1] === 'Desktop') {
60
+ webSubPlatform = PLATFORM_MAP[config.browser[0]]
61
+ }
62
+ return { webSubPlatform }
63
+ }
64
+ const getClientPayload = config => {
65
+ const payload = {
66
+ connectType: index_js_1.proto.ClientPayload.ConnectType.WIFI_UNKNOWN,
67
+ connectReason: index_js_1.proto.ClientPayload.ConnectReason.USER_ACTIVATED,
68
+ userAgent: getUserAgent(config)
69
+ }
70
+ if (!MOBILE_PLATFORMS.has(config.browser[0])) {
71
+ payload.webInfo = getWebInfo(config)
72
+ }
73
+ return payload
74
+ }
75
+ const generateLoginNode = (userJid, config, creds) => {
76
+ const { user, device } = (0, WABinary_1.jidDecode)(userJid)
77
+ // masqueradeAsPrimary: connect as device 0 so the WA server (and interop bridges)
78
+ // route primary-device traffic — including interop messages — to this session.
79
+ // Trade-off: the real phone (device 0 on TCP) may be kicked or see a conflict.
80
+ const effectiveDevice = config.masqueradeAsPrimary ? 0 : device
81
+ const payload = {
82
+ ...getClientPayload(config),
83
+ passive: !config.masqueradeAsPrimary,
84
+ pull: !config.masqueradeAsPrimary,
85
+ username: +user,
86
+ device: effectiveDevice,
87
+ lidDbMigrated: false
88
+ }
89
+ // InteropData is required for Meta/FB-linked accounts (AccountType = HOSTED).
90
+ // Populated from creds when present so the server routes interop traffic correctly.
91
+ if (creds?.interopData?.accountId) {
92
+ payload.interopData = {
93
+ accountId: creds.interopData.accountId,
94
+ token: creds.interopData.token,
95
+ enableReadReceipts: creds.interopData.enableReadReceipts ?? true
96
+ }
97
+ }
98
+ return index_js_1.proto.ClientPayload.fromObject(payload)
99
+ }
100
+ exports.generateLoginNode = generateLoginNode
101
+ const getPlatformType = platform => {
102
+ const platformType = platform.toUpperCase()
103
+ return index_js_1.proto.DeviceProps.PlatformType[platformType] || index_js_1.proto.DeviceProps.PlatformType.CHROME
104
+ }
105
+ const generateRegistrationNode = ({ registrationId, signedPreKey, signedIdentityKey }, config) => {
106
+ // the app version needs to be md5 hashed
107
+ // and passed in
108
+ const appVersionBuf = Buffer.from(rb.md5(Buffer.from(config.version.join('.'))))
109
+ const companion = {
110
+ os: config.browser[0],
111
+ platformType: getPlatformType(config.browser[1]),
112
+ requireFullSync: config.syncFullHistory,
113
+ historySyncConfig: {
114
+ fullSyncDaysLimit: undefined,
115
+ fullSyncSizeMbLimit: undefined,
116
+ storageQuotaMb: 10240,
117
+ inlineInitialPayloadInE2EeMsg: true,
118
+ recentSyncDaysLimit: undefined,
119
+ supportCallLogHistory: true,
120
+ supportBotUserAgentChatHistory: true,
121
+ supportCagReactionsAndPolls: true,
122
+ supportBizHostedMsg: true,
123
+ supportRecentSyncChunkMessageCountTuning: true,
124
+ supportHostedGroupMsg: true,
125
+ supportFbidBotChatHistory: true,
126
+ supportAddOnHistorySyncMigration: undefined,
127
+ supportMessageAssociation: true,
128
+ supportGroupHistory: true,
129
+ onDemandReady: undefined,
130
+ supportGuestChat: true,
131
+ completeOnDemandReady: undefined,
132
+ thumbnailSyncDaysLimit: undefined,
133
+ initialSyncMaxMessagesPerChat: undefined,
134
+ supportManusHistory: true,
135
+ supportHatchHistory: true,
136
+ supportedBotChannelFbids: undefined,
137
+ supportInlineContacts: true
138
+ },
139
+ version: {
140
+ primary: 10,
141
+ secondary: 15,
142
+ tertiary: 7
143
+ }
144
+ }
145
+ const companionProto = index_js_1.proto.DeviceProps.encode(companion).finish()
146
+ const registerPayload = {
147
+ ...getClientPayload(config),
148
+ passive: false,
149
+ pull: false,
150
+ devicePairingData: {
151
+ buildHash: appVersionBuf,
152
+ deviceProps: companionProto,
153
+ eRegid: (0, generics_1.encodeBigEndian)(registrationId),
154
+ eKeytype: Defaults_1.KEY_BUNDLE_TYPE,
155
+ eIdent: signedIdentityKey.public,
156
+ eSkeyId: (0, generics_1.encodeBigEndian)(signedPreKey.keyId, 3),
157
+ eSkeyVal: signedPreKey.keyPair.public,
158
+ eSkeySig: signedPreKey.signature
159
+ }
160
+ }
161
+ return index_js_1.proto.ClientPayload.fromObject(registerPayload)
162
+ }
163
+ exports.generateRegistrationNode = generateRegistrationNode
164
+ const configureSuccessfulPairing = (stanza, { advSecretKey, signedIdentityKey, signalIdentities }) => {
165
+ const msgId = stanza.attrs.id
166
+ const pairSuccessNode = (0, WABinary_1.getBinaryNodeChild)(stanza, 'pair-success')
167
+ const deviceIdentityNode = (0, WABinary_1.getBinaryNodeChild)(pairSuccessNode, 'device-identity')
168
+ const platformNode = (0, WABinary_1.getBinaryNodeChild)(pairSuccessNode, 'platform')
169
+ const deviceNode = (0, WABinary_1.getBinaryNodeChild)(pairSuccessNode, 'device')
170
+ const businessNode = (0, WABinary_1.getBinaryNodeChild)(pairSuccessNode, 'biz')
171
+ if (!deviceIdentityNode || !deviceNode) {
172
+ throw new boom_1.Boom('Missing device-identity or device in pair success node', { data: stanza })
173
+ }
174
+ const bizName = businessNode?.attrs.name
175
+ const jid = deviceNode.attrs.jid
176
+ const lid = deviceNode.attrs.lid
177
+ const { details, hmac, accountType } = index_js_1.proto.ADVSignedDeviceIdentityHMAC.decode(deviceIdentityNode.content)
178
+ let hmacPrefix = Buffer.from([])
179
+ if (accountType !== undefined && accountType === index_js_1.proto.ADVEncryptionType.HOSTED) {
180
+ hmacPrefix = Defaults_1.WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX
181
+ }
182
+ const advSign = (0, crypto_2.hmacSign)(Buffer.concat([hmacPrefix, details]), Buffer.from(advSecretKey, 'base64'))
183
+ if (Buffer.compare(hmac, advSign) !== 0) {
184
+ throw new boom_1.Boom('Invalid account signature')
185
+ }
186
+ const account = index_js_1.proto.ADVSignedDeviceIdentity.decode(details)
187
+ const { accountSignatureKey, accountSignature, details: deviceDetails } = account
188
+ const deviceIdentity = index_js_1.proto.ADVDeviceIdentity.decode(deviceDetails)
189
+ const accountSignaturePrefix =
190
+ deviceIdentity.deviceType === index_js_1.proto.ADVEncryptionType.HOSTED
191
+ ? Defaults_1.WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX
192
+ : Defaults_1.WA_ADV_ACCOUNT_SIG_PREFIX
193
+ const accountMsg = Buffer.concat([accountSignaturePrefix, deviceDetails, signedIdentityKey.public])
194
+ if (!crypto_2.Curve.verify(accountSignatureKey, accountMsg, accountSignature)) {
195
+ throw new boom_1.Boom('Failed to verify account signature')
196
+ }
197
+ const deviceMsg = Buffer.concat([
198
+ Defaults_1.WA_ADV_DEVICE_SIG_PREFIX,
199
+ deviceDetails,
200
+ signedIdentityKey.public,
201
+ accountSignatureKey
202
+ ])
203
+ account.deviceSignature = crypto_2.Curve.sign(signedIdentityKey.private, deviceMsg)
204
+ const identity = (0, signal_1.createSignalIdentity)(lid, accountSignatureKey)
205
+ const accountEnc = (0, exports.encodeSignedDeviceIdentity)(account, false)
206
+ const reply = {
207
+ tag: 'iq',
208
+ attrs: {
209
+ to: WABinary_1.S_WHATSAPP_NET,
210
+ type: 'result',
211
+ id: msgId
212
+ },
213
+ content: [
214
+ {
215
+ tag: 'pair-device-sign',
216
+ attrs: {},
217
+ content: [
218
+ {
219
+ tag: 'device-identity',
220
+ attrs: { 'key-index': deviceIdentity.keyIndex.toString() },
221
+ content: accountEnc
222
+ }
223
+ ]
224
+ }
225
+ ]
226
+ }
227
+ const authUpdate = {
228
+ account,
229
+ me: { id: jid, name: bizName, lid },
230
+ signalIdentities: [...(signalIdentities || []), identity],
231
+ platform: platformNode?.attrs.name
232
+ }
233
+ return {
234
+ creds: authUpdate,
235
+ reply
236
+ }
237
+ }
238
+ exports.configureSuccessfulPairing = configureSuccessfulPairing
239
+ const encodeSignedDeviceIdentity = (account, includeSignatureKey) => {
240
+ account = { ...account }
241
+ // set to null if we are not to include the signature key
242
+ // or if we are including the signature key but it is empty
243
+ if (!includeSignatureKey || !account.accountSignatureKey?.length) {
244
+ account.accountSignatureKey = null
245
+ }
246
+ return index_js_1.proto.ADVSignedDeviceIdentity.encode(account).finish()
247
+ }
248
+ exports.encodeSignedDeviceIdentity = encodeSignedDeviceIdentity
@@ -0,0 +1,22 @@
1
+ 'use strict'
2
+ Object.defineProperty(exports, '__esModule', { value: true })
3
+ exports.decodeE2eRekeyPayload = void 0
4
+ const index_js_1 = require('../../WAProto/index.js')
5
+ const REKEY_TYPE_NAMES = {
6
+ [index_js_1.proto.RekeyKeyType.REKEY_KEY_AUDIO]: 'REKEY_KEY_AUDIO',
7
+ [index_js_1.proto.RekeyKeyType.REKEY_KEY_VIDEO]: 'REKEY_KEY_VIDEO',
8
+ [index_js_1.proto.RekeyKeyType.REKEY_KEY_APPDATA]: 'REKEY_KEY_APPDATA'
9
+ }
10
+ const decodeE2eRekeyPayload = buffer => {
11
+ if (!Buffer.isBuffer(buffer) && !(buffer instanceof Uint8Array)) {
12
+ throw new TypeError('decodeE2eRekeyPayload: buffer must be Buffer or Uint8Array')
13
+ }
14
+ const decoded = index_js_1.proto.E2eRekeyPayload.decode(buffer)
15
+ return {
16
+ keys: (decoded.keys || []).map(entry => ({
17
+ type: REKEY_TYPE_NAMES[entry.type] ?? entry.type,
18
+ key: entry.key ? Buffer.from(entry.key) : Buffer.alloc(0)
19
+ }))
20
+ }
21
+ }
22
+ exports.decodeE2eRekeyPayload = decodeE2eRekeyPayload