@queenanya/baileys 7.4.14 → 7.5.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/README.md +26 -26
  2. package/WAProto/index.js +66875 -96112
  3. package/lib/Defaults/baileys-version.json +1 -1
  4. package/lib/Defaults/index.d.ts +1 -231
  5. package/lib/Defaults/index.js +11 -23
  6. package/lib/Socket/Client/index.d.ts +2 -3
  7. package/lib/Socket/Client/index.js +2 -3
  8. package/lib/Socket/Client/{web-socket-client.d.ts → websocket.d.ts} +1 -1
  9. package/lib/Socket/Client/{web-socket-client.js → websocket.js} +2 -2
  10. package/lib/Socket/business.d.ts +29 -22
  11. package/lib/Socket/chats.d.ts +14 -3
  12. package/lib/Socket/chats.js +76 -48
  13. package/lib/Socket/groups.d.ts +21 -4
  14. package/lib/Socket/groups.js +12 -1
  15. package/lib/Socket/index.d.ts +37 -32
  16. package/lib/Socket/index.js +2 -2
  17. package/lib/Socket/messages-recv.d.ts +28 -22
  18. package/lib/Socket/messages-recv.js +291 -180
  19. package/lib/Socket/messages-send.d.ts +23 -13
  20. package/lib/Socket/messages-send.js +110 -76
  21. package/lib/Socket/newsletter.d.ts +17 -7
  22. package/lib/Socket/newsletter.js +67 -54
  23. package/lib/Socket/socket.d.ts +3 -1
  24. package/lib/Socket/socket.js +15 -17
  25. package/lib/Store/make-cache-manager-store.d.ts +2 -1
  26. package/lib/Store/make-in-memory-store.js +13 -11
  27. package/lib/Store/make-ordered-dictionary.js +2 -2
  28. package/lib/Types/Auth.d.ts +1 -6
  29. package/lib/Types/Call.d.ts +1 -1
  30. package/lib/Types/Chat.d.ts +12 -7
  31. package/lib/Types/Contact.d.ts +1 -1
  32. package/lib/Types/Events.d.ts +44 -2
  33. package/lib/Types/GroupMetadata.d.ts +3 -1
  34. package/lib/Types/Label.d.ts +11 -0
  35. package/lib/Types/Message.d.ts +37 -30
  36. package/lib/Types/Newsletter.d.ts +0 -13
  37. package/lib/Types/Newsletter.js +1 -15
  38. package/lib/Types/Socket.d.ts +10 -3
  39. package/lib/Types/index.d.ts +8 -0
  40. package/lib/Utils/auth-utils.js +1 -7
  41. package/lib/Utils/chat-utils.d.ts +5 -4
  42. package/lib/Utils/chat-utils.js +41 -20
  43. package/lib/Utils/crypto.d.ts +2 -1
  44. package/lib/Utils/crypto.js +4 -2
  45. package/lib/Utils/decode-wa-message.d.ts +1 -0
  46. package/lib/Utils/decode-wa-message.js +34 -14
  47. package/lib/Utils/event-buffer.js +14 -8
  48. package/lib/Utils/generics.d.ts +37 -13
  49. package/lib/Utils/generics.js +102 -18
  50. package/lib/Utils/history.d.ts +6 -2
  51. package/lib/Utils/history.js +3 -0
  52. package/lib/Utils/index.d.ts +1 -0
  53. package/lib/Utils/index.js +1 -0
  54. package/lib/Utils/link-preview.js +24 -1
  55. package/lib/Utils/logger.d.ts +1 -3
  56. package/lib/Utils/make-mutex.js +1 -0
  57. package/lib/Utils/messages-media.d.ts +3 -2
  58. package/lib/Utils/messages-media.js +17 -32
  59. package/lib/Utils/messages.d.ts +1 -0
  60. package/lib/Utils/messages.js +67 -72
  61. package/lib/Utils/noise-handler.d.ts +3 -3
  62. package/lib/Utils/noise-handler.js +7 -12
  63. package/lib/Utils/process-message.d.ts +3 -2
  64. package/lib/Utils/process-message.js +55 -21
  65. package/lib/Utils/signal.js +23 -16
  66. package/lib/Utils/use-multi-file-auth-state.js +17 -3
  67. package/lib/Utils/validate-connection.d.ts +0 -1
  68. package/lib/Utils/validate-connection.js +10 -44
  69. package/lib/WABinary/constants.js +5 -5
  70. package/lib/WABinary/decode.d.ts +3 -2
  71. package/lib/WABinary/decode.js +6 -4
  72. package/lib/WABinary/encode.d.ts +1 -2
  73. package/lib/WABinary/encode.js +8 -6
  74. package/lib/WABinary/generic-utils.d.ts +1 -0
  75. package/lib/WABinary/jid-utils.d.ts +3 -3
  76. package/lib/WABinary/jid-utils.js +5 -5
  77. package/lib/WAM/BinaryInfo.d.ts +3 -2
  78. package/lib/WAM/constants.d.ts +3 -2
  79. package/lib/WAM/encode.d.ts +1 -0
  80. package/lib/WAM/encode.js +2 -2
  81. package/package.json +37 -35
  82. package/lib/Defaults/phonenumber-mcc.json +0 -223
  83. package/lib/Socket/Client/mobile-socket-client.d.ts +0 -13
  84. package/lib/Socket/Client/mobile-socket-client.js +0 -65
  85. package/lib/Socket/registration.d.ts +0 -267
  86. package/lib/Socket/registration.js +0 -166
  87. /package/lib/Socket/Client/{abstract-socket-client.d.ts → types.d.ts} +0 -0
  88. /package/lib/Socket/Client/{abstract-socket-client.js → types.js} +0 -0
@@ -1,13 +1,14 @@
1
1
  /// <reference types="node" />
2
2
  /// <reference types="node" />
3
3
  /// <reference types="node" />
4
+ /// <reference types="node" />
4
5
  import { AxiosRequestConfig } from 'axios';
5
6
  import type { Logger } from 'pino';
6
7
  import type { Readable } from 'stream';
7
8
  import type { URL } from 'url';
8
- import { BinaryNode } from '../WABinary';
9
9
  import { proto } from '../../WAProto';
10
10
  import { MEDIA_HKDF_KEY_MAPPING } from '../Defaults';
11
+ import { BinaryNode } from '../WABinary';
11
12
  import type { GroupMetadata } from './GroupMetadata';
12
13
  import { CacheStore } from './Socket';
13
14
  export { proto as WAProto };
@@ -15,18 +16,22 @@ export type WAMessage = proto.IWebMessageInfo;
15
16
  export type WAMessageContent = proto.IMessage;
16
17
  export type WAContactMessage = proto.Message.IContactMessage;
17
18
  export type WAContactsArrayMessage = proto.Message.IContactsArrayMessage;
18
- export type WAMessageKey = proto.IMessageKey;
19
+ export type WAMessageKey = proto.IMessageKey & {
20
+ server_id?: string;
21
+ };
19
22
  export type WATextMessage = proto.Message.IExtendedTextMessage;
20
23
  export type WAContextInfo = proto.IContextInfo;
21
24
  export type WALocationMessage = proto.Message.ILocationMessage;
22
25
  export type WAGenericMediaMessage = proto.Message.IVideoMessage | proto.Message.IImageMessage | proto.Message.IAudioMessage | proto.Message.IDocumentMessage | proto.Message.IStickerMessage;
23
26
  export import WAMessageStubType = proto.WebMessageInfo.StubType;
24
27
  export import WAMessageStatus = proto.WebMessageInfo.Status;
25
- export type WAMediaUpload = Buffer | {
28
+ export type WAMediaPayloadURL = {
26
29
  url: URL | string;
27
- } | {
30
+ };
31
+ export type WAMediaPayloadStream = {
28
32
  stream: Readable;
29
33
  };
34
+ export type WAMediaUpload = Buffer | WAMediaPayloadStream | WAMediaPayloadURL;
30
35
  /** Set of message types that are supported by the library */
31
36
  export type MessageType = keyof proto.Message;
32
37
  export type DownloadableMessage = {
@@ -64,26 +69,9 @@ type Contextable = {
64
69
  type ViewOnce = {
65
70
  viewOnce?: boolean;
66
71
  };
67
- type Buttonable = {
68
- /** add buttons to the message */
69
- buttons?: proto.Message.ButtonsMessage.IButton[];
70
- };
71
- type Templatable = {
72
- /** add buttons to the message (conflicts with normal buttons)*/
73
- templateButtons?: proto.IHydratedTemplateButton[];
74
- footer?: string;
75
- };
76
72
  type Editable = {
77
73
  edit?: WAMessageKey;
78
74
  };
79
- type Listable = {
80
- /** Sections of the List */
81
- sections?: proto.Message.ListMessage.ISection[];
82
- /** Title of a List Message only */
83
- title?: string;
84
- /** Text of the bnutton on the list (required) */
85
- buttonText?: string;
86
- };
87
75
  type WithDimensions = {
88
76
  width?: number;
89
77
  height?: number;
@@ -94,6 +82,7 @@ export type PollMessageOptions = {
94
82
  values: string[];
95
83
  /** 32 byte message secret to encrypt poll selections */
96
84
  messageSecret?: Uint8Array;
85
+ toAnnouncementGroup?: boolean;
97
86
  };
98
87
  type SharePhoneNumber = {
99
88
  sharePhoneNumber: boolean;
@@ -106,14 +95,14 @@ export type AnyMediaMessageContent = (({
106
95
  image: WAMediaUpload;
107
96
  caption?: string;
108
97
  jpegThumbnail?: string;
109
- } & Mentionable & Contextable & Buttonable & Templatable & WithDimensions) | ({
98
+ } & Mentionable & Contextable & WithDimensions) | ({
110
99
  video: WAMediaUpload;
111
100
  caption?: string;
112
101
  gifPlayback?: boolean;
113
102
  jpegThumbnail?: string;
114
103
  /** if set to true, will send as a `video note` */
115
104
  ptv?: boolean;
116
- } & Mentionable & Contextable & Buttonable & Templatable & WithDimensions) | {
105
+ } & Mentionable & Contextable & WithDimensions) | {
117
106
  audio: WAMediaUpload;
118
107
  /** if set to true, will send as a `voice note` */
119
108
  ptt?: boolean;
@@ -127,7 +116,7 @@ export type AnyMediaMessageContent = (({
127
116
  mimetype: string;
128
117
  fileName?: string;
129
118
  caption?: string;
130
- } & Contextable & Buttonable & Templatable)) & {
119
+ } & Contextable)) & {
131
120
  mimetype?: string;
132
121
  } & Editable;
133
122
  export type ButtonReplyInfo = {
@@ -135,15 +124,22 @@ export type ButtonReplyInfo = {
135
124
  id: string;
136
125
  index: number;
137
126
  };
127
+ export type GroupInviteInfo = {
128
+ inviteCode: string;
129
+ inviteExpiration: number;
130
+ text: string;
131
+ jid: string;
132
+ subject: string;
133
+ };
138
134
  export type WASendableProduct = Omit<proto.Message.ProductMessage.IProductSnapshot, 'productImage'> & {
139
135
  productImage: WAMediaUpload;
140
136
  };
141
137
  export type AnyRegularMessageContent = (({
142
138
  text: string;
143
139
  linkPreview?: WAUrlInfo | null;
144
- } & Mentionable & Contextable & Buttonable & Templatable & Listable & Editable) | AnyMediaMessageContent | ({
140
+ } & Mentionable & Contextable & Editable) | AnyMediaMessageContent | ({
145
141
  poll: PollMessageOptions;
146
- } & Mentionable & Contextable & Buttonable & Templatable & Editable) | {
142
+ } & Mentionable & Contextable & Editable) | {
147
143
  contacts: {
148
144
  displayName?: string;
149
145
  contacts: proto.Message.IContactMessage[];
@@ -155,8 +151,19 @@ export type AnyRegularMessageContent = (({
155
151
  } | {
156
152
  buttonReply: ButtonReplyInfo;
157
153
  type: 'template' | 'plain';
154
+ } | {
155
+ groupInvite: GroupInviteInfo;
158
156
  } | {
159
157
  listReply: Omit<proto.Message.IListResponseMessage, 'contextInfo'>;
158
+ } | {
159
+ pin: WAMessageKey;
160
+ type: proto.PinInChat.Type;
161
+ /**
162
+ * 24 hours, 7 days, 30 days
163
+ */
164
+ time?: 86400 | 604800 | 2592000;
165
+ } | {
166
+ unpin: WAMessageKey;
160
167
  } | {
161
168
  product: WASendableProduct;
162
169
  businessOwnerJid?: string;
@@ -176,8 +183,8 @@ export type GroupMetadataParticipants = Pick<GroupMetadata, 'participants'>;
176
183
  type MinimalRelayOptions = {
177
184
  /** override the message ID with a custom provided string */
178
185
  messageId?: string;
179
- /** cached group metadata, use to prevent redundant requests to WA & speed up msg sending */
180
- cachedGroupMetadata?: (jid: string) => Promise<GroupMetadataParticipants | undefined>;
186
+ /** should we use group metadata cache, or fetch afresh from the server; default assumed to be "true" */
187
+ useCachedGroupMetadata?: boolean;
181
188
  };
182
189
  export type MessageRelayOptions = MinimalRelayOptions & {
183
190
  /** only send to a specific participant; used when a message decryption fails for a single user */
@@ -200,7 +207,6 @@ export type MiscMessageGenerationOptions = MinimalRelayOptions & {
200
207
  timestamp?: Date;
201
208
  /** the message you want to quote */
202
209
  quoted?: WAMessage;
203
- additionalNodes?: BinaryNode[];
204
210
  /** disappearing messages settings */
205
211
  ephemeralExpiration?: number | string;
206
212
  /** timeout for media upload to WA server */
@@ -237,12 +243,13 @@ export type MediaGenerationOptions = {
237
243
  mediaUploadTimeoutMs?: number;
238
244
  options?: AxiosRequestConfig;
239
245
  backgroundColor?: string;
240
- font?: number;
241
246
  /** The message is for newsletter? */
242
247
  newsletter?: boolean;
248
+ font?: number;
243
249
  };
244
250
  export type MessageContentGenerationOptions = MediaGenerationOptions & {
245
251
  getUrlInfo?: (text: string) => Promise<WAUrlInfo | undefined>;
252
+ getProfilePicUrl?: (jid: string, type: 'image' | 'preview') => Promise<string | undefined>;
246
253
  };
247
254
  export type MessageGenerationOptions = MessageContentGenerationOptions & MessageGenerationOptionsFromContent;
248
255
  /**
@@ -77,16 +77,3 @@ export declare enum XWAPaths {
77
77
  NEWSLETTER = "xwa2_newsletter",
78
78
  METADATA_UPDATE = "xwa2_notify_newsletter_on_metadata_update"
79
79
  }
80
- export declare enum QueryIds {
81
- JOB_MUTATION = "7150902998257522",
82
- METADATA = "6620195908089573",
83
- UNFOLLOW = "7238632346214362",
84
- FOLLOW = "7871414976211147",
85
- UNMUTE = "7337137176362961",
86
- MUTE = "25151904754424642",
87
- CREATE = "6996806640408138",
88
- ADMIN_COUNT = "7130823597031706",
89
- CHANGE_OWNER = "7341777602580933",
90
- DELETE = "8316537688363079",
91
- DEMOTE = "6551828931592903"
92
- }
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.QueryIds = exports.XWAPaths = exports.MexOperations = void 0;
3
+ exports.XWAPaths = exports.MexOperations = void 0;
4
4
  var MexOperations;
5
5
  (function (MexOperations) {
6
6
  MexOperations["PROMOTE"] = "NotificationNewsletterAdminPromote";
@@ -16,17 +16,3 @@ var XWAPaths;
16
16
  XWAPaths["NEWSLETTER"] = "xwa2_newsletter";
17
17
  XWAPaths["METADATA_UPDATE"] = "xwa2_notify_newsletter_on_metadata_update";
18
18
  })(XWAPaths = exports.XWAPaths || (exports.XWAPaths = {}));
19
- var QueryIds;
20
- (function (QueryIds) {
21
- QueryIds["JOB_MUTATION"] = "7150902998257522";
22
- QueryIds["METADATA"] = "6620195908089573";
23
- QueryIds["UNFOLLOW"] = "7238632346214362";
24
- QueryIds["FOLLOW"] = "7871414976211147";
25
- QueryIds["UNMUTE"] = "7337137176362961";
26
- QueryIds["MUTE"] = "25151904754424642";
27
- QueryIds["CREATE"] = "6996806640408138";
28
- QueryIds["ADMIN_COUNT"] = "7130823597031706";
29
- QueryIds["CHANGE_OWNER"] = "7341777602580933";
30
- QueryIds["DELETE"] = "8316537688363079";
31
- QueryIds["DEMOTE"] = "6551828931592903";
32
- })(QueryIds = exports.QueryIds || (exports.QueryIds = {}));
@@ -6,6 +6,7 @@ import type { Logger } from 'pino';
6
6
  import type { URL } from 'url';
7
7
  import { proto } from '../../WAProto';
8
8
  import { AuthenticationState, SignalAuthState, TransactionCapabilityOptions } from './Auth';
9
+ import { GroupMetadata } from './GroupMetadata';
9
10
  import { MediaConnInfo } from './Message';
10
11
  import { SignalRepository } from './Signal';
11
12
  export type WAVersion = [number, number, number];
@@ -29,7 +30,9 @@ export type SocketConfig = {
29
30
  defaultQueryTimeoutMs: number | undefined;
30
31
  /** ping-pong interval for WS connection */
31
32
  keepAliveIntervalMs: number;
32
- /** should baileys use the mobile api instead of the multi device api */
33
+ /** should baileys use the mobile api instead of the multi device api
34
+ * @deprecated This feature has been removed
35
+ */
33
36
  mobile?: boolean;
34
37
  /** proxy agent */
35
38
  agent?: Agent;
@@ -71,10 +74,14 @@ export type SocketConfig = {
71
74
  userDevicesCache?: CacheStore;
72
75
  /** cache to store call offers */
73
76
  callOfferCache?: CacheStore;
77
+ /** cache to track placeholder resends */
78
+ placeholderResendCache?: CacheStore;
74
79
  /** width for link preview images */
75
80
  linkPreviewImageThumbnailWidth: number;
76
81
  /** Should Baileys ask the phone for full history, will be received async */
77
82
  syncFullHistory: boolean;
83
+ /** Ignore Message when offline, default is false */
84
+ ignoreMsgLoading: boolean;
78
85
  /** Should baileys fire init queries automatically, default true */
79
86
  fireInitQueries: boolean;
80
87
  /**
@@ -105,7 +112,7 @@ export type SocketConfig = {
105
112
  * (solves the "this message can take a while" issue) can be retried
106
113
  * */
107
114
  getMessage: (key: proto.IMessageKey) => Promise<proto.IMessage | undefined>;
115
+ /** cached group metadata, use to prevent redundant requests to WA & speed up msg sending */
116
+ cachedGroupMetadata: (jid: string) => Promise<GroupMetadata | undefined>;
108
117
  makeSignalRepository: (auth: SignalAuthState) => SignalRepository;
109
- /** Socket passthrough */
110
- socket?: any;
111
118
  };
@@ -15,6 +15,14 @@ import { SocketConfig } from './Socket';
15
15
  export type UserFacingSocketConfig = Partial<SocketConfig> & {
16
16
  auth: AuthenticationState;
17
17
  };
18
+ /** Other Browser Support for Paircode */
19
+ export type BrowsersMap = {
20
+ ubuntu(browser: string): [string, string, string];
21
+ macOS(browser: string): [string, string, string];
22
+ baileys(browser: string): [string, string, string];
23
+ windows(browser: string): [string, string, string];
24
+ appropriate(browser: string): [string, string, string];
25
+ };
18
26
  export declare enum DisconnectReason {
19
27
  connectionClosed = 428,
20
28
  connectionLost = 408,
@@ -6,7 +6,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.initAuthCreds = exports.addTransactionCapability = exports.makeCacheableSignalKeyStore = void 0;
7
7
  const crypto_1 = require("crypto");
8
8
  const node_cache_1 = __importDefault(require("node-cache"));
9
- const uuid_1 = require("uuid");
10
9
  const Defaults_1 = require("../Defaults");
11
10
  const crypto_2 = require("./crypto");
12
11
  const generics_1 = require("./generics");
@@ -143,6 +142,7 @@ const addTransactionCapability = (state, logger, { maxCommitRetries, delayBetwee
143
142
  let tries = maxCommitRetries;
144
143
  while (tries) {
145
144
  tries -= 1;
145
+ //eslint-disable-next-line max-depth
146
146
  try {
147
147
  await state.set(mutations);
148
148
  logger.trace({ dbQueriesInTransaction }, 'committed transaction');
@@ -191,13 +191,7 @@ const initAuthCreds = () => {
191
191
  accountSettings: {
192
192
  unarchiveChats: false
193
193
  },
194
- // mobile creds
195
- deviceId: Buffer.from((0, uuid_1.v4)().replace(/-/g, ''), 'hex').toString('base64url'),
196
- phoneId: (0, uuid_1.v4)(),
197
- identityId: (0, crypto_1.randomBytes)(20),
198
194
  registered: false,
199
- backupToken: (0, crypto_1.randomBytes)(20),
200
- registration: {},
201
195
  pairingCode: undefined,
202
196
  lastPropHash: undefined,
203
197
  routingInfo: undefined,
@@ -1,4 +1,5 @@
1
1
  /// <reference types="node" />
2
+ /// <reference types="node" />
2
3
  import { AxiosRequestConfig } from 'axios';
3
4
  import type { Logger } from 'pino';
4
5
  import { proto } from '../../WAProto';
@@ -29,7 +30,7 @@ export declare const decodeSyncdPatch: (msg: proto.ISyncdPatch, name: WAPatchNam
29
30
  };
30
31
  };
31
32
  }>;
32
- export declare const extractSyncdPatches: (result: BinaryNode, options: AxiosRequestConfig<any>) => Promise<{
33
+ export declare const extractSyncdPatches: (result: BinaryNode, options: AxiosRequestConfig<{}>) => Promise<{
33
34
  critical_block: {
34
35
  patches: proto.ISyncdPatch[];
35
36
  hasMorePatches: boolean;
@@ -56,13 +57,13 @@ export declare const extractSyncdPatches: (result: BinaryNode, options: AxiosReq
56
57
  snapshot?: proto.ISyncdSnapshot | undefined;
57
58
  };
58
59
  }>;
59
- export declare const downloadExternalBlob: (blob: proto.IExternalBlobReference, options: AxiosRequestConfig<any>) => Promise<Buffer>;
60
- export declare const downloadExternalPatch: (blob: proto.IExternalBlobReference, options: AxiosRequestConfig<any>) => Promise<proto.SyncdMutations>;
60
+ export declare const downloadExternalBlob: (blob: proto.IExternalBlobReference, options: AxiosRequestConfig<{}>) => Promise<Buffer>;
61
+ export declare const downloadExternalPatch: (blob: proto.IExternalBlobReference, options: AxiosRequestConfig<{}>) => Promise<proto.SyncdMutations>;
61
62
  export declare const decodeSyncdSnapshot: (name: WAPatchName, snapshot: proto.ISyncdSnapshot, getAppStateSyncKey: FetchAppStateSyncKey, minimumVersionNumber: number | undefined, validateMacs?: boolean) => Promise<{
62
63
  state: LTHashState;
63
64
  mutationMap: ChatMutationMap;
64
65
  }>;
65
- export declare const decodePatches: (name: WAPatchName, syncds: proto.ISyncdPatch[], initial: LTHashState, getAppStateSyncKey: FetchAppStateSyncKey, options: AxiosRequestConfig<any>, minimumVersionNumber?: number, logger?: Logger, validateMacs?: boolean) => Promise<{
66
+ export declare const decodePatches: (name: WAPatchName, syncds: proto.ISyncdPatch[], initial: LTHashState, getAppStateSyncKey: FetchAppStateSyncKey, options: AxiosRequestConfig<{}>, minimumVersionNumber?: number, logger?: Logger, validateMacs?: boolean) => Promise<{
66
67
  state: LTHashState;
67
68
  mutationMap: ChatMutationMap;
68
69
  }>;
@@ -305,8 +305,7 @@ const decodePatches = async (name, syncds, initial, getAppStateSyncKey, options,
305
305
  indexValueMap: { ...initial.indexValueMap }
306
306
  };
307
307
  const mutationMap = {};
308
- for (let i = 0; i < syncds.length; i++) {
309
- const syncd = syncds[i];
308
+ for (const syncd of syncds) {
310
309
  const { version, keyId, snapshotMac } = syncd;
311
310
  if (syncd.externalMutations) {
312
311
  logger === null || logger === void 0 ? void 0 : logger.trace({ name, version }, 'downloading external patch');
@@ -418,25 +417,31 @@ const chatModificationToAppPatch = (mod, jid) => {
418
417
  operation: OP.SET
419
418
  };
420
419
  }
420
+ else if ('deleteForMe' in mod) {
421
+ const { timestamp, key, deleteMedia } = mod.deleteForMe;
422
+ patch = {
423
+ syncAction: {
424
+ deleteMessageForMeAction: {
425
+ deleteMedia,
426
+ messageTimestamp: timestamp
427
+ }
428
+ },
429
+ index: ['deleteMessageForMe', jid, key.id, key.fromMe ? '1' : '0', '0'],
430
+ type: 'regular_high',
431
+ apiVersion: 3,
432
+ operation: OP.SET
433
+ };
434
+ }
421
435
  else if ('clear' in mod) {
422
- if (mod.clear === 'all') {
423
- throw new boom_1.Boom('not supported');
424
- }
425
- else {
426
- const key = mod.clear.messages[0];
427
- patch = {
428
- syncAction: {
429
- deleteMessageForMeAction: {
430
- deleteMedia: false,
431
- messageTimestamp: key.timestamp
432
- }
433
- },
434
- index: ['deleteMessageForMe', jid, key.id, key.fromMe ? '1' : '0', '0'],
435
- type: 'regular_high',
436
- apiVersion: 3,
437
- operation: OP.SET
438
- };
439
- }
436
+ patch = {
437
+ syncAction: {
438
+ clearChatAction: {} // add message range later
439
+ },
440
+ index: ['clearChat', jid, '1' /*the option here is 0 when keep starred messages is enabled*/, '0'],
441
+ type: 'regular_high',
442
+ apiVersion: 6,
443
+ operation: OP.SET
444
+ };
440
445
  }
441
446
  else if ('pin' in mod) {
442
447
  patch = {
@@ -491,6 +496,22 @@ const chatModificationToAppPatch = (mod, jid) => {
491
496
  operation: OP.SET,
492
497
  };
493
498
  }
499
+ else if ('addLabel' in mod) {
500
+ patch = {
501
+ syncAction: {
502
+ labelEditAction: {
503
+ name: mod.addLabel.name,
504
+ color: mod.addLabel.color,
505
+ predefinedId: mod.addLabel.predefinedId,
506
+ deleted: mod.addLabel.deleted
507
+ }
508
+ },
509
+ index: ['label_edit', mod.addLabel.id],
510
+ type: 'regular',
511
+ apiVersion: 3,
512
+ operation: OP.SET,
513
+ };
514
+ }
494
515
  else if ('addChatLabel' in mod) {
495
516
  patch = {
496
517
  syncAction: {
@@ -1,4 +1,5 @@
1
1
  /// <reference types="node" />
2
+ /// <reference types="node" />
2
3
  import { KeyPair } from '../Types';
3
4
  /** prefix version byte to the pub keys, required for some curve crypto functions */
4
5
  export declare const generateSignalPubKey: (pubKey: Uint8Array | Buffer) => Uint8Array | Buffer;
@@ -38,4 +39,4 @@ export declare function hkdf(buffer: Uint8Array | Buffer, expandedLength: number
38
39
  salt?: Buffer;
39
40
  info?: string;
40
41
  }): Buffer;
41
- export declare function derivePairingCodeKey(pairingCode: string, salt: Buffer): Buffer;
42
+ export declare function derivePairingCodeKey(pairingCode: string, salt: Buffer): Promise<Buffer>;
@@ -30,7 +30,9 @@ exports.derivePairingCodeKey = exports.hkdf = exports.md5 = exports.sha256 = exp
30
30
  const crypto_1 = require("crypto");
31
31
  const futoin_hkdf_1 = __importDefault(require("futoin-hkdf"));
32
32
  const libsignal = __importStar(require("libsignal"));
33
+ const util_1 = require("util");
33
34
  const Defaults_1 = require("../Defaults");
35
+ const pbkdf2Promise = (0, util_1.promisify)(crypto_1.pbkdf2);
34
36
  /** prefix version byte to the pub keys, required for some curve crypto functions */
35
37
  const generateSignalPubKey = (pubKey) => (pubKey.length === 33
36
38
  ? pubKey
@@ -145,7 +147,7 @@ function hkdf(buffer, expandedLength, info) {
145
147
  return (0, futoin_hkdf_1.default)(!Buffer.isBuffer(buffer) ? Buffer.from(buffer) : buffer, expandedLength, info);
146
148
  }
147
149
  exports.hkdf = hkdf;
148
- function derivePairingCodeKey(pairingCode, salt) {
149
- return (0, crypto_1.pbkdf2Sync)(pairingCode, salt, 2 << 16, 32, 'sha256');
150
+ async function derivePairingCodeKey(pairingCode, salt) {
151
+ return await pbkdf2Promise(pairingCode, salt, 2 << 16, 32, 'sha256');
150
152
  }
151
153
  exports.derivePairingCodeKey = derivePairingCodeKey;
@@ -2,6 +2,7 @@ import { Logger } from 'pino';
2
2
  import { proto } from '../../WAProto';
3
3
  import { SignalRepository } from '../Types';
4
4
  import { BinaryNode } from '../WABinary';
5
+ export declare const NO_MESSAGE_FOUND_ERROR_TEXT = "Message absent from node";
5
6
  /**
6
7
  * Decode the received node as a message.
7
8
  * @note this will only parse the message, not decrypt it
@@ -1,17 +1,17 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.decryptMessageNode = exports.decodeMessageNode = void 0;
3
+ exports.decryptMessageNode = exports.decodeMessageNode = exports.NO_MESSAGE_FOUND_ERROR_TEXT = void 0;
4
4
  const boom_1 = require("@hapi/boom");
5
5
  const WAProto_1 = require("../../WAProto");
6
6
  const WABinary_1 = require("../WABinary");
7
7
  const generics_1 = require("./generics");
8
- const NO_MESSAGE_FOUND_ERROR_TEXT = 'Message absent from node';
8
+ exports.NO_MESSAGE_FOUND_ERROR_TEXT = 'Message absent from node';
9
9
  /**
10
10
  * Decode the received node as a message.
11
11
  * @note this will only parse the message, not decrypt it
12
12
  */
13
13
  function decodeMessageNode(stanza, meId, meLid) {
14
- var _a, _b;
14
+ var _a, _b, _c, _d;
15
15
  let msgType;
16
16
  let chatId;
17
17
  let author;
@@ -55,6 +55,11 @@ function decodeMessageNode(stanza, meId, meLid) {
55
55
  author = participant;
56
56
  chatId = from;
57
57
  }
58
+ else if ((0, WABinary_1.isJidNewsletter)(from)) {
59
+ msgType = 'newsletter';
60
+ author = from;
61
+ chatId = from;
62
+ }
58
63
  else if ((0, WABinary_1.isJidBroadcast)(from)) {
59
64
  if (!participant) {
60
65
  throw new boom_1.Boom('No participant in group message');
@@ -69,7 +74,7 @@ function decodeMessageNode(stanza, meId, meLid) {
69
74
  chatId = from;
70
75
  author = participant;
71
76
  }
72
- else if ((0, WABinary_1.isJidNewsLetter)(from)) {
77
+ else if ((0, WABinary_1.isJidNewsletter)(from)) {
73
78
  msgType = 'newsletter';
74
79
  author = from;
75
80
  chatId = from;
@@ -77,13 +82,14 @@ function decodeMessageNode(stanza, meId, meLid) {
77
82
  else {
78
83
  throw new boom_1.Boom('Unknown message type', { data: stanza });
79
84
  }
80
- const fromMe = (0, WABinary_1.isJidNewsLetter)(from) ? !!((_a = stanza.attrs) === null || _a === void 0 ? void 0 : _a.is_sender) : ((0, WABinary_1.isLidUser)(from) ? isMeLid : isMe)(stanza.attrs.participant || stanza.attrs.from);
81
- const pushname = stanza.attrs.notify;
85
+ const fromMe = (0, WABinary_1.isJidNewsletter)(from) ? !!((_a = stanza.attrs) === null || _a === void 0 ? void 0 : _a.is_sender) || false : ((0, WABinary_1.isLidUser)(from) ? isMeLid : isMe)(stanza.attrs.participant || stanza.attrs.from);
86
+ const pushname = (_b = stanza === null || stanza === void 0 ? void 0 : stanza.attrs) === null || _b === void 0 ? void 0 : _b.notify;
82
87
  const key = {
83
88
  remoteJid: chatId,
84
89
  fromMe,
85
90
  id: msgId,
86
- participant
91
+ participant,
92
+ server_id: (_c = stanza.attrs) === null || _c === void 0 ? void 0 : _c.server_id
87
93
  };
88
94
  const fullMessage = {
89
95
  key,
@@ -92,7 +98,7 @@ function decodeMessageNode(stanza, meId, meLid) {
92
98
  broadcast: (0, WABinary_1.isJidBroadcast)(from)
93
99
  };
94
100
  if (msgType === 'newsletter') {
95
- fullMessage.newsletterServerId = +((_b = stanza.attrs) === null || _b === void 0 ? void 0 : _b.server_id);
101
+ fullMessage.newsletterServerId = +((_d = stanza.attrs) === null || _d === void 0 ? void 0 : _d.server_id);
96
102
  }
97
103
  if (key.fromMe) {
98
104
  fullMessage.status = WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK;
@@ -126,7 +132,7 @@ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
126
132
  }
127
133
  }
128
134
  }
129
- if ((0, WABinary_1.isJidNewsLetter)(fullMessage.key.remoteJid)) {
135
+ if ((0, WABinary_1.isJidNewsletter)(fullMessage.key.remoteJid)) {
130
136
  const node = (0, WABinary_1.getBinaryNodeChild)(stanza, 'plaintext');
131
137
  const msg = WAProto_1.proto.Message.decode(node === null || node === void 0 ? void 0 : node.content);
132
138
  await processSenderKeyDistribution(msg);
@@ -140,7 +146,7 @@ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
140
146
  const details = WAProto_1.proto.VerifiedNameCertificate.Details.decode(cert.details);
141
147
  fullMessage.verifiedBizName = details.verifiedName;
142
148
  }
143
- if (tag !== 'enc') {
149
+ if (tag !== 'enc' && tag !== 'plaintext') {
144
150
  continue;
145
151
  }
146
152
  if (!(content instanceof Uint8Array)) {
@@ -149,7 +155,7 @@ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
149
155
  decryptables += 1;
150
156
  let msgBuffer;
151
157
  try {
152
- const e2eType = attrs.type;
158
+ const e2eType = tag === 'plaintext' ? 'plaintext' : attrs.type;
153
159
  switch (e2eType) {
154
160
  case 'skmsg':
155
161
  msgBuffer = await repository.decryptGroupMessage({
@@ -167,12 +173,26 @@ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
167
173
  ciphertext: content
168
174
  });
169
175
  break;
176
+ case 'plaintext':
177
+ msgBuffer = content;
178
+ break;
170
179
  default:
171
180
  throw new Error(`Unknown e2e type: ${e2eType}`);
172
181
  }
173
- let msg = WAProto_1.proto.Message.decode((0, generics_1.unpadRandomMax16)(msgBuffer));
182
+ let msg = WAProto_1.proto.Message.decode(e2eType !== 'plaintext' ? (0, generics_1.unpadRandomMax16)(msgBuffer) : msgBuffer);
174
183
  msg = ((_a = msg.deviceSentMessage) === null || _a === void 0 ? void 0 : _a.message) || msg;
175
- await processSenderKeyDistribution(msg);
184
+ if (msg.senderKeyDistributionMessage) {
185
+ //eslint-disable-next-line max-depth
186
+ try {
187
+ await repository.processSenderKeyDistributionMessage({
188
+ authorJid: author,
189
+ item: msg.senderKeyDistributionMessage
190
+ });
191
+ }
192
+ catch (err) {
193
+ logger.error({ key: fullMessage.key, err }, 'failed to decrypt message');
194
+ }
195
+ }
176
196
  if (fullMessage.message) {
177
197
  Object.assign(fullMessage.message, msg);
178
198
  }
@@ -190,7 +210,7 @@ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
190
210
  // if nothing was found to decrypt
191
211
  if (!decryptables) {
192
212
  fullMessage.messageStubType = WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT;
193
- fullMessage.messageStubParameters = [NO_MESSAGE_FOUND_ERROR_TEXT, JSON.stringify(stanza, generics_1.BufferJSON.replacer)];
213
+ fullMessage.messageStubParameters = [exports.NO_MESSAGE_FOUND_ERROR_TEXT];
194
214
  }
195
215
  }
196
216
  };
@@ -138,7 +138,9 @@ const makeBufferData = () => {
138
138
  groupUpdates: {}
139
139
  };
140
140
  };
141
- function append(data, historyCache, event, eventData, logger) {
141
+ function append(data, historyCache, event,
142
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
143
+ eventData, logger) {
142
144
  var _a, _b, _c;
143
145
  switch (event) {
144
146
  case 'messaging-history.set':
@@ -176,6 +178,9 @@ function append(data, historyCache, event, eventData, logger) {
176
178
  }
177
179
  }
178
180
  data.historySets.empty = false;
181
+ data.historySets.syncType = eventData.syncType;
182
+ data.historySets.progress = eventData.progress;
183
+ data.historySets.peerDataRequestSessionId = eventData.peerDataRequestSessionId;
179
184
  data.historySets.isLatest = eventData.isLatest || data.historySets.isLatest;
180
185
  break;
181
186
  case 'chats.upsert':
@@ -442,7 +447,10 @@ function consolidateEvents(data) {
442
447
  chats: Object.values(data.historySets.chats),
443
448
  messages: Object.values(data.historySets.messages),
444
449
  contacts: Object.values(data.historySets.contacts),
445
- isLatest: data.historySets.isLatest
450
+ syncType: data.historySets.syncType,
451
+ progress: data.historySets.progress,
452
+ isLatest: data.historySets.isLatest,
453
+ peerDataRequestSessionId: data.historySets.peerDataRequestSessionId
446
454
  };
447
455
  }
448
456
  const chatUpsertList = Object.values(data.chatUpserts);
@@ -496,12 +504,10 @@ function consolidateEvents(data) {
496
504
  return map;
497
505
  }
498
506
  function concatChats(a, b) {
499
- if (b.unreadCount === null) {
500
- // neutralize unread counter
501
- if (a.unreadCount < 0) {
502
- a.unreadCount = undefined;
503
- b.unreadCount = undefined;
504
- }
507
+ if (b.unreadCount === null && // neutralize unread counter
508
+ a.unreadCount < 0) {
509
+ a.unreadCount = undefined;
510
+ b.unreadCount = undefined;
505
511
  }
506
512
  if (typeof a.unreadCount === 'number' && typeof b.unreadCount === 'number') {
507
513
  b = { ...b };