sanka-baileyss 2.4.7 → 2.4.9

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 CHANGED
@@ -3,15 +3,15 @@
3
3
  <div align="center">
4
4
 
5
5
  <img src="https://files.catbox.moe/clzacq.jpg" alt="Header Image" width="100%"/>
6
-
6
+ <!-- https://files.catbox.moe/ibob7z.png -->
7
7
  <br/>
8
8
 
9
9
  <!-- WhatsApp Links -->
10
10
  <p>
11
- <a href="https://whatsapp.com/channel/0029Vb054T9C1FuLUKkFy236">
11
+ <a href="https://whatsapp.com/channel/0029VbBv5edGk1Fo8WbsAK1V">
12
12
  <img src="https://img.shields.io/badge/WhatsApp-Channel-brightgreen" alt="WA Channel"/>
13
13
  </a>
14
- <a href="https://wa.me/6282375165100">
14
+ <a href="https://wa.me/message/PXN6UYNCVLO2L1">
15
15
  <img src="https://img.shields.io/badge/Owner-WA-green" alt="WA Owner"/>
16
16
  </a>
17
17
  </p>
@@ -234,7 +234,6 @@ WhatsApp provides a multi-device API that allows Baileys to be authenticated as
234
234
  import makeWASocket from 'Sanka-Baileyss'
235
235
 
236
236
  const sanka = makeWASocket({
237
- // can provide additional config here
238
237
  browser: Browsers.ubuntu('My App'),
239
238
  printQRInTerminal: true
240
239
  })
@@ -254,8 +253,7 @@ The phone number can't have `+` or `()` or `-`, only numbers, you must provide c
254
253
  import makeWASocket from 'Sanka-Baileyss'
255
254
 
256
255
  const sanka = makeWASocket({
257
- // can provide additional config here
258
- printQRInTerminal: false //need to be false
256
+ printQRInTerminal: false
259
257
  })
260
258
 
261
259
  if (!sanka.authState.creds.registered) {
@@ -37,12 +37,18 @@ class GroupCipher {
37
37
  return await this.queueJob(async () => {
38
38
  const record = await this.senderKeyStore.loadSenderKey(this.senderKeyName);
39
39
  if (!record) {
40
+ console.error('[GroupCipher] No SenderKeyRecord found for:', this.senderKeyName.toString());
40
41
  throw new Error('No SenderKeyRecord found for decryption');
41
42
  }
42
43
  const senderKeyMessage = new sender_key_message_1.SenderKeyMessage(null, null, null, null, senderKeyMessageBytes);
43
44
  const senderKeyState = record.getSenderKeyState(senderKeyMessage.getKeyId());
44
45
  if (!senderKeyState) {
45
- throw new Error('No session found to decrypt message');
46
+ console.error('[GroupCipher] No session state found for:', {
47
+ senderKeyName: this.senderKeyName.toString(),
48
+ keyId: senderKeyMessage.getKeyId(),
49
+ availableStates: record.getSenderKeyStates ? record.getSenderKeyStates().length : 'unknown'
50
+ });
51
+ throw new Error(`No session found to decrypt message from ${this.senderKeyName.toString()} with keyId ${senderKeyMessage.getKeyId()}`);
46
52
  }
47
53
  senderKeyMessage.verifySignature(senderKeyState.getSigningKeyPublic());
48
54
  const senderKey = this.getSenderKey(senderKeyState, senderKeyMessage.getIteration());
@@ -5,7 +5,6 @@ const _queueAsyncBuckets = new Map();
5
5
  const _gcLimit = 10000;
6
6
  async function _asyncQueueExecutor(queue, cleanup) {
7
7
  let offt = 0;
8
- // eslint-disable-next-line no-constant-condition
9
8
  while (true) {
10
9
  const limit = Math.min(queue.length, _gcLimit);
11
10
  for (let i = offt; i < limit; i++) {
@@ -33,7 +32,6 @@ async function _asyncQueueExecutor(queue, cleanup) {
33
32
  cleanup();
34
33
  }
35
34
  function queueJob(bucket, awaitable) {
36
- // Skip name assignment since it's readonly in strict mode
37
35
  if (typeof bucket !== 'string') {
38
36
  console.warn('Unhandled bucket type (for naming):', typeof bucket, bucket);
39
37
  }
@@ -1,22 +1,22 @@
1
1
  "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function (o, m, k, k2) {
3
3
  if (k2 === undefined) k2 = k;
4
4
  var desc = Object.getOwnPropertyDescriptor(m, k);
5
5
  if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
6
+ desc = { enumerable: true, get: function () { return m[k]; } };
7
7
  }
8
8
  Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
9
+ }) : (function (o, m, k, k2) {
10
10
  if (k2 === undefined) k2 = k;
11
11
  o[k2] = m[k];
12
12
  }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function (o, v) {
14
14
  Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
15
+ }) : function (o, v) {
16
16
  o["default"] = v;
17
17
  });
18
18
  var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
19
+ var ownKeys = function (o) {
20
20
  ownKeys = Object.getOwnPropertyNames || function (o) {
21
21
  var ar = [];
22
22
  for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
@@ -155,6 +155,7 @@ function signalStorage({ creds, keys }) {
155
155
  if (key) {
156
156
  return sender_key_record_1.SenderKeyRecord.deserialize(key);
157
157
  }
158
+ console.warn('[libsignal] No sender key found for:', keyId, '- returning empty SenderKeyRecord');
158
159
  return new sender_key_record_1.SenderKeyRecord();
159
160
  },
160
161
  storeSenderKey: async (senderKeyName, key) => {
@@ -180,7 +180,6 @@ const makeBusinessSocket = (config) => {
180
180
  return (0, business_1.parseProductNode)(productNode);
181
181
  };
182
182
  const productCreate = async (create) => {
183
- // ensure isHidden is defined
184
183
  create.isHidden = !!create.isHidden;
185
184
  create = await (0, business_1.uploadingNecessaryImagesOfProduct)(create, waUploadToServer);
186
185
  const createNode = (0, business_1.toProductNode)(undefined, create);
@@ -321,7 +321,7 @@ const makeChatsSocket = (config) => {
321
321
  throw new boom_1.Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
322
322
  }
323
323
  if ((0, WABinary_1.jidNormalizedUser)(jid) !== (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id)) {
324
- targetJid = (0, WABinary_1.jidNormalizedUser)(jid); // in case it is someone other than us
324
+ targetJid = (0, WABinary_1.jidNormalizedUser)(jid);
325
325
  }
326
326
  const { img } = await (0, Utils_1.generateProfilePicture)(content);
327
327
  await query({
@@ -348,7 +348,7 @@ const makeChatsSocket = (config) => {
348
348
  throw new boom_1.Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
349
349
  }
350
350
  if ((0, WABinary_1.jidNormalizedUser)(jid) !== (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id)) {
351
- targetJid = (0, WABinary_1.jidNormalizedUser)(jid); // in case it is someone other than us
351
+ targetJid = (0, WABinary_1.jidNormalizedUser)(jid);
352
352
  }
353
353
  await query({
354
354
  tag: 'iq',
@@ -442,18 +442,12 @@ const makeChatsSocket = (config) => {
442
442
  };
443
443
  };
444
444
  const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
445
- // we use this to determine which events to fire
446
- // otherwise when we resync from scratch -- all notifications will fire
447
445
  const initialVersionMap = {};
448
446
  const globalMutationMap = {};
449
447
  await authState.keys.transaction(async () => {
450
448
  var _a;
451
449
  const collectionsToHandle = new Set(collections);
452
- // in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
453
450
  const attemptsMap = {};
454
- // keep executing till all collections are done
455
- // sometimes a single patch request will not return all the patches (God knows why)
456
- // so we fetch till they're all done (this is determined by the "has_more_patches" flag)
457
451
  while (collectionsToHandle.size) {
458
452
  const states = {};
459
453
  const nodes = [];
@@ -475,7 +469,6 @@ const makeChatsSocket = (config) => {
475
469
  attrs: {
476
470
  name,
477
471
  version: state.version.toString(),
478
- // return snapshot if being synced from scratch
479
472
  'return_snapshot': (!state.version).toString()
480
473
  }
481
474
  });
@@ -495,7 +488,7 @@ const makeChatsSocket = (config) => {
495
488
  }
496
489
  ]
497
490
  });
498
- // extract from binary node
491
+
499
492
  const decoded = await (0, Utils_1.extractSyncdPatches)(result, config === null || config === void 0 ? void 0 : config.options);
500
493
  for (const key in decoded) {
501
494
  const name = key;
@@ -510,7 +503,7 @@ const makeChatsSocket = (config) => {
510
503
  [name]: newState
511
504
  } });
512
505
  }
513
- // only process if there are syncd patches
506
+
514
507
  if (patches.length) {
515
508
  const { state: newState, mutationMap } = await (0, Utils_1.decodePatches)(name, patches, states[name], getAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch);
516
509
  await authState.keys.set({ 'app-state-sync-version': {
@@ -523,13 +516,11 @@ const makeChatsSocket = (config) => {
523
516
  if (hasMorePatches) {
524
517
  logger.info(`${name} has more patches...`);
525
518
  }
526
- else { // collection is done with sync
519
+ else {
527
520
  collectionsToHandle.delete(name);
528
521
  }
529
522
  }
530
523
  catch (error) {
531
- // if retry attempts overshoot
532
- // or key not found
533
524
  const isIrrecoverableError = attemptsMap[name] >= MAX_SYNC_ATTEMPTS ||
534
525
  ((_a = error.output) === null || _a === void 0 ? void 0 : _a.statusCode) === 404 ||
535
526
  error.name === 'TypeError';
@@ -537,10 +528,8 @@ const makeChatsSocket = (config) => {
537
528
  await authState.keys.set({ 'app-state-sync-version': {
538
529
  [name]: null
539
530
  } });
540
- // increment number of retries
541
531
  attemptsMap[name] = (attemptsMap[name] || 0) + 1;
542
532
  if (isIrrecoverableError) {
543
- // stop retrying
544
533
  collectionsToHandle.delete(name);
545
534
  }
546
535
  }
@@ -837,7 +826,6 @@ const makeChatsSocket = (config) => {
837
826
  if (!msg.key.fromMe) {
838
827
  ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }]);
839
828
  }
840
- // update our pushname too
841
829
  if (msg.key.fromMe && msg.pushName && ((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.name) !== msg.pushName) {
842
830
  ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } });
843
831
  }
@@ -904,7 +892,6 @@ const makeChatsSocket = (config) => {
904
892
  }
905
893
  break;
906
894
  case 'groups':
907
- // handled in groups.ts
908
895
  break;
909
896
  default:
910
897
  logger.info({ node }, 'received unknown sync');
@@ -922,9 +909,6 @@ const makeChatsSocket = (config) => {
922
909
  .catch(error => onUnexpectedError(error, 'presence update requests'));
923
910
  }
924
911
  if (receivedPendingNotifications) {
925
- // if we don't have the app state key
926
- // we keep buffering events until we finally have
927
- // the key and can sync the messages
928
912
  if (!((_a = authState.creds) === null || _a === void 0 ? void 0 : _a.myAppStateKeyId) && !config.mobile) {
929
913
  ev.buffer();
930
914
  needToFlushWithAppStateSync = true;
@@ -203,10 +203,7 @@ const makeGroupsSocket = (config) => {
203
203
  admin: key.remoteJid
204
204
  }
205
205
  }]);
206
- // if we have the full message key
207
- // update the invite message to be expired
208
206
  if (key.id) {
209
- // create new invite message that is expired
210
207
  inviteMessage = WAProto_1.proto.Message.GroupInviteMessage.fromObject(inviteMessage);
211
208
  inviteMessage.inviteExpiration = 0;
212
209
  inviteMessage.inviteCode = '';
@@ -221,7 +218,6 @@ const makeGroupsSocket = (config) => {
221
218
  }
222
219
  ]);
223
220
  }
224
- // generate the group add message
225
221
  await upsertMessage({
226
222
  key: {
227
223
  remoteJid: inviteMessage.groupJid,
@@ -18,15 +18,15 @@ const messages_send_1 = require("./messages-send");
18
18
  const makeMessagesRecvSocket = (config) => {
19
19
  const {
20
20
  logger,
21
- retryRequestDelayMs,
21
+ retryRequestDelayMs,
22
22
  maxMsgRetryCount,
23
- getMessage,
24
- shouldIgnoreJid
23
+ getMessage,
24
+ shouldIgnoreJid
25
25
  } = config;
26
26
  const sock = (0, messages_send_1.makeMessagesSocket)(config);
27
- const {
27
+ const {
28
28
  ev,
29
- authState,
29
+ authState,
30
30
  ws,
31
31
  processingMutex,
32
32
  signalRepository,
@@ -34,14 +34,14 @@ const makeMessagesRecvSocket = (config) => {
34
34
  upsertMessage,
35
35
  resyncAppState,
36
36
  groupMetadata,
37
- onUnexpectedError,
37
+ onUnexpectedError,
38
38
  assertSessions,
39
39
  sendNode,
40
40
  relayMessage,
41
41
  sendReceipt,
42
42
  uploadPreKeys,
43
43
  createParticipantNodes,
44
- getUSyncDevices,
44
+ getUSyncDevices,
45
45
  sendPeerDataOperationMessage
46
46
  } = sock;
47
47
  /** this mutex ensures that each retryRequest will wait for the previous one to finish */
@@ -83,12 +83,13 @@ const makeMessagesRecvSocket = (config) => {
83
83
  if (tag === 'message' && (0, WABinary_1.getBinaryNodeChild)({ tag, attrs, content }, 'unavailable')) {
84
84
  stanza.attrs.from = authState.creds.me.id;
85
85
  }
86
- logger.debug({
86
+ logger.debug({
87
87
  recv: {
88
88
  tag,
89
- attrs
89
+ attrs
90
90
  },
91
- sent: stanza.attrs }, 'sent ack');
91
+ sent: stanza.attrs
92
+ }, 'sent ack');
92
93
  await sendNode(stanza);
93
94
  };
94
95
  const offerCall = async (toJid, isVideo = false) => {
@@ -105,8 +106,8 @@ const makeMessagesRecvSocket = (config) => {
105
106
  tag: 'audio',
106
107
  attrs: {
107
108
  enc: 'opus',
108
- rate: '8000'
109
- }, content: undefined
109
+ rate: '8000'
110
+ }, content: undefined
110
111
  });
111
112
  if (isVideo) {
112
113
  offerContent.push({
@@ -125,18 +126,19 @@ const makeMessagesRecvSocket = (config) => {
125
126
  tag: 'net',
126
127
  attrs: {
127
128
  medium: '3'
128
- }, content: undefined
129
+ }, content: undefined
129
130
  });
130
- offerContent.push({
131
+ offerContent.push({
131
132
  tag: 'capability',
132
133
  attrs: {
133
134
  ver: '1'
134
- }, content: new Uint8Array([1, 4, 255, 131, 207, 4]) });
135
+ }, content: new Uint8Array([1, 4, 255, 131, 207, 4])
136
+ });
135
137
  offerContent.push({
136
138
  tag: 'encopt',
137
- attrs: {
139
+ attrs: {
138
140
  keygen: '2'
139
- }, content: undefined
141
+ }, content: undefined
140
142
  })
141
143
  const encKey = (0, crypto_1.randomBytes)(32);
142
144
  const devices = (await getUSyncDevices([toJid], true, false)).map(({ user, device }) => (0, WABinary_1.jidEncode)(user, 's.whatsapp.net', device));
@@ -160,13 +162,13 @@ const makeMessagesRecvSocket = (config) => {
160
162
  to: toJid,
161
163
  },
162
164
  content: [{
163
- tag: 'offer',
164
- attrs: {
165
- 'call-id': callId,
166
- 'call-creator': authState.creds.me.id,
167
- },
168
- content: offerContent,
169
- }],
165
+ tag: 'offer',
166
+ attrs: {
167
+ 'call-id': callId,
168
+ 'call-creator': authState.creds.me.id,
169
+ },
170
+ content: offerContent,
171
+ }],
170
172
  });
171
173
  await query(stanza);
172
174
  return {
@@ -183,14 +185,14 @@ const makeMessagesRecvSocket = (config) => {
183
185
  to: callFrom,
184
186
  },
185
187
  content: [{
186
- tag: 'reject',
187
- attrs: {
188
- 'call-id': callId,
189
- 'call-creator': callFrom,
190
- count: '0',
191
- },
192
- content: undefined,
193
- }],
188
+ tag: 'reject',
189
+ attrs: {
190
+ 'call-id': callId,
191
+ 'call-creator': callFrom,
192
+ count: '0',
193
+ },
194
+ content: undefined,
195
+ }],
194
196
  });
195
197
  await query(stanza);
196
198
  };
@@ -209,7 +211,6 @@ const makeMessagesRecvSocket = (config) => {
209
211
  msgRetryCache.set(key, retryCount);
210
212
  const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds;
211
213
  if (retryCount === 1) {
212
- //request a resend via phone
213
214
  const msgId = await requestPlaceholderResend(msgKey);
214
215
  logger.debug(`sendRetryRequest: requested placeholder resend for message ${msgId}`);
215
216
  }
@@ -282,8 +283,6 @@ const makeMessagesRecvSocket = (config) => {
282
283
  const identityNode = (0, WABinary_1.getBinaryNodeChild)(node, 'identity');
283
284
  if (identityNode) {
284
285
  logger.info({ jid: from }, 'identity changed');
285
- // not handling right now
286
- // signal will override new identity anyway
287
286
  }
288
287
  else {
289
288
  logger.info({ node }, 'unknown encrypt notification');
@@ -300,14 +299,14 @@ const makeMessagesRecvSocket = (config) => {
300
299
  msg.messageStubParameters = [metadata.subject];
301
300
  msg.key = { participant: metadata.owner };
302
301
  ev.emit('chats.upsert', [{
303
- id: metadata.id,
304
- name: metadata.subject,
305
- conversationTimestamp: metadata.creation,
306
- }]);
302
+ id: metadata.id,
303
+ name: metadata.subject,
304
+ conversationTimestamp: metadata.creation,
305
+ }]);
307
306
  ev.emit('groups.upsert', [{
308
- ...metadata,
309
- author: participant
310
- }]);
307
+ ...metadata,
308
+ author: participant
309
+ }]);
311
310
  break;
312
311
  case 'ephemeral':
313
312
  case 'not_ephemeral':
@@ -332,8 +331,6 @@ const makeMessagesRecvSocket = (config) => {
332
331
  msg.messageStubType = Types_1.WAMessageStubType[stubType];
333
332
  const participants = (0, WABinary_1.getBinaryNodeChildren)(child, 'participant').map(p => p.attrs.jid);
334
333
  if (participants.length === 1 &&
335
- // if recv. "remove" message and sender removed themselves
336
- // mark as left
337
334
  (0, WABinary_1.areJidsSameUser)(participants[0], participant) &&
338
335
  child.tag === 'remove') {
339
336
  msg.messageStubType = Types_1.WAMessageStubType.GROUP_PARTICIPANT_LEAVE;
@@ -489,9 +486,9 @@ const makeMessagesRecvSocket = (config) => {
489
486
  const setPicture = (0, WABinary_1.getBinaryNodeChild)(node, 'set');
490
487
  const delPicture = (0, WABinary_1.getBinaryNodeChild)(node, 'delete');
491
488
  ev.emit('contacts.update', [{
492
- id: from || ((_b = (_a = (setPicture || delPicture)) === null || _a === void 0 ? void 0 : _a.attrs) === null || _b === void 0 ? void 0 : _b.hash) || '',
493
- imgUrl: setPicture ? 'changed' : 'removed'
494
- }]);
489
+ id: from || ((_b = (_a = (setPicture || delPicture)) === null || _a === void 0 ? void 0 : _a.attrs) === null || _b === void 0 ? void 0 : _b.hash) || '',
490
+ imgUrl: setPicture ? 'changed' : 'removed'
491
+ }]);
495
492
  if ((0, WABinary_1.isJidGroup)(from)) {
496
493
  const node = setPicture || delPicture;
497
494
  result.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_ICON;
@@ -617,17 +614,24 @@ const makeMessagesRecvSocket = (config) => {
617
614
  };
618
615
  const sendMessagesAgain = async (key, ids, retryNode) => {
619
616
  var _a;
620
- // todo: implement a cache to store the last 256 sent messages (copy whatsmeow)
621
617
  const msgs = await Promise.all(ids.map(id => getMessage({ ...key, id })));
622
618
  const remoteJid = key.remoteJid;
623
619
  const participant = key.participant || remoteJid;
624
- // if it's the primary jid sending the request
625
- // just re-send the message to everyone
626
- // prevents the first message decryption failure
627
620
  const sendToAll = !((_a = (0, WABinary_1.jidDecode)(participant)) === null || _a === void 0 ? void 0 : _a.device);
628
621
  await assertSessions([participant], true);
629
622
  if ((0, WABinary_1.isJidGroup)(remoteJid)) {
630
- await authState.keys.set({ 'sender-key-memory': { [remoteJid]: null } });
623
+ // Instead of clearing entire group sender-key-memory, only clear specific participant's key
624
+ const senderKeyName = `${remoteJid}::${participant}`;
625
+ logger.debug({ remoteJid, participant, senderKeyName }, 'clearing sender key for specific participant on retry');
626
+ await authState.keys.set({ 'sender-key': { [senderKeyName]: null } });
627
+
628
+ // Also update sender-key-memory to remove this specific participant
629
+ const result = await authState.keys.get('sender-key-memory', [remoteJid]);
630
+ const senderKeyMap = result[remoteJid] || {};
631
+ if (senderKeyMap[participant]) {
632
+ delete senderKeyMap[participant];
633
+ await authState.keys.set({ 'sender-key-memory': { [remoteJid]: senderKeyMap } });
634
+ }
631
635
  }
632
636
  logger.debug({ participant, sendToAll }, 'forced new session for retry recp');
633
637
  for (const [i, msg] of msgs.entries()) {
@@ -679,9 +683,7 @@ const makeMessagesRecvSocket = (config) => {
679
683
  const status = (0, Utils_1.getStatusFromReceiptType)(attrs.type);
680
684
  if (typeof status !== 'undefined' &&
681
685
  (
682
- // basically, we only want to know when a message from us has been delivered to/read by the other person
683
- // or another device of ours has read some messages
684
- status >= WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK ||
686
+ status >= WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK ||
685
687
  !isNodeFromMe)) {
686
688
  if ((0, WABinary_1.isJidGroup)(remoteJid) || (0, WABinary_1.isJidStatusBroadcast)(remoteJid)) {
687
689
  if (attrs.participant) {
@@ -703,7 +705,6 @@ const makeMessagesRecvSocket = (config) => {
703
705
  }
704
706
  }
705
707
  if (attrs.type === 'retry') {
706
- // correctly set who is asking for the retry
707
708
  key.participant = key.participant || attrs.from;
708
709
  const retryNode = (0, WABinary_1.getBinaryNodeChild)(node, 'retry');
709
710
  if (willSendMessageAgain(ids[0], key.participant)) {
@@ -772,7 +773,6 @@ const makeMessagesRecvSocket = (config) => {
772
773
  return;
773
774
  }
774
775
  const encNode = (0, WABinary_1.getBinaryNodeChild)(node, 'enc');
775
- // TODO: temporary fix for crashes and issues resulting of failed msmsg decryption
776
776
  if (encNode && encNode.attrs.type === 'msmsg') {
777
777
  logger.debug({ key: node.attrs.key }, 'ignored msmsg');
778
778
  await sendMessageAck(node);
@@ -844,12 +844,11 @@ const makeMessagesRecvSocket = (config) => {
844
844
  msg.key.remoteJid = node.attrs.sender_pn || node.attrs.peer_recipient_pn;
845
845
  }
846
846
  let participant = msg.key.participant;
847
- if (category === 'peer') { // special peer message
847
+ if (category === 'peer') {
848
848
  type = 'peer_msg';
849
849
  }
850
- else if (msg.key.fromMe) { // message was sent by us from a different device
850
+ else if (msg.key.fromMe) {
851
851
  type = 'sender';
852
- // need to specially handle this case
853
852
  if ((0, WABinary_1.isJidUser)(msg.key.remoteJid)) {
854
853
  participant = author;
855
854
  }
@@ -858,7 +857,6 @@ const makeMessagesRecvSocket = (config) => {
858
857
  type = 'inactive';
859
858
  }
860
859
  await sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type);
861
- // send ack for history message
862
860
  const isAnyHistoryMsg = (0, Utils_1.getHistoryMsg)(msg.message);
863
861
  if (isAnyHistoryMsg) {
864
862
  const jid = (0, WABinary_1.jidNormalizedUser)(msg.key.remoteJid);
@@ -911,8 +909,8 @@ const makeMessagesRecvSocket = (config) => {
911
909
  }
912
910
  const pdoMessage = {
913
911
  placeholderMessageResendRequest: [{
914
- messageKey
915
- }],
912
+ messageKey
913
+ }],
916
914
  peerDataOperationRequestType: WAProto_1.proto.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND
917
915
  };
918
916
  setTimeout(() => {
@@ -15,7 +15,7 @@ const link_preview_1 = require("../Utils/link-preview");
15
15
  const WABinary_1 = require("../WABinary");
16
16
  const newsletter_1 = require("./newsletter");
17
17
  const WAUSync_1 = require("../WAUSync")
18
- const sanka = require('./dugong');
18
+ const sanka = require('./sanka');
19
19
  var ListType = WAProto_1.proto.Message.ListMessage.ListType;
20
20
  const makeMessagesSocket = (config) => {
21
21
  const {
@@ -128,7 +128,6 @@ const makeMessagesSocket = (config) => {
128
128
  /** Bulk read messages. Keys can be from different chats & participants */
129
129
  const readMessages = async (keys) => {
130
130
  const privacySettings = await fetchPrivacySettings();
131
- // based on privacy settings, we have to change the read type
132
131
  const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
133
132
  await sendReceipts(keys, readType);
134
133
  };
@@ -258,7 +257,6 @@ const makeMessagesSocket = (config) => {
258
257
  const msgId = await relayMessage(meJid, protocolMessage, {
259
258
  additionalAttributes: {
260
259
  category: 'peer',
261
- // eslint-disable-next-line camelcase
262
260
  push_priority: 'high_force',
263
261
  },
264
262
  });
@@ -319,9 +317,6 @@ const makeMessagesSocket = (config) => {
319
317
  const messages = Utils_1.normalizeMessageContent(message)
320
318
  const buttonType = getButtonType(messages);
321
319
  if (participant) {
322
- // when the retry request is not for a group
323
- // only send to the specific device that asked for a retry
324
- // otherwise the message is sent out to every device that should be a recipient
325
320
  if (!isGroup && !isStatus) {
326
321
  additionalAttributes = { ...additionalAttributes, 'device_fanout': 'false' };
327
322
  }
@@ -401,12 +396,9 @@ const makeMessagesSocket = (config) => {
401
396
  const jid = WABinary_1.jidEncode(user, (groupData === null || groupData === void 0 ? void 0 : groupData.addressingMode) === 'lid' ? 'lid' : 's.whatsapp.net', device);
402
397
  if (!senderKeyMap[jid] || !!participant) {
403
398
  senderKeyJids.push(jid);
404
- // store that this person has had the sender keys sent to them
405
399
  senderKeyMap[jid] = true;
406
400
  }
407
401
  }
408
- // if there are some participants with whom the session has not been established
409
- // if there are, we re-send the senderkey
410
402
  if (senderKeyJids.length) {
411
403
  logger.debug({ senderKeyJids }, 'sending new sender key');
412
404
  const senderKeyMsg = {
@@ -494,7 +486,7 @@ const makeMessagesSocket = (config) => {
494
486
  const peerNode = participants[0]?.content?.[0]
495
487
 
496
488
  if (peerNode) {
497
- binaryNodeContent.push(peerNode) // push only enc
489
+ binaryNodeContent.push(peerNode)
498
490
  }
499
491
  }
500
492
 
@@ -516,9 +508,6 @@ const makeMessagesSocket = (config) => {
516
508
  },
517
509
  content: binaryNodeContent
518
510
  }
519
- // if the participant to send to is explicitly specified (generally retry recp)
520
- // ensure the message is only sent to that person
521
- // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
522
511
  if (participant) {
523
512
  if (WABinary_1.isJidGroup(destinationJid)) {
524
513
  stanza.attrs.to = destinationJid;
@@ -50,7 +50,6 @@ exports.makeRegistrationSocket = makeRegistrationSocket;
50
50
  function convertBufferToUrlHex(buffer) {
51
51
  var id = '';
52
52
  buffer.forEach((x) => {
53
- // encode random identity_id buffer as percentage url encoding
54
53
  id += `%${x.toString(16).padStart(2, '0').toLowerCase()}`;
55
54
  });
56
55
  return id;
@@ -1,4 +1,3 @@
1
- // dugong.d.ts
2
1
  import { proto } from '../../WAProto';
3
2
 
4
3
  declare namespace sanka {
@@ -113,7 +113,7 @@ exports.default = (config) => {
113
113
  const { user } = (0, WABinary_1.jidDecode)(contactId);
114
114
  return [contactId, ((0, Utils_1.md5)(Buffer.from(user + 'WA_ADD_NOTIF', 'utf8'))).toString('base64').slice(0, 3)];
115
115
  });
116
- contact = contacts[((_a = contactHashes.find(([, b]) => b === update.id)) === null || _a === void 0 ? void 0 : _a[0]) || '']; // find contact by attrs.hash, when user is not saved as a contact
116
+ contact = contacts[((_a = contactHashes.find(([, b]) => b === update.id)) === null || _a === void 0 ? void 0 : _a[0]) || ''];
117
117
  }
118
118
  if (contact) {
119
119
  if (update.imgUrl === 'changed') {
@@ -150,7 +150,6 @@ exports.default = (config) => {
150
150
  if (label.deleted) {
151
151
  return labels.deleteById(label.id);
152
152
  }
153
- // WhatsApp can store only up to 20 labels
154
153
  if (labels.count() < 20) {
155
154
  return labels.upsertById(label.id, label);
156
155
  }
@@ -78,8 +78,6 @@ exports.makeCacheableSignalKeyStore = makeCacheableSignalKeyStore;
78
78
  * @returns SignalKeyStore with transaction capability
79
79
  */
80
80
  const addTransactionCapability = (state, logger, { maxCommitRetries, delayBetweenTriesMs }) => {
81
- // number of queries made to the DB during the transaction
82
- // only there for logging purposes
83
81
  let dbQueriesInTransaction = 0;
84
82
  let transactionCache = {};
85
83
  let mutations = {};
@@ -91,7 +89,6 @@ const addTransactionCapability = (state, logger, { maxCommitRetries, delayBetwee
91
89
  const idsRequiringFetch = dict
92
90
  ? ids.filter(item => typeof dict[item] === 'undefined')
93
91
  : ids;
94
- // only fetch if there are any items to fetch
95
92
  if (idsRequiringFetch.length) {
96
93
  dbQueriesInTransaction += 1;
97
94
  const result = await state.get(type, idsRequiringFetch);
@@ -134,12 +131,9 @@ const addTransactionCapability = (state, logger, { maxCommitRetries, delayBetwee
134
131
  }
135
132
  try {
136
133
  result = await work();
137
- // commit if this is the outermost transaction
138
134
  if (transactionsInProgress === 1) {
139
135
  if (Object.keys(mutations).length) {
140
136
  logger.trace('committing transaction');
141
- // retry mechanism to ensure we've some recovery
142
- // in case a transaction fails in the first attempt
143
137
  let tries = maxCommitRetries;
144
138
  while (tries) {
145
139
  tries -= 1;
@@ -191,7 +185,6 @@ const initAuthCreds = () => {
191
185
  accountSettings: {
192
186
  unarchiveChats: false
193
187
  },
194
- // mobile creds
195
188
  deviceId: Buffer.from((0, uuid_1.v4)().replace(/-/g, ''), 'hex').toString('base64url'),
196
189
  phoneId: (0, uuid_1.v4)(),
197
190
  identityId: (0, crypto_1.randomBytes)(20),
@@ -17,9 +17,7 @@ const make_mutex_1 = require("./make-mutex");
17
17
  */
18
18
  const captureEventStream = (ev, filename) => {
19
19
  const oldEmit = ev.emit;
20
- // write mutex so data is appended in order
21
20
  const writeMutex = (0, make_mutex_1.makeMutex)();
22
- // monkey patch eventemitter to capture all events
23
21
  ev.emit = function (...args) {
24
22
  const content = JSON.stringify({ timestamp: Date.now(), event: args[0], data: args[1] }) + '\n';
25
23
  const result = oldEmit.apply(ev, args);
@@ -44,8 +42,6 @@ const readAndEmitEventStream = (filename, delayIntervalMs = 0) => {
44
42
  input: fileStream,
45
43
  crlfDelay: Infinity
46
44
  });
47
- // Note: we use the crlfDelay option to recognize all instances of CR LF
48
- // ('\r\n') in input.txt as a single line break.
49
45
  for await (const line of rl) {
50
46
  if (line) {
51
47
  const { event, data } = JSON.parse(line);
@@ -57,12 +57,10 @@ const makeLtHashGenerator = ({ indexValueMap, hash }) => {
57
57
  if (!prevOp) {
58
58
  throw new boom_1.Boom('tried remove, but no previous op', { data: { indexMac, valueMac } });
59
59
  }
60
- // remove from index value mac, since this mutation is erased
61
60
  delete indexValueMap[indexMacBase64];
62
61
  }
63
62
  else {
64
63
  addBuffs.push(new Uint8Array(valueMac).buffer);
65
- // add this index into the history map
66
64
  indexValueMap[indexMacBase64] = { valueMac };
67
65
  }
68
66
  if (prevOp) {
@@ -118,7 +116,6 @@ const encodeSyncdPatch = async ({ type, index, syncAction, apiVersion, operation
118
116
  const encValue = (0, crypto_1.aesEncrypt)(encoded, keyValue.valueEncryptionKey);
119
117
  const valueMac = generateMac(operation, encValue, encKeyId, keyValue.valueMacKey);
120
118
  const indexMac = (0, crypto_1.hmacSign)(indexBuffer, keyValue.indexKey);
121
- // update LT hash
122
119
  const generator = makeLtHashGenerator(state);
123
120
  generator.mix({ indexMac, valueMac, operation });
124
121
  Object.assign(state, generator.finish());
@@ -150,12 +147,7 @@ const encodeSyncdPatch = async ({ type, index, syncAction, apiVersion, operation
150
147
  exports.encodeSyncdPatch = encodeSyncdPatch;
151
148
  const decodeSyncdMutations = async (msgMutations, initialState, getAppStateSyncKey, onMutation, validateMacs) => {
152
149
  const ltGenerator = makeLtHashGenerator(initialState);
153
- // indexKey used to HMAC sign record.index.blob
154
- // valueEncryptionKey used to AES-256-CBC encrypt record.value.blob[0:-32]
155
- // the remaining record.value.blob[0:-32] is the mac, it the HMAC sign of key.keyId + decoded proto data + length of bytes in keyId
156
150
  for (const msgMutation of msgMutations) {
157
- // if it's a syncdmutation, get the operation property
158
- // otherwise, if it's only a record -- it'll be a SET mutation
159
151
  const operation = 'operation' in msgMutation ? msgMutation.operation : WAProto_1.proto.SyncdMutation.SyncdOperation.SET;
160
152
  const record = ('record' in msgMutation && !!msgMutation.record) ? msgMutation.record : msgMutation;
161
153
  const key = await getKey(record.keyId.id);
@@ -338,7 +330,6 @@ const decodePatches = async (name, syncds, initial, getAppStateSyncKey, options,
338
330
  throw new boom_1.Boom(`failed to verify LTHash at ${newState.version} of ${name}`);
339
331
  }
340
332
  }
341
- // clear memory used up by the mutations
342
333
  syncd.mutations = [];
343
334
  }
344
335
  return { state: newState, mutationMap };
@@ -582,16 +573,6 @@ const processSyncAction = (syncAction, ev, me, initialSyncOpts, logger) => {
582
573
  ]);
583
574
  }
584
575
  else if ((action === null || action === void 0 ? void 0 : action.archiveChatAction) || type === 'archive' || type === 'unarchive') {
585
- // okay so we've to do some annoying computation here
586
- // when we're initially syncing the app state
587
- // there are a few cases we need to handle
588
- // 1. if the account unarchiveChats setting is true
589
- // a. if the chat is archived, and no further messages have been received -- simple, keep archived
590
- // b. if the chat was archived, and the user received messages from the other person afterwards
591
- // then the chat should be marked unarchved --
592
- // we compare the timestamp of latest message from the other person to determine this
593
- // 2. if the account unarchiveChats setting is false -- then it doesn't matter,
594
- // it'll always take an app state action to mark in unarchived -- which we'll get anyway
595
576
  const archiveAction = action === null || action === void 0 ? void 0 : action.archiveChatAction;
596
577
  const isArchived = archiveAction
597
578
  ? archiveAction.archived
@@ -611,9 +592,6 @@ const processSyncAction = (syncAction, ev, me, initialSyncOpts, logger) => {
611
592
  }
612
593
  else if (action === null || action === void 0 ? void 0 : action.markChatAsReadAction) {
613
594
  const markReadAction = action.markChatAsReadAction;
614
- // basically we don't need to fire an "read" update if the chat is being marked as read
615
- // because the chat is read by default
616
- // this only applies for the initial sync
617
595
  const isNullUpdate = isInitialSync && markReadAction.read;
618
596
  ev.emit('chats.update', [{
619
597
  id,
@@ -41,7 +41,6 @@ exports.Curve = {
41
41
  const { pubKey, privKey } = libsignal.curve.generateKeyPair();
42
42
  return {
43
43
  private: Buffer.from(privKey),
44
- // remove version byte
45
44
  public: Buffer.from(pubKey.slice(1))
46
45
  };
47
46
  },
@@ -84,10 +83,8 @@ exports.aesEncryptGCM = aesEncryptGCM;
84
83
  * */
85
84
  function aesDecryptGCM(ciphertext, key, iv, additionalData) {
86
85
  const decipher = (0, crypto_1.createDecipheriv)('aes-256-gcm', key, iv);
87
- // decrypt additional adata
88
86
  const enc = ciphertext.slice(0, ciphertext.length - GCM_TAG_LENGTH);
89
87
  const tag = ciphertext.slice(ciphertext.length - GCM_TAG_LENGTH);
90
- // set additional data
91
88
  decipher.setAAD(additionalData);
92
89
  decipher.setAuthTag(tag);
93
90
  return Buffer.concat([decipher.update(enc), decipher.final()]);
@@ -114,20 +111,17 @@ function aesDecryptWithIV(buffer, key, IV) {
114
111
  return Buffer.concat([aes.update(buffer), aes.final()]);
115
112
  }
116
113
  exports.aesDecryptWithIV = aesDecryptWithIV;
117
- // encrypt AES 256 CBC; where a random IV is prefixed to the buffer
118
114
  function aesEncrypt(buffer, key) {
119
115
  const IV = (0, crypto_1.randomBytes)(16);
120
116
  const aes = (0, crypto_1.createCipheriv)('aes-256-cbc', key, IV);
121
- return Buffer.concat([IV, aes.update(buffer), aes.final()]); // prefix IV to the buffer
117
+ return Buffer.concat([IV, aes.update(buffer), aes.final()]);
122
118
  }
123
119
  exports.aesEncrypt = aesEncrypt;
124
- // encrypt AES 256 CBC with a given IV
125
120
  function aesEncrypWithIV(buffer, key, IV) {
126
121
  const aes = (0, crypto_1.createCipheriv)('aes-256-cbc', key, IV);
127
- return Buffer.concat([aes.update(buffer), aes.final()]); // prefix IV to the buffer
122
+ return Buffer.concat([aes.update(buffer), aes.final()]);
128
123
  }
129
124
  exports.aesEncrypWithIV = aesEncrypWithIV;
130
- // sign HMAC using SHA 256
131
125
  function hmacSign(buffer, key, variant = 'sha256') {
132
126
  return (0, crypto_1.createHmac)(variant, key).update(buffer).digest();
133
127
  }
@@ -140,7 +134,6 @@ function md5(buffer) {
140
134
  return (0, crypto_1.createHash)('md5').update(buffer).digest();
141
135
  }
142
136
  exports.md5 = md5;
143
- // HKDF key expansion
144
137
  function hkdf(buffer, expandedLength, info) {
145
138
  return (0, futoin_hkdf_1.default)(!Buffer.isBuffer(buffer) ? Buffer.from(buffer) : buffer, expandedLength, info);
146
139
  }
@@ -275,7 +275,6 @@ const generateForwardMessageContent = (message, forceForward) => {
275
275
  if (!content) {
276
276
  throw new boom_1.Boom('no content in message', { statusCode: 400 });
277
277
  }
278
- // hacky copy
279
278
  content = (0, exports.normalizeMessageContent)(content);
280
279
  content = WAProto_1.proto.Message.decode(WAProto_1.proto.Message.encode(content).finish());
281
280
  let key = Object.keys(content)[0];
package/lib/WAM/encode.js CHANGED
@@ -75,7 +75,6 @@ function serializeData(key, value, flag) {
75
75
  }
76
76
  }
77
77
  else if (typeof value === 'number' && Number.isInteger(value)) {
78
- // is number
79
78
  if (value === 0 || value === 1) {
80
79
  buffer = Buffer.alloc(bufferLength);
81
80
  offset = serializeHeader(buffer, offset, key, flag | ((value + 1) << 4));
@@ -107,14 +106,12 @@ function serializeData(key, value, flag) {
107
106
  }
108
107
  }
109
108
  else if (typeof value === 'number') {
110
- // is float
111
109
  buffer = Buffer.alloc(bufferLength + 8);
112
110
  offset = serializeHeader(buffer, offset, key, flag | (7 << 4));
113
111
  buffer.writeDoubleLE(value, offset);
114
112
  return buffer;
115
113
  }
116
114
  else if (typeof value === 'string') {
117
- // is string
118
115
  const utf8Bytes = Buffer.byteLength(value, 'utf8');
119
116
  if (utf8Bytes < 256) {
120
117
  buffer = Buffer.alloc(bufferLength + 1 + utf8Bytes);
@@ -13,7 +13,6 @@ class USyncContactProtocol {
13
13
  };
14
14
  }
15
15
  getUserElement(user) {
16
- //TODO: Implement type / username fields (not yet supported)
17
16
  return {
18
17
  tag: 'contact',
19
18
  attrs: {},
@@ -15,9 +15,6 @@ class USyncDeviceProtocol {
15
15
  };
16
16
  }
17
17
  getUserElement( /* user: USyncUser */) {
18
- //TODO: Implement device phashing, ts and expectedTs
19
- //TODO: if all are not present, return null <- current behavior
20
- //TODO: otherwise return a node w tag 'devices' w those as attrs
21
18
  return null;
22
19
  }
23
20
  parser(node) {
@@ -32,14 +32,10 @@ class USyncQuery {
32
32
  return [protocol.name, protocol.parser];
33
33
  }));
34
34
  const queryResult = {
35
- // TODO: implement errors etc.
36
35
  list: [],
37
36
  sideList: [],
38
37
  };
39
38
  const usyncNode = (0, WABinary_1.getBinaryNodeChild)(result, 'usync');
40
- //TODO: implement error backoff, refresh etc.
41
- //TODO: see if there are any errors in the result node
42
- //const resultNode = getBinaryNodeChild(usyncNode, 'result')
43
39
  const listNode = (0, WABinary_1.getBinaryNodeChild)(usyncNode, 'list');
44
40
  if (Array.isArray(listNode === null || listNode === void 0 ? void 0 : listNode.content) && typeof listNode !== 'undefined') {
45
41
  queryResult.list = listNode.content.map((node) => {
@@ -57,7 +53,6 @@ class USyncQuery {
57
53
  return { ...data, id };
58
54
  });
59
55
  }
60
- //TODO: implement side list
61
56
  //const sideListNode = getBinaryNodeChild(usyncNode, 'side_list')
62
57
  return queryResult;
63
58
  }
package/package.json CHANGED
@@ -1,9 +1,11 @@
1
1
  {
2
2
  "name": "sanka-baileyss",
3
- "version": "2.4.7",
3
+ "version": "2.4.9",
4
4
  "description": "WhatsApp API Modification By Sanka_Vollerei",
5
5
  "keywords": [
6
6
  "Baileys",
7
+ "Baileys-Modification",
8
+ "Bail-Mod",
7
9
  "whiskeysockets/baileys",
8
10
  "whatsapp",
9
11
  "meta",
@@ -27,7 +29,6 @@
27
29
  "files": [
28
30
  "lib/*",
29
31
  "WAProto/*",
30
- "WASignalGroup/*.js",
31
32
  "check-node-version.js"
32
33
  ],
33
34
  "scripts": {
@@ -89,10 +90,10 @@
89
90
  "json": "^11.0.0"
90
91
  },
91
92
  "peerDependencies": {
92
- "jimp": "^0.22.12",
93
- "link-preview-js": "^3.0.0",
94
- "qrcode-terminal": "^0.12.0",
95
- "sharp": "^0.32.2"
93
+ "jimp": "*",
94
+ "link-preview-js": "*",
95
+ "qrcode-terminal": "*",
96
+ "sharp": "*"
96
97
  },
97
98
  "peerDependenciesMeta": {
98
99
  "jimp": {
File without changes