@wenzyx1/bails 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of @wenzyx1/bails might be problematic. Click here for more details.

Files changed (218) hide show
  1. package/README.md +231 -0
  2. package/WAProto/fix-imports.js +85 -0
  3. package/WAProto/index.d.ts +79257 -0
  4. package/WAProto/index.js +242946 -0
  5. package/engine-requirements.js +10 -0
  6. package/lib/Defaults/baileys-version.json +3 -0
  7. package/lib/Defaults/index.d.ts +53 -0
  8. package/lib/Defaults/index.js +147 -0
  9. package/lib/Defaults/phonenumber-mcc.json +223 -0
  10. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  11. package/lib/Signal/Group/ciphertext-message.js +15 -0
  12. package/lib/Signal/Group/group-session-builder.d.ts +14 -0
  13. package/lib/Signal/Group/group-session-builder.js +64 -0
  14. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  15. package/lib/Signal/Group/group_cipher.js +93 -0
  16. package/lib/Signal/Group/index.d.ts +11 -0
  17. package/lib/Signal/Group/index.js +57 -0
  18. package/lib/Signal/Group/keyhelper.d.ts +10 -0
  19. package/lib/Signal/Group/keyhelper.js +55 -0
  20. package/lib/Signal/Group/queue-job.d.ts +1 -0
  21. package/lib/Signal/Group/queue-job.js +53 -0
  22. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  23. package/lib/Signal/Group/sender-chain-key.js +34 -0
  24. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  25. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  26. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  27. package/lib/Signal/Group/sender-key-message.js +69 -0
  28. package/lib/Signal/Group/sender-key-name.d.ts +17 -0
  29. package/lib/Signal/Group/sender-key-name.js +51 -0
  30. package/lib/Signal/Group/sender-key-record.d.ts +30 -0
  31. package/lib/Signal/Group/sender-key-record.js +53 -0
  32. package/lib/Signal/Group/sender-key-state.d.ts +38 -0
  33. package/lib/Signal/Group/sender-key-state.js +99 -0
  34. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  35. package/lib/Signal/Group/sender-message-key.js +29 -0
  36. package/lib/Signal/libsignal.d.ts +3 -0
  37. package/lib/Signal/libsignal.js +454 -0
  38. package/lib/Signal/lid-mapping.js +280 -0
  39. package/lib/Socket/Client/abstract-socket-client.d.ts +17 -0
  40. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  41. package/lib/Socket/Client/index.d.ts +3 -0
  42. package/lib/Socket/Client/index.js +19 -0
  43. package/lib/Socket/Client/mobile-socket-client.d.ts +13 -0
  44. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  45. package/lib/Socket/Client/web-socket-client.d.ts +12 -0
  46. package/lib/Socket/Client/web-socket-client.js +62 -0
  47. package/lib/Socket/business.d.ts +171 -0
  48. package/lib/Socket/business.js +342 -0
  49. package/lib/Socket/chats.d.ts +267 -0
  50. package/lib/Socket/chats.js +978 -0
  51. package/lib/Socket/communities.mjs +428 -0
  52. package/lib/Socket/dugong.d.ts +254 -0
  53. package/lib/Socket/dugong.js +558 -0
  54. package/lib/Socket/groups.d.ts +115 -0
  55. package/lib/Socket/groups.js +380 -0
  56. package/lib/Socket/index.d.ts +173 -0
  57. package/lib/Socket/index.js +32 -0
  58. package/lib/Socket/luxu.js +545 -0
  59. package/lib/Socket/messages-recv.d.ts +161 -0
  60. package/lib/Socket/messages-recv.js +1124 -0
  61. package/lib/Socket/messages-send.d.ts +149 -0
  62. package/lib/Socket/messages-send.js +1476 -0
  63. package/lib/Socket/mex.mjs +50 -0
  64. package/lib/Socket/newsletter.d.ts +134 -0
  65. package/lib/Socket/newsletter.js +351 -0
  66. package/lib/Socket/registration.d.ts +267 -0
  67. package/lib/Socket/registration.js +166 -0
  68. package/lib/Socket/socket.d.ts +43 -0
  69. package/lib/Socket/socket.js +904 -0
  70. package/lib/Socket/username.mjs +132 -0
  71. package/lib/Socket/usync.d.ts +36 -0
  72. package/lib/Socket/usync.js +70 -0
  73. package/lib/Store/index.d.ts +3 -0
  74. package/lib/Store/index.js +10 -0
  75. package/lib/Store/keyed-db.d.ts +30 -0
  76. package/lib/Store/keyed-db.js +233 -0
  77. package/lib/Store/make-cache-manager-store.d.ts +13 -0
  78. package/lib/Store/make-cache-manager-store.js +83 -0
  79. package/lib/Store/make-in-memory-store.d.ts +118 -0
  80. package/lib/Store/make-in-memory-store.js +427 -0
  81. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  82. package/lib/Store/make-ordered-dictionary.js +81 -0
  83. package/lib/Store/object-repository.d.ts +10 -0
  84. package/lib/Store/object-repository.js +27 -0
  85. package/lib/Types/Auth.d.ts +110 -0
  86. package/lib/Types/Auth.js +2 -0
  87. package/lib/Types/Call.d.ts +13 -0
  88. package/lib/Types/Call.js +2 -0
  89. package/lib/Types/Chat.d.ts +102 -0
  90. package/lib/Types/Chat.js +4 -0
  91. package/lib/Types/Contact.d.ts +19 -0
  92. package/lib/Types/Contact.js +2 -0
  93. package/lib/Types/Events.d.ts +157 -0
  94. package/lib/Types/Events.js +2 -0
  95. package/lib/Types/GroupMetadata.d.ts +55 -0
  96. package/lib/Types/GroupMetadata.js +2 -0
  97. package/lib/Types/Label.d.ts +35 -0
  98. package/lib/Types/Label.js +27 -0
  99. package/lib/Types/LabelAssociation.d.ts +29 -0
  100. package/lib/Types/LabelAssociation.js +9 -0
  101. package/lib/Types/Message.d.ts +273 -0
  102. package/lib/Types/Message.js +9 -0
  103. package/lib/Types/Mex.js +39 -0
  104. package/lib/Types/Newsletter.d.ts +103 -0
  105. package/lib/Types/Newsletter.js +38 -0
  106. package/lib/Types/Product.d.ts +78 -0
  107. package/lib/Types/Product.js +2 -0
  108. package/lib/Types/Signal.d.ts +57 -0
  109. package/lib/Types/Signal.js +2 -0
  110. package/lib/Types/Socket.d.ts +111 -0
  111. package/lib/Types/Socket.js +2 -0
  112. package/lib/Types/State.d.ts +27 -0
  113. package/lib/Types/State.js +2 -0
  114. package/lib/Types/USync.d.ts +25 -0
  115. package/lib/Types/USync.js +2 -0
  116. package/lib/Types/index.d.ts +57 -0
  117. package/lib/Types/index.js +43 -0
  118. package/lib/Utils/Mex.js +39 -0
  119. package/lib/Utils/auth-utils.d.ts +18 -0
  120. package/lib/Utils/auth-utils.js +206 -0
  121. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  122. package/lib/Utils/baileys-event-stream.js +57 -0
  123. package/lib/Utils/browser-presets.js +64 -0
  124. package/lib/Utils/business.d.ts +22 -0
  125. package/lib/Utils/business.js +234 -0
  126. package/lib/Utils/chat-utils.d.ts +71 -0
  127. package/lib/Utils/chat-utils.js +726 -0
  128. package/lib/Utils/companion-reg-client-utils.js +40 -0
  129. package/lib/Utils/crypto.d.ts +41 -0
  130. package/lib/Utils/crypto.js +151 -0
  131. package/lib/Utils/decode-wa-message.d.ts +19 -0
  132. package/lib/Utils/decode-wa-message.js +198 -0
  133. package/lib/Utils/event-buffer.d.ts +35 -0
  134. package/lib/Utils/event-buffer.js +514 -0
  135. package/lib/Utils/extended-messages.js +231 -0
  136. package/lib/Utils/generics.d.ts +92 -0
  137. package/lib/Utils/generics.js +425 -0
  138. package/lib/Utils/history.d.ts +15 -0
  139. package/lib/Utils/history.js +96 -0
  140. package/lib/Utils/identity-change-handler.js +52 -0
  141. package/lib/Utils/index.d.ts +17 -0
  142. package/lib/Utils/index.js +40 -0
  143. package/lib/Utils/link-preview.d.ts +21 -0
  144. package/lib/Utils/link-preview.js +93 -0
  145. package/lib/Utils/logger.d.ts +4 -0
  146. package/lib/Utils/logger.js +7 -0
  147. package/lib/Utils/lt-hash.d.ts +12 -0
  148. package/lib/Utils/lt-hash.js +51 -0
  149. package/lib/Utils/make-mutex.d.ts +7 -0
  150. package/lib/Utils/make-mutex.js +43 -0
  151. package/lib/Utils/message-composer.js +293 -0
  152. package/lib/Utils/message-retry-manager.js +226 -0
  153. package/lib/Utils/messages-media.d.ts +116 -0
  154. package/lib/Utils/messages-media.js +815 -0
  155. package/lib/Utils/messages.d.ts +77 -0
  156. package/lib/Utils/messages.js +888 -0
  157. package/lib/Utils/noise-handler.d.ts +21 -0
  158. package/lib/Utils/noise-handler.js +155 -0
  159. package/lib/Utils/offline-node-processor.js +46 -0
  160. package/lib/Utils/pre-key-manager.js +95 -0
  161. package/lib/Utils/process-message.d.ts +41 -0
  162. package/lib/Utils/process-message.js +321 -0
  163. package/lib/Utils/reporting-utils.js +272 -0
  164. package/lib/Utils/signal.d.ts +32 -0
  165. package/lib/Utils/signal.js +160 -0
  166. package/lib/Utils/stanza-ack.js +38 -0
  167. package/lib/Utils/sync-action-utils.js +50 -0
  168. package/lib/Utils/tc-token-utils.js +169 -0
  169. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  170. package/lib/Utils/use-multi-file-auth-state.js +119 -0
  171. package/lib/Utils/validate-connection.d.ts +11 -0
  172. package/lib/Utils/validate-connection.js +229 -0
  173. package/lib/WABinary/constants.d.ts +30 -0
  174. package/lib/WABinary/constants.js +40 -0
  175. package/lib/WABinary/decode.d.ts +7 -0
  176. package/lib/WABinary/decode.js +252 -0
  177. package/lib/WABinary/encode.d.ts +3 -0
  178. package/lib/WABinary/encode.js +265 -0
  179. package/lib/WABinary/generic-utils.d.ts +17 -0
  180. package/lib/WABinary/generic-utils.js +204 -0
  181. package/lib/WABinary/index.d.ts +5 -0
  182. package/lib/WABinary/index.js +21 -0
  183. package/lib/WABinary/jid-utils.d.ts +31 -0
  184. package/lib/WABinary/jid-utils.js +132 -0
  185. package/lib/WABinary/types.d.ts +18 -0
  186. package/lib/WABinary/types.js +2 -0
  187. package/lib/WAM/BinaryInfo.d.ts +17 -0
  188. package/lib/WAM/BinaryInfo.js +13 -0
  189. package/lib/WAM/constants.d.ts +38 -0
  190. package/lib/WAM/constants.js +15350 -0
  191. package/lib/WAM/encode.d.ts +3 -0
  192. package/lib/WAM/encode.js +155 -0
  193. package/lib/WAM/index.d.ts +3 -0
  194. package/lib/WAM/index.js +19 -0
  195. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  196. package/lib/WAUSync/Protocols/USyncContactProtocol.js +55 -0
  197. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  198. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  199. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  200. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  201. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  202. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  203. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +27 -0
  204. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +25 -0
  205. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  206. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +8 -0
  207. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  208. package/lib/WAUSync/Protocols/index.d.ts +4 -0
  209. package/lib/WAUSync/Protocols/index.js +21 -0
  210. package/lib/WAUSync/USyncQuery.d.ts +28 -0
  211. package/lib/WAUSync/USyncQuery.js +93 -0
  212. package/lib/WAUSync/USyncUser.d.ts +12 -0
  213. package/lib/WAUSync/USyncUser.js +34 -0
  214. package/lib/WAUSync/index.d.ts +3 -0
  215. package/lib/WAUSync/index.js +19 -0
  216. package/lib/index.d.ts +12 -0
  217. package/lib/index.js +52 -0
  218. package/package.json +112 -0
@@ -0,0 +1,99 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SenderKeyState = void 0;
4
+ const sender_chain_key_1 = require("./sender-chain-key");
5
+ const sender_message_key_1 = require("./sender-message-key");
6
+ class SenderKeyState {
7
+ constructor(id, iteration, chainKey, signatureKeyPair, signatureKeyPublic, signatureKeyPrivate, senderKeyStateStructure) {
8
+ this.MAX_MESSAGE_KEYS = 2000;
9
+ if (senderKeyStateStructure) {
10
+ this.senderKeyStateStructure = senderKeyStateStructure;
11
+ }
12
+ else {
13
+ if (signatureKeyPair) {
14
+ signatureKeyPublic = signatureKeyPair.public;
15
+ signatureKeyPrivate = signatureKeyPair.private;
16
+ }
17
+ chainKey = typeof chainKey === 'string' ? Buffer.from(chainKey, 'base64') : chainKey;
18
+ const senderChainKeyStructure = {
19
+ iteration: iteration || 0,
20
+ seed: chainKey || Buffer.alloc(0)
21
+ };
22
+ const signingKeyStructure = {
23
+ public: typeof signatureKeyPublic === 'string'
24
+ ? Buffer.from(signatureKeyPublic, 'base64')
25
+ : signatureKeyPublic || Buffer.alloc(0)
26
+ };
27
+ if (signatureKeyPrivate) {
28
+ signingKeyStructure.private =
29
+ typeof signatureKeyPrivate === 'string' ? Buffer.from(signatureKeyPrivate, 'base64') : signatureKeyPrivate;
30
+ }
31
+ this.senderKeyStateStructure = {
32
+ senderKeyId: id || 0,
33
+ senderChainKey: senderChainKeyStructure,
34
+ senderSigningKey: signingKeyStructure,
35
+ senderMessageKeys: []
36
+ };
37
+ }
38
+ }
39
+ getKeyId() {
40
+ return this.senderKeyStateStructure.senderKeyId;
41
+ }
42
+ getSenderChainKey() {
43
+ return new sender_chain_key_1.SenderChainKey(this.senderKeyStateStructure.senderChainKey.iteration, this.senderKeyStateStructure.senderChainKey.seed);
44
+ }
45
+ setSenderChainKey(chainKey) {
46
+ this.senderKeyStateStructure.senderChainKey = {
47
+ iteration: chainKey.getIteration(),
48
+ seed: chainKey.getSeed()
49
+ };
50
+ }
51
+ getSigningKeyPublic() {
52
+ const publicKey = this.senderKeyStateStructure.senderSigningKey.public;
53
+ if (publicKey instanceof Buffer) {
54
+ return publicKey;
55
+ }
56
+ else if (typeof publicKey === 'string') {
57
+ return Buffer.from(publicKey, 'base64');
58
+ }
59
+ return Buffer.from(publicKey || []);
60
+ }
61
+ getSigningKeyPrivate() {
62
+ const privateKey = this.senderKeyStateStructure.senderSigningKey.private;
63
+ if (!privateKey) {
64
+ return undefined;
65
+ }
66
+ if (privateKey instanceof Buffer) {
67
+ return privateKey;
68
+ }
69
+ else if (typeof privateKey === 'string') {
70
+ return Buffer.from(privateKey, 'base64');
71
+ }
72
+ return Buffer.from(privateKey || []);
73
+ }
74
+ hasSenderMessageKey(iteration) {
75
+ return this.senderKeyStateStructure.senderMessageKeys.some(key => key.iteration === iteration);
76
+ }
77
+ addSenderMessageKey(senderMessageKey) {
78
+ this.senderKeyStateStructure.senderMessageKeys.push({
79
+ iteration: senderMessageKey.getIteration(),
80
+ seed: senderMessageKey.getSeed()
81
+ });
82
+ if (this.senderKeyStateStructure.senderMessageKeys.length > this.MAX_MESSAGE_KEYS) {
83
+ this.senderKeyStateStructure.senderMessageKeys.shift();
84
+ }
85
+ }
86
+ removeSenderMessageKey(iteration) {
87
+ const index = this.senderKeyStateStructure.senderMessageKeys.findIndex(key => key.iteration === iteration);
88
+ if (index !== -1) {
89
+ const messageKey = this.senderKeyStateStructure.senderMessageKeys[index];
90
+ this.senderKeyStateStructure.senderMessageKeys.splice(index, 1);
91
+ return new sender_message_key_1.SenderMessageKey(messageKey.iteration, messageKey.seed);
92
+ }
93
+ return null;
94
+ }
95
+ getStructure() {
96
+ return this.senderKeyStateStructure;
97
+ }
98
+ }
99
+ exports.SenderKeyState = SenderKeyState;
@@ -0,0 +1,11 @@
1
+ export declare class SenderMessageKey {
2
+ private readonly iteration;
3
+ private readonly iv;
4
+ private readonly cipherKey;
5
+ private readonly seed;
6
+ constructor(iteration: number, seed: Uint8Array);
7
+ getIteration(): number;
8
+ getIv(): Uint8Array;
9
+ getCipherKey(): Uint8Array;
10
+ getSeed(): Uint8Array;
11
+ }
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SenderMessageKey = void 0;
4
+ const crypto_1 = require("libsignal/src/crypto");
5
+ class SenderMessageKey {
6
+ constructor(iteration, seed) {
7
+ const derivative = (0, crypto_1.deriveSecrets)(seed, Buffer.alloc(32), Buffer.from('WhisperGroup'));
8
+ const keys = new Uint8Array(32);
9
+ keys.set(new Uint8Array(derivative[0].slice(16)));
10
+ keys.set(new Uint8Array(derivative[1].slice(0, 16)), 16);
11
+ this.iv = Buffer.from(derivative[0].slice(0, 16));
12
+ this.cipherKey = Buffer.from(keys.buffer);
13
+ this.iteration = iteration;
14
+ this.seed = seed;
15
+ }
16
+ getIteration() {
17
+ return this.iteration;
18
+ }
19
+ getIv() {
20
+ return this.iv;
21
+ }
22
+ getCipherKey() {
23
+ return this.cipherKey;
24
+ }
25
+ getSeed() {
26
+ return this.seed;
27
+ }
28
+ }
29
+ exports.SenderMessageKey = SenderMessageKey;
@@ -0,0 +1,3 @@
1
+ import { SignalAuthState } from '../Types';
2
+ import { SignalRepository } from '../Types/Signal';
3
+ export declare function makeLibSignalRepository(auth: SignalAuthState): SignalRepository;
@@ -0,0 +1,454 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.makeLibSignalRepository = makeLibSignalRepository;
37
+ const libsignal = __importStar(require("libsignal"));
38
+ const lru_cache_1 = require("lru-cache");
39
+ const Utils_1 = require("../Utils");
40
+ const WABinary_1 = require("../WABinary");
41
+ const sender_key_name_1 = require("./Group/sender-key-name");
42
+ const sender_key_record_1 = require("./Group/sender-key-record");
43
+ const Group_1 = require("./Group");
44
+ const lid_mapping_1 = require("./lid-mapping");
45
+ /**
46
+ * Extract identity key from a PreKeyWhisperMessage, used for identity-change
47
+ * detection. Ported from xata-bail.
48
+ *
49
+ * NOTE: this depends on `libsignal/src/protobufs.js` exporting
50
+ * `PreKeyWhisperMessage`. edgar-bail uses a different libsignal fork
51
+ * (github:RILLYZY/libsignal-node) than xata-bail's (@levvicode/libsignal-node),
52
+ * so this path is wrapped defensively: if it's unavailable, identity-change
53
+ * detection is simply disabled instead of crashing the whole module.
54
+ */
55
+ let PreKeyWhisperMessage;
56
+ try {
57
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
58
+ PreKeyWhisperMessage = require('libsignal/src/protobufs.js').PreKeyWhisperMessage;
59
+ }
60
+ catch (e) {
61
+ PreKeyWhisperMessage = undefined;
62
+ }
63
+ function extractIdentityFromPkmsg(ciphertext) {
64
+ if (!PreKeyWhisperMessage) {
65
+ return undefined;
66
+ }
67
+ try {
68
+ if (!ciphertext || ciphertext.length < 2) {
69
+ return undefined;
70
+ }
71
+ const version = ciphertext[0];
72
+ if ((version & 0xf) !== 3) {
73
+ return undefined;
74
+ }
75
+ const preKeyProto = PreKeyWhisperMessage.decode(ciphertext.slice(1));
76
+ if ((preKeyProto === null || preKeyProto === void 0 ? void 0 : preKeyProto.identityKey) && preKeyProto.identityKey.length === 33) {
77
+ return new Uint8Array(preKeyProto.identityKey);
78
+ }
79
+ return undefined;
80
+ }
81
+ catch (_e) {
82
+ return undefined;
83
+ }
84
+ }
85
+ function makeLibSignalRepository(auth, logger, pnToLIDFunc) {
86
+ logger = logger || Utils_1.DEFAULT_LOGGER || console;
87
+ const lidMapping = new lid_mapping_1.LIDMappingStore(auth.keys, logger, pnToLIDFunc);
88
+ const storage = signalStorage(auth, lidMapping, logger);
89
+ const parsedKeys = auth.keys;
90
+ const migratedSessionCache = new lru_cache_1.LRUCache({
91
+ ttl: 3 * 24 * 60 * 60 * 1000, // 7 days
92
+ ttlAutopurge: true,
93
+ updateAgeOnGet: true
94
+ });
95
+ const hasTransaction = typeof parsedKeys.transaction === 'function';
96
+ const runInTransaction = (work, key) => (hasTransaction ? parsedKeys.transaction(work, key) : work());
97
+ const ensureSenderKeyAndCreateSkdm = async (group, meId) => {
98
+ const senderName = jidToSignalSenderKeyName(group, meId);
99
+ const senderNameStr = senderName.toString();
100
+ const { [senderNameStr]: senderKey } = await auth.keys.get('sender-key', [senderNameStr]);
101
+ if (!senderKey) {
102
+ await storage.storeSenderKey(senderName, new sender_key_record_1.SenderKeyRecord());
103
+ }
104
+ const skdm = await new Group_1.GroupSessionBuilder(storage).create(senderName);
105
+ return { senderName, skdm };
106
+ };
107
+ const repository = {
108
+ decryptGroupMessage({ group, authorJid, msg }) {
109
+ const senderName = jidToSignalSenderKeyName(group, authorJid);
110
+ const cipher = new Group_1.GroupCipher(storage, senderName);
111
+ return runInTransaction(async () => cipher.decrypt(msg), group);
112
+ },
113
+ async processSenderKeyDistributionMessage({ item, authorJid }) {
114
+ const builder = new Group_1.GroupSessionBuilder(storage);
115
+ if (!item.groupId) {
116
+ throw new Error('Group ID is required for sender key distribution message');
117
+ }
118
+ const senderName = jidToSignalSenderKeyName(item.groupId, authorJid);
119
+ const senderMsg = new Group_1.SenderKeyDistributionMessage(null, null, null, null, item.axolotlSenderKeyDistributionMessage);
120
+ const senderNameStr = senderName.toString();
121
+ const { [senderNameStr]: senderKey } = await auth.keys.get('sender-key', [senderNameStr]);
122
+ if (!senderKey) {
123
+ await storage.storeSenderKey(senderName, new sender_key_record_1.SenderKeyRecord());
124
+ }
125
+ return runInTransaction(async () => {
126
+ await builder.process(senderName, senderMsg);
127
+ }, item.groupId);
128
+ },
129
+ async decryptMessage({ jid, type, ciphertext }) {
130
+ const addr = jidToSignalProtocolAddress(jid);
131
+ const session = new libsignal.SessionCipher(storage, addr);
132
+ if (type === 'pkmsg') {
133
+ const identityKey = extractIdentityFromPkmsg(ciphertext);
134
+ if (identityKey) {
135
+ const addrStr = addr.toString();
136
+ const identityChanged = await storage.saveIdentity(addrStr, identityKey);
137
+ if (identityChanged) {
138
+ logger.info({ jid, addr: addrStr }, 'identity key changed or new contact, session will be re-established');
139
+ }
140
+ }
141
+ }
142
+ async function doDecrypt() {
143
+ let result;
144
+ switch (type) {
145
+ case 'pkmsg':
146
+ result = await session.decryptPreKeyWhisperMessage(ciphertext);
147
+ break;
148
+ case 'msg':
149
+ result = await session.decryptWhisperMessage(ciphertext);
150
+ break;
151
+ default:
152
+ throw new Error(`Unknown message type: ${type}`);
153
+ }
154
+ return result;
155
+ }
156
+ return runInTransaction(async () => doDecrypt(), jid);
157
+ },
158
+ async encryptMessage({ jid, data }) {
159
+ const addr = jidToSignalProtocolAddress(jid);
160
+ const cipher = new libsignal.SessionCipher(storage, addr);
161
+ return runInTransaction(async () => {
162
+ const { type: sigType, body } = await cipher.encrypt(data);
163
+ const type = sigType === 3 ? 'pkmsg' : 'msg';
164
+ return { type, ciphertext: Buffer.from(body, 'binary') };
165
+ }, jid);
166
+ },
167
+ async encryptGroupMessage({ group, meId, data }) {
168
+ return runInTransaction(async () => {
169
+ const { senderName, skdm } = await ensureSenderKeyAndCreateSkdm(group, meId);
170
+ const ciphertext = await new Group_1.GroupCipher(storage, senderName).encrypt(data);
171
+ return { ciphertext, senderKeyDistributionMessage: skdm.serialize() };
172
+ }, group);
173
+ },
174
+ async getSenderKeyDistributionMessage({ group, meId }) {
175
+ return runInTransaction(async () => {
176
+ const { skdm } = await ensureSenderKeyAndCreateSkdm(group, meId);
177
+ return skdm.serialize();
178
+ }, group);
179
+ },
180
+ async hasSenderKey({ group, meId }) {
181
+ const senderName = jidToSignalSenderKeyName(group, meId).toString();
182
+ const { [senderName]: key } = await auth.keys.get('sender-key', [senderName]);
183
+ return !!key;
184
+ },
185
+ async getSessionInfo(jid) {
186
+ var _a, _b;
187
+ const addr = jidToSignalProtocolAddress(jid).toString();
188
+ const session = await storage.loadSession(addr);
189
+ if (!session) {
190
+ return null;
191
+ }
192
+ const open = typeof session.getOpenSession === 'function' ? session.getOpenSession() : undefined;
193
+ const baseKey = (_a = open === null || open === void 0 ? void 0 : open.indexInfo) === null || _a === void 0 ? void 0 : _a.baseKey;
194
+ const registrationId = open === null || open === void 0 ? void 0 : open.registrationId;
195
+ if (!baseKey || typeof registrationId !== 'number') {
196
+ return null;
197
+ }
198
+ return { baseKey: new Uint8Array(baseKey), registrationId };
199
+ },
200
+ async injectE2ESession({ jid, session }) {
201
+ logger.trace({ jid }, 'injecting E2EE session');
202
+ const cipher = new libsignal.SessionBuilder(storage, jidToSignalProtocolAddress(jid));
203
+ return runInTransaction(async () => {
204
+ await cipher.initOutgoing(session);
205
+ }, jid);
206
+ },
207
+ jidToSignalProtocolAddress(jid) {
208
+ return jidToSignalProtocolAddress(jid).toString();
209
+ },
210
+ // Direct access to the LID mapping store
211
+ lidMapping,
212
+ async validateSession(jid) {
213
+ try {
214
+ const addr = jidToSignalProtocolAddress(jid);
215
+ const session = await storage.loadSession(addr.toString());
216
+ if (!session) {
217
+ return { exists: false, reason: 'no session' };
218
+ }
219
+ if (typeof session.haveOpenSession === 'function' && !session.haveOpenSession()) {
220
+ return { exists: false, reason: 'no open session' };
221
+ }
222
+ return { exists: true };
223
+ }
224
+ catch (_error) {
225
+ return { exists: false, reason: 'validation error' };
226
+ }
227
+ },
228
+ async deleteSession(jids) {
229
+ if (!jids.length)
230
+ return;
231
+ const sessionUpdates = {};
232
+ jids.forEach(jid => {
233
+ const addr = jidToSignalProtocolAddress(jid);
234
+ sessionUpdates[addr.toString()] = null;
235
+ });
236
+ return runInTransaction(async () => {
237
+ await auth.keys.set({ session: sessionUpdates });
238
+ }, `delete-${jids.length}-sessions`);
239
+ },
240
+ close() {
241
+ migratedSessionCache.clear();
242
+ lidMapping.close();
243
+ },
244
+ async migrateSession(fromJid, toJid) {
245
+ if (!fromJid || (!(0, WABinary_1.isLidUser)(toJid) && !(0, WABinary_1.isHostedLidUser)(toJid)))
246
+ return { migrated: 0, skipped: 0, total: 0 };
247
+ if (!(0, WABinary_1.isPnUser)(fromJid) && !(0, WABinary_1.isHostedPnUser)(fromJid)) {
248
+ return { migrated: 0, skipped: 0, total: 1 };
249
+ }
250
+ const { user } = (0, WABinary_1.jidDecode)(fromJid);
251
+ logger.debug({ fromJid }, 'bulk device migration - loading all user devices');
252
+ const { [user]: userDevices } = await parsedKeys.get('device-list', [user]);
253
+ if (!userDevices) {
254
+ return { migrated: 0, skipped: 0, total: 0 };
255
+ }
256
+ const { device: fromDevice } = (0, WABinary_1.jidDecode)(fromJid);
257
+ const fromDeviceStr = (fromDevice === null || fromDevice === void 0 ? void 0 : fromDevice.toString()) || '0';
258
+ if (!userDevices.includes(fromDeviceStr)) {
259
+ userDevices.push(fromDeviceStr);
260
+ }
261
+ const uncachedDevices = userDevices.filter(device => {
262
+ const deviceKey = `${user}.${device}`;
263
+ return !migratedSessionCache.has(deviceKey);
264
+ });
265
+ const deviceSessionKeys = uncachedDevices.map(device => `${user}.${device}`);
266
+ const existingSessions = await parsedKeys.get('session', deviceSessionKeys);
267
+ const deviceJids = [];
268
+ for (const [sessionKey, sessionData] of Object.entries(existingSessions)) {
269
+ if (sessionData) {
270
+ const deviceStr = sessionKey.split('.')[1];
271
+ if (!deviceStr)
272
+ continue;
273
+ const deviceNum = parseInt(deviceStr);
274
+ let jid = deviceNum === 0 ? `${user}@s.whatsapp.net` : `${user}:${deviceNum}@s.whatsapp.net`;
275
+ if (deviceNum === 99) {
276
+ jid = `${user}:99@hosted`;
277
+ }
278
+ deviceJids.push(jid);
279
+ }
280
+ }
281
+ logger.debug({
282
+ fromJid,
283
+ totalDevices: userDevices.length,
284
+ devicesWithSessions: deviceJids.length,
285
+ devices: deviceJids
286
+ }, 'bulk device migration complete - all user devices processed');
287
+ return runInTransaction(async () => {
288
+ const migrationOps = deviceJids.map(jid => {
289
+ const lidWithDevice = (0, WABinary_1.transferDevice)(jid, toJid);
290
+ const fromDecoded = (0, WABinary_1.jidDecode)(jid);
291
+ const toDecoded = (0, WABinary_1.jidDecode)(lidWithDevice);
292
+ return {
293
+ fromJid: jid,
294
+ toJid: lidWithDevice,
295
+ pnUser: fromDecoded.user,
296
+ lidUser: toDecoded.user,
297
+ deviceId: fromDecoded.device || 0,
298
+ fromAddr: jidToSignalProtocolAddress(jid),
299
+ toAddr: jidToSignalProtocolAddress(lidWithDevice)
300
+ };
301
+ });
302
+ const totalOps = migrationOps.length;
303
+ let migratedCount = 0;
304
+ const pnAddrStrings = Array.from(new Set(migrationOps.map(op => op.fromAddr.toString())));
305
+ const pnSessions = await parsedKeys.get('session', pnAddrStrings);
306
+ const sessionUpdates = {};
307
+ for (const op of migrationOps) {
308
+ const pnAddrStr = op.fromAddr.toString();
309
+ const lidAddrStr = op.toAddr.toString();
310
+ const pnSession = pnSessions[pnAddrStr];
311
+ if (pnSession) {
312
+ const fromSession = libsignal.SessionRecord.deserialize(pnSession);
313
+ if (typeof fromSession.haveOpenSession !== 'function' || fromSession.haveOpenSession()) {
314
+ sessionUpdates[lidAddrStr] = fromSession.serialize();
315
+ sessionUpdates[pnAddrStr] = null;
316
+ migratedCount++;
317
+ }
318
+ }
319
+ }
320
+ if (Object.keys(sessionUpdates).length > 0) {
321
+ await parsedKeys.set({ session: sessionUpdates });
322
+ logger.debug({ migratedSessions: migratedCount }, 'bulk session migration complete');
323
+ for (const op of migrationOps) {
324
+ if (sessionUpdates[op.toAddr.toString()]) {
325
+ const deviceKey = `${op.pnUser}.${op.deviceId}`;
326
+ migratedSessionCache.set(deviceKey, true);
327
+ }
328
+ }
329
+ }
330
+ const skippedCount = totalOps - migratedCount;
331
+ return { migrated: migratedCount, skipped: skippedCount, total: totalOps };
332
+ }, `migrate-${deviceJids.length}-sessions-${(0, WABinary_1.jidDecode)(toJid) === null || (0, WABinary_1.jidDecode)(toJid) === void 0 ? void 0 : (0, WABinary_1.jidDecode)(toJid).user}`);
333
+ }
334
+ };
335
+ return repository;
336
+ }
337
+ const jidToSignalProtocolAddress = (jid) => {
338
+ const decoded = (0, WABinary_1.jidDecode)(jid);
339
+ const { user, device, server, domainType } = decoded;
340
+ if (!user) {
341
+ throw new Error(`JID decoded but user is empty: "${jid}" -> user: "${user}", server: "${server}", device: ${device}`);
342
+ }
343
+ const signalUser = domainType !== WABinary_1.WAJIDDomains.WHATSAPP ? `${user}_${domainType}` : user;
344
+ const finalDevice = device || 0;
345
+ if (device === 99 && server !== 'hosted' && server !== 'hosted.lid') {
346
+ throw new Error('Unexpected non-hosted device JID with device 99. This ID seems invalid. ID:' + jid);
347
+ }
348
+ return new libsignal.ProtocolAddress(signalUser, finalDevice);
349
+ };
350
+ const jidToSignalSenderKeyName = (group, user) => {
351
+ return new sender_key_name_1.SenderKeyName(group, jidToSignalProtocolAddress(user));
352
+ };
353
+ function signalStorage({ creds, keys }, lidMapping, logger) {
354
+ const resolveLIDSignalAddress = async (id) => {
355
+ if (id.includes('.')) {
356
+ const [deviceId, device] = id.split('.');
357
+ const [user, domainType_] = deviceId.split('_');
358
+ const domainType = parseInt(domainType_ || '0');
359
+ if (domainType === WABinary_1.WAJIDDomains.LID || domainType === WABinary_1.WAJIDDomains.HOSTED_LID)
360
+ return id;
361
+ const pnJid = `${user}${device !== '0' ? `:${device}` : ''}@${domainType === WABinary_1.WAJIDDomains.HOSTED ? 'hosted' : 's.whatsapp.net'}`;
362
+ const lidForPN = await lidMapping.getLIDForPN(pnJid);
363
+ if (lidForPN) {
364
+ const lidAddr = jidToSignalProtocolAddress(lidForPN);
365
+ return lidAddr.toString();
366
+ }
367
+ }
368
+ return id;
369
+ };
370
+ return {
371
+ loadSession: async (id) => {
372
+ try {
373
+ const wireJid = await resolveLIDSignalAddress(id);
374
+ const { [wireJid]: sess } = await keys.get('session', [wireJid]);
375
+ if (sess) {
376
+ return libsignal.SessionRecord.deserialize(sess);
377
+ }
378
+ }
379
+ catch (_e) {
380
+ return null;
381
+ }
382
+ return null;
383
+ },
384
+ storeSession: async (id, session) => {
385
+ const wireJid = await resolveLIDSignalAddress(id);
386
+ await keys.set({ session: { [wireJid]: session.serialize() } });
387
+ },
388
+ isTrustedIdentity: () => {
389
+ return true; // TOFU - Trust on First Use
390
+ },
391
+ loadIdentityKey: async (id) => {
392
+ const wireJid = await resolveLIDSignalAddress(id);
393
+ const { [wireJid]: key } = await keys.get('identity-key', [wireJid]);
394
+ return key || undefined;
395
+ },
396
+ saveIdentity: async (id, identityKey) => {
397
+ const wireJid = await resolveLIDSignalAddress(id);
398
+ const { [wireJid]: existingKey } = await keys.get('identity-key', [wireJid]);
399
+ const keysMatch = (existingKey === null || existingKey === void 0 ? void 0 : existingKey.length) === identityKey.length &&
400
+ existingKey.every((byte, i) => byte === identityKey[i]);
401
+ if (existingKey && !keysMatch) {
402
+ await keys.set({
403
+ session: { [wireJid]: null },
404
+ 'identity-key': { [wireJid]: identityKey }
405
+ });
406
+ return true;
407
+ }
408
+ if (!existingKey) {
409
+ await keys.set({ 'identity-key': { [wireJid]: identityKey } });
410
+ return true;
411
+ }
412
+ return false;
413
+ },
414
+ loadPreKey: async (id) => {
415
+ const keyId = id.toString();
416
+ const { [keyId]: key } = await keys.get('pre-key', [keyId]);
417
+ if (key) {
418
+ return {
419
+ privKey: Buffer.from(key.private),
420
+ pubKey: Buffer.from(key.public)
421
+ };
422
+ }
423
+ },
424
+ removePreKey: (id) => keys.set({ 'pre-key': { [id]: null } }),
425
+ loadSignedPreKey: () => {
426
+ const key = creds.signedPreKey;
427
+ return {
428
+ privKey: Buffer.from(key.keyPair.private),
429
+ pubKey: Buffer.from(key.keyPair.public)
430
+ };
431
+ },
432
+ loadSenderKey: async (senderKeyName) => {
433
+ const keyId = senderKeyName.toString();
434
+ const { [keyId]: key } = await keys.get('sender-key', [keyId]);
435
+ if (key) {
436
+ return sender_key_record_1.SenderKeyRecord.deserialize(key);
437
+ }
438
+ return new sender_key_record_1.SenderKeyRecord();
439
+ },
440
+ storeSenderKey: async (senderKeyName, key) => {
441
+ const keyId = senderKeyName.toString();
442
+ const serialized = JSON.stringify(key.serialize());
443
+ await keys.set({ 'sender-key': { [keyId]: Buffer.from(serialized, 'utf-8') } });
444
+ },
445
+ getOurRegistrationId: () => creds.registrationId,
446
+ getOurIdentity: () => {
447
+ const { signedIdentityKey } = creds;
448
+ return {
449
+ privKey: Buffer.from(signedIdentityKey.private),
450
+ pubKey: (0, Utils_1.generateSignalPubKey)(signedIdentityKey.public)
451
+ };
452
+ }
453
+ };
454
+ }