@badzz88/baileys 8.5.6 → 8.5.8

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 (225) hide show
  1. package/README.md +337 -1055
  2. package/WAProto/WAProto.proto +28 -1189
  3. package/WAProto/fix-imports.js +79 -69
  4. package/WAProto/index.d.ts +71491 -15254
  5. package/WAProto/index.js +126436 -19814
  6. package/engine-requirements.js +8 -15
  7. package/lib/Defaults/index.js +130 -0
  8. package/{src → lib}/Signal/Group/ciphertext-message.js +2 -5
  9. package/lib/Signal/Group/group-session-builder.js +30 -0
  10. package/{src → lib}/Signal/Group/group_cipher.js +11 -11
  11. package/lib/Signal/Group/index.js +12 -0
  12. package/lib/Signal/Group/keyhelper.js +18 -0
  13. package/{src → lib}/Signal/Group/sender-chain-key.js +6 -9
  14. package/{src → lib}/Signal/Group/sender-key-distribution-message.js +6 -9
  15. package/{src → lib}/Signal/Group/sender-key-message.js +9 -12
  16. package/{src → lib}/Signal/Group/sender-key-name.js +2 -5
  17. package/{src → lib}/Signal/Group/sender-key-record.js +8 -11
  18. package/{src → lib}/Signal/Group/sender-key-state.js +6 -9
  19. package/lib/Signal/Group/sender-message-key.js +26 -0
  20. package/{src → lib}/Signal/libsignal.js +131 -155
  21. package/{src → lib}/Signal/lid-mapping.js +27 -23
  22. package/lib/Socket/Client/index.js +3 -0
  23. package/lib/Socket/Client/types.js +11 -0
  24. package/{src → lib}/Socket/Client/websocket.js +11 -18
  25. package/{src → lib}/Socket/business.js +35 -67
  26. package/{src → lib}/Socket/chats.js +294 -550
  27. package/{src → lib}/Socket/communities.js +82 -114
  28. package/lib/Socket/graphql.js +716 -0
  29. package/lib/Socket/groups.js +374 -0
  30. package/lib/Socket/index.js +18 -0
  31. package/lib/Socket/interop.js +463 -0
  32. package/{src → lib}/Socket/luxu.js +120 -82
  33. package/lib/Socket/messages-recv.js +1916 -0
  34. package/lib/Socket/messages-send.js +1436 -0
  35. package/lib/Socket/mex.js +54 -0
  36. package/lib/Socket/newsletter.js +757 -0
  37. package/lib/Socket/privacy.js +318 -0
  38. package/{src → lib}/Socket/socket.js +356 -244
  39. package/lib/Socket/username.js +236 -0
  40. package/lib/Store/index.js +10 -0
  41. package/{src → lib}/Store/keyed-db.js +11 -21
  42. package/lib/Store/make-cache-manager-store.js +85 -0
  43. package/lib/Store/make-in-memory-store.js +244 -0
  44. package/{src → lib}/Store/make-ordered-dictionary.js +19 -25
  45. package/{src → lib}/Store/object-repository.js +11 -5
  46. package/lib/Types/Auth.js +2 -0
  47. package/lib/Types/Bussines.js +2 -0
  48. package/lib/Types/Call.js +2 -0
  49. package/lib/Types/Chat.js +8 -0
  50. package/lib/Types/Contact.js +2 -0
  51. package/lib/Types/Events.js +2 -0
  52. package/lib/Types/GroupMetadata.js +2 -0
  53. package/lib/Types/Label.js +25 -0
  54. package/lib/Types/LabelAssociation.js +7 -0
  55. package/lib/Types/Message.js +11 -0
  56. package/lib/Types/Mex.js +111 -0
  57. package/lib/Types/Product.js +2 -0
  58. package/lib/Types/Signal.js +2 -0
  59. package/lib/Types/Socket.js +3 -0
  60. package/lib/Types/State.js +56 -0
  61. package/lib/Types/USync.js +2 -0
  62. package/lib/Types/index.js +26 -0
  63. package/{src → lib}/Utils/auth-utils.js +91 -43
  64. package/lib/Utils/browser-utils.js +48 -0
  65. package/lib/Utils/business.js +231 -0
  66. package/lib/Utils/chat-utils.js +872 -0
  67. package/lib/Utils/companion-reg-client-utils.js +35 -0
  68. package/lib/Utils/crypto.js +118 -0
  69. package/lib/Utils/decode-wa-message.js +350 -0
  70. package/{src → lib}/Utils/event-buffer.js +81 -39
  71. package/lib/Utils/generics.js +403 -0
  72. package/lib/Utils/history.js +134 -0
  73. package/{src → lib}/Utils/identity-change-handler.js +9 -11
  74. package/lib/Utils/index.js +23 -0
  75. package/lib/Utils/link-preview.js +85 -0
  76. package/lib/Utils/logger.js +3 -0
  77. package/lib/Utils/lt-hash.js +8 -0
  78. package/{src → lib}/Utils/make-mutex.js +7 -10
  79. package/lib/Utils/message-composer.js +273 -0
  80. package/{src → lib}/Utils/message-retry-manager.js +76 -28
  81. package/lib/Utils/messages-media.js +870 -0
  82. package/lib/Utils/messages.js +1337 -0
  83. package/lib/Utils/noise-handler.js +201 -0
  84. package/{src → lib}/Utils/offline-node-processor.js +10 -4
  85. package/{src → lib}/Utils/pre-key-manager.js +27 -11
  86. package/lib/Utils/process-message.js +630 -0
  87. package/{src → lib}/Utils/reporting-utils.js +12 -15
  88. package/lib/Utils/signal.js +201 -0
  89. package/{src → lib}/Utils/stanza-ack.js +12 -4
  90. package/lib/Utils/sticker.js +110 -0
  91. package/{src → lib}/Utils/sync-action-utils.js +14 -10
  92. package/{src → lib}/Utils/tc-token-utils.js +48 -43
  93. package/{src → lib}/Utils/use-multi-file-auth-state.js +35 -25
  94. package/lib/Utils/validate-connection.js +203 -0
  95. package/{src → lib}/WABinary/constants.js +9 -12
  96. package/{src → lib}/WABinary/decode.js +38 -118
  97. package/{src → lib}/WABinary/encode.js +6 -11
  98. package/lib/WABinary/generic-utils.js +204 -0
  99. package/lib/WABinary/index.js +6 -0
  100. package/lib/WABinary/jid-utils.js +98 -0
  101. package/lib/WABinary/types.js +2 -0
  102. package/{src → lib}/WAM/BinaryInfo.js +2 -5
  103. package/{src → lib}/WAM/constants.js +4 -16635
  104. package/{src → lib}/WAM/encode.js +18 -17
  105. package/lib/WAM/index.js +4 -0
  106. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +53 -0
  107. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +43 -0
  108. package/lib/WAUSync/Protocols/USyncContactProtocol.js +54 -0
  109. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  110. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  111. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +58 -0
  112. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +30 -0
  113. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +32 -0
  114. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +28 -0
  115. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +39 -0
  116. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +38 -0
  117. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +27 -0
  118. package/lib/WAUSync/Protocols/index.js +12 -0
  119. package/lib/WAUSync/USyncQuery.js +151 -0
  120. package/lib/WAUSync/USyncUser.js +56 -0
  121. package/lib/WAUSync/index.js +3 -0
  122. package/{src → lib}/index.js +16 -51
  123. package/package.json +129 -99
  124. package/LICENSE +0 -21
  125. package/src/Defaults/index.js +0 -186
  126. package/src/Defaults/phonenumber-mcc.json +0 -223
  127. package/src/Signal/Group/group-session-builder.js +0 -86
  128. package/src/Signal/Group/index.js +0 -140
  129. package/src/Signal/Group/keyhelper.js +0 -77
  130. package/src/Signal/Group/sender-message-key.js +0 -29
  131. package/src/Socket/Client/index.js +0 -31
  132. package/src/Socket/Client/types.js +0 -13
  133. package/src/Socket/aigroups.js +0 -221
  134. package/src/Socket/graphql.js +0 -523
  135. package/src/Socket/groups.js +0 -516
  136. package/src/Socket/index.js +0 -31
  137. package/src/Socket/interactive-handler.js +0 -527
  138. package/src/Socket/interop.js +0 -339
  139. package/src/Socket/managed-account.js +0 -98
  140. package/src/Socket/messages-recv.js +0 -2685
  141. package/src/Socket/messages-send.js +0 -2047
  142. package/src/Socket/mex.js +0 -57
  143. package/src/Socket/newsletter.js +0 -455
  144. package/src/Socket/privacy.js +0 -125
  145. package/src/Socket/registration.js +0 -236
  146. package/src/Socket/text-router.js +0 -65
  147. package/src/Socket/username.js +0 -130
  148. package/src/Store/index.js +0 -33
  149. package/src/Store/make-cache-manager-store.js +0 -84
  150. package/src/Store/make-in-memory-store.js +0 -551
  151. package/src/Types/Auth.js +0 -31
  152. package/src/Types/Bussines.js +0 -2
  153. package/src/Types/Call.js +0 -2
  154. package/src/Types/Chat.js +0 -4
  155. package/src/Types/Contact.js +0 -2
  156. package/src/Types/Events.js +0 -2
  157. package/src/Types/GroupMetadata.js +0 -2
  158. package/src/Types/Label.js +0 -26
  159. package/src/Types/LabelAssociation.js +0 -8
  160. package/src/Types/Message.js +0 -93
  161. package/src/Types/Mex.js +0 -112
  162. package/src/Types/Newsletter.js +0 -109
  163. package/src/Types/Product.js +0 -2
  164. package/src/Types/Signal.js +0 -2
  165. package/src/Types/Socket.js +0 -2
  166. package/src/Types/State.js +0 -62
  167. package/src/Types/USync.js +0 -2
  168. package/src/Types/index.js +0 -56
  169. package/src/Utils/browser-utils.js +0 -112
  170. package/src/Utils/business.js +0 -240
  171. package/src/Utils/chat-utils.js +0 -1230
  172. package/src/Utils/command-loader.d.ts +0 -27
  173. package/src/Utils/command-loader.js +0 -89
  174. package/src/Utils/companion-reg-client-utils.js +0 -40
  175. package/src/Utils/consumer-application.js +0 -105
  176. package/src/Utils/crypto.js +0 -118
  177. package/src/Utils/curve25519-js.js +0 -242
  178. package/src/Utils/decode-wa-message.js +0 -529
  179. package/src/Utils/generics.js +0 -483
  180. package/src/Utils/group-history.js +0 -44
  181. package/src/Utils/history.js +0 -232
  182. package/src/Utils/index.js +0 -58
  183. package/src/Utils/jid-display-normalization.js +0 -195
  184. package/src/Utils/link-preview.js +0 -135
  185. package/src/Utils/logger.js +0 -8
  186. package/src/Utils/lt-hash.js +0 -25
  187. package/src/Utils/message-composer.js +0 -471
  188. package/src/Utils/messages-media.js +0 -843
  189. package/src/Utils/messages.js +0 -2817
  190. package/src/Utils/meta-ai-msmsg.js +0 -222
  191. package/src/Utils/native-bridge.js +0 -68
  192. package/src/Utils/noise-handler.js +0 -169
  193. package/src/Utils/process-message.js +0 -950
  194. package/src/Utils/session-pool.d.ts +0 -14
  195. package/src/Utils/session-pool.js +0 -70
  196. package/src/Utils/signal.js +0 -217
  197. package/src/Utils/sticker.d.ts +0 -13
  198. package/src/Utils/sticker.js +0 -123
  199. package/src/Utils/validate-connection.js +0 -209
  200. package/src/Utils/view-once-cache.d.ts +0 -12
  201. package/src/Utils/view-once-cache.js +0 -63
  202. package/src/Utils/voip-rekey.js +0 -22
  203. package/src/WABinary/generic-utils.js +0 -238
  204. package/src/WABinary/index.js +0 -34
  205. package/src/WABinary/jid-utils.js +0 -351
  206. package/src/WABinary/types.js +0 -2
  207. package/src/WAM/index.js +0 -32
  208. package/src/WAUSync/Protocols/USyncBotProfileProtocol.js +0 -53
  209. package/src/WAUSync/Protocols/USyncBusinessProtocol.js +0 -44
  210. package/src/WAUSync/Protocols/USyncContactProtocol.js +0 -55
  211. package/src/WAUSync/Protocols/USyncDeviceProtocol.js +0 -55
  212. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.js +0 -31
  213. package/src/WAUSync/Protocols/USyncFeatureProtocol.js +0 -54
  214. package/src/WAUSync/Protocols/USyncLIDProtocol.js +0 -32
  215. package/src/WAUSync/Protocols/USyncNewsletterProtocol.js +0 -473
  216. package/src/WAUSync/Protocols/USyncPictureProtocol.js +0 -34
  217. package/src/WAUSync/Protocols/USyncSidelistProtocol.js +0 -29
  218. package/src/WAUSync/Protocols/USyncStatusProtocol.js +0 -42
  219. package/src/WAUSync/Protocols/USyncTextStatusProtocol.js +0 -38
  220. package/src/WAUSync/Protocols/USyncUsernameProtocol.js +0 -28
  221. package/src/WAUSync/Protocols/index.js +0 -40
  222. package/src/WAUSync/USyncQuery.js +0 -126
  223. package/src/WAUSync/USyncUser.js +0 -50
  224. package/src/WAUSync/index.js +0 -32
  225. package/src/antiban.js +0 -4152
@@ -1,28 +1,38 @@
1
- 'use strict';
2
- Object.defineProperty(exports, '__esModule', { value: true });
3
- exports.useMultiFileAuthState = void 0;
4
- const async_mutex_1 = require('async-mutex');
5
- const promises_1 = require('fs/promises');
6
- const path_1 = require('path');
7
- const index_js_1 = require('../../WAProto/index.js');
8
- const auth_utils_1 = require('./auth-utils');
9
- const generics_1 = require('./generics');
1
+ import { Mutex } from 'async-mutex';
2
+ import { mkdir, readFile, stat, unlink, writeFile } from 'fs/promises';
3
+ import { join } from 'path';
4
+ import { proto } from '../../WAProto/index.js';
5
+ import { initAuthCreds } from './auth-utils.js';
6
+ import { BufferJSON } from './generics.js';
7
+ // We need to lock files due to the fact that we are using async functions to read and write files
8
+ // https://github.com/WhiskeySockets/Baileys/issues/794
9
+ // https://github.com/nodejs/node/issues/26338
10
+ // Use a Map to store mutexes for each file path
10
11
  const fileLocks = new Map();
11
- const getFileLock = path => {
12
+ // Get or create a mutex for a specific file path
13
+ const getFileLock = (path) => {
12
14
  let mutex = fileLocks.get(path);
13
15
  if (!mutex) {
14
- mutex = new async_mutex_1.Mutex();
16
+ mutex = new Mutex();
15
17
  fileLocks.set(path, mutex);
16
18
  }
17
19
  return mutex;
18
20
  };
19
- const useMultiFileAuthState = async (folder) => {
21
+ /**
22
+ * stores the full authentication state in a single folder.
23
+ * Far more efficient than singlefileauthstate
24
+ *
25
+ * Again, I wouldn't endorse this for any production level use other than perhaps a bot.
26
+ * Would recommend writing an auth state for use with a proper SQL or No-SQL DB
27
+ * */
28
+ export const useMultiFileAuthState = async (folder) => {
29
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
20
30
  const writeData = async (data, file) => {
21
- const filePath = (0, path_1.join)(folder, fixFileName(file));
31
+ const filePath = join(folder, fixFileName(file));
22
32
  const mutex = getFileLock(filePath);
23
33
  return mutex.acquire().then(async (release) => {
24
34
  try {
25
- await (0, promises_1.writeFile)(filePath, JSON.stringify(data, generics_1.BufferJSON.replacer));
35
+ await writeFile(filePath, JSON.stringify(data, BufferJSON.replacer));
26
36
  }
27
37
  finally {
28
38
  release();
@@ -31,12 +41,12 @@ const useMultiFileAuthState = async (folder) => {
31
41
  };
32
42
  const readData = async (file) => {
33
43
  try {
34
- const filePath = (0, path_1.join)(folder, fixFileName(file));
44
+ const filePath = join(folder, fixFileName(file));
35
45
  const mutex = getFileLock(filePath);
36
46
  return await mutex.acquire().then(async (release) => {
37
47
  try {
38
- const data = await (0, promises_1.readFile)(filePath, { encoding: 'utf-8' });
39
- return JSON.parse(data, generics_1.BufferJSON.reviver);
48
+ const data = await readFile(filePath, { encoding: 'utf-8' });
49
+ return JSON.parse(data, BufferJSON.reviver);
40
50
  }
41
51
  finally {
42
52
  release();
@@ -49,11 +59,11 @@ const useMultiFileAuthState = async (folder) => {
49
59
  };
50
60
  const removeData = async (file) => {
51
61
  try {
52
- const filePath = (0, path_1.join)(folder, fixFileName(file));
62
+ const filePath = join(folder, fixFileName(file));
53
63
  const mutex = getFileLock(filePath);
54
64
  return mutex.acquire().then(async (release) => {
55
65
  try {
56
- await (0, promises_1.unlink)(filePath);
66
+ await unlink(filePath);
57
67
  }
58
68
  catch {
59
69
  }
@@ -64,17 +74,17 @@ const useMultiFileAuthState = async (folder) => {
64
74
  }
65
75
  catch { }
66
76
  };
67
- const folderInfo = await (0, promises_1.stat)(folder).catch(() => { });
77
+ const folderInfo = await stat(folder).catch(() => { });
68
78
  if (folderInfo) {
69
79
  if (!folderInfo.isDirectory()) {
70
80
  throw new Error(`found something that is not a directory at ${folder}, either delete it or specify a different location`);
71
81
  }
72
82
  }
73
83
  else {
74
- await (0, promises_1.mkdir)(folder, { recursive: true });
84
+ await mkdir(folder, { recursive: true });
75
85
  }
76
- const fixFileName = file => file?.replace(/\//g, '__')?.replace(/:/g, '-');
77
- const creds = (await readData('creds.json')) || (0, auth_utils_1.initAuthCreds)();
86
+ const fixFileName = (file) => file?.replace(/\//g, '__')?.replace(/:/g, '-');
87
+ const creds = (await readData('creds.json')) || initAuthCreds();
78
88
  return {
79
89
  state: {
80
90
  creds,
@@ -84,7 +94,7 @@ const useMultiFileAuthState = async (folder) => {
84
94
  await Promise.all(ids.map(async (id) => {
85
95
  let value = await readData(`${type}-${id}.json`);
86
96
  if (type === 'app-state-sync-key' && value) {
87
- value = index_js_1.proto.Message.AppStateSyncKeyData.fromObject(value);
97
+ value = proto.Message.AppStateSyncKeyData.fromObject(value);
88
98
  }
89
99
  data[id] = value;
90
100
  }));
@@ -108,4 +118,4 @@ const useMultiFileAuthState = async (folder) => {
108
118
  }
109
119
  };
110
120
  };
111
- exports.useMultiFileAuthState = useMultiFileAuthState;
121
+ //# sourceMappingURL=use-multi-file-auth-state.js.map
@@ -0,0 +1,203 @@
1
+ import { Boom } from '@hapi/boom';
2
+ import { createHash } from 'crypto';
3
+ import { proto } from '../../WAProto/index.js';
4
+ import { KEY_BUNDLE_TYPE, WA_ADV_ACCOUNT_SIG_PREFIX, WA_ADV_DEVICE_SIG_PREFIX, WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX } from '../Defaults/index.js';
5
+ import { getBinaryNodeChild, jidDecode, S_WHATSAPP_NET } from '../WABinary/index.js';
6
+ import { Curve, hmacSign } from './crypto.js';
7
+ import { encodeBigEndian } from './generics.js';
8
+ import { createSignalIdentity } from './signal.js';
9
+ const getUserAgent = (config) => {
10
+ return {
11
+ appVersion: {
12
+ primary: config.version[0],
13
+ secondary: config.version[1],
14
+ tertiary: config.version[2]
15
+ },
16
+ platform: proto.ClientPayload.UserAgent.Platform.MACOS,
17
+ releaseChannel: proto.ClientPayload.UserAgent.ReleaseChannel.RELEASE,
18
+ osVersion: '0.1',
19
+ device: 'Desktop',
20
+ osBuildNumber: '0.1',
21
+ localeLanguageIso6391: 'en',
22
+ mnc: '000',
23
+ mcc: '000',
24
+ localeCountryIso31661Alpha2: config.countryCode
25
+ };
26
+ };
27
+ const PLATFORM_MAP = {
28
+ 'Mac OS': proto.ClientPayload.WebInfo.WebSubPlatform.DARWIN,
29
+ Windows: proto.ClientPayload.WebInfo.WebSubPlatform.WIN32
30
+ };
31
+ const getWebInfo = (config) => {
32
+ let webSubPlatform = proto.ClientPayload.WebInfo.WebSubPlatform.WEB_BROWSER;
33
+ if (config.syncFullHistory &&
34
+ PLATFORM_MAP[config.browser[0]] &&
35
+ config.browser[1] === 'Desktop') {
36
+ webSubPlatform = PLATFORM_MAP[config.browser[0]];
37
+ }
38
+ return { webSubPlatform };
39
+ };
40
+ const getClientPayload = (config) => {
41
+ const payload = {
42
+ connectType: proto.ClientPayload.ConnectType.WIFI_UNKNOWN,
43
+ connectReason: proto.ClientPayload.ConnectReason.USER_ACTIVATED,
44
+ userAgent: getUserAgent(config)
45
+ };
46
+ payload.webInfo = getWebInfo(config);
47
+ if (config.pushName) {
48
+ payload.pushName = config.pushName;
49
+ }
50
+ return payload;
51
+ };
52
+ export const generateLoginNode = (userJid, config) => {
53
+ const { user, device } = jidDecode(userJid);
54
+ const payload = {
55
+ ...getClientPayload(config),
56
+ passive: true,
57
+ pull: true,
58
+ username: +user,
59
+ device: device,
60
+ // TODO: investigate (hard set as false atm)
61
+ lidDbMigrated: false
62
+ };
63
+ return proto.ClientPayload.fromObject(payload);
64
+ };
65
+ const getPlatformType = (platform) => {
66
+ const platformType = platform.toUpperCase();
67
+ return (proto.DeviceProps.PlatformType[platformType] ||
68
+ proto.DeviceProps.PlatformType.CHROME);
69
+ };
70
+ export const generateRegistrationNode = ({ registrationId, signedPreKey, signedIdentityKey }, config) => {
71
+ // the app version needs to be md5 hashed
72
+ // and passed in
73
+ const appVersionBuf = createHash('md5')
74
+ .update(config.version.join('.')) // join as string
75
+ .digest();
76
+ const companion = {
77
+ os: config.browser[0],
78
+ platformType: getPlatformType(config.browser[1]),
79
+ requireFullSync: config.syncFullHistory,
80
+ historySyncConfig: {
81
+ storageQuotaMb: 10240,
82
+ inlineInitialPayloadInE2EeMsg: true,
83
+ recentSyncDaysLimit: undefined,
84
+ supportCallLogHistory: false,
85
+ supportBotUserAgentChatHistory: true,
86
+ supportCagReactionsAndPolls: true,
87
+ supportBizHostedMsg: true,
88
+ supportRecentSyncChunkMessageCountTuning: true,
89
+ supportHostedGroupMsg: true,
90
+ supportFbidBotChatHistory: true,
91
+ supportAddOnHistorySyncMigration: undefined,
92
+ supportMessageAssociation: true,
93
+ supportGroupHistory: false,
94
+ onDemandReady: undefined,
95
+ supportGuestChat: undefined
96
+ },
97
+ version: {
98
+ primary: 10,
99
+ secondary: 15,
100
+ tertiary: 7
101
+ }
102
+ };
103
+ const companionProto = proto.DeviceProps.encode(companion).finish();
104
+ const registerPayload = {
105
+ ...getClientPayload(config),
106
+ passive: false,
107
+ pull: false,
108
+ devicePairingData: {
109
+ buildHash: appVersionBuf,
110
+ deviceProps: companionProto,
111
+ eRegid: encodeBigEndian(registrationId),
112
+ eKeytype: KEY_BUNDLE_TYPE,
113
+ eIdent: signedIdentityKey.public,
114
+ eSkeyId: encodeBigEndian(signedPreKey.keyId, 3),
115
+ eSkeyVal: signedPreKey.keyPair.public,
116
+ eSkeySig: signedPreKey.signature
117
+ }
118
+ };
119
+ return proto.ClientPayload.fromObject(registerPayload);
120
+ };
121
+ export const configureSuccessfulPairing = (stanza, { advSecretKey, signedIdentityKey, signalIdentities }) => {
122
+ const msgId = stanza.attrs.id;
123
+ const pairSuccessNode = getBinaryNodeChild(stanza, 'pair-success');
124
+ const deviceIdentityNode = getBinaryNodeChild(pairSuccessNode, 'device-identity');
125
+ const platformNode = getBinaryNodeChild(pairSuccessNode, 'platform');
126
+ const deviceNode = getBinaryNodeChild(pairSuccessNode, 'device');
127
+ const businessNode = getBinaryNodeChild(pairSuccessNode, 'biz');
128
+ if (!deviceIdentityNode || !deviceNode) {
129
+ throw new Boom('Missing device-identity or device in pair success node', { data: stanza });
130
+ }
131
+ const bizName = businessNode?.attrs.name;
132
+ const jid = deviceNode.attrs.jid;
133
+ const lid = deviceNode.attrs.lid;
134
+ const { details, hmac, accountType } = proto.ADVSignedDeviceIdentityHMAC.decode(deviceIdentityNode.content);
135
+ let hmacPrefix = Buffer.from([]);
136
+ if (accountType !== undefined && accountType === proto.ADVEncryptionType.HOSTED) {
137
+ hmacPrefix = WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX;
138
+ }
139
+ const advSign = hmacSign(Buffer.concat([hmacPrefix, details]), Buffer.from(advSecretKey, 'base64'));
140
+ if (Buffer.compare(hmac, advSign) !== 0) {
141
+ throw new Boom('Invalid account signature');
142
+ }
143
+ const account = proto.ADVSignedDeviceIdentity.decode(details);
144
+ const { accountSignatureKey, accountSignature, details: deviceDetails } = account;
145
+ const deviceIdentity = proto.ADVDeviceIdentity.decode(deviceDetails);
146
+ const accountSignaturePrefix = deviceIdentity.deviceType === proto.ADVEncryptionType.HOSTED
147
+ ? WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX
148
+ : WA_ADV_ACCOUNT_SIG_PREFIX;
149
+ const accountMsg = Buffer.concat([accountSignaturePrefix, deviceDetails, signedIdentityKey.public]);
150
+ if (!Curve.verify(accountSignatureKey, accountMsg, accountSignature)) {
151
+ throw new Boom('Failed to verify account signature');
152
+ }
153
+ const deviceMsg = Buffer.concat([
154
+ WA_ADV_DEVICE_SIG_PREFIX,
155
+ deviceDetails,
156
+ signedIdentityKey.public,
157
+ accountSignatureKey
158
+ ]);
159
+ account.deviceSignature = Curve.sign(signedIdentityKey.private, deviceMsg);
160
+ const identity = createSignalIdentity(lid, accountSignatureKey);
161
+ const accountEnc = encodeSignedDeviceIdentity(account, false);
162
+ const reply = {
163
+ tag: 'iq',
164
+ attrs: {
165
+ to: S_WHATSAPP_NET,
166
+ type: 'result',
167
+ id: msgId
168
+ },
169
+ content: [
170
+ {
171
+ tag: 'pair-device-sign',
172
+ attrs: {},
173
+ content: [
174
+ {
175
+ tag: 'device-identity',
176
+ attrs: { 'key-index': deviceIdentity.keyIndex.toString() },
177
+ content: accountEnc
178
+ }
179
+ ]
180
+ }
181
+ ]
182
+ };
183
+ const authUpdate = {
184
+ account,
185
+ me: { id: jid, name: bizName, lid },
186
+ signalIdentities: [...(signalIdentities || []), identity],
187
+ platform: platformNode?.attrs.name
188
+ };
189
+ return {
190
+ creds: authUpdate,
191
+ reply
192
+ };
193
+ };
194
+ export const encodeSignedDeviceIdentity = (account, includeSignatureKey) => {
195
+ account = { ...account };
196
+ // set to null if we are not to include the signature key
197
+ // or if we are including the signature key but it is empty
198
+ if (!includeSignatureKey || !account.accountSignatureKey?.length) {
199
+ account.accountSignatureKey = null;
200
+ }
201
+ return proto.ADVSignedDeviceIdentity.encode(account).finish();
202
+ };
203
+ //# sourceMappingURL=validate-connection.js.map
@@ -1,13 +1,9 @@
1
- 'use strict';
2
- Object.defineProperty(exports, '__esModule', { value: true });
3
- exports.TOKEN_MAP = exports.SINGLE_BYTE_TOKENS = exports.DOUBLE_BYTE_TOKENS = exports.TAGS = void 0;
4
- exports.TAGS = {
1
+ export const TAGS = {
5
2
  LIST_EMPTY: 0,
6
3
  DICTIONARY_0: 236,
7
4
  DICTIONARY_1: 237,
8
5
  DICTIONARY_2: 238,
9
6
  DICTIONARY_3: 239,
10
- INTEROP_JID_TUPLE: 244,
11
7
  INTEROP_JID: 245,
12
8
  FB_JID: 246,
13
9
  AD_JID: 247,
@@ -21,7 +17,7 @@ exports.TAGS = {
21
17
  NIBBLE_8: 255,
22
18
  PACKED_MAX: 127
23
19
  };
24
- exports.DOUBLE_BYTE_TOKENS = [
20
+ export const DOUBLE_BYTE_TOKENS = [
25
21
  [
26
22
  'read-self',
27
23
  'active',
@@ -1055,7 +1051,7 @@ exports.DOUBLE_BYTE_TOKENS = [
1055
1051
  '1961'
1056
1052
  ]
1057
1053
  ];
1058
- exports.SINGLE_BYTE_TOKENS = [
1054
+ export const SINGLE_BYTE_TOKENS = [
1059
1055
  '',
1060
1056
  'xmlstreamstart',
1061
1057
  'xmlstreamend',
@@ -1293,12 +1289,13 @@ exports.SINGLE_BYTE_TOKENS = [
1293
1289
  '03',
1294
1290
  'screen_height'
1295
1291
  ];
1296
- exports.TOKEN_MAP = {};
1297
- for (const [i, SINGLE_BYTE_TOKEN] of exports.SINGLE_BYTE_TOKENS.entries()) {
1298
- exports.TOKEN_MAP[SINGLE_BYTE_TOKEN] = { index: i };
1292
+ export const TOKEN_MAP = {};
1293
+ for (const [i, SINGLE_BYTE_TOKEN] of SINGLE_BYTE_TOKENS.entries()) {
1294
+ TOKEN_MAP[SINGLE_BYTE_TOKEN] = { index: i };
1299
1295
  }
1300
- for (const [i, DOUBLE_BYTE_TOKEN] of exports.DOUBLE_BYTE_TOKENS.entries()) {
1296
+ for (const [i, DOUBLE_BYTE_TOKEN] of DOUBLE_BYTE_TOKENS.entries()) {
1301
1297
  for (const [j, element] of DOUBLE_BYTE_TOKEN.entries()) {
1302
- exports.TOKEN_MAP[element] = { dict: i, index: j };
1298
+ TOKEN_MAP[element] = { dict: i, index: j };
1303
1299
  }
1304
1300
  }
1301
+ //# sourceMappingURL=constants.js.map
@@ -1,79 +1,21 @@
1
- 'use strict';
2
- var __createBinding = (this && this.__createBinding) ||
3
- (Object.create
4
- ? function (o, m, k, k2) {
5
- if (k2 === undefined)
6
- k2 = k;
7
- var desc = Object.getOwnPropertyDescriptor(m, k);
8
- if (!desc || ('get' in desc ? !m.__esModule : desc.writable || desc.configurable)) {
9
- desc = {
10
- enumerable: true,
11
- get: function () {
12
- return m[k];
13
- }
14
- };
15
- }
16
- Object.defineProperty(o, k2, desc);
17
- }
18
- : function (o, m, k, k2) {
19
- if (k2 === undefined)
20
- k2 = k;
21
- o[k2] = m[k];
22
- });
23
- var __setModuleDefault = (this && this.__setModuleDefault) ||
24
- (Object.create
25
- ? function (o, v) {
26
- Object.defineProperty(o, 'default', { enumerable: true, value: v });
27
- }
28
- : function (o, v) {
29
- o['default'] = v;
30
- });
31
- var __importStar = (this && this.__importStar) ||
32
- (function () {
33
- var ownKeys = function (o) {
34
- ownKeys =
35
- Object.getOwnPropertyNames ||
36
- function (o) {
37
- var ar = [];
38
- for (var k in o)
39
- if (Object.prototype.hasOwnProperty.call(o, k))
40
- ar[ar.length] = k;
41
- return ar;
42
- };
43
- return ownKeys(o);
44
- };
45
- return function (mod) {
46
- if (mod && mod.__esModule)
47
- return mod;
48
- var result = {};
49
- if (mod != null)
50
- for (var k = ownKeys(mod), i = 0; i < k.length; i++)
51
- if (k[i] !== 'default')
52
- __createBinding(result, mod, k[i]);
53
- __setModuleDefault(result, mod);
54
- return result;
55
- };
56
- })();
57
- Object.defineProperty(exports, '__esModule', { value: true });
58
- exports.decodeBinaryNode = exports.decodeDecompressedBinaryNode = exports.decompressingIfRequired = void 0;
59
- const util_1 = require('util');
60
- const zlib_1 = require('zlib');
61
- const constants = __importStar(require('./constants'));
62
- const jid_utils_1 = require('./jid-utils');
63
- const inflatePromise = (0, util_1.promisify)(zlib_1.inflate);
64
- const decompressingIfRequired = async (buffer) => {
1
+ import { promisify } from 'util';
2
+ import { inflate } from 'zlib';
3
+ import * as constants from './constants.js';
4
+ import { jidEncode, WAJIDDomains } from './jid-utils.js';
5
+ const inflatePromise = promisify(inflate);
6
+ export const decompressingIfRequired = async (buffer) => {
65
7
  if (2 & buffer.readUInt8()) {
66
8
  buffer = await inflatePromise(buffer.slice(1));
67
9
  }
68
10
  else {
11
+ // nodes with no compression have a 0x00 prefix, we remove that
69
12
  buffer = buffer.slice(1);
70
13
  }
71
14
  return buffer;
72
15
  };
73
- exports.decompressingIfRequired = decompressingIfRequired;
74
- const decodeDecompressedBinaryNode = (buffer, opts, indexRef = { index: 0 }) => {
16
+ export const decodeDecompressedBinaryNode = (buffer, opts, indexRef = { index: 0 }) => {
75
17
  const { DOUBLE_BYTE_TOKENS, SINGLE_BYTE_TOKENS, TAGS } = opts;
76
- const checkEOS = length => {
18
+ const checkEOS = (length) => {
77
19
  if (indexRef.index + length > buffer.length) {
78
20
  throw new Error('end of stream');
79
21
  }
@@ -87,13 +29,13 @@ const decodeDecompressedBinaryNode = (buffer, opts, indexRef = { index: 0 }) =>
87
29
  checkEOS(1);
88
30
  return next();
89
31
  };
90
- const readBytes = n => {
32
+ const readBytes = (n) => {
91
33
  checkEOS(n);
92
34
  const value = buffer.slice(indexRef.index, indexRef.index + n);
93
35
  indexRef.index += n;
94
36
  return value;
95
37
  };
96
- const readStringFromChars = length => {
38
+ const readStringFromChars = (length) => {
97
39
  return readBytes(length).toString('utf-8');
98
40
  };
99
41
  const readInt = (n, littleEndian = false) => {
@@ -109,13 +51,13 @@ const decodeDecompressedBinaryNode = (buffer, opts, indexRef = { index: 0 }) =>
109
51
  checkEOS(3);
110
52
  return ((next() & 15) << 16) + (next() << 8) + next();
111
53
  };
112
- const unpackHex = value => {
54
+ const unpackHex = (value) => {
113
55
  if (value >= 0 && value < 16) {
114
56
  return value < 10 ? '0'.charCodeAt(0) + value : 'A'.charCodeAt(0) + value - 10;
115
57
  }
116
58
  throw new Error('invalid hex: ' + value);
117
59
  };
118
- const unpackNibble = value => {
60
+ const unpackNibble = (value) => {
119
61
  if (value >= 0 && value <= 9) {
120
62
  return '0'.charCodeAt(0) + value;
121
63
  }
@@ -141,7 +83,7 @@ const decodeDecompressedBinaryNode = (buffer, opts, indexRef = { index: 0 }) =>
141
83
  throw new Error('unknown tag: ' + tag);
142
84
  }
143
85
  };
144
- const readPacked8 = tag => {
86
+ const readPacked8 = (tag) => {
145
87
  const startByte = readByte();
146
88
  let value = '';
147
89
  for (let i = 0; i < (startByte & 127); i++) {
@@ -154,10 +96,10 @@ const decodeDecompressedBinaryNode = (buffer, opts, indexRef = { index: 0 }) =>
154
96
  }
155
97
  return value;
156
98
  };
157
- const isListTag = tag => {
99
+ const isListTag = (tag) => {
158
100
  return tag === TAGS.LIST_EMPTY || tag === TAGS.LIST_8 || tag === TAGS.LIST_16;
159
101
  };
160
- const readListSize = tag => {
102
+ const readListSize = (tag) => {
161
103
  switch (tag) {
162
104
  case TAGS.LIST_EMPTY:
163
105
  return 0;
@@ -182,17 +124,17 @@ const decodeDecompressedBinaryNode = (buffer, opts, indexRef = { index: 0 }) =>
182
124
  const domainType = Number(rawDomainType);
183
125
  const device = readByte();
184
126
  const user = readString(readByte());
185
- let server = 's.whatsapp.net';
186
- if (domainType === jid_utils_1.WAJIDDomains.LID) {
127
+ let server = 's.whatsapp.net'; // default whatsapp server
128
+ if (domainType === WAJIDDomains.LID) {
187
129
  server = 'lid';
188
130
  }
189
- else if (domainType === jid_utils_1.WAJIDDomains.HOSTED) {
131
+ else if (domainType === WAJIDDomains.HOSTED) {
190
132
  server = 'hosted';
191
133
  }
192
- else if (domainType === jid_utils_1.WAJIDDomains.HOSTED_LID) {
134
+ else if (domainType === WAJIDDomains.HOSTED_LID) {
193
135
  server = 'hosted.lid';
194
136
  }
195
- return (0, jid_utils_1.jidEncode)(user, server, device);
137
+ return jidEncode(user, server, device);
196
138
  };
197
139
  const readFbJid = () => {
198
140
  const user = readString(readByte());
@@ -205,33 +147,16 @@ const decodeDecompressedBinaryNode = (buffer, opts, indexRef = { index: 0 }) =>
205
147
  const device = readInt(2);
206
148
  const integrator = readInt(2);
207
149
  let server = 'interop';
208
- if (indexRef.index < buffer.length) {
209
- const serverTag = buffer[indexRef.index];
210
- const isValidStringTag = (serverTag >= 1 && serverTag <= 235) ||
211
- serverTag === TAGS.BINARY_8 ||
212
- serverTag === TAGS.BINARY_20 ||
213
- serverTag === TAGS.BINARY_32 ||
214
- serverTag === TAGS.NIBBLE_8 ||
215
- serverTag === TAGS.HEX_8;
216
- if (isValidStringTag) {
217
- indexRef.index++;
218
- server = readString(serverTag);
219
- }
150
+ const beforeServer = indexRef.index;
151
+ try {
152
+ server = readString(readByte());
220
153
  }
221
- return `${integrator}-${user}:${device}@${server}`;
222
- };
223
- const readInteropJidTuple = () => {
224
- const user = readString(readByte());
225
- const device = readInt(2);
226
- const integrator = readInt(2);
227
- const domain = readByte();
228
- if (domain !== 0) {
229
- throw new Error(`invalid domain for INTEROP_JID_TUPLE: ${domain}`);
154
+ catch (err) {
155
+ indexRef.index = beforeServer;
230
156
  }
231
- const devicePart = device !== 0 ? `:${device}` : '';
232
- return `${integrator}-${user}${devicePart}@interop`;
157
+ return `${integrator}-${user}:${device}@${server}`;
233
158
  };
234
- const readString = tag => {
159
+ const readString = (tag) => {
235
160
  if (tag >= 1 && tag < SINGLE_BYTE_TOKENS.length) {
236
161
  return SINGLE_BYTE_TOKENS[tag] || '';
237
162
  }
@@ -253,8 +178,6 @@ const decodeDecompressedBinaryNode = (buffer, opts, indexRef = { index: 0 }) =>
253
178
  return readJidPair();
254
179
  case TAGS.FB_JID:
255
180
  return readFbJid();
256
- case TAGS.INTEROP_JID_TUPLE:
257
- return readInteropJidTuple();
258
181
  case TAGS.INTEROP_JID:
259
182
  return readInteropJid();
260
183
  case TAGS.AD_JID:
@@ -263,28 +186,25 @@ const decodeDecompressedBinaryNode = (buffer, opts, indexRef = { index: 0 }) =>
263
186
  case TAGS.NIBBLE_8:
264
187
  return readPacked8(tag);
265
188
  default:
266
- process.stderr.write(`[WABinary] unknown string tag 0x${tag.toString(16)} — token table outdated?\n`);
267
- return '';
189
+ throw new Error('invalid string with tag: ' + tag);
268
190
  }
269
191
  };
270
- const readList = tag => {
192
+ const readList = (tag) => {
271
193
  const items = [];
272
194
  const size = readListSize(tag);
273
195
  for (let i = 0; i < size; i++) {
274
- items.push((0, exports.decodeDecompressedBinaryNode)(buffer, opts, indexRef));
196
+ items.push(decodeDecompressedBinaryNode(buffer, opts, indexRef));
275
197
  }
276
198
  return items;
277
199
  };
278
200
  const getTokenDouble = (index1, index2) => {
279
201
  const dict = DOUBLE_BYTE_TOKENS[index1];
280
202
  if (!dict) {
281
- process.stderr.write(`[WABinary] unknown double-byte token dict ${index1} — token table outdated?\n`);
282
- return '';
203
+ throw new Error(`Invalid double token dict (${index1})`);
283
204
  }
284
205
  const value = dict[index2];
285
206
  if (typeof value === 'undefined') {
286
- process.stderr.write(`[WABinary] unknown double-byte token dict=${index1} idx=${index2} — token table outdated?\n`);
287
- return '';
207
+ throw new Error(`Invalid double token (${index2})`);
288
208
  }
289
209
  return value;
290
210
  };
@@ -298,6 +218,7 @@ const decodeDecompressedBinaryNode = (buffer, opts, indexRef = { index: 0 }) =>
298
218
  if (listSize === 0 || !header) {
299
219
  throw new Error('invalid node');
300
220
  }
221
+ // read the attributes in
301
222
  const attributesLength = (listSize - 1) >> 1;
302
223
  for (let i = 0; i < attributesLength; i++) {
303
224
  const key = readString(readByte());
@@ -334,9 +255,8 @@ const decodeDecompressedBinaryNode = (buffer, opts, indexRef = { index: 0 }) =>
334
255
  content: data
335
256
  };
336
257
  };
337
- exports.decodeDecompressedBinaryNode = decodeDecompressedBinaryNode;
338
- const decodeBinaryNode = buff => {
339
- const buffer = Buffer.isBuffer(buff) ? buff : Buffer.from(buff);
340
- return decodeDecompressedBinaryNode(buffer, constants);
258
+ export const decodeBinaryNode = async (buff) => {
259
+ const decompBuff = await decompressingIfRequired(buff);
260
+ return decodeDecompressedBinaryNode(decompBuff, constants);
341
261
  };
342
- exports.decodeBinaryNode = decodeBinaryNode;
262
+ //# sourceMappingURL=decode.js.map