@skyzopedia/baileys-mod 5.0.7 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (210) hide show
  1. package/WAProto/index.js +133384 -57814
  2. package/engine-requirements.js +10 -0
  3. package/lib/Defaults/baileys-version.json +3 -0
  4. package/lib/Defaults/index.d.ts +53 -0
  5. package/lib/Defaults/index.js +141 -117
  6. package/lib/Defaults/phonenumber-mcc.json +223 -0
  7. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  8. package/lib/Signal/Group/ciphertext-message.js +14 -12
  9. package/lib/Signal/Group/group-session-builder.d.ts +14 -0
  10. package/lib/Signal/Group/group-session-builder.js +42 -10
  11. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  12. package/lib/Signal/Group/group_cipher.js +87 -75
  13. package/lib/Signal/Group/index.d.ts +11 -0
  14. package/lib/Signal/Group/index.js +57 -13
  15. package/lib/Signal/Group/keyhelper.d.ts +10 -0
  16. package/lib/Signal/Group/keyhelper.js +52 -17
  17. package/lib/Signal/Group/queue-job.d.ts +1 -0
  18. package/lib/Signal/Group/queue-job.js +57 -0
  19. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  20. package/lib/Signal/Group/sender-chain-key.js +33 -27
  21. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  22. package/lib/Signal/Group/sender-key-distribution-message.js +63 -62
  23. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  24. package/lib/Signal/Group/sender-key-message.js +66 -65
  25. package/lib/Signal/Group/sender-key-name.d.ts +17 -0
  26. package/lib/Signal/Group/sender-key-name.js +44 -45
  27. package/lib/Signal/Group/sender-key-record.d.ts +30 -0
  28. package/lib/Signal/Group/sender-key-record.js +49 -39
  29. package/lib/Signal/Group/sender-key-state.d.ts +38 -0
  30. package/lib/Signal/Group/sender-key-state.js +93 -80
  31. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  32. package/lib/Signal/Group/sender-message-key.js +28 -27
  33. package/lib/Signal/libsignal.d.ts +3 -0
  34. package/lib/Signal/libsignal.js +163 -313
  35. package/lib/Socket/Client/abstract-socket-client.d.ts +17 -0
  36. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  37. package/lib/Socket/Client/index.d.ts +3 -0
  38. package/lib/Socket/Client/index.js +19 -4
  39. package/lib/Socket/Client/mobile-socket-client.d.ts +13 -0
  40. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  41. package/lib/Socket/Client/web-socket-client.d.ts +12 -0
  42. package/lib/Socket/Client/web-socket-client.js +62 -0
  43. package/lib/Socket/business.d.ts +171 -0
  44. package/lib/Socket/business.js +242 -359
  45. package/lib/Socket/chats.d.ts +267 -0
  46. package/lib/Socket/chats.js +935 -846
  47. package/lib/Socket/dugong.d.ts +254 -0
  48. package/lib/Socket/dugong.js +484 -0
  49. package/lib/Socket/groups.d.ts +115 -0
  50. package/lib/Socket/groups.js +309 -304
  51. package/lib/Socket/index.d.ts +173 -0
  52. package/lib/Socket/index.js +10 -15
  53. package/lib/Socket/messages-recv.d.ts +161 -0
  54. package/lib/Socket/messages-recv.js +1054 -1107
  55. package/lib/Socket/messages-send.d.ts +149 -0
  56. package/lib/Socket/messages-send.js +447 -706
  57. package/lib/Socket/newsletter.d.ts +134 -0
  58. package/lib/Socket/newsletter.js +314 -199
  59. package/lib/Socket/registration.d.ts +267 -0
  60. package/lib/Socket/registration.js +166 -0
  61. package/lib/Socket/socket.d.ts +43 -0
  62. package/lib/Socket/socket.js +650 -777
  63. package/lib/Socket/usync.d.ts +36 -0
  64. package/lib/Socket/usync.js +70 -0
  65. package/lib/Store/index.d.ts +3 -0
  66. package/lib/Store/index.js +10 -6
  67. package/lib/Store/make-cache-manager-store.d.ts +13 -0
  68. package/lib/Store/make-cache-manager-store.js +81 -73
  69. package/lib/Store/make-in-memory-store.d.ts +118 -0
  70. package/lib/Store/make-in-memory-store.js +423 -286
  71. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  72. package/lib/Store/make-ordered-dictionary.js +79 -77
  73. package/lib/Store/object-repository.d.ts +10 -0
  74. package/lib/Store/object-repository.js +26 -24
  75. package/lib/Types/Auth.d.ts +110 -0
  76. package/lib/Types/Auth.js +2 -3
  77. package/lib/Types/Call.d.ts +13 -0
  78. package/lib/Types/Call.js +2 -3
  79. package/lib/Types/Chat.d.ts +102 -0
  80. package/lib/Types/Chat.js +4 -9
  81. package/lib/Types/Contact.d.ts +19 -0
  82. package/lib/Types/Contact.js +2 -3
  83. package/lib/Types/Events.d.ts +157 -0
  84. package/lib/Types/Events.js +2 -3
  85. package/lib/Types/GroupMetadata.d.ts +55 -0
  86. package/lib/Types/GroupMetadata.js +2 -3
  87. package/lib/Types/Label.d.ts +35 -0
  88. package/lib/Types/Label.js +26 -24
  89. package/lib/Types/LabelAssociation.d.ts +29 -0
  90. package/lib/Types/LabelAssociation.js +8 -6
  91. package/lib/Types/Message.d.ts +273 -0
  92. package/lib/Types/Message.js +9 -12
  93. package/lib/Types/Newsletter.d.ts +103 -0
  94. package/lib/Types/Newsletter.js +38 -33
  95. package/lib/Types/Product.d.ts +78 -0
  96. package/lib/Types/Product.js +2 -3
  97. package/lib/Types/Signal.d.ts +57 -0
  98. package/lib/Types/Signal.js +2 -3
  99. package/lib/Types/Socket.d.ts +111 -0
  100. package/lib/Types/Socket.js +2 -4
  101. package/lib/Types/State.d.ts +27 -0
  102. package/lib/Types/State.js +2 -11
  103. package/lib/Types/USync.d.ts +25 -0
  104. package/lib/Types/USync.js +2 -3
  105. package/lib/Types/index.d.ts +57 -0
  106. package/lib/Types/index.js +41 -27
  107. package/lib/Utils/auth-utils.d.ts +18 -0
  108. package/lib/Utils/auth-utils.js +198 -211
  109. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  110. package/lib/Utils/baileys-event-stream.js +61 -42
  111. package/lib/Utils/business.d.ts +22 -0
  112. package/lib/Utils/business.js +214 -213
  113. package/lib/Utils/chat-utils.d.ts +71 -0
  114. package/lib/Utils/chat-utils.js +687 -710
  115. package/lib/Utils/crypto.d.ts +41 -0
  116. package/lib/Utils/crypto.js +133 -112
  117. package/lib/Utils/decode-wa-message.d.ts +19 -0
  118. package/lib/Utils/decode-wa-message.js +183 -252
  119. package/lib/Utils/event-buffer.d.ts +35 -0
  120. package/lib/Utils/event-buffer.js +496 -510
  121. package/lib/Utils/generics.d.ts +92 -0
  122. package/lib/Utils/generics.js +387 -319
  123. package/lib/Utils/history.d.ts +15 -0
  124. package/lib/Utils/history.js +92 -83
  125. package/lib/Utils/index.d.ts +17 -0
  126. package/lib/Utils/index.js +33 -21
  127. package/lib/Utils/link-preview.d.ts +21 -0
  128. package/lib/Utils/link-preview.js +83 -71
  129. package/lib/Utils/logger.d.ts +4 -0
  130. package/lib/Utils/logger.js +7 -5
  131. package/lib/Utils/lt-hash.d.ts +12 -0
  132. package/lib/Utils/lt-hash.js +46 -40
  133. package/lib/Utils/make-mutex.d.ts +7 -0
  134. package/lib/Utils/make-mutex.js +41 -34
  135. package/lib/Utils/messages-media.d.ts +116 -0
  136. package/lib/Utils/messages-media.js +768 -550
  137. package/lib/Utils/messages.d.ts +77 -0
  138. package/lib/Utils/messages.js +263 -362
  139. package/lib/Utils/noise-handler.d.ts +21 -0
  140. package/lib/Utils/noise-handler.js +149 -138
  141. package/lib/Utils/process-message.d.ts +41 -0
  142. package/lib/Utils/process-message.js +303 -323
  143. package/lib/Utils/signal.d.ts +32 -0
  144. package/lib/Utils/signal.js +141 -149
  145. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  146. package/lib/Utils/use-multi-file-auth-state.js +103 -95
  147. package/lib/Utils/validate-connection.d.ts +11 -0
  148. package/lib/Utils/validate-connection.js +220 -183
  149. package/lib/WABinary/constants.d.ts +30 -0
  150. package/lib/WABinary/constants.js +35 -1298
  151. package/lib/WABinary/decode.d.ts +7 -0
  152. package/lib/WABinary/decode.js +249 -237
  153. package/lib/WABinary/encode.d.ts +3 -0
  154. package/lib/WABinary/encode.js +260 -213
  155. package/lib/WABinary/generic-utils.d.ts +17 -0
  156. package/lib/WABinary/generic-utils.js +65 -56
  157. package/lib/WABinary/index.d.ts +5 -0
  158. package/lib/WABinary/index.js +21 -7
  159. package/lib/WABinary/jid-utils.d.ts +31 -0
  160. package/lib/WABinary/jid-utils.js +58 -89
  161. package/lib/WABinary/types.d.ts +18 -0
  162. package/lib/WABinary/types.js +2 -3
  163. package/lib/WAM/BinaryInfo.d.ts +17 -0
  164. package/lib/WAM/BinaryInfo.js +12 -10
  165. package/lib/WAM/constants.d.ts +38 -0
  166. package/lib/WAM/constants.js +15348 -22851
  167. package/lib/WAM/encode.d.ts +3 -0
  168. package/lib/WAM/encode.js +136 -135
  169. package/lib/WAM/index.d.ts +3 -0
  170. package/lib/WAM/index.js +19 -5
  171. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  172. package/lib/WAUSync/Protocols/USyncContactProtocol.js +30 -28
  173. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  174. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -49
  175. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  176. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +28 -27
  177. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  178. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +39 -36
  179. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +25 -0
  180. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +50 -50
  181. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +8 -0
  182. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +20 -26
  183. package/lib/WAUSync/Protocols/index.d.ts +4 -0
  184. package/lib/WAUSync/Protocols/index.js +20 -6
  185. package/lib/WAUSync/USyncQuery.d.ts +28 -0
  186. package/lib/WAUSync/USyncQuery.js +85 -86
  187. package/lib/WAUSync/USyncUser.d.ts +12 -0
  188. package/lib/WAUSync/USyncUser.js +25 -23
  189. package/lib/WAUSync/index.d.ts +3 -0
  190. package/lib/WAUSync/index.js +19 -5
  191. package/lib/index.d.ts +12 -0
  192. package/lib/index.js +36 -24
  193. package/package.json +106 -98
  194. package/LICENSE +0 -21
  195. package/WAProto/WAProto.proto +0 -5311
  196. package/lib/KeyDB/BinarySearch.js +0 -20
  197. package/lib/KeyDB/KeyedDB.js +0 -167
  198. package/lib/KeyDB/index.js +0 -4
  199. package/lib/Signal/lid-mapping.js +0 -155
  200. package/lib/Socket/Client/types.js +0 -13
  201. package/lib/Socket/Client/websocket.js +0 -52
  202. package/lib/Socket/Client/websocket.js.bak +0 -53
  203. package/lib/Socket/communities.js +0 -413
  204. package/lib/Socket/mex.js +0 -45
  205. package/lib/Types/Bussines.js +0 -3
  206. package/lib/Types/Newsletter.js.bak +0 -33
  207. package/lib/Utils/browser-utils.js +0 -25
  208. package/lib/Utils/message-retry-manager.js +0 -113
  209. package/lib/Utils/messages.js.bak +0 -907
  210. package/lib/Utils/pre-key-manager.js +0 -85
@@ -0,0 +1,32 @@
1
+ import { SignalRepository } from '../Types';
2
+ import { AuthenticationCreds, AuthenticationState, KeyPair, SignalIdentity, SignalKeyStore, SignedKeyPair } from '../Types/Auth';
3
+ import { BinaryNode, JidWithDevice } from '../WABinary';
4
+ export declare const createSignalIdentity: (wid: string, accountSignatureKey: Uint8Array) => SignalIdentity;
5
+ export declare const getPreKeys: ({ get }: SignalKeyStore, min: number, limit: number) => Promise<{
6
+ [id: string]: KeyPair;
7
+ }>;
8
+ export declare const generateOrGetPreKeys: (creds: AuthenticationCreds, range: number) => {
9
+ newPreKeys: {
10
+ [id: number]: KeyPair;
11
+ };
12
+ lastPreKeyId: number;
13
+ preKeysRange: readonly [number, number];
14
+ };
15
+ export declare const xmppSignedPreKey: (key: SignedKeyPair) => BinaryNode;
16
+ export declare const xmppPreKey: (pair: KeyPair, id: number) => BinaryNode;
17
+ export declare const parseAndInjectE2ESessions: (node: BinaryNode, repository: SignalRepository) => Promise<void>;
18
+ export declare const extractDeviceJids: (result: BinaryNode, myJid: string, excludeZeroDevices: boolean) => JidWithDevice[];
19
+ /**
20
+ * get the next N keys for upload or processing
21
+ * @param count number of pre-keys to get or generate
22
+ */
23
+ export declare const getNextPreKeys: ({ creds, keys }: AuthenticationState, count: number) => Promise<{
24
+ update: Partial<AuthenticationCreds>;
25
+ preKeys: {
26
+ [id: string]: KeyPair;
27
+ };
28
+ }>;
29
+ export declare const getNextPreKeysNode: (state: AuthenticationState, count: number) => Promise<{
30
+ update: Partial<AuthenticationCreds>;
31
+ node: BinaryNode;
32
+ }>;
@@ -1,161 +1,153 @@
1
- //=======================================================//
2
- import { assertNodeErrorFree, getBinaryNodeChild, getBinaryNodeChildBuffer, getBinaryNodeChildren, getBinaryNodeChildUInt, getServerFromDomainType, jidDecode, S_WHATSAPP_NET, WAJIDDomains } from "../WABinary/index.js";
3
- import { Curve, generateSignalPubKey } from "./crypto.js";
4
- import { KEY_BUNDLE_TYPE } from "../Defaults/index.js";
5
- import { encodeBigEndian } from "./generics.js";
6
- //=======================================================//
7
- function chunk(array, size) {
8
- const chunks = [];
9
- for (let i = 0; i < array.length; i += size) {
10
- chunks.push(array.slice(i, i + size));
11
- }
12
- return chunks;
13
- }
14
- //=======================================================//
15
- export const createSignalIdentity = (wid, accountSignatureKey) => {
16
- return {
17
- identifier: { name: wid, deviceId: 0 },
18
- identifierKey: generateSignalPubKey(accountSignatureKey)
19
- };
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getNextPreKeysNode = exports.getNextPreKeys = exports.extractDeviceJids = exports.parseAndInjectE2ESessions = exports.xmppPreKey = exports.xmppSignedPreKey = exports.generateOrGetPreKeys = exports.getPreKeys = exports.createSignalIdentity = void 0;
4
+ const Defaults_1 = require("../Defaults");
5
+ const WABinary_1 = require("../WABinary");
6
+ const crypto_1 = require("./crypto");
7
+ const lodash_1 = require("lodash")
8
+ const generics_1 = require("./generics");
9
+ const createSignalIdentity = (wid, accountSignatureKey) => {
10
+ return {
11
+ identifier: { name: wid, deviceId: 0 },
12
+ identifierKey: (0, crypto_1.generateSignalPubKey)(accountSignatureKey)
13
+ };
20
14
  };
21
- //=======================================================//
22
- export const getPreKeys = async ({ get }, min, limit) => {
23
- const idList = [];
24
- for (let id = min; id < limit; id++) {
25
- idList.push(id.toString());
26
- }
27
- return get("pre-key", idList);
15
+ exports.createSignalIdentity = createSignalIdentity;
16
+ const getPreKeys = async ({ get }, min, limit) => {
17
+ const idList = [];
18
+ for (let id = min; id < limit; id++) {
19
+ idList.push(id.toString());
20
+ }
21
+ return get('pre-key', idList);
28
22
  };
29
- //=======================================================//
30
- export const generateOrGetPreKeys = (creds, range) => {
31
- const avaliable = creds.nextPreKeyId - creds.firstUnuploadedPreKeyId;
32
- const remaining = range - avaliable;
33
- const lastPreKeyId = creds.nextPreKeyId + remaining - 1;
34
- const newPreKeys = {};
35
- if (remaining > 0) {
36
- for (let i = creds.nextPreKeyId; i <= lastPreKeyId; i++) {
37
- newPreKeys[i] = Curve.generateKeyPair();
23
+ exports.getPreKeys = getPreKeys;
24
+ const generateOrGetPreKeys = (creds, range) => {
25
+ const avaliable = creds.nextPreKeyId - creds.firstUnuploadedPreKeyId;
26
+ const remaining = range - avaliable;
27
+ const lastPreKeyId = creds.nextPreKeyId + remaining - 1;
28
+ const newPreKeys = {};
29
+ if (remaining > 0) {
30
+ for (let i = creds.nextPreKeyId; i <= lastPreKeyId; i++) {
31
+ newPreKeys[i] = crypto_1.Curve.generateKeyPair();
32
+ }
38
33
  }
39
- }
40
- return {
41
- newPreKeys,
42
- lastPreKeyId,
43
- preKeysRange: [creds.firstUnuploadedPreKeyId, range]
44
- };
34
+ return {
35
+ newPreKeys,
36
+ lastPreKeyId,
37
+ preKeysRange: [creds.firstUnuploadedPreKeyId, range],
38
+ };
45
39
  };
46
- //=======================================================//
47
- export const xmppSignedPreKey = (key) => ({
48
- tag: "skey",
49
- attrs: {},
50
- content: [
51
- { tag: "id", attrs: {}, content: encodeBigEndian(key.keyId, 3) },
52
- { tag: "value", attrs: {}, content: key.keyPair.public },
53
- { tag: "signature", attrs: {}, content: key.signature }
54
- ]
40
+ exports.generateOrGetPreKeys = generateOrGetPreKeys;
41
+ const xmppSignedPreKey = (key) => ({
42
+ tag: 'skey',
43
+ attrs: {},
44
+ content: [
45
+ { tag: 'id', attrs: {}, content: (0, generics_1.encodeBigEndian)(key.keyId, 3) },
46
+ { tag: 'value', attrs: {}, content: key.keyPair.public },
47
+ { tag: 'signature', attrs: {}, content: key.signature }
48
+ ]
55
49
  });
56
- //=======================================================//
57
- export const xmppPreKey = (pair, id) => ({
58
- tag: "key",
59
- attrs: {},
60
- content: [
61
- { tag: "id", attrs: {}, content: encodeBigEndian(id, 3) },
62
- { tag: "value", attrs: {}, content: pair.public }
63
- ]
50
+ exports.xmppSignedPreKey = xmppSignedPreKey;
51
+ const xmppPreKey = (pair, id) => ({
52
+ tag: 'key',
53
+ attrs: {},
54
+ content: [
55
+ { tag: 'id', attrs: {}, content: (0, generics_1.encodeBigEndian)(id, 3) },
56
+ { tag: 'value', attrs: {}, content: pair.public }
57
+ ]
64
58
  });
65
- //=======================================================//
66
- export const parseAndInjectE2ESessions = async (node, repository) => {
67
- const extractKey = (key) => key
68
- ? {
69
- keyId: getBinaryNodeChildUInt(key, "id", 3),
70
- publicKey: generateSignalPubKey(getBinaryNodeChildBuffer(key, "value")),
71
- signature: getBinaryNodeChildBuffer(key, "signature")
59
+ exports.xmppPreKey = xmppPreKey;
60
+ const parseAndInjectE2ESessions = async (node, repository) => {
61
+ const extractKey = (key) => (key ? ({
62
+ keyId: WABinary_1.getBinaryNodeChildUInt(key, 'id', 3),
63
+ publicKey: crypto_1.generateSignalPubKey(WABinary_1.getBinaryNodeChildBuffer(key, 'value')),
64
+ signature: WABinary_1.getBinaryNodeChildBuffer(key, 'signature')
65
+ }) : undefined)
66
+ const nodes = WABinary_1.getBinaryNodeChildren(WABinary_1.getBinaryNodeChild(node, 'list'), 'user')
67
+ for (const node of nodes) {
68
+ WABinary_1.assertNodeErrorFree(node)
72
69
  }
73
- : undefined;
74
- const nodes = getBinaryNodeChildren(getBinaryNodeChild(node, "list"), "user");
75
- for (const node of nodes) {
76
- assertNodeErrorFree(node);
77
- }
78
- const chunkSize = 100;
79
- const chunks = chunk(nodes, chunkSize);
80
- for (const nodesChunk of chunks) {
81
- for (const node of nodesChunk) {
82
- const signedKey = getBinaryNodeChild(node, "skey");
83
- const key = getBinaryNodeChild(node, "key");
84
- const identity = getBinaryNodeChildBuffer(node, "identity");
85
- const jid = node.attrs.jid;
86
- const registrationId = getBinaryNodeChildUInt(node, "registration", 4);
87
- await repository.injectE2ESession({
88
- jid,
89
- session: {
90
- registrationId: registrationId,
91
- identityKey: generateSignalPubKey(identity),
92
- signedPreKey: extractKey(signedKey),
93
- preKey: extractKey(key)
94
- }
95
- });
70
+ // Most of the work in repository.injectE2ESession is CPU intensive, not IO
71
+ // So Promise.all doesn't really help here,
72
+ // but blocks even loop if we're using it inside keys.transaction, and it makes it "sync" actually
73
+ // This way we chunk it in smaller parts and between those parts we can yield to the event loop
74
+ // It's rare case when you need to E2E sessions for so many users, but it's possible
75
+ const chunkSize = 100
76
+ const chunks = lodash_1.chunk(nodes, chunkSize)
77
+ for (const nodesChunk of chunks) {
78
+ await Promise.all(nodesChunk.map(async (node) => {
79
+ const signedKey = WABinary_1.getBinaryNodeChild(node, 'skey')
80
+ const key = WABinary_1.getBinaryNodeChild(node, 'key')
81
+ const identity = WABinary_1.getBinaryNodeChildBuffer(node, 'identity')
82
+ const jid = node.attrs.jid
83
+ const registrationId = WABinary_1.getBinaryNodeChildUInt(node, 'registration', 4)
84
+ await repository.injectE2ESession({
85
+ jid,
86
+ session: {
87
+ registrationId: registrationId,
88
+ identityKey: crypto_1.generateSignalPubKey(identity),
89
+ signedPreKey: extractKey(signedKey),
90
+ preKey: extractKey(key)
91
+ }
92
+ })
93
+ }))
96
94
  }
97
- }
98
- };
99
- //=======================================================//
100
- export const extractDeviceJids = (result, myJid, myLid, excludeZeroDevices) => {
101
- const { user: myUser, device: myDevice } = jidDecode(myJid);
102
- const extracted = [];
103
- for (const userResult of result) {
104
- const { devices, id } = userResult;
105
- const decoded = jidDecode(id), { user, server } = decoded;
106
- let { domainType } = decoded;
107
- const deviceList = devices?.deviceList;
108
- if (!Array.isArray(deviceList))
109
- continue;
110
- for (const { id: device, keyIndex, isHosted } of deviceList) {
111
- if ((!excludeZeroDevices || device !== 0) &&
112
- ((myUser !== user && myLid !== user) || myDevice !== device) &&
113
- (device === 0 || !!keyIndex)
114
- ) {
115
- if (isHosted) {
116
- domainType = domainType === WAJIDDomains.LID ? WAJIDDomains.HOSTED_LID : WAJIDDomains.HOSTED;
95
+ }
96
+ exports.parseAndInjectE2ESessions = parseAndInjectE2ESessions;
97
+ const extractDeviceJids = (result, myJid, excludeZeroDevices) => {
98
+ const { user: myUser, device: myDevice } = WABinary_1.jidDecode(myJid)
99
+ const extracted = []
100
+ for (const userResult of result) {
101
+ const { devices, id } = userResult
102
+ const { user } = WABinary_1.jidDecode(id)
103
+ const deviceList = devices?.deviceList
104
+ if (Array.isArray(deviceList)) {
105
+ for (const { id: device, keyIndex } of deviceList) {
106
+ if ((!excludeZeroDevices || device !== 0) && // if zero devices are not-excluded, or device is non zero
107
+ (myUser !== user || myDevice !== device) && // either different user or if me user, not this device
108
+ (device === 0 || !!keyIndex) // ensure that "key-index" is specified for "non-zero" devices, produces a bad req otherwise
109
+ ) {
110
+ extracted.push({ user, device })
111
+ }
112
+ }
117
113
  }
118
- extracted.push({
119
- user,
120
- device,
121
- domainType,
122
- server: getServerFromDomainType(server, domainType)
123
- });
124
- }
125
114
  }
126
- }
127
- return extracted;
128
- };
129
- //=======================================================//
130
- export const getNextPreKeys = async ({ creds, keys }, count) => {
131
- const { newPreKeys, lastPreKeyId, preKeysRange } = generateOrGetPreKeys(creds, count);
132
- const update = {
133
- nextPreKeyId: Math.max(lastPreKeyId + 1, creds.nextPreKeyId),
134
- firstUnuploadedPreKeyId: Math.max(creds.firstUnuploadedPreKeyId, lastPreKeyId + 1)
135
- };
136
- await keys.set({ "pre-key": newPreKeys });
137
- const preKeys = await getPreKeys(keys, preKeysRange[0], preKeysRange[0] + preKeysRange[1]);
138
- return { update, preKeys };
115
+ return extracted
116
+ }
117
+ exports.extractDeviceJids = extractDeviceJids;
118
+ /**
119
+ * get the next N keys for upload or processing
120
+ * @param count number of pre-keys to get or generate
121
+ */
122
+ const getNextPreKeys = async ({ creds, keys }, count) => {
123
+ const { newPreKeys, lastPreKeyId, preKeysRange } = (0, exports.generateOrGetPreKeys)(creds, count);
124
+ const update = {
125
+ nextPreKeyId: Math.max(lastPreKeyId + 1, creds.nextPreKeyId),
126
+ firstUnuploadedPreKeyId: Math.max(creds.firstUnuploadedPreKeyId, lastPreKeyId + 1)
127
+ };
128
+ await keys.set({ 'pre-key': newPreKeys });
129
+ const preKeys = await (0, exports.getPreKeys)(keys, preKeysRange[0], preKeysRange[0] + preKeysRange[1]);
130
+ return { update, preKeys };
139
131
  };
140
- //=======================================================//
141
- export const getNextPreKeysNode = async (state, count) => {
142
- const { creds } = state;
143
- const { update, preKeys } = await getNextPreKeys(state, count);
144
- const node = {
145
- tag: "iq",
146
- attrs: {
147
- xmlns: "encrypt",
148
- type: "set",
149
- to: S_WHATSAPP_NET
150
- },
151
- content: [
152
- { tag: "registration", attrs: {}, content: encodeBigEndian(creds.registrationId) },
153
- { tag: "type", attrs: {}, content: KEY_BUNDLE_TYPE },
154
- { tag: "identity", attrs: {}, content: creds.signedIdentityKey.public },
155
- { tag: "list", attrs: {}, content: Object.keys(preKeys).map(k => xmppPreKey(preKeys[+k], +k)) },
156
- xmppSignedPreKey(creds.signedPreKey)
157
- ]
158
- };
159
- return { update, node };
132
+ exports.getNextPreKeys = getNextPreKeys;
133
+ const getNextPreKeysNode = async (state, count) => {
134
+ const { creds } = state;
135
+ const { update, preKeys } = await (0, exports.getNextPreKeys)(state, count);
136
+ const node = {
137
+ tag: 'iq',
138
+ attrs: {
139
+ xmlns: 'encrypt',
140
+ type: 'set',
141
+ to: WABinary_1.S_WHATSAPP_NET,
142
+ },
143
+ content: [
144
+ { tag: 'registration', attrs: {}, content: (0, generics_1.encodeBigEndian)(creds.registrationId) },
145
+ { tag: 'type', attrs: {}, content: Defaults_1.KEY_BUNDLE_TYPE },
146
+ { tag: 'identity', attrs: {}, content: creds.signedIdentityKey.public },
147
+ { tag: 'list', attrs: {}, content: Object.keys(preKeys).map(k => (0, exports.xmppPreKey)(preKeys[+k], +k)) },
148
+ (0, exports.xmppSignedPreKey)(creds.signedPreKey)
149
+ ]
150
+ };
151
+ return { update, node };
160
152
  };
161
- //=======================================================//
153
+ exports.getNextPreKeysNode = getNextPreKeysNode;
@@ -0,0 +1,13 @@
1
+ import { AuthenticationState } from '../Types';
2
+ /**
3
+ * stores the full authentication state in a single folder.
4
+ * Far more efficient than singlefileauthstate
5
+ *
6
+ * Again, I wouldn't endorse this for any production level use other than perhaps a bot.
7
+ * Would recommend writing an auth state for use with a proper SQL or No-SQL DB
8
+ * */
9
+ export declare const useMultiFileAuthState: (folder: string) => Promise<{
10
+ state: AuthenticationState;
11
+ saveCreds: () => Promise<void>;
12
+ }>;
13
+
@@ -1,111 +1,119 @@
1
- //=======================================================//
2
- import { mkdir, readFile, stat, unlink, writeFile } from "fs/promises";
3
- import { initAuthCreds } from "./auth-utils.js";
4
- import { proto } from "../../WAProto/index.js";
5
- import { BufferJSON } from "./generics.js";
6
- import { Mutex } from "async-mutex";
7
- import { join } from "path";
8
- //=======================================================//
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 WAProto_1 = require("../../WAProto");
8
+ const auth_utils_1 = require("./auth-utils");
9
+ const generics_1 = require("./generics");
9
10
  const fileLocks = new Map();
10
11
  const getFileLock = (path) => {
11
- let mutex = fileLocks.get(path);
12
- if (!mutex) {
13
- mutex = new Mutex();
14
- fileLocks.set(path, mutex);
15
- }
16
- return mutex;
12
+ let mutex = fileLocks.get(path);
13
+ if (!mutex) {
14
+ mutex = new async_mutex_1.Mutex();
15
+ fileLocks.set(path, mutex);
16
+ }
17
+ return mutex;
17
18
  };
18
- //=======================================================//
19
- export const useMultiFileAuthState = async (folder) => {
20
- const writeData = async (data, file) => {
21
- const filePath = join(folder, fixFileName(file));
22
- const mutex = getFileLock(filePath);
23
- return mutex.acquire().then(async (release) => {
24
- try {
25
- await writeFile(filePath, JSON.stringify(data, BufferJSON.replacer));
26
- }
27
- finally {
28
- release();
29
- }
30
- });
31
- };
32
- const readData = async (file) => {
33
- try {
34
- const filePath = join(folder, fixFileName(file));
35
- const mutex = getFileLock(filePath);
36
- return await mutex.acquire().then(async (release) => {
19
+ /**
20
+ * stores the full authentication state in a single folder.
21
+ * Far more efficient than singlefileauthstate
22
+ *
23
+ * Again, I wouldn't endorse this for any production level use other than perhaps a bot.
24
+ * Would recommend writing an auth state for use with a proper SQL or No-SQL DB
25
+ * */
26
+ const useMultiFileAuthState = async (folder) => {
27
+ const writeData = async (data, file) => {
28
+ const filePath = (0, path_1.join)(folder, fixFileName(file));
29
+ const mutex = getFileLock(filePath);
30
+ return mutex.acquire().then(async (release) => {
31
+ try {
32
+ await (0, promises_1.writeFile)(filePath, JSON.stringify(data, generics_1.BufferJSON.replacer));
33
+ }
34
+ finally {
35
+ release();
36
+ }
37
+ });
38
+ };
39
+ const readData = async (file) => {
37
40
  try {
38
- const data = await readFile(filePath, { encoding: "utf-8" });
39
- return JSON.parse(data, BufferJSON.reviver);
41
+ const filePath = (0, path_1.join)(folder, fixFileName(file));
42
+ const mutex = getFileLock(filePath);
43
+ return await mutex.acquire().then(async (release) => {
44
+ try {
45
+ const data = await (0, promises_1.readFile)(filePath, { encoding: 'utf-8' });
46
+ return JSON.parse(data, generics_1.BufferJSON.reviver);
47
+ }
48
+ finally {
49
+ release();
50
+ }
51
+ });
40
52
  }
41
- finally {
42
- release();
53
+ catch (error) {
54
+ return null;
43
55
  }
44
- });
45
- }
46
- catch (error) {
47
- return null;
48
- }
49
- };
50
- const removeData = async (file) => {
51
- try {
52
- const filePath = join(folder, fixFileName(file));
53
- const mutex = getFileLock(filePath);
54
- return mutex.acquire().then(async (release) => {
56
+ };
57
+ const removeData = async (file) => {
55
58
  try {
56
- await unlink(filePath);
59
+ const filePath = (0, path_1.join)(folder, fixFileName(file));
60
+ const mutex = getFileLock(filePath);
61
+ return mutex.acquire().then(async (release) => {
62
+ try {
63
+ await (0, promises_1.unlink)(filePath);
64
+ }
65
+ catch (_a) {
66
+ }
67
+ finally {
68
+ release();
69
+ }
70
+ });
57
71
  }
58
- catch {
72
+ catch (_a) {
59
73
  }
60
- finally {
61
- release();
74
+ };
75
+ const folderInfo = await (0, promises_1.stat)(folder).catch(() => { });
76
+ if (folderInfo) {
77
+ if (!folderInfo.isDirectory()) {
78
+ throw new Error(`found something that is not a directory at ${folder}, either delete it or specify a different location`);
62
79
  }
63
- });
64
80
  }
65
- catch { }
66
- };
67
- const folderInfo = await stat(folder).catch(() => { });
68
- if (folderInfo) {
69
- if (!folderInfo.isDirectory()) {
70
- throw new Error(`found something that is not a directory at ${folder}, either delete it or specify a different location`);
81
+ else {
82
+ await (0, promises_1.mkdir)(folder, { recursive: true });
71
83
  }
72
- }
73
- else {
74
- await mkdir(folder, { recursive: true });
75
- }
76
- const fixFileName = (file) => file?.replace(/\//g, "__")?.replace(/:/g, "-");
77
- const creds = (await readData("creds.json")) || initAuthCreds();
78
- return {
79
- state: {
80
- creds,
81
- keys: {
82
- get: async (type, ids) => {
83
- const data = {};
84
- await Promise.all(ids.map(async (id) => {
85
- let value = await readData(`${type}-${id}.json`);
86
- if (type === "app-state-sync-key" && value) {
87
- value = proto.Message.AppStateSyncKeyData.fromObject(value);
84
+ 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, '-'); };
85
+ const creds = await readData('creds.json') || (0, auth_utils_1.initAuthCreds)();
86
+ return {
87
+ state: {
88
+ creds,
89
+ keys: {
90
+ get: async (type, ids) => {
91
+ const data = {};
92
+ await Promise.all(ids.map(async (id) => {
93
+ let value = await readData(`${type}-${id}.json`);
94
+ if (type === 'app-state-sync-key' && value) {
95
+ value = WAProto_1.proto.Message.AppStateSyncKeyData.fromObject(value);
96
+ }
97
+ data[id] = value;
98
+ }));
99
+ return data;
100
+ },
101
+ set: async (data) => {
102
+ const tasks = [];
103
+ for (const category in data) {
104
+ for (const id in data[category]) {
105
+ const value = data[category][id];
106
+ const file = `${category}-${id}.json`;
107
+ tasks.push(value ? writeData(value, file) : removeData(file));
108
+ }
109
+ }
110
+ await Promise.all(tasks);
111
+ }
88
112
  }
89
- data[id] = value;
90
- }));
91
- return data;
92
113
  },
93
- set: async (data) => {
94
- const tasks = [];
95
- for (const category in data) {
96
- for (const id in data[category]) {
97
- const value = data[category][id];
98
- const file = `${category}-${id}.json`;
99
- tasks.push(value ? writeData(value, file) : removeData(file));
100
- }
101
- }
102
- await Promise.all(tasks);
114
+ saveCreds: async () => {
115
+ return writeData(creds, 'creds.json');
103
116
  }
104
- }
105
- },
106
- saveCreds: async () => {
107
- return writeData(creds, "creds.json");
108
- }
109
- };
117
+ };
110
118
  };
111
- //=======================================================//
119
+ exports.useMultiFileAuthState = useMultiFileAuthState;
@@ -0,0 +1,11 @@
1
+ import { proto } from '../../WAProto';
2
+ import type { AuthenticationCreds, SignalCreds, SocketConfig } from '../Types';
3
+ import { BinaryNode } from '../WABinary';
4
+ export declare const generateMobileNode: (config: SocketConfig) => proto.IClientPayload;
5
+ export declare const generateLoginNode: (userJid: string, config: SocketConfig) => proto.IClientPayload;
6
+ export declare const generateRegistrationNode: ({ registrationId, signedPreKey, signedIdentityKey }: SignalCreds, config: SocketConfig) => proto.ClientPayload;
7
+ export declare const configureSuccessfulPairing: (stanza: BinaryNode, { advSecretKey, signedIdentityKey, signalIdentities }: Pick<AuthenticationCreds, 'advSecretKey' | 'signedIdentityKey' | 'signalIdentities'>) => {
8
+ creds: Partial<AuthenticationCreds>;
9
+ reply: BinaryNode;
10
+ };
11
+ export declare const encodeSignedDeviceIdentity: (account: proto.IADVSignedDeviceIdentity, includeSignatureKey: boolean) => Uint8Array;