@genuxofficial/baileys 2.0.0 → 4.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 (108) hide show
  1. package/WAProto/WAProto.proto +4451 -0
  2. package/WAProto/index.d.ts +219 -2233
  3. package/WAProto/index.js +525 -6773
  4. package/WAProto/shizo.x +1 -0
  5. package/engine-requirements.js +1 -1
  6. package/lib/Defaults/baileys-version.json +1 -1
  7. package/lib/Defaults/index.d.ts +236 -3
  8. package/lib/Defaults/index.js +24 -8
  9. package/lib/Defaults/phonenumber-mcc.json +223 -0
  10. package/lib/Signal/libsignal.js +9 -18
  11. package/lib/Socket/Client/{types.d.ts → abstract-socket-client.d.ts} +2 -0
  12. package/lib/Socket/Client/index.d.ts +3 -2
  13. package/lib/Socket/Client/index.js +3 -2
  14. package/lib/Socket/Client/mobile-socket-client.d.ts +13 -0
  15. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  16. package/lib/Socket/Client/{websocket.d.ts → web-socket-client.d.ts} +1 -1
  17. package/lib/Socket/Client/{websocket.js → web-socket-client.js} +3 -3
  18. package/lib/Socket/business.d.ts +43 -43
  19. package/lib/Socket/chats.d.ts +17 -23
  20. package/lib/Socket/chats.js +9 -123
  21. package/lib/Socket/groups.d.ts +27 -32
  22. package/lib/Socket/groups.js +5 -18
  23. package/lib/Socket/index.d.ts +51 -49
  24. package/lib/Socket/index.js +2 -2
  25. package/lib/Socket/messages-recv.d.ts +41 -42
  26. package/lib/Socket/messages-recv.js +20 -39
  27. package/lib/Socket/messages-send.d.ts +33 -38
  28. package/lib/Socket/messages-send.js +16 -37
  29. package/lib/Socket/newsletter.d.ts +30 -35
  30. package/lib/Socket/newsletter.js +22 -26
  31. package/lib/Socket/registration.d.ts +271 -0
  32. package/lib/Socket/registration.js +166 -0
  33. package/lib/Socket/socket.d.ts +10 -9
  34. package/lib/Socket/socket.js +19 -16
  35. package/lib/Socket/usync.d.ts +12 -10
  36. package/lib/Socket/usync.js +15 -10
  37. package/lib/Store/index.d.ts +2 -1
  38. package/lib/Store/index.js +3 -1
  39. package/lib/Store/make-in-memory-store.d.ts +1 -1
  40. package/lib/Store/make-in-memory-store.js +10 -8
  41. package/lib/Store/make-ordered-dictionary.d.ts +1 -1
  42. package/lib/Store/make-ordered-dictionary.js +2 -2
  43. package/lib/Types/Auth.d.ts +8 -0
  44. package/lib/Types/Chat.d.ts +2 -12
  45. package/lib/Types/Contact.d.ts +1 -6
  46. package/lib/Types/GroupMetadata.d.ts +0 -7
  47. package/lib/Types/Label.d.ts +0 -11
  48. package/lib/Types/Label.js +1 -1
  49. package/lib/Types/LabelAssociation.js +1 -1
  50. package/lib/Types/Message.d.ts +8 -7
  51. package/lib/Types/Message.js +2 -0
  52. package/lib/Types/Newsletter.js +2 -2
  53. package/lib/Types/Socket.d.ts +6 -7
  54. package/lib/Types/index.js +1 -1
  55. package/lib/Utils/auth-utils.d.ts +1 -1
  56. package/lib/Utils/auth-utils.js +12 -5
  57. package/lib/Utils/business.js +2 -2
  58. package/lib/Utils/chat-utils.d.ts +13 -11
  59. package/lib/Utils/chat-utils.js +2 -28
  60. package/lib/Utils/crypto.d.ts +16 -14
  61. package/lib/Utils/crypto.js +22 -34
  62. package/lib/Utils/decode-wa-message.d.ts +2 -4
  63. package/lib/Utils/decode-wa-message.js +24 -160
  64. package/lib/Utils/event-buffer.js +6 -4
  65. package/lib/Utils/generics.d.ts +12 -40
  66. package/lib/Utils/generics.js +25 -103
  67. package/lib/Utils/link-preview.js +1 -34
  68. package/lib/Utils/lt-hash.d.ts +3 -3
  69. package/lib/Utils/lt-hash.js +45 -11
  70. package/lib/Utils/make-mutex.d.ts +2 -2
  71. package/lib/Utils/messages-media.d.ts +16 -26
  72. package/lib/Utils/messages-media.js +26 -102
  73. package/lib/Utils/messages.d.ts +8 -5
  74. package/lib/Utils/messages.js +15 -17
  75. package/lib/Utils/noise-handler.d.ts +8 -5
  76. package/lib/Utils/noise-handler.js +10 -5
  77. package/lib/Utils/process-message.js +2 -2
  78. package/lib/Utils/use-multi-file-auth-state.js +11 -48
  79. package/lib/Utils/validate-connection.d.ts +3 -2
  80. package/lib/Utils/validate-connection.js +44 -10
  81. package/lib/WABinary/constants.js +5 -5
  82. package/lib/WABinary/decode.d.ts +4 -2
  83. package/lib/WABinary/decode.js +7 -17
  84. package/lib/WABinary/encode.d.ts +3 -1
  85. package/lib/WABinary/encode.js +17 -40
  86. package/lib/WABinary/generic-utils.d.ts +3 -1
  87. package/lib/WABinary/generic-utils.js +2 -2
  88. package/lib/WABinary/jid-utils.d.ts +3 -8
  89. package/lib/WABinary/jid-utils.js +2 -23
  90. package/lib/WAM/BinaryInfo.d.ts +12 -2
  91. package/lib/WAM/constants.d.ts +2 -3
  92. package/lib/WAM/encode.d.ts +3 -1
  93. package/lib/WAM/encode.js +2 -2
  94. package/lib/WAUSync/Protocols/USyncContactProtocol.js +2 -2
  95. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +2 -2
  96. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +2 -2
  97. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +5 -5
  98. package/lib/WAUSync/USyncQuery.d.ts +0 -2
  99. package/lib/WAUSync/USyncQuery.js +13 -27
  100. package/lib/WAUSync/USyncUser.d.ts +0 -2
  101. package/lib/WAUSync/USyncUser.js +0 -4
  102. package/package.json +60 -55
  103. package/LICENSE +0 -21
  104. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +0 -25
  105. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +0 -53
  106. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +0 -8
  107. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +0 -24
  108. /package/lib/Socket/Client/{types.js → abstract-socket-client.js} +0 -0
@@ -0,0 +1,166 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.mobileRegisterFetch = exports.mobileRegisterEncrypt = exports.mobileRegister = exports.mobileRegisterExists = exports.mobileRegisterCode = exports.registrationParams = exports.makeRegistrationSocket = void 0;
7
+ /* eslint-disable camelcase */
8
+ const axios_1 = __importDefault(require("axios"));
9
+ const Defaults_1 = require("../Defaults");
10
+ const crypto_1 = require("../Utils/crypto");
11
+ const WABinary_1 = require("../WABinary");
12
+ const business_1 = require("./business");
13
+ function urlencode(str) {
14
+ return str.replace(/-/g, '%2d').replace(/_/g, '%5f').replace(/~/g, '%7e');
15
+ }
16
+ const validRegistrationOptions = (config) => (config === null || config === void 0 ? void 0 : config.phoneNumberCountryCode) &&
17
+ config.phoneNumberNationalNumber &&
18
+ config.phoneNumberMobileCountryCode;
19
+ const makeRegistrationSocket = (config) => {
20
+ const sock = (0, business_1.makeBusinessSocket)(config);
21
+ const register = async (code) => {
22
+ if (!validRegistrationOptions(config.auth.creds.registration)) {
23
+ throw new Error('please specify the registration options');
24
+ }
25
+ const result = await mobileRegister({ ...sock.authState.creds, ...sock.authState.creds.registration, code }, config.options);
26
+ sock.authState.creds.me = {
27
+ id: (0, WABinary_1.jidEncode)(result.login, 's.whatsapp.net'),
28
+ name: '~'
29
+ };
30
+ sock.authState.creds.registered = true;
31
+ sock.ev.emit('creds.update', sock.authState.creds);
32
+ return result;
33
+ };
34
+ const requestRegistrationCode = async (registrationOptions) => {
35
+ registrationOptions = registrationOptions || config.auth.creds.registration;
36
+ if (!validRegistrationOptions(registrationOptions)) {
37
+ throw new Error('Invalid registration options');
38
+ }
39
+ sock.authState.creds.registration = registrationOptions;
40
+ sock.ev.emit('creds.update', sock.authState.creds);
41
+ return mobileRegisterCode({ ...config.auth.creds, ...registrationOptions }, config.options);
42
+ };
43
+ return {
44
+ ...sock,
45
+ register,
46
+ requestRegistrationCode,
47
+ };
48
+ };
49
+ exports.makeRegistrationSocket = makeRegistrationSocket;
50
+ function convertBufferToUrlHex(buffer) {
51
+ var id = '';
52
+ buffer.forEach((x) => {
53
+ // encode random identity_id buffer as percentage url encoding
54
+ id += `%${x.toString(16).padStart(2, '0').toLowerCase()}`;
55
+ });
56
+ return id;
57
+ }
58
+ function registrationParams(params) {
59
+ const e_regid = Buffer.alloc(4);
60
+ e_regid.writeInt32BE(params.registrationId);
61
+ const e_skey_id = Buffer.alloc(3);
62
+ e_skey_id.writeInt16BE(params.signedPreKey.keyId);
63
+ params.phoneNumberCountryCode = params.phoneNumberCountryCode.replace('+', '').trim();
64
+ params.phoneNumberNationalNumber = params.phoneNumberNationalNumber.replace(/[/-\s)(]/g, '').trim();
65
+ return {
66
+ cc: params.phoneNumberCountryCode,
67
+ in: params.phoneNumberNationalNumber,
68
+ Rc: '0',
69
+ lg: 'en',
70
+ lc: 'GB',
71
+ mistyped: '6',
72
+ authkey: Buffer.from(params.noiseKey.public).toString('base64url'),
73
+ e_regid: e_regid.toString('base64url'),
74
+ e_keytype: 'BQ',
75
+ e_ident: Buffer.from(params.signedIdentityKey.public).toString('base64url'),
76
+ // e_skey_id: e_skey_id.toString('base64url'),
77
+ e_skey_id: 'AAAA',
78
+ e_skey_val: Buffer.from(params.signedPreKey.keyPair.public).toString('base64url'),
79
+ e_skey_sig: Buffer.from(params.signedPreKey.signature).toString('base64url'),
80
+ fdid: params.phoneId,
81
+ network_ratio_type: '1',
82
+ expid: params.deviceId,
83
+ simnum: '1',
84
+ hasinrc: '1',
85
+ pid: Math.floor(Math.random() * 1000).toString(),
86
+ id: convertBufferToUrlHex(params.identityId),
87
+ backup_token: convertBufferToUrlHex(params.backupToken),
88
+ token: (0, crypto_1.md5)(Buffer.concat([Defaults_1.MOBILE_TOKEN, Buffer.from(params.phoneNumberNationalNumber)])).toString('hex'),
89
+ fraud_checkpoint_code: params.captcha,
90
+ };
91
+ }
92
+ exports.registrationParams = registrationParams;
93
+ /**
94
+ * Requests a registration code for the given phone number.
95
+ */
96
+ function mobileRegisterCode(params, fetchOptions) {
97
+ return mobileRegisterFetch('/code', {
98
+ params: {
99
+ ...registrationParams(params),
100
+ mcc: `${params.phoneNumberMobileCountryCode}`.padStart(3, '0'),
101
+ mnc: `${params.phoneNumberMobileNetworkCode || '001'}`.padStart(3, '0'),
102
+ sim_mcc: '000',
103
+ sim_mnc: '000',
104
+ method: (params === null || params === void 0 ? void 0 : params.method) || 'sms',
105
+ reason: '',
106
+ hasav: '1'
107
+ },
108
+ ...fetchOptions,
109
+ });
110
+ }
111
+ exports.mobileRegisterCode = mobileRegisterCode;
112
+ function mobileRegisterExists(params, fetchOptions) {
113
+ return mobileRegisterFetch('/exist', {
114
+ params: registrationParams(params),
115
+ ...fetchOptions
116
+ });
117
+ }
118
+ exports.mobileRegisterExists = mobileRegisterExists;
119
+ /**
120
+ * Registers the phone number on whatsapp with the received OTP code.
121
+ */
122
+ async function mobileRegister(params, fetchOptions) {
123
+ //const result = await mobileRegisterFetch(`/reg_onboard_abprop?cc=${params.phoneNumberCountryCode}&in=${params.phoneNumberNationalNumber}&rc=0`)
124
+ return mobileRegisterFetch('/register', {
125
+ params: { ...registrationParams(params), code: params.code.replace('-', '') },
126
+ ...fetchOptions,
127
+ });
128
+ }
129
+ exports.mobileRegister = mobileRegister;
130
+ /**
131
+ * Encrypts the given string as AEAD aes-256-gcm with the public whatsapp key and a random keypair.
132
+ */
133
+ function mobileRegisterEncrypt(data) {
134
+ const keypair = crypto_1.Curve.generateKeyPair();
135
+ const key = crypto_1.Curve.sharedKey(keypair.private, Defaults_1.REGISTRATION_PUBLIC_KEY);
136
+ const buffer = (0, crypto_1.aesEncryptGCM)(Buffer.from(data), new Uint8Array(key), Buffer.alloc(12), Buffer.alloc(0));
137
+ return Buffer.concat([Buffer.from(keypair.public), buffer]).toString('base64url');
138
+ }
139
+ exports.mobileRegisterEncrypt = mobileRegisterEncrypt;
140
+ async function mobileRegisterFetch(path, opts = {}) {
141
+ let url = `${Defaults_1.MOBILE_REGISTRATION_ENDPOINT}${path}`;
142
+ if (opts.params) {
143
+ const parameter = [];
144
+ for (const param in opts.params) {
145
+ if (opts.params[param] !== null && opts.params[param] !== undefined) {
146
+ parameter.push(param + '=' + urlencode(opts.params[param]));
147
+ }
148
+ }
149
+ url += `?${parameter.join('&')}`;
150
+ delete opts.params;
151
+ }
152
+ if (!opts.headers) {
153
+ opts.headers = {};
154
+ }
155
+ opts.headers['User-Agent'] = Defaults_1.MOBILE_USERAGENT;
156
+ const response = await (0, axios_1.default)(url, opts);
157
+ var json = response.data;
158
+ if (response.status > 300 || json.reason) {
159
+ throw json;
160
+ }
161
+ if (json.status && !['ok', 'sent'].includes(json.status)) {
162
+ throw json;
163
+ }
164
+ return json;
165
+ }
166
+ exports.mobileRegisterFetch = mobileRegisterFetch;
@@ -1,7 +1,8 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
1
3
  import { Boom } from '@hapi/boom';
2
4
  import { SocketConfig } from '../Types';
3
5
  import { BinaryNode } from '../WABinary';
4
- import { WebSocketClient } from './Client';
5
6
  /**
6
7
  * Connects to WA servers and performs:
7
8
  * - simple queries (no retry mechanism, wait for connection establishment)
@@ -10,12 +11,12 @@ import { WebSocketClient } from './Client';
10
11
  */
11
12
  export declare const makeSocket: (config: SocketConfig) => {
12
13
  type: "md";
13
- ws: WebSocketClient;
14
+ ws: any;
14
15
  ev: import("../Types").BaileysEventEmitter & {
15
- process(handler: (events: Partial<import("../Types").BaileysEventMap>) => void | Promise<void>): (() => void);
16
+ process(handler: (events: Partial<import("../Types").BaileysEventMap>) => void | Promise<void>): () => void;
16
17
  buffer(): void;
17
- createBufferedFunction<A extends any[], T>(work: (...args: A) => Promise<T>): ((...args: A) => Promise<T>);
18
- flush(force?: boolean): boolean;
18
+ createBufferedFunction<A extends any[], T>(work: (...args: A) => Promise<T>): (...args: A) => Promise<T>;
19
+ flush(force?: boolean | undefined): boolean;
19
20
  isBuffering(): boolean;
20
21
  };
21
22
  authState: {
@@ -25,8 +26,8 @@ export declare const makeSocket: (config: SocketConfig) => {
25
26
  signalRepository: import("../Types").SignalRepository;
26
27
  readonly user: import("../Types").Contact | undefined;
27
28
  generateMessageTag: () => string;
28
- query: (node: BinaryNode, timeoutMs?: number) => Promise<any>;
29
- waitForMessage: <T>(msgId: string, timeoutMs?: number | undefined) => Promise<any>;
29
+ query: (node: BinaryNode, timeoutMs?: number) => Promise<BinaryNode>;
30
+ waitForMessage: <T_1>(msgId: string, timeoutMs?: number | undefined) => Promise<T_1>;
30
31
  waitForSocketOpen: () => Promise<void>;
31
32
  sendRawMessage: (data: Uint8Array | Buffer) => Promise<void>;
32
33
  sendNode: (frame: BinaryNode) => Promise<void>;
@@ -37,7 +38,7 @@ export declare const makeSocket: (config: SocketConfig) => {
37
38
  uploadPreKeysToServerIfRequired: () => Promise<void>;
38
39
  requestPairingCode: (phoneNumber: string, pairCode: string) => Promise<string>;
39
40
  /** Waits for the connection to WA to reach a state */
40
- waitForConnectionUpdate: (check: (u: Partial<import("../Types").ConnectionState>) => Promise<boolean | undefined>, timeoutMs?: number) => Promise<void>;
41
- sendWAMBuffer: (wamBuffer: Buffer) => Promise<any>;
41
+ waitForConnectionUpdate: (check: (u: Partial<import("../Types").ConnectionState>) => Promise<boolean | undefined>, timeoutMs?: number | undefined) => Promise<void>;
42
+ sendWAMBuffer: (wamBuffer: Buffer) => Promise<BinaryNode>;
42
43
  };
43
44
  export type Socket = ReturnType<typeof makeSocket>;
@@ -20,14 +20,15 @@ const Client_1 = require("./Client");
20
20
  const makeSocket = (config) => {
21
21
  var _a, _b;
22
22
  const { waWebSocketUrl, connectTimeoutMs, logger, keepAliveIntervalMs, browser, auth: authState, printQRInTerminal, defaultQueryTimeoutMs, transactionOpts, qrTimeout, makeSignalRepository, } = config;
23
- const url = typeof waWebSocketUrl === 'string' ? new url_1.URL(waWebSocketUrl) : waWebSocketUrl;
24
- if (config.mobile || url.protocol === 'tcp:') {
25
- throw new boom_1.Boom('Mobile API is not supported anymore', { statusCode: Types_1.DisconnectReason.loggedOut });
23
+ let url = typeof waWebSocketUrl === 'string' ? new url_1.URL(waWebSocketUrl) : waWebSocketUrl;
24
+ config.mobile = config.mobile || url.protocol === 'tcp:';
25
+ if (config.mobile && url.protocol !== 'tcp:') {
26
+ url = new url_1.URL(`tcp://${Defaults_1.MOBILE_ENDPOINT}:${Defaults_1.MOBILE_PORT}`);
26
27
  }
27
- if (url.protocol === 'wss' && ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.routingInfo)) {
28
+ if (!config.mobile && url.protocol === 'wss' && ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.routingInfo)) {
28
29
  url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'));
29
30
  }
30
- const ws = new Client_1.WebSocketClient(url, config);
31
+ const ws = config.socket ? config.socket : config.mobile ? new Client_1.MobileSocketClient(url, config) : new Client_1.WebSocketClient(url, config);
31
32
  ws.connect();
32
33
  const ev = (0, Utils_1.makeEventBuffer)(logger);
33
34
  /** ephemeral key pair used to encrypt/decrypt communication. Unique for each connection */
@@ -35,7 +36,8 @@ const makeSocket = (config) => {
35
36
  /** WA noise protocol wrapper */
36
37
  const noise = (0, Utils_1.makeNoiseHandler)({
37
38
  keyPair: ephemeralKeyPair,
38
- NOISE_HEADER: Defaults_1.NOISE_WA_HEADER,
39
+ NOISE_HEADER: config.mobile ? Defaults_1.MOBILE_NOISE_HEADER : Defaults_1.NOISE_WA_HEADER,
40
+ mobile: config.mobile,
39
41
  logger,
40
42
  routingInfo: (_b = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _b === void 0 ? void 0 : _b.routingInfo
41
43
  });
@@ -114,7 +116,7 @@ const makeSocket = (config) => {
114
116
  let onRecv;
115
117
  let onErr;
116
118
  try {
117
- const result = await (0, Utils_1.promiseTimeout)(timeoutMs, (resolve, reject) => {
119
+ return await (0, Utils_1.promiseTimeout)(timeoutMs, (resolve, reject) => {
118
120
  onRecv = resolve;
119
121
  onErr = err => {
120
122
  reject(err || new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed }));
@@ -123,7 +125,6 @@ const makeSocket = (config) => {
123
125
  ws.on('close', onErr); // if the socket closes, you'll never receive the message
124
126
  ws.off('error', onErr);
125
127
  });
126
- return result;
127
128
  }
128
129
  finally {
129
130
  ws.off(`TAG:${msgId}`, onRecv);
@@ -137,10 +138,9 @@ const makeSocket = (config) => {
137
138
  node.attrs.id = generateMessageTag();
138
139
  }
139
140
  const msgId = node.attrs.id;
140
- const [result] = await Promise.all([
141
- waitForMessage(msgId, timeoutMs),
142
- sendNode(node)
143
- ]);
141
+ const wait = waitForMessage(msgId, timeoutMs);
142
+ await sendNode(node);
143
+ const result = await wait;
144
144
  if ('tag' in result) {
145
145
  (0, WABinary_1.assertNodeErrorFree)(result);
146
146
  }
@@ -159,7 +159,10 @@ const makeSocket = (config) => {
159
159
  logger.trace({ handshake }, 'handshake recv from WA');
160
160
  const keyEnc = await noise.processHandshake(handshake, creds.noiseKey);
161
161
  let node;
162
- if (!creds.me) {
162
+ if (config.mobile) {
163
+ node = (0, Utils_1.generateMobileNode)(config);
164
+ }
165
+ else if (!creds.me) {
163
166
  node = (0, Utils_1.generateRegistrationNode)(creds, config);
164
167
  logger.info({ node }, 'not logged in, attempting registration...');
165
168
  }
@@ -229,11 +232,11 @@ const makeSocket = (config) => {
229
232
  const l0 = frame.tag;
230
233
  const l1 = frame.attrs || {};
231
234
  const l2 = Array.isArray(frame.content) ? (_a = frame.content[0]) === null || _a === void 0 ? void 0 : _a.tag : '';
232
- for (const key of Object.keys(l1)) {
235
+ Object.keys(l1).forEach(key => {
233
236
  anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered;
234
237
  anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered;
235
238
  anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered;
236
- }
239
+ });
237
240
  anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered;
238
241
  anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered;
239
242
  if (!anyTriggered && logger.level === 'debug') {
@@ -371,7 +374,7 @@ const makeSocket = (config) => {
371
374
  }
372
375
  authState.creds.me = {
373
376
  id: (0, WABinary_1.jidEncode)(phoneNumber, 's.whatsapp.net'),
374
- name: 'ANYA WEB'
377
+ name: '~'
375
378
  };
376
379
  ev.emit('creds.update', authState.creds);
377
380
  await sendNode({
@@ -1,3 +1,5 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
1
3
  import { Boom } from '@hapi/boom';
2
4
  import { SocketConfig } from '../Types';
3
5
  import { BinaryNode } from '../WABinary';
@@ -5,12 +7,12 @@ import { USyncQuery } from '../WAUSync';
5
7
  export declare const makeUSyncSocket: (config: SocketConfig) => {
6
8
  executeUSyncQuery: (usyncQuery: USyncQuery) => Promise<import("../WAUSync").USyncQueryResult | undefined>;
7
9
  type: "md";
8
- ws: import("./Client").WebSocketClient;
10
+ ws: any;
9
11
  ev: import("../Types").BaileysEventEmitter & {
10
- process(handler: (events: Partial<import("../Types").BaileysEventMap>) => void | Promise<void>): (() => void);
12
+ process(handler: (events: Partial<import("../Types").BaileysEventMap>) => void | Promise<void>): () => void;
11
13
  buffer(): void;
12
- createBufferedFunction<A extends any[], T>(work: (...args: A) => Promise<T>): ((...args: A) => Promise<T>);
13
- flush(force?: boolean): boolean;
14
+ createBufferedFunction<A extends any[], T>(work: (...args: A) => Promise<T>): (...args: A) => Promise<T>;
15
+ flush(force?: boolean | undefined): boolean;
14
16
  isBuffering(): boolean;
15
17
  };
16
18
  authState: {
@@ -20,17 +22,17 @@ export declare const makeUSyncSocket: (config: SocketConfig) => {
20
22
  signalRepository: import("../Types").SignalRepository;
21
23
  user: import("../Types").Contact | undefined;
22
24
  generateMessageTag: () => string;
23
- query: (node: BinaryNode, timeoutMs?: number) => Promise<any>;
24
- waitForMessage: <T>(msgId: string, timeoutMs?: number | undefined) => Promise<any>;
25
+ query: (node: BinaryNode, timeoutMs?: number | undefined) => Promise<BinaryNode>;
26
+ waitForMessage: <T_1>(msgId: string, timeoutMs?: number | undefined) => Promise<T_1>;
25
27
  waitForSocketOpen: () => Promise<void>;
26
28
  sendRawMessage: (data: Uint8Array | Buffer) => Promise<void>;
27
29
  sendNode: (frame: BinaryNode) => Promise<void>;
28
- logout: (msg?: string) => Promise<void>;
30
+ logout: (msg?: string | undefined) => Promise<void>;
29
31
  end: (error: Error | undefined) => void;
30
- onUnexpectedError: (err: Error | Boom, msg: string) => void;
32
+ onUnexpectedError: (err: Error | Boom<any>, msg: string) => void;
31
33
  uploadPreKeys: (count?: number) => Promise<void>;
32
34
  uploadPreKeysToServerIfRequired: () => Promise<void>;
33
35
  requestPairingCode: (phoneNumber: string, pairCode: string) => Promise<string>;
34
- waitForConnectionUpdate: (check: (u: Partial<import("../Types").ConnectionState>) => Promise<boolean | undefined>, timeoutMs?: number) => Promise<void>;
35
- sendWAMBuffer: (wamBuffer: Buffer) => Promise<any>;
36
+ waitForConnectionUpdate: (check: (u: Partial<import("../Types").ConnectionState>) => Promise<boolean | undefined>, timeoutMs?: number | undefined) => Promise<void>;
37
+ sendWAMBuffer: (wamBuffer: Buffer) => Promise<BinaryNode>;
36
38
  };
@@ -6,7 +6,7 @@ const WABinary_1 = require("../WABinary");
6
6
  const socket_1 = require("./socket");
7
7
  const makeUSyncSocket = (config) => {
8
8
  const sock = (0, socket_1.makeSocket)(config);
9
- const { generateMessageTag, query } = sock;
9
+ const { generateMessageTag, query, } = sock;
10
10
  const executeUSyncQuery = async (usyncQuery) => {
11
11
  if (usyncQuery.protocols.length === 0) {
12
12
  throw new boom_1.Boom('USyncQuery must have at least one protocol');
@@ -14,13 +14,15 @@ const makeUSyncSocket = (config) => {
14
14
  // todo: validate users, throw WARNING on no valid users
15
15
  // variable below has only validated users
16
16
  const validUsers = usyncQuery.users;
17
- const userNodes = validUsers.map(user => {
17
+ const userNodes = validUsers.map((user) => {
18
18
  return {
19
19
  tag: 'user',
20
20
  attrs: {
21
- jid: !user.phone ? user.id : undefined
21
+ jid: !user.phone ? user.id : undefined,
22
22
  },
23
- content: usyncQuery.protocols.map(a => a.getUserElement(user)).filter(a => a !== null)
23
+ content: usyncQuery.protocols
24
+ .map((a) => a.getUserElement(user))
25
+ .filter(a => a !== null)
24
26
  };
25
27
  });
26
28
  const listNode = {
@@ -31,14 +33,14 @@ const makeUSyncSocket = (config) => {
31
33
  const queryNode = {
32
34
  tag: 'query',
33
35
  attrs: {},
34
- content: usyncQuery.protocols.map(a => a.getQueryElement())
36
+ content: usyncQuery.protocols.map((a) => a.getQueryElement())
35
37
  };
36
38
  const iq = {
37
39
  tag: 'iq',
38
40
  attrs: {
39
41
  to: WABinary_1.S_WHATSAPP_NET,
40
42
  type: 'get',
41
- xmlns: 'usync'
43
+ xmlns: 'usync',
42
44
  },
43
45
  content: [
44
46
  {
@@ -48,18 +50,21 @@ const makeUSyncSocket = (config) => {
48
50
  mode: usyncQuery.mode,
49
51
  sid: generateMessageTag(),
50
52
  last: 'true',
51
- index: '0'
53
+ index: '0',
52
54
  },
53
- content: [queryNode, listNode]
55
+ content: [
56
+ queryNode,
57
+ listNode
58
+ ]
54
59
  }
55
- ]
60
+ ],
56
61
  };
57
62
  const result = await query(iq);
58
63
  return usyncQuery.parseUSyncQueryResult(result);
59
64
  };
60
65
  return {
61
66
  ...sock,
62
- executeUSyncQuery
67
+ executeUSyncQuery,
63
68
  };
64
69
  };
65
70
  exports.makeUSyncSocket = makeUSyncSocket;
@@ -1,2 +1,3 @@
1
+ import makeCacheManagerAuthState from './make-cache-manager-store';
1
2
  import makeInMemoryStore from './make-in-memory-store';
2
- export { makeInMemoryStore };
3
+ export { makeInMemoryStore, makeCacheManagerAuthState };
@@ -3,6 +3,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.makeInMemoryStore = void 0;
6
+ exports.makeCacheManagerAuthState = exports.makeInMemoryStore = void 0;
7
+ const make_cache_manager_store_1 = __importDefault(require("./make-cache-manager-store"));
8
+ exports.makeCacheManagerAuthState = make_cache_manager_store_1.default;
7
9
  const make_in_memory_store_1 = __importDefault(require("./make-in-memory-store"));
8
10
  exports.makeInMemoryStore = make_in_memory_store_1.default;
@@ -105,7 +105,7 @@ declare const _default: (config: BaileysInMemoryStoreConfig) => {
105
105
  [id: string]: Contact;
106
106
  };
107
107
  messages: {
108
- [id: string]: WAMessage[];
108
+ [id: string]: proto.IWebMessageInfo[];
109
109
  };
110
110
  labels: {
111
111
  [labelId: string]: Label;
@@ -191,14 +191,16 @@ exports.default = (config) => {
191
191
  const jid = (0, WABinary_1.jidNormalizedUser)(msg.key.remoteJid);
192
192
  const list = assertMessageList(jid);
193
193
  list.upsert(msg, 'append');
194
- if (type === 'notify' && !chats.get(jid)) {
195
- ev.emit('chats.upsert', [
196
- {
197
- id: jid,
198
- conversationTimestamp: (0, Utils_1.toNumber)(msg.messageTimestamp),
199
- unreadCount: 1
200
- }
201
- ]);
194
+ if (type === 'notify') {
195
+ if (!chats.get(jid)) {
196
+ ev.emit('chats.upsert', [
197
+ {
198
+ id: jid,
199
+ conversationTimestamp: (0, Utils_1.toNumber)(msg.messageTimestamp),
200
+ unreadCount: 1
201
+ }
202
+ ]);
203
+ }
202
204
  }
203
205
  }
204
206
  break;
@@ -1,7 +1,7 @@
1
1
  declare function makeOrderedDictionary<T>(idGetter: (item: T) => string): {
2
2
  array: T[];
3
3
  get: (id: string) => T | undefined;
4
- upsert: (item: T, mode: "append" | "prepend") => void;
4
+ upsert: (item: T, mode: 'append' | 'prepend') => void;
5
5
  update: (item: T) => boolean;
6
6
  remove: (item: T) => boolean;
7
7
  updateAssign: (id: string, update: Partial<T>) => boolean;
@@ -56,9 +56,9 @@ function makeOrderedDictionary(idGetter) {
56
56
  },
57
57
  clear: () => {
58
58
  array.splice(0, array.length);
59
- for (const key of Object.keys(dict)) {
59
+ Object.keys(dict).forEach(key => {
60
60
  delete dict[key];
61
- }
61
+ });
62
62
  },
63
63
  filter: (contain) => {
64
64
  let i = 0;
@@ -1,4 +1,7 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
1
3
  import type { proto } from '../../WAProto';
4
+ import { RegistrationOptions } from '../Socket/registration';
2
5
  import type { Contact } from './Contact';
3
6
  import type { MinimalMessage } from './Message';
4
7
  export type KeyPair = {
@@ -55,7 +58,12 @@ export type AuthenticationCreds = SignalCreds & {
55
58
  /** number of times history & app state has been synced */
56
59
  accountSyncCounter: number;
57
60
  accountSettings: AccountSettings;
61
+ deviceId: string;
62
+ phoneId: string;
63
+ identityId: Buffer;
58
64
  registered: boolean;
65
+ backupToken: Buffer;
66
+ registration: RegistrationOptions;
59
67
  pairingCode: string | undefined;
60
68
  lastPropHash: string | undefined;
61
69
  routingInfo: Buffer | undefined;
@@ -1,18 +1,16 @@
1
1
  import type { proto } from '../../WAProto';
2
2
  import type { AccountSettings } from './Auth';
3
- import type { ContactAction } from './Contact';
4
3
  import type { BufferedEventData } from './Events';
5
- import type { LabelActionBody } from './Label';
6
4
  import type { ChatLabelAssociationActionBody } from './LabelAssociation';
7
5
  import type { MessageLabelAssociationActionBody } from './LabelAssociation';
8
6
  import type { MinimalMessage, WAMessageKey } from './Message';
9
7
  /** privacy settings in WhatsApp Web */
10
8
  export type WAPrivacyValue = 'all' | 'contacts' | 'contact_blacklist' | 'none';
9
+ export type WAPrivacyCallValue = 'all' | 'known';
10
+ export type WAPrivacyMessagesValue = 'all' | 'contacts';
11
11
  export type WAPrivacyOnlineValue = 'all' | 'match_last_seen';
12
12
  export type WAPrivacyGroupAddValue = 'all' | 'contacts' | 'contact_blacklist';
13
13
  export type WAReadReceiptsValue = 'all' | 'none';
14
- export type WAPrivacyCallValue = 'all' | 'known';
15
- export type WAPrivacyMessagesValue = 'all' | 'contacts';
16
14
  /** set of statuses visible to other people; see updatePresence() in WhatsAppWeb.Send */
17
15
  export type WAPresence = 'unavailable' | 'available' | 'composing' | 'recording' | 'paused';
18
16
  export declare const ALL_WA_PATCH_NAMES: readonly ["critical_block", "critical_unblock_low", "regular_high", "regular_low", "regular"];
@@ -21,10 +19,6 @@ export interface PresenceData {
21
19
  lastKnownPresence: WAPresence;
22
20
  lastSeen?: number;
23
21
  }
24
- export type BotListInfo = {
25
- jid: string;
26
- personaId: string;
27
- };
28
22
  export type ChatMutation = {
29
23
  syncAction: proto.ISyncActionData;
30
24
  index: string[];
@@ -89,10 +83,6 @@ export type ChatModification = {
89
83
  } | {
90
84
  delete: true;
91
85
  lastMessages: LastMessageList;
92
- } | {
93
- contact: ContactAction | null;
94
- } | {
95
- addLabel: LabelActionBody;
96
86
  } | {
97
87
  addChatLabel: ChatLabelAssociationActionBody;
98
88
  } | {
@@ -14,11 +14,6 @@ export interface Contact {
14
14
  * null => if the profile picture has not been set (default profile picture)
15
15
  * any other string => url of the profile picture
16
16
  */
17
- imgUrl?: string | null;
17
+ imgUrl?: string | null | 'changed';
18
18
  status?: string;
19
19
  }
20
- export type ContactAction = {
21
- fistName: string;
22
- fullName: string;
23
- saveOnPrimaryAddressbook: boolean;
24
- };
@@ -3,29 +3,22 @@ export type GroupParticipant = (Contact & {
3
3
  isAdmin?: boolean;
4
4
  isSuperAdmin?: boolean;
5
5
  admin?: 'admin' | 'superadmin' | null;
6
- lid?: string;
7
6
  });
8
7
  export type ParticipantAction = 'add' | 'remove' | 'promote' | 'demote' | 'modify';
9
8
  export type RequestJoinAction = 'created' | 'revoked' | 'rejected';
10
9
  export type RequestJoinMethod = 'invite_link' | 'linked_group_join' | 'non_admin_add' | undefined;
11
10
  export interface GroupMetadata {
12
11
  id: string;
13
- /** group uses 'lid' or 'pn' to send messages */
14
- addressingMode: 'pn' | 'lid';
15
12
  owner: string | undefined;
16
- onwerPn?: string | undefined;
17
13
  subject: string;
18
14
  /** group subject owner */
19
15
  subjectOwner?: string;
20
- subjectOwnerPn?: string;
21
16
  /** group subject modification date */
22
17
  subjectTime?: number;
23
18
  creation?: number;
24
19
  desc?: string;
25
20
  descOwner?: string;
26
- descOwnerPn?: string;
27
21
  descId?: string;
28
- descTime?: number;
29
22
  /** if this group is part of a community, it returns the jid of the community to which it belongs */
30
23
  linkedParent?: string;
31
24
  /** is set when the group only allows admins to change group settings */
@@ -10,17 +10,6 @@ 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
- }
24
13
  /** WhatsApp has 20 predefined colors */
25
14
  export declare enum LabelColor {
26
15
  Color1 = 0,
@@ -24,4 +24,4 @@ var LabelColor;
24
24
  LabelColor[LabelColor["Color18"] = 17] = "Color18";
25
25
  LabelColor[LabelColor["Color19"] = 18] = "Color19";
26
26
  LabelColor[LabelColor["Color20"] = 19] = "Color20";
27
- })(LabelColor || (exports.LabelColor = LabelColor = {}));
27
+ })(LabelColor = exports.LabelColor || (exports.LabelColor = {}));
@@ -6,4 +6,4 @@ var LabelAssociationType;
6
6
  (function (LabelAssociationType) {
7
7
  LabelAssociationType["Chat"] = "label_jid";
8
8
  LabelAssociationType["Message"] = "label_message";
9
- })(LabelAssociationType || (exports.LabelAssociationType = LabelAssociationType = {}));
9
+ })(LabelAssociationType = exports.LabelAssociationType || (exports.LabelAssociationType = {}));