@rizzxdc/baileys 8.0.10 → 8.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 (220) hide show
  1. package/LICENSE +4 -2
  2. package/README.md +107 -245
  3. package/WAProto/index.d.ts +15795 -0
  4. package/WAProto/index.js +25587 -4867
  5. package/lib/Defaults/index.d.ts +147 -0
  6. package/lib/Defaults/index.js +134 -104
  7. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  8. package/lib/Signal/Group/ciphertext-message.js +9 -11
  9. package/lib/Signal/Group/group-session-builder.d.ts +8 -0
  10. package/lib/Signal/Group/group-session-builder.js +5 -8
  11. package/lib/Signal/Group/group_cipher.d.ts +11 -0
  12. package/lib/Signal/Group/group_cipher.js +72 -75
  13. package/lib/Signal/Group/index.d.ts +12 -0
  14. package/lib/Signal/Group/index.js +11 -13
  15. package/lib/Signal/Group/keyhelper.d.ts +7 -0
  16. package/lib/Signal/Group/keyhelper.js +11 -14
  17. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  18. package/lib/Signal/Group/sender-chain-key.js +23 -26
  19. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  20. package/lib/Signal/Group/sender-key-distribution-message.js +58 -61
  21. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  22. package/lib/Signal/Group/sender-key-message.js +61 -64
  23. package/lib/Signal/Group/sender-key-name.d.ts +12 -0
  24. package/lib/Signal/Group/sender-key-name.js +39 -44
  25. package/lib/Signal/Group/sender-key-record.d.ts +13 -0
  26. package/lib/Signal/Group/sender-key-record.js +35 -38
  27. package/lib/Signal/Group/sender-key-state.d.ts +17 -0
  28. package/lib/Signal/Group/sender-key-state.js +76 -79
  29. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  30. package/lib/Signal/Group/sender-message-key.js +23 -26
  31. package/lib/Signal/libsignal.d.ts +55 -0
  32. package/lib/Signal/libsignal.js +414 -308
  33. package/lib/Signal/lid-mapping.d.ts +21 -0
  34. package/lib/Signal/lid-mapping.js +270 -149
  35. package/lib/Socket/Client/index.d.ts +3 -0
  36. package/lib/Socket/Client/index.js +2 -4
  37. package/lib/Socket/Client/types.d.ts +6 -0
  38. package/lib/Socket/Client/types.js +8 -11
  39. package/lib/Socket/Client/websocket.d.ts +13 -0
  40. package/lib/Socket/Client/websocket.js +51 -50
  41. package/lib/Socket/business.d.ts +395 -0
  42. package/lib/Socket/business.js +357 -355
  43. package/lib/Socket/chats.d.ts +137 -0
  44. package/lib/Socket/chats.js +1195 -867
  45. package/lib/Socket/communities.d.ts +562 -0
  46. package/lib/Socket/communities.js +416 -398
  47. package/lib/Socket/dugong.js +8 -1
  48. package/lib/Socket/groups.d.ts +286 -0
  49. package/lib/Socket/groups.js +336 -301
  50. package/lib/Socket/index.d.ts +530 -0
  51. package/lib/Socket/index.js +8 -13
  52. package/lib/Socket/messages-recv.d.ts +334 -0
  53. package/lib/Socket/messages-recv.js +1729 -1121
  54. package/lib/Socket/messages-send.d.ts +330 -0
  55. package/lib/Socket/messages-send.js +684 -462
  56. package/lib/Socket/mex.d.ts +2 -0
  57. package/lib/Socket/mex.js +36 -40
  58. package/lib/Socket/newsletter.d.ts +284 -0
  59. package/lib/Socket/newsletter.js +247 -237
  60. package/lib/Socket/socket.d.ts +61 -0
  61. package/lib/Socket/socket.js +968 -790
  62. package/lib/Store/index.d.ts +4 -0
  63. package/lib/Store/index.js +4 -6
  64. package/lib/Store/make-cache-manager-store.js +2 -2
  65. package/lib/Store/make-in-memory-store.d.ts +63 -0
  66. package/lib/Store/make-in-memory-store.js +414 -284
  67. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  68. package/lib/Store/make-ordered-dictionary.js +75 -76
  69. package/lib/Store/object-repository.d.ts +11 -0
  70. package/lib/Store/object-repository.js +21 -23
  71. package/lib/Types/Auth.d.ts +2 -0
  72. package/lib/Types/Auth.js +0 -2
  73. package/lib/Types/Bussines.d.ts +2 -0
  74. package/lib/Types/Bussines.js +0 -2
  75. package/lib/Types/Call.d.ts +2 -0
  76. package/lib/Types/Call.js +0 -2
  77. package/lib/Types/Chat.d.ts +2 -0
  78. package/lib/Types/Chat.js +5 -7
  79. package/lib/Types/Contact.d.ts +2 -0
  80. package/lib/Types/Contact.js +0 -2
  81. package/lib/Types/Events.d.ts +2 -0
  82. package/lib/Types/Events.js +1 -3
  83. package/lib/Types/GroupMetadata.d.ts +2 -0
  84. package/lib/Types/GroupMetadata.js +0 -2
  85. package/lib/Types/Label.d.ts +3 -0
  86. package/lib/Types/Label.js +21 -22
  87. package/lib/Types/LabelAssociation.d.ts +3 -0
  88. package/lib/Types/LabelAssociation.js +3 -4
  89. package/lib/Types/Message.d.ts +12 -0
  90. package/lib/Types/Message.js +11 -6
  91. package/lib/Types/Mex.d.ts +3 -0
  92. package/lib/Types/Mex.js +38 -0
  93. package/lib/Types/Product.d.ts +2 -0
  94. package/lib/Types/Product.js +0 -2
  95. package/lib/Types/RichType.d.ts +3 -0
  96. package/lib/Types/RichType.js +22 -0
  97. package/lib/Types/Signal.d.ts +2 -0
  98. package/lib/Types/Signal.js +1 -3
  99. package/lib/Types/Socket.d.ts +2 -0
  100. package/lib/Types/Socket.js +1 -4
  101. package/lib/Types/State.d.ts +6 -0
  102. package/lib/Types/State.js +52 -8
  103. package/lib/Types/USync.d.ts +2 -0
  104. package/lib/Types/USync.js +1 -3
  105. package/lib/Types/index.d.ts +14 -0
  106. package/lib/Types/index.js +22 -25
  107. package/lib/Utils/auth-utils.d.ts +58 -0
  108. package/lib/Utils/auth-utils.js +285 -203
  109. package/lib/Utils/browser-utils.d.ts +9 -0
  110. package/lib/Utils/browser-utils.js +21 -19
  111. package/lib/Utils/business.d.ts +50 -0
  112. package/lib/Utils/business.js +206 -209
  113. package/lib/Utils/chat-utils.d.ts +409 -0
  114. package/lib/Utils/chat-utils.js +825 -706
  115. package/lib/Utils/companion-reg-client-utils.d.ts +5 -0
  116. package/lib/Utils/companion-reg-client-utils.js +39 -0
  117. package/lib/Utils/crypto.d.ts +40 -0
  118. package/lib/Utils/crypto.js +88 -101
  119. package/lib/Utils/decode-wa-message.d.ts +84 -0
  120. package/lib/Utils/decode-wa-message.js +287 -238
  121. package/lib/Utils/event-buffer.d.ts +13 -0
  122. package/lib/Utils/event-buffer.js +602 -509
  123. package/lib/Utils/generics.d.ts +64 -0
  124. package/lib/Utils/generics.js +334 -295
  125. package/lib/Utils/history.d.ts +76 -0
  126. package/lib/Utils/history.js +125 -79
  127. package/lib/Utils/identity-change-handler.d.ts +14 -0
  128. package/lib/Utils/identity-change-handler.js +49 -0
  129. package/lib/Utils/index.d.ts +25 -0
  130. package/lib/Utils/index.js +25 -21
  131. package/lib/Utils/link-preview.d.ts +13 -0
  132. package/lib/Utils/link-preview.js +73 -70
  133. package/lib/Utils/logger.d.ts +3 -0
  134. package/lib/Utils/logger.js +1 -4
  135. package/lib/Utils/lt-hash.d.ts +7 -0
  136. package/lib/Utils/lt-hash.js +7 -45
  137. package/lib/Utils/make-mutex.d.ts +7 -0
  138. package/lib/Utils/make-mutex.js +27 -31
  139. package/lib/Utils/message-retry-manager.d.ts +80 -0
  140. package/lib/Utils/message-retry-manager.js +165 -14
  141. package/lib/Utils/messages-media.d.ts +137 -0
  142. package/lib/Utils/messages-media.js +768 -572
  143. package/lib/Utils/messages.d.ts +46 -0
  144. package/lib/Utils/messages.js +1082 -130
  145. package/lib/Utils/noise-handler.d.ts +21 -0
  146. package/lib/Utils/noise-handler.js +191 -135
  147. package/lib/Utils/offline-node-processor.d.ts +10 -0
  148. package/lib/Utils/offline-node-processor.js +39 -0
  149. package/lib/Utils/pre-key-manager.d.ts +26 -0
  150. package/lib/Utils/pre-key-manager.js +96 -76
  151. package/lib/Utils/process-message.d.ts +84 -0
  152. package/lib/Utils/process-message.js +718 -311
  153. package/lib/Utils/reporting-utils.d.ts +13 -0
  154. package/lib/Utils/reporting-utils.js +257 -0
  155. package/lib/Utils/rich-message-utils.d.ts +49 -0
  156. package/lib/Utils/rich-message-utils.js +257 -0
  157. package/lib/Utils/signal.d.ts +83 -0
  158. package/lib/Utils/signal.js +174 -135
  159. package/lib/Utils/stanza-ack.d.ts +17 -0
  160. package/lib/Utils/stanza-ack.js +37 -0
  161. package/lib/Utils/sync-action-utils.d.ts +3 -0
  162. package/lib/Utils/sync-action-utils.js +48 -0
  163. package/lib/Utils/tc-token-utils.d.ts +30 -0
  164. package/lib/Utils/tc-token-utils.js +162 -0
  165. package/lib/Utils/use-multi-file-auth-state.d.ts +11 -0
  166. package/lib/Utils/use-multi-file-auth-state.js +104 -95
  167. package/lib/Utils/use-single-file-auth-state.d.ts +11 -0
  168. package/lib/Utils/use-single-file-auth-state.js +108 -0
  169. package/lib/Utils/use-sqlite-auth-state.d.ts +11 -0
  170. package/lib/Utils/use-sqlite-auth-state.js +108 -0
  171. package/lib/Utils/validate-connection.d.ts +44 -0
  172. package/lib/Utils/validate-connection.js +182 -180
  173. package/lib/WABinary/constants.d.ts +62 -0
  174. package/lib/WABinary/constants.js +1455 -1292
  175. package/lib/WABinary/decode.d.ts +10 -0
  176. package/lib/WABinary/decode.js +249 -228
  177. package/lib/WABinary/encode.d.ts +3 -0
  178. package/lib/WABinary/encode.js +207 -206
  179. package/lib/WABinary/generic-utils.d.ts +77 -0
  180. package/lib/WABinary/generic-utils.js +135 -99
  181. package/lib/WABinary/index.d.ts +6 -0
  182. package/lib/WABinary/index.js +5 -7
  183. package/lib/WABinary/jid-utils.d.ts +29 -0
  184. package/lib/WABinary/jid-utils.js +80 -78
  185. package/lib/WABinary/types.d.ts +2 -0
  186. package/lib/WABinary/types.js +1 -3
  187. package/lib/WAM/BinaryInfo.d.ts +8 -0
  188. package/lib/WAM/BinaryInfo.js +7 -9
  189. package/lib/WAM/constants.d.ts +34927 -0
  190. package/lib/WAM/constants.js +22847 -22848
  191. package/lib/WAM/encode.d.ts +2 -0
  192. package/lib/WAM/encode.js +129 -134
  193. package/lib/WAM/index.d.ts +4 -0
  194. package/lib/WAM/index.js +3 -5
  195. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +37 -0
  196. package/lib/WAUSync/Protocols/USyncContactProtocol.js +48 -27
  197. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  198. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +48 -48
  199. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  200. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +23 -26
  201. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  202. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +33 -35
  203. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
  204. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  205. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +39 -0
  206. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +46 -49
  207. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +15 -0
  208. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +23 -25
  209. package/lib/WAUSync/Protocols/index.d.ts +6 -0
  210. package/lib/WAUSync/Protocols/index.js +5 -6
  211. package/lib/WAUSync/USyncQuery.d.ts +21 -0
  212. package/lib/WAUSync/USyncQuery.js +92 -85
  213. package/lib/WAUSync/USyncUser.d.ts +17 -0
  214. package/lib/WAUSync/USyncUser.js +28 -22
  215. package/lib/WAUSync/index.d.ts +4 -0
  216. package/lib/WAUSync/index.js +3 -5
  217. package/lib/index.d.ts +12 -0
  218. package/lib/index.js +31 -19
  219. package/package.json +12 -6
  220. package/lib/Types/Newsletter.js +0 -33
@@ -1,28 +1,25 @@
1
- //=======================================================//
2
- export * from "./GroupMetadata.js";
3
- export * from "./Newsletter.js";
4
- export * from "./Contact.js";
5
- export * from "./Message.js";
6
- export * from "./Product.js";
7
- export * from "./Socket.js";
8
- export * from "./Events.js";
9
- export * from "./Signal.js";
10
- export * from "./State.js";
11
- export * from "./Chat.js";
12
- export * from "./Call.js";
13
- export * from "./Auth.js";
14
- //=======================================================//
1
+ export * from './Auth.js';
2
+ export * from './GroupMetadata.js';
3
+ export * from './Chat.js';
4
+ export * from './Contact.js';
5
+ export * from './State.js';
6
+ export * from './Message.js';
7
+ export * from './Socket.js';
8
+ export * from './Events.js';
9
+ export * from './Product.js';
10
+ export * from './Call.js';
11
+ export * from './Signal.js';
12
+ export * from './Mex.js';
15
13
  export var DisconnectReason;
16
14
  (function (DisconnectReason) {
17
- DisconnectReason[DisconnectReason["connectionClosed"] = 428] = "connectionClosed";
18
- DisconnectReason[DisconnectReason["connectionLost"] = 408] = "connectionLost";
19
- DisconnectReason[DisconnectReason["connectionReplaced"] = 440] = "connectionReplaced";
20
- DisconnectReason[DisconnectReason["timedOut"] = 408] = "timedOut";
21
- DisconnectReason[DisconnectReason["loggedOut"] = 401] = "loggedOut";
22
- DisconnectReason[DisconnectReason["badSession"] = 500] = "badSession";
23
- DisconnectReason[DisconnectReason["restartRequired"] = 515] = "restartRequired";
24
- DisconnectReason[DisconnectReason["multideviceMismatch"] = 411] = "multideviceMismatch";
25
- DisconnectReason[DisconnectReason["forbidden"] = 403] = "forbidden";
26
- DisconnectReason[DisconnectReason["unavailableService"] = 503] = "unavailableService";
15
+ DisconnectReason[DisconnectReason["connectionClosed"] = 428] = "connectionClosed";
16
+ DisconnectReason[DisconnectReason["connectionLost"] = 408] = "connectionLost";
17
+ DisconnectReason[DisconnectReason["connectionReplaced"] = 440] = "connectionReplaced";
18
+ DisconnectReason[DisconnectReason["timedOut"] = 408] = "timedOut";
19
+ DisconnectReason[DisconnectReason["loggedOut"] = 401] = "loggedOut";
20
+ DisconnectReason[DisconnectReason["badSession"] = 500] = "badSession";
21
+ DisconnectReason[DisconnectReason["restartRequired"] = 515] = "restartRequired";
22
+ DisconnectReason[DisconnectReason["multideviceMismatch"] = 411] = "multideviceMismatch";
23
+ DisconnectReason[DisconnectReason["forbidden"] = 403] = "forbidden";
24
+ DisconnectReason[DisconnectReason["unavailableService"] = 503] = "unavailableService";
27
25
  })(DisconnectReason || (DisconnectReason = {}));
28
- //=======================================================//
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Adds caching capability to a SignalKeyStore
3
+ * @param store the store to add caching to
4
+ * @param logger to log trace events
5
+ * @param _cache cache store to use
6
+ */
7
+ export function makeCacheableSignalKeyStore(store: any, logger: any, _cache: any): {
8
+ get(type: any, ids: any): Promise<any>;
9
+ set(data: any): Promise<any>;
10
+ clear(): Promise<void>;
11
+ };
12
+ export function addTransactionCapability(state: any, logger: any, { maxCommitRetries, delayBetweenTriesMs }: {
13
+ maxCommitRetries: any;
14
+ delayBetweenTriesMs: any;
15
+ }): {
16
+ get: (type: any, ids: any) => Promise<any>;
17
+ set: (data: any) => Promise<void>;
18
+ isInTransaction: () => boolean;
19
+ transaction: (work: any, key: any) => Promise<any>;
20
+ };
21
+ export function assertMeId(creds: any): any;
22
+ export function initAuthCreds(): {
23
+ noiseKey: {
24
+ private: any;
25
+ public: any;
26
+ };
27
+ pairingEphemeralKeyPair: {
28
+ private: any;
29
+ public: any;
30
+ };
31
+ signedIdentityKey: {
32
+ private: any;
33
+ public: any;
34
+ };
35
+ signedPreKey: {
36
+ keyPair: {
37
+ private: any;
38
+ public: any;
39
+ };
40
+ signature: any;
41
+ keyId: any;
42
+ };
43
+ registrationId: number;
44
+ advSecretKey: any;
45
+ processedHistoryMessages: never[];
46
+ nextPreKeyId: number;
47
+ firstUnuploadedPreKeyId: number;
48
+ accountSyncCounter: number;
49
+ accountSettings: {
50
+ unarchiveChats: boolean;
51
+ };
52
+ registered: boolean;
53
+ pairingCode: undefined;
54
+ lastPropHash: undefined;
55
+ routingInfo: undefined;
56
+ additionalData: undefined;
57
+ };
58
+ //# sourceMappingURL=auth-utils.d.ts.map
@@ -1,219 +1,301 @@
1
- //=======================================================//
2
- import { delay, generateRegistrationId } from "./generics.js";
3
- import { DEFAULT_CACHE_TTLS } from "../Defaults/index.js";
4
- import { PreKeyManager } from "./pre-key-manager.js";
5
- import { Curve, signedKeyPair } from "./crypto.js";
6
- import { AsyncLocalStorage } from "async_hooks";
7
- import NodeCache from "@cacheable/node-cache";
8
- import { randomBytes } from "crypto";
9
- import { Mutex } from "async-mutex";
10
- import PQueue from "p-queue";
11
- //=======================================================//
1
+ import NodeCache from '@cacheable/node-cache';
2
+ import { Boom } from '@hapi/boom';
3
+ import { AsyncLocalStorage } from 'async_hooks';
4
+ import { Mutex } from 'async-mutex';
5
+ import { randomBytes } from 'crypto';
6
+ import PQueue from 'p-queue';
7
+ import { DEFAULT_CACHE_TTLS } from '../Defaults/index.js';
8
+ import { Curve, signedKeyPair } from './crypto.js';
9
+ import { delay, generateRegistrationId } from './generics.js';
10
+ import { PreKeyManager } from './pre-key-manager.js';
11
+ /**
12
+ * Adds caching capability to a SignalKeyStore
13
+ * @param store the store to add caching to
14
+ * @param logger to log trace events
15
+ * @param _cache cache store to use
16
+ */
12
17
  export function makeCacheableSignalKeyStore(store, logger, _cache) {
13
- const cache = _cache ||
14
- new NodeCache({
15
- stdTTL: DEFAULT_CACHE_TTLS.SIGNAL_STORE,
16
- useClones: false,
17
- deleteOnExpire: true
18
- });
19
- const cacheMutex = new Mutex();
20
- function getUniqueId(type, id) {
21
- return `${type}.${id}`;
22
- }
23
- return {
24
- async get(type, ids) {
25
- return cacheMutex.runExclusive(async () => {
26
- const data = {};
27
- const idsToFetch = [];
28
- for (const id of ids) {
29
- const item = (await cache.get(getUniqueId(type, id)));
30
- if (typeof item !== "undefined") {
31
- data[id] = item;
32
- }
33
- else {
34
- idsToFetch.push(id);
35
- }
36
- }
37
- if (idsToFetch.length) {
38
- logger?.trace({ items: idsToFetch.length }, "loading from store");
39
- const fetched = await store.get(type, idsToFetch);
40
- for (const id of idsToFetch) {
41
- const item = fetched[id];
42
- if (item) {
43
- data[id] = item;
44
- cache.set(getUniqueId(type, id), item);
45
- }
46
- }
47
- }
48
- return data;
49
- });
50
- },
51
- async set(data) {
52
- return cacheMutex.runExclusive(async () => {
53
- let keys = 0;
54
- for (const type in data) {
55
- for (const id in data[type]) {
56
- await cache.set(getUniqueId(type, id), data[type][id]);
57
- keys += 1;
58
- }
59
- }
60
- logger?.trace({ keys }, "updated cache");
61
- await store.set(data);
62
- });
63
- },
64
- async clear() {
65
- await cache.flushAll();
66
- await store.clear?.();
18
+ const cache = _cache ||
19
+ new NodeCache({
20
+ stdTTL: DEFAULT_CACHE_TTLS.SIGNAL_STORE, // 5 minutes
21
+ useClones: false,
22
+ deleteOnExpire: true
23
+ });
24
+ // Mutex for protecting cache operations
25
+ const cacheMutex = new Mutex();
26
+ function getUniqueId(type, id) {
27
+ return `${type}.${id}`;
67
28
  }
68
- };
29
+ return {
30
+ async get(type, ids) {
31
+ return cacheMutex.runExclusive(async () => {
32
+ const data = {};
33
+ const idsToFetch = [];
34
+ for (const id of ids) {
35
+ const item = (await cache.get(getUniqueId(type, id)));
36
+ if (typeof item !== 'undefined') {
37
+ data[id] = item;
38
+ }
39
+ else {
40
+ idsToFetch.push(id);
41
+ }
42
+ }
43
+ if (idsToFetch.length) {
44
+ logger?.trace({ items: idsToFetch.length }, 'loading from store');
45
+ const fetched = await store.get(type, idsToFetch);
46
+ for (const id of idsToFetch) {
47
+ const item = fetched[id];
48
+ if (item) {
49
+ data[id] = item;
50
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
51
+ await cache.set(getUniqueId(type, id), item);
52
+ }
53
+ }
54
+ }
55
+ return data;
56
+ });
57
+ },
58
+ async set(data) {
59
+ return cacheMutex.runExclusive(async () => {
60
+ let keys = 0;
61
+ for (const type in data) {
62
+ for (const id in data[type]) {
63
+ await cache.set(getUniqueId(type, id), data[type][id]);
64
+ keys += 1;
65
+ }
66
+ }
67
+ logger?.trace({ keys }, 'updated cache');
68
+ await store.set(data);
69
+ });
70
+ },
71
+ async clear() {
72
+ await cache.flushAll();
73
+ await store.clear?.();
74
+ }
75
+ };
69
76
  }
70
- //=======================================================//
77
+ /**
78
+ * Adds DB-like transaction capability to the SignalKeyStore
79
+ * Uses AsyncLocalStorage for automatic context management
80
+ * @param state the key store to apply this capability to
81
+ * @param logger logger to log events
82
+ * @returns SignalKeyStore with transaction capability
83
+ */
71
84
  export const addTransactionCapability = (state, logger, { maxCommitRetries, delayBetweenTriesMs }) => {
72
- const txStorage = new AsyncLocalStorage();
73
- const keyQueues = new Map();
74
- const txMutexes = new Map();
75
- const preKeyManager = new PreKeyManager(state, logger);
76
- function getQueue(key) {
77
- if (!keyQueues.has(key)) {
78
- keyQueues.set(key, new PQueue({ concurrency: 1 }));
85
+ const txStorage = new AsyncLocalStorage();
86
+ // Queues for concurrency control (keyed by signal data type - bounded set)
87
+ const keyQueues = new Map();
88
+ // Transaction mutexes with reference counting for cleanup
89
+ const txMutexes = new Map();
90
+ const txMutexRefCounts = new Map();
91
+ // Pre-key manager for specialized operations
92
+ const preKeyManager = new PreKeyManager(state, logger);
93
+ /**
94
+ * Get or create a queue for a specific key type
95
+ */
96
+ function getQueue(key) {
97
+ if (!keyQueues.has(key)) {
98
+ keyQueues.set(key, new PQueue({ concurrency: 1 }));
99
+ }
100
+ return keyQueues.get(key);
79
101
  }
80
- return keyQueues.get(key);
81
- }
82
- function getTxMutex(key) {
83
- if (!txMutexes.has(key)) {
84
- txMutexes.set(key, new Mutex());
102
+ /**
103
+ * Get or create a transaction mutex
104
+ */
105
+ function getTxMutex(key) {
106
+ if (!txMutexes.has(key)) {
107
+ txMutexes.set(key, new Mutex());
108
+ txMutexRefCounts.set(key, 0);
109
+ }
110
+ return txMutexes.get(key);
85
111
  }
86
- return txMutexes.get(key);
87
- }
88
- function isInTransaction() {
89
- return !!txStorage.getStore();
90
- }
91
- async function commitWithRetry(mutations) {
92
- if (Object.keys(mutations).length === 0) {
93
- logger.trace("no mutations in transaction");
94
- return;
112
+ /**
113
+ * Acquire a reference to a transaction mutex
114
+ */
115
+ function acquireTxMutexRef(key) {
116
+ const count = txMutexRefCounts.get(key) ?? 0;
117
+ txMutexRefCounts.set(key, count + 1);
95
118
  }
96
- logger.trace("committing transaction");
97
- for (let attempt = 0; attempt < maxCommitRetries; attempt++) {
98
- try {
99
- await state.set(mutations);
100
- logger.trace({ mutationCount: Object.keys(mutations).length }, "committed transaction");
101
- return;
102
- }
103
- catch (error) {
104
- const retriesLeft = maxCommitRetries - attempt - 1;
105
- logger.warn(`failed to commit mutations, retries left=${retriesLeft}`);
106
- if (retriesLeft === 0) {
107
- throw error;
119
+ /**
120
+ * Release a reference to a transaction mutex and cleanup if no longer needed
121
+ */
122
+ function releaseTxMutexRef(key) {
123
+ const count = (txMutexRefCounts.get(key) ?? 1) - 1;
124
+ txMutexRefCounts.set(key, count);
125
+ // Cleanup if no more references and mutex is not locked
126
+ if (count <= 0) {
127
+ const mutex = txMutexes.get(key);
128
+ if (mutex && !mutex.isLocked()) {
129
+ txMutexes.delete(key);
130
+ txMutexRefCounts.delete(key);
131
+ }
108
132
  }
109
- await delay(delayBetweenTriesMs);
110
- }
111
133
  }
112
- }
113
- return {
114
- get: async (type, ids) => {
115
- const ctx = txStorage.getStore();
116
- if (!ctx) {
117
- return state.get(type, ids);
118
- }
119
- const cached = ctx.cache[type] || {};
120
- const missing = ids.filter(id => !(id in cached));
121
- if (missing.length > 0) {
122
- ctx.dbQueries++;
123
- logger.trace({ type, count: missing.length }, "fetching missing keys in transaction");
124
- const fetched = await getTxMutex(type).runExclusive(() => state.get(type, missing));
125
- ctx.cache[type] = ctx.cache[type] || {};
126
- Object.assign(ctx.cache[type], fetched);
127
- }
128
- const result = {};
129
- for (const id of ids) {
130
- const value = ctx.cache[type]?.[id];
131
- if (value !== undefined && value !== null) {
132
- result[id] = value;
133
- }
134
- }
135
- return result;
136
- },
137
- set: async (data) => {
138
- const ctx = txStorage.getStore();
139
- if (!ctx) {
140
- const types = Object.keys(data);
141
- for (const type_ of types) {
142
- const type = type_;
143
- if (type === "pre-key") {
144
- await preKeyManager.validateDeletions(data, type);
145
- }
146
- }
147
- await Promise.all(types.map(type => getQueue(type).add(async () => {
148
- const typeData = { [type]: data[type] };
149
- await state.set(typeData);
150
- })));
151
- return;
152
- }
153
- logger.trace({ types: Object.keys(data) }, "caching in transaction");
154
- for (const key_ in data) {
155
- const key = key_;
156
- ctx.cache[key] = ctx.cache[key] || {};
157
- ctx.mutations[key] = ctx.mutations[key] || {};
158
- if (key === "pre-key") {
159
- await preKeyManager.processOperations(data, key, ctx.cache, ctx.mutations, true);
160
- }
161
- else {
162
- Object.assign(ctx.cache[key], data[key]);
163
- Object.assign(ctx.mutations[key], data[key]);
134
+ /**
135
+ * Check if currently in a transaction
136
+ */
137
+ function isInTransaction() {
138
+ return !!txStorage.getStore();
139
+ }
140
+ /**
141
+ * Commit transaction with retries
142
+ */
143
+ async function commitWithRetry(mutations) {
144
+ if (Object.keys(mutations).length === 0) {
145
+ logger.trace('no mutations in transaction');
146
+ return;
164
147
  }
165
- }
166
- },
167
- isInTransaction,
168
- transaction: async (work, key) => {
169
- const existing = txStorage.getStore();
170
- if (existing) {
171
- logger.trace("reusing existing transaction context");
172
- return work();
173
- }
174
- return getTxMutex(key).runExclusive(async () => {
175
- const ctx = {
176
- cache: {},
177
- mutations: {},
178
- dbQueries: 0
179
- };
180
- logger.trace("entering transaction");
181
- try {
182
- const result = await txStorage.run(ctx, work);
183
- await commitWithRetry(ctx.mutations);
184
- logger.trace({ dbQueries: ctx.dbQueries }, "transaction completed");
185
- return result;
148
+ logger.trace('committing transaction');
149
+ for (let attempt = 0; attempt < maxCommitRetries; attempt++) {
150
+ try {
151
+ await state.set(mutations);
152
+ logger.trace({ mutationCount: Object.keys(mutations).length }, 'committed transaction');
153
+ return;
154
+ }
155
+ catch (error) {
156
+ const retriesLeft = maxCommitRetries - attempt - 1;
157
+ logger.warn(`failed to commit mutations, retries left=${retriesLeft}`);
158
+ if (retriesLeft === 0) {
159
+ throw error;
160
+ }
161
+ await delay(delayBetweenTriesMs);
162
+ }
186
163
  }
187
- catch (error) {
188
- logger.error({ error }, "transaction failed, rolling back");
189
- throw error;
164
+ }
165
+ return {
166
+ get: async (type, ids) => {
167
+ const ctx = txStorage.getStore();
168
+ if (!ctx) {
169
+ // No transaction - direct read without exclusive lock for concurrency
170
+ return state.get(type, ids);
171
+ }
172
+ // In transaction - check cache first
173
+ const cached = ctx.cache[type] || {};
174
+ const missing = ids.filter(id => !(id in cached));
175
+ if (missing.length > 0) {
176
+ ctx.dbQueries++;
177
+ logger.trace({ type, count: missing.length }, 'fetching missing keys in transaction');
178
+ const fetched = await getTxMutex(type).runExclusive(() => state.get(type, missing));
179
+ // Update cache
180
+ ctx.cache[type] = ctx.cache[type] || {};
181
+ Object.assign(ctx.cache[type], fetched);
182
+ }
183
+ // Return requested ids from cache
184
+ const result = {};
185
+ for (const id of ids) {
186
+ const value = ctx.cache[type]?.[id];
187
+ if (value !== undefined && value !== null) {
188
+ result[id] = value;
189
+ }
190
+ }
191
+ return result;
192
+ },
193
+ set: async (data) => {
194
+ const ctx = txStorage.getStore();
195
+ if (!ctx) {
196
+ // No transaction - direct write with queue protection
197
+ const types = Object.keys(data);
198
+ // Process pre-keys with validation
199
+ for (const type_ of types) {
200
+ const type = type_;
201
+ if (type === 'pre-key') {
202
+ await preKeyManager.validateDeletions(data, type);
203
+ }
204
+ }
205
+ // Write all data in parallel
206
+ await Promise.all(types.map(type => getQueue(type).add(async () => {
207
+ const typeData = { [type]: data[type] };
208
+ await state.set(typeData);
209
+ })));
210
+ return;
211
+ }
212
+ // In transaction - update cache and mutations
213
+ logger.trace({ types: Object.keys(data) }, 'caching in transaction');
214
+ for (const key_ in data) {
215
+ const key = key_;
216
+ // Ensure structures exist
217
+ ctx.cache[key] = ctx.cache[key] || {};
218
+ ctx.mutations[key] = ctx.mutations[key] || {};
219
+ // Special handling for pre-keys
220
+ if (key === 'pre-key') {
221
+ await preKeyManager.processOperations(data, key, ctx.cache, ctx.mutations, true);
222
+ }
223
+ else {
224
+ // Normal key types
225
+ Object.assign(ctx.cache[key], data[key]);
226
+ Object.assign(ctx.mutations[key], data[key]);
227
+ }
228
+ }
229
+ },
230
+ isInTransaction,
231
+ transaction: async (work, key) => {
232
+ const existing = txStorage.getStore();
233
+ // Nested transaction - reuse existing context
234
+ if (existing) {
235
+ logger.trace('reusing existing transaction context');
236
+ return work();
237
+ }
238
+ // New transaction - acquire mutex and create context
239
+ const mutex = getTxMutex(key);
240
+ acquireTxMutexRef(key);
241
+ try {
242
+ return await mutex.runExclusive(async () => {
243
+ const ctx = {
244
+ cache: {},
245
+ mutations: {},
246
+ dbQueries: 0
247
+ };
248
+ logger.trace('entering transaction');
249
+ try {
250
+ const result = await txStorage.run(ctx, work);
251
+ // Commit mutations
252
+ await commitWithRetry(ctx.mutations);
253
+ logger.trace({ dbQueries: ctx.dbQueries }, 'transaction completed');
254
+ return result;
255
+ }
256
+ catch (error) {
257
+ logger.error({ error }, 'transaction failed, rolling back');
258
+ throw error;
259
+ }
260
+ });
261
+ }
262
+ finally {
263
+ releaseTxMutexRef(key);
264
+ }
190
265
  }
191
- });
266
+ };
267
+ };
268
+ /**
269
+ * Returns the authenticated user's JID, or throws a Boom-401 if creds are not yet authenticated.
270
+ * Use this anywhere we'd otherwise reach for `creds.me!.id` to fail fast with a descriptive error.
271
+ */
272
+ export const assertMeId = (creds) => {
273
+ const id = creds.me?.id;
274
+ if (!id) {
275
+ throw new Boom('Cannot proceed: socket is not authenticated yet (creds.me.id is missing)', { statusCode: 401 });
192
276
  }
193
- };
277
+ return id;
194
278
  };
195
- //=======================================================//
196
279
  export const initAuthCreds = () => {
197
- const identityKey = Curve.generateKeyPair();
198
- return {
199
- "noiseKey": Curve.generateKeyPair(),
200
- "pairingEphemeralKeyPair": Curve.generateKeyPair(),
201
- "signedIdentityKey": identityKey,
202
- "signedPreKey": signedKeyPair(identityKey, 1),
203
- "registrationId": generateRegistrationId(),
204
- "advSecretKey": randomBytes(32).toString("base64"),
205
- "processedHistoryMessages": [],
206
- "nextPreKeyId": 1,
207
- "firstUnuploadedPreKeyId": 1,
208
- "accountSyncCounter": 0,
209
- "accountSettings": {
210
- "unarchiveChats": false
211
- },
212
- "registered": false,
213
- "pairingCode": undefined,
214
- "lastPropHash": undefined,
215
- "routingInfo": undefined,
216
- "additionalData": undefined
217
- };
280
+ const identityKey = Curve.generateKeyPair();
281
+ return {
282
+ noiseKey: Curve.generateKeyPair(),
283
+ pairingEphemeralKeyPair: Curve.generateKeyPair(),
284
+ signedIdentityKey: identityKey,
285
+ signedPreKey: signedKeyPair(identityKey, 1),
286
+ registrationId: generateRegistrationId(),
287
+ advSecretKey: randomBytes(32).toString('base64'),
288
+ processedHistoryMessages: [],
289
+ nextPreKeyId: 1,
290
+ firstUnuploadedPreKeyId: 1,
291
+ accountSyncCounter: 0,
292
+ accountSettings: {
293
+ unarchiveChats: false
294
+ },
295
+ registered: false,
296
+ pairingCode: undefined,
297
+ lastPropHash: undefined,
298
+ routingInfo: undefined,
299
+ additionalData: undefined
300
+ };
218
301
  };
219
- //=======================================================//
@@ -0,0 +1,9 @@
1
+ export namespace Browsers {
2
+ function ubuntu(browser: any): any[];
3
+ function macOS(browser: any): any[];
4
+ function baileys(browser: any): any[];
5
+ function windows(browser: any): any[];
6
+ function appropriate(browser: any): any[];
7
+ }
8
+ export function getPlatformId(browser: any): string;
9
+ //# sourceMappingURL=browser-utils.d.ts.map