@neelegirl/baileys 1.5.5 → 1.5.7

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 (203) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +183 -10
  3. package/WAProto/WAProto.proto +5007 -0
  4. package/WAProto/index.d.ts +57712 -0
  5. package/WAProto/index.js +178969 -0
  6. package/lib/Defaults/baileys-version.json +3 -0
  7. package/lib/Defaults/index.d.ts +68 -0
  8. package/lib/Defaults/index.js +137 -0
  9. package/lib/Defaults/phonenumber-mcc.json +223 -0
  10. package/lib/Signal/WASignalGroup/GroupProtocol.js +1909 -0
  11. package/lib/Signal/WASignalGroup/ciphertext_message.js +16 -0
  12. package/lib/Signal/WASignalGroup/generate-proto.sh +1 -0
  13. package/lib/Signal/WASignalGroup/group.proto +42 -0
  14. package/lib/Signal/WASignalGroup/group_cipher.js +120 -0
  15. package/lib/Signal/WASignalGroup/group_session_builder.js +46 -0
  16. package/lib/Signal/WASignalGroup/index.js +6 -0
  17. package/lib/Signal/WASignalGroup/keyhelper.js +21 -0
  18. package/lib/Signal/WASignalGroup/protobufs.js +3 -0
  19. package/lib/Signal/WASignalGroup/queue_job.js +69 -0
  20. package/lib/Signal/WASignalGroup/readme.md +6 -0
  21. package/lib/Signal/WASignalGroup/sender_chain_key.js +50 -0
  22. package/lib/Signal/WASignalGroup/sender_key_distribution_message.js +78 -0
  23. package/lib/Signal/WASignalGroup/sender_key_message.js +92 -0
  24. package/lib/Signal/WASignalGroup/sender_key_name.js +70 -0
  25. package/lib/Signal/WASignalGroup/sender_key_record.js +56 -0
  26. package/lib/Signal/WASignalGroup/sender_key_state.js +129 -0
  27. package/lib/Signal/WASignalGroup/sender_message_key.js +39 -0
  28. package/lib/Signal/libsignal.d.ts +4 -0
  29. package/lib/Signal/libsignal.js +162 -0
  30. package/lib/Socket/Client/abstract-socket-client.d.ts +15 -0
  31. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  32. package/lib/Socket/Client/index.d.ts +2 -0
  33. package/lib/Socket/Client/index.js +22 -0
  34. package/lib/Socket/Client/mobile-socket-client.d.ts +12 -0
  35. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  36. package/lib/Socket/Client/types.d.ts +16 -0
  37. package/lib/Socket/Client/types.js +18 -0
  38. package/lib/Socket/Client/websocket.d.ts +13 -0
  39. package/lib/Socket/Client/websocket.js +62 -0
  40. package/lib/Socket/business.d.ts +187 -0
  41. package/lib/Socket/business.js +268 -0
  42. package/lib/Socket/chats.d.ts +98 -0
  43. package/lib/Socket/chats.js +1113 -0
  44. package/lib/Socket/communities.d.ts +223 -0
  45. package/lib/Socket/communities.js +433 -0
  46. package/lib/Socket/groups.d.ts +131 -0
  47. package/lib/Socket/groups.js +352 -0
  48. package/lib/Socket/index.d.ts +191 -0
  49. package/lib/Socket/index.js +23 -0
  50. package/lib/Socket/messages-recv.d.ts +177 -0
  51. package/lib/Socket/messages-recv.js +1764 -0
  52. package/lib/Socket/messages-send.d.ts +168 -0
  53. package/lib/Socket/messages-send.js +1303 -0
  54. package/lib/Socket/mex.d.ts +2 -0
  55. package/lib/Socket/mex.js +47 -0
  56. package/lib/Socket/newsletter.d.ts +147 -0
  57. package/lib/Socket/newsletter.js +286 -0
  58. package/lib/Socket/registration.d.ts +266 -0
  59. package/lib/Socket/registration.js +166 -0
  60. package/lib/Socket/socket.d.ts +45 -0
  61. package/lib/Socket/socket.js +766 -0
  62. package/lib/Socket/usync.d.ts +37 -0
  63. package/lib/Socket/usync.js +83 -0
  64. package/lib/Store/index.d.ts +4 -0
  65. package/lib/Store/index.js +24 -0
  66. package/lib/Store/make-cache-manager-store.d.ts +14 -0
  67. package/lib/Store/make-cache-manager-store.js +90 -0
  68. package/lib/Store/make-in-memory-store.d.ts +123 -0
  69. package/lib/Store/make-in-memory-store.js +429 -0
  70. package/lib/Store/make-ordered-dictionary.d.ts +12 -0
  71. package/lib/Store/make-ordered-dictionary.js +86 -0
  72. package/lib/Store/object-repository.d.ts +10 -0
  73. package/lib/Store/object-repository.js +31 -0
  74. package/lib/Types/Auth.d.ts +120 -0
  75. package/lib/Types/Auth.js +3 -0
  76. package/lib/Types/Call.d.ts +14 -0
  77. package/lib/Types/Call.js +3 -0
  78. package/lib/Types/Chat.d.ts +138 -0
  79. package/lib/Types/Chat.js +9 -0
  80. package/lib/Types/Contact.d.ts +20 -0
  81. package/lib/Types/Contact.js +3 -0
  82. package/lib/Types/Events.d.ts +229 -0
  83. package/lib/Types/Events.js +3 -0
  84. package/lib/Types/GroupMetadata.d.ts +66 -0
  85. package/lib/Types/GroupMetadata.js +3 -0
  86. package/lib/Types/Label.d.ts +48 -0
  87. package/lib/Types/Label.js +31 -0
  88. package/lib/Types/LabelAssociation.d.ts +35 -0
  89. package/lib/Types/LabelAssociation.js +13 -0
  90. package/lib/Types/Message.d.ts +473 -0
  91. package/lib/Types/Message.js +13 -0
  92. package/lib/Types/MexUpdates.d.ts +9 -0
  93. package/lib/Types/MexUpdates.js +18 -0
  94. package/lib/Types/Newsletter.d.ts +109 -0
  95. package/lib/Types/Newsletter.js +40 -0
  96. package/lib/Types/Product.d.ts +92 -0
  97. package/lib/Types/Product.js +3 -0
  98. package/lib/Types/Signal.d.ts +68 -0
  99. package/lib/Types/Signal.js +3 -0
  100. package/lib/Types/Socket.d.ts +122 -0
  101. package/lib/Types/Socket.js +3 -0
  102. package/lib/Types/State.d.ts +41 -0
  103. package/lib/Types/State.js +14 -0
  104. package/lib/Types/USync.d.ts +26 -0
  105. package/lib/Types/USync.js +3 -0
  106. package/lib/Types/index.d.ts +79 -0
  107. package/lib/Types/index.js +48 -0
  108. package/lib/Utils/auth-utils.d.ts +21 -0
  109. package/lib/Utils/auth-utils.js +205 -0
  110. package/lib/Utils/baileys-event-stream.d.ts +18 -0
  111. package/lib/Utils/baileys-event-stream.js +70 -0
  112. package/lib/Utils/business.d.ts +29 -0
  113. package/lib/Utils/business.js +255 -0
  114. package/lib/Utils/chat-utils.d.ts +82 -0
  115. package/lib/Utils/chat-utils.js +781 -0
  116. package/lib/Utils/check-npm-version.d.ts +15 -0
  117. package/lib/Utils/check-npm-version.js +52 -0
  118. package/lib/Utils/crypto.d.ts +56 -0
  119. package/lib/Utils/crypto.js +179 -0
  120. package/lib/Utils/decode-wa-message.d.ts +41 -0
  121. package/lib/Utils/decode-wa-message.js +253 -0
  122. package/lib/Utils/event-buffer.d.ts +39 -0
  123. package/lib/Utils/event-buffer.js +565 -0
  124. package/lib/Utils/generics.d.ts +129 -0
  125. package/lib/Utils/generics.js +618 -0
  126. package/lib/Utils/history.d.ts +23 -0
  127. package/lib/Utils/history.js +110 -0
  128. package/lib/Utils/index.d.ts +19 -0
  129. package/lib/Utils/index.js +41 -0
  130. package/lib/Utils/link-preview.d.ts +23 -0
  131. package/lib/Utils/link-preview.js +120 -0
  132. package/lib/Utils/logger.d.ts +13 -0
  133. package/lib/Utils/logger.js +7 -0
  134. package/lib/Utils/lt-hash.d.ts +14 -0
  135. package/lib/Utils/lt-hash.js +58 -0
  136. package/lib/Utils/make-mutex.d.ts +9 -0
  137. package/lib/Utils/make-mutex.js +49 -0
  138. package/lib/Utils/message-retry-manager.d.ts +82 -0
  139. package/lib/Utils/message-retry-manager.js +177 -0
  140. package/lib/Utils/messages-media.d.ts +129 -0
  141. package/lib/Utils/messages-media.js +806 -0
  142. package/lib/Utils/messages.d.ts +103 -0
  143. package/lib/Utils/messages.js +1579 -0
  144. package/lib/Utils/noise-handler.d.ts +20 -0
  145. package/lib/Utils/noise-handler.js +155 -0
  146. package/lib/Utils/process-message.d.ts +49 -0
  147. package/lib/Utils/process-message.js +428 -0
  148. package/lib/Utils/signal.d.ts +42 -0
  149. package/lib/Utils/signal.js +166 -0
  150. package/lib/Utils/use-mongo-file-auth-state.d.ts +6 -0
  151. package/lib/Utils/use-mongo-file-auth-state.js +84 -0
  152. package/lib/Utils/use-multi-file-auth-state.d.ts +18 -0
  153. package/lib/Utils/use-multi-file-auth-state.js +238 -0
  154. package/lib/Utils/use-single-file-auth-state.d.ts +13 -0
  155. package/lib/Utils/use-single-file-auth-state.js +80 -0
  156. package/lib/Utils/validate-connection.d.ts +13 -0
  157. package/lib/Utils/validate-connection.js +187 -0
  158. package/lib/WABinary/constants.d.ts +30 -0
  159. package/lib/WABinary/constants.js +1316 -0
  160. package/lib/WABinary/decode.d.ts +9 -0
  161. package/lib/WABinary/decode.js +288 -0
  162. package/lib/WABinary/encode.d.ts +3 -0
  163. package/lib/WABinary/encode.js +265 -0
  164. package/lib/WABinary/generic-utils.d.ts +28 -0
  165. package/lib/WABinary/generic-utils.js +142 -0
  166. package/lib/WABinary/index.d.ts +5 -0
  167. package/lib/WABinary/index.js +25 -0
  168. package/lib/WABinary/jid-utils.d.ts +53 -0
  169. package/lib/WABinary/jid-utils.js +92 -0
  170. package/lib/WABinary/types.d.ts +22 -0
  171. package/lib/WABinary/types.js +3 -0
  172. package/lib/WAM/BinaryInfo.d.ts +16 -0
  173. package/lib/WAM/BinaryInfo.js +17 -0
  174. package/lib/WAM/constants.d.ts +47 -0
  175. package/lib/WAM/constants.js +15371 -0
  176. package/lib/WAM/encode.d.ts +3 -0
  177. package/lib/WAM/encode.js +165 -0
  178. package/lib/WAM/index.d.ts +3 -0
  179. package/lib/WAM/index.js +23 -0
  180. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.d.ts +28 -0
  181. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +69 -0
  182. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  183. package/lib/WAUSync/Protocols/USyncContactProtocol.js +36 -0
  184. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +26 -0
  185. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +62 -0
  186. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +14 -0
  187. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +35 -0
  188. package/lib/WAUSync/Protocols/USyncLIDProtocol.d.ts +9 -0
  189. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +30 -0
  190. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +14 -0
  191. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +46 -0
  192. package/lib/WAUSync/Protocols/index.d.ts +6 -0
  193. package/lib/WAUSync/Protocols/index.js +26 -0
  194. package/lib/WAUSync/USyncQuery.d.ts +31 -0
  195. package/lib/WAUSync/USyncQuery.js +92 -0
  196. package/lib/WAUSync/USyncUser.d.ts +12 -0
  197. package/lib/WAUSync/USyncUser.js +30 -0
  198. package/lib/WAUSync/index.d.ts +3 -0
  199. package/lib/WAUSync/index.js +23 -0
  200. package/lib/index.d.ts +13 -0
  201. package/lib/index.js +33 -0
  202. package/package.json +88 -10
  203. package/index.js +0 -38
@@ -0,0 +1,20 @@
1
+ import { proto } from '../../WAProto'
2
+ import { KeyPair } from '../Types'
3
+ import { BinaryNode } from '../WABinary'
4
+ import { ILogger } from './logger'
5
+
6
+ export declare const makeNoiseHandler: ({ keyPair: { private: privateKey, public: publicKey }, NOISE_HEADER, logger, routingInfo }: {
7
+ keyPair: KeyPair
8
+ NOISE_HEADER: Uint8Array
9
+ logger: ILogger
10
+ routingInfo?: Buffer | undefined
11
+ }) => {
12
+ encrypt: (plaintext: Uint8Array) => Buffer
13
+ decrypt: (ciphertext: Uint8Array) => Buffer
14
+ authenticate: (data: Uint8Array) => void
15
+ mixIntoKey: (data: Uint8Array) => Promise<void>
16
+ finishInit: () => Promise<void>
17
+ processHandshake: ({ serverHello }: proto.HandshakeMessage, noiseKey: KeyPair) => Promise<Buffer>
18
+ encodeFrame: (data: Buffer | Uint8Array) => Buffer
19
+ decodeFrame: (newData: Buffer | Uint8Array, onFrame: (buff: Uint8Array | BinaryNode) => void) => Promise<void>
20
+ }
@@ -0,0 +1,155 @@
1
+ "use strict"
2
+
3
+ Object.defineProperty(exports, "__esModule", { value: true })
4
+
5
+ const boom_1 = require("@hapi/boom")
6
+ const WAProto_1 = require("../../WAProto")
7
+ const Defaults_1 = require("../Defaults")
8
+ const WABinary_1 = require("../WABinary")
9
+ const crypto_1 = require("./crypto")
10
+
11
+ const generateIV = (counter) => {
12
+ const iv = new ArrayBuffer(12)
13
+ new DataView(iv).setUint32(8, counter)
14
+ return new Uint8Array(iv)
15
+ }
16
+
17
+ const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publicKey }, NOISE_HEADER, logger, routingInfo }) => {
18
+ logger = logger.child({ class: 'ns' })
19
+ const authenticate = (data) => {
20
+ if (!isFinished) {
21
+ hash = crypto_1.sha256(Buffer.concat([hash, data]))
22
+ }
23
+ }
24
+ const encrypt = (plaintext) => {
25
+ const result = crypto_1.aesEncryptGCM(plaintext, encKey, generateIV(writeCounter), hash)
26
+ writeCounter += 1
27
+ authenticate(result)
28
+ return result
29
+ }
30
+ const decrypt = (ciphertext) => {
31
+ // before the handshake is finished, we use the same counter
32
+ // after handshake, the counters are different
33
+ const iv = generateIV(isFinished ? readCounter : writeCounter)
34
+ const result = crypto_1.aesDecryptGCM(ciphertext, decKey, iv, hash)
35
+ if (isFinished) {
36
+ readCounter += 1
37
+ }
38
+ else {
39
+ writeCounter += 1
40
+ }
41
+ authenticate(ciphertext)
42
+ return result
43
+ }
44
+ const localHKDF = async (data) => {
45
+ const key = await crypto_1.hkdf(Buffer.from(data), 64, { salt, info: '' })
46
+ return [key.slice(0, 32), key.slice(32)]
47
+ }
48
+ const mixIntoKey = async (data) => {
49
+ const [write, read] = await localHKDF(data)
50
+ salt = write
51
+ encKey = read
52
+ decKey = read
53
+ readCounter = 0
54
+ writeCounter = 0
55
+ }
56
+ const finishInit = async () => {
57
+ const [write, read] = await localHKDF(new Uint8Array(0))
58
+ encKey = write
59
+ decKey = read
60
+ hash = Buffer.from([])
61
+ readCounter = 0
62
+ writeCounter = 0
63
+ isFinished = true
64
+ }
65
+ const data = Buffer.from(Defaults_1.NOISE_MODE)
66
+ let hash = data.byteLength === 32 ? data : crypto_1.sha256(data)
67
+ let salt = hash
68
+ let encKey = hash
69
+ let decKey = hash
70
+ let readCounter = 0
71
+ let writeCounter = 0
72
+ let isFinished = false
73
+ let sentIntro = false
74
+ let inBytes = Buffer.alloc(0)
75
+ authenticate(NOISE_HEADER)
76
+ authenticate(publicKey)
77
+ return {
78
+ encrypt,
79
+ decrypt,
80
+ authenticate,
81
+ mixIntoKey,
82
+ finishInit,
83
+ processHandshake: async ({ serverHello }, noiseKey) => {
84
+ authenticate(serverHello.ephemeral)
85
+ await mixIntoKey(crypto_1.Curve.sharedKey(privateKey, serverHello.ephemeral))
86
+ const decStaticContent = decrypt(serverHello.static)
87
+ await mixIntoKey(crypto_1.Curve.sharedKey(privateKey, decStaticContent))
88
+ const certDecoded = decrypt(serverHello.payload)
89
+ const { intermediate: certIntermediate } = WAProto_1.proto.CertChain.decode(certDecoded)
90
+ const { issuerSerial } = WAProto_1.proto.CertChain.NoiseCertificate.Details.decode(certIntermediate.details)
91
+ if (issuerSerial !== Defaults_1.WA_CERT_DETAILS.SERIAL) {
92
+ throw new boom_1.Boom('certification match failed', { statusCode: 400 })
93
+ }
94
+ const keyEnc = encrypt(noiseKey.public)
95
+ await mixIntoKey(crypto_1.Curve.sharedKey(noiseKey.private, serverHello.ephemeral))
96
+ return keyEnc
97
+ },
98
+ encodeFrame: (data) => {
99
+ if (isFinished) {
100
+ data = encrypt(data)
101
+ }
102
+ let header
103
+ if (routingInfo) {
104
+ header = Buffer.alloc(7)
105
+ header.write('ED', 0, 'utf8')
106
+ header.writeUint8(0, 2)
107
+ header.writeUint8(1, 3)
108
+ header.writeUint8(routingInfo.byteLength >> 16, 4)
109
+ header.writeUint16BE(routingInfo.byteLength & 65535, 5)
110
+ header = Buffer.concat([header, routingInfo, NOISE_HEADER])
111
+ }
112
+ else {
113
+ header = Buffer.from(NOISE_HEADER)
114
+ }
115
+ const introSize = sentIntro ? 0 : header.length
116
+ const frame = Buffer.alloc(introSize + 3 + data.byteLength)
117
+ if (!sentIntro) {
118
+ frame.set(header)
119
+ sentIntro = true
120
+ }
121
+ frame.writeUInt8(data.byteLength >> 16, introSize)
122
+ frame.writeUInt16BE(65535 & data.byteLength, introSize + 1)
123
+ frame.set(data, introSize + 3)
124
+ return frame
125
+ },
126
+ decodeFrame: async (newData, onFrame) => {
127
+ // the binary protocol uses its own framing mechanism
128
+ // on top of the WS frames
129
+ // so we get this data and separate out the frames
130
+ const getBytesSize = () => {
131
+ if (inBytes.length >= 3) {
132
+ return (inBytes.readUInt8() << 16) | inBytes.readUInt16BE(1)
133
+ }
134
+ }
135
+ inBytes = Buffer.concat([inBytes, newData])
136
+ logger.trace(`recv ${newData.length} bytes, total recv ${inBytes.length} bytes`)
137
+ let size = getBytesSize()
138
+ while (size && inBytes.length >= size + 3) {
139
+ let frame = inBytes.slice(3, size + 3)
140
+ inBytes = inBytes.slice(size + 3)
141
+ if (isFinished) {
142
+ const result = decrypt(frame)
143
+ frame = await WABinary_1.decodeBinaryNode(result)
144
+ }
145
+ logger.trace({ msg: frame?.attrs?.id }, 'recv frame')
146
+ onFrame(frame)
147
+ size = getBytesSize()
148
+ }
149
+ }
150
+ }
151
+ }
152
+
153
+ module.exports = {
154
+ makeNoiseHandler
155
+ }
@@ -0,0 +1,49 @@
1
+ import { AxiosRequestConfig } from 'axios'
2
+ import { proto } from '../../WAProto'
3
+ import { AuthenticationCreds, BaileysEventEmitter, CacheStore, SignalKeyStoreWithTransaction, SocketConfig } from '../Types'
4
+ import { ILogger } from './logger'
5
+
6
+ type ProcessMessageContext = {
7
+ shouldProcessHistoryMsg: boolean
8
+ placeholderResendCache?: CacheStore
9
+ creds: AuthenticationCreds
10
+ keyStore: SignalKeyStoreWithTransaction
11
+ ev: BaileysEventEmitter
12
+ getMessage: SocketConfig['getMessage']
13
+ logger?: ILogger
14
+ options: AxiosRequestConfig<{}>
15
+ }
16
+
17
+ /** Cleans a received message to further processing */
18
+ export declare const cleanMessage: (message: proto.IWebMessageInfo, meId: string) => void
19
+
20
+ export declare const isRealMessage: (message: proto.IWebMessageInfo, meId: string) => boolean | undefined
21
+
22
+ export declare const shouldIncrementChatUnread: (message: proto.IWebMessageInfo) => boolean
23
+
24
+ /**
25
+ * Get the ID of the chat from the given key.
26
+ * Typically -- that'll be the remoteJid, but for broadcasts, it'll be the participant
27
+ */
28
+ export declare const getChatId: ({ remoteJid, participant, fromMe }: proto.IMessageKey) => string
29
+
30
+ type PollContext = {
31
+ /** normalised jid of the person that created the poll */
32
+ pollCreatorJid: string
33
+ /** ID of the poll creation message */
34
+ pollMsgId: string
35
+ /** poll creation message enc key */
36
+ pollEncKey: Uint8Array
37
+ /** jid of the person that voted */
38
+ voterJid: string
39
+ }
40
+
41
+ /**
42
+ * Decrypt a poll vote
43
+ * @param vote encrypted vote
44
+ * @param ctx additional info about the poll required for decryption
45
+ * @returns list of SHA256 options
46
+ */
47
+ export declare function decryptPollVote({ encPayload, encIv }: proto.Message.IPollEncValue, { pollCreatorJid, pollMsgId, pollEncKey, voterJid, }: PollContext): proto.Message.PollVoteMessage
48
+
49
+ export declare const processMessage: (message: proto.IWebMessageInfo, { shouldProcessHistoryMsg, placeholderResendCache, ev, creds, keyStore, logger, options, getMessage }: ProcessMessageContext) => Promise<void>
@@ -0,0 +1,428 @@
1
+ "use strict"
2
+
3
+ Object.defineProperty(exports, "__esModule", { value: true })
4
+
5
+ const WAProto_1 = require("../../WAProto")
6
+ const Types_1 = require("../Types")
7
+ const messages_1 = require("../Utils/messages")
8
+ const WABinary_1 = require("../WABinary")
9
+ const crypto_1 = require("./crypto")
10
+ const generics_1 = require("./generics")
11
+ const history_1 = require("./history")
12
+ const chats_1 = require("../Socket/chats")
13
+ const REAL_MSG_STUB_TYPES = new Set([
14
+ Types_1.WAMessageStubType.CALL_MISSED_GROUP_VIDEO,
15
+ Types_1.WAMessageStubType.CALL_MISSED_GROUP_VOICE,
16
+ Types_1.WAMessageStubType.CALL_MISSED_VIDEO,
17
+ Types_1.WAMessageStubType.CALL_MISSED_VOICE
18
+ ])
19
+
20
+ const REAL_MSG_REQ_ME_STUB_TYPES = new Set([
21
+ Types_1.WAMessageStubType.GROUP_PARTICIPANT_ADD
22
+ ])
23
+
24
+ /** Cleans a received message to further processing */
25
+ const cleanMessage = (message, meId) => {
26
+ // ensure remoteJid and participant doesn't have device or agent in it
27
+ message.key.remoteJid = WABinary_1.jidNormalizedUser(message.key.remoteJid)
28
+ message.key.participant = message.key.participant ? WABinary_1.jidNormalizedUser(message.key.participant) : undefined
29
+ const content = messages_1.normalizeMessageContent(message.message)
30
+ // if the message has a reaction, ensure fromMe & remoteJid are from our perspective
31
+ if (content?.reactionMessage) {
32
+ normaliseKey(content.reactionMessage.key)
33
+ }
34
+ if (content?.pollUpdateMessage) {
35
+ normaliseKey(content.pollUpdateMessage.pollCreationMessageKey)
36
+ }
37
+ function normaliseKey(msgKey) {
38
+ // if the reaction is from another user
39
+ // we've to correctly map the key to this user's perspective
40
+ if (!message.key.fromMe) {
41
+ // if the sender believed the message being reacted to is not from them
42
+ // we've to correct the key to be from them, or some other participant
43
+ msgKey.fromMe = !msgKey.fromMe
44
+ ? WABinary_1.areJidsSameUser(msgKey.participant || msgKey.remoteJid, meId)
45
+ // if the message being reacted to, was from them
46
+ // fromMe automatically becomes false
47
+ : false
48
+ // set the remoteJid to being the same as the chat the message came from
49
+ msgKey.remoteJid = message.key.remoteJid
50
+ // set participant of the message
51
+ msgKey.participant = msgKey.participant || message.key.participant
52
+ }
53
+ }
54
+ }
55
+
56
+ const isRealMessage = (message, meId) => {
57
+ const normalizedContent = messages_1.normalizeMessageContent(message.message)
58
+ const hasSomeContent = !!messages_1.getContentType(normalizedContent)
59
+ return (
60
+ !!normalizedContent ||
61
+ REAL_MSG_STUB_TYPES.has(message.messageStubType) ||
62
+ (
63
+ REAL_MSG_REQ_ME_STUB_TYPES.has(message.messageStubType) &&
64
+ message.messageStubParameters?.some(p => WABinary_1.areJidsSameUser(meId, p))
65
+ )
66
+ ) &&
67
+ hasSomeContent &&
68
+ !normalizedContent?.protocolMessage &&
69
+ !normalizedContent?.reactionMessage &&
70
+ !normalizedContent?.pollUpdateMessage
71
+ }
72
+
73
+ const shouldIncrementChatUnread = (message) => (!message.key.fromMe && !message.messageStubType)
74
+
75
+ /**
76
+ * Get the ID of the chat from the given key.
77
+ * Typically -- that'll be the remoteJid, but for broadcasts, it'll be the participant
78
+ */
79
+ const getChatId = ({ remoteJid, participant, fromMe }) => {
80
+ if (WABinary_1.isJidBroadcast(remoteJid)
81
+ && !WABinary_1.isJidStatusBroadcast(remoteJid)
82
+ && !fromMe) {
83
+ return participant
84
+ }
85
+ return remoteJid
86
+ }
87
+
88
+ /**
89
+ * Decrypt a poll vote
90
+ * @param vote encrypted vote
91
+ * @param ctx additional info about the poll required for decryption
92
+ * @returns list of SHA256 options
93
+ */
94
+ function decryptPollVote({ encPayload, encIv }, { pollCreatorJid, pollMsgId, pollEncKey, voterJid, }) {
95
+ const sign = Buffer.concat([
96
+ toBinary(pollMsgId),
97
+ toBinary(pollCreatorJid),
98
+ toBinary(voterJid),
99
+ toBinary('Poll Vote'),
100
+ new Uint8Array([1])
101
+ ])
102
+ const key0 = crypto_1.hmacSign(pollEncKey, new Uint8Array(32), 'sha256')
103
+ const decKey = crypto_1.hmacSign(sign, key0, 'sha256')
104
+ const aad = toBinary(`${pollMsgId}\u0000${voterJid}`)
105
+ const decrypted = crypto_1.aesDecryptGCM(encPayload, decKey, encIv, aad)
106
+ return WAProto_1.proto.Message.PollVoteMessage.decode(decrypted)
107
+ function toBinary(txt) {
108
+ return Buffer.from(txt)
109
+ }
110
+ }
111
+
112
+ const processMessage = async (message, { shouldProcessHistoryMsg, placeholderResendCache, ev, creds, keyStore, logger, options, getMessage }) => {
113
+ const meId = creds.me.id
114
+ const { accountSettings } = creds
115
+ const chat = { id: WABinary_1.jidNormalizedUser(getChatId(message.key)) }
116
+ const isRealMsg = isRealMessage(message, meId)
117
+ if (isRealMsg) {
118
+ chat.messages = [{ message }]
119
+ chat.conversationTimestamp = generics_1.toNumber(message.messageTimestamp)
120
+ // only increment unread count if not CIPHERTEXT and from another person
121
+ if (shouldIncrementChatUnread(message)) {
122
+ chat.unreadCount = (chat.unreadCount || 0) + 1
123
+ }
124
+ }
125
+ const content = messages_1.normalizeMessageContent(message.message)
126
+ // unarchive chat if it's a real message, or someone reacted to our message
127
+ // and we've the unarchive chats setting on
128
+ if (isRealMsg || content?.reactionMessage?.key?.fromMe
129
+ && accountSettings?.unarchiveChats) {
130
+ chat.archived = false
131
+ chat.readOnly = false
132
+ }
133
+ const protocolMsg = content?.protocolMessage
134
+ if (protocolMsg) {
135
+ switch (protocolMsg.type) {
136
+ case WAProto_1.proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION:
137
+ const histNotification = protocolMsg.historySyncNotification
138
+ const process = shouldProcessHistoryMsg
139
+ const isLatest = !creds.processedHistoryMessages?.length
140
+ logger?.info({
141
+ histNotification,
142
+ process,
143
+ id: message.key.id,
144
+ isLatest,
145
+ }, 'got history notification')
146
+ if (process) {
147
+ if (histNotification.syncType !== WAProto_1.proto.HistorySync.HistorySyncType.ON_DEMAND) {
148
+ ev.emit('creds.update', {
149
+ processedHistoryMessages: [
150
+ ...(creds.processedHistoryMessages || []),
151
+ { key: message.key, messageTimestamp: message.messageTimestamp }
152
+ ]
153
+ })
154
+ }
155
+ const data = await history_1.downloadAndProcessHistorySyncNotification(histNotification, options)
156
+ ev.emit('messaging-history.set', {
157
+ ...data,
158
+ isLatest: histNotification.syncType !== WAProto_1.proto.HistorySync.HistorySyncType.ON_DEMAND
159
+ ? isLatest
160
+ : undefined,
161
+ peerDataRequestSessionId: histNotification.peerDataRequestSessionId
162
+ })
163
+ }
164
+ break
165
+ case WAProto_1.proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE:
166
+ const keys = protocolMsg.appStateSyncKeyShare.keys
167
+ if (keys?.length) {
168
+ let newAppStateSyncKeyId = ''
169
+ await keyStore.transaction(async () => {
170
+ const newKeys = []
171
+ for (const { keyData, keyId } of keys) {
172
+ const strKeyId = Buffer.from(keyId.keyId).toString('base64')
173
+ newKeys.push(strKeyId)
174
+ await keyStore.set({ 'app-state-sync-key': { [strKeyId]: keyData } })
175
+ newAppStateSyncKeyId = strKeyId
176
+ }
177
+ logger?.info({ newAppStateSyncKeyId, newKeys }, 'injecting new app state sync keys')
178
+ })
179
+ ev.emit('creds.update', { myAppStateKeyId: newAppStateSyncKeyId })
180
+ }
181
+ else {
182
+ logger?.info({ protocolMsg }, 'recv app state sync with 0 keys')
183
+ }
184
+ break
185
+ case WAProto_1.proto.Message.ProtocolMessage.Type.REVOKE:
186
+ ev.emit('messages.update', [
187
+ {
188
+ key: {
189
+ ...message.key,
190
+ id: protocolMsg.key.id
191
+ },
192
+ update: { message: null, messageStubType: Types_1.WAMessageStubType.REVOKE, key: message.key }
193
+ }
194
+ ])
195
+ break
196
+ case WAProto_1.proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING:
197
+ Object.assign(chat, {
198
+ ephemeralSettingTimestamp: generics_1.toNumber(message.messageTimestamp),
199
+ ephemeralExpiration: protocolMsg.ephemeralExpiration || null
200
+ })
201
+ break
202
+ case WAProto_1.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE:
203
+ const response = protocolMsg.peerDataOperationRequestResponseMessage
204
+ if (response) {
205
+ placeholderResendCache?.del(response.stanzaId)
206
+ // TODO: IMPLEMENT HISTORY SYNC ETC (sticker uploads etc.).
207
+ const { peerDataOperationResult } = response
208
+ for (const result of peerDataOperationResult) {
209
+ const { placeholderMessageResendResponse: retryResponse } = result
210
+ //eslint-disable-next-line max-depth
211
+ if (retryResponse) {
212
+ const webMessageInfo = WAProto_1.proto.WebMessageInfo.decode(retryResponse.webMessageInfoBytes)
213
+ // wait till another upsert event is available, don't want it to be part of the PDO response message
214
+ setTimeout(() => {
215
+ ev.emit('messages.upsert', {
216
+ messages: [webMessageInfo],
217
+ type: 'notify',
218
+ requestId: response.stanzaId
219
+ })
220
+ }, 500)
221
+ }
222
+ }
223
+ }
224
+ break
225
+ case WAProto_1.proto.Message.ProtocolMessage.Type.MESSAGE_EDIT:
226
+ ev.emit('messages.update', [
227
+ {
228
+ // flip the sender / fromMe properties because they're in the perspective of the sender
229
+ key: { ...message.key, id: protocolMsg.key?.id },
230
+ update: {
231
+ message: {
232
+ editedMessage: {
233
+ message: protocolMsg.editedMessage
234
+ }
235
+ },
236
+ messageTimestamp: protocolMsg.timestampMs
237
+ ? Math.floor(generics_1.toNumber(protocolMsg.timestampMs) / 1000)
238
+ : message.messageTimestamp
239
+ }
240
+ }
241
+ ])
242
+ break
243
+ case WAProto_1.proto.Message.ProtocolMessage.Type.LIMIT_SHARING:
244
+ ev.emit('limit-sharing.update', {
245
+ id: protocolMsg.key.remoteJid,
246
+ author: WABinary_1.areJidsSameUser(message.key.remoteJid, protocolMsg.key.remoteJid) ? WABinary_1.jidNormalizedUser(meId) : message.key.remoteJid,
247
+ action: `${protocolMsg.limitSharing.sharingLimited ? 'on' : 'off'}`,
248
+ trigger: protocolMsg.limitSharing.trigger,
249
+ update_time: protocolMsg.limitSharing.limitSharingSettingTimestamp
250
+ })
251
+ break
252
+ }
253
+ }
254
+ else if (content?.reactionMessage) {
255
+ const reaction = {
256
+ ...content.reactionMessage,
257
+ key: message.key,
258
+ }
259
+ ev.emit('messages.reaction', [{
260
+ reaction,
261
+ key: content.reactionMessage?.key
262
+ }])
263
+ }
264
+ else if (message.messageStubType) {
265
+ const jid = message.key?.remoteJid
266
+
267
+ //let actor = whatsappID (message.participant)
268
+ let participants
269
+
270
+ const jid2 = message.key.participant;
271
+ const emitParticipantsUpdate = (action) => (ev.emit('group-participants.update', { id: jid, author: jid2, participants, action}))
272
+ const emitGroupUpdate = (update) => {
273
+ ev.emit('groups.update', [{ id: jid, ...update, author: message.participant ? message.participant : undefined }])
274
+ }
275
+ const emitCommunityUpdate = (update) => {
276
+ ev.emit('communities.update', [{ id: jid, ...update, author: message.participant ? message.participant : undefined }])
277
+ }
278
+ const emitGroupRequestJoin = (participant, action, method) => {
279
+ ev.emit('group.join-request', { id: jid, author: message.participant, participant, action, method: method })
280
+ }
281
+ const participantsIncludesMe = () => participants.find(jid => WABinary_1.areJidsSameUser(meId, jid))
282
+ switch (message.messageStubType) {
283
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER:
284
+ participants = message.messageStubParameters || []
285
+ emitParticipantsUpdate('modify')
286
+ break
287
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_LEAVE:
288
+ participants = message.messageStubParameters || [];
289
+ emitParticipantsUpdate('leave');
290
+ // mark the chat read only if you left the group
291
+ if (participantsIncludesMe()) {
292
+ chat.readOnly = true;
293
+ }
294
+ break;
295
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_REMOVE:
296
+ participants = message.messageStubParameters || []
297
+ emitParticipantsUpdate('remove')
298
+ // mark the chat read only if you left the group
299
+ if (participantsIncludesMe()) {
300
+ chat.readOnly = true
301
+ }
302
+ break
303
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_ADD:
304
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_INVITE:
305
+ let actionGp = 'invite'
306
+ participants = message.messageStubParameters || []
307
+ if (participantsIncludesMe()) chat.readOnly = false;
308
+ if (message?.key?.participant && !participants.includes(message?.key?.participant)) {
309
+ actionGp = 'approval-invite'
310
+ }
311
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:
312
+ participants = message.messageStubParameters || []
313
+ if (participantsIncludesMe()) {
314
+ chat.readOnly = false
315
+ }
316
+ emitParticipantsUpdate('add')
317
+ break
318
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_DEMOTE:
319
+ case Types_1.WAMessageStubType.COMMUNITY_PARTICIPANT_DEMOTE:
320
+ participants = message.messageStubParameters || []
321
+ emitParticipantsUpdate('demote')
322
+ break
323
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_PROMOTE:
324
+ case Types_1.WAMessageStubType.COMMUNITY_PARTICIPANT_PROMOTE:
325
+ participants = message.messageStubParameters || []
326
+ emitParticipantsUpdate('promote')
327
+ break
328
+ case Types_1.WAMessageStubType.GROUP_CHANGE_ANNOUNCE:
329
+ const announceValue = message.messageStubParameters?.[0]
330
+ emitGroupUpdate({ announce: announceValue === 'true' || announceValue === 'on' })
331
+ break
332
+ case Types_1.WAMessageStubType.GROUP_CHANGE_RESTRICT:
333
+ const restrictValue = message.messageStubParameters?.[0]
334
+ emitGroupUpdate({ restrict: restrictValue === 'true' || restrictValue === 'on' })
335
+ break
336
+ case Types_1.WAMessageStubType.GROUP_CHANGE_SUBJECT:
337
+ const name = message.messageStubParameters?.[0]
338
+ chat.name = name
339
+ emitGroupUpdate({ subject: name })
340
+ break
341
+ case Types_1.WAMessageStubType.COMMUNITY_PARENT_GROUP_SUBJECT_CHANGED:
342
+ const name2 = message.messageStubParameters?.[0]
343
+ chat.name2 = name2
344
+ emitCommunityUpdate({ subject: name2 })
345
+ break
346
+ case Types_1.WAMessageStubType.GROUP_CHANGE_DESCRIPTION:
347
+ const description = message.messageStubParameters?.[0]
348
+ chat.description = description
349
+ emitGroupUpdate({ desc: description })
350
+ break
351
+ case Types_1.WAMessageStubType.COMMUNITY_CHANGE_DESCRIPTION:
352
+ const description2 = message.messageStubParameters?.[0]
353
+ chat.description2 = description2
354
+ emitCommunityUpdate({ desc: description2 })
355
+ break
356
+ case Types_1.WAMessageStubType.GROUP_CHANGE_INVITE_LINK:
357
+ const code = message.messageStubParameters?.[0]
358
+ emitGroupUpdate({ inviteCode: code })
359
+ break
360
+ case Types_1.WAMessageStubType.GROUP_MEMBER_ADD_MODE:
361
+ const memberAddValue = message.messageStubParameters?.[0]
362
+ emitGroupUpdate({ memberAddMode: memberAddValue === 'all_member_add' })
363
+ break
364
+ case Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE:
365
+ const approvalMode = message.messageStubParameters?.[0]
366
+ emitGroupUpdate({ joinApprovalMode: approvalMode === 'on' })
367
+ break
368
+ case Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD:
369
+ const participant = message.messageStubParameters?.[0]
370
+ const action = message.messageStubParameters?.[1]
371
+ const method = message.messageStubParameters?.[2]
372
+ emitGroupRequestJoin(participant, action, method)
373
+ break
374
+ }
375
+ }
376
+ else if (content?.pollUpdateMessage) {
377
+ const creationMsgKey = content.pollUpdateMessage.pollCreationMessageKey
378
+ // we need to fetch the poll creation message to get the poll enc key
379
+ const pollMsg2 = await getMessage(creationMsgKey);
380
+ const pollMsg = pollMsg.botInvokeMessage?.message || pollMsg2;
381
+ if (pollMsg) {
382
+ const meIdNormalised = WABinary_1.jidNormalizedUser(meId)
383
+ const pollCreatorJid = generics_1.getKeyAuthor(creationMsgKey, meIdNormalised)
384
+ const voterJid = generics_1.getKeyAuthor(message.key, meIdNormalised)
385
+ const pollEncKey = pollMsg.messageContextInfo?.messageSecret
386
+ try {
387
+ const voteMsg = decryptPollVote(content.pollUpdateMessage.vote, {
388
+ pollEncKey,
389
+ pollCreatorJid,
390
+ pollMsgId: creationMsgKey.id,
391
+ voterJid,
392
+ })
393
+ ev.emit('messages.update', [
394
+ {
395
+ key: creationMsgKey,
396
+ update: {
397
+ pollUpdates: [
398
+ {
399
+ pollUpdateMessageKey: message.key,
400
+ vote: voteMsg,
401
+ senderTimestampMs: content.pollUpdateMessage.senderTimestampMs.toNumber(),
402
+ }
403
+ ]
404
+ }
405
+ }
406
+ ])
407
+ }
408
+ catch (err) {
409
+ logger?.warn({ err, creationMsgKey }, 'failed to decrypt poll vote')
410
+ }
411
+ }
412
+ else {
413
+ logger?.warn({ creationMsgKey }, 'poll creation message not found, cannot decrypt update')
414
+ }
415
+ }
416
+ if (Object.keys(chat).length > 1) {
417
+ ev.emit('chats.update', [chat])
418
+ }
419
+ }
420
+
421
+ module.exports = {
422
+ cleanMessage,
423
+ isRealMessage,
424
+ shouldIncrementChatUnread,
425
+ getChatId,
426
+ decryptPollVote,
427
+ processMessage
428
+ }