sanka-baileyss 1.4.8

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 (252) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +2520 -0
  3. package/WAProto/Adv/Adv.d.ts +518 -0
  4. package/WAProto/Adv/Adv.js +1734 -0
  5. package/WAProto/Adv/Adv.proto +36 -0
  6. package/WAProto/Cert/Cert.d.ts +497 -0
  7. package/WAProto/Cert/Cert.js +1503 -0
  8. package/WAProto/Cert/Cert.proto +28 -0
  9. package/WAProto/ChatLockSettings/ChatLockSettings.d.ts +391 -0
  10. package/WAProto/ChatLockSettings/ChatLockSettings.js +1155 -0
  11. package/WAProto/ChatLockSettings/ChatLockSettings.proto +7 -0
  12. package/WAProto/CompanionReg/CompanionReg.d.ts +1049 -0
  13. package/WAProto/CompanionReg/CompanionReg.js +3496 -0
  14. package/WAProto/CompanionReg/CompanionReg.proto +88 -0
  15. package/WAProto/DeviceCapabilities/DeviceCapabilities.d.ts +187 -0
  16. package/WAProto/DeviceCapabilities/DeviceCapabilities.js +520 -0
  17. package/WAProto/DeviceCapabilities/DeviceCapabilities.proto +14 -0
  18. package/WAProto/E2E/E2E.d.ts +27989 -0
  19. package/WAProto/E2E/E2E.js +97013 -0
  20. package/WAProto/E2E/E2E.proto +2256 -0
  21. package/WAProto/Ephemeral/Ephemeral.d.ts +95 -0
  22. package/WAProto/Ephemeral/Ephemeral.js +269 -0
  23. package/WAProto/Ephemeral/Ephemeral.proto +6 -0
  24. package/WAProto/HistorySync/HistorySync.d.ts +40300 -0
  25. package/WAProto/HistorySync/HistorySync.js +141555 -0
  26. package/WAProto/HistorySync/HistorySync.proto +207 -0
  27. package/WAProto/LidMigrationSyncPayload/LidMigrationSyncPayload.d.ts +189 -0
  28. package/WAProto/LidMigrationSyncPayload/LidMigrationSyncPayload.js +585 -0
  29. package/WAProto/LidMigrationSyncPayload/LidMigrationSyncPayload.proto +11 -0
  30. package/WAProto/MdStorageChatRowOpaqueData/MdStorageChatRowOpaqueData.d.ts +461 -0
  31. package/WAProto/MdStorageChatRowOpaqueData/MdStorageChatRowOpaqueData.js +1559 -0
  32. package/WAProto/MdStorageChatRowOpaqueData/MdStorageChatRowOpaqueData.proto +37 -0
  33. package/WAProto/MdStorageMsgRowOpaqueData/MdStorageMsgRowOpaqueData.d.ts +28866 -0
  34. package/WAProto/MdStorageMsgRowOpaqueData/MdStorageMsgRowOpaqueData.js +100307 -0
  35. package/WAProto/MdStorageMsgRowOpaqueData/MdStorageMsgRowOpaqueData.proto +76 -0
  36. package/WAProto/MmsRetry/MmsRetry.d.ts +200 -0
  37. package/WAProto/MmsRetry/MmsRetry.js +586 -0
  38. package/WAProto/MmsRetry/MmsRetry.proto +17 -0
  39. package/WAProto/Protocol/Protocol.d.ts +218 -0
  40. package/WAProto/Protocol/Protocol.js +701 -0
  41. package/WAProto/Protocol/Protocol.proto +20 -0
  42. package/WAProto/Reporting/Reporting.d.ts +301 -0
  43. package/WAProto/Reporting/Reporting.js +989 -0
  44. package/WAProto/Reporting/Reporting.proto +19 -0
  45. package/WAProto/ServerSync/ServerSync.d.ts +1050 -0
  46. package/WAProto/ServerSync/ServerSync.js +3176 -0
  47. package/WAProto/ServerSync/ServerSync.proto +59 -0
  48. package/WAProto/SignalLocalStorageProtocol/SignalLocalStorageProtocol.d.ts +1507 -0
  49. package/WAProto/SignalLocalStorageProtocol/SignalLocalStorageProtocol.js +4756 -0
  50. package/WAProto/SignalLocalStorageProtocol/SignalLocalStorageProtocol.proto +88 -0
  51. package/WAProto/SignalWhisperTextProtocol/SignalWhisperTextProtocol.d.ts +617 -0
  52. package/WAProto/SignalWhisperTextProtocol/SignalWhisperTextProtocol.js +1940 -0
  53. package/WAProto/SignalWhisperTextProtocol/SignalWhisperTextProtocol.proto +38 -0
  54. package/WAProto/StatusAttributions/StatusAttributions.d.ts +544 -0
  55. package/WAProto/StatusAttributions/StatusAttributions.js +1769 -0
  56. package/WAProto/StatusAttributions/StatusAttributions.proto +53 -0
  57. package/WAProto/SyncAction/SyncAction.d.ts +7227 -0
  58. package/WAProto/SyncAction/SyncAction.js +22271 -0
  59. package/WAProto/SyncAction/SyncAction.proto +423 -0
  60. package/WAProto/UserPassword/UserPassword.d.ts +298 -0
  61. package/WAProto/UserPassword/UserPassword.js +898 -0
  62. package/WAProto/UserPassword/UserPassword.proto +27 -0
  63. package/WAProto/VnameCert/VnameCert.d.ts +658 -0
  64. package/WAProto/VnameCert/VnameCert.js +2225 -0
  65. package/WAProto/VnameCert/VnameCert.proto +60 -0
  66. package/WAProto/Wa6/Wa6.d.ts +1613 -0
  67. package/WAProto/Wa6/Wa6.js +6299 -0
  68. package/WAProto/Wa6/Wa6.proto +229 -0
  69. package/WAProto/Web/Web.d.ts +31290 -0
  70. package/WAProto/Web/Web.js +111977 -0
  71. package/WAProto/Web/Web.proto +545 -0
  72. package/WAProto/index.d.ts +49 -0
  73. package/WAProto/index.js +28 -0
  74. package/WASignalGroup/GroupProtocol.js +1771 -0
  75. package/WASignalGroup/ciphertext_message.js +10 -0
  76. package/WASignalGroup/group_cipher.js +103 -0
  77. package/WASignalGroup/group_session_builder.js +39 -0
  78. package/WASignalGroup/index.js +5 -0
  79. package/WASignalGroup/keyhelper.js +17 -0
  80. package/WASignalGroup/protobufs.js +2 -0
  81. package/WASignalGroup/queue_job.js +64 -0
  82. package/WASignalGroup/sender_chain_key.js +38 -0
  83. package/WASignalGroup/sender_key_distribution_message.js +68 -0
  84. package/WASignalGroup/sender_key_message.js +79 -0
  85. package/WASignalGroup/sender_key_name.js +59 -0
  86. package/WASignalGroup/sender_key_record.js +47 -0
  87. package/WASignalGroup/sender_key_state.js +110 -0
  88. package/WASignalGroup/sender_message_key.js +30 -0
  89. package/check-node-version.js +10 -0
  90. package/lib/Defaults/baileys-version.json +3 -0
  91. package/lib/Defaults/index.d.ts +51 -0
  92. package/lib/Defaults/index.js +108 -0
  93. package/lib/Defaults/phonenumber-mcc.json +223 -0
  94. package/lib/Signal/libsignal.d.ts +3 -0
  95. package/lib/Signal/libsignal.js +153 -0
  96. package/lib/Socket/Client/index.d.ts +2 -0
  97. package/lib/Socket/Client/index.js +18 -0
  98. package/lib/Socket/Client/types.d.ts +15 -0
  99. package/lib/Socket/Client/types.js +14 -0
  100. package/lib/Socket/Client/websocket.d.ts +12 -0
  101. package/lib/Socket/Client/websocket.js +57 -0
  102. package/lib/Socket/business.d.ts +181 -0
  103. package/lib/Socket/business.js +259 -0
  104. package/lib/Socket/chats.d.ts +95 -0
  105. package/lib/Socket/chats.js +906 -0
  106. package/lib/Socket/groups.d.ts +128 -0
  107. package/lib/Socket/groups.js +307 -0
  108. package/lib/Socket/index.d.ts +183 -0
  109. package/lib/Socket/index.js +10 -0
  110. package/lib/Socket/messages-recv.d.ts +170 -0
  111. package/lib/Socket/messages-recv.js +1072 -0
  112. package/lib/Socket/messages-send.d.ts +161 -0
  113. package/lib/Socket/messages-send.js +984 -0
  114. package/lib/Socket/newsletter.d.ts +140 -0
  115. package/lib/Socket/newsletter.js +242 -0
  116. package/lib/Socket/socket.d.ts +43 -0
  117. package/lib/Socket/socket.js +651 -0
  118. package/lib/Socket/usync.d.ts +36 -0
  119. package/lib/Socket/usync.js +71 -0
  120. package/lib/Store/index.d.ts +4 -0
  121. package/lib/Store/index.js +20 -0
  122. package/lib/Store/make-cache-manager-store.d.ts +13 -0
  123. package/lib/Store/make-cache-manager-store.js +85 -0
  124. package/lib/Store/make-in-memory-store.d.ts +117 -0
  125. package/lib/Store/make-in-memory-store.js +420 -0
  126. package/lib/Store/make-ordered-dictionary.d.ts +12 -0
  127. package/lib/Store/make-ordered-dictionary.js +83 -0
  128. package/lib/Store/object-repository.d.ts +10 -0
  129. package/lib/Store/object-repository.js +28 -0
  130. package/lib/Types/Auth.d.ts +103 -0
  131. package/lib/Types/Auth.js +2 -0
  132. package/lib/Types/Call.d.ts +13 -0
  133. package/lib/Types/Call.js +2 -0
  134. package/lib/Types/Chat.d.ts +115 -0
  135. package/lib/Types/Chat.js +6 -0
  136. package/lib/Types/Contact.d.ts +24 -0
  137. package/lib/Types/Contact.js +2 -0
  138. package/lib/Types/Events.d.ts +208 -0
  139. package/lib/Types/Events.js +2 -0
  140. package/lib/Types/GroupMetadata.d.ts +58 -0
  141. package/lib/Types/GroupMetadata.js +2 -0
  142. package/lib/Types/Label.d.ts +46 -0
  143. package/lib/Types/Label.js +28 -0
  144. package/lib/Types/LabelAssociation.d.ts +29 -0
  145. package/lib/Types/LabelAssociation.js +10 -0
  146. package/lib/Types/Message.d.ts +391 -0
  147. package/lib/Types/Message.js +9 -0
  148. package/lib/Types/Newsletter.d.ts +92 -0
  149. package/lib/Types/Newsletter.js +33 -0
  150. package/lib/Types/Product.d.ts +78 -0
  151. package/lib/Types/Product.js +2 -0
  152. package/lib/Types/Signal.d.ts +57 -0
  153. package/lib/Types/Signal.js +2 -0
  154. package/lib/Types/Socket.d.ts +116 -0
  155. package/lib/Types/Socket.js +2 -0
  156. package/lib/Types/State.d.ts +27 -0
  157. package/lib/Types/State.js +2 -0
  158. package/lib/Types/USync.d.ts +25 -0
  159. package/lib/Types/USync.js +2 -0
  160. package/lib/Types/index.d.ts +70 -0
  161. package/lib/Types/index.js +42 -0
  162. package/lib/Utils/auth-utils.d.ts +18 -0
  163. package/lib/Utils/auth-utils.js +198 -0
  164. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  165. package/lib/Utils/baileys-event-stream.js +64 -0
  166. package/lib/Utils/business.d.ts +22 -0
  167. package/lib/Utils/business.js +239 -0
  168. package/lib/Utils/chat-utils.d.ts +70 -0
  169. package/lib/Utils/chat-utils.js +754 -0
  170. package/lib/Utils/crypto.d.ts +40 -0
  171. package/lib/Utils/crypto.js +150 -0
  172. package/lib/Utils/decode-wa-message.d.ts +36 -0
  173. package/lib/Utils/decode-wa-message.js +228 -0
  174. package/lib/Utils/event-buffer.d.ts +35 -0
  175. package/lib/Utils/event-buffer.js +539 -0
  176. package/lib/Utils/generics.d.ts +96 -0
  177. package/lib/Utils/generics.js +553 -0
  178. package/lib/Utils/history.d.ts +19 -0
  179. package/lib/Utils/history.js +93 -0
  180. package/lib/Utils/index.d.ts +19 -0
  181. package/lib/Utils/index.js +35 -0
  182. package/lib/Utils/link-preview.d.ts +21 -0
  183. package/lib/Utils/link-preview.js +112 -0
  184. package/lib/Utils/logger.d.ts +11 -0
  185. package/lib/Utils/logger.js +7 -0
  186. package/lib/Utils/lt-hash.d.ts +12 -0
  187. package/lib/Utils/lt-hash.js +53 -0
  188. package/lib/Utils/make-mutex.d.ts +7 -0
  189. package/lib/Utils/make-mutex.js +45 -0
  190. package/lib/Utils/messages-media.d.ts +104 -0
  191. package/lib/Utils/messages-media.js +751 -0
  192. package/lib/Utils/messages.d.ts +80 -0
  193. package/lib/Utils/messages.js +1371 -0
  194. package/lib/Utils/noise-handler.d.ts +19 -0
  195. package/lib/Utils/noise-handler.js +150 -0
  196. package/lib/Utils/process-message.d.ts +41 -0
  197. package/lib/Utils/process-message.js +378 -0
  198. package/lib/Utils/signal.d.ts +33 -0
  199. package/lib/Utils/signal.js +154 -0
  200. package/lib/Utils/use-mongo-file-auth-state.d.ts +5 -0
  201. package/lib/Utils/use-mongo-file-auth-state.js +75 -0
  202. package/lib/Utils/use-multi-file-auth-state.d.ts +12 -0
  203. package/lib/Utils/use-multi-file-auth-state.js +123 -0
  204. package/lib/Utils/use-single-file-auth-state.d.ts +12 -0
  205. package/lib/Utils/use-single-file-auth-state.js +75 -0
  206. package/lib/Utils/validate-connection.d.ts +10 -0
  207. package/lib/Utils/validate-connection.js +174 -0
  208. package/lib/WABinary/constants.d.ts +27 -0
  209. package/lib/WABinary/constants.js +45 -0
  210. package/lib/WABinary/decode.d.ts +6 -0
  211. package/lib/WABinary/decode.js +255 -0
  212. package/lib/WABinary/encode.d.ts +2 -0
  213. package/lib/WABinary/encode.js +243 -0
  214. package/lib/WABinary/generic-utils.d.ts +16 -0
  215. package/lib/WABinary/generic-utils.js +125 -0
  216. package/lib/WABinary/index.d.ts +5 -0
  217. package/lib/WABinary/index.js +21 -0
  218. package/lib/WABinary/jid-utils.d.ts +34 -0
  219. package/lib/WABinary/jid-utils.js +73 -0
  220. package/lib/WABinary/types.d.ts +18 -0
  221. package/lib/WABinary/types.js +2 -0
  222. package/lib/WAM/BinaryInfo.d.ts +16 -0
  223. package/lib/WAM/BinaryInfo.js +14 -0
  224. package/lib/WAM/constants.d.ts +39 -0
  225. package/lib/WAM/constants.js +15362 -0
  226. package/lib/WAM/encode.d.ts +2 -0
  227. package/lib/WAM/encode.js +156 -0
  228. package/lib/WAM/index.d.ts +3 -0
  229. package/lib/WAM/index.js +19 -0
  230. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.d.ts +25 -0
  231. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +60 -0
  232. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  233. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  234. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  235. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +58 -0
  236. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  237. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +31 -0
  238. package/lib/WAUSync/Protocols/USyncLIDProtocol.d.ts +8 -0
  239. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +26 -0
  240. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  241. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  242. package/lib/WAUSync/Protocols/index.d.ts +6 -0
  243. package/lib/WAUSync/Protocols/index.js +22 -0
  244. package/lib/WAUSync/USyncQuery.d.ts +28 -0
  245. package/lib/WAUSync/USyncQuery.js +88 -0
  246. package/lib/WAUSync/USyncUser.d.ts +12 -0
  247. package/lib/WAUSync/USyncUser.js +27 -0
  248. package/lib/WAUSync/index.d.ts +3 -0
  249. package/lib/WAUSync/index.js +19 -0
  250. package/lib/index.d.ts +13 -0
  251. package/lib/index.js +9 -0
  252. package/package.json +66 -0
@@ -0,0 +1,1072 @@
1
+ "use strict"
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod }
4
+ }
5
+ Object.defineProperty(exports, "__esModule", { value: true })
6
+ const node_cache_1 = __importDefault(require("@cacheable/node-cache"))
7
+ const boom_1 = require("@hapi/boom")
8
+ const crypto_1 = require("crypto")
9
+ const WAProto_1 = require("../../WAProto")
10
+ const Defaults_1 = require("../Defaults")
11
+ const Types_1 = require("../Types")
12
+ const Utils_1 = require("../Utils")
13
+ const make_mutex_1 = require("../Utils/make-mutex")
14
+ const WABinary_1 = require("../WABinary")
15
+ const groups_1 = require("./groups")
16
+ const messages_send_1 = require("./messages-send")
17
+ const makeMessagesRecvSocket = (config) => {
18
+ const { logger, retryRequestDelayMs, maxMsgRetryCount, getMessage, shouldIgnoreJid } = config
19
+ const suki = messages_send_1.makeMessagesSocket(config)
20
+ const { ev, authState, ws, processingMutex, signalRepository, query, upsertMessage, resyncAppState, onUnexpectedError, assertSessions, sendNode, relayMessage, sendReceipt, uploadPreKeys, getUSyncDevices, createParticipantNodes, sendPeerDataOperationMessage } = suki
21
+ /** this mutex ensures that each retryRequest will wait for the previous one to finish */
22
+ const retryMutex = make_mutex_1.makeMutex()
23
+ const msgRetryCache = config.msgRetryCounterCache || new node_cache_1.default({
24
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY,
25
+ useClones: false
26
+ })
27
+ const callOfferCache = config.callOfferCache || new node_cache_1.default({
28
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.CALL_OFFER,
29
+ useClones: false
30
+ })
31
+ const placeholderResendCache = config.placeholderResendCache || new node_cache_1.default({
32
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY,
33
+ useClones: false
34
+ })
35
+ let sendActiveReceipts = false
36
+ const sendMessageAck = async ({ tag, attrs, content }, errorCode) => {
37
+ const stanza = {
38
+ tag: 'ack',
39
+ attrs: {
40
+ id: attrs.id,
41
+ to: attrs.from,
42
+ class: tag
43
+ }
44
+ }
45
+ if (!!errorCode) {
46
+ stanza.attrs.error = errorCode.toString()
47
+ }
48
+ if (!!attrs.participant) {
49
+ stanza.attrs.participant = attrs.participant
50
+ }
51
+ if (!!attrs.recipient) {
52
+ stanza.attrs.recipient = attrs.recipient
53
+ }
54
+ if (!!attrs.type && (tag !== 'message' || WABinary_1.getBinaryNodeChild({ tag, attrs, content }, 'unavailable') || errorCode !== 0)) {
55
+ stanza.attrs.type = attrs.type
56
+ }
57
+ if (tag === 'message' && WABinary_1.getBinaryNodeChild({ tag, attrs, content }, 'unavailable')) {
58
+ stanza.attrs.from = authState.creds.me.id
59
+ }
60
+ logger.debug({ recv: { tag, attrs }, sent: stanza.attrs }, 'sent ack')
61
+ await sendNode(stanza)
62
+ }
63
+ const offerCall = async (toJid, isVideo = false) => {
64
+ const callId = crypto_1.randomBytes(16).toString('hex').toUpperCase().substring(0, 64)
65
+ const offerContent = []
66
+ offerContent.push({ tag: 'audio', attrs: { enc: 'opus', rate: '16000' }, content: undefined })
67
+ offerContent.push({ tag: 'audio', attrs: { enc: 'opus', rate: '8000' }, content: undefined })
68
+ if (isVideo) {
69
+ offerContent.push({
70
+ tag: 'video',
71
+ attrs: { enc: 'vp8', dec: 'vp8', orientation: '0', 'screen_width': '1920', 'screen_height': '1080', 'device_orientation': '0' },
72
+ content: undefined
73
+ })
74
+ }
75
+ offerContent.push({ tag: 'net', attrs: { medium: '3' }, content: undefined })
76
+ offerContent.push({ tag: 'capability', attrs: { ver: '1' }, content: new Uint8Array([1, 4, 255, 131, 207, 4]) })
77
+ offerContent.push({ tag: 'encopt', attrs: { keygen: '2' }, content: undefined })
78
+ const encKey = crypto_1.randomBytes(32)
79
+ const devices = (await getUSyncDevices([toJid], true, false)).map(({ user, device }) => WABinary_1.jidEncode(user, 's.whatsapp.net', device))
80
+ await assertSessions(devices, true)
81
+ const { nodes: destinations, shouldIncludeDeviceIdentity } = await createParticipantNodes(devices, {
82
+ call: {
83
+ callKey: new Uint8Array(encKey)
84
+ }
85
+ }, { count: '0' })
86
+ offerContent.push({ tag: 'destination', attrs: {}, content: destinations })
87
+ if (shouldIncludeDeviceIdentity) {
88
+ offerContent.push({
89
+ tag: 'device-identity',
90
+ attrs: {},
91
+ content: Utils_1.encodeSignedDeviceIdentity(authState.creds.account, true)
92
+ })
93
+ }
94
+ const stanza = ({
95
+ tag: 'call',
96
+ attrs: {
97
+ id: Utils_1.generateMessageID(),
98
+ to: toJid,
99
+ },
100
+ content: [{
101
+ tag: 'offer',
102
+ attrs: {
103
+ 'call-id': callId,
104
+ 'call-creator': authState.creds.me.id,
105
+ },
106
+ content: offerContent,
107
+ }],
108
+ })
109
+ await query(stanza)
110
+ return {
111
+ id: callId,
112
+ to: toJid
113
+ }
114
+ }
115
+ const rejectCall = async (callId, callFrom) => {
116
+ const stanza = ({
117
+ tag: 'call',
118
+ attrs: {
119
+ from: authState.creds.me.id,
120
+ to: callFrom,
121
+ },
122
+ content: [{
123
+ tag: 'reject',
124
+ attrs: {
125
+ 'call-id': callId,
126
+ 'call-creator': callFrom,
127
+ count: '0',
128
+ },
129
+ content: undefined,
130
+ }],
131
+ })
132
+ await query(stanza)
133
+ }
134
+ const sendRetryRequest = async (node, forceIncludeKeys = false) => {
135
+ const { fullMessage } = Utils_1.decodeMessageNode(node, authState.creds.me.id, authState.creds.me.lid || '')
136
+ const { key: msgKey } = fullMessage
137
+ const msgId = msgKey.id
138
+ const key = `${msgId}:${msgKey?.participant}`
139
+ let retryCount = msgRetryCache.get(key) || 0
140
+ if (retryCount >= maxMsgRetryCount) {
141
+ logger.debug({ retryCount, msgId }, 'reached retry limit, clearing')
142
+ msgRetryCache.del(key)
143
+ return
144
+ }
145
+ retryCount += 1
146
+ msgRetryCache.set(key, retryCount)
147
+ const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds
148
+ if (retryCount === 1) {
149
+ //request a resend via phone
150
+ const msgId = await requestPlaceholderResend(msgKey)
151
+ logger.debug(`sendRetryRequest: requested placeholder resend for message ${msgId}`)
152
+ }
153
+ const deviceIdentity = Utils_1.encodeSignedDeviceIdentity(account, true)
154
+ await authState.keys.transaction(async () => {
155
+ const receipt = {
156
+ tag: 'receipt',
157
+ attrs: {
158
+ id: msgId,
159
+ type: 'retry',
160
+ to: node.attrs.from
161
+ },
162
+ content: [
163
+ {
164
+ tag: 'retry',
165
+ attrs: {
166
+ count: retryCount.toString(),
167
+ id: node.attrs.id,
168
+ t: node.attrs.t,
169
+ v: '1'
170
+ }
171
+ },
172
+ {
173
+ tag: 'registration',
174
+ attrs: {},
175
+ content: Utils_1.encodeBigEndian(authState.creds.registrationId)
176
+ }
177
+ ]
178
+ }
179
+ if (node.attrs.recipient) {
180
+ receipt.attrs.recipient = node.attrs.recipient
181
+ }
182
+ if (node.attrs.participant) {
183
+ receipt.attrs.participant = node.attrs.participant
184
+ }
185
+ if (retryCount > 1 || forceIncludeKeys) {
186
+ const { update, preKeys } = await Utils_1.getNextPreKeys(authState, 1)
187
+ const [keyId] = Object.keys(preKeys)
188
+ const key = preKeys[+keyId]
189
+ const content = receipt.content
190
+ content.push({
191
+ tag: 'keys',
192
+ attrs: {},
193
+ content: [
194
+ { tag: 'type', attrs: {}, content: Buffer.from(Defaults_1.KEY_BUNDLE_TYPE) },
195
+ { tag: 'identity', attrs: {}, content: identityKey.public },
196
+ Utils_1.xmppPreKey(key, +keyId),
197
+ Utils_1.xmppSignedPreKey(signedPreKey),
198
+ { tag: 'device-identity', attrs: {}, content: deviceIdentity }
199
+ ]
200
+ })
201
+ ev.emit('creds.update', update)
202
+ }
203
+ await sendNode(receipt)
204
+ logger.info({ msgAttrs: node.attrs, retryCount }, 'sent retry receipt')
205
+ })
206
+ }
207
+ const handleEncryptNotification = async (node) => {
208
+ const from = node.attrs.from
209
+ if (from === WABinary_1.S_WHATSAPP_NET) {
210
+ const countChild = WABinary_1.getBinaryNodeChild(node, 'count')
211
+ const count = +countChild.attrs.value
212
+ const shouldUploadMorePreKeys = count < Defaults_1.MIN_PREKEY_COUNT
213
+ logger.debug({ count, shouldUploadMorePreKeys }, 'recv pre-key count')
214
+ if (shouldUploadMorePreKeys) {
215
+ await uploadPreKeys()
216
+ }
217
+ }
218
+ else {
219
+ const identityNode = WABinary_1.getBinaryNodeChild(node, 'identity')
220
+ if (identityNode) {
221
+ logger.info({ jid: from }, 'identity changed')
222
+ // not handling right now
223
+ // signal will override new identity anyway
224
+ }
225
+ else {
226
+ logger.info({ node }, 'unknown encrypt notification')
227
+ }
228
+ }
229
+ }
230
+ const handleGroupNotification = (participant, child, msg) => {
231
+ const participantJid = WABinary_1.getBinaryNodeChild(child, 'participant')?.attrs?.jid || participant
232
+ switch (child.tag) {
233
+ case 'create':
234
+ const metadata = groups_1.extractGroupMetadata(child)
235
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CREATE
236
+ msg.messageStubParameters = [metadata.subject]
237
+ msg.key = { participant: metadata.owner }
238
+ ev.emit('chats.upsert', [{
239
+ id: metadata.id,
240
+ name: metadata.subject,
241
+ conversationTimestamp: metadata.creation,
242
+ }])
243
+ ev.emit('groups.upsert', [{
244
+ ...metadata,
245
+ author: participant
246
+ }])
247
+ break
248
+ case 'delete':
249
+ msg.messageStubType = Types_1.WAMessageStubType.COMMUNITY_PARENT_GROUP_DELETED
250
+ msg.messageStubParameters = [participantJid, 'delete']
251
+ break
252
+ case 'ephemeral':
253
+ case 'not_ephemeral':
254
+ msg.message = {
255
+ protocolMessage: {
256
+ type: WAProto_1.proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
257
+ ephemeralExpiration: +(child.attrs.expiration || 0)
258
+ }
259
+ }
260
+ break
261
+ case 'modify':
262
+ const oldNumber = WABinary_1.getBinaryNodeChildren(child, 'participant').map(p => p.attrs.jid)
263
+ msg.messageStubParameters = oldNumber || []
264
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER
265
+ break
266
+ case 'promote':
267
+ case 'demote':
268
+ case 'remove':
269
+ case 'add':
270
+ case 'leave':
271
+ let stubType = `GROUP_PARTICIPANT_${child.tag.toUpperCase()}`
272
+ if (child.attrs?.reason === 'linked_group_join') {
273
+ stubType = GROUP_PARTICIPANT_LINKED_GROUP_JOIN
274
+ }
275
+ msg.messageStubType = Types_1.WAMessageStubType[stubType]
276
+ const participants = WABinary_1.getBinaryNodeChildren(child, 'participant').map(p => p.attrs.jid)
277
+ if (participants.length === 1 &&
278
+ // if recv. "remove" message and sender removed themselves
279
+ // mark as left
280
+ WABinary_1.areJidsSameUser(participants[0], participant) &&
281
+ child.tag === 'remove') {
282
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_PARTICIPANT_LEAVE
283
+ }
284
+ msg.messageStubParameters = participants
285
+ break
286
+ case 'subject':
287
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_SUBJECT
288
+ msg.messageStubParameters = [child.attrs.subject]
289
+ break
290
+ case 'description':
291
+ const description = WABinary_1.getBinaryNodeChild(child, 'body')?.content?.toString()
292
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_DESCRIPTION
293
+ msg.messageStubParameters = description ? [description] : undefined
294
+ break
295
+ case 'announcement':
296
+ case 'not_announcement':
297
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_ANNOUNCE
298
+ msg.messageStubParameters = [(child.tag === 'announcement') ? 'on' : 'off']
299
+ break
300
+ case 'locked':
301
+ case 'unlocked':
302
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_RESTRICT
303
+ msg.messageStubParameters = [(child.tag === 'locked') ? 'on' : 'off']
304
+ break
305
+ case 'invite':
306
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_INVITE_LINK
307
+ msg.messageStubParameters = [child.attrs.code]
308
+ break
309
+ case 'member_add_mode':
310
+ const addMode = child.content
311
+ if (addMode) {
312
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBER_ADD_MODE
313
+ msg.messageStubParameters = [addMode.toString()]
314
+ }
315
+ break
316
+ case 'membership_approval_mode':
317
+ const approvalMode = WABinary_1.getBinaryNodeChild(child, 'group_join')
318
+ if (approvalMode) {
319
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE
320
+ msg.messageStubParameters = [approvalMode.attrs.state]
321
+ }
322
+ break
323
+ case 'created_membership_requests':
324
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD
325
+ msg.messageStubParameters = [participantJid, 'created', child.attrs.request_method]
326
+ break
327
+ case 'revoked_membership_requests':
328
+ const isDenied = WABinary_1.areJidsSameUser(participantJid, participant)
329
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD
330
+ msg.messageStubParameters = [participantJid, isDenied ? 'revoked' : 'rejected']
331
+ break
332
+ case 'link':
333
+ case 'unlink':
334
+ const type = child.attrs?.unlink_type || child.attrs?.link_type
335
+ const stubMap = {
336
+ parent_group: Types_1.WAMessageStubType[`COMMUNITY_${child.tag.toUpperCase()}_PARENT_GROUP`],
337
+ sibling_group: Types_1.WAMessageStubType[`COMMUNITY_${child.tag.toUpperCase()}_SIBLING_GROUP`],
338
+ sub_group: Types_1.WAMessageStubType[`COMMUNITY_${child.tag.toUpperCase()}_SUB_GROUP`]
339
+ }
340
+ const groups = WABinary_1.getBinaryNodeChildren(child, 'group')
341
+ .map(g => g.attrs?.jid || g.attrs?.subject || '')
342
+ .filter(x => x)
343
+ msg.messageStubType = stubMap?.[type] || Types_1.WAMessageStubType[`COMMUNITY_${child.tag.toUpperCase()}_PARENT_GROUP`]
344
+ msg.messageStubParameters = [participantJid, child.tag, groups]
345
+ break
346
+ case 'linked_group_promote':
347
+ case 'linked_group_demote':
348
+ const stubtype = `COMMUNITY_PARTICIPANT_${child.tag.split('_')[2].toUpperCase()}`
349
+ const participantS = WABinary_1.getBinaryNodeChildren(child, 'participant').map(p => p.attrs.jid)
350
+ msg.messageStubType = Types_1.WAMessageStubType[stubtype]
351
+ msg.messageStubParameters = participantS
352
+ break
353
+ case 'created_sub_group_suggestion':
354
+ msg.messageStubType = Types_1.WAMessageStubType.SUGGESTED_SUBGROUP_ANNOUNCE
355
+ msg.messageStubParameters = [participantJid, 'add']
356
+ break
357
+ case 'revoked_sub_group_suggestions':
358
+ const res = WABinary_1.getBinaryNodeChildren(child, 'sub_group_suggestions')
359
+ const reason = res.attrs?.reason
360
+ if (reason === 'approved') msg.messageStubType = Types_1.WAMessageStubType.GROUP_CREATE
361
+ else msg.messageStubType = Types_1.WAMessageStubType.GENERIC_NOTIFICATION
362
+ msg.messageStubParameters = [participantJid, reason]
363
+ break
364
+ default:
365
+ logger.warn(child.tag, 'Unhandled group node')
366
+ break
367
+ }
368
+ }
369
+ const handleNewsletterNotification = (id, node) => {
370
+ const messages = WABinary_1.getBinaryNodeChild(node, 'messages')
371
+ const message = WABinary_1.getBinaryNodeChild(node, 'message')
372
+ const serverId = node.attrs.server_id
373
+ const reactionsList = WABinary_1.getBinaryNodeChild(node, 'reactions')
374
+ const viewsList = WABinary_1.getBinaryNodeChild(node, 'views_count')
375
+ if (reactionsList) {
376
+ const reactions = WABinary_1.getBinaryNodeChild(reactionsList, 'reaction')
377
+ if (reactions.length === 0) {
378
+ ev.emit('newsletter.reaction', {
379
+ id,
380
+ newsletter_server_id: serverId,
381
+ reaction: {
382
+ removed: true
383
+ }
384
+ })
385
+ }
386
+ reactions.forEach(item => {
387
+ ev.emit('newsletter.reaction', {
388
+ id,
389
+ newsletter_server_id: serverId,
390
+ reaction: {
391
+ code: item.attrs?.code,
392
+ count: +item.attrs.count
393
+ }
394
+ })
395
+ })
396
+ }
397
+ if (viewsList.length) {
398
+ viewsList.forEach(item => {
399
+ ev.emit('newsletter.view', {
400
+ id,
401
+ newsletter_server_id: serverId,
402
+ count: +item.attrs.count
403
+ })
404
+ })
405
+ }
406
+ }
407
+ const handleMexNewsletterNotification = (id, node) => {
408
+ const operation = node?.attrs?.op_name
409
+ const content = JSON.parse(node?.attrs?.content)
410
+ let contentPath
411
+ if (operation === Types_1.MexOperations.UPDATE) {
412
+ contentPath = content.data[Types_1.XWAPaths.METADATA_UPDATE]
413
+ ev.emit('newsletter-settings.update', {
414
+ id,
415
+ update: contentPath.thread_metadata.settings
416
+ })
417
+ } else {
418
+ let action
419
+ if (operation === Types_1.MexOperations.PROMOTE) {
420
+ action = 'promote'
421
+ contentPath.data[Types_1.XWAPaths.PROMOTE]
422
+ } else {
423
+ action = 'demote'
424
+ contentPath.data[Types_1.XWAPaths.DEMOTE]
425
+ }
426
+ ev.emit('newsletter-participants.update', {
427
+ id,
428
+ author: contentPath.actor.pn,
429
+ user: contentPath.user.pn,
430
+ new_role: contentPath.user_new_role,
431
+ action
432
+ })
433
+ }
434
+ }
435
+ const processNotification = async (node) => {
436
+ const result = {}
437
+ const [child] = WABinary_1.getAllBinaryNodeChildren(node)
438
+ const nodeType = node.attrs.type
439
+ const from = WABinary_1.jidNormalizedUser(node.attrs.from)
440
+ switch (nodeType) {
441
+ case 'privacy_token':
442
+ const tokenList = WABinary_1.getBinaryNodeChildren(child, 'token')
443
+ for (const { attrs, content } of tokenList) {
444
+ const jid = attrs.jid
445
+ ev.emit('chats.update', [
446
+ {
447
+ id: jid,
448
+ tcToken: content
449
+ }
450
+ ])
451
+ logger.debug({ jid }, 'got privacy token update')
452
+ }
453
+ break
454
+ case 'w:gp2':
455
+ handleGroupNotification(node.attrs.participant, child, result)
456
+ break
457
+ case 'newsletter':
458
+ handleNewsletterNotification(node.attrs.from, child)
459
+ break
460
+ case 'mex':
461
+ handleMexNewsletterNotification(node.attrs.from, child)
462
+ break
463
+ case 'mediaretry':
464
+ const event = Utils_1.decodeMediaRetryNode(node)
465
+ ev.emit('messages.media-update', [event])
466
+ break
467
+ case 'encrypt':
468
+ await handleEncryptNotification(node)
469
+ break
470
+ case 'devices':
471
+ const devices = WABinary_1.getBinaryNodeChildren(child, 'device')
472
+ if (WABinary_1.areJidsSameUser(child.attrs.jid, authState.creds.me.id)) {
473
+ const deviceJids = devices.map(d => d.attrs.jid)
474
+ logger.info({ deviceJids }, 'got my own devices')
475
+ }
476
+ break
477
+ case 'server_sync':
478
+ const update = WABinary_1.getBinaryNodeChild(node, 'collection')
479
+ if (update) {
480
+ const name = update.attrs.name
481
+ await resyncAppState([name], false)
482
+ }
483
+ break
484
+ case 'picture':
485
+ const setPicture = WABinary_1.getBinaryNodeChild(node, 'set')
486
+ const delPicture = WABinary_1.getBinaryNodeChild(node, 'delete')
487
+ ev.emit('contacts.update', [{
488
+ id: WABinary_1.jidNormalizedUser(node?.attrs?.from) || (setPicture || delPicture)?.attrs?.hash || '',
489
+ imgUrl: setPicture ? 'changed' : 'removed'
490
+ }])
491
+ if (WABinary_1.isJidGroup(from)) {
492
+ const node = setPicture || delPicture
493
+ result.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_ICON
494
+ if (setPicture) {
495
+ result.messageStubParameters = [setPicture.attrs.id]
496
+ }
497
+ result.participant = node?.attrs?.author
498
+ result.key = {
499
+ ...result.key || {},
500
+ participant: setPicture?.attrs?.author
501
+ }
502
+ }
503
+ break
504
+ case 'account_sync':
505
+ if (child.tag === 'disappearing_mode') {
506
+ const newDuration = +child.attrs.duration
507
+ const timestamp = +child.attrs.t
508
+ logger.info({ newDuration }, 'updated account disappearing mode')
509
+ ev.emit('creds.update', {
510
+ accountSettings: {
511
+ ...authState.creds.accountSettings,
512
+ defaultDisappearingMode: {
513
+ ephemeralExpiration: newDuration,
514
+ ephemeralSettingTimestamp: timestamp,
515
+ },
516
+ }
517
+ })
518
+ }
519
+ else if (child.tag === 'blocklist') {
520
+ const blocklists = WABinary_1.getBinaryNodeChildren(child, 'item')
521
+ for (const { attrs } of blocklists) {
522
+ const blocklist = [attrs.jid]
523
+ const type = (attrs.action === 'block') ? 'add' : 'remove'
524
+ ev.emit('blocklist.update', { blocklist, type })
525
+ }
526
+ }
527
+ break
528
+ case 'link_code_companion_reg':
529
+ const linkCodeCompanionReg = WABinary_1.getBinaryNodeChild(node, 'link_code_companion_reg')
530
+ const ref = toRequiredBuffer(WABinary_1.getBinaryNodeChildBuffer(linkCodeCompanionReg, 'link_code_pairing_ref'))
531
+ const primaryIdentityPublicKey = toRequiredBuffer(WABinary_1.getBinaryNodeChildBuffer(linkCodeCompanionReg, 'primary_identity_pub'))
532
+ const primaryEphemeralPublicKeyWrapped = toRequiredBuffer(WABinary_1.getBinaryNodeChildBuffer(linkCodeCompanionReg, 'link_code_pairing_wrapped_primary_ephemeral_pub'))
533
+ const codePairingPublicKey = await decipherLinkPublicKey(primaryEphemeralPublicKeyWrapped)
534
+ const companionSharedKey = Utils_1.Curve.sharedKey(authState.creds.pairingEphemeralKeyPair.private, codePairingPublicKey)
535
+ const random = crypto_1.randomBytes(32)
536
+ const linkCodeSalt = crypto_1.randomBytes(32)
537
+ const linkCodePairingExpanded = await Utils_1.hkdf(companionSharedKey, 32, {
538
+ salt: linkCodeSalt,
539
+ info: 'link_code_pairing_key_bundle_encryption_key'
540
+ })
541
+ const encryptPayload = Buffer.concat([Buffer.from(authState.creds.signedIdentityKey.public), primaryIdentityPublicKey, random])
542
+ const encryptIv = crypto_1.randomBytes(12)
543
+ const encrypted = Utils_1.aesEncryptGCM(encryptPayload, linkCodePairingExpanded, encryptIv, Buffer.alloc(0))
544
+ const encryptedPayload = Buffer.concat([linkCodeSalt, encryptIv, encrypted])
545
+ const identitySharedKey = Utils_1.Curve.sharedKey(authState.creds.signedIdentityKey.private, primaryIdentityPublicKey)
546
+ const identityPayload = Buffer.concat([companionSharedKey, identitySharedKey, random])
547
+ authState.creds.advSecretKey = (await Utils_1.hkdf(identityPayload, 32, { info: 'adv_secret' })).toString('base64')
548
+ await query({
549
+ tag: 'iq',
550
+ attrs: {
551
+ to: WABinary_1.S_WHATSAPP_NET,
552
+ type: 'set',
553
+ id: suki.generateMessageTag(),
554
+ xmlns: 'md'
555
+ },
556
+ content: [
557
+ {
558
+ tag: 'link_code_companion_reg',
559
+ attrs: {
560
+ jid: authState.creds.me.id,
561
+ stage: 'companion_finish',
562
+ },
563
+ content: [
564
+ {
565
+ tag: 'link_code_pairing_wrapped_key_bundle',
566
+ attrs: {},
567
+ content: encryptedPayload
568
+ },
569
+ {
570
+ tag: 'companion_identity_public',
571
+ attrs: {},
572
+ content: authState.creds.signedIdentityKey.public
573
+ },
574
+ {
575
+ tag: 'link_code_pairing_ref',
576
+ attrs: {},
577
+ content: ref
578
+ }
579
+ ]
580
+ }
581
+ ]
582
+ })
583
+ authState.creds.registered = true
584
+ ev.emit('creds.update', authState.creds)
585
+ }
586
+ if (Object.keys(result).length) {
587
+ return result
588
+ }
589
+ }
590
+ async function decipherLinkPublicKey(data) {
591
+ const buffer = toRequiredBuffer(data)
592
+ const salt = buffer.slice(0, 32)
593
+ const secretKey = await Utils_1.derivePairingCodeKey(authState.creds.pairingCode, salt)
594
+ const iv = buffer.slice(32, 48)
595
+ const payload = buffer.slice(48, 80)
596
+ return Utils_1.aesDecryptCTR(payload, secretKey, iv)
597
+ }
598
+ function toRequiredBuffer(data) {
599
+ if (data === undefined) {
600
+ throw new boom_1.Boom('Invalid buffer', { statusCode: 400 })
601
+ }
602
+ return data instanceof Buffer ? data : Buffer.from(data)
603
+ }
604
+ const willSendMessageAgain = (id, participant) => {
605
+ const key = `${id}:${participant}`
606
+ const retryCount = msgRetryCache.get(key) || 0
607
+ return retryCount < maxMsgRetryCount
608
+ }
609
+ const updateSendMessageAgainCount = (id, participant) => {
610
+ const key = `${id}:${participant}`
611
+ const newValue = (msgRetryCache.get(key) || 0) + 1
612
+ msgRetryCache.set(key, newValue)
613
+ }
614
+ const sendMessagesAgain = async (key, ids, retryNode) => {
615
+ const msgs = await Promise.all(ids.map(id => getMessage({ ...key, id })))
616
+ const remoteJid = key.remoteJid
617
+ const participant = key.participant || remoteJid
618
+ // if it's the primary jid sending the request
619
+ // just re-send the message to everyone
620
+ // prevents the first message decryption failure
621
+ const sendToAll = !WABinary_1.jidDecode(participant)?.device
622
+ await assertSessions([participant], true)
623
+ if (WABinary_1.isJidGroup(remoteJid)) {
624
+ await authState.keys.set({ 'sender-key-memory': { [remoteJid]: null } })
625
+ }
626
+ logger.debug({ participant, sendToAll }, 'forced new session for retry recp')
627
+ for (const [i, msg] of msgs.entries()) {
628
+ if (msg) {
629
+ updateSendMessageAgainCount(ids[i], participant)
630
+ const msgRelayOpts = { messageId: ids[i] }
631
+ if (sendToAll) {
632
+ msgRelayOpts.useUserDevicesCache = false
633
+ }
634
+ else {
635
+ msgRelayOpts.participant = {
636
+ jid: participant,
637
+ count: +retryNode.attrs.count
638
+ }
639
+ }
640
+ await relayMessage(key.remoteJid, msg, msgRelayOpts)
641
+ }
642
+ else {
643
+ logger.debug({ jid: key.remoteJid, id: ids[i] }, 'recv retry request, but message not available')
644
+ }
645
+ }
646
+ }
647
+ const handleReceipt = async (node) => {
648
+ const { attrs, content } = node
649
+ const isLid = attrs.from.includes('lid')
650
+ const isNodeFromMe = WABinary_1.areJidsSameUser(attrs.participant || attrs.from, isLid ? authState.creds.me?.lid : authState.creds.me?.id)
651
+ const remoteJid = !isNodeFromMe || WABinary_1.isJidGroup(attrs.from) ? attrs.from : attrs.recipient
652
+ const fromMe = !attrs.recipient || ((attrs.type === 'retry' || attrs.type === 'sender') && isNodeFromMe)
653
+ const key = {
654
+ remoteJid,
655
+ id: '',
656
+ fromMe,
657
+ participant: attrs.participant
658
+ }
659
+ if (shouldIgnoreJid(remoteJid) && remoteJid !== '@s.whatsapp.net') {
660
+ logger.debug({ remoteJid }, 'ignoring receipt from jid')
661
+ await sendMessageAck(node)
662
+ return
663
+ }
664
+ const ids = [attrs.id]
665
+ if (Array.isArray(content)) {
666
+ const items = WABinary_1.getBinaryNodeChildren(content[0], 'item')
667
+ ids.push(...items.map(i => i.attrs.id))
668
+ }
669
+ try {
670
+ await Promise.all([
671
+ processingMutex.mutex(async () => {
672
+ const status = Utils_1.getStatusFromReceiptType(attrs.type)
673
+ if (typeof status !== 'undefined' && (
674
+ // basically, we only want to know when a message from us has been delivered to/read by the other person
675
+ // or another device of ours has read some messages
676
+ status >= WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK ||
677
+ !isNodeFromMe)) {
678
+ if (WABinary_1.isJidGroup(remoteJid) || WABinary_1.isJidStatusBroadcast(remoteJid)) {
679
+ if (attrs.participant) {
680
+ const updateKey = status === WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK ? 'receiptTimestamp' : 'readTimestamp'
681
+ ev.emit('message-receipt.update', ids.map(id => ({
682
+ key: { ...key, id },
683
+ receipt: {
684
+ userJid: WABinary_1.jidNormalizedUser(attrs.participant),
685
+ [updateKey]: +attrs.t
686
+ }
687
+ })))
688
+ }
689
+ }
690
+ else {
691
+ ev.emit('messages.update', ids.map(id => ({
692
+ key: { ...key, id },
693
+ update: { status }
694
+ })))
695
+ }
696
+ }
697
+ if (attrs.type === 'retry') {
698
+ // correctly set who is asking for the retry
699
+ key.participant = key.participant || attrs.from
700
+ const retryNode = WABinary_1.getBinaryNodeChild(node, 'retry')
701
+ if (willSendMessageAgain(ids[0], key.participant)) {
702
+ if (key.fromMe) {
703
+ try {
704
+ logger.debug({ attrs, key }, 'recv retry request')
705
+ await sendMessagesAgain(key, ids, retryNode)
706
+ }
707
+ catch (error) {
708
+ logger.error({ key, ids, trace: error.stack }, 'error in sending message again')
709
+ }
710
+ }
711
+ else {
712
+ logger.info({ attrs, key }, 'recv retry for not fromMe message')
713
+ }
714
+ }
715
+ else {
716
+ logger.info({ attrs, key }, 'will not send message again, as sent too many times')
717
+ }
718
+ }
719
+ })
720
+ ])
721
+ }
722
+ finally {
723
+ await sendMessageAck(node)
724
+ }
725
+ }
726
+ const handleNotification = async (node) => {
727
+ const remoteJid = node.attrs.from
728
+ if (shouldIgnoreJid(remoteJid) && remoteJid !== '@s.whatsapp.net') {
729
+ logger.debug({ remoteJid, id: node.attrs.id }, 'ignored notification')
730
+ await sendMessageAck(node)
731
+ return
732
+ }
733
+ try {
734
+ await Promise.all([
735
+ processingMutex.mutex(async () => {
736
+ const msg = await processNotification(node)
737
+ if (msg) {
738
+ const fromMe = WABinary_1.areJidsSameUser(node.attrs.participant || remoteJid, authState.creds.me.id)
739
+ msg.key = {
740
+ remoteJid,
741
+ fromMe,
742
+ participant: node.attrs.participant,
743
+ id: node.attrs.id,
744
+ ...(msg.key || {})
745
+ }
746
+ msg.participant = msg.participant ? msg.participant : node.attrs.participant
747
+ msg.messageTimestamp = +node.attrs.t
748
+ const fullMsg = WAProto_1.proto.WebMessageInfo.fromObject(msg)
749
+ await upsertMessage(fullMsg, 'append')
750
+ }
751
+ })
752
+ ])
753
+ }
754
+ finally {
755
+ await sendMessageAck(node)
756
+ }
757
+ }
758
+ const handleMessage = async (node) => {
759
+ try {
760
+ if (shouldIgnoreJid(node.attrs.from) && node.attrs.from !== '@s.whatsapp.net') {
761
+ logger.debug({ key: node.attrs.key }, 'ignored message')
762
+ await sendMessageAck(node)
763
+ return
764
+ }
765
+ let response
766
+ if (WABinary_1.getBinaryNodeChild(node, 'unavailable') && !WABinary_1.getBinaryNodeChild(node, 'enc')) {
767
+ await sendMessageAck(node)
768
+ const { key } = Utils_1.decodeMessageNode(node, authState.creds.me.id, authState.creds.me.lid || '').fullMessage
769
+ response = await requestPlaceholderResend(key)
770
+ if (response === 'RESOLVED') {
771
+ return
772
+ }
773
+ logger.debug('received unavailable message, acked and requested resend from phone')
774
+ }
775
+ else {
776
+ if (placeholderResendCache.get(node.attrs.id)) {
777
+ placeholderResendCache.del(node.attrs.id)
778
+ }
779
+ }
780
+ const { fullMessage: msg, category, author, decrypt } = Utils_1.decryptMessageNode(node, authState.creds.me.id, authState.creds.me.lid || '', signalRepository, logger)
781
+ if (response && msg?.messageStubParameters?.[0] === Utils_1.NO_MESSAGE_FOUND_ERROR_TEXT) {
782
+ msg.messageStubParameters = [Utils_1.NO_MESSAGE_FOUND_ERROR_TEXT, response]
783
+ }
784
+ if (msg.message?.protocolMessage?.type === WAProto_1.proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER && node.attrs.sender_pn) {
785
+ ev.emit('chats.phoneNumberShare', { lid: node.attrs.from, jid: node.attrs.sender_pn })
786
+ }
787
+ await Promise.all([
788
+ processingMutex.mutex(async () => {
789
+ await decrypt()
790
+ if (msg.messageStubType === WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT) {
791
+ if (msg?.messageStubParameters?.[0] === Utils_1.MISSING_KEYS_ERROR_TEXT) {
792
+ return sendMessageAck(node, Utils_1.NACK_REASONS.ParsingError)
793
+ }
794
+ retryMutex.mutex(async () => {
795
+ if (ws.isOpen) {
796
+ if (WABinary_1.getBinaryNodeChild(node, 'unavailable')) {
797
+ return
798
+ }
799
+ const encNode = WABinary_1.getBinaryNodeChild(node, 'enc')
800
+ await sendRetryRequest(node, !encNode)
801
+ if (retryRequestDelayMs) {
802
+ await Utils_1.delay(retryRequestDelayMs)
803
+ }
804
+ }
805
+ else {
806
+ logger.debug({ node }, 'connection closed, ignoring retry req')
807
+ }
808
+ })
809
+ }
810
+ else {
811
+ let type = undefined
812
+ let participant = msg.key.participant
813
+ if (category === 'peer') {
814
+ type = 'peer_msg'
815
+ }
816
+ else if (msg.key.fromMe) {
817
+ type = 'sender'
818
+ if (WABinary_1.isJidUser(msg.key.remoteJid)) {
819
+ participant = author
820
+ }
821
+ }
822
+ else if (!sendActiveReceipts) {
823
+ type = 'inactive'
824
+ }
825
+ await sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type)
826
+ const isAnyHistoryMsg = Utils_1.getHistoryMsg(msg.message)
827
+ if (isAnyHistoryMsg) {
828
+ const jid = WABinary_1.jidNormalizedUser(msg.key.remoteJid)
829
+ await sendReceipt(jid, undefined, [msg.key.id], 'hist_sync')
830
+ }
831
+ }
832
+ if (node?.attrs?.addressing_mode === 'lid' && node?.attrs?.participant_pn) {
833
+ msg.key.participant = WABinary_1.jidNormalizedUser(node.attrs.participant_pn)
834
+ }
835
+ Utils_1.cleanMessage(msg, authState.creds.me.id)
836
+ await sendMessageAck(node)
837
+ await upsertMessage(msg, node.attrs.offline ? 'append' : 'notify')
838
+ })
839
+ ])
840
+ }
841
+ catch (error) {
842
+ logger.error({ error, node: JSON.stringify(node) }, 'CRITICAL: error in handling message')
843
+ if (node.attrs.id && node.attrs.from) {
844
+ await sendMessageAck(node, 500)
845
+ }
846
+ }
847
+ }
848
+ const fetchMessageHistory = async (count, oldestMsgKey, oldestMsgTimestamp) => {
849
+ if (!authState.creds.me?.id) {
850
+ throw new boom_1.Boom('Not authenticated')
851
+ }
852
+ const pdoMessage = {
853
+ historySyncOnDemandRequest: {
854
+ chatJid: oldestMsgKey.remoteJid,
855
+ oldestMsgFromMe: oldestMsgKey.fromMe,
856
+ oldestMsgId: oldestMsgKey.id,
857
+ oldestMsgTimestampMs: oldestMsgTimestamp,
858
+ onDemandMsgCount: count
859
+ },
860
+ peerDataOperationRequestType: WAProto_1.proto.Message.PeerDataOperationRequestType.HISTORY_SYNC_ON_DEMAND
861
+ }
862
+ return sendPeerDataOperationMessage(pdoMessage)
863
+ }
864
+ const requestPlaceholderResend = async (messageKey) => {
865
+ if (!authState.creds.me?.id) {
866
+ throw new boom_1.Boom('Not authenticated')
867
+ }
868
+ if (placeholderResendCache.get(messageKey?.id)) {
869
+ logger.debug({ messageKey }, 'already requested resend')
870
+ return
871
+ }
872
+ else {
873
+ placeholderResendCache.set(messageKey?.id, true)
874
+ }
875
+ await Utils_1.delay(5000)
876
+ if (!placeholderResendCache.get(messageKey?.id)) {
877
+ logger.debug({ messageKey }, 'message received while resend requested')
878
+ return 'RESOLVED'
879
+ }
880
+ const pdoMessage = {
881
+ placeholderMessageResendRequest: [{
882
+ messageKey
883
+ }],
884
+ peerDataOperationRequestType: WAProto_1.proto.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND
885
+ }
886
+ setTimeout(() => {
887
+ if (placeholderResendCache.get(messageKey?.id)) {
888
+ logger.debug({ messageKey }, 'PDO message without response after 15 seconds. Phone possibly offline')
889
+ placeholderResendCache.del(messageKey?.id)
890
+ }
891
+ }, 15000)
892
+ return sendPeerDataOperationMessage(pdoMessage)
893
+ }
894
+ const handleCall = async (node) => {
895
+ const { attrs } = node
896
+ const [infoChild] = WABinary_1.getAllBinaryNodeChildren(node)
897
+ const callId = infoChild.attrs['call-id']
898
+ const from = infoChild.attrs.from || infoChild.attrs['call-creator']
899
+ const status = Utils_1.getCallStatusFromNode(infoChild)
900
+ const call = {
901
+ chatId: attrs.from,
902
+ from,
903
+ id: callId,
904
+ date: new Date(+attrs.t * 1000),
905
+ offline: !!attrs.offline,
906
+ status,
907
+ }
908
+ if (status === 'offer') {
909
+ call.isVideo = !!WABinary_1.getBinaryNodeChild(infoChild, 'video')
910
+ call.isGroup = infoChild.attrs.type === 'group' || !!infoChild.attrs['group-jid']
911
+ call.groupJid = infoChild.attrs['group-jid']
912
+ callOfferCache.set(call.id, call)
913
+ }
914
+ const existingCall = callOfferCache.get(call.id)
915
+ // use existing call info to populate this event
916
+ if (existingCall) {
917
+ call.isVideo = existingCall.isVideo
918
+ call.isGroup = existingCall.isGroup
919
+ }
920
+ // delete data once call has ended
921
+ if (status === 'reject' || status === 'accept' || status === 'timeout' || status === 'terminate') {
922
+ callOfferCache.del(call.id)
923
+ }
924
+ ev.emit('call', [call])
925
+ await sendMessageAck(node)
926
+ }
927
+ const handleBadAck = async ({ attrs }) => {
928
+ const key = { remoteJid: attrs.from, fromMe: true, id: attrs.id, newsletter_server_id: attrs?.server_id }
929
+ // WARNING: REFRAIN FROM ENABLING THIS FOR NOW. IT WILL CAUSE A LOOP
930
+ // // current hypothesis is that if pash is sent in the ack
931
+ // // it means -- the message hasn't reached all devices yet
932
+ // // we'll retry sending the message here
933
+ // if(attrs.phash) {
934
+ // logger.info({ attrs }, 'received phash in ack, resending message...')
935
+ // const msg = await getMessage(key)
936
+ // if(msg) {
937
+ // await relayMessage(key.remoteJid!, msg, { messageId: key.id!, useUserDevicesCache: false })
938
+ // } else {
939
+ // logger.warn({ attrs }, 'could not send message again, as it was not found')
940
+ // }
941
+ // }
942
+ // error in acknowledgement,
943
+ // device could not display the message
944
+ if (attrs.error) {
945
+ logger.warn({ attrs }, 'received error in ack')
946
+ ev.emit('messages.update', [
947
+ {
948
+ key,
949
+ update: {
950
+ status: Types_1.WAMessageStatus.ERROR,
951
+ messageStubParameters: [
952
+ attrs.error
953
+ ]
954
+ }
955
+ }
956
+ ])
957
+ }
958
+ }
959
+ /// processes a node with the given function
960
+ /// and adds the task to the existing buffer if we're buffering events
961
+ const processNodeWithBuffer = async (node, identifier, exec) => {
962
+ ev.buffer()
963
+ await execTask()
964
+ ev.flush()
965
+ function execTask() {
966
+ return exec(node, false)
967
+ .catch(err => onUnexpectedError(err, identifier))
968
+ }
969
+ }
970
+ const makeOfflineNodeProcessor = () => {
971
+ const nodeProcessorMap = new Map([
972
+ ['message', handleMessage],
973
+ ['call', handleCall],
974
+ ['receipt', handleReceipt],
975
+ ['notification', handleNotification]
976
+ ])
977
+ const nodes = []
978
+ let isProcessing = false
979
+ const enqueue = (type, node) => {
980
+ nodes.push({ type, node })
981
+ if (isProcessing) {
982
+ return
983
+ }
984
+ isProcessing = true
985
+ const promise = async () => {
986
+ while (nodes.length && ws.isOpen) {
987
+ const { type, node } = nodes.shift()
988
+ const nodeProcessor = nodeProcessorMap.get(type)
989
+ if (!nodeProcessor) {
990
+ onUnexpectedError(new Error(`unknown offline node type: ${type}`), 'processing offline node')
991
+ continue
992
+ }
993
+ await nodeProcessor(node)
994
+ }
995
+ isProcessing = false
996
+ }
997
+ promise().catch(error => onUnexpectedError(error, 'processing offline nodes'))
998
+ }
999
+ return { enqueue }
1000
+ }
1001
+ const offlineNodeProcessor = makeOfflineNodeProcessor()
1002
+ const processNode = (type, node, identifier, exec) => {
1003
+ const isOffline = !!node.attrs.offline
1004
+ if (isOffline) {
1005
+ offlineNodeProcessor.enqueue(type, node)
1006
+ }
1007
+ else {
1008
+ processNodeWithBuffer(node, identifier, exec)
1009
+ }
1010
+ }
1011
+ // recv a message
1012
+ ws.on('CB:message', (node) => {
1013
+ processNode('message', node, 'processing message', handleMessage)
1014
+ })
1015
+ ws.on('CB:call', async (node) => {
1016
+ processNode('call', node, 'handling call', handleCall)
1017
+ })
1018
+ ws.on('CB:receipt', node => {
1019
+ processNode('receipt', node, 'handling receipt', handleReceipt)
1020
+ })
1021
+ ws.on('CB:notification', async (node) => {
1022
+ processNode('notification', node, 'handling notification', handleNotification)
1023
+ })
1024
+ ws.on('CB:ack,class:message', (node) => {
1025
+ handleBadAck(node)
1026
+ .catch(error => onUnexpectedError(error, 'handling bad ack'))
1027
+ })
1028
+ ev.on('call', ([call]) => {
1029
+ // missed call + group call notification message generation
1030
+ if (call.status === 'timeout' || (call.status === 'offer' && call.isGroup)) {
1031
+ const msg = {
1032
+ key: {
1033
+ remoteJid: call.chatId,
1034
+ id: call.id,
1035
+ fromMe: false
1036
+ },
1037
+ messageTimestamp: Utils_1.unixTimestampSeconds(call.date),
1038
+ }
1039
+ if (call.status === 'timeout') {
1040
+ if (call.isGroup) {
1041
+ msg.messageStubType = call.isVideo ? Types_1.WAMessageStubType.CALL_MISSED_GROUP_VIDEO : Types_1.WAMessageStubType.CALL_MISSED_GROUP_VOICE
1042
+ }
1043
+ else {
1044
+ msg.messageStubType = call.isVideo ? Types_1.WAMessageStubType.CALL_MISSED_VIDEO : Types_1.WAMessageStubType.CALL_MISSED_VOICE
1045
+ }
1046
+ }
1047
+ else {
1048
+ msg.message = { call: { callKey: Buffer.from(call.id) } }
1049
+ }
1050
+ const protoMsg = WAProto_1.proto.WebMessageInfo.fromObject(msg)
1051
+ upsertMessage(protoMsg, call.offline ? 'append' : 'notify')
1052
+ }
1053
+ })
1054
+ ev.on('connection.update', ({ isOnline }) => {
1055
+ if (typeof isOnline !== 'undefined') {
1056
+ sendActiveReceipts = isOnline
1057
+ logger.trace(`sendActiveReceipts set to "${sendActiveReceipts}"`)
1058
+ }
1059
+ })
1060
+ return {
1061
+ ...suki,
1062
+ sendMessageAck,
1063
+ sendRetryRequest,
1064
+ offerCall,
1065
+ rejectCall,
1066
+ fetchMessageHistory,
1067
+ requestPlaceholderResend,
1068
+ }
1069
+ }
1070
+ module.exports = {
1071
+ makeMessagesRecvSocket
1072
+ }