gifted-baileys 1.5.0 → 1.5.5

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 (222) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +1429 -684
  3. package/package.json +11 -26
  4. package/src/Defaults/baileys-version.json +3 -0
  5. package/{lib → src}/Defaults/index.js +16 -8
  6. package/src/Defaults/index.ts +131 -0
  7. package/src/Defaults/phonenumber-mcc.json +223 -0
  8. package/src/Signal/libsignal.js +180 -0
  9. package/src/Signal/libsignal.ts +141 -0
  10. package/src/Socket/Client/abstract-socket-client.ts +19 -0
  11. package/src/Socket/Client/index.ts +3 -0
  12. package/src/Socket/Client/mobile-socket-client.js +78 -0
  13. package/src/Socket/Client/mobile-socket-client.ts +66 -0
  14. package/src/Socket/Client/web-socket-client.js +75 -0
  15. package/src/Socket/Client/web-socket-client.ts +57 -0
  16. package/{lib → src}/Socket/business.js +33 -27
  17. package/src/Socket/business.ts +281 -0
  18. package/{lib → src}/Socket/chats.js +197 -178
  19. package/src/Socket/chats.ts +1030 -0
  20. package/{lib → src}/Socket/groups.js +69 -79
  21. package/src/Socket/groups.ts +356 -0
  22. package/{lib → src}/Socket/index.js +1 -4
  23. package/src/Socket/index.ts +13 -0
  24. package/{lib → src}/Socket/messages-recv.js +160 -108
  25. package/src/Socket/messages-recv.ts +985 -0
  26. package/{lib → src}/Socket/messages-send.js +183 -100
  27. package/src/Socket/messages-send.ts +871 -0
  28. package/src/Socket/newsletter.js +227 -0
  29. package/src/Socket/newsletter.ts +282 -0
  30. package/{lib → src}/Socket/registration.js +55 -63
  31. package/src/Socket/registration.ts +250 -0
  32. package/{lib → src}/Socket/socket.js +107 -66
  33. package/src/Socket/socket.ts +777 -0
  34. package/src/Store/index.ts +3 -0
  35. package/{lib → src}/Store/make-cache-manager-store.js +34 -25
  36. package/src/Store/make-cache-manager-store.ts +100 -0
  37. package/{lib → src}/Store/make-in-memory-store.js +51 -61
  38. package/src/Store/make-in-memory-store.ts +475 -0
  39. package/src/Store/make-ordered-dictionary.ts +86 -0
  40. package/{lib → src}/Store/object-repository.js +1 -1
  41. package/src/Store/object-repository.ts +32 -0
  42. package/src/Tests/test.app-state-sync.js +204 -0
  43. package/src/Tests/test.app-state-sync.ts +207 -0
  44. package/src/Tests/test.event-buffer.js +270 -0
  45. package/src/Tests/test.event-buffer.ts +319 -0
  46. package/src/Tests/test.key-store.js +76 -0
  47. package/src/Tests/test.key-store.ts +92 -0
  48. package/src/Tests/test.libsignal.js +141 -0
  49. package/src/Tests/test.libsignal.ts +186 -0
  50. package/src/Tests/test.media-download.js +93 -0
  51. package/src/Tests/test.media-download.ts +76 -0
  52. package/src/Tests/test.messages.js +33 -0
  53. package/src/Tests/test.messages.ts +37 -0
  54. package/src/Tests/utils.js +34 -0
  55. package/src/Tests/utils.ts +36 -0
  56. package/src/Types/Auth.ts +113 -0
  57. package/src/Types/Call.ts +15 -0
  58. package/src/Types/Chat.ts +106 -0
  59. package/{lib/Types/Contact.d.ts → src/Types/Contact.ts} +9 -8
  60. package/src/Types/Events.ts +93 -0
  61. package/src/Types/GroupMetadata.ts +53 -0
  62. package/{lib → src}/Types/Label.js +1 -1
  63. package/src/Types/Label.ts +36 -0
  64. package/{lib → src}/Types/LabelAssociation.js +1 -1
  65. package/{lib/Types/LabelAssociation.d.ts → src/Types/LabelAssociation.ts} +22 -16
  66. package/src/Types/Message.ts +288 -0
  67. package/src/Types/Newsletter.js +32 -0
  68. package/src/Types/Newsletter.ts +98 -0
  69. package/src/Types/Product.ts +85 -0
  70. package/src/Types/Signal.ts +68 -0
  71. package/{lib/Types/Socket.d.ts → src/Types/Socket.ts} +68 -56
  72. package/src/Types/State.ts +29 -0
  73. package/{lib → src}/Types/index.js +2 -1
  74. package/src/Types/index.ts +59 -0
  75. package/{lib → src}/Utils/auth-utils.js +95 -76
  76. package/src/Utils/auth-utils.ts +222 -0
  77. package/src/Utils/baileys-event-stream.js +92 -0
  78. package/src/Utils/baileys-event-stream.ts +66 -0
  79. package/{lib → src}/Utils/business.js +45 -17
  80. package/src/Utils/business.ts +275 -0
  81. package/{lib → src}/Utils/chat-utils.js +74 -46
  82. package/src/Utils/chat-utils.ts +860 -0
  83. package/{lib → src}/Utils/crypto.js +31 -21
  84. package/src/Utils/crypto.ts +131 -0
  85. package/src/Utils/decode-wa-message.js +211 -0
  86. package/src/Utils/decode-wa-message.ts +228 -0
  87. package/{lib → src}/Utils/event-buffer.js +13 -4
  88. package/src/Utils/event-buffer.ts +613 -0
  89. package/{lib → src}/Utils/generics.js +98 -45
  90. package/src/Utils/generics.ts +434 -0
  91. package/{lib → src}/Utils/history.js +39 -10
  92. package/src/Utils/history.ts +112 -0
  93. package/src/Utils/index.ts +17 -0
  94. package/{lib → src}/Utils/link-preview.js +54 -17
  95. package/src/Utils/link-preview.ts +122 -0
  96. package/src/Utils/logger.ts +3 -0
  97. package/src/Utils/lt-hash.ts +61 -0
  98. package/{lib → src}/Utils/make-mutex.js +13 -4
  99. package/src/Utils/make-mutex.ts +44 -0
  100. package/{lib → src}/Utils/messages-media.js +296 -192
  101. package/src/Utils/messages-media.ts +847 -0
  102. package/{lib → src}/Utils/messages.js +124 -113
  103. package/src/Utils/messages.ts +956 -0
  104. package/{lib → src}/Utils/noise-handler.js +16 -3
  105. package/src/Utils/noise-handler.ts +197 -0
  106. package/{lib → src}/Utils/process-message.js +33 -29
  107. package/src/Utils/process-message.ts +414 -0
  108. package/{lib → src}/Utils/signal.js +23 -14
  109. package/src/Utils/signal.ts +177 -0
  110. package/{lib → src}/Utils/use-multi-file-auth-state.js +28 -19
  111. package/src/Utils/use-multi-file-auth-state.ts +90 -0
  112. package/{lib → src}/Utils/validate-connection.js +25 -42
  113. package/src/Utils/validate-connection.ts +238 -0
  114. package/src/WABinary/constants.ts +42 -0
  115. package/{lib → src}/WABinary/decode.js +17 -7
  116. package/src/WABinary/decode.ts +265 -0
  117. package/{lib → src}/WABinary/encode.js +17 -7
  118. package/src/WABinary/encode.ts +236 -0
  119. package/{lib → src}/WABinary/generic-utils.js +2 -2
  120. package/src/WABinary/generic-utils.ts +121 -0
  121. package/src/WABinary/index.ts +5 -0
  122. package/{lib → src}/WABinary/jid-utils.js +4 -1
  123. package/src/WABinary/jid-utils.ts +68 -0
  124. package/src/WABinary/types.ts +17 -0
  125. package/src/WAM/BinaryInfo.js +13 -0
  126. package/src/WAM/BinaryInfo.ts +12 -0
  127. package/src/WAM/constants.js +15350 -0
  128. package/src/WAM/constants.ts +15382 -0
  129. package/src/WAM/encode.js +155 -0
  130. package/src/WAM/encode.ts +174 -0
  131. package/src/WAM/index.js +19 -0
  132. package/src/WAM/index.ts +3 -0
  133. package/src/gifted +1 -0
  134. package/{lib → src}/index.js +1 -0
  135. package/src/index.ts +13 -0
  136. package/lib/Defaults/baileys-version.json +0 -3
  137. package/lib/Defaults/index.d.ts +0 -284
  138. package/lib/Defaults/phonenumber-mcc.json +0 -223
  139. package/lib/Signal/libsignal.d.ts +0 -3
  140. package/lib/Signal/libsignal.js +0 -152
  141. package/lib/Socket/Client/abstract-socket-client.d.ts +0 -17
  142. package/lib/Socket/Client/index.d.ts +0 -3
  143. package/lib/Socket/Client/mobile-socket-client.d.ts +0 -13
  144. package/lib/Socket/Client/mobile-socket-client.js +0 -65
  145. package/lib/Socket/Client/web-socket-client.d.ts +0 -12
  146. package/lib/Socket/Client/web-socket-client.js +0 -62
  147. package/lib/Socket/business.d.ts +0 -135
  148. package/lib/Socket/chats.d.ts +0 -79
  149. package/lib/Socket/groups.d.ts +0 -113
  150. package/lib/Socket/index.d.ts +0 -137
  151. package/lib/Socket/messages-recv.d.ts +0 -124
  152. package/lib/Socket/messages-send.d.ts +0 -119
  153. package/lib/Socket/registration.d.ts +0 -232
  154. package/lib/Socket/socket.d.ts +0 -42
  155. package/lib/Store/index.d.ts +0 -3
  156. package/lib/Store/make-cache-manager-store.d.ts +0 -13
  157. package/lib/Store/make-in-memory-store.d.ts +0 -117
  158. package/lib/Store/make-ordered-dictionary.d.ts +0 -13
  159. package/lib/Store/object-repository.d.ts +0 -10
  160. package/lib/Types/Auth.d.ts +0 -108
  161. package/lib/Types/Call.d.ts +0 -13
  162. package/lib/Types/Chat.d.ts +0 -102
  163. package/lib/Types/Events.d.ts +0 -157
  164. package/lib/Types/GroupMetadata.d.ts +0 -52
  165. package/lib/Types/Label.d.ts +0 -35
  166. package/lib/Types/Message.d.ts +0 -261
  167. package/lib/Types/Product.d.ts +0 -78
  168. package/lib/Types/Signal.d.ts +0 -57
  169. package/lib/Types/State.d.ts +0 -27
  170. package/lib/Types/index.d.ts +0 -56
  171. package/lib/Utils/auth-utils.d.ts +0 -18
  172. package/lib/Utils/baileys-event-stream.d.ts +0 -16
  173. package/lib/Utils/baileys-event-stream.js +0 -63
  174. package/lib/Utils/business.d.ts +0 -22
  175. package/lib/Utils/chat-utils.d.ts +0 -71
  176. package/lib/Utils/crypto.d.ts +0 -41
  177. package/lib/Utils/decode-wa-message.d.ts +0 -19
  178. package/lib/Utils/decode-wa-message.js +0 -174
  179. package/lib/Utils/event-buffer.d.ts +0 -35
  180. package/lib/Utils/generics.d.ts +0 -94
  181. package/lib/Utils/history.d.ts +0 -15
  182. package/lib/Utils/index.d.ts +0 -17
  183. package/lib/Utils/link-preview.d.ts +0 -21
  184. package/lib/Utils/logger.d.ts +0 -4
  185. package/lib/Utils/lt-hash.d.ts +0 -12
  186. package/lib/Utils/make-mutex.d.ts +0 -7
  187. package/lib/Utils/messages-media.d.ts +0 -107
  188. package/lib/Utils/messages.d.ts +0 -76
  189. package/lib/Utils/noise-handler.d.ts +0 -20
  190. package/lib/Utils/process-message.d.ts +0 -41
  191. package/lib/Utils/signal.d.ts +0 -32
  192. package/lib/Utils/use-multi-file-auth-state.d.ts +0 -12
  193. package/lib/Utils/validate-connection.d.ts +0 -11
  194. package/lib/WABinary/constants.d.ts +0 -27
  195. package/lib/WABinary/decode.d.ts +0 -7
  196. package/lib/WABinary/encode.d.ts +0 -3
  197. package/lib/WABinary/generic-utils.d.ts +0 -15
  198. package/lib/WABinary/index.d.ts +0 -5
  199. package/lib/WABinary/jid-utils.d.ts +0 -29
  200. package/lib/WABinary/types.d.ts +0 -18
  201. package/lib/index.d.ts +0 -10
  202. /package/{lib → src}/Socket/Client/abstract-socket-client.js +0 -0
  203. /package/{lib → src}/Socket/Client/index.js +0 -0
  204. /package/{lib → src}/Store/index.js +0 -0
  205. /package/{lib → src}/Store/make-ordered-dictionary.js +0 -0
  206. /package/{lib → src}/Types/Auth.js +0 -0
  207. /package/{lib → src}/Types/Call.js +0 -0
  208. /package/{lib → src}/Types/Chat.js +0 -0
  209. /package/{lib → src}/Types/Contact.js +0 -0
  210. /package/{lib → src}/Types/Events.js +0 -0
  211. /package/{lib → src}/Types/GroupMetadata.js +0 -0
  212. /package/{lib → src}/Types/Message.js +0 -0
  213. /package/{lib → src}/Types/Product.js +0 -0
  214. /package/{lib → src}/Types/Signal.js +0 -0
  215. /package/{lib → src}/Types/Socket.js +0 -0
  216. /package/{lib → src}/Types/State.js +0 -0
  217. /package/{lib → src}/Utils/index.js +0 -0
  218. /package/{lib → src}/Utils/logger.js +0 -0
  219. /package/{lib → src}/Utils/lt-hash.js +0 -0
  220. /package/{lib → src}/WABinary/constants.js +0 -0
  221. /package/{lib → src}/WABinary/index.js +0 -0
  222. /package/{lib → src}/WABinary/types.js +0 -0
@@ -1,4 +1,13 @@
1
1
  "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
2
11
  Object.defineProperty(exports, "__esModule", { value: true });
3
12
  exports.useMultiFileAuthState = void 0;
4
13
  const promises_1 = require("fs/promises");
@@ -13,53 +22,53 @@ const generics_1 = require("./generics");
13
22
  * Again, I wouldn't endorse this for any production level use other than perhaps a bot.
14
23
  * Would recommend writing an auth state for use with a proper SQL or No-SQL DB
15
24
  * */
16
- const useMultiFileAuthState = async (folder) => {
25
+ const useMultiFileAuthState = (folder) => __awaiter(void 0, void 0, void 0, function* () {
17
26
  const writeData = (data, file) => {
18
27
  return (0, promises_1.writeFile)((0, path_1.join)(folder, fixFileName(file)), JSON.stringify(data, generics_1.BufferJSON.replacer));
19
28
  };
20
- const readData = async (file) => {
29
+ const readData = (file) => __awaiter(void 0, void 0, void 0, function* () {
21
30
  try {
22
- const data = await (0, promises_1.readFile)((0, path_1.join)(folder, fixFileName(file)), { encoding: 'utf-8' });
31
+ const data = yield (0, promises_1.readFile)((0, path_1.join)(folder, fixFileName(file)), { encoding: 'utf-8' });
23
32
  return JSON.parse(data, generics_1.BufferJSON.reviver);
24
33
  }
25
34
  catch (error) {
26
35
  return null;
27
36
  }
28
- };
29
- const removeData = async (file) => {
37
+ });
38
+ const removeData = (file) => __awaiter(void 0, void 0, void 0, function* () {
30
39
  try {
31
- await (0, promises_1.unlink)((0, path_1.join)(folder, fixFileName(file)));
40
+ yield (0, promises_1.unlink)((0, path_1.join)(folder, fixFileName(file)));
32
41
  }
33
42
  catch (_a) {
34
43
  }
35
- };
36
- const folderInfo = await (0, promises_1.stat)(folder).catch(() => { });
44
+ });
45
+ const folderInfo = yield (0, promises_1.stat)(folder).catch(() => { });
37
46
  if (folderInfo) {
38
47
  if (!folderInfo.isDirectory()) {
39
48
  throw new Error(`found something that is not a directory at ${folder}, either delete it or specify a different location`);
40
49
  }
41
50
  }
42
51
  else {
43
- await (0, promises_1.mkdir)(folder, { recursive: true });
52
+ yield (0, promises_1.mkdir)(folder, { recursive: true });
44
53
  }
45
54
  const fixFileName = (file) => { var _a; return (_a = file === null || file === void 0 ? void 0 : file.replace(/\//g, '__')) === null || _a === void 0 ? void 0 : _a.replace(/:/g, '-'); };
46
- const creds = await readData('creds.json') || (0, auth_utils_1.initAuthCreds)();
55
+ const creds = (yield readData('creds.json')) || (0, auth_utils_1.initAuthCreds)();
47
56
  return {
48
57
  state: {
49
58
  creds,
50
59
  keys: {
51
- get: async (type, ids) => {
60
+ get: (type, ids) => __awaiter(void 0, void 0, void 0, function* () {
52
61
  const data = {};
53
- await Promise.all(ids.map(async (id) => {
54
- let value = await readData(`${type}-${id}.json`);
62
+ yield Promise.all(ids.map((id) => __awaiter(void 0, void 0, void 0, function* () {
63
+ let value = yield readData(`${type}-${id}.json`);
55
64
  if (type === 'app-state-sync-key' && value) {
56
65
  value = WAProto_1.proto.Message.AppStateSyncKeyData.fromObject(value);
57
66
  }
58
67
  data[id] = value;
59
- }));
68
+ })));
60
69
  return data;
61
- },
62
- set: async (data) => {
70
+ }),
71
+ set: (data) => __awaiter(void 0, void 0, void 0, function* () {
63
72
  const tasks = [];
64
73
  for (const category in data) {
65
74
  for (const id in data[category]) {
@@ -68,13 +77,13 @@ const useMultiFileAuthState = async (folder) => {
68
77
  tasks.push(value ? writeData(value, file) : removeData(file));
69
78
  }
70
79
  }
71
- await Promise.all(tasks);
72
- }
80
+ yield Promise.all(tasks);
81
+ })
73
82
  }
74
83
  },
75
84
  saveCreds: () => {
76
85
  return writeData(creds, 'creds.json');
77
86
  }
78
87
  };
79
- };
88
+ });
80
89
  exports.useMultiFileAuthState = useMultiFileAuthState;
@@ -0,0 +1,90 @@
1
+ import { mkdir, readFile, stat, unlink, writeFile } from 'fs/promises'
2
+ import { join } from 'path'
3
+ import { proto } from '../../WAProto'
4
+ import { AuthenticationCreds, AuthenticationState, SignalDataTypeMap } from '../Types'
5
+ import { initAuthCreds } from './auth-utils'
6
+ import { BufferJSON } from './generics'
7
+
8
+ /**
9
+ * stores the full authentication state in a single folder.
10
+ * Far more efficient than singlefileauthstate
11
+ *
12
+ * Again, I wouldn't endorse this for any production level use other than perhaps a bot.
13
+ * Would recommend writing an auth state for use with a proper SQL or No-SQL DB
14
+ * */
15
+ export const useMultiFileAuthState = async(folder: string): Promise<{ state: AuthenticationState, saveCreds: () => Promise<void> }> => {
16
+
17
+ const writeData = (data: any, file: string) => {
18
+ return writeFile(join(folder, fixFileName(file)!), JSON.stringify(data, BufferJSON.replacer))
19
+ }
20
+
21
+ const readData = async(file: string) => {
22
+ try {
23
+ const data = await readFile(join(folder, fixFileName(file)!), { encoding: 'utf-8' })
24
+ return JSON.parse(data, BufferJSON.reviver)
25
+ } catch(error) {
26
+ return null
27
+ }
28
+ }
29
+
30
+ const removeData = async(file: string) => {
31
+ try {
32
+ await unlink(join(folder, fixFileName(file)!))
33
+ } catch{
34
+
35
+ }
36
+ }
37
+
38
+ const folderInfo = await stat(folder).catch(() => { })
39
+ if(folderInfo) {
40
+ if(!folderInfo.isDirectory()) {
41
+ throw new Error(`found something that is not a directory at ${folder}, either delete it or specify a different location`)
42
+ }
43
+ } else {
44
+ await mkdir(folder, { recursive: true })
45
+ }
46
+
47
+ const fixFileName = (file?: string) => file?.replace(/\//g, '__')?.replace(/:/g, '-')
48
+
49
+ const creds: AuthenticationCreds = await readData('creds.json') || initAuthCreds()
50
+
51
+ return {
52
+ state: {
53
+ creds,
54
+ keys: {
55
+ get: async(type, ids) => {
56
+ const data: { [_: string]: SignalDataTypeMap[typeof type] } = { }
57
+ await Promise.all(
58
+ ids.map(
59
+ async id => {
60
+ let value = await readData(`${type}-${id}.json`)
61
+ if(type === 'app-state-sync-key' && value) {
62
+ value = proto.Message.AppStateSyncKeyData.fromObject(value)
63
+ }
64
+
65
+ data[id] = value
66
+ }
67
+ )
68
+ )
69
+
70
+ return data
71
+ },
72
+ set: async(data) => {
73
+ const tasks: Promise<void>[] = []
74
+ for(const category in data) {
75
+ for(const id in data[category]) {
76
+ const value = data[category][id]
77
+ const file = `${category}-${id}.json`
78
+ tasks.push(value ? writeData(value, file) : removeData(file))
79
+ }
80
+ }
81
+
82
+ await Promise.all(tasks)
83
+ }
84
+ }
85
+ },
86
+ saveCreds: () => {
87
+ return writeData(creds, 'creds.json')
88
+ }
89
+ }
90
+ }
@@ -12,29 +12,28 @@ const signal_1 = require("./signal");
12
12
  const getUserAgent = (config) => {
13
13
  var _a, _b;
14
14
  const osVersion = config.mobile ? '15.3.1' : '0.1';
15
- const version = config.mobile ? [2, 22, 24] : config.version;
15
+ const version = config.mobile ? [2, 24, 6] : config.version;
16
16
  const device = config.mobile ? 'iPhone_7' : 'Desktop';
17
17
  const manufacturer = config.mobile ? 'Apple' : '';
18
- const platform = config.mobile ? WAProto_1.proto.ClientPayload.UserAgent.Platform.IOS : WAProto_1.proto.ClientPayload.UserAgent.Platform.MACOS;
18
+ const platform = config.mobile ? WAProto_1.proto.ClientPayload.UserAgent.Platform.IOS : WAProto_1.proto.ClientPayload.UserAgent.Platform.WEB;
19
19
  const phoneId = config.mobile ? { phoneId: config.auth.creds.phoneId } : {};
20
- return {
21
- appVersion: {
20
+ return Object.assign({ appVersion: {
22
21
  primary: version[0],
23
22
  secondary: version[1],
24
23
  tertiary: version[2],
25
- },
26
- platform,
27
- releaseChannel: WAProto_1.proto.ClientPayload.UserAgent.ReleaseChannel.RELEASE,
28
- mcc: ((_a = config.auth.creds.registration) === null || _a === void 0 ? void 0 : _a.phoneNumberMobileCountryCode) || '000',
29
- mnc: ((_b = config.auth.creds.registration) === null || _b === void 0 ? void 0 : _b.phoneNumberMobileNetworkCode) || '000',
30
- osVersion: osVersion,
31
- manufacturer,
32
- device,
33
- osBuildNumber: osVersion,
34
- localeLanguageIso6391: 'en',
35
- localeCountryIso31661Alpha2: 'US',
36
- ...phoneId
37
- };
24
+ }, platform, releaseChannel: WAProto_1.proto.ClientPayload.UserAgent.ReleaseChannel.RELEASE, mcc: ((_a = config.auth.creds.registration) === null || _a === void 0 ? void 0 : _a.phoneNumberMobileCountryCode) || '000', mnc: ((_b = config.auth.creds.registration) === null || _b === void 0 ? void 0 : _b.phoneNumberMobileNetworkCode) || '000', osVersion: osVersion, manufacturer,
25
+ device, osBuildNumber: osVersion, localeLanguageIso6391: 'en', localeCountryIso31661Alpha2: 'US' }, phoneId);
26
+ };
27
+ const PLATFORM_MAP = {
28
+ 'Mac OS': WAProto_1.proto.ClientPayload.WebInfo.WebSubPlatform.DARWIN,
29
+ 'Windows': WAProto_1.proto.ClientPayload.WebInfo.WebSubPlatform.WIN32
30
+ };
31
+ const getWebInfo = (config) => {
32
+ let webSubPlatform = WAProto_1.proto.ClientPayload.WebInfo.WebSubPlatform.WEB_BROWSER;
33
+ if (config.syncFullHistory && PLATFORM_MAP[config.browser[0]]) {
34
+ webSubPlatform = PLATFORM_MAP[config.browser[0]];
35
+ }
36
+ return { webSubPlatform };
38
37
  };
39
38
  const getClientPayload = (config) => {
40
39
  const payload = {
@@ -42,37 +41,25 @@ const getClientPayload = (config) => {
42
41
  connectReason: WAProto_1.proto.ClientPayload.ConnectReason.USER_ACTIVATED,
43
42
  userAgent: getUserAgent(config),
44
43
  };
44
+ if (!config.mobile) {
45
+ payload.webInfo = getWebInfo(config);
46
+ }
45
47
  return payload;
46
48
  };
47
49
  const generateMobileNode = (config) => {
48
50
  if (!config.auth.creds) {
49
51
  throw new boom_1.Boom('No registration data found', { data: config });
50
52
  }
51
- const payload = {
52
- ...getClientPayload(config),
53
- sessionId: Math.floor(Math.random() * 999999999 + 1),
54
- shortConnect: true,
55
- connectAttemptCount: 0,
56
- device: 0,
57
- dnsSource: {
53
+ const payload = Object.assign(Object.assign({}, getClientPayload(config)), { sessionId: Math.floor(Math.random() * 999999999 + 1), shortConnect: true, connectAttemptCount: 0, device: 0, dnsSource: {
58
54
  appCached: false,
59
55
  dnsMethod: WAProto_1.proto.ClientPayload.DNSSource.DNSResolutionMethod.SYSTEM,
60
- },
61
- passive: false,
62
- pushName: 'test',
63
- username: Number(`${config.auth.creds.registration.phoneNumberCountryCode}${config.auth.creds.registration.phoneNumberNationalNumber}`),
64
- };
56
+ }, passive: false, pushName: 'test', username: Number(`${config.auth.creds.registration.phoneNumberCountryCode}${config.auth.creds.registration.phoneNumberNationalNumber}`) });
65
57
  return WAProto_1.proto.ClientPayload.fromObject(payload);
66
58
  };
67
59
  exports.generateMobileNode = generateMobileNode;
68
60
  const generateLoginNode = (userJid, config) => {
69
61
  const { user, device } = (0, WABinary_1.jidDecode)(userJid);
70
- const payload = {
71
- ...getClientPayload(config),
72
- passive: true,
73
- username: +user,
74
- device: device,
75
- };
62
+ const payload = Object.assign(Object.assign({}, getClientPayload(config)), { passive: true, username: +user, device: device });
76
63
  return WAProto_1.proto.ClientPayload.fromObject(payload);
77
64
  };
78
65
  exports.generateLoginNode = generateLoginNode;
@@ -92,10 +79,7 @@ const generateRegistrationNode = ({ registrationId, signedPreKey, signedIdentity
92
79
  requireFullSync: config.syncFullHistory,
93
80
  };
94
81
  const companionProto = WAProto_1.proto.DeviceProps.encode(companion).finish();
95
- const registerPayload = {
96
- ...getClientPayload(config),
97
- passive: false,
98
- devicePairingData: {
82
+ const registerPayload = Object.assign(Object.assign({}, getClientPayload(config)), { passive: false, devicePairingData: {
99
83
  buildHash: appVersionBuf,
100
84
  deviceProps: companionProto,
101
85
  eRegid: (0, generics_1.encodeBigEndian)(registrationId),
@@ -104,8 +88,7 @@ const generateRegistrationNode = ({ registrationId, signedPreKey, signedIdentity
104
88
  eSkeyId: (0, generics_1.encodeBigEndian)(signedPreKey.keyId, 3),
105
89
  eSkeyVal: signedPreKey.keyPair.public,
106
90
  eSkeySig: signedPreKey.signature,
107
- },
108
- };
91
+ } });
109
92
  return WAProto_1.proto.ClientPayload.fromObject(registerPayload);
110
93
  };
111
94
  exports.generateRegistrationNode = generateRegistrationNode;
@@ -178,7 +161,7 @@ const configureSuccessfulPairing = (stanza, { advSecretKey, signedIdentityKey, s
178
161
  exports.configureSuccessfulPairing = configureSuccessfulPairing;
179
162
  const encodeSignedDeviceIdentity = (account, includeSignatureKey) => {
180
163
  var _a;
181
- account = { ...account };
164
+ account = Object.assign({}, account);
182
165
  // set to null if we are not to include the signature key
183
166
  // or if we are including the signature key but it is empty
184
167
  if (!includeSignatureKey || !((_a = account.accountSignatureKey) === null || _a === void 0 ? void 0 : _a.length)) {
@@ -0,0 +1,238 @@
1
+ import { Boom } from '@hapi/boom'
2
+ import { createHash } from 'crypto'
3
+ import { proto } from '../../WAProto'
4
+ import { KEY_BUNDLE_TYPE } from '../Defaults'
5
+ import type { AuthenticationCreds, SignalCreds, SocketConfig } from '../Types'
6
+ import { BinaryNode, getBinaryNodeChild, jidDecode, S_WHATSAPP_NET } from '../WABinary'
7
+ import { Curve, hmacSign } from './crypto'
8
+ import { encodeBigEndian } from './generics'
9
+ import { createSignalIdentity } from './signal'
10
+
11
+ const getUserAgent = (config: SocketConfig): proto.ClientPayload.IUserAgent => {
12
+ const osVersion = config.mobile ? '15.3.1' : '0.1'
13
+ const version = config.mobile ? [2, 24, 6] : config.version
14
+ const device = config.mobile ? 'iPhone_7' : 'Desktop'
15
+ const manufacturer = config.mobile ? 'Apple' : ''
16
+ const platform = config.mobile ? proto.ClientPayload.UserAgent.Platform.IOS : proto.ClientPayload.UserAgent.Platform.WEB
17
+ const phoneId = config.mobile ? { phoneId: config.auth.creds.phoneId } : {}
18
+
19
+ return {
20
+ appVersion: {
21
+ primary: version[0],
22
+ secondary: version[1],
23
+ tertiary: version[2],
24
+ },
25
+ platform,
26
+ releaseChannel: proto.ClientPayload.UserAgent.ReleaseChannel.RELEASE,
27
+ mcc: config.auth.creds.registration?.phoneNumberMobileCountryCode || '000',
28
+ mnc: config.auth.creds.registration?.phoneNumberMobileNetworkCode || '000',
29
+ osVersion: osVersion,
30
+ manufacturer,
31
+ device,
32
+ osBuildNumber: osVersion,
33
+ localeLanguageIso6391: 'en',
34
+ localeCountryIso31661Alpha2: 'US',
35
+ ...phoneId
36
+ }
37
+ }
38
+
39
+ const PLATFORM_MAP = {
40
+ 'Mac OS': proto.ClientPayload.WebInfo.WebSubPlatform.DARWIN,
41
+ 'Windows': proto.ClientPayload.WebInfo.WebSubPlatform.WIN32
42
+ }
43
+
44
+ const getWebInfo = (config: SocketConfig): proto.ClientPayload.IWebInfo => {
45
+ let webSubPlatform = proto.ClientPayload.WebInfo.WebSubPlatform.WEB_BROWSER
46
+ if(config.syncFullHistory && PLATFORM_MAP[config.browser[0]]) {
47
+ webSubPlatform = PLATFORM_MAP[config.browser[0]]
48
+ }
49
+
50
+ return { webSubPlatform }
51
+ }
52
+
53
+
54
+ const getClientPayload = (config: SocketConfig) => {
55
+ const payload: proto.IClientPayload = {
56
+ connectType: proto.ClientPayload.ConnectType.WIFI_UNKNOWN,
57
+ connectReason: proto.ClientPayload.ConnectReason.USER_ACTIVATED,
58
+ userAgent: getUserAgent(config),
59
+ }
60
+
61
+ if(!config.mobile) {
62
+ payload.webInfo = getWebInfo(config)
63
+ }
64
+
65
+ return payload
66
+ }
67
+
68
+ export const generateMobileNode = (config: SocketConfig): proto.IClientPayload => {
69
+ if(!config.auth.creds) {
70
+ throw new Boom('No registration data found', { data: config })
71
+ }
72
+
73
+ const payload: proto.IClientPayload = {
74
+ ...getClientPayload(config),
75
+ sessionId: Math.floor(Math.random() * 999999999 + 1),
76
+ shortConnect: true,
77
+ connectAttemptCount: 0,
78
+ device: 0,
79
+ dnsSource: {
80
+ appCached: false,
81
+ dnsMethod: proto.ClientPayload.DNSSource.DNSResolutionMethod.SYSTEM,
82
+ },
83
+ passive: false, // XMPP heartbeat setting (false: server actively pings) (true: client actively pings)
84
+ pushName: 'test',
85
+ username: Number(`${config.auth.creds.registration.phoneNumberCountryCode}${config.auth.creds.registration.phoneNumberNationalNumber}`),
86
+ }
87
+ return proto.ClientPayload.fromObject(payload)
88
+ }
89
+
90
+ export const generateLoginNode = (userJid: string, config: SocketConfig): proto.IClientPayload => {
91
+ const { user, device } = jidDecode(userJid)!
92
+ const payload: proto.IClientPayload = {
93
+ ...getClientPayload(config),
94
+ passive: true,
95
+ username: +user,
96
+ device: device,
97
+ }
98
+ return proto.ClientPayload.fromObject(payload)
99
+ }
100
+
101
+ const getPlatformType = (platform: string): proto.DeviceProps.PlatformType => {
102
+ const platformType = platform.toUpperCase()
103
+ return proto.DeviceProps.PlatformType[platformType] || proto.DeviceProps.PlatformType.DESKTOP
104
+ }
105
+
106
+ export const generateRegistrationNode = (
107
+ { registrationId, signedPreKey, signedIdentityKey }: SignalCreds,
108
+ config: SocketConfig
109
+ ) => {
110
+ // the app version needs to be md5 hashed
111
+ // and passed in
112
+ const appVersionBuf = createHash('md5')
113
+ .update(config.version.join('.')) // join as string
114
+ .digest()
115
+
116
+ const companion: proto.IDeviceProps = {
117
+ os: config.browser[0],
118
+ platformType: getPlatformType(config.browser[1]),
119
+ requireFullSync: config.syncFullHistory,
120
+ }
121
+
122
+ const companionProto = proto.DeviceProps.encode(companion).finish()
123
+
124
+ const registerPayload: proto.IClientPayload = {
125
+ ...getClientPayload(config),
126
+ passive: false,
127
+ devicePairingData: {
128
+ buildHash: appVersionBuf,
129
+ deviceProps: companionProto,
130
+ eRegid: encodeBigEndian(registrationId),
131
+ eKeytype: KEY_BUNDLE_TYPE,
132
+ eIdent: signedIdentityKey.public,
133
+ eSkeyId: encodeBigEndian(signedPreKey.keyId, 3),
134
+ eSkeyVal: signedPreKey.keyPair.public,
135
+ eSkeySig: signedPreKey.signature,
136
+ },
137
+ }
138
+
139
+ return proto.ClientPayload.fromObject(registerPayload)
140
+ }
141
+
142
+ export const configureSuccessfulPairing = (
143
+ stanza: BinaryNode,
144
+ { advSecretKey, signedIdentityKey, signalIdentities }: Pick<AuthenticationCreds, 'advSecretKey' | 'signedIdentityKey' | 'signalIdentities'>
145
+ ) => {
146
+ const msgId = stanza.attrs.id
147
+
148
+ const pairSuccessNode = getBinaryNodeChild(stanza, 'pair-success')
149
+
150
+ const deviceIdentityNode = getBinaryNodeChild(pairSuccessNode, 'device-identity')
151
+ const platformNode = getBinaryNodeChild(pairSuccessNode, 'platform')
152
+ const deviceNode = getBinaryNodeChild(pairSuccessNode, 'device')
153
+ const businessNode = getBinaryNodeChild(pairSuccessNode, 'biz')
154
+
155
+ if(!deviceIdentityNode || !deviceNode) {
156
+ throw new Boom('Missing device-identity or device in pair success node', { data: stanza })
157
+ }
158
+
159
+ const bizName = businessNode?.attrs.name
160
+ const jid = deviceNode.attrs.jid
161
+
162
+ const { details, hmac } = proto.ADVSignedDeviceIdentityHMAC.decode(deviceIdentityNode.content as Buffer)
163
+ // check HMAC matches
164
+ const advSign = hmacSign(details, Buffer.from(advSecretKey, 'base64'))
165
+ if(Buffer.compare(hmac, advSign) !== 0) {
166
+ throw new Boom('Invalid account signature')
167
+ }
168
+
169
+ const account = proto.ADVSignedDeviceIdentity.decode(details)
170
+ const { accountSignatureKey, accountSignature, details: deviceDetails } = account
171
+ // verify the device signature matches
172
+ const accountMsg = Buffer.concat([ Buffer.from([6, 0]), deviceDetails, signedIdentityKey.public ])
173
+ if(!Curve.verify(accountSignatureKey, accountMsg, accountSignature)) {
174
+ throw new Boom('Failed to verify account signature')
175
+ }
176
+
177
+ // sign the details with our identity key
178
+ const deviceMsg = Buffer.concat([ Buffer.from([6, 1]), deviceDetails, signedIdentityKey.public, accountSignatureKey ])
179
+ account.deviceSignature = Curve.sign(signedIdentityKey.private, deviceMsg)
180
+
181
+ const identity = createSignalIdentity(jid, accountSignatureKey)
182
+ const accountEnc = encodeSignedDeviceIdentity(account, false)
183
+
184
+ const deviceIdentity = proto.ADVDeviceIdentity.decode(account.details)
185
+
186
+ const reply: BinaryNode = {
187
+ tag: 'iq',
188
+ attrs: {
189
+ to: S_WHATSAPP_NET,
190
+ type: 'result',
191
+ id: msgId,
192
+ },
193
+ content: [
194
+ {
195
+ tag: 'pair-device-sign',
196
+ attrs: { },
197
+ content: [
198
+ {
199
+ tag: 'device-identity',
200
+ attrs: { 'key-index': deviceIdentity.keyIndex.toString() },
201
+ content: accountEnc
202
+ }
203
+ ]
204
+ }
205
+ ]
206
+ }
207
+
208
+ const authUpdate: Partial<AuthenticationCreds> = {
209
+ account,
210
+ me: { id: jid, name: bizName },
211
+ signalIdentities: [
212
+ ...(signalIdentities || []),
213
+ identity
214
+ ],
215
+ platform: platformNode?.attrs.name
216
+ }
217
+
218
+ return {
219
+ creds: authUpdate,
220
+ reply
221
+ }
222
+ }
223
+
224
+ export const encodeSignedDeviceIdentity = (
225
+ account: proto.IADVSignedDeviceIdentity,
226
+ includeSignatureKey: boolean
227
+ ) => {
228
+ account = { ...account }
229
+ // set to null if we are not to include the signature key
230
+ // or if we are including the signature key but it is empty
231
+ if(!includeSignatureKey || !account.accountSignatureKey?.length) {
232
+ account.accountSignatureKey = null
233
+ }
234
+
235
+ return proto.ADVSignedDeviceIdentity
236
+ .encode(account)
237
+ .finish()
238
+ }