@d0v3riz/baileys 7.0.0-rc.8 → 7.0.0-rc13
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/README.md +21 -15
- package/WAProto/fix-imports.js +74 -18
- package/WAProto/index.js +201 -160
- package/lib/Defaults/index.d.ts +19 -6
- package/lib/Defaults/index.d.ts.map +1 -1
- package/lib/Defaults/index.js +24 -10
- package/lib/Defaults/index.js.map +1 -1
- package/lib/Signal/libsignal.d.ts.map +1 -1
- package/lib/Signal/libsignal.js +105 -16
- package/lib/Signal/libsignal.js.map +1 -1
- package/lib/Signal/lid-mapping.d.ts +8 -8
- package/lib/Signal/lid-mapping.d.ts.map +1 -1
- package/lib/Signal/lid-mapping.js +176 -70
- package/lib/Signal/lid-mapping.js.map +1 -1
- package/lib/Socket/Client/websocket.d.ts +1 -1
- package/lib/Socket/Client/websocket.d.ts.map +1 -1
- package/lib/Socket/Client/websocket.js +5 -1
- package/lib/Socket/Client/websocket.js.map +1 -1
- package/lib/Socket/business.d.ts +36 -8
- package/lib/Socket/business.d.ts.map +1 -1
- package/lib/Socket/business.js +11 -8
- package/lib/Socket/business.js.map +1 -1
- package/lib/Socket/chats.d.ts +29 -5
- package/lib/Socket/chats.d.ts.map +1 -1
- package/lib/Socket/chats.js +292 -63
- package/lib/Socket/chats.js.map +1 -1
- package/lib/Socket/communities.d.ts +36 -8
- package/lib/Socket/communities.d.ts.map +1 -1
- package/lib/Socket/groups.d.ts +27 -5
- package/lib/Socket/groups.d.ts.map +1 -1
- package/lib/Socket/groups.js +20 -0
- package/lib/Socket/groups.js.map +1 -1
- package/lib/Socket/index.d.ts +36 -8
- package/lib/Socket/index.d.ts.map +1 -1
- package/lib/Socket/index.js +0 -6
- package/lib/Socket/index.js.map +1 -1
- package/lib/Socket/messages-recv.d.ts +40 -11
- package/lib/Socket/messages-recv.d.ts.map +1 -1
- package/lib/Socket/messages-recv.js +841 -354
- package/lib/Socket/messages-recv.js.map +1 -1
- package/lib/Socket/messages-send.d.ts +35 -6
- package/lib/Socket/messages-send.d.ts.map +1 -1
- package/lib/Socket/messages-send.js +263 -92
- package/lib/Socket/messages-send.js.map +1 -1
- package/lib/Socket/mex.d.ts.map +1 -1
- package/lib/Socket/mex.js +2 -0
- package/lib/Socket/mex.js.map +1 -1
- package/lib/Socket/newsletter.d.ts +27 -5
- package/lib/Socket/newsletter.d.ts.map +1 -1
- package/lib/Socket/newsletter.js +35 -3
- package/lib/Socket/newsletter.js.map +1 -1
- package/lib/Socket/socket.d.ts +9 -3
- package/lib/Socket/socket.d.ts.map +1 -1
- package/lib/Socket/socket.js +124 -39
- package/lib/Socket/socket.js.map +1 -1
- package/lib/Types/Auth.d.ts +2 -0
- package/lib/Types/Auth.d.ts.map +1 -1
- package/lib/Types/Call.d.ts +2 -1
- package/lib/Types/Call.d.ts.map +1 -1
- package/lib/Types/Chat.d.ts +1 -0
- package/lib/Types/Chat.d.ts.map +1 -1
- package/lib/Types/Contact.d.ts +2 -0
- package/lib/Types/Contact.d.ts.map +1 -1
- package/lib/Types/Events.d.ts +60 -6
- package/lib/Types/Events.d.ts.map +1 -1
- package/lib/Types/GroupMetadata.d.ts +4 -0
- package/lib/Types/GroupMetadata.d.ts.map +1 -1
- package/lib/Types/Message.d.ts +20 -5
- package/lib/Types/Message.d.ts.map +1 -1
- package/lib/Types/Message.js.map +1 -1
- package/lib/Types/{Newsletter.d.ts → Mex.d.ts} +13 -5
- package/lib/Types/Mex.d.ts.map +1 -0
- package/lib/Types/{Newsletter.js → Mex.js} +11 -3
- package/lib/Types/Mex.js.map +1 -0
- package/lib/Types/Signal.d.ts +12 -1
- package/lib/Types/Signal.d.ts.map +1 -1
- package/lib/Types/Socket.d.ts +3 -0
- package/lib/Types/Socket.d.ts.map +1 -1
- package/lib/Types/State.d.ts +58 -0
- package/lib/Types/State.d.ts.map +1 -1
- package/lib/Types/State.js +43 -0
- package/lib/Types/State.js.map +1 -1
- package/lib/Types/index.d.ts +1 -1
- package/lib/Types/index.d.ts.map +1 -1
- package/lib/Types/index.js +1 -1
- package/lib/Types/index.js.map +1 -1
- package/lib/Utils/auth-utils.d.ts +5 -0
- package/lib/Utils/auth-utils.d.ts.map +1 -1
- package/lib/Utils/auth-utils.js +65 -20
- package/lib/Utils/auth-utils.js.map +1 -1
- package/lib/Utils/chat-utils.d.ts +31 -1
- package/lib/Utils/chat-utils.d.ts.map +1 -1
- package/lib/Utils/chat-utils.js +180 -71
- package/lib/Utils/chat-utils.js.map +1 -1
- package/lib/Utils/companion-reg-client-utils.d.ts +17 -0
- package/lib/Utils/companion-reg-client-utils.d.ts.map +1 -0
- package/lib/Utils/companion-reg-client-utils.js +35 -0
- package/lib/Utils/companion-reg-client-utils.js.map +1 -0
- package/lib/Utils/crypto.d.ts +4 -8
- package/lib/Utils/crypto.d.ts.map +1 -1
- package/lib/Utils/crypto.js +2 -26
- package/lib/Utils/crypto.js.map +1 -1
- package/lib/Utils/decode-wa-message.d.ts +18 -0
- package/lib/Utils/decode-wa-message.d.ts.map +1 -1
- package/lib/Utils/decode-wa-message.js +34 -0
- package/lib/Utils/decode-wa-message.js.map +1 -1
- package/lib/Utils/event-buffer.d.ts +2 -0
- package/lib/Utils/event-buffer.d.ts.map +1 -1
- package/lib/Utils/event-buffer.js +82 -8
- package/lib/Utils/event-buffer.js.map +1 -1
- package/lib/Utils/generics.d.ts +2 -0
- package/lib/Utils/generics.d.ts.map +1 -1
- package/lib/Utils/generics.js +13 -1
- package/lib/Utils/generics.js.map +1 -1
- package/lib/Utils/history.d.ts +8 -3
- package/lib/Utils/history.d.ts.map +1 -1
- package/lib/Utils/history.js +58 -14
- package/lib/Utils/history.js.map +1 -1
- package/lib/Utils/identity-change-handler.d.ts +44 -0
- package/lib/Utils/identity-change-handler.d.ts.map +1 -0
- package/lib/Utils/identity-change-handler.js +50 -0
- package/lib/Utils/identity-change-handler.js.map +1 -0
- package/lib/Utils/index.d.ts +3 -0
- package/lib/Utils/index.d.ts.map +1 -1
- package/lib/Utils/index.js +3 -0
- package/lib/Utils/index.js.map +1 -1
- package/lib/Utils/link-preview.js +2 -2
- package/lib/Utils/link-preview.js.map +1 -1
- package/lib/Utils/lt-hash.d.ts +7 -12
- package/lib/Utils/lt-hash.d.ts.map +1 -1
- package/lib/Utils/lt-hash.js +2 -42
- package/lib/Utils/lt-hash.js.map +1 -1
- package/lib/Utils/make-mutex.d.ts +1 -0
- package/lib/Utils/make-mutex.d.ts.map +1 -1
- package/lib/Utils/make-mutex.js +20 -27
- package/lib/Utils/make-mutex.js.map +1 -1
- package/lib/Utils/message-retry-manager.d.ts +35 -2
- package/lib/Utils/message-retry-manager.d.ts.map +1 -1
- package/lib/Utils/message-retry-manager.js +98 -5
- package/lib/Utils/message-retry-manager.js.map +1 -1
- package/lib/Utils/messages-media.d.ts +22 -3
- package/lib/Utils/messages-media.d.ts.map +1 -1
- package/lib/Utils/messages-media.js +169 -44
- package/lib/Utils/messages-media.js.map +1 -1
- package/lib/Utils/messages.d.ts +2 -0
- package/lib/Utils/messages.d.ts.map +1 -1
- package/lib/Utils/messages.js +70 -27
- package/lib/Utils/messages.js.map +1 -1
- package/lib/Utils/noise-handler.d.ts +4 -4
- package/lib/Utils/noise-handler.d.ts.map +1 -1
- package/lib/Utils/noise-handler.js +139 -85
- package/lib/Utils/noise-handler.js.map +1 -1
- package/lib/Utils/offline-node-processor.d.ts +17 -0
- package/lib/Utils/offline-node-processor.d.ts.map +1 -0
- package/lib/Utils/offline-node-processor.js +40 -0
- package/lib/Utils/offline-node-processor.js.map +1 -0
- package/lib/Utils/process-message.d.ts.map +1 -1
- package/lib/Utils/process-message.js +165 -15
- package/lib/Utils/process-message.js.map +1 -1
- package/lib/Utils/reporting-utils.d.ts +11 -0
- package/lib/Utils/reporting-utils.d.ts.map +1 -0
- package/lib/Utils/reporting-utils.js +258 -0
- package/lib/Utils/reporting-utils.js.map +1 -0
- package/lib/Utils/signal.d.ts +13 -0
- package/lib/Utils/signal.d.ts.map +1 -1
- package/lib/Utils/signal.js +42 -0
- package/lib/Utils/signal.js.map +1 -1
- package/lib/Utils/stanza-ack.d.ts +11 -0
- package/lib/Utils/stanza-ack.d.ts.map +1 -0
- package/lib/Utils/stanza-ack.js +38 -0
- package/lib/Utils/stanza-ack.js.map +1 -0
- package/lib/Utils/sync-action-utils.d.ts +19 -0
- package/lib/Utils/sync-action-utils.d.ts.map +1 -0
- package/lib/Utils/sync-action-utils.js +49 -0
- package/lib/Utils/sync-action-utils.js.map +1 -0
- package/lib/Utils/tc-token-utils.d.ts +37 -0
- package/lib/Utils/tc-token-utils.d.ts.map +1 -0
- package/lib/Utils/tc-token-utils.js +163 -0
- package/lib/Utils/tc-token-utils.js.map +1 -0
- package/lib/Utils/validate-connection.d.ts.map +1 -1
- package/lib/Utils/validate-connection.js +4 -1
- package/lib/Utils/validate-connection.js.map +1 -1
- package/lib/WABinary/decode.d.ts.map +1 -1
- package/lib/WABinary/decode.js +24 -0
- package/lib/WABinary/decode.js.map +1 -1
- package/lib/WABinary/encode.js +5 -1
- package/lib/WABinary/encode.js.map +1 -1
- package/lib/WABinary/generic-utils.d.ts +1 -1
- package/lib/WABinary/generic-utils.d.ts.map +1 -1
- package/lib/WABinary/generic-utils.js +19 -8
- package/lib/WABinary/generic-utils.js.map +1 -1
- package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -1
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +26 -3
- package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -1
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts.map +1 -0
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.js.map +1 -0
- package/lib/WAUSync/Protocols/index.d.ts +1 -0
- package/lib/WAUSync/Protocols/index.d.ts.map +1 -1
- package/lib/WAUSync/Protocols/index.js +1 -0
- package/lib/WAUSync/Protocols/index.js.map +1 -1
- package/lib/WAUSync/USyncQuery.d.ts +1 -0
- package/lib/WAUSync/USyncQuery.d.ts.map +1 -1
- package/lib/WAUSync/USyncQuery.js +6 -2
- package/lib/WAUSync/USyncQuery.js.map +1 -1
- package/lib/WAUSync/USyncUser.d.ts +4 -0
- package/lib/WAUSync/USyncUser.d.ts.map +1 -1
- package/lib/WAUSync/USyncUser.js +8 -0
- package/lib/WAUSync/USyncUser.js.map +1 -1
- package/package.json +39 -8
- package/lib/Types/Newsletter.d.ts.map +0 -1
- package/lib/Types/Newsletter.js.map +0 -1
|
@@ -23,12 +23,31 @@ export interface RetryStatistics {
|
|
|
23
23
|
sessionRecreations: number;
|
|
24
24
|
phoneRequests: number;
|
|
25
25
|
}
|
|
26
|
+
export declare enum RetryReason {
|
|
27
|
+
UnknownError = 0,
|
|
28
|
+
SignalErrorNoSession = 1,
|
|
29
|
+
SignalErrorInvalidKey = 2,
|
|
30
|
+
SignalErrorInvalidKeyId = 3,
|
|
31
|
+
/** MAC verification failed - most common cause of decryption failures */
|
|
32
|
+
SignalErrorInvalidMessage = 4,
|
|
33
|
+
SignalErrorInvalidSignature = 5,
|
|
34
|
+
SignalErrorFutureMessage = 6,
|
|
35
|
+
/** Explicit MAC failure - session is definitely out of sync */
|
|
36
|
+
SignalErrorBadMac = 7,
|
|
37
|
+
SignalErrorInvalidSession = 8,
|
|
38
|
+
SignalErrorInvalidMsgKey = 9,
|
|
39
|
+
BadBroadcastEphemeralSetting = 10,
|
|
40
|
+
UnknownCompanionNoPrekey = 11,
|
|
41
|
+
AdvFailure = 12,
|
|
42
|
+
StatusRevokeDelay = 13
|
|
43
|
+
}
|
|
26
44
|
export declare class MessageRetryManager {
|
|
27
45
|
private logger;
|
|
28
46
|
private recentMessagesMap;
|
|
29
47
|
private messageKeyIndex;
|
|
30
48
|
private sessionRecreateHistory;
|
|
31
49
|
private retryCounters;
|
|
50
|
+
private baseKeys;
|
|
32
51
|
private pendingPhoneRequests;
|
|
33
52
|
private readonly maxMsgRetryCount;
|
|
34
53
|
private statistics;
|
|
@@ -42,12 +61,22 @@ export declare class MessageRetryManager {
|
|
|
42
61
|
*/
|
|
43
62
|
getRecentMessage(to: string, id: string): RecentMessage | undefined;
|
|
44
63
|
/**
|
|
45
|
-
* Check if a session should be recreated based on retry count and
|
|
64
|
+
* Check if a session should be recreated based on retry count, history, and error code.
|
|
65
|
+
* MAC errors (codes 4 and 7) trigger immediate session recreation regardless of timeout.
|
|
46
66
|
*/
|
|
47
|
-
shouldRecreateSession(jid: string,
|
|
67
|
+
shouldRecreateSession(jid: string, hasSession: boolean, errorCode?: RetryReason): {
|
|
48
68
|
reason: string;
|
|
49
69
|
recreate: boolean;
|
|
50
70
|
};
|
|
71
|
+
/**
|
|
72
|
+
* Parse error code from retry receipt's retry node.
|
|
73
|
+
* Returns undefined if no error code is present.
|
|
74
|
+
*/
|
|
75
|
+
parseRetryErrorCode(errorAttr: string | undefined): RetryReason | undefined;
|
|
76
|
+
/**
|
|
77
|
+
* Check if an error code indicates a MAC failure
|
|
78
|
+
*/
|
|
79
|
+
isMacError(errorCode: RetryReason | undefined): boolean;
|
|
51
80
|
/**
|
|
52
81
|
* Increment retry counter for a message
|
|
53
82
|
*/
|
|
@@ -76,6 +105,10 @@ export declare class MessageRetryManager {
|
|
|
76
105
|
* Cancel pending phone request
|
|
77
106
|
*/
|
|
78
107
|
cancelPendingPhoneRequest(messageId: string): void;
|
|
108
|
+
clear(): void;
|
|
109
|
+
saveBaseKey(addr: string, msgId: string, baseKey: Uint8Array): void;
|
|
110
|
+
hasSameBaseKey(addr: string, msgId: string, baseKey: Uint8Array): boolean;
|
|
111
|
+
deleteBaseKey(addr: string, msgId: string): void;
|
|
79
112
|
private keyToString;
|
|
80
113
|
private removeRecentMessage;
|
|
81
114
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"message-retry-manager.d.ts","sourceRoot":"","sources":["../../src/Utils/message-retry-manager.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,wBAAwB,CAAA;AACnD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,UAAU,CAAA;AAUvC,MAAM,WAAW,gBAAgB;IAChC,EAAE,EAAE,MAAM,CAAA;IACV,EAAE,EAAE,MAAM,CAAA;CACV;AAED,MAAM,WAAW,aAAa;IAC7B,OAAO,EAAE,KAAK,CAAC,QAAQ,CAAA;IACvB,SAAS,EAAE,MAAM,CAAA;CACjB;AAED,MAAM,WAAW,sBAAsB;IACtC,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;CACrB;AAED,MAAM,WAAW,YAAY;IAC5B,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAAA;CAC3B;AAED,MAAM,MAAM,mBAAmB,GAAG,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,OAAO,UAAU,CAAC,CAAC,CAAA;AAE/E,MAAM,WAAW,eAAe;IAC/B,YAAY,EAAE,MAAM,CAAA;IACpB,iBAAiB,EAAE,MAAM,CAAA;IACzB,aAAa,EAAE,MAAM,CAAA;IACrB,YAAY,EAAE,MAAM,CAAA;IACpB,kBAAkB,EAAE,MAAM,CAAA;IAC1B,aAAa,EAAE,MAAM,CAAA;CACrB;
|
|
1
|
+
{"version":3,"file":"message-retry-manager.d.ts","sourceRoot":"","sources":["../../src/Utils/message-retry-manager.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,wBAAwB,CAAA;AACnD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,UAAU,CAAA;AAUvC,MAAM,WAAW,gBAAgB;IAChC,EAAE,EAAE,MAAM,CAAA;IACV,EAAE,EAAE,MAAM,CAAA;CACV;AAED,MAAM,WAAW,aAAa;IAC7B,OAAO,EAAE,KAAK,CAAC,QAAQ,CAAA;IACvB,SAAS,EAAE,MAAM,CAAA;CACjB;AAED,MAAM,WAAW,sBAAsB;IACtC,CAAC,G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MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI;IAIhD,OAAO,CAAC,WAAW;IAInB,OAAO,CAAC,mBAAmB;CAS3B"}
|
|
@@ -5,6 +5,28 @@ const MESSAGE_KEY_SEPARATOR = '\u0000';
|
|
|
5
5
|
/** Timeout for session recreation - 1 hour */
|
|
6
6
|
const RECREATE_SESSION_TIMEOUT = 60 * 60 * 1000; // 1 hour in milliseconds
|
|
7
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]);
|
|
8
30
|
export class MessageRetryManager {
|
|
9
31
|
constructor(logger, maxMsgRetryCount) {
|
|
10
32
|
this.logger = logger;
|
|
@@ -30,6 +52,11 @@ export class MessageRetryManager {
|
|
|
30
52
|
ttlAutopurge: true,
|
|
31
53
|
updateAgeOnGet: true
|
|
32
54
|
}); // 15 minutes TTL
|
|
55
|
+
this.baseKeys = new LRUCache({
|
|
56
|
+
max: 1024,
|
|
57
|
+
ttl: 15 * 60 * 1000,
|
|
58
|
+
ttlAutopurge: true
|
|
59
|
+
});
|
|
33
60
|
this.pendingPhoneRequests = {};
|
|
34
61
|
this.maxMsgRetryCount = 5;
|
|
35
62
|
this.statistics = {
|
|
@@ -65,9 +92,10 @@ export class MessageRetryManager {
|
|
|
65
92
|
return this.recentMessagesMap.get(keyStr);
|
|
66
93
|
}
|
|
67
94
|
/**
|
|
68
|
-
* Check if a session should be recreated based on retry count and
|
|
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.
|
|
69
97
|
*/
|
|
70
|
-
shouldRecreateSession(jid,
|
|
98
|
+
shouldRecreateSession(jid, hasSession, errorCode) {
|
|
71
99
|
// If we don't have a session, always recreate
|
|
72
100
|
if (!hasSession) {
|
|
73
101
|
this.sessionRecreateHistory.set(jid, Date.now());
|
|
@@ -77,9 +105,15 @@ export class MessageRetryManager {
|
|
|
77
105
|
recreate: true
|
|
78
106
|
};
|
|
79
107
|
}
|
|
80
|
-
//
|
|
81
|
-
if (
|
|
82
|
-
|
|
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
|
+
};
|
|
83
117
|
}
|
|
84
118
|
const now = Date.now();
|
|
85
119
|
const prevTime = this.sessionRecreateHistory.get(jid);
|
|
@@ -94,6 +128,30 @@ export class MessageRetryManager {
|
|
|
94
128
|
}
|
|
95
129
|
return { reason: '', recreate: false };
|
|
96
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
|
+
}
|
|
97
155
|
/**
|
|
98
156
|
* Increment retry counter for a message
|
|
99
157
|
*/
|
|
@@ -157,6 +215,41 @@ export class MessageRetryManager {
|
|
|
157
215
|
this.logger.debug(`Cancelled pending phone request for message ${messageId}`);
|
|
158
216
|
}
|
|
159
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
|
+
}
|
|
160
253
|
keyToString(key) {
|
|
161
254
|
return `${key.to}${MESSAGE_KEY_SEPARATOR}${key.id}`;
|
|
162
255
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"message-retry-manager.js","sourceRoot":"","sources":["../../src/Utils/message-retry-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AAIpC,6EAA6E;AAC7E,MAAM,oBAAoB,GAAG,GAAG,CAAA;AAEhC,MAAM,qBAAqB,GAAG,QAAQ,CAAA;AAEtC,8CAA8C;AAC9C,MAAM,wBAAwB,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAA,CAAC,yBAAyB;AACzE,MAAM,mBAAmB,GAAG,IAAI,CAAA;AA8BhC,MAAM,OAAO,mBAAmB;
|
|
1
|
+
{"version":3,"file":"message-retry-manager.js","sourceRoot":"","sources":["../../src/Utils/message-retry-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AAIpC,6EAA6E;AAC7E,MAAM,oBAAoB,GAAG,GAAG,CAAA;AAEhC,MAAM,qBAAqB,GAAG,QAAQ,CAAA;AAEtC,8CAA8C;AAC9C,MAAM,wBAAwB,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAA,CAAC,yBAAyB;AACzE,MAAM,mBAAmB,GAAG,IAAI,CAAA;AA8BhC,iEAAiE;AACjE,MAAM,CAAN,IAAY,WAiBX;AAjBD,WAAY,WAAW;IACtB,6DAAgB,CAAA;IAChB,6EAAwB,CAAA;IACxB,+EAAyB,CAAA;IACzB,mFAA2B,CAAA;IAC3B,yEAAyE;IACzE,uFAA6B,CAAA;IAC7B,2FAA+B,CAAA;IAC/B,qFAA4B,CAAA;IAC5B,+DAA+D;IAC/D,uEAAqB,CAAA;IACrB,uFAA6B,CAAA;IAC7B,qFAA4B,CAAA;IAC5B,8FAAiC,CAAA;IACjC,sFAA6B,CAAA;IAC7B,0DAAe,CAAA;IACf,wEAAsB,CAAA;AACvB,CAAC,EAjBW,WAAW,KAAX,WAAW,QAiBtB;AAED,uFAAuF;AACvF,MAAM,eAAe,GAAG,IAAI,GAAG,CAAC,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CAAA;QAC3C,CAAC;QAED,OAAO,IAAI,CAAA;IACZ,CAAC;IAED,aAAa,CAAC,IAAY,EAAE,KAAa;QACxC,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,GAAG,IAAI,IAAI,KAAK,EAAE,CAAC,CAAA;IACzC,CAAC;IAEO,WAAW,CAAC,GAAqB;QACxC,OAAO,GAAG,GAAG,CAAC,EAAE,GAAG,qBAAqB,GAAG,GAAG,CAAC,EAAE,EAAE,CAAA;IACpD,CAAC;IAEO,mBAAmB,CAAC,SAAiB;QAC5C,MAAM,MAAM,GAAG,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,SAAS,CAAC,CAAA;QAClD,IAAI,CAAC,MAAM,EAAE,CAAC;YACb,OAAM;QACP,CAAC;QAED,IAAI,CAAC,iBAAiB,CAAC,MAAM,CAAC,MAAM,CAAC,CAAA;QACrC,IAAI,CAAC,eAAe,CAAC,MAAM,CAAC,SAAS,CAAC,CAAA;IACvC,CAAC;CACD"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Boom } from '@hapi/boom';
|
|
2
|
+
import type { Agent } from 'https';
|
|
2
3
|
import { Readable, Transform } from 'stream';
|
|
3
4
|
import { URL } from 'url';
|
|
4
5
|
import { proto } from '../../WAProto/index.js';
|
|
@@ -79,12 +80,15 @@ export declare const encryptedStream: (media: WAMediaUpload, mediaType: MediaTyp
|
|
|
79
80
|
fileSha256: NonSharedBuffer;
|
|
80
81
|
fileLength: number;
|
|
81
82
|
}>;
|
|
83
|
+
export declare const DEF_MEDIA_HOST = "mmg.whatsapp.net";
|
|
82
84
|
export type MediaDownloadOptions = {
|
|
83
85
|
startByte?: number;
|
|
84
86
|
endByte?: number;
|
|
85
87
|
options?: RequestInit;
|
|
88
|
+
/** Optional media host override; falls back to DEF_MEDIA_HOST when not provided. */
|
|
89
|
+
host?: string;
|
|
86
90
|
};
|
|
87
|
-
export declare const getUrlFromDirectPath: (directPath: string) => string;
|
|
91
|
+
export declare const getUrlFromDirectPath: (directPath: string, host?: string) => string;
|
|
88
92
|
export declare const downloadContentFromMessage: ({ mediaKey, directPath, url }: DownloadableMessage, type: MediaType, opts?: MediaDownloadOptions) => Promise<Transform>;
|
|
89
93
|
/**
|
|
90
94
|
* Decrypts and downloads an AES256-CBC encrypted file given the keys.
|
|
@@ -92,11 +96,26 @@ export declare const downloadContentFromMessage: ({ mediaKey, directPath, url }:
|
|
|
92
96
|
* */
|
|
93
97
|
export declare const downloadEncryptedContent: (downloadUrl: string, { cipherKey, iv }: MediaDecryptionKeyInfo, { startByte, endByte, options }?: MediaDownloadOptions) => Promise<Transform>;
|
|
94
98
|
export declare function extensionForMediaMessage(message: WAMessageContent): string;
|
|
99
|
+
type MediaUploadResult = {
|
|
100
|
+
url?: string;
|
|
101
|
+
direct_path?: string;
|
|
102
|
+
meta_hmac?: string;
|
|
103
|
+
ts?: number;
|
|
104
|
+
fbid?: number;
|
|
105
|
+
};
|
|
106
|
+
export type UploadParams = {
|
|
107
|
+
url: string;
|
|
108
|
+
filePath: string;
|
|
109
|
+
headers: Record<string, string>;
|
|
110
|
+
timeoutMs?: number;
|
|
111
|
+
agent?: Agent;
|
|
112
|
+
};
|
|
113
|
+
export declare const uploadWithNodeHttp: ({ url, filePath, headers, timeoutMs, agent }: UploadParams, redirectCount?: number) => Promise<MediaUploadResult | undefined>;
|
|
95
114
|
export declare const getWAUploadToServer: ({ customUploadHosts, fetchAgent, logger, options }: SocketConfig, refreshMediaConn: (force: boolean) => Promise<MediaConnInfo>) => WAMediaUploadFunction;
|
|
96
115
|
/**
|
|
97
116
|
* Generate a binary node that will request the phone to re-upload the media & return the newly uploaded URL
|
|
98
117
|
*/
|
|
99
|
-
export declare const encryptMediaRetryRequest: (key: WAMessageKey, mediaKey: Buffer | Uint8Array, meId: string) =>
|
|
118
|
+
export declare const encryptMediaRetryRequest: (key: WAMessageKey, mediaKey: Buffer | Uint8Array, meId: string) => BinaryNode;
|
|
100
119
|
export declare const decodeMediaRetryNode: (node: BinaryNode) => {
|
|
101
120
|
key: WAMessageKey;
|
|
102
121
|
media?: {
|
|
@@ -108,7 +127,7 @@ export declare const decodeMediaRetryNode: (node: BinaryNode) => {
|
|
|
108
127
|
export declare const decryptMediaRetryData: ({ ciphertext, iv }: {
|
|
109
128
|
ciphertext: Uint8Array;
|
|
110
129
|
iv: Uint8Array;
|
|
111
|
-
}, mediaKey: Uint8Array, msgId: string) =>
|
|
130
|
+
}, mediaKey: Uint8Array, msgId: string) => proto.MediaRetryNotification;
|
|
112
131
|
export declare const getStatusCodeForMediaRetry: (code: number) => 200 | 412 | 404 | 418;
|
|
113
132
|
export {};
|
|
114
133
|
//# sourceMappingURL=messages-media.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"messages-media.d.ts","sourceRoot":"","sources":["../../src/Utils/messages-media.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAA;
|
|
1
|
+
{"version":3,"file":"messages-media.d.ts","sourceRoot":"","sources":["../../src/Utils/messages-media.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAA;AAKjC,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,OAAO,CAAA;AAIlC,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,QAAQ,CAAA;AAC5C,OAAO,EAAE,GAAG,EAAE,MAAM,KAAK,CAAA;AACzB,OAAO,EAAE,KAAK,EAAE,MAAM,wBAAwB,CAAA;AAC9C,OAAO,EAA0D,KAAK,SAAS,EAAE,MAAM,aAAa,CAAA;AACpG,OAAO,KAAK,EAEX,mBAAmB,EACnB,aAAa,EACb,sBAAsB,EAEtB,YAAY,EAEZ,aAAa,EACb,qBAAqB,EACrB,gBAAgB,EAChB,YAAY,EACZ,MAAM,UAAU,CAAA;AACjB,OAAO,EAAE,KAAK,UAAU,EAAmE,MAAM,aAAa,CAAA;AAG9G,OAAO,KAAK,EAAE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CAAC,EAAE,MAAM,CAAA;IAClB,EAAE,CAAC,EAAE,MAAM,CAAA;IACX,IAAI,CAAC,EAAE,MAAM,CAAA;CACb,CAAA;AAED,MAAM,MAAM,YAAY,GAAG;IAC1B,GAAG,EAAE,MAAM,CAAA;IACX,QAAQ,EAAE,MAAM,CAAA;IAChB,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAC/B,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,KAAK,CAAC,EAAE,KAAK,CAAA;CACb,CAAA;AAED,eAAO,MAAM,kBAAkB,GAC9B,8CAA8C,YAAY,EAC1D,sBAAiB,KACf,OAAO,CAAC,iBAAiB,GAAG,SAAS,CAuEvC,CAAA;AA0DD,eAAO,MAAM,mBAAmB,GAC/B,oDAAoD,YAAY,EAChE,kBAAkB,CAAC,KAAK,EAAE,OAAO,KAAK,OAAO,CAAC,aAAa,CAAC,KAC1D,qBAsEF,CAAA;AAMD;;GAEG;AACH,eAAO,MAAM,wBAAwB,GAAI,KAAK,YAAY,EAAE,UAAU,MAAM,GAAG,UAAU,EAAE,MAAM,MAAM,eAwCtG,CAAA;AAED,eAAO,MAAM,oBAAoB,GAAI,MAAM,UAAU;;;;;;;CA+BpD,CAAA;AAED,eAAO,MAAM,qBAAqB,GACjC,oBAAoB;IAAE,UAAU,EAAE,UAAU,CAAC;IAAC,EAAE,EAAE,UAAU,CAAA;CAAE,EAC9D,UAAU,UAAU,EACpB,OAAO,MAAM,iCAKb,CAAA;AAED,eAAO,MAAM,0BAA0B,GAAI,MAAM,MAAM,0BACiB,CAAA"}
|
|
@@ -75,7 +75,7 @@ export async function getMediaKeys(buffer, mediaType) {
|
|
|
75
75
|
buffer = Buffer.from(buffer.replace('data:;base64,', ''), 'base64');
|
|
76
76
|
}
|
|
77
77
|
// expand using HKDF to 112 bytes, also pass in the relevant app info
|
|
78
|
-
const expandedMediaKey =
|
|
78
|
+
const expandedMediaKey = hkdf(buffer, 112, { info: hkdfInfoKey(mediaType) });
|
|
79
79
|
return {
|
|
80
80
|
iv: expandedMediaKey.slice(0, 16),
|
|
81
81
|
cipherKey: expandedMediaKey.slice(16, 48),
|
|
@@ -324,10 +324,13 @@ export const encryptedStream = async (media, mediaType, { logger, saveOriginalFi
|
|
|
324
324
|
const hmac = Crypto.createHmac('sha256', macKey).update(iv);
|
|
325
325
|
const sha256Plain = Crypto.createHash('sha256');
|
|
326
326
|
const sha256Enc = Crypto.createHash('sha256');
|
|
327
|
-
const onChunk = (buff) => {
|
|
327
|
+
const onChunk = async (buff) => {
|
|
328
328
|
sha256Enc.update(buff);
|
|
329
329
|
hmac.update(buff);
|
|
330
|
-
|
|
330
|
+
// Handle backpressure: if write returns false, wait for drain
|
|
331
|
+
if (!encFileWriteStream.write(buff)) {
|
|
332
|
+
await once(encFileWriteStream, 'drain');
|
|
333
|
+
}
|
|
331
334
|
};
|
|
332
335
|
try {
|
|
333
336
|
for await (const data of stream) {
|
|
@@ -345,17 +348,23 @@ export const encryptedStream = async (media, mediaType, { logger, saveOriginalFi
|
|
|
345
348
|
}
|
|
346
349
|
}
|
|
347
350
|
sha256Plain.update(data);
|
|
348
|
-
onChunk(aes.update(data));
|
|
351
|
+
await onChunk(aes.update(data));
|
|
349
352
|
}
|
|
350
|
-
onChunk(aes.final());
|
|
353
|
+
await onChunk(aes.final());
|
|
351
354
|
const mac = hmac.digest().slice(0, 10);
|
|
352
355
|
sha256Enc.update(mac);
|
|
353
356
|
const fileSha256 = sha256Plain.digest();
|
|
354
357
|
const fileEncSha256 = sha256Enc.digest();
|
|
355
358
|
encFileWriteStream.write(mac);
|
|
359
|
+
const encFinishPromise = once(encFileWriteStream, 'finish');
|
|
360
|
+
const originalFinishPromise = originalFileStream ? once(originalFileStream, 'finish') : Promise.resolve();
|
|
356
361
|
encFileWriteStream.end();
|
|
357
362
|
originalFileStream?.end?.();
|
|
358
363
|
stream.destroy();
|
|
364
|
+
// Wait for write streams to fully flush to disk
|
|
365
|
+
// This helps reduce memory pressure by allowing OS to release buffers
|
|
366
|
+
await encFinishPromise;
|
|
367
|
+
await originalFinishPromise;
|
|
359
368
|
logger?.debug('encrypted data successfully');
|
|
360
369
|
return {
|
|
361
370
|
mediaKey,
|
|
@@ -388,15 +397,27 @@ export const encryptedStream = async (media, mediaType, { logger, saveOriginalFi
|
|
|
388
397
|
throw error;
|
|
389
398
|
}
|
|
390
399
|
};
|
|
391
|
-
const
|
|
400
|
+
export const DEF_MEDIA_HOST = 'mmg.whatsapp.net';
|
|
392
401
|
const AES_CHUNK_SIZE = 16;
|
|
393
402
|
const toSmallestChunkSize = (num) => {
|
|
394
403
|
return Math.floor(num / AES_CHUNK_SIZE) * AES_CHUNK_SIZE;
|
|
395
404
|
};
|
|
396
|
-
export const getUrlFromDirectPath = (directPath) => `https://${
|
|
405
|
+
export const getUrlFromDirectPath = (directPath, host = DEF_MEDIA_HOST) => `https://${host}${directPath}`;
|
|
406
|
+
const extractHost = (url) => {
|
|
407
|
+
if (!url)
|
|
408
|
+
return undefined;
|
|
409
|
+
try {
|
|
410
|
+
return new URL(url).host;
|
|
411
|
+
}
|
|
412
|
+
catch {
|
|
413
|
+
return undefined;
|
|
414
|
+
}
|
|
415
|
+
};
|
|
397
416
|
export const downloadContentFromMessage = async ({ mediaKey, directPath, url }, type, opts = {}) => {
|
|
398
|
-
|
|
399
|
-
|
|
417
|
+
// Fallback host: explicit opt > host parsed from `url` > DEF_MEDIA_HOST.
|
|
418
|
+
// Lets us honor a non-default host carried by the proto without forcing callers to thread it through.
|
|
419
|
+
const fallbackHost = opts.host ?? extractHost(url);
|
|
420
|
+
const downloadUrl = directPath ? getUrlFromDirectPath(directPath, fallbackHost) : url;
|
|
400
421
|
if (!downloadUrl) {
|
|
401
422
|
throw new Boom('No valid media URL or directPath present in message', { statusCode: 400 });
|
|
402
423
|
}
|
|
@@ -456,7 +477,7 @@ export const downloadEncryptedContent = async (downloadUrl, { cipherKey, iv }, {
|
|
|
456
477
|
};
|
|
457
478
|
const output = new Transform({
|
|
458
479
|
transform(chunk, _, callback) {
|
|
459
|
-
let data = Buffer.concat([remainingBytes, chunk]);
|
|
480
|
+
let data = remainingBytes.length ? Buffer.concat([remainingBytes, chunk]) : chunk;
|
|
460
481
|
const decryptLength = toSmallestChunkSize(data.length);
|
|
461
482
|
remainingBytes = data.slice(decryptLength);
|
|
462
483
|
data = data.slice(0, decryptLength);
|
|
@@ -506,6 +527,119 @@ export function extensionForMediaMessage(message) {
|
|
|
506
527
|
}
|
|
507
528
|
return extension;
|
|
508
529
|
}
|
|
530
|
+
const isNodeRuntime = () => {
|
|
531
|
+
return (typeof process !== 'undefined' &&
|
|
532
|
+
process.versions?.node !== null &&
|
|
533
|
+
typeof process.versions.bun === 'undefined' &&
|
|
534
|
+
typeof globalThis.Deno === 'undefined');
|
|
535
|
+
};
|
|
536
|
+
export const uploadWithNodeHttp = async ({ url, filePath, headers, timeoutMs, agent }, redirectCount = 0) => {
|
|
537
|
+
if (redirectCount > 5) {
|
|
538
|
+
throw new Error('Too many redirects');
|
|
539
|
+
}
|
|
540
|
+
const parsedUrl = new URL(url);
|
|
541
|
+
const httpModule = parsedUrl.protocol === 'https:' ? await import('https') : await import('http');
|
|
542
|
+
// Get file size for Content-Length header (required for Node.js streaming)
|
|
543
|
+
const fileStats = await fs.stat(filePath);
|
|
544
|
+
const fileSize = fileStats.size;
|
|
545
|
+
return new Promise((resolve, reject) => {
|
|
546
|
+
const req = httpModule.request({
|
|
547
|
+
hostname: parsedUrl.hostname,
|
|
548
|
+
port: parsedUrl.port || (parsedUrl.protocol === 'https:' ? 443 : 80),
|
|
549
|
+
path: parsedUrl.pathname + parsedUrl.search,
|
|
550
|
+
method: 'POST',
|
|
551
|
+
headers: {
|
|
552
|
+
...headers,
|
|
553
|
+
'Content-Length': fileSize
|
|
554
|
+
},
|
|
555
|
+
agent,
|
|
556
|
+
timeout: timeoutMs
|
|
557
|
+
}, res => {
|
|
558
|
+
// Handle redirects (3xx)
|
|
559
|
+
if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
|
|
560
|
+
res.resume(); // Consume response to free resources
|
|
561
|
+
const newUrl = new URL(res.headers.location, url).toString();
|
|
562
|
+
resolve(uploadWithNodeHttp({
|
|
563
|
+
url: newUrl,
|
|
564
|
+
filePath,
|
|
565
|
+
headers,
|
|
566
|
+
timeoutMs,
|
|
567
|
+
agent
|
|
568
|
+
}, redirectCount + 1));
|
|
569
|
+
return;
|
|
570
|
+
}
|
|
571
|
+
let body = '';
|
|
572
|
+
res.on('data', chunk => (body += chunk));
|
|
573
|
+
res.on('end', () => {
|
|
574
|
+
try {
|
|
575
|
+
resolve(JSON.parse(body));
|
|
576
|
+
}
|
|
577
|
+
catch {
|
|
578
|
+
resolve(undefined);
|
|
579
|
+
}
|
|
580
|
+
});
|
|
581
|
+
});
|
|
582
|
+
req.on('error', reject);
|
|
583
|
+
req.on('timeout', () => {
|
|
584
|
+
req.destroy();
|
|
585
|
+
reject(new Error('Upload timeout'));
|
|
586
|
+
});
|
|
587
|
+
const stream = createReadStream(filePath);
|
|
588
|
+
stream.pipe(req);
|
|
589
|
+
stream.on('error', err => {
|
|
590
|
+
req.destroy();
|
|
591
|
+
reject(err);
|
|
592
|
+
});
|
|
593
|
+
});
|
|
594
|
+
};
|
|
595
|
+
const uploadWithFetch = async ({ url, filePath, headers, timeoutMs, agent }) => {
|
|
596
|
+
// Convert Node.js Readable to Web ReadableStream
|
|
597
|
+
const nodeStream = createReadStream(filePath);
|
|
598
|
+
const webStream = Readable.toWeb(nodeStream);
|
|
599
|
+
// Native fetch only accepts Undici-style dispatchers, not generic https Agents.
|
|
600
|
+
const dispatcher = typeof agent?.dispatch === 'function' ? agent : undefined;
|
|
601
|
+
const response = await fetch(url, {
|
|
602
|
+
...(dispatcher ? { dispatcher } : {}),
|
|
603
|
+
method: 'POST',
|
|
604
|
+
body: webStream,
|
|
605
|
+
headers,
|
|
606
|
+
duplex: 'half',
|
|
607
|
+
signal: timeoutMs ? AbortSignal.timeout(timeoutMs) : undefined
|
|
608
|
+
});
|
|
609
|
+
try {
|
|
610
|
+
return (await response.json());
|
|
611
|
+
}
|
|
612
|
+
catch {
|
|
613
|
+
return undefined;
|
|
614
|
+
}
|
|
615
|
+
};
|
|
616
|
+
/**
|
|
617
|
+
* Uploads media to WhatsApp servers.
|
|
618
|
+
*
|
|
619
|
+
* ## Why we have two upload implementations:
|
|
620
|
+
*
|
|
621
|
+
* Node.js's native `fetch` (powered by undici) has a known bug where it buffers
|
|
622
|
+
* the entire request body in memory before sending, even when using streams.
|
|
623
|
+
* This causes memory issues with large files (e.g., 1GB file = 1GB+ memory usage).
|
|
624
|
+
* See: https://github.com/nodejs/undici/issues/4058
|
|
625
|
+
*
|
|
626
|
+
* Other runtimes (Bun, Deno, browsers) correctly stream the request body without
|
|
627
|
+
* buffering, so we can use the web-standard Fetch API there.
|
|
628
|
+
*
|
|
629
|
+
* ## Future considerations:
|
|
630
|
+
* Once the undici bug is fixed, we can simplify this to use only the Fetch API
|
|
631
|
+
* across all runtimes. Monitor the GitHub issue for updates.
|
|
632
|
+
*/
|
|
633
|
+
const uploadMedia = async (params, logger) => {
|
|
634
|
+
if (isNodeRuntime()) {
|
|
635
|
+
logger?.debug('Using Node.js https module for upload (avoids undici buffering bug)');
|
|
636
|
+
return uploadWithNodeHttp(params);
|
|
637
|
+
}
|
|
638
|
+
else {
|
|
639
|
+
logger?.debug('Using web-standard Fetch API for upload');
|
|
640
|
+
return uploadWithFetch(params);
|
|
641
|
+
}
|
|
642
|
+
};
|
|
509
643
|
export const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, options }, refreshMediaConn) => {
|
|
510
644
|
return async (filePath, { mediaType, fileEncSha256B64, timeoutMs }) => {
|
|
511
645
|
// send a query JSON to obtain the url & auth token to upload our media
|
|
@@ -513,41 +647,32 @@ export const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, opt
|
|
|
513
647
|
let urls;
|
|
514
648
|
const hosts = [...customUploadHosts, ...uploadInfo.hosts];
|
|
515
649
|
fileEncSha256B64 = encodeBase64EncodedStringForUpload(fileEncSha256B64);
|
|
650
|
+
// Prepare common headers
|
|
651
|
+
const customHeaders = (() => {
|
|
652
|
+
const hdrs = options?.headers;
|
|
653
|
+
if (!hdrs)
|
|
654
|
+
return {};
|
|
655
|
+
return Array.isArray(hdrs) ? Object.fromEntries(hdrs) : hdrs;
|
|
656
|
+
})();
|
|
657
|
+
const headers = {
|
|
658
|
+
...customHeaders,
|
|
659
|
+
'Content-Type': 'application/octet-stream',
|
|
660
|
+
Origin: DEFAULT_ORIGIN
|
|
661
|
+
};
|
|
516
662
|
for (const { hostname } of hosts) {
|
|
517
663
|
logger.debug(`uploading to "${hostname}"`);
|
|
518
|
-
const auth = encodeURIComponent(uploadInfo.auth);
|
|
664
|
+
const auth = encodeURIComponent(uploadInfo.auth);
|
|
519
665
|
const url = `https://${hostname}${MEDIA_PATH_MAP[mediaType]}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}`;
|
|
520
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
521
666
|
let result;
|
|
522
667
|
try {
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
if (!hdrs)
|
|
532
|
-
return {};
|
|
533
|
-
return Array.isArray(hdrs) ? Object.fromEntries(hdrs) : hdrs;
|
|
534
|
-
})(),
|
|
535
|
-
'Content-Type': 'application/octet-stream',
|
|
536
|
-
Origin: DEFAULT_ORIGIN
|
|
537
|
-
},
|
|
538
|
-
duplex: 'half',
|
|
539
|
-
// Note: custom agents/proxy require undici Agent; omitted here.
|
|
540
|
-
signal: timeoutMs ? AbortSignal.timeout(timeoutMs) : undefined
|
|
541
|
-
});
|
|
542
|
-
let parsed = undefined;
|
|
543
|
-
try {
|
|
544
|
-
parsed = await response.json();
|
|
545
|
-
}
|
|
546
|
-
catch {
|
|
547
|
-
parsed = undefined;
|
|
548
|
-
}
|
|
549
|
-
result = parsed;
|
|
550
|
-
if (result?.url || result?.directPath) {
|
|
668
|
+
result = await uploadMedia({
|
|
669
|
+
url,
|
|
670
|
+
filePath,
|
|
671
|
+
headers,
|
|
672
|
+
timeoutMs,
|
|
673
|
+
agent: fetchAgent
|
|
674
|
+
}, logger);
|
|
675
|
+
if (result?.url || result?.direct_path) {
|
|
551
676
|
urls = {
|
|
552
677
|
mediaUrl: result.url,
|
|
553
678
|
directPath: result.direct_path,
|
|
@@ -579,11 +704,11 @@ const getMediaRetryKey = (mediaKey) => {
|
|
|
579
704
|
/**
|
|
580
705
|
* Generate a binary node that will request the phone to re-upload the media & return the newly uploaded URL
|
|
581
706
|
*/
|
|
582
|
-
export const encryptMediaRetryRequest =
|
|
707
|
+
export const encryptMediaRetryRequest = (key, mediaKey, meId) => {
|
|
583
708
|
const recp = { stanzaId: key.id };
|
|
584
709
|
const recpBuffer = proto.ServerErrorReceipt.encode(recp).finish();
|
|
585
710
|
const iv = Crypto.randomBytes(12);
|
|
586
|
-
const retryKey =
|
|
711
|
+
const retryKey = getMediaRetryKey(mediaKey);
|
|
587
712
|
const ciphertext = aesEncryptGCM(recpBuffer, retryKey, iv, Buffer.from(key.id));
|
|
588
713
|
const req = {
|
|
589
714
|
tag: 'receipt',
|
|
@@ -648,8 +773,8 @@ export const decodeMediaRetryNode = (node) => {
|
|
|
648
773
|
}
|
|
649
774
|
return event;
|
|
650
775
|
};
|
|
651
|
-
export const decryptMediaRetryData =
|
|
652
|
-
const retryKey =
|
|
776
|
+
export const decryptMediaRetryData = ({ ciphertext, iv }, mediaKey, msgId) => {
|
|
777
|
+
const retryKey = getMediaRetryKey(mediaKey);
|
|
653
778
|
const plaintext = aesDecryptGCM(ciphertext, retryKey, iv, Buffer.from(msgId));
|
|
654
779
|
return proto.MediaRetryNotification.decode(plaintext);
|
|
655
780
|
};
|