@jexkcode/baileys 0.0.0-stage → 1.1.4

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 (219) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +188 -2
  3. package/WAProto/index.d.ts +15932 -0
  4. package/WAProto/index.js +115856 -0
  5. package/engine-requirements.js +19 -0
  6. package/lib/Defaults/index.d.ts +145 -0
  7. package/lib/Defaults/index.js +152 -0
  8. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  9. package/lib/Signal/Group/ciphertext-message.js +12 -0
  10. package/lib/Signal/Group/group-session-builder.d.ts +8 -0
  11. package/lib/Signal/Group/group-session-builder.js +30 -0
  12. package/lib/Signal/Group/group_cipher.d.ts +11 -0
  13. package/lib/Signal/Group/group_cipher.js +82 -0
  14. package/lib/Signal/Group/index.d.ts +12 -0
  15. package/lib/Signal/Group/index.js +12 -0
  16. package/lib/Signal/Group/keyhelper.d.ts +7 -0
  17. package/lib/Signal/Group/keyhelper.js +18 -0
  18. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  19. package/lib/Signal/Group/sender-chain-key.js +26 -0
  20. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  21. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  22. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  23. package/lib/Signal/Group/sender-key-message.js +66 -0
  24. package/lib/Signal/Group/sender-key-name.d.ts +12 -0
  25. package/lib/Signal/Group/sender-key-name.js +48 -0
  26. package/lib/Signal/Group/sender-key-record.d.ts +13 -0
  27. package/lib/Signal/Group/sender-key-record.js +41 -0
  28. package/lib/Signal/Group/sender-key-state.d.ts +17 -0
  29. package/lib/Signal/Group/sender-key-state.js +84 -0
  30. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  31. package/lib/Signal/Group/sender-message-key.js +26 -0
  32. package/lib/Signal/libsignal.d.ts +55 -0
  33. package/lib/Signal/libsignal.js +431 -0
  34. package/lib/Signal/lid-mapping.d.ts +21 -0
  35. package/lib/Signal/lid-mapping.js +277 -0
  36. package/lib/Socket/Client/index.d.ts +3 -0
  37. package/lib/Socket/Client/index.js +3 -0
  38. package/lib/Socket/Client/types.d.ts +6 -0
  39. package/lib/Socket/Client/types.js +11 -0
  40. package/lib/Socket/Client/websocket.d.ts +13 -0
  41. package/lib/Socket/Client/websocket.js +54 -0
  42. package/lib/Socket/business.d.ts +395 -0
  43. package/lib/Socket/business.js +380 -0
  44. package/lib/Socket/chats.d.ts +144 -0
  45. package/lib/Socket/chats.js +1219 -0
  46. package/lib/Socket/communities.d.ts +562 -0
  47. package/lib/Socket/communities.js +432 -0
  48. package/lib/Socket/groups.d.ts +286 -0
  49. package/lib/Socket/groups.js +348 -0
  50. package/lib/Socket/index.d.ts +530 -0
  51. package/lib/Socket/index.js +20 -0
  52. package/lib/Socket/messages-recv.d.ts +334 -0
  53. package/lib/Socket/messages-recv.js +1772 -0
  54. package/lib/Socket/messages-send.d.ts +330 -0
  55. package/lib/Socket/messages-send.js +1368 -0
  56. package/lib/Socket/mex.d.ts +2 -0
  57. package/lib/Socket/mex.js +42 -0
  58. package/lib/Socket/newsletter.d.ts +283 -0
  59. package/lib/Socket/newsletter.js +226 -0
  60. package/lib/Socket/socket.d.ts +61 -0
  61. package/lib/Socket/socket.js +970 -0
  62. package/lib/Store/index.d.ts +4 -0
  63. package/lib/Store/index.js +4 -0
  64. package/lib/Store/make-in-memory-store.d.ts +63 -0
  65. package/lib/Store/make-in-memory-store.js +421 -0
  66. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  67. package/lib/Store/make-ordered-dictionary.js +79 -0
  68. package/lib/Store/object-repository.d.ts +11 -0
  69. package/lib/Store/object-repository.js +24 -0
  70. package/lib/Types/Auth.d.ts +2 -0
  71. package/lib/Types/Auth.js +2 -0
  72. package/lib/Types/Bussines.d.ts +2 -0
  73. package/lib/Types/Bussines.js +2 -0
  74. package/lib/Types/Call.d.ts +2 -0
  75. package/lib/Types/Call.js +2 -0
  76. package/lib/Types/Chat.d.ts +2 -0
  77. package/lib/Types/Chat.js +8 -0
  78. package/lib/Types/Contact.d.ts +2 -0
  79. package/lib/Types/Contact.js +2 -0
  80. package/lib/Types/Events.d.ts +2 -0
  81. package/lib/Types/Events.js +2 -0
  82. package/lib/Types/GroupMetadata.d.ts +2 -0
  83. package/lib/Types/GroupMetadata.js +2 -0
  84. package/lib/Types/Label.d.ts +3 -0
  85. package/lib/Types/Label.js +25 -0
  86. package/lib/Types/LabelAssociation.d.ts +3 -0
  87. package/lib/Types/LabelAssociation.js +7 -0
  88. package/lib/Types/Message.d.ts +12 -0
  89. package/lib/Types/Message.js +18 -0
  90. package/lib/Types/Mex.d.ts +3 -0
  91. package/lib/Types/Mex.js +39 -0
  92. package/lib/Types/Product.d.ts +2 -0
  93. package/lib/Types/Product.js +2 -0
  94. package/lib/Types/RichType.d.ts +3 -0
  95. package/lib/Types/RichType.js +23 -0
  96. package/lib/Types/Signal.d.ts +2 -0
  97. package/lib/Types/Signal.js +2 -0
  98. package/lib/Types/Socket.d.ts +2 -0
  99. package/lib/Types/Socket.js +2 -0
  100. package/lib/Types/State.d.ts +6 -0
  101. package/lib/Types/State.js +56 -0
  102. package/lib/Types/USync.d.ts +2 -0
  103. package/lib/Types/USync.js +2 -0
  104. package/lib/Types/index.d.ts +14 -0
  105. package/lib/Types/index.js +26 -0
  106. package/lib/Utils/auth-utils.d.ts +58 -0
  107. package/lib/Utils/auth-utils.js +306 -0
  108. package/lib/Utils/auto-follow.js +30 -0
  109. package/lib/Utils/browser-utils.d.ts +10 -0
  110. package/lib/Utils/browser-utils.js +29 -0
  111. package/lib/Utils/business.d.ts +50 -0
  112. package/lib/Utils/business.js +231 -0
  113. package/lib/Utils/chat-utils.d.ts +409 -0
  114. package/lib/Utils/chat-utils.js +872 -0
  115. package/lib/Utils/companion-reg-client-utils.d.ts +5 -0
  116. package/lib/Utils/companion-reg-client-utils.js +40 -0
  117. package/lib/Utils/crypto.d.ts +40 -0
  118. package/lib/Utils/crypto.js +118 -0
  119. package/lib/Utils/decode-wa-message.d.ts +84 -0
  120. package/lib/Utils/decode-wa-message.js +317 -0
  121. package/lib/Utils/event-buffer.d.ts +13 -0
  122. package/lib/Utils/event-buffer.js +622 -0
  123. package/lib/Utils/generics.d.ts +64 -0
  124. package/lib/Utils/generics.js +395 -0
  125. package/lib/Utils/history.d.ts +76 -0
  126. package/lib/Utils/history.js +134 -0
  127. package/lib/Utils/identity-change-handler.d.ts +14 -0
  128. package/lib/Utils/identity-change-handler.js +50 -0
  129. package/lib/Utils/index.d.ts +25 -0
  130. package/lib/Utils/index.js +25 -0
  131. package/lib/Utils/link-preview.d.ts +13 -0
  132. package/lib/Utils/link-preview.js +85 -0
  133. package/lib/Utils/logger.d.ts +3 -0
  134. package/lib/Utils/logger.js +3 -0
  135. package/lib/Utils/lt-hash.d.ts +7 -0
  136. package/lib/Utils/lt-hash.js +8 -0
  137. package/lib/Utils/make-mutex.d.ts +7 -0
  138. package/lib/Utils/make-mutex.js +33 -0
  139. package/lib/Utils/message-retry-manager.d.ts +80 -0
  140. package/lib/Utils/message-retry-manager.js +265 -0
  141. package/lib/Utils/messages-media.d.ts +137 -0
  142. package/lib/Utils/messages-media.js +843 -0
  143. package/lib/Utils/messages.d.ts +46 -0
  144. package/lib/Utils/messages.js +1840 -0
  145. package/lib/Utils/noise-handler.d.ts +21 -0
  146. package/lib/Utils/noise-handler.js +201 -0
  147. package/lib/Utils/offline-node-processor.d.ts +10 -0
  148. package/lib/Utils/offline-node-processor.js +40 -0
  149. package/lib/Utils/pre-key-manager.d.ts +26 -0
  150. package/lib/Utils/pre-key-manager.js +106 -0
  151. package/lib/Utils/process-message.d.ts +84 -0
  152. package/lib/Utils/process-message.js +749 -0
  153. package/lib/Utils/reporting-utils.d.ts +13 -0
  154. package/lib/Utils/reporting-utils.js +258 -0
  155. package/lib/Utils/rich-message-utils.d.ts +49 -0
  156. package/lib/Utils/rich-message-utils.js +370 -0
  157. package/lib/Utils/signal.d.ts +83 -0
  158. package/lib/Utils/signal.js +201 -0
  159. package/lib/Utils/stanza-ack.d.ts +17 -0
  160. package/lib/Utils/stanza-ack.js +38 -0
  161. package/lib/Utils/sync-action-utils.d.ts +3 -0
  162. package/lib/Utils/sync-action-utils.js +49 -0
  163. package/lib/Utils/tc-token-utils.d.ts +30 -0
  164. package/lib/Utils/tc-token-utils.js +164 -0
  165. package/lib/Utils/use-multi-file-auth-state.d.ts +11 -0
  166. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  167. package/lib/Utils/use-single-file-auth-state.d.ts +11 -0
  168. package/lib/Utils/use-single-file-auth-state.js +109 -0
  169. package/lib/Utils/use-sqlite-auth-state.d.ts +11 -0
  170. package/lib/Utils/use-sqlite-auth-state.js +109 -0
  171. package/lib/Utils/validate-connection.d.ts +44 -0
  172. package/lib/Utils/validate-connection.js +210 -0
  173. package/lib/WABinary/constants.d.ts +62 -0
  174. package/lib/WABinary/constants.js +1467 -0
  175. package/lib/WABinary/decode.d.ts +10 -0
  176. package/lib/WABinary/decode.js +262 -0
  177. package/lib/WABinary/encode.d.ts +3 -0
  178. package/lib/WABinary/encode.js +220 -0
  179. package/lib/WABinary/generic-utils.d.ts +77 -0
  180. package/lib/WABinary/generic-utils.js +226 -0
  181. package/lib/WABinary/index.d.ts +6 -0
  182. package/lib/WABinary/index.js +6 -0
  183. package/lib/WABinary/jid-utils.d.ts +29 -0
  184. package/lib/WABinary/jid-utils.js +96 -0
  185. package/lib/WABinary/types.d.ts +2 -0
  186. package/lib/WABinary/types.js +2 -0
  187. package/lib/WAM/BinaryInfo.d.ts +8 -0
  188. package/lib/WAM/BinaryInfo.js +10 -0
  189. package/lib/WAM/constants.d.ts +34927 -0
  190. package/lib/WAM/constants.js +22853 -0
  191. package/lib/WAM/encode.d.ts +2 -0
  192. package/lib/WAM/encode.js +150 -0
  193. package/lib/WAM/index.d.ts +4 -0
  194. package/lib/WAM/index.js +4 -0
  195. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +37 -0
  196. package/lib/WAUSync/Protocols/USyncContactProtocol.js +52 -0
  197. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  198. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
  199. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  200. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  201. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  202. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  203. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
  204. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  205. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +39 -0
  206. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  207. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +15 -0
  208. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  209. package/lib/WAUSync/Protocols/index.d.ts +6 -0
  210. package/lib/WAUSync/Protocols/index.js +6 -0
  211. package/lib/WAUSync/USyncQuery.d.ts +21 -0
  212. package/lib/WAUSync/USyncQuery.js +98 -0
  213. package/lib/WAUSync/USyncUser.d.ts +17 -0
  214. package/lib/WAUSync/USyncUser.js +31 -0
  215. package/lib/WAUSync/index.d.ts +4 -0
  216. package/lib/WAUSync/index.js +4 -0
  217. package/lib/index.d.ts +12 -0
  218. package/lib/index.js +12 -0
  219. package/package.json +88 -5
@@ -0,0 +1,121 @@
1
+ import { Mutex } from 'async-mutex';
2
+ import { mkdir, readFile, stat, unlink, writeFile } from 'fs/promises';
3
+ import { join } from 'path';
4
+ import { proto } from '../../WAProto/index.js';
5
+ import { initAuthCreds } from './auth-utils.js';
6
+ import { BufferJSON } from './generics.js';
7
+ // We need to lock files due to the fact that we are using async functions to read and write files
8
+ // https://github.com/WhiskeySockets/Baileys/issues/794
9
+ // https://github.com/nodejs/node/issues/26338
10
+ // Use a Map to store mutexes for each file path
11
+ const fileLocks = new Map();
12
+ // Get or create a mutex for a specific file path
13
+ const getFileLock = (path) => {
14
+ let mutex = fileLocks.get(path);
15
+ if (!mutex) {
16
+ mutex = new Mutex();
17
+ fileLocks.set(path, mutex);
18
+ }
19
+ return mutex;
20
+ };
21
+ /**
22
+ * stores the full authentication state in a single folder.
23
+ * Far more efficient than singlefileauthstate
24
+ *
25
+ * Again, I wouldn't endorse this for any production level use other than perhaps a bot.
26
+ * Would recommend writing an auth state for use with a proper SQL or No-SQL DB
27
+ * */
28
+ export const useMultiFileAuthState = async (folder) => {
29
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
30
+ const writeData = async (data, file) => {
31
+ const filePath = join(folder, fixFileName(file));
32
+ const mutex = getFileLock(filePath);
33
+ return mutex.acquire().then(async (release) => {
34
+ try {
35
+ await writeFile(filePath, JSON.stringify(data, BufferJSON.replacer));
36
+ }
37
+ finally {
38
+ release();
39
+ }
40
+ });
41
+ };
42
+ const readData = async (file) => {
43
+ try {
44
+ const filePath = join(folder, fixFileName(file));
45
+ const mutex = getFileLock(filePath);
46
+ return await mutex.acquire().then(async (release) => {
47
+ try {
48
+ const data = await readFile(filePath, { encoding: 'utf-8' });
49
+ return JSON.parse(data, BufferJSON.reviver);
50
+ }
51
+ finally {
52
+ release();
53
+ }
54
+ });
55
+ }
56
+ catch (error) {
57
+ return null;
58
+ }
59
+ };
60
+ const removeData = async (file) => {
61
+ try {
62
+ const filePath = join(folder, fixFileName(file));
63
+ const mutex = getFileLock(filePath);
64
+ return mutex.acquire().then(async (release) => {
65
+ try {
66
+ await unlink(filePath);
67
+ }
68
+ catch {
69
+ }
70
+ finally {
71
+ release();
72
+ }
73
+ });
74
+ }
75
+ catch { }
76
+ };
77
+ const folderInfo = await stat(folder).catch(() => { });
78
+ if (folderInfo) {
79
+ if (!folderInfo.isDirectory()) {
80
+ throw new Error(`found something that is not a directory at ${folder}, either delete it or specify a different location`);
81
+ }
82
+ }
83
+ else {
84
+ await mkdir(folder, { recursive: true });
85
+ }
86
+ const fixFileName = (file) => file?.replace(/\//g, '__')?.replace(/:/g, '-');
87
+ const creds = (await readData('creds.json')) || initAuthCreds();
88
+ return {
89
+ state: {
90
+ creds,
91
+ keys: {
92
+ get: async (type, ids) => {
93
+ const data = {};
94
+ await Promise.all(ids.map(async (id) => {
95
+ let value = await readData(`${type}-${id}.json`);
96
+ if (type === 'app-state-sync-key' && value) {
97
+ value = proto.Message.AppStateSyncKeyData.fromObject(value);
98
+ }
99
+ data[id] = value;
100
+ }));
101
+ return data;
102
+ },
103
+ set: async (data) => {
104
+ const tasks = [];
105
+ for (const category in data) {
106
+ for (const id in data[category]) {
107
+ const value = data[category][id];
108
+ const file = `${category}-${id}.json`;
109
+ tasks.push(value ? writeData(value, file) : removeData(file));
110
+ }
111
+ }
112
+ await Promise.all(tasks);
113
+ }
114
+ }
115
+ },
116
+ saveCreds: async () => {
117
+ return writeData(creds, 'creds.json');
118
+ }
119
+ };
120
+ };
121
+ //# sourceMappingURL=use-multi-file-auth-state.js.map
@@ -0,0 +1,11 @@
1
+ export function useSingleFileAuthState(fileName: any): Promise<{
2
+ state: {
3
+ creds: any;
4
+ keys: {
5
+ get: (type: any, ids: any) => {};
6
+ set: (data: any) => void;
7
+ };
8
+ };
9
+ saveCreds: () => void;
10
+ }>;
11
+ //# sourceMappingURL=use-single-file-auth-state.d.ts.map
@@ -0,0 +1,109 @@
1
+ import { readFile, rename, stat, writeFile } from 'fs/promises';
2
+ import { DEFAULT_CACHE_TTLS } from '../Defaults/index.js';
3
+ import { proto } from '../../WAProto/index.js';
4
+ import { initAuthCreds } from './auth-utils.js';
5
+ import { BufferJSON } from './generics.js';
6
+ import { LRUCache } from 'lru-cache';
7
+ import { Mutex } from 'async-mutex';
8
+ // JexkCode@Update - Add useSingleFileAuthState with integrated cache
9
+ const FLUSH_TIMEOUT_MS = 3000;
10
+ // JexkCode@Update - Enhanced useSingleFileAuthState with LRUCache
11
+ export const useSingleFileAuthState = async (fileName) => {
12
+ const cache = new LRUCache({
13
+ max: 20000,
14
+ ttl: 1000 * DEFAULT_CACHE_TTLS.SIGNAL_STORE,
15
+ updateAgeOnGet: false,
16
+ updateAgeOnHas: false,
17
+ ttlAutopurge: true
18
+ });
19
+ // JexkCode@Update - Add mutex for prevent race condition
20
+ const mutex = new Mutex();
21
+ let fileData = {};
22
+ let isLoaded = false;
23
+ let flushTimeout = null;
24
+ const loadKey = async () => {
25
+ return await mutex.runExclusive(async () => {
26
+ if (isLoaded)
27
+ return;
28
+ try {
29
+ const data = JSON.parse(await readFile(fileName, 'utf-8'), BufferJSON.reviver);
30
+ fileData = data || {};
31
+ for (const [keyName, value] of Object.entries(fileData)) {
32
+ cache.set(keyName, value);
33
+ }
34
+ }
35
+ catch {
36
+ fileData = {};
37
+ }
38
+ isLoaded = true;
39
+ });
40
+ };
41
+ const flushKey = () => {
42
+ if (flushTimeout)
43
+ return;
44
+ flushTimeout = setTimeout(async () => {
45
+ flushTimeout = null;
46
+ await mutex.runExclusive(async () => {
47
+ try {
48
+ const tempFile = fileName + '.temp';
49
+ await writeFile(tempFile, JSON.stringify(fileData, BufferJSON.replacer));
50
+ await rename(tempFile, fileName);
51
+ }
52
+ catch { }
53
+ });
54
+ }, FLUSH_TIMEOUT_MS);
55
+ };
56
+ const writeKey = (keyName, value) => {
57
+ cache.set(keyName, value);
58
+ fileData[keyName] = value;
59
+ flushKey();
60
+ };
61
+ const removeKey = (keyName) => {
62
+ cache.delete(keyName);
63
+ delete fileData[keyName];
64
+ flushKey();
65
+ };
66
+ const fileInfo = await stat(fileName).catch(() => null);
67
+ if (!fileInfo) {
68
+ await writeFile(fileName, '{}');
69
+ }
70
+ else if (!fileInfo.isFile()) {
71
+ throw new Error(`found something that is not a file at ${fileName}, either delete it or specify a different location`);
72
+ }
73
+ await loadKey();
74
+ const creds = fileData['creds'] || initAuthCreds();
75
+ return {
76
+ state: {
77
+ creds,
78
+ keys: {
79
+ get: (type, ids) => {
80
+ const data = {};
81
+ for (const id of ids) {
82
+ const keyName = type + id;
83
+ let value = cache.get(keyName);
84
+ if (value === undefined && fileData[keyName] !== undefined) {
85
+ value = fileData[keyName];
86
+ cache.set(keyName, value);
87
+ }
88
+ if (type === 'app-state-sync-key' && value) {
89
+ value = proto.Message.AppStateSyncKeyData.fromObject(value);
90
+ }
91
+ data[id] = value;
92
+ }
93
+ return data;
94
+ },
95
+ set: (data) => {
96
+ for (const category in data) {
97
+ for (const id in data[category]) {
98
+ const keyName = category + id;
99
+ const value = data[category][id];
100
+ value ? writeKey(keyName, value) : removeKey(keyName);
101
+ }
102
+ }
103
+ }
104
+ }
105
+ },
106
+ saveCreds: () => writeKey('creds', creds)
107
+ };
108
+ };
109
+ //# sourceMappingURL=use-single-file-auth-state.js.map
@@ -0,0 +1,11 @@
1
+ export function useSqliteAuthState(opts: any): Promise<{
2
+ state: {
3
+ creds: any;
4
+ keys: {
5
+ get: (type: any, ids: any) => Promise<{}>;
6
+ set: (data: any) => Promise<void>;
7
+ };
8
+ };
9
+ saveCreds: () => Promise<void>;
10
+ }>;
11
+ //# sourceMappingURL=use-sqlite-auth-state.d.ts.map
@@ -0,0 +1,109 @@
1
+ import { mkdir, readFile, stat, unlink, writeFile } from 'fs/promises';
2
+ import { join } from 'path';
3
+ import { proto } from '../../WAProto/index.js';
4
+ import { initAuthCreds } from './auth-utils.js';
5
+ import { BufferJSON } from './generics.js';
6
+ async function loadBetterSqlite3() {
7
+ try {
8
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
9
+ const mod = (await import('better-sqlite3'));
10
+ return mod.default ?? mod;
11
+ }
12
+ catch (err) {
13
+ const helpful = new Error('`better-sqlite3` is required for `useSqliteAuthState`. Install it as a peer dependency: `npm install better-sqlite3` (or `yarn add better-sqlite3`).');
14
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
15
+ helpful.cause = err;
16
+ throw helpful;
17
+ }
18
+ }
19
+ const CREDS_ROW_KEY = '__creds__';
20
+ const CREATE_SCHEMA_SQL = `
21
+ CREATE TABLE IF NOT EXISTS creds (
22
+ key TEXT PRIMARY KEY,
23
+ value TEXT NOT NULL
24
+ );
25
+ CREATE TABLE IF NOT EXISTS signal_keys (
26
+ type TEXT NOT NULL,
27
+ id TEXT NOT NULL,
28
+ value TEXT NOT NULL,
29
+ PRIMARY KEY (type, id)
30
+ );
31
+ CREATE INDEX IF NOT EXISTS signal_keys_type_idx ON signal_keys(type);
32
+ `;
33
+ export async function useSqliteAuthState(opts) {
34
+ let db;
35
+ if (opts.database) {
36
+ db = opts.database;
37
+ }
38
+ else {
39
+ const Database = await loadBetterSqlite3();
40
+ db = new Database(opts.dbPath);
41
+ }
42
+ // WAL mode allows concurrent reads alongside a single writer; matches
43
+ // what SQLite recommends for read-heavy workloads with sporadic writes.
44
+ db.pragma('journal_mode = WAL');
45
+ db.pragma('synchronous = NORMAL');
46
+ db.exec(CREATE_SCHEMA_SQL);
47
+ const stmts = {
48
+ credsSelect: db.prepare('SELECT value FROM creds WHERE key = ?'),
49
+ credsUpsert: db.prepare('INSERT INTO creds (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value'),
50
+ keySelect: db.prepare('SELECT value FROM signal_keys WHERE type = ? AND id = ?'),
51
+ keyUpsert: db.prepare('INSERT INTO signal_keys (type, id, value) VALUES (?, ?, ?) ON CONFLICT(type, id) DO UPDATE SET value = excluded.value'),
52
+ keyDelete: db.prepare('DELETE FROM signal_keys WHERE type = ? AND id = ?'),
53
+ keyListIds: db.prepare('SELECT id FROM signal_keys WHERE type = ?'),
54
+ keyList: db.prepare('SELECT id, value FROM signal_keys WHERE type = ?'),
55
+ clearKeys: db.prepare('DELETE FROM signal_keys')
56
+ };
57
+ const loadCreds = () => {
58
+ const row = stmts.credsSelect.get(CREDS_ROW_KEY);
59
+ if (!row)
60
+ return initAuthCreds();
61
+ return JSON.parse(row.value, BufferJSON.reviver);
62
+ };
63
+ const persistCreds = (creds) => {
64
+ stmts.credsUpsert.run(CREDS_ROW_KEY, JSON.stringify(creds, BufferJSON.replacer));
65
+ };
66
+ const creds = loadCreds();
67
+ return {
68
+ state: {
69
+ creds,
70
+ keys: {
71
+ get: async (type, ids) => {
72
+ const data = {};
73
+ for (const id of ids) {
74
+ const row = stmts.keySelect.get(type, id);
75
+ if (row) {
76
+ let value = JSON.parse(row.value, BufferJSON.reviver);
77
+ if (type === 'app-state-sync-key' && value) {
78
+ value = proto.Message.AppStateSyncKeyData.fromObject(value);
79
+ }
80
+ data[id] = value;
81
+ }
82
+ }
83
+ return data;
84
+ },
85
+ set: async (data) => {
86
+ const writeTx = db.transaction(() => {
87
+ for (const category in data) {
88
+ for (const id in data[category]) {
89
+ const value = data[category][id];
90
+ if (value) {
91
+ const stringified = JSON.stringify(value, BufferJSON.replacer);
92
+ stmts.keyUpsert.run(category, id, stringified);
93
+ }
94
+ else {
95
+ stmts.keyDelete.run(category, id);
96
+ }
97
+ }
98
+ }
99
+ });
100
+ writeTx();
101
+ }
102
+ }
103
+ },
104
+ saveCreds: async () => {
105
+ persistCreds(creds);
106
+ }
107
+ };
108
+ }
109
+ //# sourceMappingURL=use-sqlite-auth-state.js.map
@@ -0,0 +1,44 @@
1
+ export function generateLoginNode(userJid: any, config: any): proto.ClientPayload;
2
+ export function generateRegistrationNode({ registrationId, signedPreKey, signedIdentityKey }: {
3
+ registrationId: any;
4
+ signedPreKey: any;
5
+ signedIdentityKey: any;
6
+ }, config: any): proto.ClientPayload;
7
+ export function configureSuccessfulPairing(stanza: any, { advSecretKey, signedIdentityKey, signalIdentities }: {
8
+ advSecretKey: any;
9
+ signedIdentityKey: any;
10
+ signalIdentities: any;
11
+ }): {
12
+ creds: {
13
+ account: proto.ADVSignedDeviceIdentity;
14
+ me: {
15
+ id: any;
16
+ name: any;
17
+ lid: any;
18
+ };
19
+ signalIdentities: any[];
20
+ platform: any;
21
+ };
22
+ reply: {
23
+ tag: string;
24
+ attrs: {
25
+ to: string;
26
+ type: string;
27
+ id: any;
28
+ };
29
+ content: {
30
+ tag: string;
31
+ attrs: {};
32
+ content: {
33
+ tag: string;
34
+ attrs: {
35
+ 'key-index': string;
36
+ };
37
+ content: any;
38
+ }[];
39
+ }[];
40
+ };
41
+ };
42
+ export function encodeSignedDeviceIdentity(account: any, includeSignatureKey: any): any;
43
+ import { proto } from '../../WAProto/index.js';
44
+ //# sourceMappingURL=validate-connection.d.ts.map
@@ -0,0 +1,210 @@
1
+ import { Boom } from '@hapi/boom';
2
+ import { createHash } from 'crypto';
3
+ import { proto } from '../../WAProto/index.js';
4
+ import { KEY_BUNDLE_TYPE, WA_ADV_ACCOUNT_SIG_PREFIX, WA_ADV_DEVICE_SIG_PREFIX, WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX } from '../Defaults/index.js';
5
+ import { getBinaryNodeChild, jidDecode, S_WHATSAPP_NET } from '../WABinary/index.js';
6
+ import { Curve, hmacSign } from './crypto.js';
7
+ import { encodeBigEndian } from './generics.js';
8
+ import { createSignalIdentity } from './signal.js';
9
+ const getUserAgent = (config) => {
10
+ return {
11
+ appVersion: {
12
+ primary: config.version[0],
13
+ secondary: config.version[1],
14
+ tertiary: config.version[2]
15
+ },
16
+ platform: config.browser[1].toLocaleLowerCase().includes('android')
17
+ ? proto.ClientPayload.UserAgent.Platform.ANDROID
18
+ : proto.ClientPayload.UserAgent.Platform.WEB,
19
+ releaseChannel: proto.ClientPayload.UserAgent.ReleaseChannel.RELEASE,
20
+ osVersion: '0.1',
21
+ device: 'Desktop',
22
+ osBuildNumber: '0.1',
23
+ localeLanguageIso6391: 'en',
24
+ mnc: '000',
25
+ mcc: '000',
26
+ localeCountryIso31661Alpha2: config.countryCode
27
+ };
28
+ };
29
+ const PLATFORM_MAP = {
30
+ 'Mac OS': proto.ClientPayload.WebInfo.WebSubPlatform.DARWIN,
31
+ Windows: proto.ClientPayload.WebInfo.WebSubPlatform.WIN32
32
+ };
33
+ const getWebInfo = (config) => {
34
+ let webSubPlatform = proto.ClientPayload.WebInfo.WebSubPlatform.WEB_BROWSER;
35
+ if (config.syncFullHistory &&
36
+ PLATFORM_MAP[config.browser[0]] &&
37
+ config.browser[1] === 'Desktop') {
38
+ webSubPlatform = PLATFORM_MAP[config.browser[0]];
39
+ }
40
+ return { webSubPlatform };
41
+ };
42
+ const getClientPayload = (config) => {
43
+ const payload = {
44
+ connectType: proto.ClientPayload.ConnectType.WIFI_UNKNOWN,
45
+ connectReason: proto.ClientPayload.ConnectReason.USER_ACTIVATED,
46
+ userAgent: getUserAgent(config)
47
+ };
48
+ if (!config.browser[1].toLocaleLowerCase().includes('android')) {
49
+ payload.webInfo = getWebInfo(config);
50
+ }
51
+ if (config.pushName) {
52
+ payload.pushName = config.pushName;
53
+ }
54
+ return payload;
55
+ };
56
+ export const generateLoginNode = (userJid, config) => {
57
+ const { user, device } = jidDecode(userJid);
58
+ const payload = {
59
+ ...getClientPayload(config),
60
+ passive: true,
61
+ pull: true,
62
+ username: +user,
63
+ device: device,
64
+ // TODO: investigate (hard set as false atm)
65
+ lidDbMigrated: false
66
+ };
67
+ return proto.ClientPayload.fromObject(payload);
68
+ };
69
+ const getPlatformType = (platform) => {
70
+ const platformType = platform.toUpperCase();
71
+ if (platformType === 'ANDROID') {
72
+ return proto.DeviceProps.PlatformType.ANDROID_PHONE;
73
+ }
74
+ return (proto.DeviceProps.PlatformType[platformType] ||
75
+ proto.DeviceProps.PlatformType.CHROME);
76
+ };
77
+ export const generateRegistrationNode = ({ registrationId, signedPreKey, signedIdentityKey }, config) => {
78
+ // the app version needs to be md5 hashed
79
+ // and passed in
80
+ const appVersionBuf = createHash('md5')
81
+ .update(config.version.join('.')) // join as string
82
+ .digest();
83
+ const companion = {
84
+ os: config.browser[0],
85
+ platformType: getPlatformType(config.browser[1]),
86
+ requireFullSync: config.syncFullHistory,
87
+ historySyncConfig: {
88
+ storageQuotaMb: 10240,
89
+ inlineInitialPayloadInE2EeMsg: true,
90
+ recentSyncDaysLimit: undefined,
91
+ supportCallLogHistory: false,
92
+ supportBotUserAgentChatHistory: true,
93
+ supportCagReactionsAndPolls: true,
94
+ supportBizHostedMsg: true,
95
+ supportRecentSyncChunkMessageCountTuning: true,
96
+ supportHostedGroupMsg: true,
97
+ supportFbidBotChatHistory: true,
98
+ supportAddOnHistorySyncMigration: undefined,
99
+ supportMessageAssociation: true,
100
+ supportGroupHistory: false,
101
+ onDemandReady: undefined,
102
+ supportGuestChat: undefined
103
+ },
104
+ version: {
105
+ primary: 10,
106
+ secondary: 15,
107
+ tertiary: 7
108
+ }
109
+ };
110
+ const companionProto = proto.DeviceProps.encode(companion).finish();
111
+ const registerPayload = {
112
+ ...getClientPayload(config),
113
+ passive: false,
114
+ pull: false,
115
+ devicePairingData: {
116
+ buildHash: appVersionBuf,
117
+ deviceProps: companionProto,
118
+ eRegid: encodeBigEndian(registrationId),
119
+ eKeytype: KEY_BUNDLE_TYPE,
120
+ eIdent: signedIdentityKey.public,
121
+ eSkeyId: encodeBigEndian(signedPreKey.keyId, 3),
122
+ eSkeyVal: signedPreKey.keyPair.public,
123
+ eSkeySig: signedPreKey.signature
124
+ }
125
+ };
126
+ return proto.ClientPayload.fromObject(registerPayload);
127
+ };
128
+ export const configureSuccessfulPairing = (stanza, { advSecretKey, signedIdentityKey, signalIdentities }) => {
129
+ const msgId = stanza.attrs.id;
130
+ const pairSuccessNode = getBinaryNodeChild(stanza, 'pair-success');
131
+ const deviceIdentityNode = getBinaryNodeChild(pairSuccessNode, 'device-identity');
132
+ const platformNode = getBinaryNodeChild(pairSuccessNode, 'platform');
133
+ const deviceNode = getBinaryNodeChild(pairSuccessNode, 'device');
134
+ const businessNode = getBinaryNodeChild(pairSuccessNode, 'biz');
135
+ if (!deviceIdentityNode || !deviceNode) {
136
+ throw new Boom('Missing device-identity or device in pair success node', { data: stanza });
137
+ }
138
+ const bizName = businessNode?.attrs.name;
139
+ const jid = deviceNode.attrs.jid;
140
+ const lid = deviceNode.attrs.lid;
141
+ const { details, hmac, accountType } = proto.ADVSignedDeviceIdentityHMAC.decode(deviceIdentityNode.content);
142
+ let hmacPrefix = Buffer.from([]);
143
+ if (accountType !== undefined && accountType === proto.ADVEncryptionType.HOSTED) {
144
+ hmacPrefix = WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX;
145
+ }
146
+ const advSign = hmacSign(Buffer.concat([hmacPrefix, details]), Buffer.from(advSecretKey, 'base64'));
147
+ if (Buffer.compare(hmac, advSign) !== 0) {
148
+ throw new Boom('Invalid account signature');
149
+ }
150
+ const account = proto.ADVSignedDeviceIdentity.decode(details);
151
+ const { accountSignatureKey, accountSignature, details: deviceDetails } = account;
152
+ const deviceIdentity = proto.ADVDeviceIdentity.decode(deviceDetails);
153
+ const accountSignaturePrefix = deviceIdentity.deviceType === proto.ADVEncryptionType.HOSTED
154
+ ? WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX
155
+ : WA_ADV_ACCOUNT_SIG_PREFIX;
156
+ const accountMsg = Buffer.concat([accountSignaturePrefix, deviceDetails, signedIdentityKey.public]);
157
+ if (!Curve.verify(accountSignatureKey, accountMsg, accountSignature)) {
158
+ throw new Boom('Failed to verify account signature');
159
+ }
160
+ const deviceMsg = Buffer.concat([
161
+ WA_ADV_DEVICE_SIG_PREFIX,
162
+ deviceDetails,
163
+ signedIdentityKey.public,
164
+ accountSignatureKey
165
+ ]);
166
+ account.deviceSignature = Curve.sign(signedIdentityKey.private, deviceMsg);
167
+ const identity = createSignalIdentity(lid, accountSignatureKey);
168
+ const accountEnc = encodeSignedDeviceIdentity(account, false);
169
+ const reply = {
170
+ tag: 'iq',
171
+ attrs: {
172
+ to: S_WHATSAPP_NET,
173
+ type: 'result',
174
+ id: msgId
175
+ },
176
+ content: [
177
+ {
178
+ tag: 'pair-device-sign',
179
+ attrs: {},
180
+ content: [
181
+ {
182
+ tag: 'device-identity',
183
+ attrs: { 'key-index': deviceIdentity.keyIndex.toString() },
184
+ content: accountEnc
185
+ }
186
+ ]
187
+ }
188
+ ]
189
+ };
190
+ const authUpdate = {
191
+ account,
192
+ me: { id: jid, name: bizName, lid },
193
+ signalIdentities: [...(signalIdentities || []), identity],
194
+ platform: platformNode?.attrs.name
195
+ };
196
+ return {
197
+ creds: authUpdate,
198
+ reply
199
+ };
200
+ };
201
+ export const encodeSignedDeviceIdentity = (account, includeSignatureKey) => {
202
+ account = { ...account };
203
+ // set to null if we are not to include the signature key
204
+ // or if we are including the signature key but it is empty
205
+ if (!includeSignatureKey || !account.accountSignatureKey?.length) {
206
+ account.accountSignatureKey = null;
207
+ }
208
+ return proto.ADVSignedDeviceIdentity.encode(account).finish();
209
+ };
210
+ //# sourceMappingURL=validate-connection.js.map
@@ -0,0 +1,62 @@
1
+ export namespace TAGS {
2
+ let LIST_EMPTY: number;
3
+ let DICTIONARY_0: number;
4
+ let DICTIONARY_1: number;
5
+ let DICTIONARY_2: number;
6
+ let DICTIONARY_3: number;
7
+ let INTEROP_JID: number;
8
+ let FB_JID: number;
9
+ let AD_JID: number;
10
+ let LIST_8: number;
11
+ let LIST_16: number;
12
+ let JID_PAIR: number;
13
+ let HEX_8: number;
14
+ let BINARY_8: number;
15
+ let BINARY_20: number;
16
+ let BINARY_32: number;
17
+ let NIBBLE_8: number;
18
+ let PACKED_MAX: number;
19
+ }
20
+ export const DOUBLE_BYTE_TOKENS: string[][];
21
+ export const SINGLE_BYTE_TOKENS: string[];
22
+ export const TOKEN_MAP: {};
23
+ export const CPP_KEYWORDS: Set<string>;
24
+ export const CSS_KEYWORDS: Set<string>;
25
+ export const GO_KEYWORDS: Set<string>;
26
+ export const HTML_KEYWORDS: Set<string>;
27
+ export const JS_KEYWORDS: Set<string>;
28
+ export const PYTHON_KEYWORDS: Set<string>;
29
+ export const RUST_KEYWORDS: Set<string>;
30
+ export const C_KEYWORDS: Set<string>;
31
+ export const CSHARP_KEYWORDS: Set<string>;
32
+ export const BASH_KEYWORDS: Set<string>;
33
+ export const CMD_KEYWORDS: Set<string>;
34
+ export const POWERSHELL_KEYWORDS: Set<string>;
35
+ export const LANGUAGE_KEYWORDS: {
36
+ css: Set<string>;
37
+ html: Set<string>;
38
+ javascript: Set<string>;
39
+ typescript: Set<string>;
40
+ js: Set<string>;
41
+ ts: Set<string>;
42
+ python: Set<string>;
43
+ py: Set<string>;
44
+ go: Set<string>;
45
+ golang: Set<string>;
46
+ cpp: Set<string>;
47
+ 'c++': Set<string>;
48
+ rust: Set<string>;
49
+ rs: Set<string>;
50
+ c: Set<string>;
51
+ h: Set<string>;
52
+ csharp: Set<string>;
53
+ cs: Set<string>;
54
+ bash: Set<string>;
55
+ sh: Set<string>;
56
+ zsh: Set<string>;
57
+ cmd: Set<string>;
58
+ bat: Set<string>;
59
+ powershell: Set<string>;
60
+ ps1: Set<string>;
61
+ };
62
+ //# sourceMappingURL=constants.d.ts.map