@queenanya/baileys 7.4.0 → 7.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/README.md +0 -10
  2. package/lib/Defaults/baileys-version.json +1 -1
  3. package/lib/Defaults/index.d.ts +0 -231
  4. package/lib/Defaults/index.js +1 -17
  5. package/lib/Socket/Client/index.d.ts +2 -3
  6. package/lib/Socket/Client/index.js +2 -3
  7. package/lib/Socket/Client/{web-socket-client.d.ts → websocket.d.ts} +1 -1
  8. package/lib/Socket/Client/{web-socket-client.js → websocket.js} +2 -2
  9. package/lib/Socket/business.d.ts +1 -1
  10. package/lib/Socket/chats.d.ts +2 -2
  11. package/lib/Socket/chats.js +5 -6
  12. package/lib/Socket/groups.d.ts +1 -7
  13. package/lib/Socket/index.d.ts +10 -12
  14. package/lib/Socket/index.js +2 -2
  15. package/lib/Socket/messages-recv.d.ts +2 -2
  16. package/lib/Socket/messages-recv.js +3 -6
  17. package/lib/Socket/messages-send.d.ts +1 -1
  18. package/lib/Socket/messages-send.js +23 -8
  19. package/lib/Socket/newsletter.d.ts +1 -1
  20. package/lib/Socket/socket.d.ts +2 -1
  21. package/lib/Socket/socket.js +9 -14
  22. package/lib/Store/make-in-memory-store.js +8 -10
  23. package/lib/Store/make-ordered-dictionary.js +2 -2
  24. package/lib/Types/Auth.d.ts +0 -6
  25. package/lib/Types/Chat.d.ts +7 -7
  26. package/lib/Types/Contact.d.ts +1 -1
  27. package/lib/Types/Message.d.ts +4 -2
  28. package/lib/Types/Socket.d.ts +3 -3
  29. package/lib/Utils/auth-utils.js +1 -7
  30. package/lib/Utils/chat-utils.d.ts +4 -4
  31. package/lib/Utils/chat-utils.js +25 -20
  32. package/lib/Utils/decode-wa-message.js +14 -3
  33. package/lib/Utils/event-buffer.js +7 -7
  34. package/lib/Utils/generics.d.ts +8 -4
  35. package/lib/Utils/generics.js +33 -6
  36. package/lib/Utils/history.d.ts +2 -2
  37. package/lib/Utils/link-preview.js +24 -1
  38. package/lib/Utils/make-mutex.js +1 -0
  39. package/lib/Utils/messages-media.d.ts +1 -1
  40. package/lib/Utils/messages-media.js +9 -16
  41. package/lib/Utils/messages.js +7 -11
  42. package/lib/Utils/noise-handler.d.ts +1 -2
  43. package/lib/Utils/noise-handler.js +5 -10
  44. package/lib/Utils/process-message.js +1 -0
  45. package/lib/Utils/signal.js +2 -0
  46. package/lib/Utils/use-multi-file-auth-state.js +1 -0
  47. package/lib/Utils/validate-connection.d.ts +0 -1
  48. package/lib/Utils/validate-connection.js +10 -44
  49. package/lib/WABinary/constants.js +5 -5
  50. package/lib/WABinary/encode.js +7 -5
  51. package/lib/WABinary/jid-utils.d.ts +1 -1
  52. package/lib/WABinary/jid-utils.js +1 -1
  53. package/lib/WAM/BinaryInfo.d.ts +2 -2
  54. package/lib/WAM/constants.d.ts +3 -2
  55. package/lib/WAM/encode.js +2 -2
  56. package/package.json +4 -5
  57. package/lib/Defaults/phonenumber-mcc.json +0 -223
  58. package/lib/Socket/Client/mobile-socket-client.d.ts +0 -13
  59. package/lib/Socket/Client/mobile-socket-client.js +0 -65
  60. package/lib/Socket/registration.d.ts +0 -271
  61. package/lib/Socket/registration.js +0 -166
  62. /package/lib/Socket/Client/{abstract-socket-client.d.ts → types.d.ts} +0 -0
  63. /package/lib/Socket/Client/{abstract-socket-client.js → types.js} +0 -0
@@ -1,65 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MobileSocketClient = void 0;
4
- const net_1 = require("net");
5
- const abstract_socket_client_1 = require("./abstract-socket-client");
6
- class MobileSocketClient extends abstract_socket_client_1.AbstractSocketClient {
7
- constructor() {
8
- super(...arguments);
9
- this.socket = null;
10
- }
11
- get isOpen() {
12
- var _a;
13
- return ((_a = this.socket) === null || _a === void 0 ? void 0 : _a.readyState) === 'open';
14
- }
15
- get isClosed() {
16
- var _a;
17
- return this.socket === null || ((_a = this.socket) === null || _a === void 0 ? void 0 : _a.readyState) === 'closed';
18
- }
19
- get isClosing() {
20
- var _a;
21
- return this.socket === null || ((_a = this.socket) === null || _a === void 0 ? void 0 : _a.readyState) === 'closed';
22
- }
23
- get isConnecting() {
24
- var _a;
25
- return ((_a = this.socket) === null || _a === void 0 ? void 0 : _a.readyState) === 'opening';
26
- }
27
- async connect() {
28
- var _a;
29
- if (this.socket) {
30
- return;
31
- }
32
- if (this.config.agent) {
33
- throw new Error('There are not support for proxy agent for mobile connection');
34
- }
35
- else {
36
- this.socket = (0, net_1.connect)({
37
- host: this.url.hostname,
38
- port: Number(this.url.port) || 443
39
- });
40
- }
41
- this.socket.setMaxListeners(0);
42
- const events = ['close', 'connect', 'data', 'drain', 'end', 'error', 'lookup', 'ready', 'timeout'];
43
- for (const event of events) {
44
- (_a = this.socket) === null || _a === void 0 ? void 0 : _a.on(event, (...args) => this.emit(event, ...args));
45
- }
46
- this.socket.on('data', (...args) => this.emit('message', ...args));
47
- this.socket.on('ready', (...args) => this.emit('open', ...args));
48
- }
49
- async close() {
50
- if (!this.socket) {
51
- return;
52
- }
53
- return new Promise(resolve => {
54
- this.socket.end(resolve);
55
- this.socket = null;
56
- });
57
- }
58
- send(str, cb) {
59
- if (this.socket === null) {
60
- return false;
61
- }
62
- return this.socket.write(str, undefined, cb);
63
- }
64
- }
65
- exports.MobileSocketClient = MobileSocketClient;
@@ -1,271 +0,0 @@
1
- /// <reference types="long" />
2
- /// <reference types="node" />
3
- /// <reference types="node" />
4
- import { AxiosRequestConfig } from 'axios';
5
- import { KeyPair, SignedKeyPair, SocketConfig } from '../Types';
6
- export declare const makeRegistrationSocket: (config: SocketConfig) => {
7
- register: (code: string) => Promise<ExistsResponse>;
8
- requestRegistrationCode: (registrationOptions?: RegistrationOptions) => Promise<ExistsResponse>;
9
- logger: import("pino").Logger<never, boolean>;
10
- getOrderDetails: (orderId: string, tokenBase64: string) => Promise<import("../Types").OrderDetails>;
11
- getCatalog: ({ jid, limit, cursor }: import("../Types").GetCatalogOptions) => Promise<{
12
- products: import("../Types").Product[];
13
- nextPageCursor: string | undefined;
14
- }>;
15
- getCollections: (jid?: string | undefined, limit?: number) => Promise<{
16
- collections: import("../Types").CatalogCollection[];
17
- }>;
18
- productCreate: (create: import("../Types").ProductCreate) => Promise<import("../Types").Product>;
19
- productDelete: (productIds: string[]) => Promise<{
20
- deleted: number;
21
- }>;
22
- productUpdate: (productId: string, update: import("../Types").ProductUpdate) => Promise<import("../Types").Product>;
23
- sendMessageAck: ({ tag, attrs, content }: import("../WABinary").BinaryNode) => Promise<void>;
24
- sendRetryRequest: (node: import("../WABinary").BinaryNode, forceIncludeKeys?: boolean) => Promise<void>;
25
- rejectCall: (callId: string, callFrom: string) => Promise<void>;
26
- fetchMessageHistory: (count: number, oldestMsgKey: import("../Types").WAMessageKey, oldestMsgTimestamp: number | import("long").Long) => Promise<string>;
27
- requestPlaceholderResend: (messageKey: import("../Types").WAMessageKey) => Promise<string | undefined>;
28
- getPrivacyTokens: (jids: string[]) => Promise<import("../WABinary").BinaryNode>;
29
- assertSessions: (jids: string[], force: boolean) => Promise<boolean>;
30
- relayMessage: (jid: string, message: import("../Types").WAProto.IMessage, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList }: import("../Types").MessageRelayOptions) => Promise<string>;
31
- sendReceipt: (jid: string, participant: string | undefined, messageIds: string[], type: import("../Types").MessageReceiptType) => Promise<void>;
32
- sendReceipts: (keys: import("../Types").WAMessageKey[], type: import("../Types").MessageReceiptType) => Promise<void>;
33
- readMessages: (keys: import("../Types").WAMessageKey[]) => Promise<void>;
34
- refreshMediaConn: (forceGet?: boolean) => Promise<import("../Types").MediaConnInfo>;
35
- waUploadToServer: import("../Types").WAMediaUploadFunction;
36
- fetchPrivacySettings: (force?: boolean) => Promise<{
37
- [_: string]: string;
38
- }>;
39
- sendPeerDataOperationMessage: (pdoMessage: import("../Types").WAProto.Message.IPeerDataOperationRequestMessage) => Promise<string>;
40
- createParticipantNodes: (jids: string[], message: import("../Types").WAProto.IMessage, extraAttrs?: {
41
- [key: string]: string;
42
- } | undefined) => Promise<{
43
- nodes: import("../WABinary").BinaryNode[];
44
- shouldIncludeDeviceIdentity: boolean;
45
- }>;
46
- getUSyncDevices: (jids: string[], useCache: boolean, ignoreZeroDevices: boolean) => Promise<import("../WABinary").JidWithDevice[]>;
47
- updateMediaMessage: (message: import("../Types").WAProto.IWebMessageInfo) => Promise<import("../Types").WAProto.IWebMessageInfo>;
48
- sendMessage: (jid: string, content: import("../Types").AnyMessageContent, options?: import("../Types").MiscMessageGenerationOptions) => Promise<import("../Types").WAProto.WebMessageInfo | undefined>;
49
- subscribeNewsletterUpdates: (jid: string) => Promise<{
50
- duration: string;
51
- }>;
52
- newsletterReactionMode: (jid: string, mode: import("../Types").NewsletterReactionMode) => Promise<void>;
53
- newsletterUpdateDescription: (jid: string, description?: string | undefined) => Promise<void>;
54
- newsletterUpdateName: (jid: string, name: string) => Promise<void>;
55
- newsletterUpdatePicture: (jid: string, content: import("../Types").WAMediaUpload) => Promise<void>;
56
- newsletterRemovePicture: (jid: string) => Promise<void>;
57
- newsletterUnfollow: (jid: string) => Promise<void>;
58
- newsletterFollow: (jid: string) => Promise<void>;
59
- newsletterUnmute: (jid: string) => Promise<void>;
60
- newsletterMute: (jid: string) => Promise<void>;
61
- newsletterCreate: (name: string, description: string) => Promise<import("../Types").NewsletterMetadata>;
62
- newsletterMetadata: (type: "invite" | "jid", key: string, role?: import("../Types").NewsletterViewRole | undefined) => Promise<import("../Types").NewsletterMetadata>;
63
- newsletterAdminCount: (jid: string) => Promise<number>;
64
- newsletterChangeOwner: (jid: string, user: string) => Promise<void>;
65
- newsletterDemote: (jid: string, user: string) => Promise<void>;
66
- newsletterDelete: (jid: string) => Promise<void>;
67
- newsletterReactMessage: (jid: string, server_id: string, code?: string | undefined) => Promise<void>;
68
- newsletterFetchMessages: (type: "invite" | "jid", key: string, count: number, after?: number | undefined) => Promise<import("../Types").NewsletterFetchedUpdate[]>;
69
- newsletterFetchUpdates: (jid: string, count: number, after?: number | undefined, since?: number | undefined) => Promise<import("../Types").NewsletterFetchedUpdate[]>;
70
- groupMetadata: (jid: string) => Promise<import("../Types").GroupMetadata>;
71
- groupCreate: (subject: string, participants: string[]) => Promise<import("../Types").GroupMetadata>;
72
- groupLeave: (id: string) => Promise<void>;
73
- groupUpdateSubject: (jid: string, subject: string) => Promise<void>;
74
- groupRequestParticipantsList: (jid: string) => Promise<{
75
- [key: string]: string;
76
- }[]>;
77
- groupRequestParticipantsUpdate: (jid: string, participants: string[], action: "reject" | "approve") => Promise<{
78
- status: string;
79
- jid: string;
80
- }[]>;
81
- groupParticipantsUpdate: (jid: string, participants: string[], action: import("../Types").ParticipantAction) => Promise<{
82
- status: string;
83
- jid: string;
84
- content: import("../WABinary").BinaryNode;
85
- }[]>;
86
- groupUpdateDescription: (jid: string, description?: string | undefined) => Promise<void>;
87
- groupInviteCode: (jid: string) => Promise<string | undefined>;
88
- groupRevokeInvite: (jid: string) => Promise<string | undefined>;
89
- groupAcceptInvite: (code: string) => Promise<string | undefined>;
90
- groupRevokeInviteV4: (groupJid: string, invitedJid: string) => Promise<boolean>;
91
- groupAcceptInviteV4: (key: string | import("../Types").WAMessageKey, inviteMessage: import("../Types").WAProto.Message.IGroupInviteMessage) => Promise<string>;
92
- groupGetInviteInfo: (code: string) => Promise<import("../Types").GroupMetadata>;
93
- groupToggleEphemeral: (jid: string, ephemeralExpiration: number) => Promise<void>;
94
- groupSettingUpdate: (jid: string, setting: "announcement" | "locked" | "not_announcement" | "unlocked") => Promise<void>;
95
- groupMemberAddMode: (jid: string, mode: "all_member_add" | "admin_add") => Promise<void>;
96
- groupJoinApprovalMode: (jid: string, mode: "on" | "off") => Promise<void>;
97
- groupFetchAllParticipating: () => Promise<{
98
- [_: string]: import("../Types").GroupMetadata;
99
- }>;
100
- processingMutex: {
101
- mutex<T>(code: () => T | Promise<T>): Promise<T>;
102
- };
103
- upsertMessage: (msg: import("../Types").WAProto.IWebMessageInfo, type: import("../Types").MessageUpsertType) => Promise<void>;
104
- appPatch: (patchCreate: import("../Types").WAPatchCreate) => Promise<void>;
105
- sendPresenceUpdate: (type: import("../Types").WAPresence, toJid?: string | undefined) => Promise<void>;
106
- presenceSubscribe: (toJid: string, tcToken?: Buffer | undefined) => Promise<void>;
107
- profilePictureUrl: (jid: string, type?: "image" | "preview", timeoutMs?: number | undefined) => Promise<string | undefined>;
108
- onWhatsApp: (...jids: string[]) => Promise<{
109
- exists: boolean;
110
- jid: string;
111
- }[]>;
112
- fetchBlocklist: () => Promise<string[]>;
113
- fetchDisappearingDuration: (...jids: string[]) => Promise<{
114
- user: string;
115
- duration: number;
116
- setAt: Date;
117
- }[]>;
118
- fetchStatus: (jid: string) => Promise<{
119
- status: string | undefined;
120
- setAt: Date;
121
- } | undefined>;
122
- updateProfilePicture: (jid: string, content: import("../Types").WAMediaUpload) => Promise<void>;
123
- updateProfilePictureFull: (jid: any, content: any) => Promise<void>;
124
- updateProfilePictureFull2: (jid: any, content: any) => Promise<void>;
125
- removeProfilePicture: (jid: string) => Promise<void>;
126
- updateProfileStatus: (status: string) => Promise<void>;
127
- updateProfileName: (name: string) => Promise<void>;
128
- updateBlockStatus: (jid: string, action: "block" | "unblock") => Promise<void>;
129
- updateCallPrivacy: (value: import("../Types").WAPrivacyCallValue) => Promise<void>;
130
- updateLastSeenPrivacy: (value: import("../Types").WAPrivacyValue) => Promise<void>;
131
- updateOnlinePrivacy: (value: import("../Types").WAPrivacyOnlineValue) => Promise<void>;
132
- updateProfilePicturePrivacy: (value: import("../Types").WAPrivacyValue) => Promise<void>;
133
- updateStatusPrivacy: (value: import("../Types").WAPrivacyValue) => Promise<void>;
134
- updateReadReceiptsPrivacy: (value: import("../Types").WAReadReceiptsValue) => Promise<void>;
135
- updateGroupsAddPrivacy: (value: import("../Types").WAPrivacyGroupAddValue) => Promise<void>;
136
- updateDefaultDisappearingMode: (duration: number) => Promise<void>;
137
- getBusinessProfile: (jid: string) => Promise<void | import("../Types").WABusinessProfile>;
138
- resyncAppState: (collections: readonly ("critical_block" | "critical_unblock_low" | "regular_high" | "regular_low" | "regular")[], isInitialSync: boolean) => Promise<void>;
139
- chatModify: (mod: import("../Types").ChatModification, jid: string) => Promise<void>;
140
- cleanDirtyBits: (type: "account_sync" | "groups", fromTimestamp?: string | number | undefined) => Promise<void>;
141
- addLabel: (jid: string, labels: import("../Types/Label").LabelActionBody) => Promise<void>;
142
- addChatLabel: (jid: string, labelId: string) => Promise<void>;
143
- removeChatLabel: (jid: string, labelId: string) => Promise<void>;
144
- addMessageLabel: (jid: string, messageId: string, labelId: string) => Promise<void>;
145
- removeMessageLabel: (jid: string, messageId: string, labelId: string) => Promise<void>;
146
- star: (jid: string, messages: {
147
- id: string;
148
- fromMe?: boolean | undefined;
149
- }[], star: boolean) => Promise<void>;
150
- type: "md";
151
- ws: any;
152
- ev: import("../Types").BaileysEventEmitter & {
153
- process(handler: (events: Partial<import("../Types").BaileysEventMap>) => void | Promise<void>): () => void;
154
- buffer(): void;
155
- createBufferedFunction<A extends any[], T_1>(work: (...args: A) => Promise<T_1>): (...args: A) => Promise<T_1>;
156
- flush(force?: boolean | undefined): boolean;
157
- isBuffering(): boolean;
158
- };
159
- authState: {
160
- creds: import("../Types").AuthenticationCreds;
161
- keys: import("../Types").SignalKeyStoreWithTransaction;
162
- };
163
- signalRepository: import("../Types").SignalRepository;
164
- user: import("../Types").Contact | undefined;
165
- generateMessageTag: () => string;
166
- query: (node: import("../WABinary").BinaryNode, timeoutMs?: number | undefined) => Promise<import("../WABinary").BinaryNode>;
167
- waitForMessage: <T_2>(msgId: string, timeoutMs?: number | undefined) => Promise<T_2>;
168
- waitForSocketOpen: () => Promise<void>;
169
- sendRawMessage: (data: Uint8Array | Buffer) => Promise<void>;
170
- sendNode: (frame: import("../WABinary").BinaryNode) => Promise<void>;
171
- logout: (msg?: string | undefined) => Promise<void>;
172
- end: (error: Error | undefined) => void;
173
- onUnexpectedError: (err: Error | import("@hapi/boom").Boom<any>, msg: string) => void;
174
- uploadPreKeys: (count?: number) => Promise<void>;
175
- uploadPreKeysToServerIfRequired: () => Promise<void>;
176
- requestPairingCode: (phoneNumber: string) => Promise<string>;
177
- waitForConnectionUpdate: (check: (u: Partial<import("../Types").ConnectionState>) => boolean | undefined, timeoutMs?: number | undefined) => Promise<void>;
178
- sendWAMBuffer: (wamBuffer: Buffer) => Promise<import("../WABinary").BinaryNode>;
179
- };
180
- export interface RegistrationData {
181
- registrationId: number;
182
- signedPreKey: SignedKeyPair;
183
- noiseKey: KeyPair;
184
- signedIdentityKey: KeyPair;
185
- identityId: Buffer;
186
- phoneId: string;
187
- deviceId: string;
188
- backupToken: Buffer;
189
- }
190
- export interface RegistrationOptions {
191
- /** your phone number */
192
- phoneNumber?: string;
193
- /** the country code of your phone number */
194
- phoneNumberCountryCode: string;
195
- /** your phone number without country code */
196
- phoneNumberNationalNumber: string;
197
- /** the country code of your mobile network
198
- * @see {@link https://de.wikipedia.org/wiki/Mobile_Country_Code}
199
- */
200
- phoneNumberMobileCountryCode: string;
201
- /** the network code of your mobile network
202
- * @see {@link https://de.wikipedia.org/wiki/Mobile_Network_Code}
203
- */
204
- phoneNumberMobileNetworkCode: string;
205
- /**
206
- * How to send the one time code
207
- */
208
- method?: 'sms' | 'voice' | 'captcha';
209
- /**
210
- * The captcha code if it was requested
211
- */
212
- captcha?: string;
213
- }
214
- export type RegistrationParams = RegistrationData & RegistrationOptions;
215
- export declare function registrationParams(params: RegistrationParams): {
216
- cc: string;
217
- in: string;
218
- Rc: string;
219
- lg: string;
220
- lc: string;
221
- mistyped: string;
222
- authkey: string;
223
- e_regid: string;
224
- e_keytype: string;
225
- e_ident: string;
226
- e_skey_id: string;
227
- e_skey_val: string;
228
- e_skey_sig: string;
229
- fdid: string;
230
- network_ratio_type: string;
231
- expid: string;
232
- simnum: string;
233
- hasinrc: string;
234
- pid: string;
235
- id: string;
236
- backup_token: string;
237
- token: string;
238
- fraud_checkpoint_code: string | undefined;
239
- };
240
- /**
241
- * Requests a registration code for the given phone number.
242
- */
243
- export declare function mobileRegisterCode(params: RegistrationParams, fetchOptions?: AxiosRequestConfig): Promise<ExistsResponse>;
244
- export declare function mobileRegisterExists(params: RegistrationParams, fetchOptions?: AxiosRequestConfig): Promise<ExistsResponse>;
245
- /**
246
- * Registers the phone number on whatsapp with the received OTP code.
247
- */
248
- export declare function mobileRegister(params: RegistrationParams & {
249
- code: string;
250
- }, fetchOptions?: AxiosRequestConfig): Promise<ExistsResponse>;
251
- /**
252
- * Encrypts the given string as AEAD aes-256-gcm with the public whatsapp key and a random keypair.
253
- */
254
- export declare function mobileRegisterEncrypt(data: string): string;
255
- export declare function mobileRegisterFetch(path: string, opts?: AxiosRequestConfig): Promise<ExistsResponse>;
256
- export interface ExistsResponse {
257
- status: 'fail' | 'sent';
258
- voice_length?: number;
259
- voice_wait?: number;
260
- sms_length?: number;
261
- sms_wait?: number;
262
- reason?: 'incorrect' | 'missing_param' | 'code_checkpoint';
263
- login?: string;
264
- flash_type?: number;
265
- ab_hash?: string;
266
- ab_key?: string;
267
- exp_cfg?: string;
268
- lid?: string;
269
- image_blob?: string;
270
- audio_blob?: string;
271
- }
@@ -1,166 +0,0 @@
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;