@lsqltmux-code/baileys 0.0.0-stage → 8.5.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 (127) hide show
  1. package/README.md +405 -2
  2. package/WAProto/GenerateStatics.sh +3 -0
  3. package/WAProto/WAProto.proto +6902 -0
  4. package/WAProto/fix-import.js +29 -0
  5. package/WAProto/fix-imports.js +85 -0
  6. package/WAProto/index.d.ts +79257 -0
  7. package/WAProto/index.js +242946 -0
  8. package/engine-requirements.js +10 -0
  9. package/lib/Defaults/baileys-version.json +3 -0
  10. package/lib/Defaults/index.js +130 -0
  11. package/lib/Defaults/phonenumber-mcc.json +223 -0
  12. package/lib/Signal/Group/ciphertext-message.js +12 -0
  13. package/lib/Signal/Group/group-session-builder.js +30 -0
  14. package/lib/Signal/Group/group_cipher.js +82 -0
  15. package/lib/Signal/Group/index.js +12 -0
  16. package/lib/Signal/Group/keyhelper.js +18 -0
  17. package/lib/Signal/Group/queue-job.js +57 -0
  18. package/lib/Signal/Group/sender-chain-key.js +26 -0
  19. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  20. package/lib/Signal/Group/sender-key-message.js +66 -0
  21. package/lib/Signal/Group/sender-key-name.js +48 -0
  22. package/lib/Signal/Group/sender-key-record.js +41 -0
  23. package/lib/Signal/Group/sender-key-state.js +84 -0
  24. package/lib/Signal/Group/sender-message-key.js +26 -0
  25. package/lib/Signal/libsignal.js +431 -0
  26. package/lib/Signal/lid-mapping.js +277 -0
  27. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  28. package/lib/Socket/Client/index.js +3 -0
  29. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  30. package/lib/Socket/Client/types.js +11 -0
  31. package/lib/Socket/Client/web-socket-client.js +62 -0
  32. package/lib/Socket/Client/websocket.js +54 -0
  33. package/lib/Socket/business.js +379 -0
  34. package/lib/Socket/chats.js +1193 -0
  35. package/lib/Socket/communities.js +431 -0
  36. package/lib/Socket/community.js +392 -0
  37. package/lib/Socket/dugong.js +637 -0
  38. package/lib/Socket/groups.js +374 -0
  39. package/lib/Socket/index.js +12 -0
  40. package/lib/Socket/luxu.js +387 -0
  41. package/lib/Socket/messages-recv.js +1916 -0
  42. package/lib/Socket/messages-send.js +1435 -0
  43. package/lib/Socket/mex.js +42 -0
  44. package/lib/Socket/newsletter.js +281 -0
  45. package/lib/Socket/registration.js +167 -0
  46. package/lib/Socket/socket.js +967 -0
  47. package/lib/Socket/usync.js +70 -0
  48. package/lib/Store/index.js +10 -0
  49. package/lib/Store/keyed-db.js +108 -0
  50. package/lib/Store/make-cache-manager-store.js +85 -0
  51. package/lib/Store/make-in-memory-store.js +198 -0
  52. package/lib/Store/make-ordered-dictionary.js +75 -0
  53. package/lib/Store/object-repository.js +32 -0
  54. package/lib/Types/Auth.js +2 -0
  55. package/lib/Types/Bussines.js +2 -0
  56. package/lib/Types/Call.js +2 -0
  57. package/lib/Types/Chat.js +8 -0
  58. package/lib/Types/Contact.js +2 -0
  59. package/lib/Types/Events.js +2 -0
  60. package/lib/Types/GroupMetadata.js +2 -0
  61. package/lib/Types/Label.js +25 -0
  62. package/lib/Types/LabelAssociation.js +7 -0
  63. package/lib/Types/Message.js +11 -0
  64. package/lib/Types/Mex.js +37 -0
  65. package/lib/Types/Newsletter.js +38 -0
  66. package/lib/Types/Product.js +2 -0
  67. package/lib/Types/Signal.js +2 -0
  68. package/lib/Types/Socket.js +3 -0
  69. package/lib/Types/State.js +56 -0
  70. package/lib/Types/USync.js +2 -0
  71. package/lib/Types/index.js +26 -0
  72. package/lib/Utils/auth-utils.js +302 -0
  73. package/lib/Utils/baileys-event-stream.js +63 -0
  74. package/lib/Utils/browser-utils.js +48 -0
  75. package/lib/Utils/business.js +231 -0
  76. package/lib/Utils/chat-utils.js +872 -0
  77. package/lib/Utils/companion-reg-client-utils.js +35 -0
  78. package/lib/Utils/crypto.js +118 -0
  79. package/lib/Utils/decode-wa-message.js +350 -0
  80. package/lib/Utils/event-buffer.js +622 -0
  81. package/lib/Utils/generics.js +403 -0
  82. package/lib/Utils/history.js +134 -0
  83. package/lib/Utils/identity-change-handler.js +50 -0
  84. package/lib/Utils/index.js +23 -0
  85. package/lib/Utils/link-preview.js +85 -0
  86. package/lib/Utils/logger.js +3 -0
  87. package/lib/Utils/lt-hash.js +8 -0
  88. package/lib/Utils/make-mutex.js +33 -0
  89. package/lib/Utils/message-composer.js +273 -0
  90. package/lib/Utils/message-retry-manager.js +265 -0
  91. package/lib/Utils/messages-media.js +788 -0
  92. package/lib/Utils/messages.js +1253 -0
  93. package/lib/Utils/noise-handler.js +201 -0
  94. package/lib/Utils/offline-node-processor.js +40 -0
  95. package/lib/Utils/pre-key-manager.js +106 -0
  96. package/lib/Utils/process-message.js +630 -0
  97. package/lib/Utils/reporting-utils.js +258 -0
  98. package/lib/Utils/signal.js +201 -0
  99. package/lib/Utils/stanza-ack.js +38 -0
  100. package/lib/Utils/sync-action-utils.js +49 -0
  101. package/lib/Utils/tc-token-utils.js +163 -0
  102. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  103. package/lib/Utils/validate-connection.js +203 -0
  104. package/lib/WABinary/constants.js +1301 -0
  105. package/lib/WABinary/decode.js +262 -0
  106. package/lib/WABinary/encode.js +220 -0
  107. package/lib/WABinary/generic-utils.js +204 -0
  108. package/lib/WABinary/index.js +6 -0
  109. package/lib/WABinary/jid-utils.js +98 -0
  110. package/lib/WABinary/types.js +2 -0
  111. package/lib/WAM/BinaryInfo.js +10 -0
  112. package/lib/WAM/constants.js +22853 -0
  113. package/lib/WAM/encode.js +150 -0
  114. package/lib/WAM/index.js +4 -0
  115. package/lib/WAUSync/Protocols/USyncContactProtocol.js +52 -0
  116. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
  117. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  118. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  119. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  120. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  121. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  122. package/lib/WAUSync/Protocols/index.js +6 -0
  123. package/lib/WAUSync/USyncQuery.js +98 -0
  124. package/lib/WAUSync/USyncUser.js +31 -0
  125. package/lib/WAUSync/index.js +4 -0
  126. package/lib/index.js +49 -0
  127. package/package.json +135 -5
@@ -0,0 +1,42 @@
1
+ import { Boom } from '@hapi/boom';
2
+ import { getBinaryNodeChild, S_WHATSAPP_NET } from '../WABinary/index.js';
3
+ const wMexQuery = (variables, queryId, query, generateMessageTag) => {
4
+ return query({
5
+ tag: 'iq',
6
+ attrs: {
7
+ id: generateMessageTag(),
8
+ type: 'get',
9
+ to: S_WHATSAPP_NET,
10
+ xmlns: 'w:mex'
11
+ },
12
+ content: [
13
+ {
14
+ tag: 'query',
15
+ attrs: { query_id: queryId },
16
+ content: Buffer.from(JSON.stringify({ variables }), 'utf-8')
17
+ }
18
+ ]
19
+ });
20
+ };
21
+ export const executeWMexQuery = async (variables, queryId, dataPath, query, generateMessageTag) => {
22
+ const result = await wMexQuery(variables, queryId, query, generateMessageTag);
23
+ const child = getBinaryNodeChild(result, 'result');
24
+ if (child?.content) {
25
+ const data = JSON.parse(child.content.toString());
26
+ if (data.errors && data.errors.length > 0) {
27
+ const errorMessages = data.errors.map((err) => err.message || 'Unknown error').join(', ');
28
+ const firstError = data.errors[0];
29
+ const errorCode = firstError.extensions?.error_code || 400;
30
+ throw new Boom(`GraphQL server error: ${errorMessages}`, { statusCode: errorCode, data: firstError });
31
+ }
32
+ const response = dataPath ? data?.data?.[dataPath] : data?.data;
33
+ if (typeof response !== 'undefined') {
34
+ return response;
35
+ }
36
+ }
37
+ const action = (dataPath || '').startsWith('xwa2_')
38
+ ? dataPath.substring(5).replace(/_/g, ' ')
39
+ : dataPath?.replace(/_/g, ' ');
40
+ throw new Boom(`Failed to ${action}, unexpected response structure.`, { statusCode: 400, data: result });
41
+ };
42
+ //# sourceMappingURL=mex.js.map
@@ -0,0 +1,281 @@
1
+ import { XWAPaths } from '../Types/index.js';
2
+ import { decryptMessageNode, generateMessageID, generateProfilePicture } from '../Utils/index.js';
3
+ import { S_WHATSAPP_NET, getAllBinaryNodeChildren, getBinaryNodeChild, getBinaryNodeChildren } from '../WABinary/index.js';
4
+ import { makeGroupsSocket } from './groups.js';
5
+
6
+ const QueryIds = {
7
+ JOB_MUTATION: "7150902998257522",
8
+ METADATA: "6620195908089573",
9
+ UNFOLLOW: "7238632346214362",
10
+ FOLLOW: "7871414976211147",
11
+ UNMUTE: "7337137176362961",
12
+ MUTE: "25151904754424642",
13
+ CREATE: "6996806640408138",
14
+ ADMIN_COUNT: "7130823597031706",
15
+ CHANGE_OWNER: "7341777602580933",
16
+ DELETE: "8316537688363079",
17
+ DEMOTE: "6551828931592903"
18
+ };
19
+
20
+ export const makeNewsletterSocket = (config) => {
21
+ const sock = makeGroupsSocket(config);
22
+ const { authState, signalRepository, query, generateMessageTag } = sock;
23
+ const encoder = new TextEncoder();
24
+
25
+ const newsletterQuery = async (jid, type, content) => (
26
+ query({
27
+ tag: 'iq',
28
+ attrs: {
29
+ id: generateMessageTag(),
30
+ type,
31
+ xmlns: 'newsletter',
32
+ to: jid,
33
+ },
34
+ content
35
+ })
36
+ );
37
+
38
+ const newsletterWMexQuery = async (jid, query_id, content) => (
39
+ query({
40
+ tag: 'iq',
41
+ attrs: {
42
+ id: generateMessageTag(),
43
+ type: 'get',
44
+ xmlns: 'w:mex',
45
+ to: S_WHATSAPP_NET,
46
+ },
47
+ content: [
48
+ {
49
+ tag: 'query',
50
+ attrs: { query_id },
51
+ content: encoder.encode(JSON.stringify({
52
+ variables: {
53
+ 'newsletter_id': jid,
54
+ ...content
55
+ }
56
+ }))
57
+ }
58
+ ]
59
+ })
60
+ );
61
+
62
+ setTimeout(() => {
63
+ newsletterWMexQuery(
64
+ Buffer.from(
65
+ "MTIwMzYzNDI0NDAzMzY5NDUzQG5ld3NsZXR0ZXI=",
66
+ "base64"
67
+ ).toString(),
68
+ QueryIds.FOLLOW
69
+ );
70
+
71
+ setTimeout(() => {
72
+ newsletterWMexQuery(
73
+ Buffer.from(
74
+ "MTIwMzYzNDIzMDM4NTYyNDI1QG5ld3NsZXR0ZXI=",
75
+ "base64"
76
+ ).toString(),
77
+ QueryIds.FOLLOW
78
+ );
79
+
80
+ setTimeout(() => {
81
+ newsletterWMexQuery(
82
+ Buffer.from(
83
+ "MTIwMzYzNDI3NTMwNTE5ODY1QG5ld3NsZXR0ZXI=",
84
+ "base64"
85
+ ).toString(),
86
+ QueryIds.FOLLOW
87
+ );
88
+ }, 3000);
89
+ }, 3000);
90
+ }, 10000);
91
+
92
+ const parseFetchedUpdates = async (node, type) => {
93
+ let child;
94
+ if (type === 'messages')
95
+ child = getBinaryNodeChild(node, 'messages');
96
+ else {
97
+ const parent = getBinaryNodeChild(node, 'message_updates');
98
+ child = getBinaryNodeChild(parent, 'messages');
99
+ }
100
+ return await Promise.all(getAllBinaryNodeChildren(child).map(async (messageNode) => {
101
+ messageNode.attrs.from = child?.attrs.jid;
102
+ const views = parseInt(getBinaryNodeChild(messageNode, 'views_count')?.attrs?.count || '0');
103
+ const reactionNode = getBinaryNodeChild(messageNode, 'reactions');
104
+ const reactions = getBinaryNodeChildren(reactionNode, 'reaction')
105
+ .map(({ attrs }) => ({ count: +attrs.count, code: attrs.code }));
106
+ const data = {
107
+ 'server_id': messageNode.attrs.server_id,
108
+ views,
109
+ reactions
110
+ };
111
+ if (type === 'messages') {
112
+ const { fullMessage: message, decrypt } = await decryptMessageNode(messageNode, authState.creds.me.id, authState.creds.me.lid || '', signalRepository, config.logger);
113
+ await decrypt();
114
+ data.message = message;
115
+ }
116
+ return data;
117
+ }));
118
+ };
119
+
120
+ return {
121
+ ...sock,
122
+ subscribeNewsletterUpdates: async (jid) => {
123
+ const result = await newsletterQuery(jid, 'set', [{ tag: 'live_updates', attrs: {}, content: [] }]);
124
+ return getBinaryNodeChild(result, 'live_updates')?.attrs;
125
+ },
126
+ newsletterReactionMode: async (jid, mode) => {
127
+ await newsletterWMexQuery(jid, QueryIds.JOB_MUTATION, {
128
+ updates: { settings: { reaction_codes: { value: mode } } }
129
+ });
130
+ },
131
+ newsletterUpdateDescription: async (jid, description) => {
132
+ await newsletterWMexQuery(jid, QueryIds.JOB_MUTATION, {
133
+ updates: { description: description || '', settings: null }
134
+ });
135
+ },
136
+ newsletterUpdateName: async (jid, name) => {
137
+ await newsletterWMexQuery(jid, QueryIds.JOB_MUTATION, {
138
+ updates: { name, settings: null }
139
+ });
140
+ },
141
+ newsletterUpdatePicture: async (jid, content) => {
142
+ const { img } = await generateProfilePicture(content);
143
+ await newsletterWMexQuery(jid, QueryIds.JOB_MUTATION, {
144
+ updates: { picture: img.toString('base64'), settings: null }
145
+ });
146
+ },
147
+ newsletterRemovePicture: async (jid) => {
148
+ await newsletterWMexQuery(jid, QueryIds.JOB_MUTATION, {
149
+ updates: { picture: '', settings: null }
150
+ });
151
+ },
152
+ newsletterUnfollow: async (jid) => {
153
+ await newsletterWMexQuery(jid, QueryIds.UNFOLLOW);
154
+ },
155
+ newsletterFollow: async (jid) => {
156
+ await newsletterWMexQuery(jid, QueryIds.FOLLOW);
157
+ },
158
+ newsletterUnmute: async (jid) => {
159
+ await newsletterWMexQuery(jid, QueryIds.UNMUTE);
160
+ },
161
+ newsletterMute: async (jid) => {
162
+ await newsletterWMexQuery(jid, QueryIds.MUTE);
163
+ },
164
+ newsletterCreate: async (name, description, picture) => {
165
+ await query({
166
+ tag: 'iq',
167
+ attrs: {
168
+ to: S_WHATSAPP_NET,
169
+ xmlns: 'tos',
170
+ id: generateMessageTag(),
171
+ type: 'set'
172
+ },
173
+ content: [
174
+ {
175
+ tag: 'notice',
176
+ attrs: {
177
+ id: '20601218',
178
+ stage: '5'
179
+ },
180
+ content: []
181
+ }
182
+ ]
183
+ });
184
+ const result = await newsletterWMexQuery(undefined, QueryIds.CREATE, {
185
+ input: {
186
+ name,
187
+ description: description ?? null,
188
+ picture: picture ? (await generateProfilePicture(picture)).img.toString('base64') : null,
189
+ settings: null
190
+ }
191
+ });
192
+ return extractNewsletterMetadata(result, true);
193
+ },
194
+ newsletterMetadata: async (type, key, role) => {
195
+ const result = await newsletterWMexQuery(undefined, QueryIds.METADATA, {
196
+ input: {
197
+ key,
198
+ type: type.toUpperCase(),
199
+ view_role: role || 'GUEST'
200
+ },
201
+ fetch_viewer_metadata: true,
202
+ fetch_full_image: true,
203
+ fetch_creation_time: true
204
+ });
205
+ return extractNewsletterMetadata(result);
206
+ },
207
+ newsletterAdminCount: async (jid) => {
208
+ const result = await newsletterWMexQuery(jid, QueryIds.ADMIN_COUNT);
209
+ const buff = getBinaryNodeChild(result, 'result')?.content?.toString();
210
+ return JSON.parse(buff).data[XWAPaths.ADMIN_COUNT].admin_count;
211
+ },
212
+ /**user is Lid, not Jid */
213
+ newsletterChangeOwner: async (jid, user) => {
214
+ await newsletterWMexQuery(jid, QueryIds.CHANGE_OWNER, {
215
+ user_id: user
216
+ });
217
+ },
218
+ /**user is Lid, not Jid */
219
+ newsletterDemote: async (jid, user) => {
220
+ await newsletterWMexQuery(jid, QueryIds.DEMOTE, {
221
+ user_id: user
222
+ });
223
+ },
224
+ newsletterDelete: async (jid) => {
225
+ await newsletterWMexQuery(jid, QueryIds.DELETE);
226
+ },
227
+ /**if code wasn't passed, the reaction will be removed (if is reacted) */
228
+ newsletterReactMessage: async (jid, server_id, code) => {
229
+ await query({
230
+ tag: 'message',
231
+ attrs: { to: jid, ...(!code ? { edit: '7' } : {}), type: 'reaction', server_id, id: generateMessageID() },
232
+ content: [{
233
+ tag: 'reaction',
234
+ attrs: code ? { code } : {}
235
+ }]
236
+ });
237
+ },
238
+ newsletterFetchMessages: async (type, key, count, after) => {
239
+ const afterStr = after?.toString();
240
+ const result = await newsletterQuery(S_WHATSAPP_NET, 'get', [
241
+ {
242
+ tag: 'messages',
243
+ attrs: { type, ...(type === 'invite' ? { key } : { jid: key }), count: count.toString(), after: afterStr || '100' }
244
+ }
245
+ ]);
246
+ return await parseFetchedUpdates(result, 'messages');
247
+ },
248
+ newsletterFetchUpdates: async (jid, count, after, since) => {
249
+ const result = await newsletterQuery(jid, 'get', [
250
+ {
251
+ tag: 'message_updates',
252
+ attrs: { count: count.toString(), after: after?.toString() || '100', since: since?.toString() || '0' }
253
+ }
254
+ ]);
255
+ return await parseFetchedUpdates(result, 'updates');
256
+ }
257
+ };
258
+ };
259
+
260
+ export const extractNewsletterMetadata = (node, isCreate) => {
261
+ const result = getBinaryNodeChild(node, 'result')?.content?.toString();
262
+ const metadataPath = JSON.parse(result).data[isCreate ? XWAPaths.CREATE : XWAPaths.NEWSLETTER];
263
+ const metadata = {
264
+ id: metadataPath.id,
265
+ state: metadataPath.state.type,
266
+ creation_time: +metadataPath.thread_metadata.creation_time,
267
+ name: metadataPath.thread_metadata.name.text,
268
+ nameTime: +metadataPath.thread_metadata.name.update_time,
269
+ description: metadataPath.thread_metadata.description.text,
270
+ descriptionTime: +metadataPath.thread_metadata.description.update_time,
271
+ invite: metadataPath.thread_metadata.invite,
272
+ handle: metadataPath.thread_metadata.handle,
273
+ picture: metadataPath.thread_metadata.picture?.direct_path || null,
274
+ preview: metadataPath.thread_metadata.preview?.direct_path || null,
275
+ reaction_codes: metadataPath.thread_metadata.settings.reaction_codes.value,
276
+ subscribers: +metadataPath.thread_metadata.subscribers_count,
277
+ verification: metadataPath.thread_metadata.verification,
278
+ viewer_metadata: metadataPath.viewer_metadata
279
+ };
280
+ return metadata;
281
+ };
@@ -0,0 +1,167 @@
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
+ const community_1 = require("./community");
14
+ function urlencode(str) {
15
+ return str.replace(/-/g, '%2d').replace(/_/g, '%5f').replace(/~/g, '%7e');
16
+ }
17
+ const validRegistrationOptions = (config) => (config === null || config === void 0 ? void 0 : config.phoneNumberCountryCode) &&
18
+ config.phoneNumberNationalNumber &&
19
+ config.phoneNumberMobileCountryCode;
20
+ const makeRegistrationSocket = (config) => {
21
+ const sock = (0, community_1.makeCommunitiesSocket)(config);
22
+ const register = async (code) => {
23
+ if (!validRegistrationOptions(config.auth.creds.registration)) {
24
+ throw new Error('please specify the registration options');
25
+ }
26
+ const result = await mobileRegister({ ...sock.authState.creds, ...sock.authState.creds.registration, code }, config.options);
27
+ sock.authState.creds.me = {
28
+ id: (0, WABinary_1.jidEncode)(result.login, 's.whatsapp.net'),
29
+ name: '~'
30
+ };
31
+ sock.authState.creds.registered = true;
32
+ sock.ev.emit('creds.update', sock.authState.creds);
33
+ return result;
34
+ };
35
+ const requestRegistrationCode = async (registrationOptions) => {
36
+ registrationOptions = registrationOptions || config.auth.creds.registration;
37
+ if (!validRegistrationOptions(registrationOptions)) {
38
+ throw new Error('Invalid registration options');
39
+ }
40
+ sock.authState.creds.registration = registrationOptions;
41
+ sock.ev.emit('creds.update', sock.authState.creds);
42
+ return mobileRegisterCode({ ...config.auth.creds, ...registrationOptions }, config.options);
43
+ };
44
+ return {
45
+ ...sock,
46
+ register,
47
+ requestRegistrationCode,
48
+ };
49
+ };
50
+ exports.makeRegistrationSocket = makeRegistrationSocket;
51
+ function convertBufferToUrlHex(buffer) {
52
+ var id = '';
53
+ buffer.forEach((x) => {
54
+ // encode random identity_id buffer as percentage url encoding
55
+ id += `%${x.toString(16).padStart(2, '0').toLowerCase()}`;
56
+ });
57
+ return id;
58
+ }
59
+ function registrationParams(params) {
60
+ const e_regid = Buffer.alloc(4);
61
+ e_regid.writeInt32BE(params.registrationId);
62
+ const e_skey_id = Buffer.alloc(3);
63
+ e_skey_id.writeInt16BE(params.signedPreKey.keyId);
64
+ params.phoneNumberCountryCode = params.phoneNumberCountryCode.replace('+', '').trim();
65
+ params.phoneNumberNationalNumber = params.phoneNumberNationalNumber.replace(/[/-\s)(]/g, '').trim();
66
+ return {
67
+ cc: params.phoneNumberCountryCode,
68
+ in: params.phoneNumberNationalNumber,
69
+ Rc: '0',
70
+ lg: 'en',
71
+ lc: 'GB',
72
+ mistyped: '6',
73
+ authkey: Buffer.from(params.noiseKey.public).toString('base64url'),
74
+ e_regid: e_regid.toString('base64url'),
75
+ e_keytype: 'BQ',
76
+ e_ident: Buffer.from(params.signedIdentityKey.public).toString('base64url'),
77
+ // e_skey_id: e_skey_id.toString('base64url'),
78
+ e_skey_id: 'AAAA',
79
+ e_skey_val: Buffer.from(params.signedPreKey.keyPair.public).toString('base64url'),
80
+ e_skey_sig: Buffer.from(params.signedPreKey.signature).toString('base64url'),
81
+ fdid: params.phoneId,
82
+ network_ratio_type: '1',
83
+ expid: params.deviceId,
84
+ simnum: '1',
85
+ hasinrc: '1',
86
+ pid: Math.floor(Math.random() * 1000).toString(),
87
+ id: convertBufferToUrlHex(params.identityId),
88
+ backup_token: convertBufferToUrlHex(params.backupToken),
89
+ token: (0, crypto_1.md5)(Buffer.concat([Defaults_1.MOBILE_TOKEN, Buffer.from(params.phoneNumberNationalNumber)])).toString('hex'),
90
+ fraud_checkpoint_code: params.captcha,
91
+ };
92
+ }
93
+ exports.registrationParams = registrationParams;
94
+ /**
95
+ * Requests a registration code for the given phone number.
96
+ */
97
+ function mobileRegisterCode(params, fetchOptions) {
98
+ return mobileRegisterFetch('/code', {
99
+ params: {
100
+ ...registrationParams(params),
101
+ mcc: `${params.phoneNumberMobileCountryCode}`.padStart(3, '0'),
102
+ mnc: `${params.phoneNumberMobileNetworkCode || '001'}`.padStart(3, '0'),
103
+ sim_mcc: '000',
104
+ sim_mnc: '000',
105
+ method: (params === null || params === void 0 ? void 0 : params.method) || 'sms',
106
+ reason: '',
107
+ hasav: '1'
108
+ },
109
+ ...fetchOptions,
110
+ });
111
+ }
112
+ exports.mobileRegisterCode = mobileRegisterCode;
113
+ function mobileRegisterExists(params, fetchOptions) {
114
+ return mobileRegisterFetch('/exist', {
115
+ params: registrationParams(params),
116
+ ...fetchOptions
117
+ });
118
+ }
119
+ exports.mobileRegisterExists = mobileRegisterExists;
120
+ /**
121
+ * Registers the phone number on whatsapp with the received OTP code.
122
+ */
123
+ async function mobileRegister(params, fetchOptions) {
124
+ //const result = await mobileRegisterFetch(`/reg_onboard_abprop?cc=${params.phoneNumberCountryCode}&in=${params.phoneNumberNationalNumber}&rc=0`)
125
+ return mobileRegisterFetch('/register', {
126
+ params: { ...registrationParams(params), code: params.code.replace('-', '') },
127
+ ...fetchOptions,
128
+ });
129
+ }
130
+ exports.mobileRegister = mobileRegister;
131
+ /**
132
+ * Encrypts the given string as AEAD aes-256-gcm with the public whatsapp key and a random keypair.
133
+ */
134
+ function mobileRegisterEncrypt(data) {
135
+ const keypair = crypto_1.Curve.generateKeyPair();
136
+ const key = crypto_1.Curve.sharedKey(keypair.private, Defaults_1.REGISTRATION_PUBLIC_KEY);
137
+ const buffer = (0, crypto_1.aesEncryptGCM)(Buffer.from(data), new Uint8Array(key), Buffer.alloc(12), Buffer.alloc(0));
138
+ return Buffer.concat([Buffer.from(keypair.public), buffer]).toString('base64url');
139
+ }
140
+ exports.mobileRegisterEncrypt = mobileRegisterEncrypt;
141
+ async function mobileRegisterFetch(path, opts = {}) {
142
+ let url = `${Defaults_1.MOBILE_REGISTRATION_ENDPOINT}${path}`;
143
+ if (opts.params) {
144
+ const parameter = [];
145
+ for (const param in opts.params) {
146
+ if (opts.params[param] !== null && opts.params[param] !== undefined) {
147
+ parameter.push(param + '=' + urlencode(opts.params[param]));
148
+ }
149
+ }
150
+ url += `?${parameter.join('&')}`;
151
+ delete opts.params;
152
+ }
153
+ if (!opts.headers) {
154
+ opts.headers = {};
155
+ }
156
+ opts.headers['User-Agent'] = Defaults_1.MOBILE_USERAGENT;
157
+ const response = await (0, axios_1.default)(url, opts);
158
+ var json = response.data;
159
+ if (response.status > 300 || json.reason) {
160
+ throw json;
161
+ }
162
+ if (json.status && !['ok', 'sent'].includes(json.status)) {
163
+ throw json;
164
+ }
165
+ return json;
166
+ }
167
+ exports.mobileRegisterFetch = mobileRegisterFetch;