lordceaser-baileys 2.0.2 → 2.0.3

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 (166) hide show
  1. package/index.js +1 -17
  2. package/package.json +4 -3
  3. package/WAProto/index.js +0 -155693
  4. package/lib/Defaults/baileys-version.json +0 -3
  5. package/lib/Defaults/index.d.ts +0 -53
  6. package/lib/Defaults/index.js +0 -108
  7. package/lib/Signal/libsignal.d.ts +0 -3
  8. package/lib/Signal/libsignal.js +0 -152
  9. package/lib/Socket/Client/abstract-socket-client.d.ts +0 -17
  10. package/lib/Socket/Client/abstract-socket-client.js +0 -13
  11. package/lib/Socket/Client/index.d.ts +0 -3
  12. package/lib/Socket/Client/index.js +0 -19
  13. package/lib/Socket/Client/mobile-socket-client.d.ts +0 -13
  14. package/lib/Socket/Client/mobile-socket-client.js +0 -65
  15. package/lib/Socket/Client/web-socket-client.d.ts +0 -12
  16. package/lib/Socket/Client/web-socket-client.js +0 -62
  17. package/lib/Socket/business.d.ts +0 -170
  18. package/lib/Socket/business.js +0 -260
  19. package/lib/Socket/chats.d.ts +0 -81
  20. package/lib/Socket/chats.js +0 -950
  21. package/lib/Socket/groups.d.ts +0 -115
  22. package/lib/Socket/groups.js +0 -315
  23. package/lib/Socket/index.d.ts +0 -172
  24. package/lib/Socket/index.js +0 -10
  25. package/lib/Socket/messages-recv.d.ts +0 -158
  26. package/lib/Socket/messages-recv.js +0 -972
  27. package/lib/Socket/messages-send.d.ts +0 -155
  28. package/lib/Socket/messages-send.js +0 -1087
  29. package/lib/Socket/newsletter.d.ts +0 -132
  30. package/lib/Socket/newsletter.js +0 -236
  31. package/lib/Socket/registration.d.ts +0 -264
  32. package/lib/Socket/registration.js +0 -166
  33. package/lib/Socket/socket.d.ts +0 -44
  34. package/lib/Socket/socket.js +0 -642
  35. package/lib/Socket/usync.d.ts +0 -37
  36. package/lib/Socket/usync.js +0 -70
  37. package/lib/Store/index.d.ts +0 -3
  38. package/lib/Store/index.js +0 -10
  39. package/lib/Store/make-cache-manager-store.d.ts +0 -14
  40. package/lib/Store/make-cache-manager-store.js +0 -83
  41. package/lib/Store/make-in-memory-store.d.ts +0 -118
  42. package/lib/Store/make-in-memory-store.js +0 -431
  43. package/lib/Store/make-ordered-dictionary.d.ts +0 -13
  44. package/lib/Store/make-ordered-dictionary.js +0 -81
  45. package/lib/Store/object-repository.d.ts +0 -10
  46. package/lib/Store/object-repository.js +0 -27
  47. package/lib/Types/Auth.d.ts +0 -109
  48. package/lib/Types/Auth.js +0 -2
  49. package/lib/Types/Call.d.ts +0 -13
  50. package/lib/Types/Call.js +0 -2
  51. package/lib/Types/Chat.d.ts +0 -107
  52. package/lib/Types/Chat.js +0 -4
  53. package/lib/Types/Contact.d.ts +0 -19
  54. package/lib/Types/Contact.js +0 -2
  55. package/lib/Types/Events.d.ts +0 -172
  56. package/lib/Types/Events.js +0 -2
  57. package/lib/Types/GroupMetadata.d.ts +0 -56
  58. package/lib/Types/GroupMetadata.js +0 -2
  59. package/lib/Types/Label.d.ts +0 -46
  60. package/lib/Types/Label.js +0 -27
  61. package/lib/Types/LabelAssociation.d.ts +0 -29
  62. package/lib/Types/LabelAssociation.js +0 -9
  63. package/lib/Types/Message.d.ts +0 -433
  64. package/lib/Types/Message.js +0 -9
  65. package/lib/Types/Newsletter.d.ts +0 -92
  66. package/lib/Types/Newsletter.js +0 -32
  67. package/lib/Types/Product.d.ts +0 -78
  68. package/lib/Types/Product.js +0 -2
  69. package/lib/Types/Signal.d.ts +0 -57
  70. package/lib/Types/Signal.js +0 -2
  71. package/lib/Types/Socket.d.ts +0 -116
  72. package/lib/Types/Socket.js +0 -2
  73. package/lib/Types/State.d.ts +0 -27
  74. package/lib/Types/State.js +0 -2
  75. package/lib/Types/USync.d.ts +0 -25
  76. package/lib/Types/USync.js +0 -2
  77. package/lib/Types/index.d.ts +0 -66
  78. package/lib/Types/index.js +0 -42
  79. package/lib/Utils/auth-utils.d.ts +0 -18
  80. package/lib/Utils/auth-utils.js +0 -206
  81. package/lib/Utils/baileys-event-stream.d.ts +0 -16
  82. package/lib/Utils/baileys-event-stream.js +0 -63
  83. package/lib/Utils/business.d.ts +0 -22
  84. package/lib/Utils/business.js +0 -234
  85. package/lib/Utils/c4-compat.js +0 -16
  86. package/lib/Utils/chat-utils.d.ts +0 -70
  87. package/lib/Utils/chat-utils.js +0 -745
  88. package/lib/Utils/crypto.d.ts +0 -40
  89. package/lib/Utils/crypto.js +0 -199
  90. package/lib/Utils/decode-wa-message.d.ts +0 -36
  91. package/lib/Utils/decode-wa-message.js +0 -234
  92. package/lib/Utils/event-buffer.d.ts +0 -35
  93. package/lib/Utils/event-buffer.js +0 -517
  94. package/lib/Utils/generics.d.ts +0 -88
  95. package/lib/Utils/generics.js +0 -402
  96. package/lib/Utils/history.d.ts +0 -19
  97. package/lib/Utils/history.js +0 -94
  98. package/lib/Utils/index.d.ts +0 -17
  99. package/lib/Utils/index.js +0 -34
  100. package/lib/Utils/link-preview.d.ts +0 -21
  101. package/lib/Utils/link-preview.js +0 -93
  102. package/lib/Utils/logger.d.ts +0 -2
  103. package/lib/Utils/logger.js +0 -7
  104. package/lib/Utils/lt-hash.d.ts +0 -12
  105. package/lib/Utils/lt-hash.js +0 -51
  106. package/lib/Utils/make-mutex.d.ts +0 -7
  107. package/lib/Utils/make-mutex.js +0 -43
  108. package/lib/Utils/messages-media.d.ts +0 -113
  109. package/lib/Utils/messages-media.js +0 -721
  110. package/lib/Utils/messages.d.ts +0 -77
  111. package/lib/Utils/messages.js +0 -1221
  112. package/lib/Utils/noise-handler.d.ts +0 -20
  113. package/lib/Utils/noise-handler.js +0 -160
  114. package/lib/Utils/process-message.d.ts +0 -41
  115. package/lib/Utils/process-message.js +0 -373
  116. package/lib/Utils/signal.d.ts +0 -33
  117. package/lib/Utils/signal.js +0 -159
  118. package/lib/Utils/use-multi-file-auth-state.d.ts +0 -12
  119. package/lib/Utils/use-multi-file-auth-state.js +0 -167
  120. package/lib/Utils/use-single-file-auth-state.d.ts +0 -12
  121. package/lib/Utils/use-single-file-auth-state.js +0 -76
  122. package/lib/Utils/validate-connection.d.ts +0 -11
  123. package/lib/Utils/validate-connection.js +0 -205
  124. package/lib/WABinary/constants.d.ts +0 -27
  125. package/lib/WABinary/constants.js +0 -40
  126. package/lib/WABinary/decode.d.ts +0 -6
  127. package/lib/WABinary/decode.js +0 -264
  128. package/lib/WABinary/encode.d.ts +0 -2
  129. package/lib/WABinary/encode.js +0 -252
  130. package/lib/WABinary/generic-utils.d.ts +0 -14
  131. package/lib/WABinary/generic-utils.js +0 -110
  132. package/lib/WABinary/index.d.ts +0 -5
  133. package/lib/WABinary/index.js +0 -21
  134. package/lib/WABinary/jid-utils.d.ts +0 -31
  135. package/lib/WABinary/jid-utils.js +0 -62
  136. package/lib/WABinary/types.d.ts +0 -18
  137. package/lib/WABinary/types.js +0 -2
  138. package/lib/WAM/BinaryInfo.d.ts +0 -8
  139. package/lib/WAM/BinaryInfo.js +0 -13
  140. package/lib/WAM/constants.d.ts +0 -38
  141. package/lib/WAM/constants.js +0 -15350
  142. package/lib/WAM/encode.d.ts +0 -2
  143. package/lib/WAM/encode.js +0 -155
  144. package/lib/WAM/index.d.ts +0 -3
  145. package/lib/WAM/index.js +0 -19
  146. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +0 -9
  147. package/lib/WAUSync/Protocols/USyncContactProtocol.js +0 -32
  148. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +0 -22
  149. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +0 -57
  150. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +0 -12
  151. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +0 -30
  152. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +0 -12
  153. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +0 -42
  154. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +0 -25
  155. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +0 -53
  156. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +0 -8
  157. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +0 -24
  158. package/lib/WAUSync/Protocols/index.d.ts +0 -4
  159. package/lib/WAUSync/Protocols/index.js +0 -20
  160. package/lib/WAUSync/USyncQuery.d.ts +0 -28
  161. package/lib/WAUSync/USyncQuery.js +0 -89
  162. package/lib/WAUSync/USyncUser.d.ts +0 -10
  163. package/lib/WAUSync/USyncUser.js +0 -26
  164. package/lib/WAUSync/index.d.ts +0 -3
  165. package/lib/WAUSync/index.js +0 -19
  166. package/lib/index.js +0 -31
@@ -1,159 +0,0 @@
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 generics_1 = require("./generics");
8
- function chunk(array, size) {
9
- const result = [];
10
- for (let i = 0; i < array.length; i += size) {
11
- result.push(array.slice(i, i + size));
12
- }
13
- return result;
14
- }
15
- const createSignalIdentity = (wid, accountSignatureKey) => {
16
- return {
17
- identifier: { name: wid, deviceId: 0 },
18
- identifierKey: (0, crypto_1.generateSignalPubKey)(accountSignatureKey)
19
- };
20
- };
21
- exports.createSignalIdentity = createSignalIdentity;
22
- 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);
28
- };
29
- exports.getPreKeys = getPreKeys;
30
- 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] = crypto_1.Curve.generateKeyPair();
38
- }
39
- }
40
- return {
41
- newPreKeys,
42
- lastPreKeyId,
43
- preKeysRange: [creds.firstUnuploadedPreKeyId, range],
44
- };
45
- };
46
- exports.generateOrGetPreKeys = generateOrGetPreKeys;
47
- const xmppSignedPreKey = (key) => ({
48
- tag: 'skey',
49
- attrs: {},
50
- content: [
51
- { tag: 'id', attrs: {}, content: (0, generics_1.encodeBigEndian)(key.keyId, 3) },
52
- { tag: 'value', attrs: {}, content: key.keyPair.public },
53
- { tag: 'signature', attrs: {}, content: key.signature }
54
- ]
55
- });
56
- exports.xmppSignedPreKey = xmppSignedPreKey;
57
- const xmppPreKey = (pair, id) => ({
58
- tag: 'key',
59
- attrs: {},
60
- content: [
61
- { tag: 'id', attrs: {}, content: (0, generics_1.encodeBigEndian)(id, 3) },
62
- { tag: 'value', attrs: {}, content: pair.public }
63
- ]
64
- });
65
- exports.xmppPreKey = xmppPreKey;
66
- const parseAndInjectE2ESessions = async (node, repository) => {
67
- const extractKey = (key) => (key ? ({
68
- keyId: (0, WABinary_1.getBinaryNodeChildUInt)(key, 'id', 3),
69
- publicKey: (0, crypto_1.generateSignalPubKey)((0, WABinary_1.getBinaryNodeChildBuffer)(key, 'value')),
70
- signature: (0, WABinary_1.getBinaryNodeChildBuffer)(key, 'signature'),
71
- }) : undefined);
72
- const nodes = (0, WABinary_1.getBinaryNodeChildren)((0, WABinary_1.getBinaryNodeChild)(node, 'list'), 'user');
73
- for (const node of nodes) {
74
- (0, WABinary_1.assertNodeErrorFree)(node);
75
- }
76
- // Most of the work in repository.injectE2ESession is CPU intensive, not IO
77
- // So Promise.all doesn't really help here,
78
- // but blocks even loop if we're using it inside keys.transaction, and it makes it "sync" actually
79
- // This way we chunk it in smaller parts and between those parts we can yield to the event loop
80
- // It's rare case when you need to E2E sessions for so many users, but it's possible
81
- const chunkSize = 100;
82
- const chunks = chunk(nodes, chunkSize);
83
- for (const nodesChunk of chunks) {
84
- await Promise.all(nodesChunk.map(async (node) => {
85
- const signedKey = (0, WABinary_1.getBinaryNodeChild)(node, 'skey');
86
- const key = (0, WABinary_1.getBinaryNodeChild)(node, 'key');
87
- const identity = (0, WABinary_1.getBinaryNodeChildBuffer)(node, 'identity');
88
- const jid = node.attrs.jid;
89
- const registrationId = (0, WABinary_1.getBinaryNodeChildUInt)(node, 'registration', 4);
90
- await repository.injectE2ESession({
91
- jid,
92
- session: {
93
- registrationId: registrationId,
94
- identityKey: (0, crypto_1.generateSignalPubKey)(identity),
95
- signedPreKey: extractKey(signedKey),
96
- preKey: extractKey(key)
97
- }
98
- });
99
- }));
100
- }
101
- };
102
- exports.parseAndInjectE2ESessions = parseAndInjectE2ESessions;
103
- const extractDeviceJids = (result, myJid, excludeZeroDevices) => {
104
- const { user: myUser, device: myDevice } = (0, WABinary_1.jidDecode)(myJid);
105
- const extracted = [];
106
- for (const userResult of result) {
107
- const { devices, id } = userResult;
108
- const { user } = (0, WABinary_1.jidDecode)(id);
109
- const deviceList = devices === null || devices === void 0 ? void 0 : devices.deviceList;
110
- if (Array.isArray(deviceList)) {
111
- for (const { id: device, keyIndex } of deviceList) {
112
- if ((!excludeZeroDevices || device !== 0) && // if zero devices are not-excluded, or device is non zero
113
- (myUser !== user || myDevice !== device) && // either different user or if me user, not this device
114
- (device === 0 || !!keyIndex) // ensure that "key-index" is specified for "non-zero" devices, produces a bad req otherwise
115
- ) {
116
- extracted.push({ user, device });
117
- }
118
- }
119
- }
120
- }
121
- return extracted;
122
- };
123
- exports.extractDeviceJids = extractDeviceJids;
124
- /**
125
- * get the next N keys for upload or processing
126
- * @param count number of pre-keys to get or generate
127
- */
128
- const getNextPreKeys = async ({ creds, keys }, count) => {
129
- const { newPreKeys, lastPreKeyId, preKeysRange } = (0, exports.generateOrGetPreKeys)(creds, count);
130
- const update = {
131
- nextPreKeyId: Math.max(lastPreKeyId + 1, creds.nextPreKeyId),
132
- firstUnuploadedPreKeyId: Math.max(creds.firstUnuploadedPreKeyId, lastPreKeyId + 1)
133
- };
134
- await keys.set({ 'pre-key': newPreKeys });
135
- const preKeys = await (0, exports.getPreKeys)(keys, preKeysRange[0], preKeysRange[0] + preKeysRange[1]);
136
- return { update, preKeys };
137
- };
138
- exports.getNextPreKeys = getNextPreKeys;
139
- const getNextPreKeysNode = async (state, count) => {
140
- const { creds } = state;
141
- const { update, preKeys } = await (0, exports.getNextPreKeys)(state, count);
142
- const node = {
143
- tag: 'iq',
144
- attrs: {
145
- xmlns: 'encrypt',
146
- type: 'set',
147
- to: WABinary_1.S_WHATSAPP_NET,
148
- },
149
- content: [
150
- { tag: 'registration', attrs: {}, content: (0, generics_1.encodeBigEndian)(creds.registrationId) },
151
- { tag: 'type', attrs: {}, content: Defaults_1.KEY_BUNDLE_TYPE },
152
- { tag: 'identity', attrs: {}, content: creds.signedIdentityKey.public },
153
- { tag: 'list', attrs: {}, content: Object.keys(preKeys).map(k => (0, exports.xmppPreKey)(preKeys[+k], +k)) },
154
- (0, exports.xmppSignedPreKey)(creds.signedPreKey)
155
- ]
156
- };
157
- return { update, node };
158
- };
159
- exports.getNextPreKeysNode = getNextPreKeysNode;
@@ -1,12 +0,0 @@
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
- }>;
@@ -1,167 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.useMultiFileAuthState = void 0;
7
- const async_lock_1 = __importDefault(require("async-lock"));
8
- const promises_1 = require("fs/promises");
9
- const path_1 = require("path");
10
- const WAProto_1 = require("../../WAProto");
11
- const auth_utils_1 = require("./auth-utils");
12
- const generics_1 = require("./generics");
13
- // We need to lock files due to the fact that we are using async functions to read and write files
14
- // https://github.com/WhiskeySockets/Baileys/issues/794
15
- // https://github.com/nodejs/node/issues/26338
16
- // Default pending is 1000, set it to infinity
17
- // https://github.com/rogierschouten/async-lock/issues/63
18
- const fileLock = new async_lock_1.default({ maxPending: Infinity });
19
-
20
- // Helper function to log debug information if authDebug is enabled
21
- const logDebug = (message, options) => {
22
- if (options && typeof options === 'object' && options.authDebug === true) {
23
- console.log(`[AUTH_DEBUG] ${message}`);
24
- }
25
- };
26
-
27
- /**
28
- * stores the full authentication state in a single folder.
29
- * Far more efficient than singlefileauthstate
30
- *
31
- * Again, I wouldn't endorse this for any production level use other than perhaps a bot.
32
- * Would recommend writing an auth state for use with a proper SQL or No-SQL DB
33
- * */
34
- const useMultiFileAuthState = async (folder, options) => {
35
- logDebug(`Initializing auth state in folder: ${folder}`, options);
36
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
37
- const writeData = (data, file) => {
38
- const filePath = (0, path_1.join)(folder, fixFileName(file));
39
- logDebug(`Writing data to file: ${filePath}`, options);
40
- return fileLock.acquire(filePath, () => {
41
- logDebug(`Lock acquired for writing: ${filePath}`, options);
42
- return (0, promises_1.writeFile)((0, path_1.join)(filePath), JSON.stringify(data, generics_1.BufferJSON.replacer))
43
- .then(() => {
44
- logDebug(`Successfully wrote data to: ${filePath}`, options);
45
- })
46
- .catch((error) => {
47
- logDebug(`Error writing to file ${filePath}: ${error.message}`, options);
48
- throw error;
49
- });
50
- });
51
- };
52
-
53
- const readData = async (file) => {
54
- try {
55
- const filePath = (0, path_1.join)(folder, fixFileName(file));
56
- logDebug(`Attempting to read data from: ${filePath}`, options);
57
- const data = await fileLock.acquire(filePath, () => {
58
- logDebug(`Lock acquired for reading: ${filePath}`, options);
59
- return (0, promises_1.readFile)(filePath, { encoding: 'utf-8' });
60
- });
61
- logDebug(`Successfully read data from: ${filePath}`, options);
62
- return JSON.parse(data, generics_1.BufferJSON.reviver);
63
- }
64
- catch (error) {
65
- logDebug(`Could not read file ${file}: ${error.message}`, options);
66
- return null;
67
- }
68
- };
69
-
70
- const removeData = async (file) => {
71
- try {
72
- const filePath = (0, path_1.join)(folder, fixFileName(file));
73
- logDebug(`Attempting to remove file: ${filePath}`, options);
74
- await fileLock.acquire(filePath, () => {
75
- logDebug(`Lock acquired for removal: ${filePath}`, options);
76
- return (0, promises_1.unlink)(filePath);
77
- });
78
- logDebug(`Successfully removed file: ${filePath}`, options);
79
- }
80
- catch (error) {
81
- logDebug(`Error removing file ${file}: ${error.message}`, options);
82
- }
83
- };
84
-
85
- const folderInfo = await (0, promises_1.stat)(folder).catch(() => {
86
- logDebug(`Folder ${folder} does not exist yet`, options);
87
- });
88
-
89
- if (folderInfo) {
90
- if (!folderInfo.isDirectory()) {
91
- logDebug(`Error: ${folder} is not a directory`, options);
92
- throw new Error(`found something that is not a directory at ${folder}, either delete it or specify a different location`);
93
- }
94
- logDebug(`Using existing folder: ${folder}`, options);
95
- }
96
- else {
97
- logDebug(`Creating folder: ${folder}`, options);
98
- await (0, promises_1.mkdir)(folder, { recursive: true });
99
- logDebug(`Successfully created folder: ${folder}`, options);
100
- }
101
-
102
- const fixFileName = (file) => {
103
- var _a;
104
- const fixedName = (_a = file === null || file === void 0 ? void 0 : file.replace(/\//g, '__')) === null || _a === void 0 ? void 0 : _a.replace(/:/g, '-');
105
- logDebug(`Original filename: ${file}, Fixed filename: ${fixedName}`, options);
106
- return fixedName;
107
- };
108
-
109
- logDebug(`Reading credentials file`, options);
110
- const creds = await readData('creds.json') || (0, auth_utils_1.initAuthCreds)();
111
- if (!creds) {
112
- logDebug(`No existing credentials found, initialized new auth credentials`, options);
113
- } else {
114
- logDebug(`Successfully loaded credentials`, options);
115
- }
116
-
117
- return {
118
- state: {
119
- creds,
120
- keys: {
121
- get: async (type, ids) => {
122
- logDebug(`Getting keys of type: ${type}, ids: ${JSON.stringify(ids)}`, options);
123
- const data = {};
124
- await Promise.all(ids.map(async (id) => {
125
- logDebug(`Fetching key: ${type}-${id}`, options);
126
- let value = await readData(`${type}-${id}.json`);
127
- if (type === 'app-state-sync-key' && value) {
128
- logDebug(`Converting app-state-sync-key to protobuf for id: ${id}`, options);
129
- value = WAProto_1.proto.Message.AppStateSyncKeyData.fromObject(value);
130
- }
131
- data[id] = value;
132
- logDebug(`Key ${id} ${value ? 'found' : 'not found'}`, options);
133
- }));
134
- return data;
135
- },
136
- set: async (data) => {
137
- logDebug(`Setting keys: ${JSON.stringify(Object.keys(data))}`, options);
138
- const tasks = [];
139
- for (const category in data) {
140
- logDebug(`Processing category: ${category}`, options);
141
- for (const id in data[category]) {
142
- const value = data[category][id];
143
- const file = `${category}-${id}.json`;
144
- logDebug(`${value ? 'Setting' : 'Removing'} key: ${file}`, options);
145
- tasks.push(value ? writeData(value, file) : removeData(file));
146
- }
147
- }
148
- await Promise.all(tasks);
149
- logDebug(`Successfully completed setting all keys`, options);
150
- }
151
- }
152
- },
153
- saveCreds: () => {
154
- logDebug(`Saving credentials to creds.json`, options);
155
- return writeData(creds, 'creds.json')
156
- .then(() => {
157
- logDebug(`Successfully saved credentials`, options);
158
- })
159
- .catch((error) => {
160
- logDebug(`Error saving credentials: ${error.message}`, options);
161
- throw error;
162
- });
163
- },
164
- cache: null
165
- };
166
- };
167
- exports.useMultiFileAuthState = useMultiFileAuthState;
@@ -1,12 +0,0 @@
1
- import type { Logger } from 'pino';
2
- import type { AuthenticationState } from '../Types';
3
- /**
4
- * @deprecated use multi file auth state instead please
5
- * stores the full authentication state in a single JSON file
6
- *
7
- * DO NOT USE IN A PROD ENVIRONMENT, only meant to serve as an example
8
- * */
9
- export declare const useSingleFileAuthState: (filename: string, logger?: Logger) => {
10
- state: AuthenticationState;
11
- saveState: () => void;
12
- };
@@ -1,76 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.useSingleFileAuthState = void 0;
4
- const WAProto_1 = require("../../WAProto");
5
- const auth_utils_1 = require("./auth-utils");
6
- const generics_1 = require("./generics");
7
- // useless key map only there to maintain backwards compatibility
8
- // do not use in your own systems please
9
- const KEY_MAP = {
10
- 'pre-key': 'preKeys',
11
- 'session': 'sessions',
12
- 'sender-key': 'senderKeys',
13
- 'app-state-sync-key': 'appStateSyncKeys',
14
- 'app-state-sync-version': 'appStateVersions',
15
- 'sender-key-memory': 'senderKeyMemory'
16
- };
17
- /**
18
- * @deprecated use multi file auth state instead please
19
- * stores the full authentication state in a single JSON file
20
- *
21
- * DO NOT USE IN A PROD ENVIRONMENT, only meant to serve as an example
22
- * */
23
- const useSingleFileAuthState = (filename, logger) => {
24
- // require fs here so that in case "fs" is not available -- the app does not crash
25
- const { readFileSync, writeFileSync, existsSync } = require('fs');
26
- let creds;
27
- let keys = {};
28
- // save the authentication state to a file
29
- const saveState = () => {
30
- logger && logger.trace('saving auth state');
31
- writeFileSync(filename,
32
- // BufferJSON replacer utility saves buffers nicely
33
- JSON.stringify({ creds, keys }, generics_1.BufferJSON.replacer, 2));
34
- };
35
- if (existsSync(filename)) {
36
- const result = JSON.parse(readFileSync(filename, { encoding: 'utf-8' }), generics_1.BufferJSON.reviver);
37
- creds = result.creds;
38
- keys = result.keys;
39
- }
40
- else {
41
- creds = (0, auth_utils_1.initAuthCreds)();
42
- keys = {};
43
- }
44
- return {
45
- state: {
46
- creds,
47
- keys: {
48
- get: (type, ids) => {
49
- const key = KEY_MAP[type];
50
- return ids.reduce((dict, id) => {
51
- var _a;
52
- let value = (_a = keys[key]) === null || _a === void 0 ? void 0 : _a[id];
53
- if (value) {
54
- if (type === 'app-state-sync-key') {
55
- value = WAProto_1.proto.Message.AppStateSyncKeyData.fromObject(value);
56
- }
57
- dict[id] = value;
58
- }
59
- return dict;
60
- }, {});
61
- },
62
- set: (data) => {
63
- for (const _key in data) {
64
- const key = KEY_MAP[_key];
65
- keys[key] = keys[key] || {};
66
- Object.assign(keys[key], data[_key]);
67
- }
68
- saveState();
69
- }
70
- }
71
- },
72
- saveState,
73
- cache: null
74
- };
75
- };
76
- exports.useSingleFileAuthState = useSingleFileAuthState;
@@ -1,11 +0,0 @@
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;
@@ -1,205 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.encodeSignedDeviceIdentity = exports.configureSuccessfulPairing = exports.generateRegistrationNode = exports.generateLoginNode = exports.generateMobileNode = void 0;
4
- const boom_1 = require("@hapi/boom");
5
- const crypto_1 = require("crypto");
6
- const WAProto_1 = require("../../WAProto");
7
- const Defaults_1 = require("../Defaults");
8
- const WABinary_1 = require("../WABinary");
9
- const crypto_2 = require("./crypto");
10
- const generics_1 = require("./generics");
11
- const signal_1 = require("./signal");
12
- const getUserAgent = (config) => {
13
- var _a, _b;
14
- const osVersion = config.mobile ? '15.3.1' : '0.1';
15
- const version = config.mobile ? [2, 24, 6] : config.version;
16
- const device = config.mobile ? 'iPhone_7' : 'Desktop';
17
- const manufacturer = config.mobile ? 'Apple' : '';
18
- const platform = config.mobile ? WAProto_1.proto.ClientPayload.UserAgent.Platform.IOS : WAProto_1.proto.ClientPayload.UserAgent.Platform.WEB;
19
- const phoneId = config.mobile ? { phoneId: config.auth.creds.phoneId } : {};
20
- return {
21
- appVersion: {
22
- primary: version[0],
23
- secondary: version[1],
24
- 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
- };
38
- };
39
- const PLATFORM_MAP = {
40
- 'Mac OS': WAProto_1.proto.ClientPayload.WebInfo.WebSubPlatform.DARWIN,
41
- 'Windows': WAProto_1.proto.ClientPayload.WebInfo.WebSubPlatform.WIN32
42
- };
43
- const getWebInfo = (config) => {
44
- let webSubPlatform = WAProto_1.proto.ClientPayload.WebInfo.WebSubPlatform.WEB_BROWSER;
45
- if (config.syncFullHistory && PLATFORM_MAP[config.browser[0]]) {
46
- webSubPlatform = PLATFORM_MAP[config.browser[0]];
47
- }
48
- return { webSubPlatform };
49
- };
50
- const getClientPayload = (config) => {
51
- const payload = {
52
- connectType: WAProto_1.proto.ClientPayload.ConnectType.WIFI_UNKNOWN,
53
- connectReason: WAProto_1.proto.ClientPayload.ConnectReason.USER_ACTIVATED,
54
- userAgent: getUserAgent(config),
55
- };
56
- if (!config.mobile) {
57
- payload.webInfo = getWebInfo(config);
58
- }
59
- return payload;
60
- };
61
- const generateMobileNode = (config) => {
62
- if (!config.auth.creds) {
63
- throw new boom_1.Boom('No registration data found', { data: config });
64
- }
65
- const payload = {
66
- ...getClientPayload(config),
67
- sessionId: Math.floor(Math.random() * 999999999 + 1),
68
- shortConnect: true,
69
- connectAttemptCount: 0,
70
- device: 0,
71
- dnsSource: {
72
- appCached: false,
73
- dnsMethod: WAProto_1.proto.ClientPayload.DNSSource.DNSResolutionMethod.SYSTEM,
74
- },
75
- passive: false,
76
- pushName: 'test',
77
- username: Number(`${config.auth.creds.registration.phoneNumberCountryCode}${config.auth.creds.registration.phoneNumberNationalNumber}`),
78
- };
79
- return WAProto_1.proto.ClientPayload.fromObject(payload);
80
- };
81
- exports.generateMobileNode = generateMobileNode;
82
- const generateLoginNode = (userJid, config) => {
83
- const { user, device } = (0, WABinary_1.jidDecode)(userJid);
84
- const payload = {
85
- ...getClientPayload(config),
86
- passive: true,
87
- username: +user,
88
- device: device,
89
- };
90
- return WAProto_1.proto.ClientPayload.fromObject(payload);
91
- };
92
- exports.generateLoginNode = generateLoginNode;
93
- const getPlatformType = (platform) => {
94
- const platformType = platform.toUpperCase();
95
- return WAProto_1.proto.DeviceProps.PlatformType[platformType] || WAProto_1.proto.DeviceProps.PlatformType.DESKTOP;
96
- };
97
- const generateRegistrationNode = ({ registrationId, signedPreKey, signedIdentityKey }, config) => {
98
- // the app version needs to be md5 hashed
99
- // and passed in
100
- const appVersionBuf = (0, crypto_1.createHash)('md5')
101
- .update(config.version.join('.')) // join as string
102
- .digest();
103
- const companion = {
104
- os: config.browser[0],
105
- platformType: getPlatformType(config.browser[1]),
106
- requireFullSync: config.syncFullHistory,
107
- };
108
- const companionProto = WAProto_1.proto.DeviceProps.encode(companion).finish();
109
- const registerPayload = {
110
- ...getClientPayload(config),
111
- passive: false,
112
- devicePairingData: {
113
- buildHash: appVersionBuf,
114
- deviceProps: companionProto,
115
- eRegid: (0, generics_1.encodeBigEndian)(registrationId),
116
- eKeytype: Defaults_1.KEY_BUNDLE_TYPE,
117
- eIdent: signedIdentityKey.public,
118
- eSkeyId: (0, generics_1.encodeBigEndian)(signedPreKey.keyId, 3),
119
- eSkeyVal: signedPreKey.keyPair.public,
120
- eSkeySig: signedPreKey.signature,
121
- },
122
- };
123
- return WAProto_1.proto.ClientPayload.fromObject(registerPayload);
124
- };
125
- exports.generateRegistrationNode = generateRegistrationNode;
126
- const configureSuccessfulPairing = (stanza, { advSecretKey, signedIdentityKey, signalIdentities }) => {
127
- const msgId = stanza.attrs.id;
128
- const pairSuccessNode = (0, WABinary_1.getBinaryNodeChild)(stanza, 'pair-success');
129
- const deviceIdentityNode = (0, WABinary_1.getBinaryNodeChild)(pairSuccessNode, 'device-identity');
130
- const platformNode = (0, WABinary_1.getBinaryNodeChild)(pairSuccessNode, 'platform');
131
- const deviceNode = (0, WABinary_1.getBinaryNodeChild)(pairSuccessNode, 'device');
132
- const businessNode = (0, WABinary_1.getBinaryNodeChild)(pairSuccessNode, 'biz');
133
- if (!deviceIdentityNode || !deviceNode) {
134
- throw new boom_1.Boom('Missing device-identity or device in pair success node', { data: stanza });
135
- }
136
- const bizName = businessNode === null || businessNode === void 0 ? void 0 : businessNode.attrs.name;
137
- const jid = deviceNode.attrs.jid;
138
- const { details, hmac } = WAProto_1.proto.ADVSignedDeviceIdentityHMAC.decode(deviceIdentityNode.content);
139
- // check HMAC matches
140
- const advSign = (0, crypto_2.hmacSign)(details, Buffer.from(advSecretKey, 'base64'));
141
- if (Buffer.compare(hmac, advSign) !== 0) {
142
- throw new boom_1.Boom('Invalid account signature');
143
- }
144
- const account = WAProto_1.proto.ADVSignedDeviceIdentity.decode(details);
145
- const { accountSignatureKey, accountSignature, details: deviceDetails } = account;
146
- // verify the device signature matches
147
- const accountMsg = Buffer.concat([Buffer.from([6, 0]), deviceDetails, signedIdentityKey.public]);
148
- if (!crypto_2.Curve.verify(accountSignatureKey, accountMsg, accountSignature)) {
149
- throw new boom_1.Boom('Failed to verify account signature');
150
- }
151
- // sign the details with our identity key
152
- const deviceMsg = Buffer.concat([Buffer.from([6, 1]), deviceDetails, signedIdentityKey.public, accountSignatureKey]);
153
- account.deviceSignature = crypto_2.Curve.sign(signedIdentityKey.private, deviceMsg);
154
- const identity = (0, signal_1.createSignalIdentity)(jid, accountSignatureKey);
155
- const accountEnc = (0, exports.encodeSignedDeviceIdentity)(account, false);
156
- const deviceIdentity = WAProto_1.proto.ADVDeviceIdentity.decode(account.details);
157
- const reply = {
158
- tag: 'iq',
159
- attrs: {
160
- to: WABinary_1.S_WHATSAPP_NET,
161
- type: 'result',
162
- id: msgId,
163
- },
164
- content: [
165
- {
166
- tag: 'pair-device-sign',
167
- attrs: {},
168
- content: [
169
- {
170
- tag: 'device-identity',
171
- attrs: { 'key-index': deviceIdentity.keyIndex.toString() },
172
- content: accountEnc
173
- }
174
- ]
175
- }
176
- ]
177
- };
178
- const authUpdate = {
179
- account,
180
- me: { id: jid, name: bizName },
181
- signalIdentities: [
182
- ...(signalIdentities || []),
183
- identity
184
- ],
185
- platform: platformNode === null || platformNode === void 0 ? void 0 : platformNode.attrs.name
186
- };
187
- return {
188
- creds: authUpdate,
189
- reply
190
- };
191
- };
192
- exports.configureSuccessfulPairing = configureSuccessfulPairing;
193
- const encodeSignedDeviceIdentity = (account, includeSignatureKey) => {
194
- var _a;
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 || !((_a = account.accountSignatureKey) === null || _a === void 0 ? void 0 : _a.length)) {
199
- account.accountSignatureKey = null;
200
- }
201
- return WAProto_1.proto.ADVSignedDeviceIdentity
202
- .encode(account)
203
- .finish();
204
- };
205
- exports.encodeSignedDeviceIdentity = encodeSignedDeviceIdentity;
@@ -1,27 +0,0 @@
1
- export declare const TAGS: {
2
- LIST_EMPTY: number;
3
- DICTIONARY_0: number;
4
- DICTIONARY_1: number;
5
- DICTIONARY_2: number;
6
- DICTIONARY_3: number;
7
- AD_JID: number;
8
- LIST_8: number;
9
- LIST_16: number;
10
- JID_PAIR: number;
11
- HEX_8: number;
12
- BINARY_8: number;
13
- BINARY_20: number;
14
- BINARY_32: number;
15
- NIBBLE_8: number;
16
- PACKED_MAX: number;
17
- SINGLE_BYTE_MAX: number;
18
- STREAM_END: number;
19
- };
20
- export declare const DOUBLE_BYTE_TOKENS: string[][];
21
- export declare const SINGLE_BYTE_TOKENS: (string | null)[];
22
- export declare const TOKEN_MAP: {
23
- [token: string]: {
24
- dict?: number;
25
- index: number;
26
- };
27
- };