@x4r1s3/baileys 0.0.0-stage → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +1245 -2
- package/SECURITY.md +47 -0
- package/WAProto/V +1 -0
- package/WAProto/WAProto.proto +8892 -0
- package/WAProto/index.d.ts +104128 -0
- package/WAProto/index.js +334920 -0
- package/assets/rolling-circle.svg +133 -0
- package/assets/x4r1s3-banner.svg +32 -0
- package/engine-requirements.js +27 -0
- package/lib/Builders/A2UI.js +245 -0
- package/lib/Builders/AIRich.js +179 -0
- package/lib/Builders/Button.js +108 -0
- package/lib/Builders/CFC.js +284 -0
- package/lib/Builders/Carousel.js +81 -0
- package/lib/Call/THIRD_PARTY_LICENSE.txt +21 -0
- package/lib/Call/astralena-v3.mjs +96 -0
- package/lib/Call/audio-feeder.mjs +201 -0
- package/lib/Call/audio-recorder.mjs +250 -0
- package/lib/Call/fetch-wasm-resources.mjs +104 -0
- package/lib/Call/index.mjs +707 -0
- package/lib/Call/relay-transport.mjs +563 -0
- package/lib/Call/signaling.mjs +660 -0
- package/lib/Call/types.mjs +17 -0
- package/lib/Call/video-feeder.mjs +94 -0
- package/lib/Call/voip-resources.mjs +259 -0
- package/lib/Call/wasm-engine.mjs +1372 -0
- package/lib/Call/worker-bootstrap.mjs +1042 -0
- package/lib/Defaults/ban-checker.js +56 -0
- package/lib/Defaults/index.js +170 -0
- package/lib/Signal/Group/ciphertext-message.js +23 -0
- package/lib/Signal/Group/group-session-builder.js +41 -0
- package/lib/Signal/Group/group_cipher.js +93 -0
- package/lib/Signal/Group/index.js +23 -0
- package/lib/Signal/Group/keyhelper.js +29 -0
- package/lib/Signal/Group/sender-chain-key.js +37 -0
- package/lib/Signal/Group/sender-key-distribution-message.js +74 -0
- package/lib/Signal/Group/sender-key-message.js +77 -0
- package/lib/Signal/Group/sender-key-name.js +59 -0
- package/lib/Signal/Group/sender-key-record.js +52 -0
- package/lib/Signal/Group/sender-key-state.js +95 -0
- package/lib/Signal/Group/sender-message-key.js +37 -0
- package/lib/Signal/libsignal.js +440 -0
- package/lib/Signal/lid-mapping.js +292 -0
- package/lib/Socket/Client/index.js +14 -0
- package/lib/Socket/Client/types.js +22 -0
- package/lib/Socket/Client/websocket.js +65 -0
- package/lib/Socket/aigroups.js +327 -0
- package/lib/Socket/ban-checker.js +165 -0
- package/lib/Socket/business.js +419 -0
- package/lib/Socket/chats.js +1921 -0
- package/lib/Socket/communities.js +443 -0
- package/lib/Socket/graphql.js +911 -0
- package/lib/Socket/groups.js +561 -0
- package/lib/Socket/index.js +49 -0
- package/lib/Socket/interactive-handler.js +612 -0
- package/lib/Socket/interop.js +575 -0
- package/lib/Socket/managed-account.js +220 -0
- package/lib/Socket/messages-recv.js +2193 -0
- package/lib/Socket/messages-send.js +4141 -0
- package/lib/Socket/mex.js +53 -0
- package/lib/Socket/newsletter.js +291 -0
- package/lib/Socket/privacy.js +458 -0
- package/lib/Socket/registration.js +440 -0
- package/lib/Socket/socket.js +1042 -0
- package/lib/Socket/status-actions.js +287 -0
- package/lib/Socket/username.js +241 -0
- package/lib/Store/index.js +16 -0
- package/lib/Store/make-cache-manager-store.js +101 -0
- package/lib/Store/make-in-memory-store.js +432 -0
- package/lib/Store/make-ordered-dictionary.js +90 -0
- package/lib/Store/object-repository.js +35 -0
- package/lib/Types/Auth.js +13 -0
- package/lib/Types/Bussines.js +13 -0
- package/lib/Types/Call.js +13 -0
- package/lib/Types/Chat.js +19 -0
- package/lib/Types/Contact.js +13 -0
- package/lib/Types/Events.js +13 -0
- package/lib/Types/GroupMetadata.js +13 -0
- package/lib/Types/Label.js +36 -0
- package/lib/Types/LabelAssociation.js +18 -0
- package/lib/Types/Message.js +30 -0
- package/lib/Types/Mex.js +53 -0
- package/lib/Types/Product.js +13 -0
- package/lib/Types/RichType.js +34 -0
- package/lib/Types/Signal.js +13 -0
- package/lib/Types/Socket.js +14 -0
- package/lib/Types/State.js +60 -0
- package/lib/Types/USync.js +13 -0
- package/lib/Types/index.js +37 -0
- package/lib/Utils/auth-utils.js +313 -0
- package/lib/Utils/ban-checker.js +48 -0
- package/lib/Utils/bot-capabilities.js +96 -0
- package/lib/Utils/bot-planning-replay.js +177 -0
- package/lib/Utils/browser-utils.js +40 -0
- package/lib/Utils/business.js +242 -0
- package/lib/Utils/c2582.js +147 -0
- package/lib/Utils/chat-utils.js +905 -0
- package/lib/Utils/companion-reg-client-utils.js +104 -0
- package/lib/Utils/consumer-application.js +114 -0
- package/lib/Utils/crypto.js +129 -0
- package/lib/Utils/decode-wa-message.js +496 -0
- package/lib/Utils/direct-chat-theme.js +164 -0
- package/lib/Utils/event-buffer.js +601 -0
- package/lib/Utils/experimental-proto.js +206 -0
- package/lib/Utils/games/miniapp.js +17 -0
- package/lib/Utils/games/slot-machine.js +270 -0
- package/lib/Utils/games/website-preview.js +306 -0
- package/lib/Utils/generics.js +402 -0
- package/lib/Utils/group-history.js +68 -0
- package/lib/Utils/group-wallpaper.js +168 -0
- package/lib/Utils/history.js +162 -0
- package/lib/Utils/identity-change-handler.js +60 -0
- package/lib/Utils/index.js +61 -0
- package/lib/Utils/jid-display-normalization.js +221 -0
- package/lib/Utils/link-preview.js +96 -0
- package/lib/Utils/logger.js +14 -0
- package/lib/Utils/lt-hash.js +19 -0
- package/lib/Utils/make-mutex.js +44 -0
- package/lib/Utils/message-composer.js +709 -0
- package/lib/Utils/message-inspect.js +79 -0
- package/lib/Utils/message-retry-manager.js +253 -0
- package/lib/Utils/message-security.js +167 -0
- package/lib/Utils/messages-media.js +1027 -0
- package/lib/Utils/messages.js +2467 -0
- package/lib/Utils/meta-ai-msmsg.js +215 -0
- package/lib/Utils/meta-compositing.js +239 -0
- package/lib/Utils/native-flow.js +158 -0
- package/lib/Utils/newsletter-live-update-utils.js +74 -0
- package/lib/Utils/newsletter-status-utils.js +152 -0
- package/lib/Utils/noise-handler.js +212 -0
- package/lib/Utils/offline-node-processor.js +51 -0
- package/lib/Utils/poll-manager.js +206 -0
- package/lib/Utils/portable-compat.js +12 -0
- package/lib/Utils/pre-key-manager.js +117 -0
- package/lib/Utils/process-message.js +610 -0
- package/lib/Utils/reporting-utils.js +269 -0
- package/lib/Utils/rich-message-utils.js +2841 -0
- package/lib/Utils/scheduled-message.js +107 -0
- package/lib/Utils/signal.js +212 -0
- package/lib/Utils/source-grep.js +57 -0
- package/lib/Utils/stanza-ack.js +49 -0
- package/lib/Utils/sticker-annotation.js +87 -0
- package/lib/Utils/sync-action-utils.js +59 -0
- package/lib/Utils/tc-token-utils.js +174 -0
- package/lib/Utils/use-multi-file-auth-state.js +132 -0
- package/lib/Utils/use-single-file-auth-state.js +108 -0
- package/lib/Utils/use-sqlite-auth-state.js +120 -0
- package/lib/Utils/validate-connection.js +221 -0
- package/lib/Utils/view-once-utils.js +218 -0
- package/lib/Utils/voip-rekey.js +32 -0
- package/lib/Utils/website-preview.js +27 -0
- package/lib/Utils/welcome-flow.js +228 -0
- package/lib/Utils/x4r1s3.js +144 -0
- package/lib/WABinary/constants.js +1475 -0
- package/lib/WABinary/decode.js +273 -0
- package/lib/WABinary/encode.js +231 -0
- package/lib/WABinary/generic-utils.js +242 -0
- package/lib/WABinary/index.js +17 -0
- package/lib/WABinary/jid-utils.js +107 -0
- package/lib/WABinary/types.js +13 -0
- package/lib/WAM/BinaryInfo.js +21 -0
- package/lib/WAM/constants.js +22864 -0
- package/lib/WAM/encode.js +161 -0
- package/lib/WAM/index.js +15 -0
- package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +108 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +68 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +65 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +38 -0
- package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +82 -0
- package/lib/WAUSync/Protocols/USyncPictureProtocol.js +40 -0
- package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +37 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +49 -0
- package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +46 -0
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +36 -0
- package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +62 -0
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +40 -0
- package/lib/WAUSync/Protocols/index.js +24 -0
- package/lib/WAUSync/USyncQuery.js +213 -0
- package/lib/WAUSync/USyncUser.js +66 -0
- package/lib/WAUSync/index.js +15 -0
- package/lib/antiban.cjs +4726 -0
- package/lib/index.d.ts +1895 -0
- package/lib/index.js +41 -0
- package/package.json +125 -4
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @X4R1S3
|
|
3
|
+
*
|
|
4
|
+
* File: lib/Utils/message-inspect.js
|
|
5
|
+
* About: Message inspect module for the X4R1S3 WhatsApp protocol client.
|
|
6
|
+
* Important exports: isScheduledMessage, getScheduledMessageTime, getMessagePaymentInfo, getMessageCommentMetadata, getMessageAddOns, getPollCorrectAnswer, toJid, getSenderLid
|
|
7
|
+
* Directions: Import the listed exports and preserve protocol, validation, and compatibility invariants when modifying.
|
|
8
|
+
*
|
|
9
|
+
* Copyright and attribution notice.
|
|
10
|
+
* Do not copy, reproduce, redistribute, modify, or create derivative works
|
|
11
|
+
* from this source without explicit written permission.
|
|
12
|
+
*/
|
|
13
|
+
import { proto } from '../../WAProto/index.js';
|
|
14
|
+
import { isLidUser, jidEncode } from '../WABinary/index.js';
|
|
15
|
+
|
|
16
|
+
// ── Message inspection helpers ────────────────────────────────────────────────
|
|
17
|
+
// Ported from baron-baileys-v2 Utils/message-inspect.js. Only the helpers that
|
|
18
|
+
// were not already present in lib/Utils/messages.js are exported here — the
|
|
19
|
+
// shared ones (getContentType, normalizeMessageContent, extractMessageContent,
|
|
20
|
+
// downloadMediaMessage, assertMediaContent, getDevice, …) live in messages.js.
|
|
21
|
+
|
|
22
|
+
/** Check if a WebMessageInfo has a scheduled reveal time (ConditionalRevealMessage) */
|
|
23
|
+
export const isScheduledMessage = (msg) => !!msg?.scheduledMessageMetadata?.scheduledTime;
|
|
24
|
+
|
|
25
|
+
/** Get scheduled reveal time of a message as a Date, or null */
|
|
26
|
+
export const getScheduledMessageTime = (msg) => {
|
|
27
|
+
const t = msg?.scheduledMessageMetadata?.scheduledTime;
|
|
28
|
+
if (!t) return null;
|
|
29
|
+
return new Date(Number(t) * 1000);
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
/** Extract PaymentInfo from a WebMessageInfo (the payment status field, not the message content) */
|
|
33
|
+
export const getMessagePaymentInfo = (msg) => msg?.paymentInfo || msg?.quotedPaymentInfo || null;
|
|
34
|
+
|
|
35
|
+
/** Get all comment metadata from a WebMessageInfo */
|
|
36
|
+
export const getMessageCommentMetadata = (msg) => msg?.commentMetadata || null;
|
|
37
|
+
|
|
38
|
+
/** Get all message add-ons (reactions, poll updates, pins) from a WebMessageInfo */
|
|
39
|
+
export const getMessageAddOns = (msg) => msg?.messageAddOns || [];
|
|
40
|
+
|
|
41
|
+
/** Get the quiz correct answer from a poll creation message, if it's a quiz */
|
|
42
|
+
export const getPollCorrectAnswer = (pollMsg) => {
|
|
43
|
+
const poll =
|
|
44
|
+
pollMsg?.pollCreationMessage ||
|
|
45
|
+
pollMsg?.pollCreationMessageV2 ||
|
|
46
|
+
pollMsg?.pollCreationMessageV3 ||
|
|
47
|
+
pollMsg?.pollCreationMessageV5 ||
|
|
48
|
+
pollMsg?.pollCreationMessageV6;
|
|
49
|
+
if (!poll) return null;
|
|
50
|
+
const isQuiz = poll.pollType === proto.Message.PollType?.QUIZ || poll.pollType === 1;
|
|
51
|
+
return isQuiz ? poll.correctAnswer?.optionName || null : null;
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
/** Normalizes a bare user id to @s.whatsapp.net. Does not convert LID↔PN; use lidMapping / PN in key.remoteJidAlt when needed. */
|
|
55
|
+
export const toJid = (id) => {
|
|
56
|
+
if (!id) return '';
|
|
57
|
+
if (id.includes('@')) return id;
|
|
58
|
+
return `${id}@s.whatsapp.net`;
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
/** Returns the peer LID JID when the key is LID-primary (decode sets remoteJid/participant to @lid when WA sends LID). */
|
|
62
|
+
export const getSenderLid = (message) => {
|
|
63
|
+
const k = message.key;
|
|
64
|
+
if (!k) {
|
|
65
|
+
return { jid: '', lid: '' };
|
|
66
|
+
}
|
|
67
|
+
const jid = k.participant || k.remoteJid || '';
|
|
68
|
+
if (jid.endsWith('@lid') || jid.endsWith('@hosted.lid')) {
|
|
69
|
+
return { jid, lid: jid };
|
|
70
|
+
}
|
|
71
|
+
if (k.lid && typeof k.lid === 'string') {
|
|
72
|
+
const lid = k.lid.includes('@') ? k.lid : jidEncode(k.lid, 'lid');
|
|
73
|
+
return { jid, lid };
|
|
74
|
+
}
|
|
75
|
+
if (k.participantLid && isLidUser(k.participantLid)) {
|
|
76
|
+
return { jid, lid: k.participantLid };
|
|
77
|
+
}
|
|
78
|
+
return { jid, lid: '' };
|
|
79
|
+
};
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @X4R1S3
|
|
3
|
+
*
|
|
4
|
+
* File: lib/Utils/message-retry-manager.js
|
|
5
|
+
* About: Message retry manager module for the X4R1S3 WhatsApp protocol client.
|
|
6
|
+
* Important exports: RetryReason, MessageRetryManager
|
|
7
|
+
* Directions: Import the listed exports and preserve protocol, validation, and compatibility invariants when modifying.
|
|
8
|
+
*
|
|
9
|
+
* Copyright and attribution notice.
|
|
10
|
+
* Do not copy, reproduce, redistribute, modify, or create derivative works
|
|
11
|
+
* from this source without explicit written permission.
|
|
12
|
+
*/
|
|
13
|
+
import { LRUCache } from 'lru-cache';
|
|
14
|
+
/** Number of sent messages to cache in memory for handling retry receipts */
|
|
15
|
+
const RECENT_MESSAGES_SIZE = 1024;
|
|
16
|
+
const MESSAGE_KEY_SEPARATOR = '\u0000';
|
|
17
|
+
/** Timeout for session recreation - 1 hour */
|
|
18
|
+
const RECREATE_SESSION_TIMEOUT = 60 * 60 * 1000; // 1 hour in milliseconds
|
|
19
|
+
const PHONE_REQUEST_DELAY = 3000;
|
|
20
|
+
// Retry reason codes matching WhatsApp Web's Signal error codes.
|
|
21
|
+
export var RetryReason;
|
|
22
|
+
(function (RetryReason) {
|
|
23
|
+
RetryReason[RetryReason["UnknownError"] = 0] = "UnknownError";
|
|
24
|
+
RetryReason[RetryReason["SignalErrorNoSession"] = 1] = "SignalErrorNoSession";
|
|
25
|
+
RetryReason[RetryReason["SignalErrorInvalidKey"] = 2] = "SignalErrorInvalidKey";
|
|
26
|
+
RetryReason[RetryReason["SignalErrorInvalidKeyId"] = 3] = "SignalErrorInvalidKeyId";
|
|
27
|
+
/** MAC verification failed - most common cause of decryption failures */
|
|
28
|
+
RetryReason[RetryReason["SignalErrorInvalidMessage"] = 4] = "SignalErrorInvalidMessage";
|
|
29
|
+
RetryReason[RetryReason["SignalErrorInvalidSignature"] = 5] = "SignalErrorInvalidSignature";
|
|
30
|
+
RetryReason[RetryReason["SignalErrorFutureMessage"] = 6] = "SignalErrorFutureMessage";
|
|
31
|
+
/** Explicit MAC failure - session is definitely out of sync */
|
|
32
|
+
RetryReason[RetryReason["SignalErrorBadMac"] = 7] = "SignalErrorBadMac";
|
|
33
|
+
RetryReason[RetryReason["SignalErrorInvalidSession"] = 8] = "SignalErrorInvalidSession";
|
|
34
|
+
RetryReason[RetryReason["SignalErrorInvalidMsgKey"] = 9] = "SignalErrorInvalidMsgKey";
|
|
35
|
+
RetryReason[RetryReason["BadBroadcastEphemeralSetting"] = 10] = "BadBroadcastEphemeralSetting";
|
|
36
|
+
RetryReason[RetryReason["UnknownCompanionNoPrekey"] = 11] = "UnknownCompanionNoPrekey";
|
|
37
|
+
RetryReason[RetryReason["AdvFailure"] = 12] = "AdvFailure";
|
|
38
|
+
RetryReason[RetryReason["StatusRevokeDelay"] = 13] = "StatusRevokeDelay";
|
|
39
|
+
})(RetryReason || (RetryReason = {}));
|
|
40
|
+
/** Error codes that indicate a MAC failure and require immediate session recreation */
|
|
41
|
+
const MAC_ERROR_CODES = new Set([RetryReason.SignalErrorInvalidMessage, RetryReason.SignalErrorBadMac]);
|
|
42
|
+
export class MessageRetryManager {
|
|
43
|
+
constructor(logger, maxMsgRetryCount) {
|
|
44
|
+
this.logger = logger;
|
|
45
|
+
this.recentMessagesMap = new LRUCache({
|
|
46
|
+
max: RECENT_MESSAGES_SIZE,
|
|
47
|
+
ttl: 5 * 60 * 1000,
|
|
48
|
+
ttlAutopurge: true,
|
|
49
|
+
dispose: (_value, key) => {
|
|
50
|
+
const separatorIndex = key.lastIndexOf(MESSAGE_KEY_SEPARATOR);
|
|
51
|
+
if (separatorIndex > -1) {
|
|
52
|
+
const messageId = key.slice(separatorIndex + MESSAGE_KEY_SEPARATOR.length);
|
|
53
|
+
this.messageKeyIndex.delete(messageId);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
this.messageKeyIndex = new Map();
|
|
58
|
+
this.sessionRecreateHistory = new LRUCache({
|
|
59
|
+
ttl: RECREATE_SESSION_TIMEOUT * 2,
|
|
60
|
+
ttlAutopurge: true
|
|
61
|
+
});
|
|
62
|
+
this.retryCounters = new LRUCache({
|
|
63
|
+
ttl: 15 * 60 * 1000,
|
|
64
|
+
ttlAutopurge: true,
|
|
65
|
+
updateAgeOnGet: true
|
|
66
|
+
}); // 15 minutes TTL
|
|
67
|
+
this.pendingPhoneRequests = {};
|
|
68
|
+
this.maxMsgRetryCount = 5;
|
|
69
|
+
this.statistics = {
|
|
70
|
+
totalRetries: 0,
|
|
71
|
+
successfulRetries: 0,
|
|
72
|
+
failedRetries: 0,
|
|
73
|
+
mediaRetries: 0,
|
|
74
|
+
sessionRecreations: 0,
|
|
75
|
+
phoneRequests: 0
|
|
76
|
+
};
|
|
77
|
+
this.maxMsgRetryCount = maxMsgRetryCount;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Add a recent message to the cache for retry handling
|
|
81
|
+
*/
|
|
82
|
+
addRecentMessage(to, id, message) {
|
|
83
|
+
const key = { to, id };
|
|
84
|
+
const keyStr = this.keyToString(key);
|
|
85
|
+
// Add new message
|
|
86
|
+
this.recentMessagesMap.set(keyStr, {
|
|
87
|
+
message,
|
|
88
|
+
timestamp: Date.now()
|
|
89
|
+
});
|
|
90
|
+
this.messageKeyIndex.set(id, keyStr);
|
|
91
|
+
this.logger.debug(`Added message to retry cache: ${to}/${id}`);
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Get a recent message from the cache
|
|
95
|
+
*/
|
|
96
|
+
getRecentMessage(to, id) {
|
|
97
|
+
const key = { to, id };
|
|
98
|
+
const keyStr = this.keyToString(key);
|
|
99
|
+
return this.recentMessagesMap.get(keyStr);
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Check if a session should be recreated based on retry count, history, and error code.
|
|
103
|
+
* MAC errors (codes 4 and 7) trigger immediate session recreation regardless of timeout.
|
|
104
|
+
*/
|
|
105
|
+
shouldRecreateSession(jid, hasSession, errorCode) {
|
|
106
|
+
// If we don't have a session, always recreate
|
|
107
|
+
if (!hasSession) {
|
|
108
|
+
this.sessionRecreateHistory.set(jid, Date.now());
|
|
109
|
+
this.statistics.sessionRecreations++;
|
|
110
|
+
return {
|
|
111
|
+
reason: "we don't have a Signal session with them",
|
|
112
|
+
recreate: true
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
// IMMEDIATE recreation for MAC errors - session is definitely out of sync
|
|
116
|
+
if (errorCode !== undefined && MAC_ERROR_CODES.has(errorCode)) {
|
|
117
|
+
this.sessionRecreateHistory.set(jid, Date.now());
|
|
118
|
+
this.statistics.sessionRecreations++;
|
|
119
|
+
this.logger.warn({ jid, errorCode: RetryReason[errorCode] }, 'MAC error detected, forcing immediate session recreation');
|
|
120
|
+
return {
|
|
121
|
+
reason: `MAC error (code ${errorCode}: ${RetryReason[errorCode]}), immediate session recreation`,
|
|
122
|
+
recreate: true
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
const now = Date.now();
|
|
126
|
+
const prevTime = this.sessionRecreateHistory.get(jid);
|
|
127
|
+
// If no previous recreation or it's been more than an hour
|
|
128
|
+
if (!prevTime || now - prevTime > RECREATE_SESSION_TIMEOUT) {
|
|
129
|
+
this.sessionRecreateHistory.set(jid, now);
|
|
130
|
+
this.statistics.sessionRecreations++;
|
|
131
|
+
return {
|
|
132
|
+
reason: 'retry count > 1 and over an hour since last recreation',
|
|
133
|
+
recreate: true
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
return { reason: '', recreate: false };
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Parse error code from retry receipt's retry node.
|
|
140
|
+
* Returns undefined if no error code is present.
|
|
141
|
+
*/
|
|
142
|
+
parseRetryErrorCode(errorAttr) {
|
|
143
|
+
if (errorAttr === undefined || errorAttr === '') {
|
|
144
|
+
return undefined;
|
|
145
|
+
}
|
|
146
|
+
const code = parseInt(errorAttr, 10);
|
|
147
|
+
if (Number.isNaN(code)) {
|
|
148
|
+
return undefined;
|
|
149
|
+
}
|
|
150
|
+
// Validate it's a known RetryReason
|
|
151
|
+
if (code >= RetryReason.UnknownError && code <= RetryReason.StatusRevokeDelay) {
|
|
152
|
+
return code;
|
|
153
|
+
}
|
|
154
|
+
return RetryReason.UnknownError;
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Check if an error code indicates a MAC failure
|
|
158
|
+
*/
|
|
159
|
+
isMacError(errorCode) {
|
|
160
|
+
return errorCode !== undefined && MAC_ERROR_CODES.has(errorCode);
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Increment retry counter for a message
|
|
164
|
+
*/
|
|
165
|
+
incrementRetryCount(messageId) {
|
|
166
|
+
this.retryCounters.set(messageId, (this.retryCounters.get(messageId) || 0) + 1);
|
|
167
|
+
this.statistics.totalRetries++;
|
|
168
|
+
return this.retryCounters.get(messageId);
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Get retry count for a message
|
|
172
|
+
*/
|
|
173
|
+
getRetryCount(messageId) {
|
|
174
|
+
return this.retryCounters.get(messageId) || 0;
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Check if message has exceeded maximum retry attempts
|
|
178
|
+
*/
|
|
179
|
+
hasExceededMaxRetries(messageId) {
|
|
180
|
+
return this.getRetryCount(messageId) >= this.maxMsgRetryCount;
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Mark retry as successful
|
|
184
|
+
*/
|
|
185
|
+
markRetrySuccess(messageId) {
|
|
186
|
+
this.statistics.successfulRetries++;
|
|
187
|
+
// Clean up retry counter for successful message
|
|
188
|
+
this.retryCounters.delete(messageId);
|
|
189
|
+
this.cancelPendingPhoneRequest(messageId);
|
|
190
|
+
this.removeRecentMessage(messageId);
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Mark retry as failed
|
|
194
|
+
*/
|
|
195
|
+
markRetryFailed(messageId) {
|
|
196
|
+
this.statistics.failedRetries++;
|
|
197
|
+
this.retryCounters.delete(messageId);
|
|
198
|
+
this.cancelPendingPhoneRequest(messageId);
|
|
199
|
+
this.removeRecentMessage(messageId);
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Schedule a phone request with delay
|
|
203
|
+
*/
|
|
204
|
+
schedulePhoneRequest(messageId, callback, delay = PHONE_REQUEST_DELAY) {
|
|
205
|
+
// Cancel any existing request for this message
|
|
206
|
+
this.cancelPendingPhoneRequest(messageId);
|
|
207
|
+
this.pendingPhoneRequests[messageId] = setTimeout(() => {
|
|
208
|
+
delete this.pendingPhoneRequests[messageId];
|
|
209
|
+
this.statistics.phoneRequests++;
|
|
210
|
+
callback();
|
|
211
|
+
}, delay);
|
|
212
|
+
this.logger.debug(`Scheduled phone request for message ${messageId} with ${delay}ms delay`);
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Cancel pending phone request
|
|
216
|
+
*/
|
|
217
|
+
cancelPendingPhoneRequest(messageId) {
|
|
218
|
+
const timeout = this.pendingPhoneRequests[messageId];
|
|
219
|
+
if (timeout) {
|
|
220
|
+
clearTimeout(timeout);
|
|
221
|
+
delete this.pendingPhoneRequests[messageId];
|
|
222
|
+
this.logger.debug(`Cancelled pending phone request for message ${messageId}`);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
clear() {
|
|
226
|
+
this.recentMessagesMap.clear();
|
|
227
|
+
this.messageKeyIndex.clear();
|
|
228
|
+
this.sessionRecreateHistory.clear();
|
|
229
|
+
this.retryCounters.clear();
|
|
230
|
+
for (const messageId of Object.keys(this.pendingPhoneRequests)) {
|
|
231
|
+
this.cancelPendingPhoneRequest(messageId);
|
|
232
|
+
}
|
|
233
|
+
this.statistics = {
|
|
234
|
+
totalRetries: 0,
|
|
235
|
+
successfulRetries: 0,
|
|
236
|
+
failedRetries: 0,
|
|
237
|
+
mediaRetries: 0,
|
|
238
|
+
sessionRecreations: 0,
|
|
239
|
+
phoneRequests: 0
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
keyToString(key) {
|
|
243
|
+
return `${key.to}${MESSAGE_KEY_SEPARATOR}${key.id}`;
|
|
244
|
+
}
|
|
245
|
+
removeRecentMessage(messageId) {
|
|
246
|
+
const keyStr = this.messageKeyIndex.get(messageId);
|
|
247
|
+
if (!keyStr) {
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
this.recentMessagesMap.delete(keyStr);
|
|
251
|
+
this.messageKeyIndex.delete(messageId);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
// Based on velowa (https://github.com/7ucg/velowa) by Baron - velowa License; see THIRD_PARTY_NOTICES.md.
|
|
2
|
+
import { makeMutex } from './make-mutex.js';
|
|
3
|
+
import { areJidsSameUser, jidNormalizedUser } from '../WABinary/index.js';
|
|
4
|
+
import { normalizeMessageContent } from './messages.js';
|
|
5
|
+
|
|
6
|
+
const STORE_TYPE = 'baileys-message-security';
|
|
7
|
+
const STORE_ID = 'recent';
|
|
8
|
+
const MAX_ENTRIES = 5000;
|
|
9
|
+
const MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
|
|
10
|
+
const FLUSH_DELAY_MS = 250;
|
|
11
|
+
|
|
12
|
+
const normalizeJid = (jid) => {
|
|
13
|
+
if (!jid || typeof jid !== 'string') return undefined;
|
|
14
|
+
try {
|
|
15
|
+
return jidNormalizedUser(jid);
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return jid;
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
const hasIdentityMatch = (left, right) => {
|
|
23
|
+
const a = [...new Set(left.filter(Boolean).map(normalizeJid))];
|
|
24
|
+
const b = [...new Set(right.filter(Boolean).map(normalizeJid))];
|
|
25
|
+
return a.some(x => b.some(y => x === y || areJidsSameUser(x, y)));
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Persists recent sent IDs and authenticated message origins in the auth key store.
|
|
30
|
+
* The store is advisory for suspicious-receipt events, but fail-closed for edit authorization.
|
|
31
|
+
*/
|
|
32
|
+
export class MessageSecurityStore {
|
|
33
|
+
#keys;
|
|
34
|
+
#logger;
|
|
35
|
+
#sent = new Map();
|
|
36
|
+
#origins = new Map();
|
|
37
|
+
#mutex = makeMutex();
|
|
38
|
+
#flushTimer;
|
|
39
|
+
|
|
40
|
+
constructor(keys, logger) {
|
|
41
|
+
this.#keys = keys;
|
|
42
|
+
this.#logger = logger;
|
|
43
|
+
this.ready = this.#load();
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async #load() {
|
|
47
|
+
if (!this.#keys?.get) return;
|
|
48
|
+
try {
|
|
49
|
+
const records = await this.#keys.get(STORE_TYPE, [STORE_ID]);
|
|
50
|
+
let state = records?.[STORE_ID];
|
|
51
|
+
if (typeof state === 'string') state = JSON.parse(state);
|
|
52
|
+
const now = Date.now();
|
|
53
|
+
for (const [id, at] of Object.entries(state?.sent || {})) {
|
|
54
|
+
if (typeof at === 'number' && now - at <= MAX_AGE_MS) this.#sent.set(id, at);
|
|
55
|
+
}
|
|
56
|
+
for (const [id, entry] of Object.entries(state?.origins || {})) {
|
|
57
|
+
if (entry && typeof entry.at === 'number' && now - entry.at <= MAX_AGE_MS && entry.chat && entry.author) {
|
|
58
|
+
this.#origins.set(id, entry);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
this.#trim(this.#sent);
|
|
62
|
+
this.#trim(this.#origins);
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
this.#logger?.warn?.({ error }, 'unable to load recent message-security metadata');
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
#trim(map) {
|
|
70
|
+
while (map.size > MAX_ENTRIES) map.delete(map.keys().next().value);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
#scheduleFlush() {
|
|
74
|
+
if (!this.#keys?.set || this.#flushTimer) return;
|
|
75
|
+
this.#flushTimer = setTimeout(() => {
|
|
76
|
+
this.#flushTimer = undefined;
|
|
77
|
+
this.#persist().catch(error => this.#logger?.warn?.({ error }, 'unable to persist message-security metadata'));
|
|
78
|
+
}, FLUSH_DELAY_MS);
|
|
79
|
+
this.#flushTimer.unref?.();
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async #persist() {
|
|
83
|
+
if (!this.#keys?.set) return;
|
|
84
|
+
await this.ready;
|
|
85
|
+
return this.#mutex.mutex(async () => {
|
|
86
|
+
const state = {
|
|
87
|
+
version: 1,
|
|
88
|
+
sent: Object.fromEntries(this.#sent),
|
|
89
|
+
origins: Object.fromEntries(this.#origins)
|
|
90
|
+
};
|
|
91
|
+
await this.#keys.set({ [STORE_TYPE]: { [STORE_ID]: JSON.stringify(state) } });
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
async flush() {
|
|
96
|
+
if (this.#flushTimer) {
|
|
97
|
+
clearTimeout(this.#flushTimer);
|
|
98
|
+
this.#flushTimer = undefined;
|
|
99
|
+
}
|
|
100
|
+
await this.#persist();
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
#rememberOrigin(id, chat, chatAlt, author, authorAlt, fromMe) {
|
|
104
|
+
if (!id || !chat || !author) return;
|
|
105
|
+
this.#origins.delete(id);
|
|
106
|
+
this.#origins.set(id, { chat, chatAlt, author, authorAlt, fromMe: !!fromMe, at: Date.now() });
|
|
107
|
+
this.#trim(this.#origins);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
async recordSent(id, chat, author, chatAlt, authorAlt) {
|
|
111
|
+
if (!id) return;
|
|
112
|
+
await this.ready;
|
|
113
|
+
const now = Date.now();
|
|
114
|
+
this.#sent.delete(id);
|
|
115
|
+
this.#sent.set(id, now);
|
|
116
|
+
this.#trim(this.#sent);
|
|
117
|
+
this.#rememberOrigin(id, chat, chatAlt, author, authorAlt, true);
|
|
118
|
+
this.#scheduleFlush();
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
async hasSent(id) {
|
|
122
|
+
await this.ready;
|
|
123
|
+
return this.#sent.has(id);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async rememberMessage(message, me) {
|
|
127
|
+
await this.ready;
|
|
128
|
+
const key = message?.key;
|
|
129
|
+
const content = normalizeMessageContent(message?.message);
|
|
130
|
+
if (!key?.id || !key.remoteJid || !content || content.protocolMessage || content.reactionMessage || content.pollUpdateMessage) return;
|
|
131
|
+
const author = key.participant || (key.fromMe ? me?.id : key.remoteJid);
|
|
132
|
+
const authorAlt = key.participantAlt || (key.fromMe ? me?.lid : key.remoteJidAlt);
|
|
133
|
+
this.#rememberOrigin(key.id, key.remoteJid, key.remoteJidAlt, author, authorAlt, key.fromMe);
|
|
134
|
+
if (key.fromMe) {
|
|
135
|
+
this.#sent.delete(key.id);
|
|
136
|
+
this.#sent.set(key.id, Date.now());
|
|
137
|
+
this.#trim(this.#sent);
|
|
138
|
+
}
|
|
139
|
+
this.#scheduleFlush();
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async isEditAuthorized(targetId, message, me) {
|
|
143
|
+
await this.ready;
|
|
144
|
+
const origin = this.#origins.get(targetId);
|
|
145
|
+
const key = message?.key;
|
|
146
|
+
if (!origin || !key?.remoteJid) return false;
|
|
147
|
+
const originChats = [origin.chat, origin.chatAlt];
|
|
148
|
+
const editChats = [key.remoteJid, key.remoteJidAlt];
|
|
149
|
+
if (!hasIdentityMatch(originChats, editChats)) return false;
|
|
150
|
+
const originAuthors = [origin.author, origin.authorAlt];
|
|
151
|
+
if (origin.fromMe) originAuthors.push(me?.id, me?.lid);
|
|
152
|
+
const editAuthor = key.participant || (key.fromMe ? me?.id : key.remoteJid);
|
|
153
|
+
const editAuthors = [editAuthor, key.participantAlt, key.remoteJidAlt];
|
|
154
|
+
if (key.fromMe) editAuthors.push(me?.id, me?.lid);
|
|
155
|
+
return hasIdentityMatch(originAuthors, editAuthors);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Return receipt IDs which are not known to have been sent by this account. */
|
|
160
|
+
export async function findUnknownReceiptIds(ids, store) {
|
|
161
|
+
if (!store) return [];
|
|
162
|
+
const unknown = [];
|
|
163
|
+
for (const id of ids) {
|
|
164
|
+
if (id && !(await store.hasSent(id))) unknown.push(id);
|
|
165
|
+
}
|
|
166
|
+
return unknown;
|
|
167
|
+
}
|