@hbmodsofc/baileys 1.5.0 → 1.7.6

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 (156) hide show
  1. package/LICENSE +1 -1
  2. package/WAProto/index.js +19671 -152026
  3. package/engine-requirements.js +4 -4
  4. package/lib/Defaults/index.d.ts +12 -8
  5. package/lib/Defaults/index.js +90 -124
  6. package/lib/Signal/Group/group_cipher.d.ts +0 -1
  7. package/lib/Signal/Group/group_cipher.js +28 -39
  8. package/lib/Signal/Group/sender-chain-key.d.ts +1 -1
  9. package/lib/Signal/Group/sender-chain-key.js +9 -2
  10. package/lib/Signal/Group/sender-key-distribution-message.js +3 -3
  11. package/lib/Signal/Group/sender-key-message.js +3 -3
  12. package/lib/Signal/Group/sender-key-state.d.ts +4 -4
  13. package/lib/Signal/Group/sender-key-state.js +47 -16
  14. package/lib/Signal/libsignal.d.ts +7 -3
  15. package/lib/Signal/libsignal.js +224 -39
  16. package/lib/Signal/lid-mapping.d.ts +26 -0
  17. package/lib/Signal/lid-mapping.js +146 -0
  18. package/lib/Socket/Client/index.d.ts +2 -3
  19. package/lib/Socket/Client/index.js +2 -3
  20. package/lib/Socket/Client/{abstract-socket-client.d.ts → types.d.ts} +1 -3
  21. package/lib/Socket/Client/{web-socket-client.d.ts → websocket.d.ts} +1 -1
  22. package/lib/Socket/Client/{web-socket-client.js → websocket.js} +10 -16
  23. package/lib/Socket/business.d.ts +94 -78
  24. package/lib/Socket/business.js +130 -11
  25. package/lib/Socket/chats.d.ts +63 -233
  26. package/lib/Socket/chats.js +234 -184
  27. package/lib/Socket/communities.d.ts +232 -0
  28. package/lib/Socket/communities.js +402 -0
  29. package/lib/Socket/groups.d.ts +62 -41
  30. package/lib/Socket/groups.js +76 -64
  31. package/lib/Socket/index.d.ts +129 -83
  32. package/lib/Socket/index.js +13 -6
  33. package/lib/Socket/messages-recv.d.ts +59 -48
  34. package/lib/Socket/messages-recv.js +516 -371
  35. package/lib/Socket/messages-send.d.ts +86 -67
  36. package/lib/Socket/messages-send.js +1091 -1
  37. package/lib/Socket/mex.d.ts +2 -0
  38. package/lib/Socket/mex.js +45 -0
  39. package/lib/Socket/newsletter.d.ts +76 -64
  40. package/lib/Socket/newsletter.js +184 -1
  41. package/lib/Socket/socket.d.ts +19 -13
  42. package/lib/Socket/socket.js +805 -1
  43. package/lib/Types/Auth.d.ts +4 -10
  44. package/lib/Types/Bussines.d.ts +24 -0
  45. package/lib/Types/Bussines.js +2 -0
  46. package/lib/Types/Call.d.ts +1 -1
  47. package/lib/Types/Chat.d.ts +29 -9
  48. package/lib/Types/Chat.js +7 -1
  49. package/lib/Types/Contact.d.ts +5 -1
  50. package/lib/Types/Events.d.ts +55 -14
  51. package/lib/Types/GroupMetadata.d.ts +15 -5
  52. package/lib/Types/Label.d.ts +11 -0
  53. package/lib/Types/Label.js +1 -1
  54. package/lib/Types/LabelAssociation.js +1 -1
  55. package/lib/Types/Message.d.ts +75 -49
  56. package/lib/Types/Message.js +10 -7
  57. package/lib/Types/Newsletter.d.ts +129 -98
  58. package/lib/Types/Newsletter.js +33 -38
  59. package/lib/Types/Product.d.ts +1 -1
  60. package/lib/Types/Signal.d.ts +29 -1
  61. package/lib/Types/Socket.d.ts +48 -22
  62. package/lib/Types/State.d.ts +13 -2
  63. package/lib/Types/State.js +12 -0
  64. package/lib/Types/USync.d.ts +1 -1
  65. package/lib/Types/index.d.ts +10 -3
  66. package/lib/Types/index.js +2 -2
  67. package/lib/Utils/auth-utils.d.ts +3 -3
  68. package/lib/Utils/auth-utils.js +378 -102
  69. package/lib/Utils/baileys-event-stream.js +1 -1
  70. package/lib/Utils/business.d.ts +2 -2
  71. package/lib/Utils/business.js +19 -13
  72. package/lib/Utils/chat-utils.d.ts +21 -22
  73. package/lib/Utils/chat-utils.js +201 -154
  74. package/lib/Utils/crypto.d.ts +18 -19
  75. package/lib/Utils/crypto.js +78 -37
  76. package/lib/Utils/decode-wa-message.d.ts +34 -7
  77. package/lib/Utils/decode-wa-message.js +138 -66
  78. package/lib/Utils/event-buffer.d.ts +6 -8
  79. package/lib/Utils/event-buffer.js +81 -43
  80. package/lib/Utils/generics.d.ts +27 -27
  81. package/lib/Utils/generics.js +128 -133
  82. package/lib/Utils/history.d.ts +9 -5
  83. package/lib/Utils/history.js +17 -23
  84. package/lib/Utils/index.d.ts +2 -0
  85. package/lib/Utils/index.js +2 -0
  86. package/lib/Utils/lidToJid-test.d.ts +11 -0
  87. package/lib/Utils/lidToJid-test.js +27 -0
  88. package/lib/Utils/link-preview.d.ts +4 -4
  89. package/lib/Utils/link-preview.js +40 -12
  90. package/lib/Utils/logger.d.ts +11 -3
  91. package/lib/Utils/lt-hash.d.ts +8 -8
  92. package/lib/Utils/lt-hash.js +23 -24
  93. package/lib/Utils/make-mutex.d.ts +2 -2
  94. package/lib/Utils/make-mutex.js +3 -2
  95. package/lib/Utils/message-retry-manager.d.ts +81 -0
  96. package/lib/Utils/message-retry-manager.js +152 -0
  97. package/lib/Utils/messages-media.d.ts +37 -41
  98. package/lib/Utils/messages-media.js +252 -368
  99. package/lib/Utils/messages.d.ts +13 -15
  100. package/lib/Utils/messages.js +274 -261
  101. package/lib/Utils/noise-handler.d.ts +13 -15
  102. package/lib/Utils/noise-handler.js +20 -26
  103. package/lib/Utils/process-message.d.ts +9 -8
  104. package/lib/Utils/process-message.js +157 -93
  105. package/lib/Utils/signal.d.ts +6 -5
  106. package/lib/Utils/signal.js +37 -29
  107. package/lib/Utils/use-multi-file-auth-state.d.ts +1 -2
  108. package/lib/Utils/use-multi-file-auth-state.js +12 -7
  109. package/lib/Utils/validate-connection.d.ts +5 -6
  110. package/lib/Utils/validate-connection.js +39 -97
  111. package/lib/WABinary/constants.d.ts +24 -27
  112. package/lib/WABinary/constants.js +1276 -13
  113. package/lib/WABinary/decode.d.ts +3 -4
  114. package/lib/WABinary/decode.js +28 -14
  115. package/lib/WABinary/encode.d.ts +1 -2
  116. package/lib/WABinary/encode.js +134 -147
  117. package/lib/WABinary/generic-utils.d.ts +4 -7
  118. package/lib/WABinary/generic-utils.js +40 -125
  119. package/lib/WABinary/jid-utils.d.ts +13 -8
  120. package/lib/WABinary/jid-utils.js +27 -16
  121. package/lib/WAM/BinaryInfo.d.ts +2 -11
  122. package/lib/WAM/constants.d.ts +3 -2
  123. package/lib/WAM/constants.js +2252 -2359
  124. package/lib/WAM/encode.d.ts +1 -2
  125. package/lib/WAM/encode.js +8 -11
  126. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +2 -2
  127. package/lib/WAUSync/Protocols/USyncContactProtocol.js +3 -4
  128. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +2 -2
  129. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +5 -5
  130. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +2 -2
  131. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +5 -5
  132. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +2 -2
  133. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +5 -6
  134. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +2 -2
  135. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +1 -1
  136. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +4 -3
  137. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +11 -3
  138. package/lib/WAUSync/USyncQuery.d.ts +2 -2
  139. package/lib/WAUSync/USyncQuery.js +19 -15
  140. package/lib/WAUSync/USyncUser.d.ts +5 -5
  141. package/lib/WAUSync/index.d.ts +1 -1
  142. package/lib/WAUSync/index.js +1 -1
  143. package/package.json +102 -102
  144. package/lib/Defaults/baileys-version.json +0 -3
  145. package/lib/Defaults/phonenumber-mcc.json +0 -223
  146. package/lib/Signal/Group/queue-job.d.ts +0 -1
  147. package/lib/Signal/Group/queue-job.js +0 -57
  148. package/lib/Socket/Client/mobile-socket-client.d.ts +0 -13
  149. package/lib/Socket/Client/mobile-socket-client.js +0 -65
  150. package/lib/Socket/hbmods.d.ts +0 -253
  151. package/lib/Socket/hbmods.js +0 -1
  152. package/lib/Socket/registration.d.ts +0 -267
  153. package/lib/Socket/registration.js +0 -166
  154. package/lib/Socket/usync.d.ts +0 -36
  155. package/lib/Socket/usync.js +0 -70
  156. /package/lib/Socket/Client/{abstract-socket-client.js → types.js} +0 -0
@@ -1,21 +1,19 @@
1
- /// <reference types="node" />
2
- import { Logger } from 'pino';
3
- import { proto } from '../../WAProto';
4
- import { KeyPair } from '../Types';
5
- import { BinaryNode } from '../WABinary';
6
- export declare const makeNoiseHandler: ({ keyPair: { private: privateKey, public: publicKey }, NOISE_HEADER, mobile, logger, routingInfo }: {
1
+ import { proto } from '../../WAProto/index.js';
2
+ import type { KeyPair } from '../Types';
3
+ import type { BinaryNode } from '../WABinary';
4
+ import type { ILogger } from './logger';
5
+ export declare const makeNoiseHandler: ({ keyPair: { private: privateKey, public: publicKey }, NOISE_HEADER, logger, routingInfo }: {
7
6
  keyPair: KeyPair;
8
7
  NOISE_HEADER: Uint8Array;
9
- mobile: boolean;
10
- logger: Logger;
8
+ logger: ILogger;
11
9
  routingInfo?: Buffer | undefined;
12
10
  }) => {
13
- encrypt: (plaintext: Uint8Array) => Buffer;
14
- decrypt: (ciphertext: Uint8Array) => Buffer;
11
+ encrypt: (plaintext: Uint8Array) => Buffer<ArrayBuffer>;
12
+ decrypt: (ciphertext: Uint8Array) => Buffer<ArrayBuffer>;
15
13
  authenticate: (data: Uint8Array) => void;
16
- mixIntoKey: (data: Uint8Array) => void;
17
- finishInit: () => void;
18
- processHandshake: ({ serverHello }: proto.HandshakeMessage, noiseKey: KeyPair) => Buffer;
19
- encodeFrame: (data: Buffer | Uint8Array) => Buffer;
20
- decodeFrame: (newData: Buffer | Uint8Array, onFrame: (buff: Uint8Array | BinaryNode) => void) => void;
14
+ mixIntoKey: (data: Uint8Array) => Promise<void>;
15
+ finishInit: () => Promise<void>;
16
+ processHandshake: ({ serverHello }: proto.HandshakeMessage, noiseKey: KeyPair) => Promise<Buffer<ArrayBuffer>>;
17
+ encodeFrame: (data: Buffer | Uint8Array) => Buffer<ArrayBuffer>;
18
+ decodeFrame: (newData: Buffer | Uint8Array, onFrame: (buff: Uint8Array | BinaryNode) => void) => Promise<void>;
21
19
  };
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.makeNoiseHandler = void 0;
4
4
  const boom_1 = require("@hapi/boom");
5
- const WAProto_1 = require("../../WAProto");
5
+ const index_js_1 = require("../../WAProto/index.js");
6
6
  const Defaults_1 = require("../Defaults");
7
7
  const WABinary_1 = require("../WABinary");
8
8
  const crypto_1 = require("./crypto");
@@ -11,7 +11,7 @@ const generateIV = (counter) => {
11
11
  new DataView(iv).setUint32(8, counter);
12
12
  return new Uint8Array(iv);
13
13
  };
14
- const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publicKey }, NOISE_HEADER, mobile, logger, routingInfo }) => {
14
+ const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publicKey }, NOISE_HEADER, logger, routingInfo }) => {
15
15
  logger = logger.child({ class: 'ns' });
16
16
  const authenticate = (data) => {
17
17
  if (!isFinished) {
@@ -38,20 +38,20 @@ const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publicKey },
38
38
  authenticate(ciphertext);
39
39
  return result;
40
40
  };
41
- const localHKDF = (data) => {
42
- const key = (0, crypto_1.hkdf)(Buffer.from(data), 64, { salt, info: '' });
41
+ const localHKDF = async (data) => {
42
+ const key = await (0, crypto_1.hkdf)(Buffer.from(data), 64, { salt, info: '' });
43
43
  return [key.slice(0, 32), key.slice(32)];
44
44
  };
45
- const mixIntoKey = (data) => {
46
- const [write, read] = localHKDF(data);
45
+ const mixIntoKey = async (data) => {
46
+ const [write, read] = await localHKDF(data);
47
47
  salt = write;
48
48
  encKey = read;
49
49
  decKey = read;
50
50
  readCounter = 0;
51
51
  writeCounter = 0;
52
52
  };
53
- const finishInit = () => {
54
- const [write, read] = localHKDF(new Uint8Array(0));
53
+ const finishInit = async () => {
54
+ const [write, read] = await localHKDF(new Uint8Array(0));
55
55
  encKey = write;
56
56
  decKey = read;
57
57
  hash = Buffer.from([]);
@@ -60,7 +60,7 @@ const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publicKey },
60
60
  isFinished = true;
61
61
  };
62
62
  const data = Buffer.from(Defaults_1.NOISE_MODE);
63
- let hash = Buffer.from(data.byteLength === 32 ? data : (0, crypto_1.sha256)(data));
63
+ let hash = data.byteLength === 32 ? data : (0, crypto_1.sha256)(data);
64
64
  let salt = hash;
65
65
  let encKey = hash;
66
66
  let decKey = hash;
@@ -77,24 +77,19 @@ const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publicKey },
77
77
  authenticate,
78
78
  mixIntoKey,
79
79
  finishInit,
80
- processHandshake: ({ serverHello }, noiseKey) => {
80
+ processHandshake: async ({ serverHello }, noiseKey) => {
81
81
  authenticate(serverHello.ephemeral);
82
- mixIntoKey(crypto_1.Curve.sharedKey(privateKey, serverHello.ephemeral));
82
+ await mixIntoKey(crypto_1.Curve.sharedKey(privateKey, serverHello.ephemeral));
83
83
  const decStaticContent = decrypt(serverHello.static);
84
- mixIntoKey(crypto_1.Curve.sharedKey(privateKey, decStaticContent));
84
+ await mixIntoKey(crypto_1.Curve.sharedKey(privateKey, decStaticContent));
85
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
- }
86
+ const { intermediate: certIntermediate } = index_js_1.proto.CertChain.decode(certDecoded);
87
+ const { issuerSerial } = index_js_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 });
95
90
  }
96
91
  const keyEnc = encrypt(noiseKey.public);
97
- mixIntoKey(crypto_1.Curve.sharedKey(noiseKey.private, serverHello.ephemeral));
92
+ await mixIntoKey(crypto_1.Curve.sharedKey(noiseKey.private, serverHello.ephemeral));
98
93
  return keyEnc;
99
94
  },
100
95
  encodeFrame: (data) => {
@@ -125,8 +120,7 @@ const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publicKey },
125
120
  frame.set(data, introSize + 3);
126
121
  return frame;
127
122
  },
128
- decodeFrame: (newData, onFrame) => {
129
- var _a;
123
+ decodeFrame: async (newData, onFrame) => {
130
124
  // the binary protocol uses its own framing mechanism
131
125
  // on top of the WS frames
132
126
  // so we get this data and separate out the frames
@@ -143,9 +137,9 @@ const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publicKey },
143
137
  inBytes = inBytes.slice(size + 3);
144
138
  if (isFinished) {
145
139
  const result = decrypt(frame);
146
- frame = (0, WABinary_1.decodeBinaryNode)(result);
140
+ frame = await (0, WABinary_1.decodeBinaryNode)(result);
147
141
  }
148
- logger.trace({ msg: (_a = frame === null || frame === void 0 ? void 0 : frame.attrs) === null || _a === void 0 ? void 0 : _a.id }, 'recv frame');
142
+ logger.trace({ msg: frame?.attrs?.id }, 'recv frame');
149
143
  onFrame(frame);
150
144
  size = getBytesSize();
151
145
  }
@@ -1,15 +1,16 @@
1
- import { AxiosRequestConfig } from 'axios';
2
- import type { Logger } from 'pino';
3
- import { proto } from '../../WAProto';
4
- import { AuthenticationCreds, BaileysEventEmitter, SignalKeyStoreWithTransaction, SocketConfig } from '../Types';
1
+ import type { AxiosRequestConfig } from 'axios';
2
+ import { proto } from '../../WAProto/index.js';
3
+ import type { AuthenticationCreds, BaileysEventEmitter, CacheStore, SignalKeyStoreWithTransaction, SignalRepositoryWithLIDStore } from '../Types';
4
+ import type { ILogger } from './logger';
5
5
  type ProcessMessageContext = {
6
6
  shouldProcessHistoryMsg: boolean;
7
+ placeholderResendCache?: CacheStore;
7
8
  creds: AuthenticationCreds;
8
9
  keyStore: SignalKeyStoreWithTransaction;
9
10
  ev: BaileysEventEmitter;
10
- getMessage: SocketConfig['getMessage'];
11
- logger?: Logger;
11
+ logger?: ILogger;
12
12
  options: AxiosRequestConfig<{}>;
13
+ signalRepository: SignalRepositoryWithLIDStore;
13
14
  };
14
15
  /** Cleans a received message to further processing */
15
16
  export declare const cleanMessage: (message: proto.IWebMessageInfo, meId: string) => void;
@@ -36,6 +37,6 @@ type PollContext = {
36
37
  * @param ctx additional info about the poll required for decryption
37
38
  * @returns list of SHA256 options
38
39
  */
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>;
40
+ export declare function decryptPollVote({ encPayload, encIv }: proto.Message.IPollEncValue, { pollCreatorJid, pollMsgId, pollEncKey, voterJid }: PollContext): proto.Message.PollVoteMessage;
41
+ declare const processMessage: (message: proto.IWebMessageInfo, { shouldProcessHistoryMsg, placeholderResendCache, ev, creds, signalRepository, keyStore, logger, options }: ProcessMessageContext) => Promise<void>;
41
42
  export default processMessage;
@@ -1,7 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.decryptPollVote = exports.getChatId = exports.shouldIncrementChatUnread = exports.isRealMessage = exports.cleanMessage = void 0;
4
- const WAProto_1 = require("../../WAProto");
3
+ exports.getChatId = exports.shouldIncrementChatUnread = exports.isRealMessage = exports.cleanMessage = void 0;
4
+ exports.decryptPollVote = decryptPollVote;
5
+ const index_js_1 = require("../../WAProto/index.js");
5
6
  const Types_1 = require("../Types");
6
7
  const messages_1 = require("../Utils/messages");
7
8
  const WABinary_1 = require("../WABinary");
@@ -14,9 +15,7 @@ const REAL_MSG_STUB_TYPES = new Set([
14
15
  Types_1.WAMessageStubType.CALL_MISSED_VIDEO,
15
16
  Types_1.WAMessageStubType.CALL_MISSED_VOICE
16
17
  ]);
17
- const REAL_MSG_REQ_ME_STUB_TYPES = new Set([
18
- Types_1.WAMessageStubType.GROUP_PARTICIPANT_ADD
19
- ]);
18
+ const REAL_MSG_REQ_ME_STUB_TYPES = new Set([Types_1.WAMessageStubType.GROUP_PARTICIPANT_ADD]);
20
19
  /** Cleans a received message to further processing */
21
20
  const cleanMessage = (message, meId) => {
22
21
  // ensure remoteJid and participant doesn't have device or agent in it
@@ -24,10 +23,10 @@ const cleanMessage = (message, meId) => {
24
23
  message.key.participant = message.key.participant ? (0, WABinary_1.jidNormalizedUser)(message.key.participant) : undefined;
25
24
  const content = (0, messages_1.normalizeMessageContent)(message.message);
26
25
  // if the message has a reaction, ensure fromMe & remoteJid are from our perspective
27
- if (content === null || content === void 0 ? void 0 : content.reactionMessage) {
26
+ if (content?.reactionMessage) {
28
27
  normaliseKey(content.reactionMessage.key);
29
28
  }
30
- if (content === null || content === void 0 ? void 0 : content.pollUpdateMessage) {
29
+ if (content?.pollUpdateMessage) {
31
30
  normaliseKey(content.pollUpdateMessage.pollCreationMessageKey);
32
31
  }
33
32
  function normaliseKey(msgKey) {
@@ -38,9 +37,9 @@ const cleanMessage = (message, meId) => {
38
37
  // we've to correct the key to be from them, or some other participant
39
38
  msgKey.fromMe = !msgKey.fromMe
40
39
  ? (0, WABinary_1.areJidsSameUser)(msgKey.participant || msgKey.remoteJid, meId)
41
- // if the message being reacted to, was from them
42
- // fromMe automatically becomes false
43
- : false;
40
+ : // if the message being reacted to, was from them
41
+ // fromMe automatically becomes false
42
+ false;
44
43
  // set the remoteJid to being the same as the chat the message came from
45
44
  msgKey.remoteJid = message.key.remoteJid;
46
45
  // set participant of the message
@@ -50,29 +49,26 @@ const cleanMessage = (message, meId) => {
50
49
  };
51
50
  exports.cleanMessage = cleanMessage;
52
51
  const isRealMessage = (message, meId) => {
53
- var _a;
54
52
  const normalizedContent = (0, messages_1.normalizeMessageContent)(message.message);
55
53
  const hasSomeContent = !!(0, messages_1.getContentType)(normalizedContent);
56
- return (!!normalizedContent
57
- || REAL_MSG_STUB_TYPES.has(message.messageStubType)
58
- || (REAL_MSG_REQ_ME_STUB_TYPES.has(message.messageStubType)
59
- && ((_a = message.messageStubParameters) === null || _a === void 0 ? void 0 : _a.some(p => (0, WABinary_1.areJidsSameUser)(meId, p)))))
60
- && hasSomeContent
61
- && !(normalizedContent === null || normalizedContent === void 0 ? void 0 : normalizedContent.protocolMessage)
62
- && !(normalizedContent === null || normalizedContent === void 0 ? void 0 : normalizedContent.reactionMessage)
63
- && !(normalizedContent === null || normalizedContent === void 0 ? void 0 : normalizedContent.pollUpdateMessage);
54
+ return ((!!normalizedContent ||
55
+ REAL_MSG_STUB_TYPES.has(message.messageStubType) ||
56
+ (REAL_MSG_REQ_ME_STUB_TYPES.has(message.messageStubType) &&
57
+ message.messageStubParameters?.some(p => (0, WABinary_1.areJidsSameUser)(meId, p)))) &&
58
+ hasSomeContent &&
59
+ !normalizedContent?.protocolMessage &&
60
+ !normalizedContent?.reactionMessage &&
61
+ !normalizedContent?.pollUpdateMessage);
64
62
  };
65
63
  exports.isRealMessage = isRealMessage;
66
- const shouldIncrementChatUnread = (message) => (!message.key.fromMe && !message.messageStubType);
64
+ const shouldIncrementChatUnread = (message) => !message.key.fromMe && !message.messageStubType;
67
65
  exports.shouldIncrementChatUnread = shouldIncrementChatUnread;
68
66
  /**
69
67
  * Get the ID of the chat from the given key.
70
68
  * Typically -- that'll be the remoteJid, but for broadcasts, it'll be the participant
71
69
  */
72
70
  const getChatId = ({ remoteJid, participant, fromMe }) => {
73
- if ((0, WABinary_1.isJidBroadcast)(remoteJid)
74
- && !(0, WABinary_1.isJidStatusBroadcast)(remoteJid)
75
- && !fromMe) {
71
+ if ((0, WABinary_1.isJidBroadcast)(remoteJid) && !(0, WABinary_1.isJidStatusBroadcast)(remoteJid) && !fromMe) {
76
72
  return participant;
77
73
  }
78
74
  return remoteJid;
@@ -84,7 +80,7 @@ exports.getChatId = getChatId;
84
80
  * @param ctx additional info about the poll required for decryption
85
81
  * @returns list of SHA256 options
86
82
  */
87
- function decryptPollVote({ encPayload, encIv }, { pollCreatorJid, pollMsgId, pollEncKey, voterJid, }) {
83
+ function decryptPollVote({ encPayload, encIv }, { pollCreatorJid, pollMsgId, pollEncKey, voterJid }) {
88
84
  const sign = Buffer.concat([
89
85
  toBinary(pollMsgId),
90
86
  toBinary(pollCreatorJid),
@@ -96,19 +92,18 @@ function decryptPollVote({ encPayload, encIv }, { pollCreatorJid, pollMsgId, pol
96
92
  const decKey = (0, crypto_1.hmacSign)(sign, key0, 'sha256');
97
93
  const aad = toBinary(`${pollMsgId}\u0000${voterJid}`);
98
94
  const decrypted = (0, crypto_1.aesDecryptGCM)(encPayload, decKey, encIv, aad);
99
- return WAProto_1.proto.Message.PollVoteMessage.decode(decrypted);
95
+ return index_js_1.proto.Message.PollVoteMessage.decode(decrypted);
100
96
  function toBinary(txt) {
101
97
  return Buffer.from(txt);
102
98
  }
103
99
  }
104
- exports.decryptPollVote = decryptPollVote;
105
- const processMessage = async (message, { shouldProcessHistoryMsg, ev, creds, keyStore, logger, options, getMessage }) => {
106
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
100
+ const processMessage = async (message, { shouldProcessHistoryMsg, placeholderResendCache, ev, creds, signalRepository, keyStore, logger, options }) => {
107
101
  const meId = creds.me.id;
108
102
  const { accountSettings } = creds;
109
103
  const chat = { id: (0, WABinary_1.jidNormalizedUser)((0, exports.getChatId)(message.key)) };
110
104
  const isRealMsg = (0, exports.isRealMessage)(message, meId);
111
105
  if (isRealMsg) {
106
+ chat.messages = [{ message }];
112
107
  chat.conversationTimestamp = (0, generics_1.toNumber)(message.messageTimestamp);
113
108
  // only increment unread count if not CIPHERTEXT and from another person
114
109
  if ((0, exports.shouldIncrementChatUnread)(message)) {
@@ -118,38 +113,43 @@ const processMessage = async (message, { shouldProcessHistoryMsg, ev, creds, key
118
113
  const content = (0, messages_1.normalizeMessageContent)(message.message);
119
114
  // unarchive chat if it's a real message, or someone reacted to our message
120
115
  // 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)) {
116
+ if ((isRealMsg || content?.reactionMessage?.key?.fromMe) && accountSettings?.unarchiveChats) {
123
117
  chat.archived = false;
124
118
  chat.readOnly = false;
125
119
  }
126
- const protocolMsg = content === null || content === void 0 ? void 0 : content.protocolMessage;
120
+ const protocolMsg = content?.protocolMessage;
127
121
  if (protocolMsg) {
128
122
  switch (protocolMsg.type) {
129
- case WAProto_1.proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION:
123
+ case index_js_1.proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION:
130
124
  const histNotification = protocolMsg.historySyncNotification;
131
125
  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({
126
+ const isLatest = !creds.processedHistoryMessages?.length;
127
+ logger?.info({
134
128
  histNotification,
135
129
  process,
136
130
  id: message.key.id,
137
- isLatest,
131
+ isLatest
138
132
  }, 'got history notification');
139
133
  if (process) {
140
- ev.emit('creds.update', {
141
- processedHistoryMessages: [
142
- ...(creds.processedHistoryMessages || []),
143
- { key: message.key, messageTimestamp: message.messageTimestamp }
144
- ]
145
- });
134
+ if (histNotification.syncType !== index_js_1.proto.HistorySync.HistorySyncType.ON_DEMAND) {
135
+ ev.emit('creds.update', {
136
+ processedHistoryMessages: [
137
+ ...(creds.processedHistoryMessages || []),
138
+ { key: message.key, messageTimestamp: message.messageTimestamp }
139
+ ]
140
+ });
141
+ }
146
142
  const data = await (0, history_1.downloadAndProcessHistorySyncNotification)(histNotification, options);
147
- ev.emit('messaging-history.set', { ...data, isLatest });
143
+ ev.emit('messaging-history.set', {
144
+ ...data,
145
+ isLatest: histNotification.syncType !== index_js_1.proto.HistorySync.HistorySyncType.ON_DEMAND ? isLatest : undefined,
146
+ peerDataRequestSessionId: histNotification.peerDataRequestSessionId
147
+ });
148
148
  }
149
149
  break;
150
- case WAProto_1.proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE:
150
+ case index_js_1.proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE:
151
151
  const keys = protocolMsg.appStateSyncKeyShare.keys;
152
- if (keys === null || keys === void 0 ? void 0 : keys.length) {
152
+ if (keys?.length) {
153
153
  let newAppStateSyncKeyId = '';
154
154
  await keyStore.transaction(async () => {
155
155
  const newKeys = [];
@@ -159,15 +159,15 @@ const processMessage = async (message, { shouldProcessHistoryMsg, ev, creds, key
159
159
  await keyStore.set({ 'app-state-sync-key': { [strKeyId]: keyData } });
160
160
  newAppStateSyncKeyId = strKeyId;
161
161
  }
162
- logger === null || logger === void 0 ? void 0 : logger.info({ newAppStateSyncKeyId, newKeys }, 'injecting new app state sync keys');
163
- });
162
+ logger?.info({ newAppStateSyncKeyId, newKeys }, 'injecting new app state sync keys');
163
+ }, meId);
164
164
  ev.emit('creds.update', { myAppStateKeyId: newAppStateSyncKeyId });
165
165
  }
166
166
  else {
167
- logger === null || logger === void 0 ? void 0 : logger.info({ protocolMsg }, 'recv app state sync with 0 keys');
167
+ logger?.info({ protocolMsg }, 'recv app state sync with 0 keys');
168
168
  }
169
169
  break;
170
- case WAProto_1.proto.Message.ProtocolMessage.Type.REVOKE:
170
+ case index_js_1.proto.Message.ProtocolMessage.Type.REVOKE:
171
171
  ev.emit('messages.update', [
172
172
  {
173
173
  key: {
@@ -178,50 +178,94 @@ const processMessage = async (message, { shouldProcessHistoryMsg, ev, creds, key
178
178
  }
179
179
  ]);
180
180
  break;
181
- case WAProto_1.proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING:
181
+ case index_js_1.proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING:
182
182
  Object.assign(chat, {
183
183
  ephemeralSettingTimestamp: (0, generics_1.toNumber)(message.messageTimestamp),
184
184
  ephemeralExpiration: protocolMsg.ephemeralExpiration || null
185
185
  });
186
186
  break;
187
- case WAProto_1.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE:
187
+ case index_js_1.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE:
188
188
  const response = protocolMsg.peerDataOperationRequestResponseMessage;
189
189
  if (response) {
190
+ await placeholderResendCache?.del(response.stanzaId);
191
+ // TODO: IMPLEMENT HISTORY SYNC ETC (sticker uploads etc.).
190
192
  const { peerDataOperationResult } = response;
191
193
  for (const result of peerDataOperationResult) {
192
194
  const { placeholderMessageResendResponse: retryResponse } = result;
195
+ //eslint-disable-next-line max-depth
193
196
  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
- ]);
197
+ const webMessageInfo = index_js_1.proto.WebMessageInfo.decode(retryResponse.webMessageInfoBytes);
198
+ // wait till another upsert event is available, don't want it to be part of the PDO response message
199
+ setTimeout(() => {
200
+ ev.emit('messages.upsert', {
201
+ messages: [webMessageInfo],
202
+ type: 'notify',
203
+ requestId: response.stanzaId
204
+ });
205
+ }, 500);
198
206
  }
199
207
  }
200
208
  }
201
209
  break;
210
+ case index_js_1.proto.Message.ProtocolMessage.Type.MESSAGE_EDIT:
211
+ ev.emit('messages.update', [
212
+ {
213
+ // flip the sender / fromMe properties because they're in the perspective of the sender
214
+ key: { ...message.key, id: protocolMsg.key?.id },
215
+ update: {
216
+ message: {
217
+ editedMessage: {
218
+ message: protocolMsg.editedMessage
219
+ }
220
+ },
221
+ messageTimestamp: protocolMsg.timestampMs
222
+ ? Math.floor((0, generics_1.toNumber)(protocolMsg.timestampMs) / 1000)
223
+ : message.messageTimestamp
224
+ }
225
+ }
226
+ ]);
227
+ break;
228
+ case index_js_1.proto.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC:
229
+ const encodedPayload = protocolMsg.lidMigrationMappingSyncMessage?.encodedMappingPayload;
230
+ const { pnToLidMappings, chatDbMigrationTimestamp } = index_js_1.proto.LIDMigrationMappingSyncPayload.decode(encodedPayload);
231
+ logger?.debug({ pnToLidMappings, chatDbMigrationTimestamp }, 'got lid mappings and chat db migration timestamp');
232
+ const pairs = [];
233
+ for (const { pn, latestLid, assignedLid } of pnToLidMappings) {
234
+ const lid = latestLid || assignedLid;
235
+ pairs.push({ lid: `${lid}@lid`, pn: `${pn}@s.whatsapp.net` });
236
+ }
237
+ await signalRepository.lidMapping.storeLIDPNMappings(pairs);
202
238
  }
203
239
  }
204
- else if (content === null || content === void 0 ? void 0 : content.reactionMessage) {
240
+ else if (content?.reactionMessage) {
205
241
  const reaction = {
206
242
  ...content.reactionMessage,
207
- key: message.key,
243
+ key: message.key
208
244
  };
209
- ev.emit('messages.reaction', [{
245
+ ev.emit('messages.reaction', [
246
+ {
210
247
  reaction,
211
- key: content.reactionMessage.key,
212
- }]);
248
+ key: content.reactionMessage?.key
249
+ }
250
+ ]);
213
251
  }
214
252
  else if (message.messageStubType) {
215
- const jid = message.key.remoteJid;
253
+ const jid = message.key?.remoteJid;
216
254
  //let actor = whatsappID (message.participant)
217
255
  let participants;
218
- const emitParticipantsUpdate = (action) => (ev.emit('group-participants.update', { id: jid, author: message.participant, participants, action }));
256
+ const emitParticipantsUpdate = (action) => ev.emit('group-participants.update', { id: jid, author: message.participant, participants, action });
219
257
  const emitGroupUpdate = (update) => {
220
- var _a;
221
- ev.emit('groups.update', [{ id: jid, ...update, author: (_a = message.participant) !== null && _a !== void 0 ? _a : undefined }]);
258
+ ev.emit('groups.update', [{ id: jid, ...update, author: message.participant ?? undefined }]);
259
+ };
260
+ const emitGroupRequestJoin = (participant, action, method) => {
261
+ ev.emit('group.join-request', { id: jid, author: message.participant, participant, action, method: method });
222
262
  };
223
263
  const participantsIncludesMe = () => participants.find(jid => (0, WABinary_1.areJidsSameUser)(meId, jid));
224
264
  switch (message.messageStubType) {
265
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER:
266
+ participants = message.messageStubParameters || [];
267
+ emitParticipantsUpdate('modify');
268
+ break;
225
269
  case Types_1.WAMessageStubType.GROUP_PARTICIPANT_LEAVE:
226
270
  case Types_1.WAMessageStubType.GROUP_PARTICIPANT_REMOVE:
227
271
  participants = message.messageStubParameters || [];
@@ -249,48 +293,64 @@ const processMessage = async (message, { shouldProcessHistoryMsg, ev, creds, key
249
293
  emitParticipantsUpdate('promote');
250
294
  break;
251
295
  case Types_1.WAMessageStubType.GROUP_CHANGE_ANNOUNCE:
252
- const announceValue = (_d = message.messageStubParameters) === null || _d === void 0 ? void 0 : _d[0];
296
+ const announceValue = message.messageStubParameters?.[0];
253
297
  emitGroupUpdate({ announce: announceValue === 'true' || announceValue === 'on' });
254
298
  break;
255
299
  case Types_1.WAMessageStubType.GROUP_CHANGE_RESTRICT:
256
- const restrictValue = (_e = message.messageStubParameters) === null || _e === void 0 ? void 0 : _e[0];
300
+ const restrictValue = message.messageStubParameters?.[0];
257
301
  emitGroupUpdate({ restrict: restrictValue === 'true' || restrictValue === 'on' });
258
302
  break;
259
303
  case Types_1.WAMessageStubType.GROUP_CHANGE_SUBJECT:
260
- const name = (_f = message.messageStubParameters) === null || _f === void 0 ? void 0 : _f[0];
304
+ const name = message.messageStubParameters?.[0];
261
305
  chat.name = name;
262
306
  emitGroupUpdate({ subject: name });
263
307
  break;
308
+ case Types_1.WAMessageStubType.GROUP_CHANGE_DESCRIPTION:
309
+ const description = message.messageStubParameters?.[0];
310
+ chat.description = description;
311
+ emitGroupUpdate({ desc: description });
312
+ break;
264
313
  case Types_1.WAMessageStubType.GROUP_CHANGE_INVITE_LINK:
265
- const code = (_g = message.messageStubParameters) === null || _g === void 0 ? void 0 : _g[0];
314
+ const code = message.messageStubParameters?.[0];
266
315
  emitGroupUpdate({ inviteCode: code });
267
316
  break;
268
317
  case Types_1.WAMessageStubType.GROUP_MEMBER_ADD_MODE:
269
- const memberAddValue = (_h = message.messageStubParameters) === null || _h === void 0 ? void 0 : _h[0];
318
+ const memberAddValue = message.messageStubParameters?.[0];
270
319
  emitGroupUpdate({ memberAddMode: memberAddValue === 'all_member_add' });
271
320
  break;
272
321
  case Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE:
273
- const approvalMode = (_j = message.messageStubParameters) === null || _j === void 0 ? void 0 : _j[0];
322
+ const approvalMode = message.messageStubParameters?.[0];
274
323
  emitGroupUpdate({ joinApprovalMode: approvalMode === 'on' });
275
324
  break;
325
+ case Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD:
326
+ const participant = message.messageStubParameters?.[0];
327
+ const action = message.messageStubParameters?.[1];
328
+ const method = message.messageStubParameters?.[2];
329
+ emitGroupRequestJoin(participant, action, method);
330
+ break;
276
331
  }
277
- }
278
- else if (content === null || content === void 0 ? void 0 : content.pollUpdateMessage) {
279
- const creationMsgKey = content.pollUpdateMessage.pollCreationMessageKey;
332
+ } /* else if(content?.pollUpdateMessage) {
333
+ const creationMsgKey = content.pollUpdateMessage.pollCreationMessageKey!
280
334
  // 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;
335
+ // TODO: make standalone, remove getMessage reference
336
+ // TODO: Remove entirely
337
+ const pollMsg = await getMessage(creationMsgKey)
338
+ if(pollMsg) {
339
+ const meIdNormalised = jidNormalizedUser(meId)
340
+ const pollCreatorJid = getKeyAuthor(creationMsgKey, meIdNormalised)
341
+ const voterJid = getKeyAuthor(message.key, meIdNormalised)
342
+ const pollEncKey = pollMsg.messageContextInfo?.messageSecret!
343
+
287
344
  try {
288
- const voteMsg = decryptPollVote(content.pollUpdateMessage.vote, {
289
- pollEncKey,
290
- pollCreatorJid,
291
- pollMsgId: creationMsgKey.id,
292
- voterJid,
293
- });
345
+ const voteMsg = decryptPollVote(
346
+ content.pollUpdateMessage.vote!,
347
+ {
348
+ pollEncKey,
349
+ pollCreatorJid,
350
+ pollMsgId: creationMsgKey.id!,
351
+ voterJid,
352
+ }
353
+ )
294
354
  ev.emit('messages.update', [
295
355
  {
296
356
  key: creationMsgKey,
@@ -299,21 +359,25 @@ const processMessage = async (message, { shouldProcessHistoryMsg, ev, creds, key
299
359
  {
300
360
  pollUpdateMessageKey: message.key,
301
361
  vote: voteMsg,
302
- senderTimestampMs: content.pollUpdateMessage.senderTimestampMs.toNumber(),
362
+ senderTimestampMs: (content.pollUpdateMessage.senderTimestampMs! as Long).toNumber(),
303
363
  }
304
364
  ]
305
365
  }
306
366
  }
307
- ]);
367
+ ])
368
+ } catch(err) {
369
+ logger?.warn(
370
+ { err, creationMsgKey },
371
+ 'failed to decrypt poll vote'
372
+ )
308
373
  }
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');
374
+ } else {
375
+ logger?.warn(
376
+ { creationMsgKey },
377
+ 'poll creation message not found, cannot decrypt update'
378
+ )
315
379
  }
316
- }
380
+ } */
317
381
  if (Object.keys(chat).length > 1) {
318
382
  ev.emit('chats.update', [chat]);
319
383
  }
@@ -1,6 +1,7 @@
1
- import { SignalRepository } from '../Types';
2
- import { AuthenticationCreds, AuthenticationState, KeyPair, SignalIdentity, SignalKeyStore, SignedKeyPair } from '../Types/Auth';
3
- import { BinaryNode, JidWithDevice } from '../WABinary';
1
+ import type { SignalRepositoryWithLIDStore } from '../Types';
2
+ import type { AuthenticationCreds, AuthenticationState, KeyPair, SignalIdentity, SignalKeyStore, SignedKeyPair } from '../Types/Auth';
3
+ import { type BinaryNode, type JidWithDevice } from '../WABinary';
4
+ import type { USyncQueryResultList } from '../WAUSync';
4
5
  export declare const createSignalIdentity: (wid: string, accountSignatureKey: Uint8Array) => SignalIdentity;
5
6
  export declare const getPreKeys: ({ get }: SignalKeyStore, min: number, limit: number) => Promise<{
6
7
  [id: string]: KeyPair;
@@ -14,8 +15,8 @@ export declare const generateOrGetPreKeys: (creds: AuthenticationCreds, range: n
14
15
  };
15
16
  export declare const xmppSignedPreKey: (key: SignedKeyPair) => BinaryNode;
16
17
  export declare const xmppPreKey: (pair: KeyPair, id: number) => BinaryNode;
17
- export declare const parseAndInjectE2ESessions: (node: BinaryNode, repository: SignalRepository) => Promise<void>;
18
- export declare const extractDeviceJids: (result: BinaryNode, myJid: string, excludeZeroDevices: boolean) => JidWithDevice[];
18
+ export declare const parseAndInjectE2ESessions: (node: BinaryNode, repository: SignalRepositoryWithLIDStore) => Promise<void>;
19
+ export declare const extractDeviceJids: (result: USyncQueryResultList[], myJid: string, excludeZeroDevices: boolean) => JidWithDevice[];
19
20
  /**
20
21
  * get the next N keys for upload or processing
21
22
  * @param count number of pre-keys to get or generate