@dhilzzkz/baileys 0.0.0-stage → 0.1.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 (241) hide show
  1. package/LICENSE +23 -0
  2. package/NOTICE.md +37 -0
  3. package/README.md +2083 -2
  4. package/WAProto/index.d.ts +22220 -0
  5. package/WAProto/index.js +5 -0
  6. package/lib/Addon/http-error.d.ts +18 -0
  7. package/lib/Addon/http-error.js +40 -0
  8. package/lib/Addon/index.d.ts +3 -0
  9. package/lib/Addon/index.js +4 -0
  10. package/lib/Addon/keyed-db.d.ts +14 -0
  11. package/lib/Addon/keyed-db.js +241 -0
  12. package/lib/Addon/link-preview.d.ts +15 -0
  13. package/lib/Addon/link-preview.js +79 -0
  14. package/lib/Defaults/index.d.ts +188 -0
  15. package/lib/Defaults/index.js +185 -0
  16. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  17. package/lib/Signal/Group/ciphertext-message.js +11 -0
  18. package/lib/Signal/Group/group-cipher.d.ts +10 -0
  19. package/lib/Signal/Group/group-cipher.js +81 -0
  20. package/lib/Signal/Group/group-session-builder.d.ts +7 -0
  21. package/lib/Signal/Group/group-session-builder.js +29 -0
  22. package/lib/Signal/Group/index.d.ts +11 -0
  23. package/lib/Signal/Group/index.js +11 -0
  24. package/lib/Signal/Group/keyhelper.d.ts +6 -0
  25. package/lib/Signal/Group/keyhelper.js +17 -0
  26. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  27. package/lib/Signal/Group/sender-chain-key.js +25 -0
  28. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  29. package/lib/Signal/Group/sender-key-distribution-message.js +62 -0
  30. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  31. package/lib/Signal/Group/sender-key-message.js +65 -0
  32. package/lib/Signal/Group/sender-key-name.d.ts +11 -0
  33. package/lib/Signal/Group/sender-key-name.js +47 -0
  34. package/lib/Signal/Group/sender-key-record.d.ts +12 -0
  35. package/lib/Signal/Group/sender-key-record.js +40 -0
  36. package/lib/Signal/Group/sender-key-state.d.ts +16 -0
  37. package/lib/Signal/Group/sender-key-state.js +83 -0
  38. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  39. package/lib/Signal/Group/sender-message-key.js +25 -0
  40. package/lib/Signal/Protocol/crypto.d.ts +6 -0
  41. package/lib/Signal/Protocol/crypto.js +61 -0
  42. package/lib/Signal/Protocol/curve.d.ts +8 -0
  43. package/lib/Signal/Protocol/curve.js +61 -0
  44. package/lib/Signal/Protocol/index.d.ts +16 -0
  45. package/lib/Signal/Protocol/index.js +9 -0
  46. package/lib/Signal/Protocol/internals.d.ts +57 -0
  47. package/lib/Signal/Protocol/internals.js +155 -0
  48. package/lib/Signal/Protocol/session-builder.d.ts +40 -0
  49. package/lib/Signal/Protocol/session-builder.js +143 -0
  50. package/lib/Signal/Protocol/session-cipher.d.ts +26 -0
  51. package/lib/Signal/Protocol/session-cipher.js +301 -0
  52. package/lib/Signal/Protocol/session-record.d.ts +55 -0
  53. package/lib/Signal/Protocol/session-record.js +272 -0
  54. package/lib/Signal/libsignal.d.ts +54 -0
  55. package/lib/Signal/libsignal.js +426 -0
  56. package/lib/Signal/lid-mapping.d.ts +20 -0
  57. package/lib/Signal/lid-mapping.js +274 -0
  58. package/lib/Socket/Client/index.d.ts +2 -0
  59. package/lib/Socket/Client/index.js +2 -0
  60. package/lib/Socket/Client/types.d.ts +5 -0
  61. package/lib/Socket/Client/types.js +10 -0
  62. package/lib/Socket/Client/websocket.d.ts +12 -0
  63. package/lib/Socket/Client/websocket.js +119 -0
  64. package/lib/Socket/business.d.ts +387 -0
  65. package/lib/Socket/business.js +380 -0
  66. package/lib/Socket/chats.d.ts +144 -0
  67. package/lib/Socket/chats.js +1216 -0
  68. package/lib/Socket/communities.d.ts +554 -0
  69. package/lib/Socket/communities.js +431 -0
  70. package/lib/Socket/groups.d.ts +286 -0
  71. package/lib/Socket/groups.js +347 -0
  72. package/lib/Socket/index.d.ts +522 -0
  73. package/lib/Socket/index.js +11 -0
  74. package/lib/Socket/messages-recv.d.ts +326 -0
  75. package/lib/Socket/messages-recv.js +1822 -0
  76. package/lib/Socket/messages-send.d.ts +321 -0
  77. package/lib/Socket/messages-send.js +1378 -0
  78. package/lib/Socket/mex.d.ts +1 -0
  79. package/lib/Socket/mex.js +41 -0
  80. package/lib/Socket/newsletter.d.ts +283 -0
  81. package/lib/Socket/newsletter.js +225 -0
  82. package/lib/Socket/socket.d.ts +61 -0
  83. package/lib/Socket/socket.js +992 -0
  84. package/lib/Store/index.d.ts +3 -0
  85. package/lib/Store/index.js +3 -0
  86. package/lib/Store/make-in-memory-store.d.ts +63 -0
  87. package/lib/Store/make-in-memory-store.js +418 -0
  88. package/lib/Store/make-ordered-dictionary.d.ts +12 -0
  89. package/lib/Store/make-ordered-dictionary.js +78 -0
  90. package/lib/Store/object-repository.d.ts +10 -0
  91. package/lib/Store/object-repository.js +23 -0
  92. package/lib/Types/Auth.d.ts +1 -0
  93. package/lib/Types/Auth.js +1 -0
  94. package/lib/Types/Business.d.ts +1 -0
  95. package/lib/Types/Business.js +1 -0
  96. package/lib/Types/Call.d.ts +1 -0
  97. package/lib/Types/Call.js +1 -0
  98. package/lib/Types/Chat.d.ts +1 -0
  99. package/lib/Types/Chat.js +7 -0
  100. package/lib/Types/Contact.d.ts +1 -0
  101. package/lib/Types/Contact.js +1 -0
  102. package/lib/Types/Events.d.ts +1 -0
  103. package/lib/Types/Events.js +1 -0
  104. package/lib/Types/GroupMetadata.d.ts +1 -0
  105. package/lib/Types/GroupMetadata.js +1 -0
  106. package/lib/Types/Label.d.ts +2 -0
  107. package/lib/Types/Label.js +24 -0
  108. package/lib/Types/LabelAssociation.d.ts +2 -0
  109. package/lib/Types/LabelAssociation.js +6 -0
  110. package/lib/Types/Message.d.ts +11 -0
  111. package/lib/Types/Message.js +17 -0
  112. package/lib/Types/Mex.d.ts +2 -0
  113. package/lib/Types/Mex.js +38 -0
  114. package/lib/Types/Product.d.ts +1 -0
  115. package/lib/Types/Product.js +1 -0
  116. package/lib/Types/RichType.d.ts +2 -0
  117. package/lib/Types/RichType.js +22 -0
  118. package/lib/Types/Signal.d.ts +1 -0
  119. package/lib/Types/Signal.js +1 -0
  120. package/lib/Types/Socket.d.ts +1 -0
  121. package/lib/Types/Socket.js +1 -0
  122. package/lib/Types/State.d.ts +5 -0
  123. package/lib/Types/State.js +54 -0
  124. package/lib/Types/USync.d.ts +1 -0
  125. package/lib/Types/USync.js +1 -0
  126. package/lib/Types/index.d.ts +13 -0
  127. package/lib/Types/index.js +25 -0
  128. package/lib/Utils/Auth/auth-utils.d.ts +58 -0
  129. package/lib/Utils/Auth/auth-utils.js +316 -0
  130. package/lib/Utils/Auth/companion-reg-client-utils.d.ts +4 -0
  131. package/lib/Utils/Auth/companion-reg-client-utils.js +39 -0
  132. package/lib/Utils/Auth/pre-key-manager.d.ts +25 -0
  133. package/lib/Utils/Auth/pre-key-manager.js +105 -0
  134. package/lib/Utils/Auth/use-multi-file-auth-state.d.ts +10 -0
  135. package/lib/Utils/Auth/use-multi-file-auth-state.js +116 -0
  136. package/lib/Utils/Auth/use-single-file-auth-state.d.ts +11 -0
  137. package/lib/Utils/Auth/use-single-file-auth-state.js +94 -0
  138. package/lib/Utils/Auth/use-sqlite-auth-state.d.ts +11 -0
  139. package/lib/Utils/Auth/use-sqlite-auth-state.js +109 -0
  140. package/lib/Utils/Auth/validate-connection.d.ts +44 -0
  141. package/lib/Utils/Auth/validate-connection.js +210 -0
  142. package/lib/Utils/Common/browser-utils.d.ts +9 -0
  143. package/lib/Utils/Common/browser-utils.js +28 -0
  144. package/lib/Utils/Common/generics.d.ts +63 -0
  145. package/lib/Utils/Common/generics.js +392 -0
  146. package/lib/Utils/Common/logger.d.ts +12 -0
  147. package/lib/Utils/Common/logger.js +12 -0
  148. package/lib/Utils/Common/make-mutex.d.ts +6 -0
  149. package/lib/Utils/Common/make-mutex.js +32 -0
  150. package/lib/Utils/Crypto/crypto.d.ts +39 -0
  151. package/lib/Utils/Crypto/crypto.js +117 -0
  152. package/lib/Utils/Crypto/lt-hash.d.ts +6 -0
  153. package/lib/Utils/Crypto/lt-hash.js +7 -0
  154. package/lib/Utils/Crypto/noise-handler.d.ts +20 -0
  155. package/lib/Utils/Crypto/noise-handler.js +200 -0
  156. package/lib/Utils/Crypto/signal.d.ts +82 -0
  157. package/lib/Utils/Crypto/signal.js +200 -0
  158. package/lib/Utils/Message/business.d.ts +49 -0
  159. package/lib/Utils/Message/business.js +230 -0
  160. package/lib/Utils/Message/decode-wa-message.d.ts +83 -0
  161. package/lib/Utils/Message/decode-wa-message.js +316 -0
  162. package/lib/Utils/Message/history.d.ts +75 -0
  163. package/lib/Utils/Message/history.js +133 -0
  164. package/lib/Utils/Message/link-preview.d.ts +13 -0
  165. package/lib/Utils/Message/link-preview.js +73 -0
  166. package/lib/Utils/Message/message-retry-manager.d.ts +79 -0
  167. package/lib/Utils/Message/message-retry-manager.js +259 -0
  168. package/lib/Utils/Message/messages-media.d.ts +134 -0
  169. package/lib/Utils/Message/messages-media.js +802 -0
  170. package/lib/Utils/Message/messages.d.ts +47 -0
  171. package/lib/Utils/Message/messages.js +1907 -0
  172. package/lib/Utils/Message/offline-node-processor.d.ts +10 -0
  173. package/lib/Utils/Message/offline-node-processor.js +40 -0
  174. package/lib/Utils/Message/process-message.d.ts +83 -0
  175. package/lib/Utils/Message/process-message.js +748 -0
  176. package/lib/Utils/Message/reporting-utils.d.ts +12 -0
  177. package/lib/Utils/Message/reporting-utils.js +257 -0
  178. package/lib/Utils/Message/rich-message-utils.d.ts +48 -0
  179. package/lib/Utils/Message/rich-message-utils.js +366 -0
  180. package/lib/Utils/Message/stanza-ack.d.ts +16 -0
  181. package/lib/Utils/Message/stanza-ack.js +37 -0
  182. package/lib/Utils/State/chat-utils.d.ts +408 -0
  183. package/lib/Utils/State/chat-utils.js +871 -0
  184. package/lib/Utils/State/event-buffer.d.ts +12 -0
  185. package/lib/Utils/State/event-buffer.js +621 -0
  186. package/lib/Utils/State/identity-change-handler.d.ts +13 -0
  187. package/lib/Utils/State/identity-change-handler.js +48 -0
  188. package/lib/Utils/State/sync-action-utils.d.ts +2 -0
  189. package/lib/Utils/State/sync-action-utils.js +48 -0
  190. package/lib/Utils/State/tc-token-utils.d.ts +29 -0
  191. package/lib/Utils/State/tc-token-utils.js +163 -0
  192. package/lib/Utils/index.d.ts +24 -0
  193. package/lib/Utils/index.js +24 -0
  194. package/lib/WABinary/constants.d.ts +61 -0
  195. package/lib/WABinary/constants.js +1466 -0
  196. package/lib/WABinary/decode.d.ts +9 -0
  197. package/lib/WABinary/decode.js +261 -0
  198. package/lib/WABinary/encode.d.ts +2 -0
  199. package/lib/WABinary/encode.js +219 -0
  200. package/lib/WABinary/generic-utils.d.ts +79 -0
  201. package/lib/WABinary/generic-utils.js +226 -0
  202. package/lib/WABinary/index.d.ts +5 -0
  203. package/lib/WABinary/index.js +5 -0
  204. package/lib/WABinary/jid-utils.d.ts +28 -0
  205. package/lib/WABinary/jid-utils.js +95 -0
  206. package/lib/WABinary/types.d.ts +1 -0
  207. package/lib/WABinary/types.js +1 -0
  208. package/lib/WAM/BinaryInfo.d.ts +7 -0
  209. package/lib/WAM/BinaryInfo.js +9 -0
  210. package/lib/WAM/constants.d.ts +34926 -0
  211. package/lib/WAM/constants.js +22852 -0
  212. package/lib/WAM/encode.d.ts +1 -0
  213. package/lib/WAM/encode.js +149 -0
  214. package/lib/WAM/index.d.ts +3 -0
  215. package/lib/WAM/index.js +3 -0
  216. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.d.ts +38 -0
  217. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +50 -0
  218. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +36 -0
  219. package/lib/WAUSync/Protocols/USyncContactProtocol.js +51 -0
  220. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  221. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
  222. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  223. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  224. package/lib/WAUSync/Protocols/USyncLIDProtocol.d.ts +14 -0
  225. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +28 -0
  226. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  227. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  228. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +9 -0
  229. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  230. package/lib/WAUSync/Protocols/index.d.ts +5 -0
  231. package/lib/WAUSync/Protocols/index.js +5 -0
  232. package/lib/WAUSync/USyncQuery.d.ts +20 -0
  233. package/lib/WAUSync/USyncQuery.js +97 -0
  234. package/lib/WAUSync/USyncUser.d.ts +16 -0
  235. package/lib/WAUSync/USyncUser.js +30 -0
  236. package/lib/WAUSync/index.d.ts +3 -0
  237. package/lib/WAUSync/index.js +3 -0
  238. package/lib/index.d.ts +11 -0
  239. package/lib/index.js +11 -0
  240. package/package.json +120 -5
  241. package/scripts/engine-requirements.js +16 -0
@@ -0,0 +1,39 @@
1
+ export var CompanionWebClientType;
2
+ (function (CompanionWebClientType) {
3
+ CompanionWebClientType[CompanionWebClientType["UNKNOWN"] = 0] = "UNKNOWN";
4
+ CompanionWebClientType[CompanionWebClientType["CHROME"] = 1] = "CHROME";
5
+ CompanionWebClientType[CompanionWebClientType["EDGE"] = 2] = "EDGE";
6
+ CompanionWebClientType[CompanionWebClientType["FIREFOX"] = 3] = "FIREFOX";
7
+ CompanionWebClientType[CompanionWebClientType["IE"] = 4] = "IE";
8
+ CompanionWebClientType[CompanionWebClientType["OPERA"] = 5] = "OPERA";
9
+ CompanionWebClientType[CompanionWebClientType["SAFARI"] = 6] = "SAFARI";
10
+ CompanionWebClientType[CompanionWebClientType["ELECTRON"] = 7] = "ELECTRON";
11
+ CompanionWebClientType[CompanionWebClientType["UWP"] = 8] = "UWP";
12
+ CompanionWebClientType[CompanionWebClientType["OTHER_WEB_CLIENT"] = 9] = "OTHER_WEB_CLIENT";
13
+ })(CompanionWebClientType || (CompanionWebClientType = {}));
14
+ const BROWSER_TO_COMPANION_WEB_CLIENT = {
15
+ Chrome: CompanionWebClientType.CHROME,
16
+ Edge: CompanionWebClientType.EDGE,
17
+ Firefox: CompanionWebClientType.FIREFOX,
18
+ IE: CompanionWebClientType.IE,
19
+ Opera: CompanionWebClientType.OPERA,
20
+ Safari: CompanionWebClientType.SAFARI
21
+ };
22
+ export const getCompanionWebClientType = ([os, browserName]) => {
23
+ if (browserName === 'Desktop') {
24
+ return os === 'Windows' ? CompanionWebClientType.UWP : CompanionWebClientType.ELECTRON;
25
+ }
26
+ return BROWSER_TO_COMPANION_WEB_CLIENT[browserName] || CompanionWebClientType.OTHER_WEB_CLIENT;
27
+ };
28
+ export const getCompanionPlatformId = (browser) => {
29
+ return getCompanionWebClientType(browser).toString();
30
+ };
31
+ export const buildPairingQRData = (ref, noiseKeyB64, identityKeyB64, advB64, browser) => {
32
+ return 'https://wa.me/settings/linked_devices#' + [
33
+ ref,
34
+ noiseKeyB64,
35
+ identityKeyB64,
36
+ advB64,
37
+ getCompanionPlatformId(browser)
38
+ ].join(',');
39
+ };
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Manages pre-key operations with proper concurrency control
3
+ */
4
+ export class PreKeyManager {
5
+ constructor(store: any, logger: any);
6
+ store: any;
7
+ logger: any;
8
+ queues: Map<any, any>;
9
+ /**
10
+ * Get or create a queue for a specific key type
11
+ */
12
+ getQueue(keyType: any): any;
13
+ /**
14
+ * Process pre-key operations (updates and deletions)
15
+ */
16
+ processOperations(data: any, keyType: any, transactionCache: any, mutations: any, isInTransaction: any): Promise<any>;
17
+ /**
18
+ * Process deletions with validation
19
+ */
20
+ processDeletions(keyType: any, ids: any, transactionCache: any, mutations: any, isInTransaction: any): Promise<void>;
21
+ /**
22
+ * Validate and process pre-key deletions outside transactions
23
+ */
24
+ validateDeletions(data: any, keyType: any): Promise<any>;
25
+ }
@@ -0,0 +1,105 @@
1
+ import { createQueue } from '../../Addon/index.js';
2
+ /**
3
+ * Manages pre-key operations with proper concurrency control
4
+ */
5
+ export class PreKeyManager {
6
+ constructor(store, logger) {
7
+ this.store = store;
8
+ this.logger = logger;
9
+ this.queues = new Map();
10
+ }
11
+ /**
12
+ * Get or create a queue for a specific key type
13
+ */
14
+ getQueue(keyType) {
15
+ if (!this.queues.has(keyType)) {
16
+ this.queues.set(keyType, createQueue(1));
17
+ }
18
+ return this.queues.get(keyType);
19
+ }
20
+ /**
21
+ * Process pre-key operations (updates and deletions)
22
+ */
23
+ async processOperations(data, keyType, transactionCache, mutations, isInTransaction) {
24
+ const keyData = data[keyType];
25
+ if (!keyData)
26
+ return;
27
+ return this.getQueue(keyType).add(async () => {
28
+ // Ensure structures exist
29
+ transactionCache[keyType] = transactionCache[keyType] || {};
30
+ mutations[keyType] = mutations[keyType] || {};
31
+ // Separate deletions from updates
32
+ const deletions = [];
33
+ const updates = {};
34
+ for (const keyId in keyData) {
35
+ if (keyData[keyId] === null) {
36
+ deletions.push(keyId);
37
+ }
38
+ else {
39
+ updates[keyId] = keyData[keyId];
40
+ }
41
+ }
42
+ // Process updates (no validation needed)
43
+ if (Object.keys(updates).length > 0) {
44
+ Object.assign(transactionCache[keyType], updates);
45
+ Object.assign(mutations[keyType], updates);
46
+ }
47
+ // Process deletions with validation
48
+ if (deletions.length > 0) {
49
+ await this.processDeletions(keyType, deletions, transactionCache, mutations, isInTransaction);
50
+ }
51
+ });
52
+ }
53
+ /**
54
+ * Process deletions with validation
55
+ */
56
+ async processDeletions(keyType, ids, transactionCache, mutations, isInTransaction) {
57
+ if (isInTransaction) {
58
+ // In transaction, only allow deletion if key exists in cache
59
+ for (const keyId of ids) {
60
+ if (transactionCache[keyType]?.[keyId]) {
61
+ transactionCache[keyType][keyId] = null;
62
+ mutations[keyType][keyId] = null;
63
+ }
64
+ else {
65
+ this.logger.warn(`Skipping deletion of non-existent ${keyType} in transaction: ${keyId}`);
66
+ }
67
+ }
68
+ }
69
+ else {
70
+ // Outside transaction, validate against store
71
+ const existingKeys = await this.store.get(keyType, ids);
72
+ for (const keyId of ids) {
73
+ if (existingKeys[keyId]) {
74
+ transactionCache[keyType][keyId] = null;
75
+ mutations[keyType][keyId] = null;
76
+ }
77
+ else {
78
+ this.logger.warn(`Skipping deletion of non-existent ${keyType}: ${keyId}`);
79
+ }
80
+ }
81
+ }
82
+ }
83
+ /**
84
+ * Validate and process pre-key deletions outside transactions
85
+ */
86
+ async validateDeletions(data, keyType) {
87
+ const keyData = data[keyType];
88
+ if (!keyData)
89
+ return;
90
+ return this.getQueue(keyType).add(async () => {
91
+ // Find all deletion requests
92
+ const deletionIds = Object.keys(keyData).filter(id => keyData[id] === null);
93
+ if (deletionIds.length === 0)
94
+ return;
95
+ // Validate deletions
96
+ const existingKeys = await this.store.get(keyType, deletionIds);
97
+ for (const keyId of deletionIds) {
98
+ if (!existingKeys[keyId]) {
99
+ this.logger.warn(`Skipping deletion of non-existent ${keyType}: ${keyId}`);
100
+ delete data[keyType][keyId];
101
+ }
102
+ }
103
+ });
104
+ }
105
+ }
@@ -0,0 +1,10 @@
1
+ export function useMultiFileAuthState(folder: 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<any>;
10
+ }>;
@@ -0,0 +1,116 @@
1
+ import { mkdir, open, readFile, rename, unlink } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { proto } from '../../../WAProto/index.js';
4
+ import { createMutex } from '../../Addon/index.js';
5
+ import { initAuthCreds } from './auth-utils.js';
6
+ import { BufferJSON } from '../Common/generics.js';
7
+ // Refactored useMultiFileAuthState with atomic writes and per-file mutex for better stability and RAM consumption
8
+ const WRITE_BATCH = 32;
9
+ const locks = new Map();
10
+ const noop = () => { };
11
+ const withLock = async (path, fn) => {
12
+ let entry = locks.get(path);
13
+ if (!entry)
14
+ locks.set(path, entry = { mutex: createMutex(), refs: 0 });
15
+ entry.refs++;
16
+ try {
17
+ return await entry.mutex.runExclusive(fn);
18
+ }
19
+ finally {
20
+ if (!--entry.refs)
21
+ locks.delete(path);
22
+ }
23
+ };
24
+ const writeAtomic = async (path, json, durable) => {
25
+ const tmp = path + '.tmp';
26
+ const fh = await open(tmp, 'w');
27
+ try {
28
+ await fh.writeFile(json);
29
+ if (durable)
30
+ await fh.datasync();
31
+ }
32
+ finally {
33
+ await fh.close();
34
+ }
35
+ await rename(tmp, path);
36
+ };
37
+ const readJson = (path, quarantine) => withLock(path, async () => {
38
+ let raw;
39
+ try {
40
+ raw = await readFile(path, 'utf-8');
41
+ }
42
+ catch (err) {
43
+ if (err.code === 'ENOENT')
44
+ return null;
45
+ throw err;
46
+ }
47
+ try {
48
+ return JSON.parse(raw, BufferJSON.reviver);
49
+ }
50
+ catch {
51
+ if (quarantine)
52
+ await rename(path, path + '.corrupt').catch(noop);
53
+ return null;
54
+ }
55
+ });
56
+ const fixFileName = (file) => file.replace(/\//g, '__').replace(/:/g, '-');
57
+ export const useMultiFileAuthState = async (folder) => {
58
+ try {
59
+ await mkdir(folder, { recursive: true });
60
+ }
61
+ catch (err) {
62
+ if (err.code === 'EEXIST' || err.code === 'ENOTDIR')
63
+ throw new Error(`Found something that is not a directory at ${folder}, either delete it or specify a different location`);
64
+ throw err;
65
+ }
66
+ const pathOf = (file) => join(folder, fixFileName(file));
67
+ const credsPath = pathOf('creds.json');
68
+ const creds = await readJson(credsPath, true) ?? initAuthCreds();
69
+ let lastCreds;
70
+ return {
71
+ state: {
72
+ creds,
73
+ keys: {
74
+ get: async (type, ids) => {
75
+ const data = {};
76
+ await Promise.all(ids.map(async (id) => {
77
+ let value = await readJson(pathOf(`${type}-${id}.json`));
78
+ if (type === 'app-state-sync-key' && value) {
79
+ value = proto.Message.AppStateSyncKeyData.fromObject(value);
80
+ }
81
+ data[id] = value;
82
+ }));
83
+ return data;
84
+ },
85
+ set: async (data) => {
86
+ const tasks = [];
87
+ for (const category in data) {
88
+ const items = data[category];
89
+ for (const id in items) {
90
+ const value = items[id];
91
+ const path = pathOf(`${category}-${id}.json`);
92
+ tasks.push(value
93
+ ? () => withLock(path, () => writeAtomic(path, JSON.stringify(value, BufferJSON.replacer), false))
94
+ : () => withLock(path, () => unlink(path).catch((err) => {
95
+ if (err.code !== 'ENOENT')
96
+ throw err;
97
+ })));
98
+ }
99
+ }
100
+ for (let i = 0; i < tasks.length; i += WRITE_BATCH) {
101
+ await Promise.all(tasks.slice(i, i + WRITE_BATCH).map((run) => run()));
102
+ }
103
+ }
104
+ }
105
+ },
106
+ saveCreds: () => {
107
+ const json = JSON.stringify(creds, BufferJSON.replacer);
108
+ if (json === lastCreds)
109
+ return Promise.resolve();
110
+ return withLock(credsPath, async () => {
111
+ await writeAtomic(credsPath, json, true);
112
+ lastCreds = json;
113
+ });
114
+ }
115
+ };
116
+ };
@@ -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: () => any;
10
+ flush: () => any;
11
+ }>;
@@ -0,0 +1,94 @@
1
+ import { readFile, rename, open } from 'node:fs/promises';
2
+ import { proto } from '../../../WAProto/index.js';
3
+ import { createMutex } from '../../Addon/index.js';
4
+ import { initAuthCreds } from './auth-utils.js';
5
+ import { BufferJSON } from '../Common/generics.js';
6
+ // Refactored useSingleFileAuthState with debounced atomic flush and shared mutex for better stability and RAM consumption
7
+ const FLUSH_DELAY_MS = 3000;
8
+ const files = new Map();
9
+ export const useSingleFileAuthState = async (fileName) => {
10
+ let shared = files.get(fileName);
11
+ if (!shared)
12
+ files.set(fileName, shared = { mutex: createMutex(), flush: null });
13
+ const { mutex } = shared;
14
+ await shared.flush?.();
15
+ const tempFile = fileName + '.temp';
16
+ const store = Object.create(null);
17
+ let ver = 0, saved = 0, timer = null;
18
+ await mutex.runExclusive(async () => {
19
+ try {
20
+ Object.assign(store, JSON.parse(await readFile(fileName, 'utf-8'), BufferJSON.reviver));
21
+ }
22
+ catch (err) {
23
+ if (err.code === 'EISDIR')
24
+ throw new Error(`found something that is not a file at ${fileName}, either delete it or specify a different location`);
25
+ if (err.code !== 'ENOENT')
26
+ await rename(fileName, fileName + '.corrupt').catch(() => { });
27
+ }
28
+ });
29
+ const flush = () => {
30
+ clearTimeout(timer);
31
+ timer = null;
32
+ return mutex.runExclusive(async () => {
33
+ if (ver === saved)
34
+ return;
35
+ const v = ver;
36
+ try {
37
+ const fh = await open(tempFile, 'w');
38
+ try {
39
+ await fh.writeFile(JSON.stringify(store, BufferJSON.replacer));
40
+ await fh.datasync();
41
+ }
42
+ finally {
43
+ await fh.close();
44
+ }
45
+ await rename(tempFile, fileName);
46
+ saved = v;
47
+ }
48
+ catch {
49
+ schedule();
50
+ }
51
+ });
52
+ };
53
+ const schedule = () => {
54
+ timer ?? (timer = setTimeout(flush, FLUSH_DELAY_MS));
55
+ };
56
+ shared.flush = flush;
57
+ const creds = store.creds ?? (store.creds = initAuthCreds());
58
+ return {
59
+ state: {
60
+ creds,
61
+ keys: {
62
+ get: (type, ids) => {
63
+ const data = {};
64
+ for (const id of ids) {
65
+ const value = store[type + id];
66
+ data[id] = value && type === 'app-state-sync-key'
67
+ ? proto.Message.AppStateSyncKeyData.fromObject(value)
68
+ : value;
69
+ }
70
+ return data;
71
+ },
72
+ set: (data) => {
73
+ for (const type in data) {
74
+ const items = data[type];
75
+ for (const id in items) {
76
+ const value = items[id];
77
+ if (value)
78
+ store[type + id] = value;
79
+ else
80
+ delete store[type + id];
81
+ }
82
+ }
83
+ ver++;
84
+ schedule();
85
+ }
86
+ }
87
+ },
88
+ saveCreds: () => {
89
+ ver++;
90
+ return flush();
91
+ },
92
+ flush
93
+ };
94
+ };
@@ -0,0 +1,11 @@
1
+ export function useSqliteAuthState(dbPath: any, ownedDatabase: 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
+ close: () => any;
11
+ }>;
@@ -0,0 +1,109 @@
1
+ import { proto } from '../../../WAProto/index.js';
2
+ import { initAuthCreds } from './auth-utils.js';
3
+ import { BufferJSON } from '../Common/generics.js';
4
+ // Refactored useSqliteAuthState to use bun:sqlite, node:sqlite and better-sqlite3 with synchronous prepared statements
5
+ const CREDS_KEY = '__creds__';
6
+ const SCHEMA = `
7
+ PRAGMA busy_timeout = 5000;
8
+ PRAGMA journal_mode = WAL;
9
+ PRAGMA synchronous = NORMAL;
10
+ CREATE TABLE IF NOT EXISTS creds (
11
+ key TEXT PRIMARY KEY,
12
+ value TEXT NOT NULL
13
+ ) WITHOUT ROWID;
14
+ CREATE TABLE IF NOT EXISTS signal_keys (
15
+ type TEXT NOT NULL,
16
+ id TEXT NOT NULL,
17
+ value TEXT NOT NULL,
18
+ PRIMARY KEY (type, id)
19
+ ) WITHOUT ROWID;
20
+ DROP INDEX IF EXISTS signal_keys_type_idx;
21
+ `;
22
+ const loadDriver = async () => {
23
+ if (process.versions.bun)
24
+ return (await import('bun:sqlite')).Database;
25
+ try {
26
+ return (await import('node:sqlite')).DatabaseSync;
27
+ }
28
+ catch { }
29
+ try {
30
+ const mod = await import('better-sqlite3');
31
+ return mod.default ?? mod;
32
+ }
33
+ catch (cause) {
34
+ throw new Error('No SQLite driver found. Use Bun, Node >= 22.13, or install "better-sqlite3".', { cause });
35
+ }
36
+ };
37
+ export async function useSqliteAuthState(dbPath, ownedDatabase) {
38
+ const owned = !ownedDatabase;
39
+ let db = ownedDatabase;
40
+ if (owned) {
41
+ const Database = await loadDriver();
42
+ db = new Database(dbPath);
43
+ }
44
+ db.exec(SCHEMA);
45
+ const acts = {
46
+ credsGet: db.prepare('SELECT value FROM creds WHERE key = ?'),
47
+ credsSet: db.prepare('INSERT OR REPLACE INTO creds (key, value) VALUES (?, ?)'),
48
+ keyGet: db.prepare('SELECT value FROM signal_keys WHERE type = ? AND id = ?'),
49
+ keySet: db.prepare('INSERT OR REPLACE INTO signal_keys (type, id, value) VALUES (?, ?, ?)'),
50
+ keyDel: db.prepare('DELETE FROM signal_keys WHERE type = ? AND id = ?'),
51
+ begin: db.prepare('BEGIN IMMEDIATE'),
52
+ commit: db.prepare('COMMIT'),
53
+ rollback: db.prepare('ROLLBACK')
54
+ };
55
+ const row = acts.credsGet.get(CREDS_KEY);
56
+ const creds = row ? JSON.parse(row.value, BufferJSON.reviver) : initAuthCreds();
57
+ let lastCreds = row?.value;
58
+ return {
59
+ state: {
60
+ creds,
61
+ keys: {
62
+ get: (type, ids) => {
63
+ const data = {};
64
+ for (const id of ids) {
65
+ const r = acts.keyGet.get(type, id);
66
+ if (!r)
67
+ continue;
68
+ const value = JSON.parse(r.value, BufferJSON.reviver);
69
+ data[id] = type === 'app-state-sync-key'
70
+ ? proto.Message.AppStateSyncKeyData.fromObject(value)
71
+ : value;
72
+ }
73
+ return data;
74
+ },
75
+ set: (data) => {
76
+ acts.begin.run();
77
+ try {
78
+ for (const type in data) {
79
+ const items = data[type];
80
+ for (const id in items) {
81
+ const value = items[id];
82
+ if (value)
83
+ acts.keySet.run(type, id, JSON.stringify(value, BufferJSON.replacer));
84
+ else
85
+ acts.keyDel.run(type, id);
86
+ }
87
+ }
88
+ acts.commit.run();
89
+ }
90
+ catch (err) {
91
+ try {
92
+ acts.rollback.run();
93
+ }
94
+ catch { }
95
+ throw err;
96
+ }
97
+ }
98
+ }
99
+ },
100
+ saveCreds: () => {
101
+ const json = JSON.stringify(creds, BufferJSON.replacer);
102
+ if (json === lastCreds)
103
+ return;
104
+ acts.credsSet.run(CREDS_KEY, json);
105
+ lastCreds = json;
106
+ },
107
+ close: () => owned && db.close()
108
+ };
109
+ }
@@ -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 & proto.ADVSignedDeviceIdentity.$Properties;
14
+ me: {
15
+ id: any;
16
+ name: any;
17
+ lid: any;
18
+ };
19
+ signalIdentities: any[];
20
+ platform: any;
21
+ registered: boolean;
22
+ };
23
+ reply: {
24
+ tag: string;
25
+ attrs: {
26
+ to: string;
27
+ type: string;
28
+ id: any;
29
+ };
30
+ content: {
31
+ tag: string;
32
+ attrs: {};
33
+ content: {
34
+ tag: string;
35
+ attrs: {
36
+ 'key-index': string;
37
+ };
38
+ content: Uint8Array<ArrayBufferLike>;
39
+ }[];
40
+ }[];
41
+ };
42
+ };
43
+ export function encodeSignedDeviceIdentity(account: any, includeSignatureKey: any): Uint8Array<ArrayBufferLike>;
44
+ import { proto } from '../../../WAProto/index.js';