@kanaraa/baileys 3.1.8

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 (107) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1426 -0
  3. package/WAProto/GenerateStatics.sh +3 -0
  4. package/WAProto/WAProto.proto +5479 -0
  5. package/WAProto/fix-imports.js +85 -0
  6. package/WAProto/index.js +97691 -0
  7. package/engine-requirements.js +10 -0
  8. package/lib/Defaults/index.js +128 -0
  9. package/lib/Signal/Group/ciphertext-message.js +11 -0
  10. package/lib/Signal/Group/group-session-builder.js +29 -0
  11. package/lib/Signal/Group/group_cipher.js +81 -0
  12. package/lib/Signal/Group/index.js +11 -0
  13. package/lib/Signal/Group/keyhelper.js +17 -0
  14. package/lib/Signal/Group/sender-chain-key.js +25 -0
  15. package/lib/Signal/Group/sender-key-distribution-message.js +62 -0
  16. package/lib/Signal/Group/sender-key-message.js +65 -0
  17. package/lib/Signal/Group/sender-key-name.js +47 -0
  18. package/lib/Signal/Group/sender-key-record.js +40 -0
  19. package/lib/Signal/Group/sender-key-state.js +83 -0
  20. package/lib/Signal/Group/sender-message-key.js +25 -0
  21. package/lib/Signal/libsignal.js +430 -0
  22. package/lib/Signal/lid-mapping.js +276 -0
  23. package/lib/Socket/Client/index.js +2 -0
  24. package/lib/Socket/Client/types.js +10 -0
  25. package/lib/Socket/Client/websocket.js +53 -0
  26. package/lib/Socket/business.js +378 -0
  27. package/lib/Socket/chats.js +1192 -0
  28. package/lib/Socket/communities.js +430 -0
  29. package/lib/Socket/groups.js +346 -0
  30. package/lib/Socket/index.js +11 -0
  31. package/lib/Socket/messages-recv.js +1785 -0
  32. package/lib/Socket/messages-send.js +1174 -0
  33. package/lib/Socket/mex.js +41 -0
  34. package/lib/Socket/newsletter.js +180 -0
  35. package/lib/Socket/socket.js +966 -0
  36. package/lib/Types/Auth.js +1 -0
  37. package/lib/Types/Bussines.js +1 -0
  38. package/lib/Types/Call.js +1 -0
  39. package/lib/Types/Chat.js +7 -0
  40. package/lib/Types/Contact.js +1 -0
  41. package/lib/Types/Events.js +1 -0
  42. package/lib/Types/GroupMetadata.js +1 -0
  43. package/lib/Types/Label.js +24 -0
  44. package/lib/Types/LabelAssociation.js +6 -0
  45. package/lib/Types/Message.js +10 -0
  46. package/lib/Types/Mex.js +36 -0
  47. package/lib/Types/Product.js +1 -0
  48. package/lib/Types/Signal.js +1 -0
  49. package/lib/Types/Socket.js +2 -0
  50. package/lib/Types/State.js +55 -0
  51. package/lib/Types/USync.js +1 -0
  52. package/lib/Types/index.js +25 -0
  53. package/lib/Utils/auth-utils.js +301 -0
  54. package/lib/Utils/browser-utils.js +27 -0
  55. package/lib/Utils/business.js +230 -0
  56. package/lib/Utils/chat-utils.js +871 -0
  57. package/lib/Utils/companion-reg-client-utils.js +34 -0
  58. package/lib/Utils/crypto.js +117 -0
  59. package/lib/Utils/decode-wa-message.js +316 -0
  60. package/lib/Utils/event-buffer.js +621 -0
  61. package/lib/Utils/generics.js +392 -0
  62. package/lib/Utils/history.js +133 -0
  63. package/lib/Utils/identity-change-handler.js +49 -0
  64. package/lib/Utils/index.js +22 -0
  65. package/lib/Utils/interactive-send.js +136 -0
  66. package/lib/Utils/link-preview.js +84 -0
  67. package/lib/Utils/logger.js +2 -0
  68. package/lib/Utils/lt-hash.js +7 -0
  69. package/lib/Utils/make-mutex.js +32 -0
  70. package/lib/Utils/message-retry-manager.js +264 -0
  71. package/lib/Utils/messages-media.js +787 -0
  72. package/lib/Utils/messages.js +2306 -0
  73. package/lib/Utils/noise-handler.js +200 -0
  74. package/lib/Utils/offline-node-processor.js +39 -0
  75. package/lib/Utils/pre-key-manager.js +105 -0
  76. package/lib/Utils/process-message.js +629 -0
  77. package/lib/Utils/reporting-utils.js +257 -0
  78. package/lib/Utils/signal.js +200 -0
  79. package/lib/Utils/stanza-ack.js +37 -0
  80. package/lib/Utils/sync-action-utils.js +48 -0
  81. package/lib/Utils/tc-token-utils.js +162 -0
  82. package/lib/Utils/use-multi-file-auth-state.js +120 -0
  83. package/lib/Utils/validate-connection.js +202 -0
  84. package/lib/WABinary/constants.js +1300 -0
  85. package/lib/WABinary/decode.js +261 -0
  86. package/lib/WABinary/encode.js +219 -0
  87. package/lib/WABinary/generic-utils.js +112 -0
  88. package/lib/WABinary/index.js +5 -0
  89. package/lib/WABinary/jid-utils.js +95 -0
  90. package/lib/WABinary/types.js +1 -0
  91. package/lib/WAM/BinaryInfo.js +9 -0
  92. package/lib/WAM/constants.js +22852 -0
  93. package/lib/WAM/encode.js +149 -0
  94. package/lib/WAM/index.js +3 -0
  95. package/lib/WAUSync/Protocols/USyncContactProtocol.js +51 -0
  96. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
  97. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  98. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  99. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  100. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +50 -0
  101. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  102. package/lib/WAUSync/Protocols/index.js +5 -0
  103. package/lib/WAUSync/USyncQuery.js +97 -0
  104. package/lib/WAUSync/USyncUser.js +30 -0
  105. package/lib/WAUSync/index.js +3 -0
  106. package/lib/index.js +10 -0
  107. package/package.json +75 -0
@@ -0,0 +1,136 @@
1
+ import { generateWAMessageContent, generateWAMessageFromContent, getDevice } from './messages.js';
2
+
3
+ /**
4
+ * True if the message being quoted/replied-to was sent from an iOS device.
5
+ * iOS WhatsApp has historically had weaker/inconsistent support for the
6
+ * "interactiveMessage" wrapper trick used by send()/sendMedia() below, so
7
+ * both functions fall back to a plain sendMessage() for iOS senders.
8
+ *
9
+ * Self-contained: does not read or write any global state.
10
+ */
11
+ export const isIosSender = (quotedMsg) => {
12
+ try {
13
+ const id = quotedMsg?.key?.id;
14
+ if (!id)
15
+ return false;
16
+ return getDevice(id) === 'ios';
17
+ }
18
+ catch {
19
+ return false;
20
+ }
21
+ };
22
+
23
+ /**
24
+ * Send a text message, styled as a borderless "interactive" bubble on
25
+ * platforms that support it (Android/Web), falling back to a normal text
26
+ * message for iOS senders or if anything goes wrong building the
27
+ * interactive payload.
28
+ *
29
+ * @param {import('../Socket/index.js').WASocket} sock
30
+ * @param {string} jid
31
+ * @param {object} quotedMsg
32
+ * @param {string} text
33
+ * @param {string[]} [mentions]
34
+ * @returns {Promise<object>} the sent message (with .key.id etc.)
35
+ */
36
+ export const send = async (sock, jid, quotedMsg, text, mentions = []) => {
37
+ try {
38
+ if (isIosSender(quotedMsg)) {
39
+ return await sock.sendMessage(jid, { text: String(text ?? ''), ...(mentions.length > 0 ? { mentions } : {}) }, { quoted: quotedMsg });
40
+ }
41
+ const built = generateWAMessageFromContent(jid, {
42
+ viewOnceMessage: {
43
+ message: {
44
+ interactiveMessage: {
45
+ body: { text: '' },
46
+ footer: { text: String(text ?? '') },
47
+ nativeFlowMessage: { buttons: [] },
48
+ ...(mentions.length > 0 ? { contextInfo: { mentionedJid: mentions } } : {})
49
+ }
50
+ }
51
+ }
52
+ }, {
53
+ quoted: quotedMsg,
54
+ userJid: quotedMsg?.key?.participant ?? quotedMsg?.key?.remoteJid ?? jid
55
+ });
56
+ await sock.relayMessage(jid, built.message, { messageId: built.key.id });
57
+ return built;
58
+ }
59
+ catch (error) {
60
+ console.error('[send] fallback to simple text:', error.message);
61
+ return await sock.sendMessage(jid, { text: String(text ?? ''), ...(mentions.length > 0 ? { mentions } : {}) }, { quoted: quotedMsg });
62
+ }
63
+ };
64
+
65
+ /**
66
+ * Send an image or video (as buffer, url, or existing Buffer), styled as an
67
+ * interactive bubble when there's a caption and the sender isn't on iOS;
68
+ * otherwise falls back to a plain image/video message.
69
+ *
70
+ * @param {import('../Socket/index.js').WASocket} sock
71
+ * @param {string} jid
72
+ * @param {object} quotedMsg
73
+ * @param {Buffer|string} src
74
+ * @param {string} mime
75
+ * @param {string} caption
76
+ * @param {string[]} [mentions]
77
+ * @returns {Promise<object>} the sent message (with .key.id etc.)
78
+ */
79
+ export const sendMedia = async (sock, jid, quotedMsg, src, mime, caption, mentions = []) => {
80
+ try {
81
+ const isVideo = mime?.startsWith('video');
82
+ let buf;
83
+ if (Buffer.isBuffer(src)) {
84
+ buf = src;
85
+ }
86
+ else {
87
+ const res = await fetch(src);
88
+ if (!res.ok)
89
+ throw new Error('Gagal fetch media');
90
+ buf = Buffer.from(await res.arrayBuffer());
91
+ }
92
+ const hasCaption = String(caption ?? '').trim().length > 0;
93
+ if (isIosSender(quotedMsg) || !hasCaption) {
94
+ const payload = isVideo
95
+ ? { video: buf, mimetype: mime ?? 'video/mp4', caption: String(caption ?? '') }
96
+ : { image: buf, mimetype: mime ?? 'image/jpeg', caption: String(caption ?? '') };
97
+ return await sock.sendMessage(jid, { ...payload, ...(mentions.length > 0 ? { mentions } : {}) }, { quoted: quotedMsg });
98
+ }
99
+ const generated = await generateWAMessageContent(isVideo ? { video: buf, mimetype: mime ?? 'video/mp4' } : { image: buf, mimetype: mime ?? 'image/jpeg' }, { upload: sock.waUploadToServer });
100
+ const mediaMsg = isVideo
101
+ ? (generated?.videoMessage ?? null)
102
+ : (generated?.imageMessage ?? null);
103
+ const header = mediaMsg
104
+ ? (isVideo
105
+ ? { videoMessage: mediaMsg, hasMediaAttachment: true }
106
+ : { imageMessage: mediaMsg, hasMediaAttachment: true })
107
+ : { title: '' };
108
+ const built = generateWAMessageFromContent(jid, {
109
+ viewOnceMessage: {
110
+ message: {
111
+ interactiveMessage: {
112
+ header,
113
+ body: { text: '' },
114
+ footer: { text: String(caption ?? '') },
115
+ nativeFlowMessage: { buttons: [] },
116
+ contextInfo: {
117
+ stanzaId: quotedMsg.key.id,
118
+ participant: quotedMsg.key.participant || quotedMsg.key.remoteJid,
119
+ quotedMessage: quotedMsg.message,
120
+ ...(mentions.length > 0 ? { mentionedJid: mentions } : {})
121
+ }
122
+ }
123
+ }
124
+ }
125
+ }, {
126
+ quoted: quotedMsg,
127
+ userJid: quotedMsg.key.participant ?? quotedMsg.key.remoteJid ?? jid
128
+ });
129
+ await sock.relayMessage(jid, built.message, { messageId: built.key.id });
130
+ return built;
131
+ }
132
+ catch (error) {
133
+ console.error('[sendMedia] error:', error.message);
134
+ throw error;
135
+ }
136
+ };
@@ -0,0 +1,84 @@
1
+ import { prepareWAMessageMedia } from './messages.js';
2
+ import { extractImageThumb, getHttpStream } from './messages-media.js';
3
+ const THUMBNAIL_WIDTH_PX = 192;
4
+ /** Fetches an image and generates a thumbnail for it */
5
+ const getCompressedJpegThumbnail = async (url, { thumbnailWidth, fetchOpts }) => {
6
+ const stream = await getHttpStream(url, fetchOpts);
7
+ const result = await extractImageThumb(stream, thumbnailWidth);
8
+ return result;
9
+ };
10
+ /**
11
+ * Given a piece of text, checks for any URL present, generates link preview for the same and returns it
12
+ * Return undefined if the fetch failed or no URL was found
13
+ * @param text first matched URL in text
14
+ * @returns the URL info required to generate link preview
15
+ */
16
+ export const getUrlInfo = async (text, opts = {
17
+ thumbnailWidth: THUMBNAIL_WIDTH_PX,
18
+ fetchOpts: { timeout: 3000 }
19
+ }) => {
20
+ try {
21
+ // retries
22
+ let retries = 0;
23
+ const maxRetry = 5;
24
+ const { getLinkPreview } = await import('link-preview-js');
25
+ let previewLink = text;
26
+ if (!text.startsWith('https://') && !text.startsWith('http://')) {
27
+ previewLink = 'https://' + previewLink;
28
+ }
29
+ const info = await getLinkPreview(previewLink, {
30
+ ...opts.fetchOpts,
31
+ followRedirects: 'follow',
32
+ handleRedirects: (baseURL, forwardedURL) => {
33
+ const urlObj = new URL(baseURL);
34
+ const forwardedURLObj = new URL(forwardedURL);
35
+ if (retries >= maxRetry) {
36
+ return false;
37
+ }
38
+ if (forwardedURLObj.hostname === urlObj.hostname ||
39
+ forwardedURLObj.hostname === 'www.' + urlObj.hostname ||
40
+ 'www.' + forwardedURLObj.hostname === urlObj.hostname) {
41
+ retries += 1;
42
+ return true;
43
+ }
44
+ else {
45
+ return false;
46
+ }
47
+ },
48
+ headers: opts.fetchOpts?.headers
49
+ });
50
+ if (info && 'title' in info && info.title) {
51
+ const [image] = info.images;
52
+ const urlInfo = {
53
+ 'canonical-url': info.url,
54
+ 'matched-text': text,
55
+ title: info.title,
56
+ description: info.description,
57
+ originalThumbnailUrl: image
58
+ };
59
+ if (opts.uploadImage) {
60
+ const { imageMessage } = await prepareWAMessageMedia({ image: { url: image } }, {
61
+ upload: opts.uploadImage,
62
+ mediaTypeOverride: 'thumbnail-link',
63
+ options: opts.fetchOpts
64
+ });
65
+ urlInfo.jpegThumbnail = imageMessage?.jpegThumbnail ? Buffer.from(imageMessage.jpegThumbnail) : undefined;
66
+ urlInfo.highQualityThumbnail = imageMessage || undefined;
67
+ }
68
+ else {
69
+ try {
70
+ urlInfo.jpegThumbnail = image ? (await getCompressedJpegThumbnail(image, opts)).buffer : undefined;
71
+ }
72
+ catch (error) {
73
+ opts.logger?.debug({ err: error.stack, url: previewLink }, 'error in generating thumbnail');
74
+ }
75
+ }
76
+ return urlInfo;
77
+ }
78
+ }
79
+ catch (error) {
80
+ if (!error.message.includes('receive a valid')) {
81
+ throw error;
82
+ }
83
+ }
84
+ };
@@ -0,0 +1,2 @@
1
+ import P from 'pino';
2
+ export default P({ timestamp: () => `,"time":"${new Date().toJSON()}"` });
@@ -0,0 +1,7 @@
1
+ import { LTHashAntiTampering } from 'whatsapp-rust-bridge';
2
+ /**
3
+ * LT Hash is a summation based hash algorithm that maintains the integrity of a piece of data
4
+ * over a series of mutations. You can add/remove mutations and it'll return a hash equal to
5
+ * if the same series of mutations was made sequentially.
6
+ */
7
+ export const LT_HASH_ANTI_TAMPERING = new LTHashAntiTampering();
@@ -0,0 +1,32 @@
1
+ import { Mutex as AsyncMutex } from 'async-mutex';
2
+ export const makeMutex = () => {
3
+ const mutex = new AsyncMutex();
4
+ return {
5
+ mutex(code) {
6
+ return mutex.runExclusive(code);
7
+ }
8
+ };
9
+ };
10
+ export const makeKeyedMutex = () => {
11
+ const map = new Map();
12
+ return {
13
+ async mutex(key, task) {
14
+ let entry = map.get(key);
15
+ if (!entry) {
16
+ entry = { mutex: new AsyncMutex(), refCount: 0 };
17
+ map.set(key, entry);
18
+ }
19
+ entry.refCount++;
20
+ try {
21
+ return await entry.mutex.runExclusive(task);
22
+ }
23
+ finally {
24
+ entry.refCount--;
25
+ // only delete it if this is still the current entry
26
+ if (entry.refCount === 0 && map.get(key) === entry) {
27
+ map.delete(key);
28
+ }
29
+ }
30
+ }
31
+ };
32
+ };
@@ -0,0 +1,264 @@
1
+ import { LRUCache } from 'lru-cache';
2
+ /** Number of sent messages to cache in memory for handling retry receipts */
3
+ const RECENT_MESSAGES_SIZE = 512;
4
+ const MESSAGE_KEY_SEPARATOR = '\u0000';
5
+ /** Timeout for session recreation - 1 hour */
6
+ const RECREATE_SESSION_TIMEOUT = 60 * 60 * 1000; // 1 hour in milliseconds
7
+ const PHONE_REQUEST_DELAY = 3000;
8
+ // Retry reason codes matching WhatsApp Web's Signal error codes.
9
+ export var RetryReason;
10
+ (function (RetryReason) {
11
+ RetryReason[RetryReason["UnknownError"] = 0] = "UnknownError";
12
+ RetryReason[RetryReason["SignalErrorNoSession"] = 1] = "SignalErrorNoSession";
13
+ RetryReason[RetryReason["SignalErrorInvalidKey"] = 2] = "SignalErrorInvalidKey";
14
+ RetryReason[RetryReason["SignalErrorInvalidKeyId"] = 3] = "SignalErrorInvalidKeyId";
15
+ /** MAC verification failed - most common cause of decryption failures */
16
+ RetryReason[RetryReason["SignalErrorInvalidMessage"] = 4] = "SignalErrorInvalidMessage";
17
+ RetryReason[RetryReason["SignalErrorInvalidSignature"] = 5] = "SignalErrorInvalidSignature";
18
+ RetryReason[RetryReason["SignalErrorFutureMessage"] = 6] = "SignalErrorFutureMessage";
19
+ /** Explicit MAC failure - session is definitely out of sync */
20
+ RetryReason[RetryReason["SignalErrorBadMac"] = 7] = "SignalErrorBadMac";
21
+ RetryReason[RetryReason["SignalErrorInvalidSession"] = 8] = "SignalErrorInvalidSession";
22
+ RetryReason[RetryReason["SignalErrorInvalidMsgKey"] = 9] = "SignalErrorInvalidMsgKey";
23
+ RetryReason[RetryReason["BadBroadcastEphemeralSetting"] = 10] = "BadBroadcastEphemeralSetting";
24
+ RetryReason[RetryReason["UnknownCompanionNoPrekey"] = 11] = "UnknownCompanionNoPrekey";
25
+ RetryReason[RetryReason["AdvFailure"] = 12] = "AdvFailure";
26
+ RetryReason[RetryReason["StatusRevokeDelay"] = 13] = "StatusRevokeDelay";
27
+ })(RetryReason || (RetryReason = {}));
28
+ /** Error codes that indicate a MAC failure and require immediate session recreation */
29
+ const MAC_ERROR_CODES = new Set([RetryReason.SignalErrorInvalidMessage, RetryReason.SignalErrorBadMac]);
30
+ export class MessageRetryManager {
31
+ constructor(logger, maxMsgRetryCount) {
32
+ this.logger = logger;
33
+ this.recentMessagesMap = new LRUCache({
34
+ max: RECENT_MESSAGES_SIZE,
35
+ ttl: 5 * 60 * 1000,
36
+ ttlAutopurge: true,
37
+ dispose: (_value, key) => {
38
+ const separatorIndex = key.lastIndexOf(MESSAGE_KEY_SEPARATOR);
39
+ if (separatorIndex > -1) {
40
+ const messageId = key.slice(separatorIndex + MESSAGE_KEY_SEPARATOR.length);
41
+ this.messageKeyIndex.delete(messageId);
42
+ }
43
+ }
44
+ });
45
+ this.messageKeyIndex = new Map();
46
+ this.sessionRecreateHistory = new LRUCache({
47
+ ttl: RECREATE_SESSION_TIMEOUT * 2,
48
+ ttlAutopurge: true
49
+ });
50
+ this.retryCounters = new LRUCache({
51
+ ttl: 15 * 60 * 1000,
52
+ ttlAutopurge: true,
53
+ updateAgeOnGet: true
54
+ }); // 15 minutes TTL
55
+ this.baseKeys = new LRUCache({
56
+ max: 1024,
57
+ ttl: 15 * 60 * 1000,
58
+ ttlAutopurge: true
59
+ });
60
+ this.pendingPhoneRequests = {};
61
+ this.maxMsgRetryCount = 5;
62
+ this.statistics = {
63
+ totalRetries: 0,
64
+ successfulRetries: 0,
65
+ failedRetries: 0,
66
+ mediaRetries: 0,
67
+ sessionRecreations: 0,
68
+ phoneRequests: 0
69
+ };
70
+ this.maxMsgRetryCount = maxMsgRetryCount;
71
+ }
72
+ /**
73
+ * Add a recent message to the cache for retry handling
74
+ */
75
+ addRecentMessage(to, id, message) {
76
+ const key = { to, id };
77
+ const keyStr = this.keyToString(key);
78
+ // Add new message
79
+ this.recentMessagesMap.set(keyStr, {
80
+ message,
81
+ timestamp: Date.now()
82
+ });
83
+ this.messageKeyIndex.set(id, keyStr);
84
+ this.logger.debug(`Added message to retry cache: ${to}/${id}`);
85
+ }
86
+ /**
87
+ * Get a recent message from the cache
88
+ */
89
+ getRecentMessage(to, id) {
90
+ const key = { to, id };
91
+ const keyStr = this.keyToString(key);
92
+ return this.recentMessagesMap.get(keyStr);
93
+ }
94
+ /**
95
+ * Check if a session should be recreated based on retry count, history, and error code.
96
+ * MAC errors (codes 4 and 7) trigger immediate session recreation regardless of timeout.
97
+ */
98
+ shouldRecreateSession(jid, hasSession, errorCode) {
99
+ // If we don't have a session, always recreate
100
+ if (!hasSession) {
101
+ this.sessionRecreateHistory.set(jid, Date.now());
102
+ this.statistics.sessionRecreations++;
103
+ return {
104
+ reason: "we don't have a Signal session with them",
105
+ recreate: true
106
+ };
107
+ }
108
+ // IMMEDIATE recreation for MAC errors - session is definitely out of sync
109
+ if (errorCode !== undefined && MAC_ERROR_CODES.has(errorCode)) {
110
+ this.sessionRecreateHistory.set(jid, Date.now());
111
+ this.statistics.sessionRecreations++;
112
+ this.logger.warn({ jid, errorCode: RetryReason[errorCode] }, 'MAC error detected, forcing immediate session recreation');
113
+ return {
114
+ reason: `MAC error (code ${errorCode}: ${RetryReason[errorCode]}), immediate session recreation`,
115
+ recreate: true
116
+ };
117
+ }
118
+ const now = Date.now();
119
+ const prevTime = this.sessionRecreateHistory.get(jid);
120
+ // If no previous recreation or it's been more than an hour
121
+ if (!prevTime || now - prevTime > RECREATE_SESSION_TIMEOUT) {
122
+ this.sessionRecreateHistory.set(jid, now);
123
+ this.statistics.sessionRecreations++;
124
+ return {
125
+ reason: 'retry count > 1 and over an hour since last recreation',
126
+ recreate: true
127
+ };
128
+ }
129
+ return { reason: '', recreate: false };
130
+ }
131
+ /**
132
+ * Parse error code from retry receipt's retry node.
133
+ * Returns undefined if no error code is present.
134
+ */
135
+ parseRetryErrorCode(errorAttr) {
136
+ if (errorAttr === undefined || errorAttr === '') {
137
+ return undefined;
138
+ }
139
+ const code = parseInt(errorAttr, 10);
140
+ if (Number.isNaN(code)) {
141
+ return undefined;
142
+ }
143
+ // Validate it's a known RetryReason
144
+ if (code >= RetryReason.UnknownError && code <= RetryReason.StatusRevokeDelay) {
145
+ return code;
146
+ }
147
+ return RetryReason.UnknownError;
148
+ }
149
+ /**
150
+ * Check if an error code indicates a MAC failure
151
+ */
152
+ isMacError(errorCode) {
153
+ return errorCode !== undefined && MAC_ERROR_CODES.has(errorCode);
154
+ }
155
+ /**
156
+ * Increment retry counter for a message
157
+ */
158
+ incrementRetryCount(messageId) {
159
+ this.retryCounters.set(messageId, (this.retryCounters.get(messageId) || 0) + 1);
160
+ this.statistics.totalRetries++;
161
+ return this.retryCounters.get(messageId);
162
+ }
163
+ /**
164
+ * Get retry count for a message
165
+ */
166
+ getRetryCount(messageId) {
167
+ return this.retryCounters.get(messageId) || 0;
168
+ }
169
+ /**
170
+ * Check if message has exceeded maximum retry attempts
171
+ */
172
+ hasExceededMaxRetries(messageId) {
173
+ return this.getRetryCount(messageId) >= this.maxMsgRetryCount;
174
+ }
175
+ /**
176
+ * Mark retry as successful
177
+ */
178
+ markRetrySuccess(messageId) {
179
+ this.statistics.successfulRetries++;
180
+ // Clean up retry counter for successful message
181
+ this.retryCounters.delete(messageId);
182
+ this.cancelPendingPhoneRequest(messageId);
183
+ this.removeRecentMessage(messageId);
184
+ }
185
+ /**
186
+ * Mark retry as failed
187
+ */
188
+ markRetryFailed(messageId) {
189
+ this.statistics.failedRetries++;
190
+ this.retryCounters.delete(messageId);
191
+ this.cancelPendingPhoneRequest(messageId);
192
+ this.removeRecentMessage(messageId);
193
+ }
194
+ /**
195
+ * Schedule a phone request with delay
196
+ */
197
+ schedulePhoneRequest(messageId, callback, delay = PHONE_REQUEST_DELAY) {
198
+ // Cancel any existing request for this message
199
+ this.cancelPendingPhoneRequest(messageId);
200
+ this.pendingPhoneRequests[messageId] = setTimeout(() => {
201
+ delete this.pendingPhoneRequests[messageId];
202
+ this.statistics.phoneRequests++;
203
+ callback();
204
+ }, delay);
205
+ this.logger.debug(`Scheduled phone request for message ${messageId} with ${delay}ms delay`);
206
+ }
207
+ /**
208
+ * Cancel pending phone request
209
+ */
210
+ cancelPendingPhoneRequest(messageId) {
211
+ const timeout = this.pendingPhoneRequests[messageId];
212
+ if (timeout) {
213
+ clearTimeout(timeout);
214
+ delete this.pendingPhoneRequests[messageId];
215
+ this.logger.debug(`Cancelled pending phone request for message ${messageId}`);
216
+ }
217
+ }
218
+ clear() {
219
+ this.recentMessagesMap.clear();
220
+ this.messageKeyIndex.clear();
221
+ this.sessionRecreateHistory.clear();
222
+ this.retryCounters.clear();
223
+ this.baseKeys.clear();
224
+ for (const messageId of Object.keys(this.pendingPhoneRequests)) {
225
+ this.cancelPendingPhoneRequest(messageId);
226
+ }
227
+ this.statistics = {
228
+ totalRetries: 0,
229
+ successfulRetries: 0,
230
+ failedRetries: 0,
231
+ mediaRetries: 0,
232
+ sessionRecreations: 0,
233
+ phoneRequests: 0
234
+ };
235
+ }
236
+ saveBaseKey(addr, msgId, baseKey) {
237
+ this.baseKeys.set(`${addr}:${msgId}`, baseKey);
238
+ }
239
+ hasSameBaseKey(addr, msgId, baseKey) {
240
+ const stored = this.baseKeys.get(`${addr}:${msgId}`);
241
+ if (!stored || stored.length !== baseKey.length) {
242
+ return false;
243
+ }
244
+ for (let i = 0; i < stored.length; i++) {
245
+ if (stored[i] !== baseKey[i])
246
+ return false;
247
+ }
248
+ return true;
249
+ }
250
+ deleteBaseKey(addr, msgId) {
251
+ this.baseKeys.delete(`${addr}:${msgId}`);
252
+ }
253
+ keyToString(key) {
254
+ return `${key.to}${MESSAGE_KEY_SEPARATOR}${key.id}`;
255
+ }
256
+ removeRecentMessage(messageId) {
257
+ const keyStr = this.messageKeyIndex.get(messageId);
258
+ if (!keyStr) {
259
+ return;
260
+ }
261
+ this.recentMessagesMap.delete(keyStr);
262
+ this.messageKeyIndex.delete(messageId);
263
+ }
264
+ }