@queenanya/baileys 6.9.2 → 7.0.0

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 (59) hide show
  1. package/README.md +56 -13
  2. package/lib/Defaults/baileys-version.json +1 -1
  3. package/lib/Defaults/index.js +5 -2
  4. package/lib/Socket/business.d.ts +46 -8
  5. package/lib/Socket/business.js +1 -0
  6. package/lib/Socket/chats.d.ts +10 -2
  7. package/lib/Socket/chats.js +42 -3
  8. package/lib/Socket/groups.d.ts +17 -3
  9. package/lib/Socket/groups.js +12 -1
  10. package/lib/Socket/index.d.ts +46 -8
  11. package/lib/Socket/messages-recv.d.ts +45 -9
  12. package/lib/Socket/messages-recv.js +184 -22
  13. package/lib/Socket/messages-send.d.ts +40 -6
  14. package/lib/Socket/messages-send.js +153 -37
  15. package/lib/Socket/newsletter.d.ts +140 -0
  16. package/lib/Socket/newsletter.js +249 -0
  17. package/lib/Socket/registration.d.ts +46 -11
  18. package/lib/Socket/socket.js +18 -4
  19. package/lib/Store/make-in-memory-store.d.ts +2 -2
  20. package/lib/Store/make-in-memory-store.js +11 -44
  21. package/lib/Types/Auth.d.ts +1 -0
  22. package/lib/Types/Chat.d.ts +5 -0
  23. package/lib/Types/Events.d.ts +40 -2
  24. package/lib/Types/GroupMetadata.d.ts +3 -1
  25. package/lib/Types/Label.d.ts +11 -0
  26. package/lib/Types/Message.d.ts +39 -27
  27. package/lib/Types/Newsletter.d.ts +79 -0
  28. package/lib/Types/Newsletter.js +18 -0
  29. package/lib/Types/Socket.d.ts +7 -0
  30. package/lib/Types/index.d.ts +9 -0
  31. package/lib/Types/index.js +1 -0
  32. package/lib/Utils/auth-utils.js +1 -0
  33. package/lib/Utils/chat-utils.js +16 -0
  34. package/lib/Utils/crypto.d.ts +1 -1
  35. package/lib/Utils/crypto.js +4 -2
  36. package/lib/Utils/decode-wa-message.d.ts +1 -0
  37. package/lib/Utils/decode-wa-message.js +50 -22
  38. package/lib/Utils/generics.d.ts +30 -10
  39. package/lib/Utils/generics.js +82 -10
  40. package/lib/Utils/history.d.ts +4 -0
  41. package/lib/Utils/history.js +3 -0
  42. package/lib/Utils/logger.d.ts +1 -3
  43. package/lib/Utils/messages-media.d.ts +10 -1
  44. package/lib/Utils/messages-media.js +61 -18
  45. package/lib/Utils/messages.d.ts +2 -1
  46. package/lib/Utils/messages.js +77 -76
  47. package/lib/Utils/noise-handler.d.ts +3 -2
  48. package/lib/Utils/noise-handler.js +18 -5
  49. package/lib/Utils/process-message.d.ts +3 -2
  50. package/lib/Utils/process-message.js +53 -21
  51. package/lib/Utils/signal.js +21 -16
  52. package/lib/Utils/use-multi-file-auth-state.js +16 -3
  53. package/lib/WABinary/decode.d.ts +2 -2
  54. package/lib/WABinary/decode.js +6 -4
  55. package/lib/WABinary/encode.d.ts +1 -2
  56. package/lib/WABinary/encode.js +1 -1
  57. package/lib/WABinary/jid-utils.d.ts +3 -1
  58. package/lib/WABinary/jid-utils.js +4 -1
  59. package/package.json +32 -27
@@ -10,6 +10,17 @@ export interface Label {
10
10
  /** WhatsApp has 5 predefined labels (New customer, New order & etc) */
11
11
  predefinedId?: string;
12
12
  }
13
+ export interface LabelActionBody {
14
+ id: string;
15
+ /** Label name */
16
+ name?: string;
17
+ /** Label color ID */
18
+ color?: number;
19
+ /** Is label has been deleted */
20
+ deleted?: boolean;
21
+ /** WhatsApp has 5 predefined labels (New customer, New order & etc) */
22
+ predefinedId?: number;
23
+ }
13
24
  /** WhatsApp has 20 predefined colors */
14
25
  export declare enum LabelColor {
15
26
  Color1 = 0,
@@ -7,6 +7,7 @@ import type { Readable } from 'stream';
7
7
  import type { URL } from 'url';
8
8
  import { proto } from '../../WAProto';
9
9
  import { MEDIA_HKDF_KEY_MAPPING } from '../Defaults';
10
+ import { BinaryNode } from '../WABinary';
10
11
  import type { GroupMetadata } from './GroupMetadata';
11
12
  import { CacheStore } from './Socket';
12
13
  export { proto as WAProto };
@@ -14,7 +15,9 @@ export type WAMessage = proto.IWebMessageInfo;
14
15
  export type WAMessageContent = proto.IMessage;
15
16
  export type WAContactMessage = proto.Message.IContactMessage;
16
17
  export type WAContactsArrayMessage = proto.Message.IContactsArrayMessage;
17
- export type WAMessageKey = proto.IMessageKey;
18
+ export type WAMessageKey = proto.IMessageKey & {
19
+ server_id?: string;
20
+ };
18
21
  export type WATextMessage = proto.Message.IExtendedTextMessage;
19
22
  export type WAContextInfo = proto.IContextInfo;
20
23
  export type WALocationMessage = proto.Message.ILocationMessage;
@@ -63,26 +66,9 @@ type Contextable = {
63
66
  type ViewOnce = {
64
67
  viewOnce?: boolean;
65
68
  };
66
- type Buttonable = {
67
- /** add buttons to the message */
68
- buttons?: proto.Message.ButtonsMessage.IButton[];
69
- };
70
- type Templatable = {
71
- /** add buttons to the message (conflicts with normal buttons)*/
72
- templateButtons?: proto.IHydratedTemplateButton[];
73
- footer?: string;
74
- };
75
69
  type Editable = {
76
70
  edit?: WAMessageKey;
77
71
  };
78
- type Listable = {
79
- /** Sections of the List */
80
- sections?: proto.Message.ListMessage.ISection[];
81
- /** Title of a List Message only */
82
- title?: string;
83
- /** Text of the bnutton on the list (required) */
84
- buttonText?: string;
85
- };
86
72
  type WithDimensions = {
87
73
  width?: number;
88
74
  height?: number;
@@ -93,6 +79,7 @@ export type PollMessageOptions = {
93
79
  values: string[];
94
80
  /** 32 byte message secret to encrypt poll selections */
95
81
  messageSecret?: Uint8Array;
82
+ toAnnouncementGroup?: boolean;
96
83
  };
97
84
  type SharePhoneNumber = {
98
85
  sharePhoneNumber: boolean;
@@ -105,14 +92,14 @@ export type AnyMediaMessageContent = (({
105
92
  image: WAMediaUpload;
106
93
  caption?: string;
107
94
  jpegThumbnail?: string;
108
- } & Mentionable & Contextable & Buttonable & Templatable & WithDimensions) | ({
95
+ } & Mentionable & Contextable & WithDimensions) | ({
109
96
  video: WAMediaUpload;
110
97
  caption?: string;
111
98
  gifPlayback?: boolean;
112
99
  jpegThumbnail?: string;
113
100
  /** if set to true, will send as a `video note` */
114
101
  ptv?: boolean;
115
- } & Mentionable & Contextable & Buttonable & Templatable & WithDimensions) | {
102
+ } & Mentionable & Contextable & WithDimensions) | {
116
103
  audio: WAMediaUpload;
117
104
  /** if set to true, will send as a `voice note` */
118
105
  ptt?: boolean;
@@ -126,7 +113,7 @@ export type AnyMediaMessageContent = (({
126
113
  mimetype: string;
127
114
  fileName?: string;
128
115
  caption?: string;
129
- } & Contextable & Buttonable & Templatable)) & {
116
+ } & Contextable)) & {
130
117
  mimetype?: string;
131
118
  } & Editable;
132
119
  export type ButtonReplyInfo = {
@@ -134,15 +121,22 @@ export type ButtonReplyInfo = {
134
121
  id: string;
135
122
  index: number;
136
123
  };
124
+ export type GroupInviteInfo = {
125
+ inviteCode: string;
126
+ inviteExpiration: number;
127
+ text: string;
128
+ jid: string;
129
+ subject: string;
130
+ };
137
131
  export type WASendableProduct = Omit<proto.Message.ProductMessage.IProductSnapshot, 'productImage'> & {
138
132
  productImage: WAMediaUpload;
139
133
  };
140
134
  export type AnyRegularMessageContent = (({
141
135
  text: string;
142
136
  linkPreview?: WAUrlInfo | null;
143
- } & Mentionable & Contextable & Buttonable & Templatable & Listable & Editable) | AnyMediaMessageContent | ({
137
+ } & Mentionable & Contextable & Editable) | AnyMediaMessageContent | ({
144
138
  poll: PollMessageOptions;
145
- } & Mentionable & Contextable & Buttonable & Templatable & Editable) | {
139
+ } & Mentionable & Contextable & Editable) | {
146
140
  contacts: {
147
141
  displayName?: string;
148
142
  contacts: proto.Message.IContactMessage[];
@@ -154,8 +148,19 @@ export type AnyRegularMessageContent = (({
154
148
  } | {
155
149
  buttonReply: ButtonReplyInfo;
156
150
  type: 'template' | 'plain';
151
+ } | {
152
+ groupInvite: GroupInviteInfo;
157
153
  } | {
158
154
  listReply: Omit<proto.Message.IListResponseMessage, 'contextInfo'>;
155
+ } | {
156
+ pin: WAMessageKey;
157
+ type: proto.PinInChat.Type;
158
+ /**
159
+ * 24 hours, 7 days, 30 days
160
+ */
161
+ time?: 86400 | 604800 | 2592000;
162
+ } | {
163
+ unpin: WAMessageKey;
159
164
  } | {
160
165
  product: WASendableProduct;
161
166
  businessOwnerJid?: string;
@@ -175,8 +180,8 @@ export type GroupMetadataParticipants = Pick<GroupMetadata, 'participants'>;
175
180
  type MinimalRelayOptions = {
176
181
  /** override the message ID with a custom provided string */
177
182
  messageId?: string;
178
- /** cached group metadata, use to prevent redundant requests to WA & speed up msg sending */
179
- cachedGroupMetadata?: (jid: string) => Promise<GroupMetadataParticipants | undefined>;
183
+ /** should we use group metadata cache, or fetch afresh from the server; default assumed to be "true" */
184
+ useCachedGroupMetadata?: boolean;
180
185
  };
181
186
  export type MessageRelayOptions = MinimalRelayOptions & {
182
187
  /** only send to a specific participant; used when a message decryption fails for a single user */
@@ -188,6 +193,7 @@ export type MessageRelayOptions = MinimalRelayOptions & {
188
193
  additionalAttributes?: {
189
194
  [_: string]: string;
190
195
  };
196
+ additionalNodes?: BinaryNode[];
191
197
  /** should we use the devices cache, or fetch afresh from the server; default assumed to be "true" */
192
198
  useUserDevicesCache?: boolean;
193
199
  /** jid list of participants for status@broadcast */
@@ -214,13 +220,16 @@ export type MiscMessageGenerationOptions = MinimalRelayOptions & {
214
220
  export type MessageGenerationOptionsFromContent = MiscMessageGenerationOptions & {
215
221
  userJid: string;
216
222
  };
217
- export type WAMediaUploadFunction = (readStream: Readable, opts: {
223
+ export type WAMediaUploadFunctionOpts = {
218
224
  fileEncSha256B64: string;
219
225
  mediaType: MediaType;
226
+ newsletter?: boolean;
220
227
  timeoutMs?: number;
221
- }) => Promise<{
228
+ };
229
+ export type WAMediaUploadFunction = (readStream: Readable | Buffer, opts: WAMediaUploadFunctionOpts) => Promise<{
222
230
  mediaUrl: string;
223
231
  directPath: string;
232
+ handle?: string;
224
233
  }>;
225
234
  export type MediaGenerationOptions = {
226
235
  logger?: Logger;
@@ -231,10 +240,13 @@ export type MediaGenerationOptions = {
231
240
  mediaUploadTimeoutMs?: number;
232
241
  options?: AxiosRequestConfig;
233
242
  backgroundColor?: string;
243
+ /** The message is for newsletter? */
244
+ newsletter?: boolean;
234
245
  font?: number;
235
246
  };
236
247
  export type MessageContentGenerationOptions = MediaGenerationOptions & {
237
248
  getUrlInfo?: (text: string) => Promise<WAUrlInfo | undefined>;
249
+ getProfilePicUrl?: (jid: string, type: 'image' | 'preview') => Promise<string | undefined>;
238
250
  };
239
251
  export type MessageGenerationOptions = MessageContentGenerationOptions & MessageGenerationOptionsFromContent;
240
252
  /**
@@ -0,0 +1,79 @@
1
+ import { proto } from '../../WAProto';
2
+ export type NewsletterReactionMode = 'ALL' | 'BASIC' | 'NONE';
3
+ export type NewsletterState = 'ACTIVE' | 'GEOSUSPENDED' | 'SUSPENDED';
4
+ export type NewsletterVerification = 'VERIFIED' | 'UNVERIFIED';
5
+ export type NewsletterMute = 'ON' | 'OFF' | 'UNDEFINED';
6
+ export type NewsletterViewRole = 'ADMIN' | 'GUEST' | 'OWNER' | 'SUBSCRIBER';
7
+ export type NewsletterViewerMetadata = {
8
+ mute: NewsletterMute;
9
+ view_role: NewsletterViewRole;
10
+ };
11
+ export type NewsletterMetadata = {
12
+ /**jid of newsletter */
13
+ id: string;
14
+ /**state of newsletter */
15
+ state: NewsletterState;
16
+ /**creation timestamp of newsletter */
17
+ creation_time: number;
18
+ /**name of newsletter */
19
+ name: string;
20
+ /**timestamp of last name modification of newsletter */
21
+ nameTime: number;
22
+ /**description of newsletter */
23
+ description: string;
24
+ /**timestamp of last description modification of newsletter */
25
+ descriptionTime: number;
26
+ /**invite code of newsletter */
27
+ invite: string;
28
+ /**i dont know */
29
+ handle: null;
30
+ /**direct path of picture */
31
+ picture: string | null;
32
+ /**direct path of picture preview (lower quality) */
33
+ preview: string | null;
34
+ /**reaction mode of newsletter */
35
+ reaction_codes?: NewsletterReactionMode;
36
+ /**subscribers count of newsletter */
37
+ subscribers: number;
38
+ /**verification state of newsletter */
39
+ verification: NewsletterVerification;
40
+ /**viewer metadata */
41
+ viewer_metadata: NewsletterViewerMetadata;
42
+ };
43
+ export type SubscriberAction = 'promote' | 'demote';
44
+ export type ReactionModeUpdate = {
45
+ reaction_codes: {
46
+ blocked_codes: null;
47
+ enabled_ts_sec: null;
48
+ value: NewsletterReactionMode;
49
+ };
50
+ };
51
+ /**only exists reaction mode update */
52
+ export type NewsletterSettingsUpdate = ReactionModeUpdate;
53
+ export type NewsletterReaction = {
54
+ count: number;
55
+ code: string;
56
+ };
57
+ export type NewsletterFetchedUpdate = {
58
+ /**id of message in newsletter, starts from 100 */
59
+ server_id: string;
60
+ /**count of views in this message */
61
+ views?: number;
62
+ /**reactions in this message */
63
+ reactions: NewsletterReaction[];
64
+ /**the message, if you requested only updates, you will not receive message */
65
+ message?: proto.IWebMessageInfo;
66
+ };
67
+ export declare enum MexOperations {
68
+ PROMOTE = "NotificationNewsletterAdminPromote",
69
+ DEMOTE = "NotificationNewsletterAdminDemote",
70
+ UPDATE = "NotificationNewsletterUpdate"
71
+ }
72
+ export declare enum XWAPaths {
73
+ PROMOTE = "xwa2_notify_newsletter_admin_promote",
74
+ DEMOTE = "xwa2_notify_newsletter_admin_demote",
75
+ ADMIN_COUNT = "xwa2_newsletter_admin",
76
+ CREATE = "xwa2_newsletter_create",
77
+ NEWSLETTER = "xwa2_newsletter",
78
+ METADATA_UPDATE = "xwa2_notify_newsletter_on_metadata_update"
79
+ }
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.XWAPaths = exports.MexOperations = void 0;
4
+ var MexOperations;
5
+ (function (MexOperations) {
6
+ MexOperations["PROMOTE"] = "NotificationNewsletterAdminPromote";
7
+ MexOperations["DEMOTE"] = "NotificationNewsletterAdminDemote";
8
+ MexOperations["UPDATE"] = "NotificationNewsletterUpdate";
9
+ })(MexOperations = exports.MexOperations || (exports.MexOperations = {}));
10
+ var XWAPaths;
11
+ (function (XWAPaths) {
12
+ XWAPaths["PROMOTE"] = "xwa2_notify_newsletter_admin_promote";
13
+ XWAPaths["DEMOTE"] = "xwa2_notify_newsletter_admin_demote";
14
+ XWAPaths["ADMIN_COUNT"] = "xwa2_newsletter_admin";
15
+ XWAPaths["CREATE"] = "xwa2_newsletter_create";
16
+ XWAPaths["NEWSLETTER"] = "xwa2_newsletter";
17
+ XWAPaths["METADATA_UPDATE"] = "xwa2_notify_newsletter_on_metadata_update";
18
+ })(XWAPaths = exports.XWAPaths || (exports.XWAPaths = {}));
@@ -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];
@@ -71,10 +72,14 @@ export type SocketConfig = {
71
72
  userDevicesCache?: CacheStore;
72
73
  /** cache to store call offers */
73
74
  callOfferCache?: CacheStore;
75
+ /** cache to track placeholder resends */
76
+ placeholderResendCache?: CacheStore;
74
77
  /** width for link preview images */
75
78
  linkPreviewImageThumbnailWidth: number;
76
79
  /** Should Baileys ask the phone for full history, will be received async */
77
80
  syncFullHistory: boolean;
81
+ /** Ignore Message when offline, default is false */
82
+ ignoreMsgLoading: boolean;
78
83
  /** Should baileys fire init queries automatically, default true */
79
84
  fireInitQueries: boolean;
80
85
  /**
@@ -105,6 +110,8 @@ export type SocketConfig = {
105
110
  * (solves the "this message can take a while" issue) can be retried
106
111
  * */
107
112
  getMessage: (key: proto.IMessageKey) => Promise<proto.IMessage | undefined>;
113
+ /** cached group metadata, use to prevent redundant requests to WA & speed up msg sending */
114
+ cachedGroupMetadata: (jid: string) => Promise<GroupMetadata | undefined>;
108
115
  makeSignalRepository: (auth: SignalAuthState) => SignalRepository;
109
116
  /** Socket passthrough */
110
117
  socket?: any;
@@ -4,6 +4,7 @@ export * from './Chat';
4
4
  export * from './Contact';
5
5
  export * from './State';
6
6
  export * from './Message';
7
+ export * from './Newsletter';
7
8
  export * from './Socket';
8
9
  export * from './Events';
9
10
  export * from './Product';
@@ -14,6 +15,14 @@ import { SocketConfig } from './Socket';
14
15
  export type UserFacingSocketConfig = Partial<SocketConfig> & {
15
16
  auth: AuthenticationState;
16
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
+ };
17
26
  export declare enum DisconnectReason {
18
27
  connectionClosed = 428,
19
28
  connectionLost = 408,
@@ -21,6 +21,7 @@ __exportStar(require("./Chat"), exports);
21
21
  __exportStar(require("./Contact"), exports);
22
22
  __exportStar(require("./State"), exports);
23
23
  __exportStar(require("./Message"), exports);
24
+ __exportStar(require("./Newsletter"), exports);
24
25
  __exportStar(require("./Socket"), exports);
25
26
  __exportStar(require("./Events"), exports);
26
27
  __exportStar(require("./Product"), exports);
@@ -200,6 +200,7 @@ const initAuthCreds = () => {
200
200
  registration: {},
201
201
  pairingCode: undefined,
202
202
  lastPropHash: undefined,
203
+ routingInfo: undefined,
203
204
  };
204
205
  };
205
206
  exports.initAuthCreds = initAuthCreds;
@@ -491,6 +491,22 @@ const chatModificationToAppPatch = (mod, jid) => {
491
491
  operation: OP.SET,
492
492
  };
493
493
  }
494
+ else if ('addLabel' in mod) {
495
+ patch = {
496
+ syncAction: {
497
+ labelEditAction: {
498
+ name: mod.addLabel.name,
499
+ color: mod.addLabel.color,
500
+ predefinedId: mod.addLabel.predefinedId,
501
+ deleted: mod.addLabel.deleted
502
+ }
503
+ },
504
+ index: ['label_edit', mod.addLabel.id],
505
+ type: 'regular',
506
+ apiVersion: 3,
507
+ operation: OP.SET,
508
+ };
509
+ }
494
510
  else if ('addChatLabel' in mod) {
495
511
  patch = {
496
512
  syncAction: {
@@ -38,4 +38,4 @@ export declare function hkdf(buffer: Uint8Array | Buffer, expandedLength: number
38
38
  salt?: Buffer;
39
39
  info?: string;
40
40
  }): Buffer;
41
- export declare function derivePairingCodeKey(pairingCode: string, salt: Buffer): Buffer;
41
+ 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,16 +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, _c, _d;
14
15
  let msgType;
15
16
  let chatId;
16
17
  let author;
@@ -54,6 +55,11 @@ function decodeMessageNode(stanza, meId, meLid) {
54
55
  author = participant;
55
56
  chatId = from;
56
57
  }
58
+ else if ((0, WABinary_1.isJidNewsletter)(from)) {
59
+ msgType = 'newsletter';
60
+ author = from;
61
+ chatId = from;
62
+ }
57
63
  else if ((0, WABinary_1.isJidBroadcast)(from)) {
58
64
  if (!participant) {
59
65
  throw new boom_1.Boom('No participant in group message');
@@ -68,16 +74,22 @@ function decodeMessageNode(stanza, meId, meLid) {
68
74
  chatId = from;
69
75
  author = participant;
70
76
  }
77
+ else if ((0, WABinary_1.isJidNewsletter)(from)) {
78
+ msgType = 'newsletter';
79
+ author = from;
80
+ chatId = from;
81
+ }
71
82
  else {
72
83
  throw new boom_1.Boom('Unknown message type', { data: stanza });
73
84
  }
74
- const fromMe = ((0, WABinary_1.isLidUser)(from) ? isMeLid : isMe)(stanza.attrs.participant || stanza.attrs.from);
75
- 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;
76
87
  const key = {
77
88
  remoteJid: chatId,
78
89
  fromMe,
79
90
  id: msgId,
80
- participant
91
+ participant,
92
+ server_id: (_c = stanza.attrs) === null || _c === void 0 ? void 0 : _c.server_id
81
93
  };
82
94
  const fullMessage = {
83
95
  key,
@@ -85,6 +97,9 @@ function decodeMessageNode(stanza, meId, meLid) {
85
97
  pushName: pushname,
86
98
  broadcast: (0, WABinary_1.isJidBroadcast)(from)
87
99
  };
100
+ if (msgType === 'newsletter') {
101
+ fullMessage.newsletterServerId = +((_d = stanza.attrs) === null || _d === void 0 ? void 0 : _d.server_id);
102
+ }
88
103
  if (key.fromMe) {
89
104
  fullMessage.status = WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK;
90
105
  }
@@ -104,14 +119,34 @@ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
104
119
  async decrypt() {
105
120
  var _a;
106
121
  let decryptables = 0;
107
- if (Array.isArray(stanza.content)) {
122
+ async function processSenderKeyDistribution(msg) {
123
+ if (msg.senderKeyDistributionMessage) {
124
+ try {
125
+ await repository.processSenderKeyDistributionMessage({
126
+ authorJid: author,
127
+ item: msg.senderKeyDistributionMessage
128
+ });
129
+ }
130
+ catch (err) {
131
+ logger.error({ key: fullMessage.key, err }, 'failed to process senderKeyDistribution');
132
+ }
133
+ }
134
+ }
135
+ if ((0, WABinary_1.isJidNewsletter)(fullMessage.key.remoteJid)) {
136
+ const node = (0, WABinary_1.getBinaryNodeChild)(stanza, 'plaintext');
137
+ const msg = WAProto_1.proto.Message.decode(node === null || node === void 0 ? void 0 : node.content);
138
+ await processSenderKeyDistribution(msg);
139
+ fullMessage.message = msg;
140
+ decryptables += 1;
141
+ }
142
+ else if (Array.isArray(stanza.content)) {
108
143
  for (const { tag, attrs, content } of stanza.content) {
109
144
  if (tag === 'verified_name' && content instanceof Uint8Array) {
110
145
  const cert = WAProto_1.proto.VerifiedNameCertificate.decode(content);
111
146
  const details = WAProto_1.proto.VerifiedNameCertificate.Details.decode(cert.details);
112
147
  fullMessage.verifiedBizName = details.verifiedName;
113
148
  }
114
- if (tag !== 'enc') {
149
+ if (tag !== 'enc' && tag !== 'plaintext') {
115
150
  continue;
116
151
  }
117
152
  if (!(content instanceof Uint8Array)) {
@@ -120,7 +155,7 @@ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
120
155
  decryptables += 1;
121
156
  let msgBuffer;
122
157
  try {
123
- const e2eType = attrs.type;
158
+ const e2eType = tag === 'plaintext' ? 'plaintext' : attrs.type;
124
159
  switch (e2eType) {
125
160
  case 'skmsg':
126
161
  msgBuffer = await repository.decryptGroupMessage({
@@ -138,22 +173,15 @@ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
138
173
  ciphertext: content
139
174
  });
140
175
  break;
176
+ case 'plaintext':
177
+ msgBuffer = content;
178
+ break;
141
179
  default:
142
180
  throw new Error(`Unknown e2e type: ${e2eType}`);
143
181
  }
144
- let msg = WAProto_1.proto.Message.decode((0, generics_1.unpadRandomMax16)(msgBuffer));
145
- msg = ((_a = msg.deviceSentMessage) === null || _a === void 0 ? void 0 : _a.message) || msg;
146
- if (msg.senderKeyDistributionMessage) {
147
- try {
148
- await repository.processSenderKeyDistributionMessage({
149
- authorJid: author,
150
- item: msg.senderKeyDistributionMessage
151
- });
152
- }
153
- catch (err) {
154
- logger.error({ key: fullMessage.key, err }, 'failed to decrypt message');
155
- }
156
- }
182
+ let msg = WAProto_1.proto.Message.decode(tag === 'plaintext' ? msgBuffer : (0, generics_1.unpadRandomMax16)(msgBuffer));
183
+ msg = ((_a = msg === null || msg === void 0 ? void 0 : msg.deviceSentMessage) === null || _a === void 0 ? void 0 : _a.message) || msg;
184
+ await processSenderKeyDistribution(msg);
157
185
  if (fullMessage.message) {
158
186
  Object.assign(fullMessage.message, msg);
159
187
  }
@@ -171,7 +199,7 @@ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
171
199
  // if nothing was found to decrypt
172
200
  if (!decryptables) {
173
201
  fullMessage.messageStubType = WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT;
174
- fullMessage.messageStubParameters = [NO_MESSAGE_FOUND_ERROR_TEXT, JSON.stringify(stanza, generics_1.BufferJSON.replacer)];
202
+ fullMessage.messageStubParameters = [exports.NO_MESSAGE_FOUND_ERROR_TEXT];
175
203
  }
176
204
  }
177
205
  };
@@ -2,16 +2,20 @@
2
2
  import { AxiosRequestConfig } from 'axios';
3
3
  import { Logger } from 'pino';
4
4
  import { proto } from '../../WAProto';
5
- import { BaileysEventEmitter, BaileysEventMap, WACallUpdateType, WAVersion } from '../Types';
5
+ import { BaileysEventEmitter, BaileysEventMap, BrowsersMap, WACallUpdateType, WAVersion } from '../Types';
6
6
  import { BinaryNode } from '../WABinary';
7
- export declare const Browsers: {
8
- ubuntu: (browser: any) => [string, string, string];
9
- macOS: (browser: any) => [string, string, string];
10
- baileys: (browser: any) => [string, string, string];
11
- windows: (browser: any) => [string, string, string];
12
- /** The appropriate browser based on your OS & release */
13
- appropriate: (browser: any) => [string, string, string];
14
- };
7
+ /**
8
+ const COMPANION_PLATFORM_MAP = {
9
+ 'Chrome': '49',
10
+ 'Edge': '50',
11
+ 'Firefox': '51',
12
+ 'Opera': '53',
13
+ 'Safari': '54'
14
+ }
15
+ */
16
+ export declare const Browsers: BrowsersMap;
17
+ /** Other Browser Support for Paircode */
18
+ export declare const getPlatformId: (browser: string) => any;
15
19
  export declare const BufferJSON: {
16
20
  replacer: (k: any, value: any) => any;
17
21
  reviver: (_: any, value: any) => any;
@@ -20,6 +24,7 @@ export declare const getKeyAuthor: (key: proto.IMessageKey | undefined | null, m
20
24
  export declare const writeRandomPadMax16: (msg: Uint8Array) => Buffer;
21
25
  export declare const unpadRandomMax16: (e: Uint8Array | Buffer) => Uint8Array;
22
26
  export declare const encodeWAMessage: (message: proto.IMessage) => Buffer;
27
+ export declare const encodeNewsletterMessage: (message: proto.IMessage) => Uint8Array;
23
28
  export declare const generateRegistrationId: () => number;
24
29
  export declare const encodeBigEndian: (e: number, t?: number) => Uint8Array;
25
30
  export declare const toNumber: (t: Long | number | null | undefined) => number;
@@ -38,15 +43,30 @@ export declare const delayCancellable: (ms: number) => {
38
43
  cancel: () => void;
39
44
  };
40
45
  export declare function promiseTimeout<T>(ms: number | undefined, promise: (resolve: (v: T) => void, reject: (error: any) => void) => void): Promise<T>;
46
+ export declare const generateMessageIDV2: (userId?: string) => string;
47
+ export declare const generateMessageIDV3: (userId?: string) => string;
41
48
  export declare const generateMessageID: () => string;
42
49
  export declare function bindWaitForEvent<T extends keyof BaileysEventMap>(ev: BaileysEventEmitter, event: T): (check: (u: BaileysEventMap[T]) => boolean | undefined, timeoutMs?: number) => Promise<void>;
43
50
  export declare const bindWaitForConnectionUpdate: (ev: BaileysEventEmitter) => (check: (u: Partial<import("../Types").ConnectionState>) => boolean | undefined, timeoutMs?: number) => Promise<void>;
44
51
  export declare const printQRIfNecessaryListener: (ev: BaileysEventEmitter, logger: Logger) => void;
45
52
  /**
46
- * utility that fetches latest baileys version from the master branch.
53
+ * utility that fetches latest baileys version from the main branch.
47
54
  * Use to ensure your WA connection is always on the latest version
48
55
  */
49
56
  export declare const fetchLatestBaileysVersion: (options?: AxiosRequestConfig<any>) => Promise<{
57
+ version: number[];
58
+ isLatest: boolean;
59
+ error?: undefined;
60
+ } | {
61
+ version: WAVersion;
62
+ isLatest: boolean;
63
+ error: any;
64
+ }>;
65
+ /**
66
+ * utility that fetches latest baileys version from the master branch.
67
+ * Use to ensure your WA connection is always on the latest version
68
+ */
69
+ export declare const fetchLatestBaileysVersion2: (options?: AxiosRequestConfig<any>) => Promise<{
50
70
  version: WAVersion;
51
71
  isLatest: boolean;
52
72
  error?: undefined;