@neelegirly/baileys 2.2.16

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 (206) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +108 -0
  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 +1 -0
  7. package/lib/Defaults/index.d.ts +68 -0
  8. package/lib/Defaults/index.js +155 -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 +22 -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 +427 -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 +1133 -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 +1826 -0
  52. package/lib/Socket/messages-send.d.ts +168 -0
  53. package/lib/Socket/messages-send.js +1537 -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 +928 -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/Bussines.d.ts +20 -0
  77. package/lib/Types/Bussines.js +2 -0
  78. package/lib/Types/Call.d.ts +14 -0
  79. package/lib/Types/Call.js +3 -0
  80. package/lib/Types/Chat.d.ts +141 -0
  81. package/lib/Types/Chat.js +9 -0
  82. package/lib/Types/Contact.d.ts +20 -0
  83. package/lib/Types/Contact.js +3 -0
  84. package/lib/Types/Events.d.ts +237 -0
  85. package/lib/Types/Events.js +3 -0
  86. package/lib/Types/GroupMetadata.d.ts +66 -0
  87. package/lib/Types/GroupMetadata.js +3 -0
  88. package/lib/Types/Label.d.ts +48 -0
  89. package/lib/Types/Label.js +31 -0
  90. package/lib/Types/LabelAssociation.d.ts +35 -0
  91. package/lib/Types/LabelAssociation.js +13 -0
  92. package/lib/Types/Message.d.ts +473 -0
  93. package/lib/Types/Message.js +13 -0
  94. package/lib/Types/MexUpdates.d.ts +9 -0
  95. package/lib/Types/MexUpdates.js +18 -0
  96. package/lib/Types/Newsletter.d.ts +109 -0
  97. package/lib/Types/Newsletter.js +40 -0
  98. package/lib/Types/Product.d.ts +92 -0
  99. package/lib/Types/Product.js +3 -0
  100. package/lib/Types/Signal.d.ts +68 -0
  101. package/lib/Types/Signal.js +3 -0
  102. package/lib/Types/Socket.d.ts +122 -0
  103. package/lib/Types/Socket.js +3 -0
  104. package/lib/Types/State.d.ts +41 -0
  105. package/lib/Types/State.js +14 -0
  106. package/lib/Types/USync.d.ts +26 -0
  107. package/lib/Types/USync.js +3 -0
  108. package/lib/Types/index.d.ts +80 -0
  109. package/lib/Types/index.js +48 -0
  110. package/lib/Utils/auth-utils.d.ts +21 -0
  111. package/lib/Utils/auth-utils.js +205 -0
  112. package/lib/Utils/baileys-event-stream.d.ts +18 -0
  113. package/lib/Utils/baileys-event-stream.js +70 -0
  114. package/lib/Utils/branding.d.ts +24 -0
  115. package/lib/Utils/branding.js +209 -0
  116. package/lib/Utils/business.d.ts +29 -0
  117. package/lib/Utils/business.js +255 -0
  118. package/lib/Utils/chat-utils.d.ts +82 -0
  119. package/lib/Utils/chat-utils.js +798 -0
  120. package/lib/Utils/check-npm-version.d.ts +18 -0
  121. package/lib/Utils/check-npm-version.js +130 -0
  122. package/lib/Utils/crypto.d.ts +56 -0
  123. package/lib/Utils/crypto.js +179 -0
  124. package/lib/Utils/decode-wa-message.d.ts +41 -0
  125. package/lib/Utils/decode-wa-message.js +288 -0
  126. package/lib/Utils/event-buffer.d.ts +39 -0
  127. package/lib/Utils/event-buffer.js +565 -0
  128. package/lib/Utils/generics.d.ts +129 -0
  129. package/lib/Utils/generics.js +630 -0
  130. package/lib/Utils/history.d.ts +23 -0
  131. package/lib/Utils/history.js +110 -0
  132. package/lib/Utils/index.d.ts +22 -0
  133. package/lib/Utils/index.js +42 -0
  134. package/lib/Utils/link-preview.d.ts +23 -0
  135. package/lib/Utils/link-preview.js +120 -0
  136. package/lib/Utils/logger.d.ts +13 -0
  137. package/lib/Utils/logger.js +7 -0
  138. package/lib/Utils/lt-hash.d.ts +14 -0
  139. package/lib/Utils/lt-hash.js +58 -0
  140. package/lib/Utils/make-mutex.d.ts +9 -0
  141. package/lib/Utils/make-mutex.js +49 -0
  142. package/lib/Utils/message-retry-manager.d.ts +84 -0
  143. package/lib/Utils/message-retry-manager.js +179 -0
  144. package/lib/Utils/messages-media.d.ts +129 -0
  145. package/lib/Utils/messages-media.js +806 -0
  146. package/lib/Utils/messages.d.ts +103 -0
  147. package/lib/Utils/messages.js +1579 -0
  148. package/lib/Utils/noise-handler.d.ts +20 -0
  149. package/lib/Utils/noise-handler.js +155 -0
  150. package/lib/Utils/process-message.d.ts +49 -0
  151. package/lib/Utils/process-message.js +443 -0
  152. package/lib/Utils/signal.d.ts +42 -0
  153. package/lib/Utils/signal.js +168 -0
  154. package/lib/Utils/use-mongo-file-auth-state.d.ts +6 -0
  155. package/lib/Utils/use-mongo-file-auth-state.js +84 -0
  156. package/lib/Utils/use-multi-file-auth-state.d.ts +18 -0
  157. package/lib/Utils/use-multi-file-auth-state.js +249 -0
  158. package/lib/Utils/use-single-file-auth-state.d.ts +13 -0
  159. package/lib/Utils/use-single-file-auth-state.js +80 -0
  160. package/lib/Utils/validate-connection.d.ts +13 -0
  161. package/lib/Utils/validate-connection.js +218 -0
  162. package/lib/WABinary/constants.d.ts +30 -0
  163. package/lib/WABinary/constants.js +1316 -0
  164. package/lib/WABinary/decode.d.ts +9 -0
  165. package/lib/WABinary/decode.js +288 -0
  166. package/lib/WABinary/encode.d.ts +3 -0
  167. package/lib/WABinary/encode.js +265 -0
  168. package/lib/WABinary/generic-utils.d.ts +28 -0
  169. package/lib/WABinary/generic-utils.js +142 -0
  170. package/lib/WABinary/index.d.ts +5 -0
  171. package/lib/WABinary/index.js +25 -0
  172. package/lib/WABinary/jid-utils.d.ts +59 -0
  173. package/lib/WABinary/jid-utils.js +105 -0
  174. package/lib/WABinary/types.d.ts +22 -0
  175. package/lib/WABinary/types.js +3 -0
  176. package/lib/WAM/BinaryInfo.d.ts +16 -0
  177. package/lib/WAM/BinaryInfo.js +17 -0
  178. package/lib/WAM/constants.d.ts +47 -0
  179. package/lib/WAM/constants.js +15371 -0
  180. package/lib/WAM/encode.d.ts +3 -0
  181. package/lib/WAM/encode.js +165 -0
  182. package/lib/WAM/index.d.ts +3 -0
  183. package/lib/WAM/index.js +23 -0
  184. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.d.ts +28 -0
  185. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +69 -0
  186. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  187. package/lib/WAUSync/Protocols/USyncContactProtocol.js +36 -0
  188. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +26 -0
  189. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +62 -0
  190. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +14 -0
  191. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +35 -0
  192. package/lib/WAUSync/Protocols/USyncLIDProtocol.d.ts +9 -0
  193. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +30 -0
  194. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +14 -0
  195. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +46 -0
  196. package/lib/WAUSync/Protocols/index.d.ts +6 -0
  197. package/lib/WAUSync/Protocols/index.js +26 -0
  198. package/lib/WAUSync/USyncQuery.d.ts +31 -0
  199. package/lib/WAUSync/USyncQuery.js +82 -0
  200. package/lib/WAUSync/USyncUser.d.ts +12 -0
  201. package/lib/WAUSync/USyncUser.js +30 -0
  202. package/lib/WAUSync/index.d.ts +3 -0
  203. package/lib/WAUSync/index.js +23 -0
  204. package/lib/index.d.ts +13 -0
  205. package/lib/index.js +33 -0
  206. package/package.json +120 -0
@@ -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 (Baileys 7.x: hosted Pn/LID + meLid) */
18
+ export declare const cleanMessage: (message: proto.IWebMessageInfo, meId: string, meLid?: string) => void
19
+
20
+ export declare const isRealMessage: (message: proto.IWebMessageInfo) => 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,443 @@
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 (Baileys 7.x: hosted Pn/LID + meLid) */
25
+ const cleanMessage = (message, meId, meLid) => {
26
+ if (WABinary_1.isHostedPnUser(message.key.remoteJid) || WABinary_1.isHostedLidUser(message.key.remoteJid)) {
27
+ const d = WABinary_1.jidDecode(message.key.remoteJid)
28
+ const server = WABinary_1.isHostedPnUser(message.key.remoteJid) ? 's.whatsapp.net' : 'lid'
29
+ message.key.remoteJid = WABinary_1.jidEncode(d?.user, server)
30
+ } else {
31
+ message.key.remoteJid = WABinary_1.jidNormalizedUser(message.key.remoteJid)
32
+ }
33
+ if (message.key.participant) {
34
+ if (WABinary_1.isHostedPnUser(message.key.participant) || WABinary_1.isHostedLidUser(message.key.participant)) {
35
+ const d = WABinary_1.jidDecode(message.key.participant)
36
+ const server = WABinary_1.isHostedPnUser(message.key.participant) ? 's.whatsapp.net' : 'lid'
37
+ message.key.participant = WABinary_1.jidEncode(d?.user, server)
38
+ } else {
39
+ message.key.participant = WABinary_1.jidNormalizedUser(message.key.participant)
40
+ }
41
+ } else {
42
+ message.key.participant = undefined
43
+ }
44
+ const content = messages_1.normalizeMessageContent(message.message)
45
+ if (content?.reactionMessage) {
46
+ normaliseKey(content.reactionMessage.key)
47
+ }
48
+ if (content?.pollUpdateMessage) {
49
+ normaliseKey(content.pollUpdateMessage.pollCreationMessageKey)
50
+ }
51
+ function normaliseKey(msgKey) {
52
+ if (!message.key.fromMe) {
53
+ const isMe = WABinary_1.areJidsSameUser(msgKey.participant || msgKey.remoteJid, meId) ||
54
+ (meLid && WABinary_1.areJidsSameUser(msgKey.participant || msgKey.remoteJid, meLid))
55
+ msgKey.fromMe = !msgKey.fromMe ? isMe : false
56
+ msgKey.remoteJid = message.key.remoteJid
57
+ msgKey.participant = msgKey.participant || message.key.participant
58
+ }
59
+ }
60
+ }
61
+
62
+ const isRealMessage = (message) => {
63
+ const normalizedContent = messages_1.normalizeMessageContent(message.message)
64
+ const hasSomeContent = !!messages_1.getContentType(normalizedContent)
65
+ return (
66
+ (!!normalizedContent ||
67
+ REAL_MSG_STUB_TYPES.has(message.messageStubType) ||
68
+ REAL_MSG_REQ_ME_STUB_TYPES.has(message.messageStubType)) &&
69
+ hasSomeContent &&
70
+ !normalizedContent?.protocolMessage &&
71
+ !normalizedContent?.reactionMessage &&
72
+ !normalizedContent?.pollUpdateMessage
73
+ )
74
+ }
75
+
76
+ const shouldIncrementChatUnread = (message) => !message.key.fromMe && !message.messageStubType
77
+
78
+ /**
79
+ * Get the ID of the chat from the given key.
80
+ * Typically -- that'll be the remoteJid, but for broadcasts, it'll be the participant
81
+ */
82
+ const getChatId = ({ remoteJid, participant, fromMe }) => {
83
+ if (WABinary_1.isJidBroadcast(remoteJid)
84
+ && !WABinary_1.isJidStatusBroadcast(remoteJid)
85
+ && !fromMe) {
86
+ return participant
87
+ }
88
+ return remoteJid
89
+ }
90
+
91
+ /**
92
+ * Decrypt a poll vote
93
+ * @param vote encrypted vote
94
+ * @param ctx additional info about the poll required for decryption
95
+ * @returns list of SHA256 options
96
+ */
97
+ function decryptPollVote({ encPayload, encIv }, { pollCreatorJid, pollMsgId, pollEncKey, voterJid, }) {
98
+ const sign = Buffer.concat([
99
+ toBinary(pollMsgId),
100
+ toBinary(pollCreatorJid),
101
+ toBinary(voterJid),
102
+ toBinary('Poll Vote'),
103
+ new Uint8Array([1])
104
+ ])
105
+ const key0 = crypto_1.hmacSign(pollEncKey, new Uint8Array(32), 'sha256')
106
+ const decKey = crypto_1.hmacSign(sign, key0, 'sha256')
107
+ const aad = toBinary(`${pollMsgId}\u0000${voterJid}`)
108
+ const decrypted = crypto_1.aesDecryptGCM(encPayload, decKey, encIv, aad)
109
+ return WAProto_1.proto.Message.PollVoteMessage.decode(decrypted)
110
+ function toBinary(txt) {
111
+ return Buffer.from(txt)
112
+ }
113
+ }
114
+
115
+ const processMessage = async (message, { shouldProcessHistoryMsg, placeholderResendCache, ev, creds, keyStore, logger, options, getMessage }) => {
116
+ const meId = creds.me.id
117
+ const { accountSettings } = creds
118
+ const chat = { id: WABinary_1.jidNormalizedUser(getChatId(message.key)) }
119
+ const isRealMsg = isRealMessage(message)
120
+ if (isRealMsg) {
121
+ chat.messages = [{ message }]
122
+ chat.conversationTimestamp = generics_1.toNumber(message.messageTimestamp)
123
+ // only increment unread count if not CIPHERTEXT and from another person
124
+ if (shouldIncrementChatUnread(message)) {
125
+ chat.unreadCount = (chat.unreadCount || 0) + 1
126
+ }
127
+ }
128
+ const content = messages_1.normalizeMessageContent(message.message)
129
+ // unarchive chat if it's a real message, or someone reacted to our message
130
+ // and we've the unarchive chats setting on
131
+ if (isRealMsg || content?.reactionMessage?.key?.fromMe
132
+ && accountSettings?.unarchiveChats) {
133
+ chat.archived = false
134
+ chat.readOnly = false
135
+ }
136
+ const protocolMsg = content?.protocolMessage
137
+ if (protocolMsg) {
138
+ switch (protocolMsg.type) {
139
+ case WAProto_1.proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION:
140
+ const histNotification = protocolMsg.historySyncNotification
141
+ const process = shouldProcessHistoryMsg
142
+ const isLatest = !creds.processedHistoryMessages?.length
143
+ logger?.info({
144
+ histNotification,
145
+ process,
146
+ id: message.key.id,
147
+ isLatest,
148
+ }, 'got history notification')
149
+ if (process) {
150
+ if (histNotification.syncType !== WAProto_1.proto.HistorySync.HistorySyncType.ON_DEMAND) {
151
+ ev.emit('creds.update', {
152
+ processedHistoryMessages: [
153
+ ...(creds.processedHistoryMessages || []),
154
+ { key: message.key, messageTimestamp: message.messageTimestamp }
155
+ ]
156
+ })
157
+ }
158
+ const data = await history_1.downloadAndProcessHistorySyncNotification(histNotification, options)
159
+ ev.emit('messaging-history.set', {
160
+ ...data,
161
+ isLatest: histNotification.syncType !== WAProto_1.proto.HistorySync.HistorySyncType.ON_DEMAND
162
+ ? isLatest
163
+ : undefined,
164
+ peerDataRequestSessionId: histNotification.peerDataRequestSessionId
165
+ })
166
+ }
167
+ break
168
+ case WAProto_1.proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE:
169
+ const keys = protocolMsg.appStateSyncKeyShare.keys
170
+ if (keys?.length) {
171
+ let newAppStateSyncKeyId = ''
172
+ await keyStore.transaction(async () => {
173
+ const newKeys = []
174
+ for (const { keyData, keyId } of keys) {
175
+ const strKeyId = Buffer.from(keyId.keyId).toString('base64')
176
+ newKeys.push(strKeyId)
177
+ await keyStore.set({ 'app-state-sync-key': { [strKeyId]: keyData } })
178
+ newAppStateSyncKeyId = strKeyId
179
+ }
180
+ logger?.info({ newAppStateSyncKeyId, newKeys }, 'injecting new app state sync keys')
181
+ })
182
+ ev.emit('creds.update', { myAppStateKeyId: newAppStateSyncKeyId })
183
+ }
184
+ else {
185
+ logger?.info({ protocolMsg }, 'recv app state sync with 0 keys')
186
+ }
187
+ break
188
+ case WAProto_1.proto.Message.ProtocolMessage.Type.REVOKE:
189
+ ev.emit('messages.update', [
190
+ {
191
+ key: {
192
+ ...message.key,
193
+ id: protocolMsg.key.id
194
+ },
195
+ update: { message: null, messageStubType: Types_1.WAMessageStubType.REVOKE, key: message.key }
196
+ }
197
+ ])
198
+ break
199
+ case WAProto_1.proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING:
200
+ Object.assign(chat, {
201
+ ephemeralSettingTimestamp: generics_1.toNumber(message.messageTimestamp),
202
+ ephemeralExpiration: protocolMsg.ephemeralExpiration || null
203
+ })
204
+ break
205
+ case WAProto_1.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE:
206
+ const response = protocolMsg.peerDataOperationRequestResponseMessage
207
+ if (response) {
208
+ placeholderResendCache?.del(response.stanzaId)
209
+ // TODO: IMPLEMENT HISTORY SYNC ETC (sticker uploads etc.).
210
+ const { peerDataOperationResult } = response
211
+ for (const result of peerDataOperationResult) {
212
+ const { placeholderMessageResendResponse: retryResponse } = result
213
+ //eslint-disable-next-line max-depth
214
+ if (retryResponse) {
215
+ const webMessageInfo = WAProto_1.proto.WebMessageInfo.decode(retryResponse.webMessageInfoBytes)
216
+ // wait till another upsert event is available, don't want it to be part of the PDO response message
217
+ setTimeout(() => {
218
+ ev.emit('messages.upsert', {
219
+ messages: [webMessageInfo],
220
+ type: 'notify',
221
+ requestId: response.stanzaId
222
+ })
223
+ }, 500)
224
+ }
225
+ }
226
+ }
227
+ break
228
+ case WAProto_1.proto.Message.ProtocolMessage.Type.MESSAGE_EDIT:
229
+ ev.emit('messages.update', [
230
+ {
231
+ // flip the sender / fromMe properties because they're in the perspective of the sender
232
+ key: { ...message.key, id: protocolMsg.key?.id },
233
+ update: {
234
+ message: {
235
+ editedMessage: {
236
+ message: protocolMsg.editedMessage
237
+ }
238
+ },
239
+ messageTimestamp: protocolMsg.timestampMs
240
+ ? Math.floor(generics_1.toNumber(protocolMsg.timestampMs) / 1000)
241
+ : message.messageTimestamp
242
+ }
243
+ }
244
+ ])
245
+ break
246
+ case WAProto_1.proto.Message.ProtocolMessage.Type.LIMIT_SHARING:
247
+ ev.emit('limit-sharing.update', {
248
+ id: protocolMsg.key.remoteJid,
249
+ author: WABinary_1.areJidsSameUser(message.key.remoteJid, protocolMsg.key.remoteJid) ? WABinary_1.jidNormalizedUser(meId) : message.key.remoteJid,
250
+ action: `${protocolMsg.limitSharing.sharingLimited ? 'on' : 'off'}`,
251
+ trigger: protocolMsg.limitSharing.trigger,
252
+ update_time: protocolMsg.limitSharing.limitSharingSettingTimestamp
253
+ })
254
+ break
255
+ case WAProto_1.proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE:
256
+ const labelAssociationMsg = protocolMsg.memberLabel
257
+ if (labelAssociationMsg?.label) {
258
+ ev.emit('group.member-tag.update', {
259
+ groupId: chat.id,
260
+ label: labelAssociationMsg.label,
261
+ participant: message.key.participant,
262
+ participantAlt: message.key.participantAlt,
263
+ messageTimestamp: Number(message.messageTimestamp)
264
+ })
265
+ }
266
+ break
267
+ }
268
+ }
269
+ else if (content?.reactionMessage) {
270
+ const reaction = {
271
+ ...content.reactionMessage,
272
+ key: message.key,
273
+ }
274
+ ev.emit('messages.reaction', [{
275
+ reaction,
276
+ key: content.reactionMessage?.key
277
+ }])
278
+ }
279
+ else if (message.messageStubType) {
280
+ const jid = message.key?.remoteJid
281
+
282
+ //let actor = whatsappID (message.participant)
283
+ let participants
284
+
285
+ const jid2 = message.key.participant;
286
+ const emitParticipantsUpdate = (action) => (ev.emit('group-participants.update', { id: jid, author: jid2, participants, action}))
287
+ const emitGroupUpdate = (update) => {
288
+ ev.emit('groups.update', [{ id: jid, ...update, author: message.participant ? message.participant : undefined }])
289
+ }
290
+ const emitCommunityUpdate = (update) => {
291
+ ev.emit('communities.update', [{ id: jid, ...update, author: message.participant ? message.participant : undefined }])
292
+ }
293
+ const emitGroupRequestJoin = (participant, action, method) => {
294
+ ev.emit('group.join-request', { id: jid, author: message.participant, participant, action, method: method })
295
+ }
296
+ const participantsIncludesMe = () => participants.find(jid => WABinary_1.areJidsSameUser(meId, jid))
297
+ switch (message.messageStubType) {
298
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER:
299
+ participants = message.messageStubParameters || []
300
+ emitParticipantsUpdate('modify')
301
+ break
302
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_LEAVE:
303
+ participants = message.messageStubParameters || [];
304
+ emitParticipantsUpdate('leave');
305
+ // mark the chat read only if you left the group
306
+ if (participantsIncludesMe()) {
307
+ chat.readOnly = true;
308
+ }
309
+ break;
310
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_REMOVE:
311
+ participants = message.messageStubParameters || []
312
+ emitParticipantsUpdate('remove')
313
+ // mark the chat read only if you left the group
314
+ if (participantsIncludesMe()) {
315
+ chat.readOnly = true
316
+ }
317
+ break
318
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_ADD:
319
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_INVITE:
320
+ let actionGp = 'invite'
321
+ participants = message.messageStubParameters || []
322
+ if (participantsIncludesMe()) chat.readOnly = false;
323
+ if (message?.key?.participant && !participants.includes(message?.key?.participant)) {
324
+ actionGp = 'approval-invite'
325
+ }
326
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:
327
+ participants = message.messageStubParameters || []
328
+ if (participantsIncludesMe()) {
329
+ chat.readOnly = false
330
+ }
331
+ emitParticipantsUpdate('add')
332
+ break
333
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_DEMOTE:
334
+ case Types_1.WAMessageStubType.COMMUNITY_PARTICIPANT_DEMOTE:
335
+ participants = message.messageStubParameters || []
336
+ emitParticipantsUpdate('demote')
337
+ break
338
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_PROMOTE:
339
+ case Types_1.WAMessageStubType.COMMUNITY_PARTICIPANT_PROMOTE:
340
+ participants = message.messageStubParameters || []
341
+ emitParticipantsUpdate('promote')
342
+ break
343
+ case Types_1.WAMessageStubType.GROUP_CHANGE_ANNOUNCE:
344
+ const announceValue = message.messageStubParameters?.[0]
345
+ emitGroupUpdate({ announce: announceValue === 'true' || announceValue === 'on' })
346
+ break
347
+ case Types_1.WAMessageStubType.GROUP_CHANGE_RESTRICT:
348
+ const restrictValue = message.messageStubParameters?.[0]
349
+ emitGroupUpdate({ restrict: restrictValue === 'true' || restrictValue === 'on' })
350
+ break
351
+ case Types_1.WAMessageStubType.GROUP_CHANGE_SUBJECT:
352
+ const name = message.messageStubParameters?.[0]
353
+ chat.name = name
354
+ emitGroupUpdate({ subject: name })
355
+ break
356
+ case Types_1.WAMessageStubType.COMMUNITY_PARENT_GROUP_SUBJECT_CHANGED:
357
+ const name2 = message.messageStubParameters?.[0]
358
+ chat.name2 = name2
359
+ emitCommunityUpdate({ subject: name2 })
360
+ break
361
+ case Types_1.WAMessageStubType.GROUP_CHANGE_DESCRIPTION:
362
+ const description = message.messageStubParameters?.[0]
363
+ chat.description = description
364
+ emitGroupUpdate({ desc: description })
365
+ break
366
+ case Types_1.WAMessageStubType.COMMUNITY_CHANGE_DESCRIPTION:
367
+ const description2 = message.messageStubParameters?.[0]
368
+ chat.description2 = description2
369
+ emitCommunityUpdate({ desc: description2 })
370
+ break
371
+ case Types_1.WAMessageStubType.GROUP_CHANGE_INVITE_LINK:
372
+ const code = message.messageStubParameters?.[0]
373
+ emitGroupUpdate({ inviteCode: code })
374
+ break
375
+ case Types_1.WAMessageStubType.GROUP_MEMBER_ADD_MODE:
376
+ const memberAddValue = message.messageStubParameters?.[0]
377
+ emitGroupUpdate({ memberAddMode: memberAddValue === 'all_member_add' })
378
+ break
379
+ case Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE:
380
+ const approvalMode = message.messageStubParameters?.[0]
381
+ emitGroupUpdate({ joinApprovalMode: approvalMode === 'on' })
382
+ break
383
+ case Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD:
384
+ const participant = message.messageStubParameters?.[0]
385
+ const action = message.messageStubParameters?.[1]
386
+ const method = message.messageStubParameters?.[2]
387
+ emitGroupRequestJoin(participant, action, method)
388
+ break
389
+ }
390
+ }
391
+ else if (content?.pollUpdateMessage) {
392
+ const creationMsgKey = content.pollUpdateMessage.pollCreationMessageKey
393
+ // we need to fetch the poll creation message to get the poll enc key
394
+ const pollMsg2 = await getMessage(creationMsgKey);
395
+ const pollMsg = pollMsg.botInvokeMessage?.message || pollMsg2;
396
+ if (pollMsg) {
397
+ const meIdNormalised = WABinary_1.jidNormalizedUser(meId)
398
+ const pollCreatorJid = generics_1.getKeyAuthor(creationMsgKey, meIdNormalised)
399
+ const voterJid = generics_1.getKeyAuthor(message.key, meIdNormalised)
400
+ const pollEncKey = pollMsg.messageContextInfo?.messageSecret
401
+ try {
402
+ const voteMsg = decryptPollVote(content.pollUpdateMessage.vote, {
403
+ pollEncKey,
404
+ pollCreatorJid,
405
+ pollMsgId: creationMsgKey.id,
406
+ voterJid,
407
+ })
408
+ ev.emit('messages.update', [
409
+ {
410
+ key: creationMsgKey,
411
+ update: {
412
+ pollUpdates: [
413
+ {
414
+ pollUpdateMessageKey: message.key,
415
+ vote: voteMsg,
416
+ senderTimestampMs: content.pollUpdateMessage.senderTimestampMs.toNumber(),
417
+ }
418
+ ]
419
+ }
420
+ }
421
+ ])
422
+ }
423
+ catch (err) {
424
+ logger?.warn({ err, creationMsgKey }, 'failed to decrypt poll vote')
425
+ }
426
+ }
427
+ else {
428
+ logger?.warn({ creationMsgKey }, 'poll creation message not found, cannot decrypt update')
429
+ }
430
+ }
431
+ if (Object.keys(chat).length > 1) {
432
+ ev.emit('chats.update', [chat])
433
+ }
434
+ }
435
+
436
+ module.exports = {
437
+ cleanMessage,
438
+ isRealMessage,
439
+ shouldIncrementChatUnread,
440
+ getChatId,
441
+ decryptPollVote,
442
+ processMessage
443
+ }