@mihiranga_mihiranga/mezuka-baileys 1.0.2

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 (114) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +651 -0
  3. package/WAProto/GenerateStatics.sh +4 -0
  4. package/WAProto/WAProto.proto +4775 -0
  5. package/WAProto/index.js +169661 -0
  6. package/WAProto//342/235/244/357/270/217 +1 -0
  7. package/engine-requirements.js +10 -0
  8. package/lib/Defaults/baileys-version.json +3 -0
  9. package/lib/Defaults/index.js +112 -0
  10. package/lib/Defaults/phonenumber-mcc.json +223 -0
  11. package/lib/Defaults//360/237/222/226 +1 -0
  12. package/lib/Signal/Group/ciphertext-message.js +15 -0
  13. package/lib/Signal/Group/group-session-builder.js +64 -0
  14. package/lib/Signal/Group/group_cipher.js +96 -0
  15. package/lib/Signal/Group/index.js +57 -0
  16. package/lib/Signal/Group/keyhelper.js +55 -0
  17. package/lib/Signal/Group/queue-job.js +57 -0
  18. package/lib/Signal/Group/sender-chain-key.js +34 -0
  19. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  20. package/lib/Signal/Group/sender-key-message.js +69 -0
  21. package/lib/Signal/Group/sender-key-name.js +51 -0
  22. package/lib/Signal/Group/sender-key-record.js +53 -0
  23. package/lib/Signal/Group/sender-key-state.js +99 -0
  24. package/lib/Signal/Group/sender-message-key.js +29 -0
  25. package/lib/Signal/Group//342/235/244/357/270/217 +1 -0
  26. package/lib/Signal/libsignal.js +174 -0
  27. package/lib/Signal//360/237/222/226 +1 -0
  28. package/lib/Socket/Client/index.js +18 -0
  29. package/lib/Socket/Client/types.js +13 -0
  30. package/lib/Socket/Client/websocket.js +72 -0
  31. package/lib/Socket/Client//342/235/244/357/270/217 +1 -0
  32. package/lib/Socket/business.js +260 -0
  33. package/lib/Socket/chats.js +890 -0
  34. package/lib/Socket/groups.js +332 -0
  35. package/lib/Socket/index.js +10 -0
  36. package/lib/Socket/messages-recv.js +1142 -0
  37. package/lib/Socket/messages-send.js +1068 -0
  38. package/lib/Socket/newsletter.js +250 -0
  39. package/lib/Socket/socket.js +654 -0
  40. package/lib/Socket/usync.js +70 -0
  41. package/lib/Socket//360/237/222/236 +1 -0
  42. package/lib/Store/index.js +8 -0
  43. package/lib/Store/make-in-memory-store.js +429 -0
  44. package/lib/Store/make-ordered-dictionary.js +81 -0
  45. package/lib/Store/object-repository.js +27 -0
  46. package/lib/Store//342/235/244/357/270/217 +1 -0
  47. package/lib/Types/Auth.js +2 -0
  48. package/lib/Types/Call.js +2 -0
  49. package/lib/Types/Chat.js +4 -0
  50. package/lib/Types/Contact.js +2 -0
  51. package/lib/Types/Events.js +2 -0
  52. package/lib/Types/GroupMetadata.js +2 -0
  53. package/lib/Types/Label.js +27 -0
  54. package/lib/Types/LabelAssociation.js +9 -0
  55. package/lib/Types/Message.js +7 -0
  56. package/lib/Types/Newsletter.js +18 -0
  57. package/lib/Types/Product.js +2 -0
  58. package/lib/Types/Signal.js +2 -0
  59. package/lib/Types/Socket.js +2 -0
  60. package/lib/Types/State.js +2 -0
  61. package/lib/Types/USync.js +2 -0
  62. package/lib/Types/index.js +42 -0
  63. package/lib/Types//360/237/222/236 +1 -0
  64. package/lib/Utils/auth-utils.js +199 -0
  65. package/lib/Utils/baileys-event-stream.js +63 -0
  66. package/lib/Utils/browser-utils.js +35 -0
  67. package/lib/Utils/business.js +234 -0
  68. package/lib/Utils/chat-utils.js +730 -0
  69. package/lib/Utils/crypto.js +193 -0
  70. package/lib/Utils/decode-wa-message.js +207 -0
  71. package/lib/Utils/event-buffer.js +518 -0
  72. package/lib/Utils/generics.js +473 -0
  73. package/lib/Utils/history.js +95 -0
  74. package/lib/Utils/index.js +33 -0
  75. package/lib/Utils/link-preview.js +126 -0
  76. package/lib/Utils/logger.js +7 -0
  77. package/lib/Utils/lt-hash.js +51 -0
  78. package/lib/Utils/make-mutex.js +43 -0
  79. package/lib/Utils/messages-media.js +880 -0
  80. package/lib/Utils/messages.js +1154 -0
  81. package/lib/Utils/noise-handler.js +150 -0
  82. package/lib/Utils/process-message.js +372 -0
  83. package/lib/Utils/signal.js +153 -0
  84. package/lib/Utils/use-multi-file-auth-state.js +125 -0
  85. package/lib/Utils/validate-connection.js +199 -0
  86. package/lib/Utils//342/235/244/357/270/217 +1 -0
  87. package/lib/WABinary/constants.js +1303 -0
  88. package/lib/WABinary/decode.js +265 -0
  89. package/lib/WABinary/encode.js +250 -0
  90. package/lib/WABinary/generic-utils.js +130 -0
  91. package/lib/WABinary/index.js +21 -0
  92. package/lib/WABinary/jid-utils.js +83 -0
  93. package/lib/WABinary/types.js +2 -0
  94. package/lib/WABinary//360/237/222/226 +1 -0
  95. package/lib/WAM/BinaryInfo.js +13 -0
  96. package/lib/WAM/constants.js +15350 -0
  97. package/lib/WAM/encode.js +155 -0
  98. package/lib/WAM/index.js +19 -0
  99. package/lib/WAM//360/237/222/226 +1 -0
  100. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  101. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  102. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  103. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  104. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  105. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  106. package/lib/WAUSync/Protocols/index.js +20 -0
  107. package/lib/WAUSync/Protocols//342/235/244/357/270/217 +1 -0
  108. package/lib/WAUSync/USyncQuery.js +89 -0
  109. package/lib/WAUSync/USyncUser.js +26 -0
  110. package/lib/WAUSync/index.js +19 -0
  111. package/lib/WAUSync//360/237/222/226 +1 -0
  112. package/lib/index.js +45 -0
  113. package/lib//360/237/222/226 +1 -0
  114. package/package.json +121 -0
@@ -0,0 +1,150 @@
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, 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 = async (data) => {
42
+ const key = await (0, crypto_1.hkdf)(Buffer.from(data), 64, { salt, info: '' });
43
+ return [key.slice(0, 32), key.slice(32)];
44
+ };
45
+ const mixIntoKey = async (data) => {
46
+ const [write, read] = await localHKDF(data);
47
+ salt = write;
48
+ encKey = read;
49
+ decKey = read;
50
+ readCounter = 0;
51
+ writeCounter = 0;
52
+ };
53
+ const finishInit = async () => {
54
+ const [write, read] = await 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 = 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: async ({ serverHello }, noiseKey) => {
81
+ authenticate(serverHello.ephemeral);
82
+ await mixIntoKey(crypto_1.Curve.sharedKey(privateKey, serverHello.ephemeral));
83
+ const decStaticContent = decrypt(serverHello.static);
84
+ await mixIntoKey(crypto_1.Curve.sharedKey(privateKey, decStaticContent));
85
+ const certDecoded = decrypt(serverHello.payload);
86
+ const { intermediate: certIntermediate } = WAProto_1.proto.CertChain.decode(certDecoded);
87
+ const { issuerSerial } = WAProto_1.proto.CertChain.NoiseCertificate.Details.decode(certIntermediate.details);
88
+ if (issuerSerial !== Defaults_1.WA_CERT_DETAILS.SERIAL) {
89
+ throw new boom_1.Boom('certification match failed', { statusCode: 400 });
90
+ }
91
+ const keyEnc = encrypt(noiseKey.public);
92
+ await mixIntoKey(crypto_1.Curve.sharedKey(noiseKey.private, serverHello.ephemeral));
93
+ return keyEnc;
94
+ },
95
+ encodeFrame: (data) => {
96
+ if (isFinished) {
97
+ data = encrypt(data);
98
+ }
99
+ let header;
100
+ if (routingInfo) {
101
+ header = Buffer.alloc(7);
102
+ header.write('ED', 0, 'utf8');
103
+ header.writeUint8(0, 2);
104
+ header.writeUint8(1, 3);
105
+ header.writeUint8(routingInfo.byteLength >> 16, 4);
106
+ header.writeUint16BE(routingInfo.byteLength & 65535, 5);
107
+ header = Buffer.concat([header, routingInfo, NOISE_HEADER]);
108
+ }
109
+ else {
110
+ header = Buffer.from(NOISE_HEADER);
111
+ }
112
+ const introSize = sentIntro ? 0 : header.length;
113
+ const frame = Buffer.alloc(introSize + 3 + data.byteLength);
114
+ if (!sentIntro) {
115
+ frame.set(header);
116
+ sentIntro = true;
117
+ }
118
+ frame.writeUInt8(data.byteLength >> 16, introSize);
119
+ frame.writeUInt16BE(65535 & data.byteLength, introSize + 1);
120
+ frame.set(data, introSize + 3);
121
+ return frame;
122
+ },
123
+ decodeFrame: async (newData, onFrame) => {
124
+ var _a;
125
+ // the binary protocol uses its own framing mechanism
126
+ // on top of the WS frames
127
+ // so we get this data and separate out the frames
128
+ const getBytesSize = () => {
129
+ if (inBytes.length >= 3) {
130
+ return (inBytes.readUInt8() << 16) | inBytes.readUInt16BE(1);
131
+ }
132
+ };
133
+ inBytes = Buffer.concat([inBytes, newData]);
134
+ logger.trace(`recv ${newData.length} bytes, total recv ${inBytes.length} bytes`);
135
+ let size = getBytesSize();
136
+ while (size && inBytes.length >= size + 3) {
137
+ let frame = inBytes.slice(3, size + 3);
138
+ inBytes = inBytes.slice(size + 3);
139
+ if (isFinished) {
140
+ const result = decrypt(frame);
141
+ frame = await (0, WABinary_1.decodeBinaryNode)(result);
142
+ }
143
+ logger.trace({ msg: (_a = frame === null || frame === void 0 ? void 0 : frame.attrs) === null || _a === void 0 ? void 0 : _a.id }, 'recv frame');
144
+ onFrame(frame);
145
+ size = getBytesSize();
146
+ }
147
+ }
148
+ };
149
+ };
150
+ exports.makeNoiseHandler = makeNoiseHandler;
@@ -0,0 +1,372 @@
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, placeholderResendCache, ev, creds, keyStore, logger, options, getMessage }) => {
106
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s;
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.messages = [{ message }];
113
+ chat.conversationTimestamp = (0, generics_1.toNumber)(message.messageTimestamp);
114
+ // only increment unread count if not CIPHERTEXT and from another person
115
+ if ((0, exports.shouldIncrementChatUnread)(message)) {
116
+ chat.unreadCount = (chat.unreadCount || 0) + 1;
117
+ }
118
+ }
119
+ const content = (0, messages_1.normalizeMessageContent)(message.message);
120
+ // unarchive chat if it's a real message, or someone reacted to our message
121
+ // and we've the unarchive chats setting on
122
+ 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))
123
+ && (accountSettings === null || accountSettings === void 0 ? void 0 : accountSettings.unarchiveChats)) {
124
+ chat.archived = false;
125
+ chat.readOnly = false;
126
+ }
127
+ const protocolMsg = content === null || content === void 0 ? void 0 : content.protocolMessage;
128
+ if (protocolMsg) {
129
+ switch (protocolMsg.type) {
130
+ case WAProto_1.proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION:
131
+ const histNotification = protocolMsg.historySyncNotification;
132
+ const process = shouldProcessHistoryMsg;
133
+ const isLatest = !((_c = creds.processedHistoryMessages) === null || _c === void 0 ? void 0 : _c.length);
134
+ logger === null || logger === void 0 ? void 0 : logger.info({
135
+ histNotification,
136
+ process,
137
+ id: message.key.id,
138
+ isLatest,
139
+ }, 'got history notification');
140
+ if (process) {
141
+ if (histNotification.syncType !== WAProto_1.proto.HistorySync.HistorySyncType.ON_DEMAND) {
142
+ ev.emit('creds.update', {
143
+ processedHistoryMessages: [
144
+ ...(creds.processedHistoryMessages || []),
145
+ { key: message.key, messageTimestamp: message.messageTimestamp }
146
+ ]
147
+ });
148
+ }
149
+ const data = await (0, history_1.downloadAndProcessHistorySyncNotification)(histNotification, options);
150
+ ev.emit('messaging-history.set', {
151
+ ...data,
152
+ isLatest: histNotification.syncType !== WAProto_1.proto.HistorySync.HistorySyncType.ON_DEMAND
153
+ ? isLatest
154
+ : undefined,
155
+ peerDataRequestSessionId: histNotification.peerDataRequestSessionId
156
+ });
157
+ }
158
+ break;
159
+ case WAProto_1.proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE:
160
+ const keys = protocolMsg.appStateSyncKeyShare.keys;
161
+ if (keys === null || keys === void 0 ? void 0 : keys.length) {
162
+ let newAppStateSyncKeyId = '';
163
+ await keyStore.transaction(async () => {
164
+ const newKeys = [];
165
+ for (const { keyData, keyId } of keys) {
166
+ const strKeyId = Buffer.from(keyId.keyId).toString('base64');
167
+ newKeys.push(strKeyId);
168
+ await keyStore.set({ 'app-state-sync-key': { [strKeyId]: keyData } });
169
+ newAppStateSyncKeyId = strKeyId;
170
+ }
171
+ logger === null || logger === void 0 ? void 0 : logger.info({ newAppStateSyncKeyId, newKeys }, 'injecting new app state sync keys');
172
+ });
173
+ ev.emit('creds.update', { myAppStateKeyId: newAppStateSyncKeyId });
174
+ }
175
+ else {
176
+ logger === null || logger === void 0 ? void 0 : logger.info({ protocolMsg }, 'recv app state sync with 0 keys');
177
+ }
178
+ break;
179
+ case WAProto_1.proto.Message.ProtocolMessage.Type.REVOKE:
180
+ ev.emit('messages.update', [
181
+ {
182
+ key: {
183
+ ...message.key,
184
+ id: protocolMsg.key.id
185
+ },
186
+ update: { message: null, messageStubType: Types_1.WAMessageStubType.REVOKE, key: message.key }
187
+ }
188
+ ]);
189
+ break;
190
+ case WAProto_1.proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING:
191
+ Object.assign(chat, {
192
+ ephemeralSettingTimestamp: (0, generics_1.toNumber)(message.messageTimestamp),
193
+ ephemeralExpiration: protocolMsg.ephemeralExpiration || null
194
+ });
195
+ break;
196
+ case WAProto_1.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE:
197
+ const response = protocolMsg.peerDataOperationRequestResponseMessage;
198
+ if (response) {
199
+ placeholderResendCache === null || placeholderResendCache === void 0 ? void 0 : placeholderResendCache.del(response.stanzaId);
200
+ // TODO: IMPLEMENT HISTORY SYNC ETC (sticker uploads etc.).
201
+ const { peerDataOperationResult } = response;
202
+ for (const result of peerDataOperationResult) {
203
+ const { placeholderMessageResendResponse: retryResponse } = result;
204
+ if (retryResponse) {
205
+ const webMessageInfo = WAProto_1.proto.WebMessageInfo.decode(retryResponse.webMessageInfoBytes);
206
+ // wait till another upsert event is available, don't want it to be part of the PDO response message
207
+ setTimeout(() => {
208
+ ev.emit('messages.upsert', {
209
+ messages: [webMessageInfo],
210
+ type: 'notify',
211
+ requestId: response.stanzaId
212
+ });
213
+ }, 500);
214
+ }
215
+ }
216
+ }
217
+ case WAProto_1.proto.Message.ProtocolMessage.Type.MESSAGE_EDIT:
218
+ ev.emit('messages.update', [
219
+ {
220
+ // flip the sender / fromMe properties because they're in the perspective of the sender
221
+ key: { ...message.key, id: (_d = protocolMsg.key) === null || _d === void 0 ? void 0 : _d.id },
222
+ update: {
223
+ message: {
224
+ editedMessage: {
225
+ message: protocolMsg.editedMessage
226
+ }
227
+ },
228
+ messageTimestamp: protocolMsg.timestampMs
229
+ ? Math.floor((0, generics_1.toNumber)(protocolMsg.timestampMs) / 1000)
230
+ : message.messageTimestamp
231
+ }
232
+ }
233
+ ]);
234
+ break;
235
+ }
236
+ }
237
+ else if (content === null || content === void 0 ? void 0 : content.reactionMessage) {
238
+ const reaction = {
239
+ ...content.reactionMessage,
240
+ key: message.key,
241
+ };
242
+ ev.emit('messages.reaction', [{
243
+ reaction,
244
+ key: (_e = content.reactionMessage) === null || _e === void 0 ? void 0 : _e.key,
245
+ }]);
246
+ }
247
+ else if (message.messageStubType) {
248
+ const jid = (_f = message.key) === null || _f === void 0 ? void 0 : _f.remoteJid;
249
+ //let actor = whatsappID (message.participant)
250
+ let participants;
251
+ const emitParticipantsUpdate = (action) => (ev.emit('group-participants.update', { id: jid, author: message.participant, participants, action }));
252
+ const emitGroupUpdate = (update) => {
253
+ var _a;
254
+ ev.emit('groups.update', [{ id: jid, ...update, author: (_a = message.participant) !== null && _a !== void 0 ? _a : undefined }]);
255
+ };
256
+ const emitGroupRequestJoin = (participant, action, method) => {
257
+ ev.emit('group.join-request', { id: jid, author: message.participant, participant, action, method: method });
258
+ };
259
+ const participantsIncludesMe = () => participants.find(jid => (0, WABinary_1.areJidsSameUser)(meId, jid));
260
+ switch (message.messageStubType) {
261
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER:
262
+ participants = message.messageStubParameters || [];
263
+ emitParticipantsUpdate('modify');
264
+ break;
265
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_LEAVE:
266
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_REMOVE:
267
+ participants = message.messageStubParameters || [];
268
+ emitParticipantsUpdate('remove');
269
+ // mark the chat read only if you left the group
270
+ if (participantsIncludesMe()) {
271
+ chat.readOnly = true;
272
+ }
273
+ break;
274
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_ADD:
275
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_INVITE:
276
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:
277
+ participants = message.messageStubParameters || [];
278
+ if (participantsIncludesMe()) {
279
+ chat.readOnly = false;
280
+ }
281
+ emitParticipantsUpdate('add');
282
+ break;
283
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_DEMOTE:
284
+ participants = message.messageStubParameters || [];
285
+ emitParticipantsUpdate('demote');
286
+ break;
287
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_PROMOTE:
288
+ participants = message.messageStubParameters || [];
289
+ emitParticipantsUpdate('promote');
290
+ break;
291
+ case Types_1.WAMessageStubType.GROUP_CHANGE_ANNOUNCE:
292
+ const announceValue = (_g = message.messageStubParameters) === null || _g === void 0 ? void 0 : _g[0];
293
+ emitGroupUpdate({ announce: announceValue === 'true' || announceValue === 'on' });
294
+ break;
295
+ case Types_1.WAMessageStubType.GROUP_CHANGE_RESTRICT:
296
+ const restrictValue = (_h = message.messageStubParameters) === null || _h === void 0 ? void 0 : _h[0];
297
+ emitGroupUpdate({ restrict: restrictValue === 'true' || restrictValue === 'on' });
298
+ break;
299
+ case Types_1.WAMessageStubType.GROUP_CHANGE_SUBJECT:
300
+ const name = (_j = message.messageStubParameters) === null || _j === void 0 ? void 0 : _j[0];
301
+ chat.name = name;
302
+ emitGroupUpdate({ subject: name });
303
+ break;
304
+ case Types_1.WAMessageStubType.GROUP_CHANGE_DESCRIPTION:
305
+ const description = (_k = message.messageStubParameters) === null || _k === void 0 ? void 0 : _k[0];
306
+ chat.description = description;
307
+ emitGroupUpdate({ desc: description });
308
+ break;
309
+ case Types_1.WAMessageStubType.GROUP_CHANGE_INVITE_LINK:
310
+ const code = (_l = message.messageStubParameters) === null || _l === void 0 ? void 0 : _l[0];
311
+ emitGroupUpdate({ inviteCode: code });
312
+ break;
313
+ case Types_1.WAMessageStubType.GROUP_MEMBER_ADD_MODE:
314
+ const memberAddValue = (_m = message.messageStubParameters) === null || _m === void 0 ? void 0 : _m[0];
315
+ emitGroupUpdate({ memberAddMode: memberAddValue === 'all_member_add' });
316
+ break;
317
+ case Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE:
318
+ const approvalMode = (_o = message.messageStubParameters) === null || _o === void 0 ? void 0 : _o[0];
319
+ emitGroupUpdate({ joinApprovalMode: approvalMode === 'on' });
320
+ break;
321
+ case Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD:
322
+ const participant = (_p = message.messageStubParameters) === null || _p === void 0 ? void 0 : _p[0];
323
+ const action = (_q = message.messageStubParameters) === null || _q === void 0 ? void 0 : _q[1];
324
+ const method = (_r = message.messageStubParameters) === null || _r === void 0 ? void 0 : _r[2];
325
+ emitGroupRequestJoin(participant, action, method);
326
+ break;
327
+ }
328
+ }
329
+ else if (content === null || content === void 0 ? void 0 : content.pollUpdateMessage) {
330
+ const creationMsgKey = content.pollUpdateMessage.pollCreationMessageKey;
331
+ // we need to fetch the poll creation message to get the poll enc key
332
+ const pollMsg = await getMessage(creationMsgKey);
333
+ if (pollMsg) {
334
+ const meIdNormalised = (0, WABinary_1.jidNormalizedUser)(meId);
335
+ const pollCreatorJid = (0, generics_1.getKeyAuthor)(creationMsgKey, meIdNormalised);
336
+ const voterJid = (0, generics_1.getKeyAuthor)(message.key, meIdNormalised);
337
+ const pollEncKey = (_s = pollMsg.messageContextInfo) === null || _s === void 0 ? void 0 : _s.messageSecret;
338
+ try {
339
+ const voteMsg = decryptPollVote(content.pollUpdateMessage.vote, {
340
+ pollEncKey,
341
+ pollCreatorJid,
342
+ pollMsgId: creationMsgKey.id,
343
+ voterJid,
344
+ });
345
+ ev.emit('messages.update', [
346
+ {
347
+ key: creationMsgKey,
348
+ update: {
349
+ pollUpdates: [
350
+ {
351
+ pollUpdateMessageKey: message.key,
352
+ vote: voteMsg,
353
+ senderTimestampMs: content.pollUpdateMessage.senderTimestampMs.toNumber(),
354
+ }
355
+ ]
356
+ }
357
+ }
358
+ ]);
359
+ }
360
+ catch (err) {
361
+ logger === null || logger === void 0 ? void 0 : logger.warn({ err, creationMsgKey }, 'failed to decrypt poll vote');
362
+ }
363
+ }
364
+ else {
365
+ logger === null || logger === void 0 ? void 0 : logger.warn({ creationMsgKey }, 'poll creation message not found, cannot decrypt update');
366
+ }
367
+ }
368
+ if (Object.keys(chat).length > 1) {
369
+ ev.emit('chats.update', [chat]);
370
+ }
371
+ };
372
+ exports.default = processMessage;
@@ -0,0 +1,153 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getNextPreKeysNode = exports.getNextPreKeys = exports.extractDeviceJids = exports.parseAndInjectE2ESessions = exports.xmppPreKey = exports.xmppSignedPreKey = exports.generateOrGetPreKeys = exports.getPreKeys = exports.createSignalIdentity = void 0;
4
+ const lodash_1 = require("lodash");
5
+ const Defaults_1 = require("../Defaults");
6
+ const WABinary_1 = require("../WABinary");
7
+ const crypto_1 = require("./crypto");
8
+ const generics_1 = require("./generics");
9
+ const createSignalIdentity = (wid, accountSignatureKey) => {
10
+ return {
11
+ identifier: { name: wid, deviceId: 0 },
12
+ identifierKey: (0, crypto_1.generateSignalPubKey)(accountSignatureKey)
13
+ };
14
+ };
15
+ exports.createSignalIdentity = createSignalIdentity;
16
+ const getPreKeys = async ({ get }, min, limit) => {
17
+ const idList = [];
18
+ for (let id = min; id < limit; id++) {
19
+ idList.push(id.toString());
20
+ }
21
+ return get('pre-key', idList);
22
+ };
23
+ exports.getPreKeys = getPreKeys;
24
+ const generateOrGetPreKeys = (creds, range) => {
25
+ const avaliable = creds.nextPreKeyId - creds.firstUnuploadedPreKeyId;
26
+ const remaining = range - avaliable;
27
+ const lastPreKeyId = creds.nextPreKeyId + remaining - 1;
28
+ const newPreKeys = {};
29
+ if (remaining > 0) {
30
+ for (let i = creds.nextPreKeyId; i <= lastPreKeyId; i++) {
31
+ newPreKeys[i] = crypto_1.Curve.generateKeyPair();
32
+ }
33
+ }
34
+ return {
35
+ newPreKeys,
36
+ lastPreKeyId,
37
+ preKeysRange: [creds.firstUnuploadedPreKeyId, range],
38
+ };
39
+ };
40
+ exports.generateOrGetPreKeys = generateOrGetPreKeys;
41
+ const xmppSignedPreKey = (key) => ({
42
+ tag: 'skey',
43
+ attrs: {},
44
+ content: [
45
+ { tag: 'id', attrs: {}, content: (0, generics_1.encodeBigEndian)(key.keyId, 3) },
46
+ { tag: 'value', attrs: {}, content: key.keyPair.public },
47
+ { tag: 'signature', attrs: {}, content: key.signature }
48
+ ]
49
+ });
50
+ exports.xmppSignedPreKey = xmppSignedPreKey;
51
+ const xmppPreKey = (pair, id) => ({
52
+ tag: 'key',
53
+ attrs: {},
54
+ content: [
55
+ { tag: 'id', attrs: {}, content: (0, generics_1.encodeBigEndian)(id, 3) },
56
+ { tag: 'value', attrs: {}, content: pair.public }
57
+ ]
58
+ });
59
+ exports.xmppPreKey = xmppPreKey;
60
+ const parseAndInjectE2ESessions = async (node, repository) => {
61
+ const extractKey = (key) => (key ? ({
62
+ keyId: (0, WABinary_1.getBinaryNodeChildUInt)(key, 'id', 3),
63
+ publicKey: (0, crypto_1.generateSignalPubKey)((0, WABinary_1.getBinaryNodeChildBuffer)(key, 'value')),
64
+ signature: (0, WABinary_1.getBinaryNodeChildBuffer)(key, 'signature'),
65
+ }) : undefined);
66
+ const nodes = (0, WABinary_1.getBinaryNodeChildren)((0, WABinary_1.getBinaryNodeChild)(node, 'list'), 'user');
67
+ for (const node of nodes) {
68
+ (0, WABinary_1.assertNodeErrorFree)(node);
69
+ }
70
+ // Most of the work in repository.injectE2ESession is CPU intensive, not IO
71
+ // So Promise.all doesn't really help here,
72
+ // but blocks even loop if we're using it inside keys.transaction, and it makes it "sync" actually
73
+ // This way we chunk it in smaller parts and between those parts we can yield to the event loop
74
+ // It's rare case when you need to E2E sessions for so many users, but it's possible
75
+ const chunkSize = 100;
76
+ const chunks = (0, lodash_1.chunk)(nodes, chunkSize);
77
+ for (const nodesChunk of chunks) {
78
+ await Promise.all(nodesChunk.map(async (node) => {
79
+ const signedKey = (0, WABinary_1.getBinaryNodeChild)(node, 'skey');
80
+ const key = (0, WABinary_1.getBinaryNodeChild)(node, 'key');
81
+ const identity = (0, WABinary_1.getBinaryNodeChildBuffer)(node, 'identity');
82
+ const jid = node.attrs.jid;
83
+ const registrationId = (0, WABinary_1.getBinaryNodeChildUInt)(node, 'registration', 4);
84
+ await repository.injectE2ESession({
85
+ jid,
86
+ session: {
87
+ registrationId: registrationId,
88
+ identityKey: (0, crypto_1.generateSignalPubKey)(identity),
89
+ signedPreKey: extractKey(signedKey),
90
+ preKey: extractKey(key)
91
+ }
92
+ });
93
+ }));
94
+ }
95
+ };
96
+ exports.parseAndInjectE2ESessions = parseAndInjectE2ESessions;
97
+ const extractDeviceJids = (result, myJid, excludeZeroDevices) => {
98
+ const { user: myUser, device: myDevice } = (0, WABinary_1.jidDecode)(myJid);
99
+ const extracted = [];
100
+ for (const userResult of result) {
101
+ const { devices, id } = userResult;
102
+ const { user } = (0, WABinary_1.jidDecode)(id);
103
+ const deviceList = devices === null || devices === void 0 ? void 0 : devices.deviceList;
104
+ if (Array.isArray(deviceList)) {
105
+ for (const { id: device, keyIndex } of deviceList) {
106
+ if ((!excludeZeroDevices || device !== 0) && // if zero devices are not-excluded, or device is non zero
107
+ (myUser !== user || myDevice !== device) && // either different user or if me user, not this device
108
+ (device === 0 || !!keyIndex) // ensure that "key-index" is specified for "non-zero" devices, produces a bad req otherwise
109
+ ) {
110
+ extracted.push({ user, device });
111
+ }
112
+ }
113
+ }
114
+ }
115
+ return extracted;
116
+ };
117
+ exports.extractDeviceJids = extractDeviceJids;
118
+ /**
119
+ * get the next N keys for upload or processing
120
+ * @param count number of pre-keys to get or generate
121
+ */
122
+ const getNextPreKeys = async ({ creds, keys }, count) => {
123
+ const { newPreKeys, lastPreKeyId, preKeysRange } = (0, exports.generateOrGetPreKeys)(creds, count);
124
+ const update = {
125
+ nextPreKeyId: Math.max(lastPreKeyId + 1, creds.nextPreKeyId),
126
+ firstUnuploadedPreKeyId: Math.max(creds.firstUnuploadedPreKeyId, lastPreKeyId + 1)
127
+ };
128
+ await keys.set({ 'pre-key': newPreKeys });
129
+ const preKeys = await (0, exports.getPreKeys)(keys, preKeysRange[0], preKeysRange[0] + preKeysRange[1]);
130
+ return { update, preKeys };
131
+ };
132
+ exports.getNextPreKeys = getNextPreKeys;
133
+ const getNextPreKeysNode = async (state, count) => {
134
+ const { creds } = state;
135
+ const { update, preKeys } = await (0, exports.getNextPreKeys)(state, count);
136
+ const node = {
137
+ tag: 'iq',
138
+ attrs: {
139
+ xmlns: 'encrypt',
140
+ type: 'set',
141
+ to: WABinary_1.S_WHATSAPP_NET,
142
+ },
143
+ content: [
144
+ { tag: 'registration', attrs: {}, content: (0, generics_1.encodeBigEndian)(creds.registrationId) },
145
+ { tag: 'type', attrs: {}, content: Defaults_1.KEY_BUNDLE_TYPE },
146
+ { tag: 'identity', attrs: {}, content: creds.signedIdentityKey.public },
147
+ { tag: 'list', attrs: {}, content: Object.keys(preKeys).map(k => (0, exports.xmppPreKey)(preKeys[+k], +k)) },
148
+ (0, exports.xmppSignedPreKey)(creds.signedPreKey)
149
+ ]
150
+ };
151
+ return { update, node };
152
+ };
153
+ exports.getNextPreKeysNode = getNextPreKeysNode;