@crysnovax/baileys 2.5.6 → 2.6.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/README.md +11 -0
- package/README.md[old] +1612 -0
- package/WAProto/index.js +14789 -3578
- package/lib/Defaults/index.js +14 -7
- package/lib/Signal/libsignal.js +40 -18
- package/lib/Socket/business.js +2 -1
- package/lib/Socket/chats.js +266 -92
- package/lib/Socket/chats.js[past] +1213 -0
- package/lib/Socket/communities.js +2 -1
- package/lib/Socket/groups.js +24 -5
- package/lib/Socket/messages-recv.js +617 -322
- package/lib/Socket/messages-send.js +160 -61
- package/lib/Socket/newsletter.js +4 -4
- package/lib/Socket/socket.js +49 -20
- package/lib/Types/{Newsletter.js → Mex.js} +10 -4
- package/lib/Types/State.js +37 -1
- package/lib/Types/index.js +1 -1
- package/lib/Utils/auth-utils.js +13 -1
- package/lib/Utils/chat-utils.js +81 -21
- package/lib/Utils/decode-wa-message.js +35 -1
- package/lib/Utils/index.js +1 -0
- package/lib/Utils/messages-media.js +28 -16
- package/lib/Utils/messages-media.js[past] +842 -0
- package/lib/Utils/messages.js +325 -352
- package/lib/Utils/signal.js +43 -1
- package/lib/Utils/tc-token-utils.js +150 -5
- package/lib/Utils/use-sqlite-auth-state.js +108 -0
- package/lib/WABinary/constants.js +91 -0
- package/package.json +45 -10
package/lib/Types/index.js
CHANGED
|
@@ -3,13 +3,13 @@ export * from './GroupMetadata.js';
|
|
|
3
3
|
export * from './Chat.js';
|
|
4
4
|
export * from './Contact.js';
|
|
5
5
|
export * from './State.js';
|
|
6
|
+
export * from './Mex.js';
|
|
6
7
|
export * from './Message.js';
|
|
7
8
|
export * from './Socket.js';
|
|
8
9
|
export * from './Events.js';
|
|
9
10
|
export * from './Product.js';
|
|
10
11
|
export * from './Call.js';
|
|
11
12
|
export * from './Signal.js';
|
|
12
|
-
export * from './Newsletter.js';
|
|
13
13
|
export var DisconnectReason;
|
|
14
14
|
(function (DisconnectReason) {
|
|
15
15
|
DisconnectReason[DisconnectReason["connectionClosed"] = 428] = "connectionClosed";
|
package/lib/Utils/auth-utils.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import NodeCache from '@cacheable/node-cache';
|
|
2
|
+
import { Boom } from '@hapi/boom';
|
|
2
3
|
import { AsyncLocalStorage } from 'async_hooks';
|
|
3
4
|
import { Mutex } from 'async-mutex';
|
|
4
5
|
import { randomBytes } from 'crypto';
|
|
@@ -264,6 +265,17 @@ export const addTransactionCapability = (state, logger, { maxCommitRetries, dela
|
|
|
264
265
|
}
|
|
265
266
|
};
|
|
266
267
|
};
|
|
268
|
+
/**
|
|
269
|
+
* Returns the authenticated user's JID, or throws a Boom-401 if creds are not yet authenticated.
|
|
270
|
+
* Use this anywhere we'd otherwise reach for `creds.me!.id` to fail fast with a descriptive error.
|
|
271
|
+
*/
|
|
272
|
+
export const assertMeId = (creds) => {
|
|
273
|
+
const id = creds.me?.id;
|
|
274
|
+
if (!id) {
|
|
275
|
+
throw new Boom('Cannot proceed: socket is not authenticated yet (creds.me.id is missing)', { statusCode: 401 });
|
|
276
|
+
}
|
|
277
|
+
return id;
|
|
278
|
+
};
|
|
267
279
|
export const initAuthCreds = () => {
|
|
268
280
|
const identityKey = Curve.generateKeyPair();
|
|
269
281
|
return {
|
|
@@ -286,4 +298,4 @@ export const initAuthCreds = () => {
|
|
|
286
298
|
routingInfo: undefined,
|
|
287
299
|
additionalData: undefined
|
|
288
300
|
};
|
|
289
|
-
};
|
|
301
|
+
};
|
package/lib/Utils/chat-utils.js
CHANGED
|
@@ -38,7 +38,7 @@ const to64BitNetworkOrder = (e) => {
|
|
|
38
38
|
buff.writeUint32BE(e, 4);
|
|
39
39
|
return buff;
|
|
40
40
|
};
|
|
41
|
-
const makeLtHashGenerator = ({ indexValueMap, hash }) => {
|
|
41
|
+
export const makeLtHashGenerator = ({ indexValueMap, hash }) => {
|
|
42
42
|
indexValueMap = { ...indexValueMap };
|
|
43
43
|
const addBuffs = [];
|
|
44
44
|
const subBuffs = [];
|
|
@@ -48,7 +48,10 @@ const makeLtHashGenerator = ({ indexValueMap, hash }) => {
|
|
|
48
48
|
const prevOp = indexValueMap[indexMacBase64];
|
|
49
49
|
if (operation === proto.SyncdMutation.SyncdOperation.REMOVE) {
|
|
50
50
|
if (!prevOp) {
|
|
51
|
-
|
|
51
|
+
// WA Web does not throw here — it logs a warning and skips the subtract.
|
|
52
|
+
// The missing REMOVE will cause an LTHash mismatch, which is handled
|
|
53
|
+
// by the MAC validation layer (snapshot recovery or retry).
|
|
54
|
+
return;
|
|
52
55
|
}
|
|
53
56
|
// remove from index value mac, since this mutation is erased
|
|
54
57
|
delete indexValueMap[indexMacBase64];
|
|
@@ -80,10 +83,33 @@ const generatePatchMac = (snapshotMac, valueMacs, version, type, key) => {
|
|
|
80
83
|
return hmacSign(total, key);
|
|
81
84
|
};
|
|
82
85
|
export const newLTHashState = () => ({ version: 0, hash: Buffer.alloc(128), indexValueMap: {} });
|
|
86
|
+
export const ensureLTHashStateVersion = (state) => {
|
|
87
|
+
if (typeof state.version !== 'number' || isNaN(state.version)) {
|
|
88
|
+
state.version = 0;
|
|
89
|
+
}
|
|
90
|
+
return state;
|
|
91
|
+
};
|
|
92
|
+
export const MAX_SYNC_ATTEMPTS = 2;
|
|
93
|
+
/**
|
|
94
|
+
* Check if an error is a missing app state sync key.
|
|
95
|
+
* WA Web treats these as "Blocked" (waits for key arrival), not fatal.
|
|
96
|
+
* In Baileys we retry with a snapshot which may use a different key.
|
|
97
|
+
*/
|
|
98
|
+
export const isMissingKeyError = (error) => {
|
|
99
|
+
return error?.data?.isMissingKey === true;
|
|
100
|
+
};
|
|
101
|
+
/**
|
|
102
|
+
* Determines if an app state sync error is unrecoverable.
|
|
103
|
+
* TypeError indicates a WASM crash; otherwise we give up after MAX_SYNC_ATTEMPTS.
|
|
104
|
+
* Missing keys are NOT checked here — they are handled separately as "Blocked".
|
|
105
|
+
*/
|
|
106
|
+
export const isAppStateSyncIrrecoverable = (error, attempts) => {
|
|
107
|
+
return attempts >= MAX_SYNC_ATTEMPTS || error?.name === 'TypeError';
|
|
108
|
+
};
|
|
83
109
|
export const encodeSyncdPatch = async ({ type, index, syncAction, apiVersion, operation }, myAppStateKeyId, state, getAppStateSyncKey) => {
|
|
84
110
|
const key = !!myAppStateKeyId ? await getAppStateSyncKey(myAppStateKeyId) : undefined;
|
|
85
111
|
if (!key) {
|
|
86
|
-
throw new Boom(`myAppStateKey ("${myAppStateKeyId}") not present`, {
|
|
112
|
+
throw new Boom(`myAppStateKey ("${myAppStateKeyId}") not present`, { data: { isMissingKey: true } });
|
|
87
113
|
}
|
|
88
114
|
const encKeyId = Buffer.from(myAppStateKeyId, 'base64');
|
|
89
115
|
state = { ...state, indexValueMap: { ...state.indexValueMap } };
|
|
@@ -139,17 +165,36 @@ export const decodeSyncdMutations = async (msgMutations, initialState, getAppSta
|
|
|
139
165
|
// otherwise, if it's only a record -- it'll be a SET mutation
|
|
140
166
|
const operation = 'operation' in msgMutation ? msgMutation.operation : proto.SyncdMutation.SyncdOperation.SET;
|
|
141
167
|
const record = 'record' in msgMutation && !!msgMutation.record ? msgMutation.record : msgMutation;
|
|
142
|
-
|
|
168
|
+
let key;
|
|
169
|
+
try {
|
|
170
|
+
key = await getKey(record.keyId.id);
|
|
171
|
+
}
|
|
172
|
+
catch (err) {
|
|
173
|
+
// Missing-key errors must propagate so the orchestrator can park the
|
|
174
|
+
// collection (Blocked) and retry when APP_STATE_SYNC_KEY_SHARE arrives.
|
|
175
|
+
// Other errors → individual record corruption, skip and keep going.
|
|
176
|
+
if (isMissingKeyError(err))
|
|
177
|
+
throw err;
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
143
180
|
const content = record.value.blob;
|
|
144
181
|
const encContent = content.subarray(0, -32);
|
|
145
182
|
const ogValueMac = content.subarray(-32);
|
|
146
183
|
if (validateMacs) {
|
|
147
184
|
const contentHmac = generateMac(operation, encContent, record.keyId.id, key.valueMacKey);
|
|
148
185
|
if (Buffer.compare(contentHmac, ogValueMac) !== 0) {
|
|
149
|
-
|
|
186
|
+
// HMAC verification failed — skip this record
|
|
187
|
+
continue;
|
|
150
188
|
}
|
|
151
189
|
}
|
|
152
|
-
|
|
190
|
+
let result;
|
|
191
|
+
try {
|
|
192
|
+
result = aesDecrypt(encContent, key.valueEncryptionKey);
|
|
193
|
+
}
|
|
194
|
+
catch {
|
|
195
|
+
// decrypt failed — skip this record instead of aborting
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
153
198
|
const syncAction = proto.SyncActionData.decode(result);
|
|
154
199
|
if (validateMacs) {
|
|
155
200
|
const hmac = hmacSign(syncAction.index, key.indexKey);
|
|
@@ -175,8 +220,7 @@ export const decodeSyncdMutations = async (msgMutations, initialState, getAppSta
|
|
|
175
220
|
const keyEnc = await getAppStateSyncKey(base64Key);
|
|
176
221
|
if (!keyEnc) {
|
|
177
222
|
throw new Boom(`failed to find key "${base64Key}" to decode mutation`, {
|
|
178
|
-
|
|
179
|
-
data: { msgMutations }
|
|
223
|
+
data: { isMissingKey: true, msgMutations }
|
|
180
224
|
});
|
|
181
225
|
}
|
|
182
226
|
const keys = mutationKeys(keyEnc.keyData);
|
|
@@ -189,7 +233,7 @@ export const decodeSyncdPatch = async (msg, name, initialState, getAppStateSyncK
|
|
|
189
233
|
const base64Key = Buffer.from(msg.keyId.id).toString('base64');
|
|
190
234
|
const mainKeyObj = await getAppStateSyncKey(base64Key);
|
|
191
235
|
if (!mainKeyObj) {
|
|
192
|
-
throw new Boom(`failed to find key "${base64Key}" to decode patch`, {
|
|
236
|
+
throw new Boom(`failed to find key "${base64Key}" to decode patch`, { data: { isMissingKey: true, msg } });
|
|
193
237
|
}
|
|
194
238
|
const mainKey = mutationKeys(mainKeyObj.keyData);
|
|
195
239
|
const mutationmacs = msg.mutations.map(mutation => mutation.record.value.blob.slice(-32));
|
|
@@ -250,7 +294,7 @@ export const downloadExternalPatch = async (blob, options) => {
|
|
|
250
294
|
const syncData = proto.SyncdMutations.decode(buffer);
|
|
251
295
|
return syncData;
|
|
252
296
|
};
|
|
253
|
-
export const decodeSyncdSnapshot = async (name, snapshot, getAppStateSyncKey, minimumVersionNumber, validateMacs = true) => {
|
|
297
|
+
export const decodeSyncdSnapshot = async (name, snapshot, getAppStateSyncKey, minimumVersionNumber, validateMacs = true, logger) => {
|
|
254
298
|
const newState = newLTHashState();
|
|
255
299
|
newState.version = toNumber(snapshot.version.version);
|
|
256
300
|
const mutationMap = {};
|
|
@@ -267,12 +311,17 @@ export const decodeSyncdSnapshot = async (name, snapshot, getAppStateSyncKey, mi
|
|
|
267
311
|
const base64Key = Buffer.from(snapshot.keyId.id).toString('base64');
|
|
268
312
|
const keyEnc = await getAppStateSyncKey(base64Key);
|
|
269
313
|
if (!keyEnc) {
|
|
270
|
-
throw new Boom(`failed to find key "${base64Key}" to decode mutation
|
|
314
|
+
throw new Boom(`failed to find key "${base64Key}" to decode mutation`, { data: { isMissingKey: true } });
|
|
271
315
|
}
|
|
272
316
|
const result = mutationKeys(keyEnc.keyData);
|
|
273
317
|
const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, result.snapshotMacKey);
|
|
274
318
|
if (Buffer.compare(snapshot.mac, computedSnapshotMac) !== 0) {
|
|
275
|
-
|
|
319
|
+
// LTHash verification may fail when decodeSyncdMutations skipped undecryptable
|
|
320
|
+
// records (poisoned server-side snapshot); the aggregate client hash diverges
|
|
321
|
+
// from the server-computed mac. Fall through with a warning so the session stays
|
|
322
|
+
// alive with partial state, symmetric to how decodePatches handles its own
|
|
323
|
+
// LTHash mismatch a few lines below.
|
|
324
|
+
logger?.warn({ name, version: newState.version }, 'LTHash verification failed on snapshot, continuing with partial state');
|
|
276
325
|
}
|
|
277
326
|
}
|
|
278
327
|
return {
|
|
@@ -297,24 +346,34 @@ export const decodePatches = async (name, syncds, initial, getAppStateSyncKey, o
|
|
|
297
346
|
const patchVersion = toNumber(version.version);
|
|
298
347
|
newState.version = patchVersion;
|
|
299
348
|
const shouldMutate = typeof minimumVersionNumber === 'undefined' || patchVersion > minimumVersionNumber;
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
349
|
+
let decodeResult;
|
|
350
|
+
try {
|
|
351
|
+
decodeResult = await decodeSyncdPatch(syncd, name, newState, getAppStateSyncKey, shouldMutate
|
|
352
|
+
? mutation => {
|
|
353
|
+
const index = mutation.syncAction.index?.toString();
|
|
354
|
+
mutationMap[index] = mutation;
|
|
355
|
+
}
|
|
356
|
+
: () => { }, validateMacs);
|
|
357
|
+
}
|
|
358
|
+
catch (err) {
|
|
359
|
+
if (isMissingKeyError(err))
|
|
360
|
+
throw err;
|
|
361
|
+
logger?.warn({ name, version: patchVersion, error: err.message }, 'failed to decode patch, skipping');
|
|
362
|
+
continue;
|
|
363
|
+
}
|
|
306
364
|
newState.hash = decodeResult.hash;
|
|
307
365
|
newState.indexValueMap = decodeResult.indexValueMap;
|
|
308
366
|
if (validateMacs) {
|
|
309
367
|
const base64Key = Buffer.from(keyId.id).toString('base64');
|
|
310
368
|
const keyEnc = await getAppStateSyncKey(base64Key);
|
|
311
369
|
if (!keyEnc) {
|
|
312
|
-
throw new Boom(`failed to find key "${base64Key}" to decode mutation
|
|
370
|
+
throw new Boom(`failed to find key "${base64Key}" to decode mutation`, { data: { isMissingKey: true } });
|
|
313
371
|
}
|
|
314
372
|
const result = mutationKeys(keyEnc.keyData);
|
|
315
373
|
const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, result.snapshotMacKey);
|
|
316
374
|
if (Buffer.compare(snapshotMac, computedSnapshotMac) !== 0) {
|
|
317
|
-
|
|
375
|
+
logger?.warn({ name, version: newState.version }, 'LTHash verification failed, skipping remaining patches');
|
|
376
|
+
break;
|
|
318
377
|
}
|
|
319
378
|
}
|
|
320
379
|
// clear memory used up by the mutations
|
|
@@ -779,6 +838,7 @@ export const processSyncAction = (syncAction, ev, me, initialSyncOpts, logger) =
|
|
|
779
838
|
action.lidContactAction.firstName ||
|
|
780
839
|
action.lidContactAction.username ||
|
|
781
840
|
undefined,
|
|
841
|
+
username: action.lidContactAction.username || undefined,
|
|
782
842
|
lid: id,
|
|
783
843
|
phoneNumber: undefined
|
|
784
844
|
}
|
|
@@ -808,4 +868,4 @@ export const processSyncAction = (syncAction, ev, me, initialSyncOpts, logger) =
|
|
|
808
868
|
const chatLastMsgTimestamp = Number(chat?.lastMessageRecvTimestamp || 0);
|
|
809
869
|
return lastMsgTimestamp >= chatLastMsgTimestamp;
|
|
810
870
|
}
|
|
811
|
-
};
|
|
871
|
+
};
|
|
@@ -27,13 +27,16 @@ const storeMappingFromEnvelope = async (stanza, sender, repository, decryptionJi
|
|
|
27
27
|
};
|
|
28
28
|
export const NO_MESSAGE_FOUND_ERROR_TEXT = 'Message absent from node';
|
|
29
29
|
export const MISSING_KEYS_ERROR_TEXT = 'Key used already or never filled';
|
|
30
|
+
export const ACCOUNT_RESTRICTED_TEXT = 'Your account has been restricted';
|
|
30
31
|
// Retry configuration for failed decryption
|
|
31
32
|
export const DECRYPTION_RETRY_CONFIG = {
|
|
32
33
|
maxRetries: 3,
|
|
33
34
|
baseDelayMs: 100,
|
|
34
35
|
sessionRecordErrors: ['No session record', 'SessionError: No session record']
|
|
35
36
|
};
|
|
37
|
+
/** NACK reason codes we send to the server (client → server) */
|
|
36
38
|
export const NACK_REASONS = {
|
|
39
|
+
SenderReachoutTimelocked: 463,
|
|
37
40
|
ParsingError: 487,
|
|
38
41
|
UnrecognizedStanza: 488,
|
|
39
42
|
UnrecognizedStanzaClass: 489,
|
|
@@ -48,6 +51,21 @@ export const NACK_REASONS = {
|
|
|
48
51
|
UnsupportedLIDGroup: 551,
|
|
49
52
|
DBOperationFailed: 552
|
|
50
53
|
};
|
|
54
|
+
/**
|
|
55
|
+
* Server-side error codes returned in ack stanzas (server → client) that we
|
|
56
|
+
* currently have dedicated handlers for. Extend as more handlers are added.
|
|
57
|
+
* Distinct from the client-side NackReason enum (WAWebCreateNackFromStanza).
|
|
58
|
+
*/
|
|
59
|
+
export const SERVER_ERROR_CODES = {
|
|
60
|
+
/**
|
|
61
|
+
* 1:1 message missing privacy token (tctoken). Usually means the account is
|
|
62
|
+
* restricted: WhatsApp blocks starting new chats but preserves existing ones,
|
|
63
|
+
* since established chats already carry a tctoken.
|
|
64
|
+
*/
|
|
65
|
+
MessageAccountRestriction: '463',
|
|
66
|
+
/** Stanza validation failure (SMAX_INVALID) — likely stale device session */
|
|
67
|
+
SmaxInvalid: '479'
|
|
68
|
+
};
|
|
51
69
|
export const extractAddressingContext = (stanza) => {
|
|
52
70
|
let senderAlt;
|
|
53
71
|
let recipientAlt;
|
|
@@ -88,6 +106,12 @@ export function decodeMessageNode(stanza, meId, meLid) {
|
|
|
88
106
|
const from = stanza.attrs.from;
|
|
89
107
|
const participant = stanza.attrs.participant;
|
|
90
108
|
const recipient = stanza.attrs.recipient;
|
|
109
|
+
if (!msgId) {
|
|
110
|
+
throw new Boom('Invalid message stanza: missing id attribute', { data: stanza });
|
|
111
|
+
}
|
|
112
|
+
if (!from) {
|
|
113
|
+
throw new Boom('Invalid message stanza: missing from attribute', { data: stanza });
|
|
114
|
+
}
|
|
91
115
|
const addressingContext = extractAddressingContext(stanza);
|
|
92
116
|
const isMe = (jid) => areJidsSameUser(jid, meId);
|
|
93
117
|
const isMeLid = (jid) => areJidsSameUser(jid, meLid);
|
|
@@ -102,6 +126,12 @@ export function decodeMessageNode(stanza, meId, meLid) {
|
|
|
102
126
|
chatId = recipient;
|
|
103
127
|
}
|
|
104
128
|
else {
|
|
129
|
+
// Peer-routed self stanzas (history sync, app-state sync, etc.) arrive
|
|
130
|
+
// with `from` set to our own device but no `recipient` attribute —
|
|
131
|
+
// still mark as fromMe so self-only protocolMessage handlers run.
|
|
132
|
+
if (isMe(from) || isMeLid(from)) {
|
|
133
|
+
fromMe = true;
|
|
134
|
+
}
|
|
105
135
|
chatId = from;
|
|
106
136
|
}
|
|
107
137
|
msgType = 'chat';
|
|
@@ -148,10 +178,14 @@ export function decodeMessageNode(stanza, meId, meLid) {
|
|
|
148
178
|
const key = {
|
|
149
179
|
remoteJid: chatId,
|
|
150
180
|
remoteJidAlt: !isJidGroup(chatId) ? addressingContext.senderAlt : undefined,
|
|
181
|
+
remoteJidUsername: !isJidGroup(chatId)
|
|
182
|
+
? stanza.attrs.peer_recipient_username || stanza.attrs.recipient_username
|
|
183
|
+
: undefined,
|
|
151
184
|
fromMe,
|
|
152
185
|
id: msgId,
|
|
153
186
|
participant,
|
|
154
187
|
participantAlt: isJidGroup(chatId) ? addressingContext.senderAlt : undefined,
|
|
188
|
+
participantUsername: stanza.attrs.participant ? stanza.attrs.participant_username : undefined,
|
|
155
189
|
addressingMode: addressingContext.addressingMode,
|
|
156
190
|
...(msgType === 'newsletter' && stanza.attrs.server_id ? { server_id: stanza.attrs.server_id } : {})
|
|
157
191
|
};
|
|
@@ -279,4 +313,4 @@ export const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
|
|
|
279
313
|
function isSessionRecordError(error) {
|
|
280
314
|
const errorMessage = error?.message || error?.toString() || '';
|
|
281
315
|
return DECRYPTION_RETRY_CONFIG.sessionRecordErrors.some(errorPattern => errorMessage.includes(errorPattern));
|
|
282
|
-
}
|
|
316
|
+
}
|
package/lib/Utils/index.js
CHANGED
|
@@ -16,6 +16,7 @@ export * from './lt-hash.js';
|
|
|
16
16
|
export * from './auth-utils.js';
|
|
17
17
|
export * from './use-multi-file-auth-state.js';
|
|
18
18
|
export * from './use-single-file-auth-state.js';
|
|
19
|
+
export * from './use-sqlite-auth-state.js';
|
|
19
20
|
export * from './link-preview.js';
|
|
20
21
|
export * from './event-buffer.js';
|
|
21
22
|
export * from './process-message.js';
|
|
@@ -120,10 +120,8 @@ export const extractVideoThumb = async (path, time, size) => {
|
|
|
120
120
|
ffmpeg.stderr.on('data', (chunk) => stderrChunks.push(chunk));
|
|
121
121
|
const [code] = await once(ffmpeg, 'close');
|
|
122
122
|
if (code !== 0) {
|
|
123
|
-
throw new Boom(
|
|
124
|
-
|
|
125
|
-
Buffer.concat(stderrChunks).toString('utf8')
|
|
126
|
-
);
|
|
123
|
+
throw new Boom(`FFmpeg failed (code ${code}):\n` +
|
|
124
|
+
Buffer.concat(stderrChunks).toString('utf8'));
|
|
127
125
|
}
|
|
128
126
|
return buffer;
|
|
129
127
|
};
|
|
@@ -323,7 +321,7 @@ export async function generateThumbnail(file, mediaType, options) {
|
|
|
323
321
|
let originalImageDimensions;
|
|
324
322
|
if (mediaType === 'image') {
|
|
325
323
|
const { buffer, original } = await extractImageThumb(file);
|
|
326
|
-
thumbnail = buffer;
|
|
324
|
+
thumbnail = buffer.toString('base64');
|
|
327
325
|
if (original.width && original.height) {
|
|
328
326
|
originalImageDimensions = {
|
|
329
327
|
width: original.width,
|
|
@@ -333,8 +331,8 @@ export async function generateThumbnail(file, mediaType, options) {
|
|
|
333
331
|
}
|
|
334
332
|
else if (mediaType === 'video') {
|
|
335
333
|
try {
|
|
336
|
-
const
|
|
337
|
-
thumbnail =
|
|
334
|
+
const buff = await extractVideoThumb(file, '00:00:00', { width: 32, height: 32 });
|
|
335
|
+
thumbnail = buff.toString('base64');
|
|
338
336
|
}
|
|
339
337
|
catch (err) {
|
|
340
338
|
options.logger?.debug('could not generate video thumb: ' + err);
|
|
@@ -448,15 +446,27 @@ export const encryptedStream = async (media, mediaType, { logger, saveOriginalFi
|
|
|
448
446
|
throw error;
|
|
449
447
|
}
|
|
450
448
|
};
|
|
451
|
-
const
|
|
449
|
+
export const DEF_MEDIA_HOST = 'mmg.whatsapp.net';
|
|
452
450
|
const AES_CHUNK_SIZE = 16;
|
|
453
451
|
const toSmallestChunkSize = (num) => {
|
|
454
452
|
return Math.floor(num / AES_CHUNK_SIZE) * AES_CHUNK_SIZE;
|
|
455
453
|
};
|
|
456
|
-
export const getUrlFromDirectPath = (directPath) => `https://${
|
|
454
|
+
export const getUrlFromDirectPath = (directPath, host = DEF_MEDIA_HOST) => `https://${host}${directPath}`;
|
|
455
|
+
const extractHost = (url) => {
|
|
456
|
+
if (!url)
|
|
457
|
+
return undefined;
|
|
458
|
+
try {
|
|
459
|
+
return new URL(url).host;
|
|
460
|
+
}
|
|
461
|
+
catch {
|
|
462
|
+
return undefined;
|
|
463
|
+
}
|
|
464
|
+
};
|
|
457
465
|
export const downloadContentFromMessage = async ({ mediaKey, directPath, url }, type, opts = {}) => {
|
|
458
|
-
|
|
459
|
-
|
|
466
|
+
// Fallback host: explicit opt > host parsed from `url` > DEF_MEDIA_HOST.
|
|
467
|
+
// Lets us honor a non-default host carried by the proto without forcing callers to thread it through.
|
|
468
|
+
const fallbackHost = opts.host ?? extractHost(url);
|
|
469
|
+
const downloadUrl = directPath ? getUrlFromDirectPath(directPath, fallbackHost) : url;
|
|
460
470
|
if (!downloadUrl) {
|
|
461
471
|
throw new Boom('No valid media URL or directPath present in message', { statusCode: 400 });
|
|
462
472
|
}
|
|
@@ -516,7 +526,7 @@ export const downloadEncryptedContent = async (downloadUrl, { cipherKey, iv }, {
|
|
|
516
526
|
};
|
|
517
527
|
const output = new Transform({
|
|
518
528
|
transform(chunk, _, callback) {
|
|
519
|
-
let data = Buffer.concat([remainingBytes, chunk]);
|
|
529
|
+
let data = remainingBytes.length ? Buffer.concat([remainingBytes, chunk]) : chunk;
|
|
520
530
|
const decryptLength = toSmallestChunkSize(data.length);
|
|
521
531
|
remainingBytes = data.slice(decryptLength);
|
|
522
532
|
data = data.slice(0, decryptLength);
|
|
@@ -635,8 +645,10 @@ const uploadWithFetch = async ({ url, filePath, headers, timeoutMs, agent }) =>
|
|
|
635
645
|
// Convert Node.js Readable to Web ReadableStream
|
|
636
646
|
const nodeStream = createReadStream(filePath);
|
|
637
647
|
const webStream = Readable.toWeb(nodeStream);
|
|
648
|
+
// Native fetch only accepts Undici-style dispatchers, not generic https Agents.
|
|
649
|
+
const dispatcher = typeof agent?.dispatch === 'function' ? agent : undefined;
|
|
638
650
|
const response = await fetch(url, {
|
|
639
|
-
dispatcher:
|
|
651
|
+
...(dispatcher ? { dispatcher } : {}),
|
|
640
652
|
method: 'POST',
|
|
641
653
|
body: webStream,
|
|
642
654
|
headers,
|
|
@@ -700,9 +712,9 @@ export const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, opt
|
|
|
700
712
|
logger.debug(`uploading to "${hostname}"`);
|
|
701
713
|
const auth = encodeURIComponent(uploadInfo.auth);
|
|
702
714
|
// Lia@Changes 06-02-26 --- Switch media path map for newsletter uploads
|
|
703
|
-
const mediaPathMap = newsletter ? NEWSLETTER_MEDIA_PATH_MAP : MEDIA_PATH_MAP
|
|
715
|
+
const mediaPathMap = newsletter ? NEWSLETTER_MEDIA_PATH_MAP : MEDIA_PATH_MAP;
|
|
704
716
|
// Lia@Changes 20-03-26 --- Add server thumb for newsletter media
|
|
705
|
-
const serverThumb = newsletter ? '&server_thumb_gen=1' : ''
|
|
717
|
+
const serverThumb = newsletter ? '&server_thumb_gen=1' : '';
|
|
706
718
|
const url = `https://${hostname}${mediaPathMap[mediaType]}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}${serverThumb}`;
|
|
707
719
|
let result;
|
|
708
720
|
try {
|
|
@@ -827,4 +839,4 @@ const MEDIA_RETRY_STATUS_MAP = {
|
|
|
827
839
|
[proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
|
|
828
840
|
[proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
|
|
829
841
|
[proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418
|
|
830
|
-
};
|
|
842
|
+
};
|