naya-flore 4.7.1

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 (182) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +104 -0
  3. package/WAProto/GenerateStatics.sh +4 -0
  4. package/WAProto/WAProto.proto +4450 -0
  5. package/WAProto/index.d.ts +48955 -0
  6. package/WAProto/index.js +151420 -0
  7. package/WASignalGroup/GroupProtocol.js +1697 -0
  8. package/WASignalGroup/ciphertext_message.js +16 -0
  9. package/WASignalGroup/group_cipher.js +120 -0
  10. package/WASignalGroup/group_session_builder.js +46 -0
  11. package/WASignalGroup/index.js +5 -0
  12. package/WASignalGroup/keyhelper.js +21 -0
  13. package/WASignalGroup/protobufs.js +3 -0
  14. package/WASignalGroup/queue_job.js +69 -0
  15. package/WASignalGroup/sender_chain_key.js +50 -0
  16. package/WASignalGroup/sender_key_distribution_message.js +78 -0
  17. package/WASignalGroup/sender_key_message.js +92 -0
  18. package/WASignalGroup/sender_key_name.js +70 -0
  19. package/WASignalGroup/sender_key_record.js +56 -0
  20. package/WASignalGroup/sender_key_state.js +129 -0
  21. package/WASignalGroup/sender_message_key.js +39 -0
  22. package/lib/Defaults/baileys-version.json +3 -0
  23. package/lib/Defaults/index.d.ts +284 -0
  24. package/lib/Defaults/index.js +120 -0
  25. package/lib/Defaults/phonenumber-mcc.json +223 -0
  26. package/lib/Signal/libsignal.d.ts +3 -0
  27. package/lib/Signal/libsignal.js +161 -0
  28. package/lib/Socket/Client/abstract-socket-client.d.ts +15 -0
  29. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  30. package/lib/Socket/Client/index.d.ts +2 -0
  31. package/lib/Socket/Client/index.js +18 -0
  32. package/lib/Socket/Client/mobile-socket-client.d.ts +12 -0
  33. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  34. package/lib/Socket/Client/types.d.ts +17 -0
  35. package/lib/Socket/Client/types.js +13 -0
  36. package/lib/Socket/Client/websocket.d.ts +12 -0
  37. package/lib/Socket/Client/websocket.js +62 -0
  38. package/lib/Socket/business.d.ts +170 -0
  39. package/lib/Socket/business.js +260 -0
  40. package/lib/Socket/chats.d.ts +81 -0
  41. package/lib/Socket/chats.js +871 -0
  42. package/lib/Socket/groups.d.ts +115 -0
  43. package/lib/Socket/groups.js +304 -0
  44. package/lib/Socket/index.d.ts +172 -0
  45. package/lib/Socket/index.js +10 -0
  46. package/lib/Socket/messages-recv.d.ts +158 -0
  47. package/lib/Socket/messages-recv.js +966 -0
  48. package/lib/Socket/messages-send.d.ts +155 -0
  49. package/lib/Socket/messages-send.js +1021 -0
  50. package/lib/Socket/newsletter.d.ts +132 -0
  51. package/lib/Socket/newsletter.js +236 -0
  52. package/lib/Socket/registration.d.ts +264 -0
  53. package/lib/Socket/registration.js +166 -0
  54. package/lib/Socket/socket.d.ts +44 -0
  55. package/lib/Socket/socket.js +666 -0
  56. package/lib/Socket/usync.d.ts +37 -0
  57. package/lib/Socket/usync.js +70 -0
  58. package/lib/Store/index.d.ts +3 -0
  59. package/lib/Store/index.js +10 -0
  60. package/lib/Store/make-cache-manager-store.d.ts +14 -0
  61. package/lib/Store/make-cache-manager-store.js +83 -0
  62. package/lib/Store/make-in-memory-store.d.ts +118 -0
  63. package/lib/Store/make-in-memory-store.js +431 -0
  64. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  65. package/lib/Store/make-ordered-dictionary.js +81 -0
  66. package/lib/Store/object-repository.d.ts +10 -0
  67. package/lib/Store/object-repository.js +27 -0
  68. package/lib/Types/Auth.d.ts +109 -0
  69. package/lib/Types/Auth.js +2 -0
  70. package/lib/Types/Call.d.ts +13 -0
  71. package/lib/Types/Call.js +2 -0
  72. package/lib/Types/Chat.d.ts +107 -0
  73. package/lib/Types/Chat.js +4 -0
  74. package/lib/Types/Contact.d.ts +19 -0
  75. package/lib/Types/Contact.js +2 -0
  76. package/lib/Types/Events.d.ts +172 -0
  77. package/lib/Types/Events.js +2 -0
  78. package/lib/Types/GroupMetadata.d.ts +56 -0
  79. package/lib/Types/GroupMetadata.js +2 -0
  80. package/lib/Types/Label.d.ts +46 -0
  81. package/lib/Types/Label.js +27 -0
  82. package/lib/Types/LabelAssociation.d.ts +29 -0
  83. package/lib/Types/LabelAssociation.js +9 -0
  84. package/lib/Types/Message.d.ts +433 -0
  85. package/lib/Types/Message.js +9 -0
  86. package/lib/Types/Newsletter.d.ts +92 -0
  87. package/lib/Types/Newsletter.js +32 -0
  88. package/lib/Types/Product.d.ts +78 -0
  89. package/lib/Types/Product.js +2 -0
  90. package/lib/Types/Signal.d.ts +57 -0
  91. package/lib/Types/Signal.js +2 -0
  92. package/lib/Types/Socket.d.ts +114 -0
  93. package/lib/Types/Socket.js +2 -0
  94. package/lib/Types/State.d.ts +27 -0
  95. package/lib/Types/State.js +2 -0
  96. package/lib/Types/USync.d.ts +25 -0
  97. package/lib/Types/USync.js +2 -0
  98. package/lib/Types/index.d.ts +66 -0
  99. package/lib/Types/index.js +42 -0
  100. package/lib/Utils/auth-utils.d.ts +18 -0
  101. package/lib/Utils/auth-utils.js +206 -0
  102. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  103. package/lib/Utils/baileys-event-stream.js +63 -0
  104. package/lib/Utils/business.d.ts +22 -0
  105. package/lib/Utils/business.js +234 -0
  106. package/lib/Utils/chat-utils.d.ts +70 -0
  107. package/lib/Utils/chat-utils.js +745 -0
  108. package/lib/Utils/crypto.d.ts +40 -0
  109. package/lib/Utils/crypto.js +163 -0
  110. package/lib/Utils/decode-wa-message.d.ts +36 -0
  111. package/lib/Utils/decode-wa-message.js +226 -0
  112. package/lib/Utils/event-buffer.d.ts +35 -0
  113. package/lib/Utils/event-buffer.js +514 -0
  114. package/lib/Utils/generics.d.ts +88 -0
  115. package/lib/Utils/generics.js +401 -0
  116. package/lib/Utils/history.d.ts +19 -0
  117. package/lib/Utils/history.js +94 -0
  118. package/lib/Utils/index.d.ts +17 -0
  119. package/lib/Utils/index.js +33 -0
  120. package/lib/Utils/link-preview.d.ts +21 -0
  121. package/lib/Utils/link-preview.js +93 -0
  122. package/lib/Utils/logger.d.ts +2 -0
  123. package/lib/Utils/logger.js +7 -0
  124. package/lib/Utils/lt-hash.d.ts +12 -0
  125. package/lib/Utils/lt-hash.js +51 -0
  126. package/lib/Utils/make-mutex.d.ts +7 -0
  127. package/lib/Utils/make-mutex.js +43 -0
  128. package/lib/Utils/messages-media.d.ts +113 -0
  129. package/lib/Utils/messages-media.js +722 -0
  130. package/lib/Utils/messages.d.ts +77 -0
  131. package/lib/Utils/messages.js +1217 -0
  132. package/lib/Utils/noise-handler.d.ts +20 -0
  133. package/lib/Utils/noise-handler.js +155 -0
  134. package/lib/Utils/process-message.d.ts +41 -0
  135. package/lib/Utils/process-message.js +321 -0
  136. package/lib/Utils/signal.d.ts +33 -0
  137. package/lib/Utils/signal.js +143 -0
  138. package/lib/Utils/use-multi-file-auth-state.d.ts +12 -0
  139. package/lib/Utils/use-multi-file-auth-state.js +88 -0
  140. package/lib/Utils/validate-connection.d.ts +11 -0
  141. package/lib/Utils/validate-connection.js +205 -0
  142. package/lib/WABinary/constants.d.ts +27 -0
  143. package/lib/WABinary/constants.js +40 -0
  144. package/lib/WABinary/decode.d.ts +6 -0
  145. package/lib/WABinary/decode.js +262 -0
  146. package/lib/WABinary/encode.d.ts +2 -0
  147. package/lib/WABinary/encode.js +244 -0
  148. package/lib/WABinary/generic-utils.d.ts +14 -0
  149. package/lib/WABinary/generic-utils.js +110 -0
  150. package/lib/WABinary/index.d.ts +5 -0
  151. package/lib/WABinary/index.js +21 -0
  152. package/lib/WABinary/jid-utils.d.ts +31 -0
  153. package/lib/WABinary/jid-utils.js +62 -0
  154. package/lib/WABinary/types.d.ts +18 -0
  155. package/lib/WABinary/types.js +2 -0
  156. package/lib/WAM/BinaryInfo.d.ts +8 -0
  157. package/lib/WAM/BinaryInfo.js +13 -0
  158. package/lib/WAM/constants.d.ts +38 -0
  159. package/lib/WAM/constants.js +15350 -0
  160. package/lib/WAM/encode.d.ts +2 -0
  161. package/lib/WAM/encode.js +155 -0
  162. package/lib/WAM/index.d.ts +3 -0
  163. package/lib/WAM/index.js +19 -0
  164. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  165. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  166. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  167. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  168. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  169. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  170. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  171. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  172. package/lib/WAUSync/Protocols/index.d.ts +4 -0
  173. package/lib/WAUSync/Protocols/index.js +20 -0
  174. package/lib/WAUSync/USyncQuery.d.ts +26 -0
  175. package/lib/WAUSync/USyncQuery.js +79 -0
  176. package/lib/WAUSync/USyncUser.d.ts +10 -0
  177. package/lib/WAUSync/USyncUser.js +22 -0
  178. package/lib/WAUSync/index.d.ts +3 -0
  179. package/lib/WAUSync/index.js +19 -0
  180. package/lib/index.d.ts +12 -0
  181. package/lib/index.js +31 -0
  182. package/package.json +116 -0
@@ -0,0 +1,20 @@
1
+ import { Logger } from 'pino';
2
+ import { proto } from '../../WAProto';
3
+ import { KeyPair } from '../Types';
4
+ import { BinaryNode } from '../WABinary';
5
+ export declare const makeNoiseHandler: ({ keyPair: { private: privateKey, public: publicKey }, NOISE_HEADER, mobile, logger, routingInfo }: {
6
+ keyPair: KeyPair;
7
+ NOISE_HEADER: Uint8Array;
8
+ mobile: boolean;
9
+ logger: Logger;
10
+ routingInfo?: Buffer | undefined;
11
+ }) => {
12
+ encrypt: (plaintext: Uint8Array) => any;
13
+ decrypt: (ciphertext: Uint8Array) => any;
14
+ authenticate: (data: Uint8Array) => void;
15
+ mixIntoKey: (data: Uint8Array) => void;
16
+ finishInit: () => void;
17
+ processHandshake: ({ serverHello }: proto.HandshakeMessage, noiseKey: KeyPair) => any;
18
+ encodeFrame: (data: Buffer | Uint8Array) => any;
19
+ decodeFrame: (newData: Buffer | Uint8Array, onFrame: (buff: Uint8Array | BinaryNode) => void) => void;
20
+ };
@@ -0,0 +1,155 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.makeNoiseHandler = void 0;
4
+ const boom_1 = require("@hapi/boom");
5
+ const WAProto_1 = require("../../WAProto");
6
+ const Defaults_1 = require("../Defaults");
7
+ const WABinary_1 = require("../WABinary");
8
+ const crypto_1 = require("./crypto");
9
+ const generateIV = (counter) => {
10
+ const iv = new ArrayBuffer(12);
11
+ new DataView(iv).setUint32(8, counter);
12
+ return new Uint8Array(iv);
13
+ };
14
+ const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publicKey }, NOISE_HEADER, mobile, logger, routingInfo }) => {
15
+ logger = logger.child({ class: 'ns' });
16
+ const authenticate = (data) => {
17
+ if (!isFinished) {
18
+ hash = (0, crypto_1.sha256)(Buffer.concat([hash, data]));
19
+ }
20
+ };
21
+ const encrypt = (plaintext) => {
22
+ const result = (0, crypto_1.aesEncryptGCM)(plaintext, encKey, generateIV(writeCounter), hash);
23
+ writeCounter += 1;
24
+ authenticate(result);
25
+ return result;
26
+ };
27
+ const decrypt = (ciphertext) => {
28
+ // before the handshake is finished, we use the same counter
29
+ // after handshake, the counters are different
30
+ const iv = generateIV(isFinished ? readCounter : writeCounter);
31
+ const result = (0, crypto_1.aesDecryptGCM)(ciphertext, decKey, iv, hash);
32
+ if (isFinished) {
33
+ readCounter += 1;
34
+ }
35
+ else {
36
+ writeCounter += 1;
37
+ }
38
+ authenticate(ciphertext);
39
+ return result;
40
+ };
41
+ const localHKDF = (data) => {
42
+ const key = (0, crypto_1.hkdf)(Buffer.from(data), 64, { salt, info: '' });
43
+ return [key.slice(0, 32), key.slice(32)];
44
+ };
45
+ const mixIntoKey = (data) => {
46
+ const [write, read] = localHKDF(data);
47
+ salt = write;
48
+ encKey = read;
49
+ decKey = read;
50
+ readCounter = 0;
51
+ writeCounter = 0;
52
+ };
53
+ const finishInit = () => {
54
+ const [write, read] = localHKDF(new Uint8Array(0));
55
+ encKey = write;
56
+ decKey = read;
57
+ hash = Buffer.from([]);
58
+ readCounter = 0;
59
+ writeCounter = 0;
60
+ isFinished = true;
61
+ };
62
+ const data = Buffer.from(Defaults_1.NOISE_MODE);
63
+ let hash = Buffer.from(data.byteLength === 32 ? data : (0, crypto_1.sha256)(data));
64
+ let salt = hash;
65
+ let encKey = hash;
66
+ let decKey = hash;
67
+ let readCounter = 0;
68
+ let writeCounter = 0;
69
+ let isFinished = false;
70
+ let sentIntro = false;
71
+ let inBytes = Buffer.alloc(0);
72
+ authenticate(NOISE_HEADER);
73
+ authenticate(publicKey);
74
+ return {
75
+ encrypt,
76
+ decrypt,
77
+ authenticate,
78
+ mixIntoKey,
79
+ finishInit,
80
+ processHandshake: ({ serverHello }, noiseKey) => {
81
+ authenticate(serverHello.ephemeral);
82
+ mixIntoKey(crypto_1.Curve.sharedKey(privateKey, serverHello.ephemeral));
83
+ const decStaticContent = decrypt(serverHello.static);
84
+ mixIntoKey(crypto_1.Curve.sharedKey(privateKey, decStaticContent));
85
+ const certDecoded = decrypt(serverHello.payload);
86
+ if (mobile) {
87
+ WAProto_1.proto.CertChain.NoiseCertificate.decode(certDecoded);
88
+ }
89
+ else {
90
+ const { intermediate: certIntermediate } = WAProto_1.proto.CertChain.decode(certDecoded);
91
+ const { issuerSerial } = WAProto_1.proto.CertChain.NoiseCertificate.Details.decode(certIntermediate.details);
92
+ if (issuerSerial !== Defaults_1.WA_CERT_DETAILS.SERIAL) {
93
+ throw new boom_1.Boom('certification match failed', { statusCode: 400 });
94
+ }
95
+ }
96
+ const keyEnc = encrypt(noiseKey.public);
97
+ mixIntoKey(crypto_1.Curve.sharedKey(noiseKey.private, serverHello.ephemeral));
98
+ return keyEnc;
99
+ },
100
+ encodeFrame: (data) => {
101
+ if (isFinished) {
102
+ data = encrypt(data);
103
+ }
104
+ let header;
105
+ if (routingInfo) {
106
+ header = Buffer.alloc(7);
107
+ header.write('ED', 0, 'utf8');
108
+ header.writeUint8(0, 2);
109
+ header.writeUint8(1, 3);
110
+ header.writeUint8(routingInfo.byteLength >> 16, 4);
111
+ header.writeUint16BE(routingInfo.byteLength & 65535, 5);
112
+ header = Buffer.concat([header, routingInfo, NOISE_HEADER]);
113
+ }
114
+ else {
115
+ header = Buffer.from(NOISE_HEADER);
116
+ }
117
+ const introSize = sentIntro ? 0 : header.length;
118
+ const frame = Buffer.alloc(introSize + 3 + data.byteLength);
119
+ if (!sentIntro) {
120
+ frame.set(header);
121
+ sentIntro = true;
122
+ }
123
+ frame.writeUInt8(data.byteLength >> 16, introSize);
124
+ frame.writeUInt16BE(65535 & data.byteLength, introSize + 1);
125
+ frame.set(data, introSize + 3);
126
+ return frame;
127
+ },
128
+ decodeFrame: (newData, onFrame) => {
129
+ var _a;
130
+ // the binary protocol uses its own framing mechanism
131
+ // on top of the WS frames
132
+ // so we get this data and separate out the frames
133
+ const getBytesSize = () => {
134
+ if (inBytes.length >= 3) {
135
+ return (inBytes.readUInt8() << 16) | inBytes.readUInt16BE(1);
136
+ }
137
+ };
138
+ inBytes = Buffer.concat([inBytes, newData]);
139
+ logger.trace(`recv ${newData.length} bytes, total recv ${inBytes.length} bytes`);
140
+ let size = getBytesSize();
141
+ while (size && inBytes.length >= size + 3) {
142
+ let frame = inBytes.slice(3, size + 3);
143
+ inBytes = inBytes.slice(size + 3);
144
+ if (isFinished) {
145
+ const result = decrypt(frame);
146
+ frame = (0, WABinary_1.decodeBinaryNode)(result);
147
+ }
148
+ logger.trace({ msg: (_a = frame === null || frame === void 0 ? void 0 : frame.attrs) === null || _a === void 0 ? void 0 : _a.id }, 'recv frame');
149
+ onFrame(frame);
150
+ size = getBytesSize();
151
+ }
152
+ }
153
+ };
154
+ };
155
+ exports.makeNoiseHandler = makeNoiseHandler;
@@ -0,0 +1,41 @@
1
+ import { AxiosRequestConfig } from 'axios';
2
+ import type { Logger } from 'pino';
3
+ import { proto } from '../../WAProto';
4
+ import { AuthenticationCreds, BaileysEventEmitter, SignalKeyStoreWithTransaction, SocketConfig } from '../Types';
5
+ type ProcessMessageContext = {
6
+ shouldProcessHistoryMsg: boolean;
7
+ creds: AuthenticationCreds;
8
+ keyStore: SignalKeyStoreWithTransaction;
9
+ ev: BaileysEventEmitter;
10
+ getMessage: SocketConfig['getMessage'];
11
+ logger?: Logger;
12
+ options: AxiosRequestConfig<{}>;
13
+ };
14
+ /** Cleans a received message to further processing */
15
+ export declare const cleanMessage: (message: proto.IWebMessageInfo, meId: string) => void;
16
+ export declare const isRealMessage: (message: proto.IWebMessageInfo, meId: string) => boolean | undefined;
17
+ export declare const shouldIncrementChatUnread: (message: proto.IWebMessageInfo) => boolean;
18
+ /**
19
+ * Get the ID of the chat from the given key.
20
+ * Typically -- that'll be the remoteJid, but for broadcasts, it'll be the participant
21
+ */
22
+ export declare const getChatId: ({ remoteJid, participant, fromMe }: proto.IMessageKey) => string;
23
+ type PollContext = {
24
+ /** normalised jid of the person that created the poll */
25
+ pollCreatorJid: string;
26
+ /** ID of the poll creation message */
27
+ pollMsgId: string;
28
+ /** poll creation message enc key */
29
+ pollEncKey: Uint8Array;
30
+ /** jid of the person that voted */
31
+ voterJid: string;
32
+ };
33
+ /**
34
+ * Decrypt a poll vote
35
+ * @param vote encrypted vote
36
+ * @param ctx additional info about the poll required for decryption
37
+ * @returns list of SHA256 options
38
+ */
39
+ export declare function decryptPollVote({ encPayload, encIv }: proto.Message.IPollEncValue, { pollCreatorJid, pollMsgId, pollEncKey, voterJid, }: PollContext): proto.Message.PollVoteMessage;
40
+ declare const processMessage: (message: proto.IWebMessageInfo, { shouldProcessHistoryMsg, ev, creds, keyStore, logger, options, getMessage }: ProcessMessageContext) => Promise<void>;
41
+ export default processMessage;
@@ -0,0 +1,321 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getChatId = exports.shouldIncrementChatUnread = exports.isRealMessage = exports.cleanMessage = void 0;
4
+ exports.decryptPollVote = decryptPollVote;
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 REAL_MSG_STUB_TYPES = new Set([
13
+ Types_1.WAMessageStubType.CALL_MISSED_GROUP_VIDEO,
14
+ Types_1.WAMessageStubType.CALL_MISSED_GROUP_VOICE,
15
+ Types_1.WAMessageStubType.CALL_MISSED_VIDEO,
16
+ Types_1.WAMessageStubType.CALL_MISSED_VOICE
17
+ ]);
18
+ const REAL_MSG_REQ_ME_STUB_TYPES = new Set([
19
+ Types_1.WAMessageStubType.GROUP_PARTICIPANT_ADD
20
+ ]);
21
+ /** Cleans a received message to further processing */
22
+ const cleanMessage = (message, meId) => {
23
+ // ensure remoteJid and participant doesn't have device or agent in it
24
+ message.key.remoteJid = (0, WABinary_1.jidNormalizedUser)(message.key.remoteJid);
25
+ message.key.participant = message.key.participant ? (0, WABinary_1.jidNormalizedUser)(message.key.participant) : undefined;
26
+ const content = (0, messages_1.normalizeMessageContent)(message.message);
27
+ // if the message has a reaction, ensure fromMe & remoteJid are from our perspective
28
+ if (content === null || content === void 0 ? void 0 : content.reactionMessage) {
29
+ normaliseKey(content.reactionMessage.key);
30
+ }
31
+ if (content === null || content === void 0 ? void 0 : content.pollUpdateMessage) {
32
+ normaliseKey(content.pollUpdateMessage.pollCreationMessageKey);
33
+ }
34
+ function normaliseKey(msgKey) {
35
+ // if the reaction is from another user
36
+ // we've to correctly map the key to this user's perspective
37
+ if (!message.key.fromMe) {
38
+ // if the sender believed the message being reacted to is not from them
39
+ // we've to correct the key to be from them, or some other participant
40
+ msgKey.fromMe = !msgKey.fromMe
41
+ ? (0, WABinary_1.areJidsSameUser)(msgKey.participant || msgKey.remoteJid, meId)
42
+ // if the message being reacted to, was from them
43
+ // fromMe automatically becomes false
44
+ : false;
45
+ // set the remoteJid to being the same as the chat the message came from
46
+ msgKey.remoteJid = message.key.remoteJid;
47
+ // set participant of the message
48
+ msgKey.participant = msgKey.participant || message.key.participant;
49
+ }
50
+ }
51
+ };
52
+ exports.cleanMessage = cleanMessage;
53
+ const isRealMessage = (message, meId) => {
54
+ var _a;
55
+ const normalizedContent = (0, messages_1.normalizeMessageContent)(message.message);
56
+ const hasSomeContent = !!(0, messages_1.getContentType)(normalizedContent);
57
+ return (!!normalizedContent
58
+ || REAL_MSG_STUB_TYPES.has(message.messageStubType)
59
+ || (REAL_MSG_REQ_ME_STUB_TYPES.has(message.messageStubType)
60
+ && ((_a = message.messageStubParameters) === null || _a === void 0 ? void 0 : _a.some(p => (0, WABinary_1.areJidsSameUser)(meId, p)))))
61
+ && hasSomeContent
62
+ && !(normalizedContent === null || normalizedContent === void 0 ? void 0 : normalizedContent.protocolMessage)
63
+ && !(normalizedContent === null || normalizedContent === void 0 ? void 0 : normalizedContent.reactionMessage)
64
+ && !(normalizedContent === null || normalizedContent === void 0 ? void 0 : normalizedContent.pollUpdateMessage);
65
+ };
66
+ exports.isRealMessage = isRealMessage;
67
+ const shouldIncrementChatUnread = (message) => (!message.key.fromMe && !message.messageStubType);
68
+ exports.shouldIncrementChatUnread = shouldIncrementChatUnread;
69
+ /**
70
+ * Get the ID of the chat from the given key.
71
+ * Typically -- that'll be the remoteJid, but for broadcasts, it'll be the participant
72
+ */
73
+ const getChatId = ({ remoteJid, participant, fromMe }) => {
74
+ if ((0, WABinary_1.isJidBroadcast)(remoteJid)
75
+ && !(0, WABinary_1.isJidStatusBroadcast)(remoteJid)
76
+ && !fromMe) {
77
+ return participant;
78
+ }
79
+ return remoteJid;
80
+ };
81
+ exports.getChatId = getChatId;
82
+ /**
83
+ * Decrypt a poll vote
84
+ * @param vote encrypted vote
85
+ * @param ctx additional info about the poll required for decryption
86
+ * @returns list of SHA256 options
87
+ */
88
+ function decryptPollVote({ encPayload, encIv }, { pollCreatorJid, pollMsgId, pollEncKey, voterJid, }) {
89
+ const sign = Buffer.concat([
90
+ toBinary(pollMsgId),
91
+ toBinary(pollCreatorJid),
92
+ toBinary(voterJid),
93
+ toBinary('Poll Vote'),
94
+ new Uint8Array([1])
95
+ ]);
96
+ const key0 = (0, crypto_1.hmacSign)(pollEncKey, new Uint8Array(32), 'sha256');
97
+ const decKey = (0, crypto_1.hmacSign)(sign, key0, 'sha256');
98
+ const aad = toBinary(`${pollMsgId}\u0000${voterJid}`);
99
+ const decrypted = (0, crypto_1.aesDecryptGCM)(encPayload, decKey, encIv, aad);
100
+ return WAProto_1.proto.Message.PollVoteMessage.decode(decrypted);
101
+ function toBinary(txt) {
102
+ return Buffer.from(txt);
103
+ }
104
+ }
105
+ const processMessage = async (message, { shouldProcessHistoryMsg, ev, creds, keyStore, logger, options, getMessage }) => {
106
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
107
+ const meId = creds.me.id;
108
+ const { accountSettings } = creds;
109
+ const chat = { id: (0, WABinary_1.jidNormalizedUser)((0, exports.getChatId)(message.key)) };
110
+ const isRealMsg = (0, exports.isRealMessage)(message, meId);
111
+ if (isRealMsg) {
112
+ chat.conversationTimestamp = (0, generics_1.toNumber)(message.messageTimestamp);
113
+ // only increment unread count if not CIPHERTEXT and from another person
114
+ if ((0, exports.shouldIncrementChatUnread)(message)) {
115
+ chat.unreadCount = (chat.unreadCount || 0) + 1;
116
+ }
117
+ }
118
+ const content = (0, messages_1.normalizeMessageContent)(message.message);
119
+ // unarchive chat if it's a real message, or someone reacted to our message
120
+ // and we've the unarchive chats setting on
121
+ if ((isRealMsg || ((_b = (_a = content === null || content === void 0 ? void 0 : content.reactionMessage) === null || _a === void 0 ? void 0 : _a.key) === null || _b === void 0 ? void 0 : _b.fromMe))
122
+ && (accountSettings === null || accountSettings === void 0 ? void 0 : accountSettings.unarchiveChats)) {
123
+ chat.archived = false;
124
+ chat.readOnly = false;
125
+ }
126
+ const protocolMsg = content === null || content === void 0 ? void 0 : content.protocolMessage;
127
+ if (protocolMsg) {
128
+ switch (protocolMsg.type) {
129
+ case WAProto_1.proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION:
130
+ const histNotification = protocolMsg.historySyncNotification;
131
+ const process = shouldProcessHistoryMsg;
132
+ const isLatest = !((_c = creds.processedHistoryMessages) === null || _c === void 0 ? void 0 : _c.length);
133
+ logger === null || logger === void 0 ? void 0 : logger.info({
134
+ histNotification,
135
+ process,
136
+ id: message.key.id,
137
+ isLatest,
138
+ }, 'got history notification');
139
+ if (process) {
140
+ ev.emit('creds.update', {
141
+ processedHistoryMessages: [
142
+ ...(creds.processedHistoryMessages || []),
143
+ { key: message.key, messageTimestamp: message.messageTimestamp }
144
+ ]
145
+ });
146
+ const data = await (0, history_1.downloadAndProcessHistorySyncNotification)(histNotification, options);
147
+ ev.emit('messaging-history.set', { ...data, isLatest });
148
+ }
149
+ break;
150
+ case WAProto_1.proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE:
151
+ const keys = protocolMsg.appStateSyncKeyShare.keys;
152
+ if (keys === null || keys === void 0 ? void 0 : keys.length) {
153
+ let newAppStateSyncKeyId = '';
154
+ await keyStore.transaction(async () => {
155
+ const newKeys = [];
156
+ for (const { keyData, keyId } of keys) {
157
+ const strKeyId = Buffer.from(keyId.keyId).toString('base64');
158
+ newKeys.push(strKeyId);
159
+ await keyStore.set({ 'app-state-sync-key': { [strKeyId]: keyData } });
160
+ newAppStateSyncKeyId = strKeyId;
161
+ }
162
+ logger === null || logger === void 0 ? void 0 : logger.info({ newAppStateSyncKeyId, newKeys }, 'injecting new app state sync keys');
163
+ });
164
+ ev.emit('creds.update', { myAppStateKeyId: newAppStateSyncKeyId });
165
+ }
166
+ else {
167
+ logger === null || logger === void 0 ? void 0 : logger.info({ protocolMsg }, 'recv app state sync with 0 keys');
168
+ }
169
+ break;
170
+ case WAProto_1.proto.Message.ProtocolMessage.Type.REVOKE:
171
+ ev.emit('messages.update', [
172
+ {
173
+ key: {
174
+ ...message.key,
175
+ id: protocolMsg.key.id
176
+ },
177
+ update: { message: null, messageStubType: Types_1.WAMessageStubType.REVOKE, key: message.key }
178
+ }
179
+ ]);
180
+ break;
181
+ case WAProto_1.proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING:
182
+ Object.assign(chat, {
183
+ ephemeralSettingTimestamp: (0, generics_1.toNumber)(message.messageTimestamp),
184
+ ephemeralExpiration: protocolMsg.ephemeralExpiration || null
185
+ });
186
+ break;
187
+ case WAProto_1.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE:
188
+ const response = protocolMsg.peerDataOperationRequestResponseMessage;
189
+ if (response) {
190
+ const { peerDataOperationResult } = response;
191
+ for (const result of peerDataOperationResult) {
192
+ const { placeholderMessageResendResponse: retryResponse } = result;
193
+ if (retryResponse) {
194
+ const webMessageInfo = WAProto_1.proto.WebMessageInfo.decode(retryResponse.webMessageInfoBytes);
195
+ ev.emit('messages.update', [
196
+ { key: webMessageInfo.key, update: { message: webMessageInfo.message } }
197
+ ]);
198
+ }
199
+ }
200
+ }
201
+ break;
202
+ }
203
+ }
204
+ else if (content === null || content === void 0 ? void 0 : content.reactionMessage) {
205
+ const reaction = {
206
+ ...content.reactionMessage,
207
+ key: message.key,
208
+ };
209
+ ev.emit('messages.reaction', [{
210
+ reaction,
211
+ key: content.reactionMessage.key,
212
+ }]);
213
+ }
214
+ else if (message.messageStubType) {
215
+ const jid = message.key.remoteJid;
216
+ //let actor = whatsappID (message.participant)
217
+ let participants;
218
+ const emitParticipantsUpdate = (action) => (ev.emit('group-participants.update', { id: jid, author: message.participant, participants, action }));
219
+ const emitGroupUpdate = (update) => {
220
+ var _a;
221
+ ev.emit('groups.update', [{ id: jid, ...update, author: (_a = message.participant) !== null && _a !== void 0 ? _a : undefined }]);
222
+ };
223
+ const participantsIncludesMe = () => participants.find(jid => (0, WABinary_1.areJidsSameUser)(meId, jid));
224
+ switch (message.messageStubType) {
225
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_LEAVE:
226
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_REMOVE:
227
+ participants = message.messageStubParameters || [];
228
+ emitParticipantsUpdate('remove');
229
+ // mark the chat read only if you left the group
230
+ if (participantsIncludesMe()) {
231
+ chat.readOnly = true;
232
+ }
233
+ break;
234
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_ADD:
235
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_INVITE:
236
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:
237
+ participants = message.messageStubParameters || [];
238
+ if (participantsIncludesMe()) {
239
+ chat.readOnly = false;
240
+ }
241
+ emitParticipantsUpdate('add');
242
+ break;
243
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_DEMOTE:
244
+ participants = message.messageStubParameters || [];
245
+ emitParticipantsUpdate('demote');
246
+ break;
247
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_PROMOTE:
248
+ participants = message.messageStubParameters || [];
249
+ emitParticipantsUpdate('promote');
250
+ break;
251
+ case Types_1.WAMessageStubType.GROUP_CHANGE_ANNOUNCE:
252
+ const announceValue = (_d = message.messageStubParameters) === null || _d === void 0 ? void 0 : _d[0];
253
+ emitGroupUpdate({ announce: announceValue === 'true' || announceValue === 'on' });
254
+ break;
255
+ case Types_1.WAMessageStubType.GROUP_CHANGE_RESTRICT:
256
+ const restrictValue = (_e = message.messageStubParameters) === null || _e === void 0 ? void 0 : _e[0];
257
+ emitGroupUpdate({ restrict: restrictValue === 'true' || restrictValue === 'on' });
258
+ break;
259
+ case Types_1.WAMessageStubType.GROUP_CHANGE_SUBJECT:
260
+ const name = (_f = message.messageStubParameters) === null || _f === void 0 ? void 0 : _f[0];
261
+ chat.name = name;
262
+ emitGroupUpdate({ subject: name });
263
+ break;
264
+ case Types_1.WAMessageStubType.GROUP_CHANGE_INVITE_LINK:
265
+ const code = (_g = message.messageStubParameters) === null || _g === void 0 ? void 0 : _g[0];
266
+ emitGroupUpdate({ inviteCode: code });
267
+ break;
268
+ case Types_1.WAMessageStubType.GROUP_MEMBER_ADD_MODE:
269
+ const memberAddValue = (_h = message.messageStubParameters) === null || _h === void 0 ? void 0 : _h[0];
270
+ emitGroupUpdate({ memberAddMode: memberAddValue === 'all_member_add' });
271
+ break;
272
+ case Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE:
273
+ const approvalMode = (_j = message.messageStubParameters) === null || _j === void 0 ? void 0 : _j[0];
274
+ emitGroupUpdate({ joinApprovalMode: approvalMode === 'on' });
275
+ break;
276
+ }
277
+ }
278
+ else if (content === null || content === void 0 ? void 0 : content.pollUpdateMessage) {
279
+ const creationMsgKey = content.pollUpdateMessage.pollCreationMessageKey;
280
+ // we need to fetch the poll creation message to get the poll enc key
281
+ const pollMsg = await getMessage(creationMsgKey);
282
+ if (pollMsg) {
283
+ const meIdNormalised = (0, WABinary_1.jidNormalizedUser)(meId);
284
+ const pollCreatorJid = (0, generics_1.getKeyAuthor)(creationMsgKey, meIdNormalised);
285
+ const voterJid = (0, generics_1.getKeyAuthor)(message.key, meIdNormalised);
286
+ const pollEncKey = (_k = pollMsg.messageContextInfo) === null || _k === void 0 ? void 0 : _k.messageSecret;
287
+ try {
288
+ const voteMsg = decryptPollVote(content.pollUpdateMessage.vote, {
289
+ pollEncKey,
290
+ pollCreatorJid,
291
+ pollMsgId: creationMsgKey.id,
292
+ voterJid,
293
+ });
294
+ ev.emit('messages.update', [
295
+ {
296
+ key: creationMsgKey,
297
+ update: {
298
+ pollUpdates: [
299
+ {
300
+ pollUpdateMessageKey: message.key,
301
+ vote: voteMsg,
302
+ senderTimestampMs: content.pollUpdateMessage.senderTimestampMs.toNumber(),
303
+ }
304
+ ]
305
+ }
306
+ }
307
+ ]);
308
+ }
309
+ catch (err) {
310
+ logger === null || logger === void 0 ? void 0 : logger.warn({ err, creationMsgKey }, 'failed to decrypt poll vote');
311
+ }
312
+ }
313
+ else {
314
+ logger === null || logger === void 0 ? void 0 : logger.warn({ creationMsgKey }, 'poll creation message not found, cannot decrypt update');
315
+ }
316
+ }
317
+ if (Object.keys(chat).length > 1) {
318
+ ev.emit('chats.update', [chat]);
319
+ }
320
+ };
321
+ exports.default = processMessage;
@@ -0,0 +1,33 @@
1
+ import { SignalRepository } from '../Types';
2
+ import { AuthenticationCreds, AuthenticationState, KeyPair, SignalIdentity, SignalKeyStore, SignedKeyPair } from '../Types/Auth';
3
+ import { BinaryNode, JidWithDevice } from '../WABinary';
4
+ import { USyncQueryResultList } from '../WAUSync';
5
+ export declare const createSignalIdentity: (wid: string, accountSignatureKey: Uint8Array) => SignalIdentity;
6
+ export declare const getPreKeys: ({ get }: SignalKeyStore, min: number, limit: number) => Promise<{
7
+ [id: string]: KeyPair;
8
+ }>;
9
+ export declare const generateOrGetPreKeys: (creds: AuthenticationCreds, range: number) => {
10
+ newPreKeys: {
11
+ [id: number]: KeyPair;
12
+ };
13
+ lastPreKeyId: number;
14
+ preKeysRange: readonly [number, number];
15
+ };
16
+ export declare const xmppSignedPreKey: (key: SignedKeyPair) => BinaryNode;
17
+ export declare const xmppPreKey: (pair: KeyPair, id: number) => BinaryNode;
18
+ export declare const parseAndInjectE2ESessions: (node: BinaryNode, repository: SignalRepository) => Promise<void>;
19
+ export declare const extractDeviceJids: (result: USyncQueryResultList[], myJid: string, excludeZeroDevices: boolean) => JidWithDevice[];
20
+ /**
21
+ * get the next N keys for upload or processing
22
+ * @param count number of pre-keys to get or generate
23
+ */
24
+ export declare const getNextPreKeys: ({ creds, keys }: AuthenticationState, count: number) => Promise<{
25
+ update: Partial<AuthenticationCreds>;
26
+ preKeys: {
27
+ [id: string]: KeyPair;
28
+ };
29
+ }>;
30
+ export declare const getNextPreKeysNode: (state: AuthenticationState, count: number) => Promise<{
31
+ update: Partial<AuthenticationCreds>;
32
+ node: BinaryNode;
33
+ }>;