violetics 7.0.1-alpha → 7.0.2-alpha

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 +3 -2
  2. package/README.md +1001 -232
  3. package/WAProto/index.js +75379 -142631
  4. package/engine-requirements.js +11 -8
  5. package/lib/Defaults/index.js +132 -146
  6. package/lib/Signal/Group/ciphertext-message.js +2 -6
  7. package/lib/Signal/Group/group-session-builder.js +7 -42
  8. package/lib/Signal/Group/group_cipher.js +37 -52
  9. package/lib/Signal/Group/index.js +11 -57
  10. package/lib/Signal/Group/keyhelper.js +7 -45
  11. package/lib/Signal/Group/sender-chain-key.js +7 -16
  12. package/lib/Signal/Group/sender-key-distribution-message.js +8 -12
  13. package/lib/Signal/Group/sender-key-message.js +9 -13
  14. package/lib/Signal/Group/sender-key-name.js +2 -6
  15. package/lib/Signal/Group/sender-key-record.js +9 -22
  16. package/lib/Signal/Group/sender-key-state.js +27 -43
  17. package/lib/Signal/Group/sender-message-key.js +4 -8
  18. package/lib/Signal/libsignal.js +319 -94
  19. package/lib/Signal/lid-mapping.js +224 -139
  20. package/lib/Socket/Client/index.js +2 -19
  21. package/lib/Socket/Client/types.js +10 -0
  22. package/lib/Socket/Client/websocket.js +53 -0
  23. package/lib/Socket/business.js +162 -44
  24. package/lib/Socket/chats.js +477 -418
  25. package/lib/Socket/communities.js +430 -0
  26. package/lib/Socket/groups.js +110 -99
  27. package/lib/Socket/index.js +10 -10
  28. package/lib/Socket/messages-recv.js +884 -561
  29. package/lib/Socket/messages-send.js +859 -428
  30. package/lib/Socket/mex.js +41 -0
  31. package/lib/Socket/newsletter.js +195 -390
  32. package/lib/Socket/socket.js +465 -315
  33. package/lib/Store/index.js +3 -10
  34. package/lib/Store/make-in-memory-store.js +73 -79
  35. package/lib/Store/make-ordered-dictionary.js +4 -7
  36. package/lib/Store/object-repository.js +2 -6
  37. package/lib/Types/Auth.js +1 -2
  38. package/lib/Types/Bussines.js +1 -0
  39. package/lib/Types/Call.js +1 -2
  40. package/lib/Types/Chat.js +7 -4
  41. package/lib/Types/Contact.js +1 -2
  42. package/lib/Types/Events.js +1 -2
  43. package/lib/Types/GroupMetadata.js +1 -2
  44. package/lib/Types/Label.js +2 -5
  45. package/lib/Types/LabelAssociation.js +2 -5
  46. package/lib/Types/Message.js +17 -9
  47. package/lib/Types/Newsletter.js +33 -38
  48. package/lib/Types/Product.js +1 -2
  49. package/lib/Types/Signal.js +1 -2
  50. package/lib/Types/Socket.js +2 -2
  51. package/lib/Types/State.js +12 -2
  52. package/lib/Types/USync.js +1 -2
  53. package/lib/Types/index.js +14 -31
  54. package/lib/Utils/auth-utils.js +228 -152
  55. package/lib/Utils/browser-utils.js +28 -0
  56. package/lib/Utils/business.js +66 -70
  57. package/lib/Utils/chat-utils.js +331 -249
  58. package/lib/Utils/crypto.js +57 -91
  59. package/lib/Utils/decode-wa-message.js +168 -84
  60. package/lib/Utils/event-buffer.js +138 -80
  61. package/lib/Utils/generics.js +180 -297
  62. package/lib/Utils/history.js +83 -49
  63. package/lib/Utils/identity-change-handler.js +48 -0
  64. package/lib/Utils/index.js +19 -33
  65. package/lib/Utils/link-preview.js +14 -23
  66. package/lib/Utils/logger.js +2 -7
  67. package/lib/Utils/lt-hash.js +2 -46
  68. package/lib/Utils/make-mutex.js +24 -47
  69. package/lib/Utils/message-retry-manager.js +224 -0
  70. package/lib/Utils/messages-media.js +501 -496
  71. package/lib/Utils/messages.js +1428 -362
  72. package/lib/Utils/noise-handler.js +145 -100
  73. package/lib/Utils/pre-key-manager.js +105 -0
  74. package/lib/Utils/process-message.js +356 -150
  75. package/lib/Utils/reporting-utils.js +257 -0
  76. package/lib/Utils/signal.js +78 -73
  77. package/lib/Utils/sync-action-utils.js +47 -0
  78. package/lib/Utils/tc-token-utils.js +17 -0
  79. package/lib/Utils/use-multi-file-auth-state.js +35 -45
  80. package/lib/Utils/validate-connection.js +91 -107
  81. package/lib/WABinary/constants.js +1300 -1304
  82. package/lib/WABinary/decode.js +26 -48
  83. package/lib/WABinary/encode.js +109 -155
  84. package/lib/WABinary/generic-utils.js +161 -149
  85. package/lib/WABinary/index.js +5 -21
  86. package/lib/WABinary/jid-utils.js +73 -40
  87. package/lib/WABinary/types.js +1 -2
  88. package/lib/WAM/BinaryInfo.js +2 -6
  89. package/lib/WAM/constants.js +19070 -11568
  90. package/lib/WAM/encode.js +17 -23
  91. package/lib/WAM/index.js +3 -19
  92. package/lib/WAUSync/Protocols/USyncContactProtocol.js +8 -12
  93. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +11 -15
  94. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +9 -13
  95. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +9 -14
  96. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +20 -23
  97. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +13 -9
  98. package/lib/WAUSync/Protocols/index.js +4 -20
  99. package/lib/WAUSync/USyncQuery.js +40 -36
  100. package/lib/WAUSync/USyncUser.js +2 -6
  101. package/lib/WAUSync/index.js +3 -19
  102. package/lib/index.js +11 -44
  103. package/package.json +74 -107
  104. package/lib/Defaults/baileys-version.json +0 -3
  105. package/lib/Defaults/phonenumber-mcc.json +0 -223
  106. package/lib/Signal/Group/queue-job.js +0 -57
  107. package/lib/Socket/Client/abstract-socket-client.js +0 -13
  108. package/lib/Socket/Client/mobile-socket-client.js +0 -65
  109. package/lib/Socket/Client/web-socket-client.js +0 -118
  110. package/lib/Socket/groupStatus.js +0 -637
  111. package/lib/Socket/registration.js +0 -166
  112. package/lib/Socket/usync.js +0 -70
  113. package/lib/Store/make-cache-manager-store.js +0 -83
  114. package/lib/Utils/baileys-event-stream.js +0 -63
@@ -1,44 +1,14 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- var __importDefault = (this && this.__importDefault) || function (mod) {
26
- return (mod && mod.__esModule) ? mod : { "default": mod };
27
- };
28
- Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.derivePairingCodeKey = exports.hkdf = exports.md5 = exports.sha256 = exports.hmacSign = exports.aesEncrypWithIV = exports.aesEncrypt = exports.aesDecryptWithIV = exports.aesDecrypt = exports.aesDecryptCTR = exports.aesEncryptCTR = exports.aesDecryptGCM = exports.aesEncryptGCM = exports.signedKeyPair = exports.Curve = exports.generateSignalPubKey = void 0;
30
- const crypto_1 = require("crypto");
31
- const futoin_hkdf_1 = __importDefault(require("futoin-hkdf"));
32
- const libsignal = __importStar(require("libsignal"));
33
- const Defaults_1 = require("../Defaults");
1
+ import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes } from 'crypto';
2
+ import * as curve from 'libsignal/src/curve.js';
3
+ import { KEY_BUNDLE_TYPE } from '../Defaults/index.js';
4
+ export { md5, hkdf } from 'whatsapp-rust-bridge';
5
+ // insure browser & node compatibility
6
+ const { subtle } = globalThis.crypto;
34
7
  /** prefix version byte to the pub keys, required for some curve crypto functions */
35
- const generateSignalPubKey = (pubKey) => (pubKey.length === 33
36
- ? pubKey
37
- : Buffer.concat([Defaults_1.KEY_BUNDLE_TYPE, pubKey]));
38
- exports.generateSignalPubKey = generateSignalPubKey;
39
- exports.Curve = {
8
+ export const generateSignalPubKey = (pubKey) => pubKey.length === 33 ? pubKey : Buffer.concat([KEY_BUNDLE_TYPE, pubKey]);
9
+ export const Curve = {
40
10
  generateKeyPair: () => {
41
- const { pubKey, privKey } = libsignal.curve.generateKeyPair();
11
+ const { pubKey, privKey } = curve.generateKeyPair();
42
12
  return {
43
13
  private: Buffer.from(privKey),
44
14
  // remove version byte
@@ -46,13 +16,13 @@ exports.Curve = {
46
16
  };
47
17
  },
48
18
  sharedKey: (privateKey, publicKey) => {
49
- const shared = libsignal.curve.calculateAgreement((0, exports.generateSignalPubKey)(publicKey), privateKey);
19
+ const shared = curve.calculateAgreement(generateSignalPubKey(publicKey), privateKey);
50
20
  return Buffer.from(shared);
51
21
  },
52
- sign: (privateKey, buf) => (libsignal.curve.calculateSignature(privateKey, buf)),
22
+ sign: (privateKey, buf) => curve.calculateSignature(privateKey, buf),
53
23
  verify: (pubKey, message, signature) => {
54
24
  try {
55
- libsignal.curve.verifySignature((0, exports.generateSignalPubKey)(pubKey), message, signature);
25
+ curve.verifySignature(generateSignalPubKey(pubKey), message, signature);
56
26
  return true;
57
27
  }
58
28
  catch (error) {
@@ -60,30 +30,28 @@ exports.Curve = {
60
30
  }
61
31
  }
62
32
  };
63
- const signedKeyPair = (identityKeyPair, keyId) => {
64
- const preKey = exports.Curve.generateKeyPair();
65
- const pubKey = (0, exports.generateSignalPubKey)(preKey.public);
66
- const signature = exports.Curve.sign(identityKeyPair.private, pubKey);
33
+ export const signedKeyPair = (identityKeyPair, keyId) => {
34
+ const preKey = Curve.generateKeyPair();
35
+ const pubKey = generateSignalPubKey(preKey.public);
36
+ const signature = Curve.sign(identityKeyPair.private, pubKey);
67
37
  return { keyPair: preKey, signature, keyId };
68
38
  };
69
- exports.signedKeyPair = signedKeyPair;
70
39
  const GCM_TAG_LENGTH = 128 >> 3;
71
40
  /**
72
41
  * encrypt AES 256 GCM;
73
42
  * where the tag tag is suffixed to the ciphertext
74
43
  * */
75
- function aesEncryptGCM(plaintext, key, iv, additionalData) {
76
- const cipher = (0, crypto_1.createCipheriv)('aes-256-gcm', key, iv);
44
+ export function aesEncryptGCM(plaintext, key, iv, additionalData) {
45
+ const cipher = createCipheriv('aes-256-gcm', key, iv);
77
46
  cipher.setAAD(additionalData);
78
47
  return Buffer.concat([cipher.update(plaintext), cipher.final(), cipher.getAuthTag()]);
79
48
  }
80
- exports.aesEncryptGCM = aesEncryptGCM;
81
49
  /**
82
50
  * decrypt AES 256 GCM;
83
51
  * where the auth tag is suffixed to the ciphertext
84
52
  * */
85
- function aesDecryptGCM(ciphertext, key, iv, additionalData) {
86
- const decipher = (0, crypto_1.createDecipheriv)('aes-256-gcm', key, iv);
53
+ export function aesDecryptGCM(ciphertext, key, iv, additionalData) {
54
+ const decipher = createDecipheriv('aes-256-gcm', key, iv);
87
55
  // decrypt additional adata
88
56
  const enc = ciphertext.slice(0, ciphertext.length - GCM_TAG_LENGTH);
89
57
  const tag = ciphertext.slice(ciphertext.length - GCM_TAG_LENGTH);
@@ -92,60 +60,58 @@ function aesDecryptGCM(ciphertext, key, iv, additionalData) {
92
60
  decipher.setAuthTag(tag);
93
61
  return Buffer.concat([decipher.update(enc), decipher.final()]);
94
62
  }
95
- exports.aesDecryptGCM = aesDecryptGCM;
96
- function aesEncryptCTR(plaintext, key, iv) {
97
- const cipher = (0, crypto_1.createCipheriv)('aes-256-ctr', key, iv);
63
+ export function aesEncryptCTR(plaintext, key, iv) {
64
+ const cipher = createCipheriv('aes-256-ctr', key, iv);
98
65
  return Buffer.concat([cipher.update(plaintext), cipher.final()]);
99
66
  }
100
- exports.aesEncryptCTR = aesEncryptCTR;
101
- function aesDecryptCTR(ciphertext, key, iv) {
102
- const decipher = (0, crypto_1.createDecipheriv)('aes-256-ctr', key, iv);
67
+ export function aesDecryptCTR(ciphertext, key, iv) {
68
+ const decipher = createDecipheriv('aes-256-ctr', key, iv);
103
69
  return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
104
70
  }
105
- exports.aesDecryptCTR = aesDecryptCTR;
106
71
  /** decrypt AES 256 CBC; where the IV is prefixed to the buffer */
107
- function aesDecrypt(buffer, key) {
108
- return aesDecryptWithIV(buffer.slice(16, buffer.length), key, buffer.slice(0, 16));
72
+ export function aesDecrypt(buffer, key) {
73
+ return aesDecryptWithIV(buffer.subarray(16), key, buffer.subarray(0, 16));
109
74
  }
110
- exports.aesDecrypt = aesDecrypt;
111
75
  /** decrypt AES 256 CBC */
112
- function aesDecryptWithIV(buffer, key, IV) {
113
- const aes = (0, crypto_1.createDecipheriv)('aes-256-cbc', key, IV);
76
+ export function aesDecryptWithIV(buffer, key, IV) {
77
+ const aes = createDecipheriv('aes-256-cbc', key, IV);
114
78
  return Buffer.concat([aes.update(buffer), aes.final()]);
115
79
  }
116
- exports.aesDecryptWithIV = aesDecryptWithIV;
117
80
  // encrypt AES 256 CBC; where a random IV is prefixed to the buffer
118
- function aesEncrypt(buffer, key) {
119
- const IV = (0, crypto_1.randomBytes)(16);
120
- const aes = (0, crypto_1.createCipheriv)('aes-256-cbc', key, IV);
81
+ export function aesEncrypt(buffer, key) {
82
+ const IV = randomBytes(16);
83
+ const aes = createCipheriv('aes-256-cbc', key, IV);
121
84
  return Buffer.concat([IV, aes.update(buffer), aes.final()]); // prefix IV to the buffer
122
85
  }
123
- exports.aesEncrypt = aesEncrypt;
124
86
  // encrypt AES 256 CBC with a given IV
125
- function aesEncrypWithIV(buffer, key, IV) {
126
- const aes = (0, crypto_1.createCipheriv)('aes-256-cbc', key, IV);
87
+ export function aesEncrypWithIV(buffer, key, IV) {
88
+ const aes = createCipheriv('aes-256-cbc', key, IV);
127
89
  return Buffer.concat([aes.update(buffer), aes.final()]); // prefix IV to the buffer
128
90
  }
129
- exports.aesEncrypWithIV = aesEncrypWithIV;
130
91
  // sign HMAC using SHA 256
131
- function hmacSign(buffer, key, variant = 'sha256') {
132
- return (0, crypto_1.createHmac)(variant, key).update(buffer).digest();
133
- }
134
- exports.hmacSign = hmacSign;
135
- function sha256(buffer) {
136
- return (0, crypto_1.createHash)('sha256').update(buffer).digest();
137
- }
138
- exports.sha256 = sha256;
139
- function md5(buffer) {
140
- return (0, crypto_1.createHash)('md5').update(buffer).digest();
141
- }
142
- exports.md5 = md5;
143
- // HKDF key expansion
144
- function hkdf(buffer, expandedLength, info) {
145
- return (0, futoin_hkdf_1.default)(!Buffer.isBuffer(buffer) ? Buffer.from(buffer) : buffer, expandedLength, info);
92
+ export function hmacSign(buffer, key, variant = 'sha256') {
93
+ return createHmac(variant, key).update(buffer).digest();
146
94
  }
147
- exports.hkdf = hkdf;
148
- function derivePairingCodeKey(pairingCode, salt) {
149
- return (0, crypto_1.pbkdf2Sync)(pairingCode, salt, 2 << 16, 32, 'sha256');
95
+ export function sha256(buffer) {
96
+ return createHash('sha256').update(buffer).digest();
150
97
  }
151
- exports.derivePairingCodeKey = derivePairingCodeKey;
98
+ export async function derivePairingCodeKey(pairingCode, salt) {
99
+ // Convert inputs to formats Web Crypto API can work with
100
+ const encoder = new TextEncoder();
101
+ const pairingCodeBuffer = encoder.encode(pairingCode);
102
+ const saltBuffer = new Uint8Array(salt instanceof Uint8Array ? salt : new Uint8Array(salt));
103
+ // Import the pairing code as key material
104
+ const keyMaterial = await subtle.importKey('raw', pairingCodeBuffer, { name: 'PBKDF2' }, false, [
105
+ 'deriveBits'
106
+ ]);
107
+ // Derive bits using PBKDF2 with the same parameters
108
+ // 2 << 16 = 131,072 iterations
109
+ const derivedBits = await subtle.deriveBits({
110
+ name: 'PBKDF2',
111
+ salt: saltBuffer,
112
+ iterations: 2 << 16,
113
+ hash: 'SHA-256'
114
+ }, keyMaterial, 32 * 8 // 32 bytes * 8 = 256 bits
115
+ );
116
+ return Buffer.from(derivedBits);
117
+ }
@@ -1,43 +1,103 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.decryptMessageNode = exports.decodeMessageNode = void 0;
4
- const boom_1 = require("@hapi/boom");
5
- const WAProto_1 = require("../../WAProto");
6
- const WABinary_1 = require("../WABinary");
7
- const generics_1 = require("./generics");
8
- const NO_MESSAGE_FOUND_ERROR_TEXT = 'Message absent from node';
1
+ import { Boom } from '@hapi/boom';
2
+ import { proto } from '../../WAProto/index.js';
3
+ import { areJidsSameUser, isHostedLidUser, isHostedPnUser, isJidBroadcast, isJidGroup, isJidMetaAI, isJidNewsletter, isJidStatusBroadcast, isLidUser, isPnUser
4
+ // transferDevice
5
+ } from '../WABinary/index.js';
6
+ import { unpadRandomMax16 } from './generics.js';
7
+ export const getDecryptionJid = async (sender, repository) => {
8
+ if (isLidUser(sender) || isHostedLidUser(sender)) {
9
+ return sender;
10
+ }
11
+ const mapped = await repository.lidMapping.getLIDForPN(sender);
12
+ return mapped || sender;
13
+ };
14
+ const storeMappingFromEnvelope = async (stanza, sender, repository, decryptionJid, logger) => {
15
+ // TODO: Handle hosted IDs
16
+ const { senderAlt } = extractAddressingContext(stanza);
17
+ if (senderAlt && isLidUser(senderAlt) && isPnUser(sender) && decryptionJid === sender) {
18
+ try {
19
+ await repository.lidMapping.storeLIDPNMappings([{ lid: senderAlt, pn: sender }]);
20
+ await repository.migrateSession(sender, senderAlt);
21
+ logger.debug({ sender, senderAlt }, 'Stored LID mapping from envelope');
22
+ }
23
+ catch (error) {
24
+ logger.warn({ sender, senderAlt, error }, 'Failed to store LID mapping');
25
+ }
26
+ }
27
+ };
28
+ export const NO_MESSAGE_FOUND_ERROR_TEXT = 'Message absent from node';
29
+ export const MISSING_KEYS_ERROR_TEXT = 'Key used already or never filled';
30
+ // Retry configuration for failed decryption
31
+ export const DECRYPTION_RETRY_CONFIG = {
32
+ maxRetries: 3,
33
+ baseDelayMs: 100,
34
+ sessionRecordErrors: ['No session record', 'SessionError: No session record']
35
+ };
36
+ export const NACK_REASONS = {
37
+ ParsingError: 487,
38
+ UnrecognizedStanza: 488,
39
+ UnrecognizedStanzaClass: 489,
40
+ UnrecognizedStanzaType: 490,
41
+ InvalidProtobuf: 491,
42
+ InvalidHostedCompanionStanza: 493,
43
+ MissingMessageSecret: 495,
44
+ SignalErrorOldCounter: 496,
45
+ MessageDeletedOnPeer: 499,
46
+ UnhandledError: 500,
47
+ UnsupportedAdminRevoke: 550,
48
+ UnsupportedLIDGroup: 551,
49
+ DBOperationFailed: 552
50
+ };
51
+ export const extractAddressingContext = (stanza) => {
52
+ let senderAlt;
53
+ let recipientAlt;
54
+ const sender = stanza.attrs.participant || stanza.attrs.from;
55
+ const addressingMode = stanza.attrs.addressing_mode || (sender?.endsWith('lid') ? 'lid' : 'pn');
56
+ if (addressingMode === 'lid') {
57
+ // Message is LID-addressed: sender is LID, extract corresponding PN
58
+ // without device data
59
+ senderAlt = stanza.attrs.participant_pn || stanza.attrs.sender_pn || stanza.attrs.peer_recipient_pn;
60
+ recipientAlt = stanza.attrs.recipient_pn;
61
+ // with device data
62
+ //if (sender && senderAlt) senderAlt = transferDevice(sender, senderAlt)
63
+ }
64
+ else {
65
+ // Message is PN-addressed: sender is PN, extract corresponding LID
66
+ // without device data
67
+ senderAlt = stanza.attrs.participant_lid || stanza.attrs.sender_lid || stanza.attrs.peer_recipient_lid;
68
+ recipientAlt = stanza.attrs.recipient_lid;
69
+ //with device data
70
+ //if (sender && senderAlt) senderAlt = transferDevice(sender, senderAlt)
71
+ }
72
+ return {
73
+ addressingMode,
74
+ senderAlt,
75
+ recipientAlt
76
+ };
77
+ };
9
78
  /**
10
79
  * Decode the received node as a message.
11
80
  * @note this will only parse the message, not decrypt it
12
81
  */
13
- function decodeMessageNode(stanza, meId, meLid) {
14
- var _a, _b;
82
+ export function decodeMessageNode(stanza, meId, meLid) {
15
83
  let msgType;
16
84
  let chatId;
17
85
  let author;
86
+ let fromMe = false;
18
87
  const msgId = stanza.attrs.id;
19
88
  const from = stanza.attrs.from;
20
89
  const participant = stanza.attrs.participant;
21
90
  const recipient = stanza.attrs.recipient;
22
- const isMe = (jid) => (0, WABinary_1.areJidsSameUser)(jid, meId);
23
- const isMeLid = (jid) => (0, WABinary_1.areJidsSameUser)(jid, meLid);
24
- if ((0, WABinary_1.isJidUser)(from)) {
25
- if (recipient) {
26
- if (!isMe(from)) {
27
- throw new boom_1.Boom('receipient present, but msg not from me', { data: stanza });
91
+ const addressingContext = extractAddressingContext(stanza);
92
+ const isMe = (jid) => areJidsSameUser(jid, meId);
93
+ const isMeLid = (jid) => areJidsSameUser(jid, meLid);
94
+ if (isPnUser(from) || isLidUser(from) || isHostedLidUser(from) || isHostedPnUser(from)) {
95
+ if (recipient && !isJidMetaAI(recipient)) {
96
+ if (!isMe(from) && !isMeLid(from)) {
97
+ throw new Boom('receipient present, but msg not from me', { data: stanza });
28
98
  }
29
- chatId = recipient;
30
- }
31
- else {
32
- chatId = from;
33
- }
34
- msgType = 'chat';
35
- author = from;
36
- }
37
- else if ((0, WABinary_1.isLidUser)(from)) {
38
- if (recipient) {
39
- if (!isMeLid(from)) {
40
- throw new boom_1.Boom('receipient present, but msg not from me', { data: stanza });
99
+ if (isMe(from) || isMeLid(from)) {
100
+ fromMe = true;
41
101
  }
42
102
  chatId = recipient;
43
103
  }
@@ -47,55 +107,63 @@ function decodeMessageNode(stanza, meId, meLid) {
47
107
  msgType = 'chat';
48
108
  author = from;
49
109
  }
50
- else if ((0, WABinary_1.isJidGroup)(from)) {
110
+ else if (isJidGroup(from)) {
51
111
  if (!participant) {
52
- throw new boom_1.Boom('No participant in group message');
112
+ throw new Boom('No participant in group message');
113
+ }
114
+ if (isMe(participant) || isMeLid(participant)) {
115
+ fromMe = true;
53
116
  }
54
117
  msgType = 'group';
55
118
  author = participant;
56
119
  chatId = from;
57
120
  }
58
- else if ((0, WABinary_1.isJidBroadcast)(from)) {
121
+ else if (isJidBroadcast(from)) {
59
122
  if (!participant) {
60
- throw new boom_1.Boom('No participant in group message');
123
+ throw new Boom('No participant in group message');
61
124
  }
62
125
  const isParticipantMe = isMe(participant);
63
- if ((0, WABinary_1.isJidStatusBroadcast)(from)) {
126
+ if (isJidStatusBroadcast(from)) {
64
127
  msgType = isParticipantMe ? 'direct_peer_status' : 'other_status';
65
128
  }
66
129
  else {
67
130
  msgType = isParticipantMe ? 'peer_broadcast' : 'other_broadcast';
68
131
  }
132
+ fromMe = isParticipantMe;
69
133
  chatId = from;
70
134
  author = participant;
71
135
  }
72
- else if ((0, WABinary_1.isJidNewsLetter)(from)) {
136
+ else if (isJidNewsletter(from)) {
73
137
  msgType = 'newsletter';
74
- author = from;
75
138
  chatId = from;
139
+ author = from;
140
+ if (isMe(from) || isMeLid(from)) {
141
+ fromMe = true;
142
+ }
76
143
  }
77
144
  else {
78
- throw new boom_1.Boom('Unknown message type', { data: stanza });
145
+ throw new Boom('Unknown message type', { data: stanza });
79
146
  }
80
- const fromMe = (0, WABinary_1.isJidNewsLetter)(from) ? !!((_a = stanza.attrs) === null || _a === void 0 ? void 0 : _a.is_sender) : ((0, WABinary_1.isLidUser)(from) ? isMeLid : isMe)(stanza.attrs.participant || stanza.attrs.from);
81
- const pushname = stanza.attrs.notify;
147
+ const pushname = stanza?.attrs?.notify;
82
148
  const key = {
83
149
  remoteJid: chatId,
150
+ remoteJidAlt: !isJidGroup(chatId) ? addressingContext.senderAlt : undefined,
84
151
  fromMe,
85
152
  id: msgId,
86
- participant
153
+ participant,
154
+ participantAlt: isJidGroup(chatId) ? addressingContext.senderAlt : undefined,
155
+ addressingMode: addressingContext.addressingMode,
156
+ ...(msgType === 'newsletter' && stanza.attrs.server_id ? { server_id: stanza.attrs.server_id } : {})
87
157
  };
88
158
  const fullMessage = {
89
159
  key,
160
+ category: stanza.attrs.category,
90
161
  messageTimestamp: +stanza.attrs.t,
91
162
  pushName: pushname,
92
- broadcast: (0, WABinary_1.isJidBroadcast)(from)
163
+ broadcast: isJidBroadcast(from)
93
164
  };
94
- if (msgType === 'newsletter') {
95
- fullMessage.newsletterServerId = +((_b = stanza.attrs) === null || _b === void 0 ? void 0 : _b.server_id);
96
- }
97
165
  if (key.fromMe) {
98
- fullMessage.status = WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK;
166
+ fullMessage.status = proto.WebMessageInfo.Status.SERVER_ACK;
99
167
  }
100
168
  return {
101
169
  fullMessage,
@@ -103,44 +171,28 @@ function decodeMessageNode(stanza, meId, meLid) {
103
171
  sender: msgType === 'chat' ? author : chatId
104
172
  };
105
173
  }
106
- exports.decodeMessageNode = decodeMessageNode;
107
- const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
174
+ export const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
108
175
  const { fullMessage, author, sender } = decodeMessageNode(stanza, meId, meLid);
109
176
  return {
110
177
  fullMessage,
111
178
  category: stanza.attrs.category,
112
179
  author,
113
180
  async decrypt() {
114
- var _a;
115
181
  let decryptables = 0;
116
- async function processSenderKeyDistribution(msg) {
117
- if (msg.senderKeyDistributionMessage) {
118
- try {
119
- await repository.processSenderKeyDistributionMessage({
120
- authorJid: author,
121
- item: msg.senderKeyDistributionMessage
122
- });
123
- }
124
- catch (err) {
125
- logger.error({ key: fullMessage.key, err }, 'failed to process senderKeyDistribution');
126
- }
127
- }
128
- }
129
- if ((0, WABinary_1.isJidNewsLetter)(fullMessage.key.remoteJid)) {
130
- const node = (0, WABinary_1.getBinaryNodeChild)(stanza, 'plaintext');
131
- const msg = WAProto_1.proto.Message.decode(node === null || node === void 0 ? void 0 : node.content);
132
- await processSenderKeyDistribution(msg);
133
- fullMessage.message = msg;
134
- decryptables += 1;
135
- }
136
- else if (Array.isArray(stanza.content)) {
182
+ if (Array.isArray(stanza.content)) {
137
183
  for (const { tag, attrs, content } of stanza.content) {
138
184
  if (tag === 'verified_name' && content instanceof Uint8Array) {
139
- const cert = WAProto_1.proto.VerifiedNameCertificate.decode(content);
140
- const details = WAProto_1.proto.VerifiedNameCertificate.Details.decode(cert.details);
185
+ const cert = proto.VerifiedNameCertificate.decode(content);
186
+ const details = proto.VerifiedNameCertificate.Details.decode(cert.details);
141
187
  fullMessage.verifiedBizName = details.verifiedName;
142
188
  }
143
- if (tag !== 'enc') {
189
+ if (tag === 'unavailable' && attrs.type === 'view_once') {
190
+ fullMessage.key.isViewOnce = true; // TODO: remove from here and add a STUB TYPE
191
+ }
192
+ if (attrs.count && tag === 'enc') {
193
+ fullMessage.retryCount = Number(attrs.count);
194
+ }
195
+ if (tag !== 'enc' && tag !== 'plaintext') {
144
196
  continue;
145
197
  }
146
198
  if (!(content instanceof Uint8Array)) {
@@ -148,8 +200,13 @@ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
148
200
  }
149
201
  decryptables += 1;
150
202
  let msgBuffer;
203
+ const decryptionJid = await getDecryptionJid(author, repository);
204
+ if (tag !== 'plaintext') {
205
+ // TODO: Handle hosted devices
206
+ await storeMappingFromEnvelope(stanza, author, repository, decryptionJid, logger);
207
+ }
151
208
  try {
152
- const e2eType = attrs.type;
209
+ const e2eType = tag === 'plaintext' ? 'plaintext' : attrs.type;
153
210
  switch (e2eType) {
154
211
  case 'skmsg':
155
212
  msgBuffer = await repository.decryptGroupMessage({
@@ -160,19 +217,32 @@ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
160
217
  break;
161
218
  case 'pkmsg':
162
219
  case 'msg':
163
- const user = (0, WABinary_1.isJidUser)(sender) ? sender : author;
164
220
  msgBuffer = await repository.decryptMessage({
165
- jid: user,
221
+ jid: decryptionJid,
166
222
  type: e2eType,
167
223
  ciphertext: content
168
224
  });
169
225
  break;
226
+ case 'plaintext':
227
+ msgBuffer = content;
228
+ break;
170
229
  default:
171
230
  throw new Error(`Unknown e2e type: ${e2eType}`);
172
231
  }
173
- let msg = WAProto_1.proto.Message.decode((0, generics_1.unpadRandomMax16)(msgBuffer));
174
- msg = ((_a = msg.deviceSentMessage) === null || _a === void 0 ? void 0 : _a.message) || msg;
175
- await processSenderKeyDistribution(msg);
232
+ let msg = proto.Message.decode(e2eType !== 'plaintext' ? unpadRandomMax16(msgBuffer) : msgBuffer);
233
+ msg = msg.deviceSentMessage?.message || msg;
234
+ if (msg.senderKeyDistributionMessage) {
235
+ //eslint-disable-next-line max-depth
236
+ try {
237
+ await repository.processSenderKeyDistributionMessage({
238
+ authorJid: author,
239
+ item: msg.senderKeyDistributionMessage
240
+ });
241
+ }
242
+ catch (err) {
243
+ logger.error({ key: fullMessage.key, err }, 'failed to process sender key distribution message');
244
+ }
245
+ }
176
246
  if (fullMessage.message) {
177
247
  Object.assign(fullMessage.message, msg);
178
248
  }
@@ -181,18 +251,32 @@ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
181
251
  }
182
252
  }
183
253
  catch (err) {
184
- logger.error({ key: fullMessage.key, err }, 'failed to decrypt message');
185
- fullMessage.messageStubType = WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT;
186
- fullMessage.messageStubParameters = [err.message];
254
+ const errorContext = {
255
+ key: fullMessage.key,
256
+ err,
257
+ messageType: tag === 'plaintext' ? 'plaintext' : attrs.type,
258
+ sender,
259
+ author,
260
+ isSessionRecordError: isSessionRecordError(err)
261
+ };
262
+ logger.error(errorContext, 'failed to decrypt message');
263
+ fullMessage.messageStubType = proto.WebMessageInfo.StubType.CIPHERTEXT;
264
+ fullMessage.messageStubParameters = [err.message.toString()];
187
265
  }
188
266
  }
189
267
  }
190
268
  // if nothing was found to decrypt
191
- if (!decryptables) {
192
- fullMessage.messageStubType = WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT;
193
- fullMessage.messageStubParameters = [NO_MESSAGE_FOUND_ERROR_TEXT, JSON.stringify(stanza, generics_1.BufferJSON.replacer)];
269
+ if (!decryptables && !fullMessage.key?.isViewOnce) {
270
+ fullMessage.messageStubType = proto.WebMessageInfo.StubType.CIPHERTEXT;
271
+ fullMessage.messageStubParameters = [NO_MESSAGE_FOUND_ERROR_TEXT];
194
272
  }
195
273
  }
196
274
  };
197
275
  };
198
- exports.decryptMessageNode = decryptMessageNode;
276
+ /**
277
+ * Utility function to check if an error is related to missing session record
278
+ */
279
+ function isSessionRecordError(error) {
280
+ const errorMessage = error?.message || error?.toString() || '';
281
+ return DECRYPTION_RETRY_CONFIG.sessionRecordErrors.some(errorPattern => errorMessage.includes(errorPattern));
282
+ }