@vanzxy/baileys 1.4.0 → 1.4.2

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 (114) hide show
  1. package/cjs/WAProto/index.js +106053 -0
  2. package/cjs/lib/Defaults/index.js +168 -0
  3. package/cjs/lib/Signal/Group/ciphertext-message.js +16 -0
  4. package/cjs/lib/Signal/Group/group-session-builder.js +67 -0
  5. package/cjs/lib/Signal/Group/group_cipher.js +86 -0
  6. package/cjs/lib/Signal/Group/index.js +58 -0
  7. package/cjs/lib/Signal/Group/keyhelper.js +56 -0
  8. package/cjs/lib/Signal/Group/sender-chain-key.js +30 -0
  9. package/cjs/lib/Signal/Group/sender-key-distribution-message.js +67 -0
  10. package/cjs/lib/Signal/Group/sender-key-message.js +70 -0
  11. package/cjs/lib/Signal/Group/sender-key-name.js +52 -0
  12. package/cjs/lib/Signal/Group/sender-key-record.js +45 -0
  13. package/cjs/lib/Signal/Group/sender-key-state.js +88 -0
  14. package/cjs/lib/Signal/Group/sender-message-key.js +30 -0
  15. package/cjs/lib/Signal/libsignal.js +467 -0
  16. package/cjs/lib/Signal/lid-mapping.js +281 -0
  17. package/cjs/lib/Socket/Client/index.js +19 -0
  18. package/cjs/lib/Socket/Client/types.js +15 -0
  19. package/cjs/lib/Socket/Client/websocket.js +61 -0
  20. package/cjs/lib/Socket/business.js +384 -0
  21. package/cjs/lib/Socket/chats.js +1257 -0
  22. package/cjs/lib/Socket/communities.js +442 -0
  23. package/cjs/lib/Socket/dugong.js +753 -0
  24. package/cjs/lib/Socket/groups.js +360 -0
  25. package/cjs/lib/Socket/index.js +19 -0
  26. package/cjs/lib/Socket/messages-recv.js +1790 -0
  27. package/cjs/lib/Socket/messages-send.js +1390 -0
  28. package/cjs/lib/Socket/mex.js +46 -0
  29. package/cjs/lib/Socket/newsletter.js +340 -0
  30. package/cjs/lib/Socket/socket.js +1007 -0
  31. package/cjs/lib/Store/index.js +20 -0
  32. package/cjs/lib/Store/make-in-memory-store.js +438 -0
  33. package/cjs/lib/Store/make-ordered-dictionary.js +82 -0
  34. package/cjs/lib/Store/object-repository.js +28 -0
  35. package/cjs/lib/Types/Auth.js +3 -0
  36. package/cjs/lib/Types/Bussines.js +3 -0
  37. package/cjs/lib/Types/Call.js +3 -0
  38. package/cjs/lib/Types/Chat.js +11 -0
  39. package/cjs/lib/Types/Contact.js +3 -0
  40. package/cjs/lib/Types/Events.js +4 -0
  41. package/cjs/lib/Types/GroupMetadata.js +3 -0
  42. package/cjs/lib/Types/Label.js +26 -0
  43. package/cjs/lib/Types/LabelAssociation.js +8 -0
  44. package/cjs/lib/Types/Message.js +19 -0
  45. package/cjs/lib/Types/Mex.js +40 -0
  46. package/cjs/lib/Types/Product.js +3 -0
  47. package/cjs/lib/Types/RichType.js +24 -0
  48. package/cjs/lib/Types/Signal.js +4 -0
  49. package/cjs/lib/Types/Socket.js +4 -0
  50. package/cjs/lib/Types/State.js +54 -0
  51. package/cjs/lib/Types/USync.js +4 -0
  52. package/cjs/lib/Types/index.js +42 -0
  53. package/cjs/lib/Utils/MessageBuilder.js +2164 -0
  54. package/cjs/lib/Utils/auth-utils.js +312 -0
  55. package/cjs/lib/Utils/browser-utils.js +32 -0
  56. package/cjs/lib/Utils/business.js +245 -0
  57. package/cjs/lib/Utils/chat-utils.js +937 -0
  58. package/cjs/lib/Utils/companion-reg-client-utils.js +45 -0
  59. package/cjs/lib/Utils/crypto.js +196 -0
  60. package/cjs/lib/Utils/decode-wa-message.js +324 -0
  61. package/cjs/lib/Utils/event-buffer.js +643 -0
  62. package/cjs/lib/Utils/generics.js +429 -0
  63. package/cjs/lib/Utils/history.js +151 -0
  64. package/cjs/lib/Utils/identity-change-handler.js +56 -0
  65. package/cjs/lib/Utils/index.js +42 -0
  66. package/cjs/lib/Utils/link-preview.js +122 -0
  67. package/cjs/lib/Utils/logger.js +8 -0
  68. package/cjs/lib/Utils/lt-hash.js +62 -0
  69. package/cjs/lib/Utils/make-mutex.js +38 -0
  70. package/cjs/lib/Utils/message-retry-manager.js +267 -0
  71. package/cjs/lib/Utils/messages-media.js +933 -0
  72. package/cjs/lib/Utils/messages.js +2175 -0
  73. package/cjs/lib/Utils/noise-handler.js +205 -0
  74. package/cjs/lib/Utils/offline-node-processor.js +43 -0
  75. package/cjs/lib/Utils/pre-key-manager.js +113 -0
  76. package/cjs/lib/Utils/process-message.js +772 -0
  77. package/cjs/lib/Utils/reporting-utils.js +263 -0
  78. package/cjs/lib/Utils/rich-message-utils.js +439 -0
  79. package/cjs/lib/Utils/signal.js +214 -0
  80. package/cjs/lib/Utils/stanza-ack.js +41 -0
  81. package/cjs/lib/Utils/sync-action-utils.js +54 -0
  82. package/cjs/lib/Utils/tc-token-utils.js +174 -0
  83. package/cjs/lib/Utils/use-multi-file-auth-state.js +125 -0
  84. package/cjs/lib/Utils/use-single-file-auth-state.js +121 -0
  85. package/cjs/lib/Utils/use-sqlite-auth-state.js +182 -0
  86. package/cjs/lib/Utils/validate-connection.js +210 -0
  87. package/cjs/lib/WABinary/constants.js +1470 -0
  88. package/cjs/lib/WABinary/decode.js +301 -0
  89. package/cjs/lib/WABinary/encode.js +257 -0
  90. package/cjs/lib/WABinary/generic-utils.js +274 -0
  91. package/cjs/lib/WABinary/index.js +22 -0
  92. package/cjs/lib/WABinary/jid-utils.js +114 -0
  93. package/cjs/lib/WABinary/types.js +37 -0
  94. package/cjs/lib/WAM/BinaryInfo.js +14 -0
  95. package/cjs/lib/WAM/constants.js +22856 -0
  96. package/cjs/lib/WAM/encode.js +154 -0
  97. package/cjs/lib/WAM/index.js +20 -0
  98. package/cjs/lib/WAUSync/Protocols/USyncContactProtocol.js +56 -0
  99. package/cjs/lib/WAUSync/Protocols/USyncDeviceProtocol.js +67 -0
  100. package/cjs/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +31 -0
  101. package/cjs/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  102. package/cjs/lib/WAUSync/Protocols/USyncUsernameProtocol.js +29 -0
  103. package/cjs/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +55 -0
  104. package/cjs/lib/WAUSync/Protocols/UsyncLIDProtocol.js +33 -0
  105. package/cjs/lib/WAUSync/Protocols/index.js +24 -0
  106. package/cjs/lib/WAUSync/USyncQuery.js +126 -0
  107. package/cjs/lib/WAUSync/USyncUser.js +35 -0
  108. package/cjs/lib/WAUSync/index.js +20 -0
  109. package/cjs/lib/index.js +34 -0
  110. package/cjs/package.json +1 -0
  111. package/lib/Socket/messages-send.js +4 -3
  112. package/lib/Utils/messages.js +4 -1
  113. package/package.json +16 -5
  114. package/postinstall-banner.js +3 -2
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SenderKeyName = void 0;
4
+ function isNull(str) {
5
+ return str === null || str === '';
6
+ }
7
+ function intValue(num) {
8
+ const MAX_VALUE = 0x7fffffff;
9
+ const MIN_VALUE = -0x80000000;
10
+ if (num > MAX_VALUE || num < MIN_VALUE) {
11
+ return num & 0xffffffff;
12
+ }
13
+ return num;
14
+ }
15
+ function hashCode(strKey) {
16
+ let hash = 0;
17
+ if (!isNull(strKey)) {
18
+ for (let i = 0; i < strKey.length; i++) {
19
+ hash = hash * 31 + strKey.charCodeAt(i);
20
+ hash = intValue(hash);
21
+ }
22
+ }
23
+ return hash;
24
+ }
25
+ class SenderKeyName {
26
+ constructor(groupId, sender) {
27
+ this.groupId = groupId;
28
+ this.sender = sender;
29
+ }
30
+ getGroupId() {
31
+ return this.groupId;
32
+ }
33
+ getSender() {
34
+ return this.sender;
35
+ }
36
+ serialize() {
37
+ return `${this.groupId}::${this.sender.id}::${this.sender.deviceId}`;
38
+ }
39
+ toString() {
40
+ return this.serialize();
41
+ }
42
+ equals(other) {
43
+ if (other === null)
44
+ return false;
45
+ return this.groupId === other.groupId && this.sender.toString() === other.sender.toString();
46
+ }
47
+ hashCode() {
48
+ return hashCode(this.groupId) ^ hashCode(this.sender.toString());
49
+ }
50
+ }
51
+ exports.SenderKeyName = SenderKeyName;
52
+ //# sourceMappingURL=sender-key-name.js.map
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SenderKeyRecord = void 0;
4
+ const generics_js_1 = require("../../Utils/generics.js");
5
+ const sender_key_state_js_1 = require("./sender-key-state.js");
6
+ class SenderKeyRecord {
7
+ constructor(serialized) {
8
+ this.MAX_STATES = 5;
9
+ this.senderKeyStates = [];
10
+ if (serialized) {
11
+ for (const structure of serialized) {
12
+ this.senderKeyStates.push(new sender_key_state_js_1.SenderKeyState(null, null, null, null, null, null, structure));
13
+ }
14
+ }
15
+ }
16
+ isEmpty() {
17
+ return this.senderKeyStates.length === 0;
18
+ }
19
+ getSenderKeyState(keyId) {
20
+ if (keyId === undefined && this.senderKeyStates.length) {
21
+ return this.senderKeyStates[this.senderKeyStates.length - 1];
22
+ }
23
+ return this.senderKeyStates.find(state => state.getKeyId() === keyId);
24
+ }
25
+ addSenderKeyState(id, iteration, chainKey, signatureKey) {
26
+ this.senderKeyStates.push(new sender_key_state_js_1.SenderKeyState(id, iteration, chainKey, null, signatureKey));
27
+ if (this.senderKeyStates.length > this.MAX_STATES) {
28
+ this.senderKeyStates.shift();
29
+ }
30
+ }
31
+ setSenderKeyState(id, iteration, chainKey, keyPair) {
32
+ this.senderKeyStates.length = 0;
33
+ this.senderKeyStates.push(new sender_key_state_js_1.SenderKeyState(id, iteration, chainKey, keyPair));
34
+ }
35
+ serialize() {
36
+ return this.senderKeyStates.map(state => state.getStructure());
37
+ }
38
+ static deserialize(data) {
39
+ const str = Buffer.from(data).toString('utf-8');
40
+ const parsed = JSON.parse(str, generics_js_1.BufferJSON.reviver);
41
+ return new SenderKeyRecord(parsed);
42
+ }
43
+ }
44
+ exports.SenderKeyRecord = SenderKeyRecord;
45
+ //# sourceMappingURL=sender-key-record.js.map
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SenderKeyState = void 0;
4
+ const sender_chain_key_js_1 = require("./sender-chain-key.js");
5
+ const sender_message_key_js_1 = require("./sender-message-key.js");
6
+ class SenderKeyState {
7
+ constructor(id, iteration, chainKey, signatureKeyPair, signatureKeyPublic, signatureKeyPrivate, senderKeyStateStructure) {
8
+ this.MAX_MESSAGE_KEYS = 2000;
9
+ if (senderKeyStateStructure) {
10
+ this.senderKeyStateStructure = {
11
+ ...senderKeyStateStructure,
12
+ senderMessageKeys: Array.isArray(senderKeyStateStructure.senderMessageKeys)
13
+ ? senderKeyStateStructure.senderMessageKeys
14
+ : []
15
+ };
16
+ }
17
+ else {
18
+ if (signatureKeyPair) {
19
+ signatureKeyPublic = signatureKeyPair.public;
20
+ signatureKeyPrivate = signatureKeyPair.private;
21
+ }
22
+ this.senderKeyStateStructure = {
23
+ senderKeyId: id || 0,
24
+ senderChainKey: {
25
+ iteration: iteration || 0,
26
+ seed: Buffer.from(chainKey || [])
27
+ },
28
+ senderSigningKey: {
29
+ public: Buffer.from(signatureKeyPublic || []),
30
+ private: Buffer.from(signatureKeyPrivate || [])
31
+ },
32
+ senderMessageKeys: []
33
+ };
34
+ }
35
+ }
36
+ getKeyId() {
37
+ return this.senderKeyStateStructure.senderKeyId;
38
+ }
39
+ getSenderChainKey() {
40
+ return new sender_chain_key_js_1.SenderChainKey(this.senderKeyStateStructure.senderChainKey.iteration, this.senderKeyStateStructure.senderChainKey.seed);
41
+ }
42
+ setSenderChainKey(chainKey) {
43
+ this.senderKeyStateStructure.senderChainKey = {
44
+ iteration: chainKey.getIteration(),
45
+ seed: chainKey.getSeed()
46
+ };
47
+ }
48
+ getSigningKeyPublic() {
49
+ const publicKey = Buffer.from(this.senderKeyStateStructure.senderSigningKey.public);
50
+ if (publicKey.length === 32) {
51
+ const fixed = Buffer.alloc(33);
52
+ fixed[0] = 0x05;
53
+ publicKey.copy(fixed, 1);
54
+ return fixed;
55
+ }
56
+ return publicKey;
57
+ }
58
+ getSigningKeyPrivate() {
59
+ const privateKey = this.senderKeyStateStructure.senderSigningKey.private;
60
+ return Buffer.from(privateKey || []);
61
+ }
62
+ hasSenderMessageKey(iteration) {
63
+ return this.senderKeyStateStructure.senderMessageKeys.some(key => key.iteration === iteration);
64
+ }
65
+ addSenderMessageKey(senderMessageKey) {
66
+ this.senderKeyStateStructure.senderMessageKeys.push({
67
+ iteration: senderMessageKey.getIteration(),
68
+ seed: senderMessageKey.getSeed()
69
+ });
70
+ if (this.senderKeyStateStructure.senderMessageKeys.length > this.MAX_MESSAGE_KEYS) {
71
+ this.senderKeyStateStructure.senderMessageKeys.shift();
72
+ }
73
+ }
74
+ removeSenderMessageKey(iteration) {
75
+ const index = this.senderKeyStateStructure.senderMessageKeys.findIndex(key => key.iteration === iteration);
76
+ if (index !== -1) {
77
+ const messageKey = this.senderKeyStateStructure.senderMessageKeys[index];
78
+ this.senderKeyStateStructure.senderMessageKeys.splice(index, 1);
79
+ return new sender_message_key_js_1.SenderMessageKey(messageKey.iteration, messageKey.seed);
80
+ }
81
+ return null;
82
+ }
83
+ getStructure() {
84
+ return this.senderKeyStateStructure;
85
+ }
86
+ }
87
+ exports.SenderKeyState = SenderKeyState;
88
+ //# sourceMappingURL=sender-key-state.js.map
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SenderMessageKey = void 0;
4
+ const crypto_js_1 = require("libsignal/src/crypto.js");
5
+ class SenderMessageKey {
6
+ constructor(iteration, seed) {
7
+ const derivative = (0, crypto_js_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;
30
+ //# sourceMappingURL=sender-message-key.js.map
@@ -0,0 +1,467 @@
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
+ // @ts-ignore
38
+ const libsignal = __importStar(require("libsignal"));
39
+ // @ts-ignore
40
+ const protobufs_js_1 = require("libsignal/src/protobufs.js");
41
+ const lru_cache_1 = require("lru-cache");
42
+ const index_js_1 = require("../Utils/index.js");
43
+ const index_js_2 = require("../WABinary/index.js");
44
+ const sender_key_name_js_1 = require("./Group/sender-key-name.js");
45
+ const sender_key_record_js_1 = require("./Group/sender-key-record.js");
46
+ const index_js_3 = require("./Group/index.js");
47
+ const lid_mapping_js_1 = require("./lid-mapping.js");
48
+ /** Extract identity key from PreKeyWhisperMessage for identity change detection */
49
+ function extractIdentityFromPkmsg(ciphertext) {
50
+ try {
51
+ if (!ciphertext || ciphertext.length < 2) {
52
+ return undefined;
53
+ }
54
+ // Version byte check (version 3)
55
+ const version = ciphertext[0];
56
+ if ((version & 0xf) !== 3) {
57
+ return undefined;
58
+ }
59
+ // Parse protobuf (skip version byte)
60
+ const preKeyProto = protobufs_js_1.PreKeyWhisperMessage.decode(ciphertext.slice(1));
61
+ if (preKeyProto.identityKey?.length === 33) {
62
+ return new Uint8Array(preKeyProto.identityKey);
63
+ }
64
+ return undefined;
65
+ }
66
+ catch {
67
+ return undefined;
68
+ }
69
+ }
70
+ function makeLibSignalRepository(auth, logger, pnToLIDFunc) {
71
+ const lidMapping = new lid_mapping_js_1.LIDMappingStore(auth.keys, logger, pnToLIDFunc);
72
+ const storage = signalStorage(auth, lidMapping);
73
+ const parsedKeys = auth.keys;
74
+ const migratedSessionCache = new lru_cache_1.LRUCache({
75
+ ttl: 3 * 24 * 60 * 60 * 1000, // 7 days
76
+ ttlAutopurge: true,
77
+ updateAgeOnGet: true
78
+ });
79
+ const ensureSenderKeyAndCreateSkdm = async (group, meId) => {
80
+ const senderName = jidToSignalSenderKeyName(group, meId);
81
+ const senderNameStr = senderName.toString();
82
+ const { [senderNameStr]: senderKey } = await auth.keys.get('sender-key', [senderNameStr]);
83
+ if (!senderKey) {
84
+ await storage.storeSenderKey(senderName, new sender_key_record_js_1.SenderKeyRecord());
85
+ }
86
+ const skdm = await new index_js_3.GroupSessionBuilder(storage).create(senderName);
87
+ return { senderName, skdm };
88
+ };
89
+ const repository = {
90
+ decryptGroupMessage({ group, authorJid, msg }) {
91
+ const senderName = jidToSignalSenderKeyName(group, authorJid);
92
+ const cipher = new index_js_3.GroupCipher(storage, senderName);
93
+ // Use transaction to ensure atomicity
94
+ return parsedKeys.transaction(async () => {
95
+ return cipher.decrypt(msg);
96
+ }, group);
97
+ },
98
+ async processSenderKeyDistributionMessage({ item, authorJid }) {
99
+ const builder = new index_js_3.GroupSessionBuilder(storage);
100
+ if (!item.groupId) {
101
+ throw new Error('Group ID is required for sender key distribution message');
102
+ }
103
+ const senderName = jidToSignalSenderKeyName(item.groupId, authorJid);
104
+ const senderMsg = new index_js_3.SenderKeyDistributionMessage(null, null, null, null, item.axolotlSenderKeyDistributionMessage);
105
+ const senderNameStr = senderName.toString();
106
+ const { [senderNameStr]: senderKey } = await auth.keys.get('sender-key', [senderNameStr]);
107
+ if (!senderKey) {
108
+ await storage.storeSenderKey(senderName, new sender_key_record_js_1.SenderKeyRecord());
109
+ }
110
+ return parsedKeys.transaction(async () => {
111
+ const { [senderNameStr]: senderKey } = await auth.keys.get('sender-key', [senderNameStr]);
112
+ if (!senderKey) {
113
+ await storage.storeSenderKey(senderName, new sender_key_record_js_1.SenderKeyRecord());
114
+ }
115
+ await builder.process(senderName, senderMsg);
116
+ }, item.groupId);
117
+ },
118
+ async decryptMessage({ jid, type, ciphertext }) {
119
+ const addr = jidToSignalProtocolAddress(jid);
120
+ const session = new libsignal.SessionCipher(storage, addr);
121
+ // Extract and save sender's identity key before decryption for identity change detection
122
+ if (type === 'pkmsg') {
123
+ const identityKey = extractIdentityFromPkmsg(ciphertext);
124
+ if (identityKey) {
125
+ const addrStr = addr.toString();
126
+ const identityChanged = await storage.saveIdentity(addrStr, identityKey);
127
+ if (identityChanged) {
128
+ logger.info({ jid, addr: addrStr }, 'identity key changed or new contact, session will be re-established');
129
+ }
130
+ }
131
+ }
132
+ async function doDecrypt() {
133
+ let result;
134
+ switch (type) {
135
+ case 'pkmsg':
136
+ result = await session.decryptPreKeyWhisperMessage(ciphertext);
137
+ break;
138
+ case 'msg':
139
+ result = await session.decryptWhisperMessage(ciphertext);
140
+ break;
141
+ }
142
+ return result;
143
+ }
144
+ // If it's not a sync message, we need to ensure atomicity
145
+ // For regular messages, we use a transaction to ensure atomicity
146
+ return parsedKeys.transaction(async () => {
147
+ return await doDecrypt();
148
+ }, jid);
149
+ },
150
+ async encryptMessage({ jid, data }) {
151
+ const addr = jidToSignalProtocolAddress(jid);
152
+ const cipher = new libsignal.SessionCipher(storage, addr);
153
+ // Use transaction to ensure atomicity
154
+ return parsedKeys.transaction(async () => {
155
+ const { type: sigType, body } = await cipher.encrypt(data);
156
+ const type = sigType === 3 ? 'pkmsg' : 'msg';
157
+ return { type, ciphertext: Buffer.from(body, 'binary') };
158
+ }, jid);
159
+ },
160
+ async encryptGroupMessage({ group, meId, data }) {
161
+ return parsedKeys.transaction(async () => {
162
+ const { senderName, skdm } = await ensureSenderKeyAndCreateSkdm(group, meId);
163
+ const ciphertext = await new index_js_3.GroupCipher(storage, senderName).encrypt(data);
164
+ return { ciphertext, senderKeyDistributionMessage: skdm.serialize() };
165
+ }, group);
166
+ },
167
+ async getSenderKeyDistributionMessage({ group, meId }) {
168
+ return parsedKeys.transaction(async () => {
169
+ const { skdm } = await ensureSenderKeyAndCreateSkdm(group, meId);
170
+ return skdm.serialize();
171
+ }, group);
172
+ },
173
+ async hasSenderKey({ group, meId }) {
174
+ const senderName = jidToSignalSenderKeyName(group, meId).toString();
175
+ const { [senderName]: key } = await auth.keys.get('sender-key', [senderName]);
176
+ return !!key;
177
+ },
178
+ async getSessionInfo(jid) {
179
+ const addr = jidToSignalProtocolAddress(jid).toString();
180
+ const session = (await storage.loadSession(addr));
181
+ if (!session) {
182
+ return null;
183
+ }
184
+ const open = session.getOpenSession?.();
185
+ const baseKey = open?.indexInfo?.baseKey;
186
+ const registrationId = open?.registrationId;
187
+ if (!baseKey || typeof registrationId !== 'number') {
188
+ return null;
189
+ }
190
+ return { baseKey: new Uint8Array(baseKey), registrationId };
191
+ },
192
+ async injectE2ESession({ jid, session }) {
193
+ logger.trace({ jid }, 'injecting E2EE session');
194
+ const cipher = new libsignal.SessionBuilder(storage, jidToSignalProtocolAddress(jid));
195
+ return parsedKeys.transaction(async () => {
196
+ // libsignal runtime accepts an absent prekey (initOutgoing checks `device.preKey && ...`)
197
+ // but the bundled .d.ts marks it required.
198
+ await cipher.initOutgoing(session);
199
+ }, jid);
200
+ },
201
+ jidToSignalProtocolAddress(jid) {
202
+ return jidToSignalProtocolAddress(jid).toString();
203
+ },
204
+ // Optimized direct access to LID mapping store
205
+ lidMapping,
206
+ async validateSession(jid) {
207
+ try {
208
+ const addr = jidToSignalProtocolAddress(jid);
209
+ const session = await storage.loadSession(addr.toString());
210
+ if (!session) {
211
+ return { exists: false, reason: 'no session' };
212
+ }
213
+ if (!session.haveOpenSession()) {
214
+ return { exists: false, reason: 'no open session' };
215
+ }
216
+ return { exists: true };
217
+ }
218
+ catch (error) {
219
+ return { exists: false, reason: 'validation error' };
220
+ }
221
+ },
222
+ async deleteSession(jids) {
223
+ if (!jids.length)
224
+ return;
225
+ // Convert JIDs to signal addresses and prepare for bulk deletion
226
+ const sessionUpdates = {};
227
+ jids.forEach(jid => {
228
+ const addr = jidToSignalProtocolAddress(jid);
229
+ sessionUpdates[addr.toString()] = null;
230
+ });
231
+ // Single transaction for all deletions
232
+ return parsedKeys.transaction(async () => {
233
+ await auth.keys.set({ session: sessionUpdates });
234
+ }, `delete-${jids.length}-sessions`);
235
+ },
236
+ close() {
237
+ migratedSessionCache.clear();
238
+ lidMapping.close();
239
+ },
240
+ async migrateSession(fromJid, toJid) {
241
+ // TODO: use usync to handle this entire mess
242
+ if (!fromJid || (!(0, index_js_2.isLidUser)(toJid) && !(0, index_js_2.isHostedLidUser)(toJid)))
243
+ return { migrated: 0, skipped: 0, total: 0 };
244
+ // Only support PN to LID migration
245
+ if (!(0, index_js_2.isPnUser)(fromJid) && !(0, index_js_2.isHostedPnUser)(fromJid)) {
246
+ return { migrated: 0, skipped: 0, total: 1 };
247
+ }
248
+ const { user } = (0, index_js_2.jidDecode)(fromJid);
249
+ logger.debug({ fromJid }, 'bulk device migration - loading all user devices');
250
+ // Get user's device list from storage
251
+ const { [user]: userDevices } = await parsedKeys.get('device-list', [user]);
252
+ if (!userDevices) {
253
+ return { migrated: 0, skipped: 0, total: 0 };
254
+ }
255
+ const { device: fromDevice } = (0, index_js_2.jidDecode)(fromJid);
256
+ const fromDeviceStr = fromDevice?.toString() || '0';
257
+ if (!userDevices.includes(fromDeviceStr)) {
258
+ userDevices.push(fromDeviceStr);
259
+ }
260
+ // Filter out cached devices before database fetch
261
+ const uncachedDevices = userDevices.filter(device => {
262
+ const deviceKey = `${user}.${device}`;
263
+ return !migratedSessionCache.has(deviceKey);
264
+ });
265
+ // Bulk check session existence only for uncached devices
266
+ const deviceSessionKeys = uncachedDevices.map(device => `${user}.${device}`);
267
+ const existingSessions = await parsedKeys.get('session', deviceSessionKeys);
268
+ // Step 3: Convert existing sessions to JIDs (only migrate sessions that exist)
269
+ const deviceJids = [];
270
+ for (const [sessionKey, sessionData] of Object.entries(existingSessions)) {
271
+ if (sessionData) {
272
+ // Session exists in storage
273
+ const deviceStr = sessionKey.split('.')[1];
274
+ if (!deviceStr)
275
+ continue;
276
+ const deviceNum = parseInt(deviceStr);
277
+ let jid = deviceNum === 0 ? `${user}@s.whatsapp.net` : `${user}:${deviceNum}@s.whatsapp.net`;
278
+ if (deviceNum === 99) {
279
+ jid = `${user}:99@hosted`;
280
+ }
281
+ deviceJids.push(jid);
282
+ }
283
+ }
284
+ logger.debug({
285
+ fromJid,
286
+ totalDevices: userDevices.length,
287
+ devicesWithSessions: deviceJids.length,
288
+ devices: deviceJids
289
+ }, 'bulk device migration complete - all user devices processed');
290
+ // Single transaction for all migrations
291
+ return parsedKeys.transaction(async () => {
292
+ const migrationOps = deviceJids.map(jid => {
293
+ const lidWithDevice = (0, index_js_2.transferDevice)(jid, toJid);
294
+ const fromDecoded = (0, index_js_2.jidDecode)(jid);
295
+ const toDecoded = (0, index_js_2.jidDecode)(lidWithDevice);
296
+ return {
297
+ fromJid: jid,
298
+ toJid: lidWithDevice,
299
+ pnUser: fromDecoded.user,
300
+ lidUser: toDecoded.user,
301
+ deviceId: fromDecoded.device || 0,
302
+ fromAddr: jidToSignalProtocolAddress(jid),
303
+ toAddr: jidToSignalProtocolAddress(lidWithDevice)
304
+ };
305
+ });
306
+ const totalOps = migrationOps.length;
307
+ let migratedCount = 0;
308
+ // Bulk fetch PN sessions - already exist (verified during device discovery)
309
+ const pnAddrStrings = Array.from(new Set(migrationOps.map(op => op.fromAddr.toString())));
310
+ const pnSessions = await parsedKeys.get('session', pnAddrStrings);
311
+ // Prepare bulk session updates (PN → LID migration + deletion)
312
+ const sessionUpdates = {};
313
+ for (const op of migrationOps) {
314
+ const pnAddrStr = op.fromAddr.toString();
315
+ const lidAddrStr = op.toAddr.toString();
316
+ const pnSession = pnSessions[pnAddrStr];
317
+ if (pnSession) {
318
+ // Session exists (guaranteed from device discovery)
319
+ const fromSession = libsignal.SessionRecord.deserialize(pnSession);
320
+ if (fromSession.haveOpenSession()) {
321
+ // Queue for bulk update: copy to LID, delete from PN
322
+ sessionUpdates[lidAddrStr] = fromSession.serialize();
323
+ sessionUpdates[pnAddrStr] = null;
324
+ migratedCount++;
325
+ }
326
+ }
327
+ }
328
+ // Single bulk session update for all migrations
329
+ if (Object.keys(sessionUpdates).length > 0) {
330
+ await parsedKeys.set({ session: sessionUpdates });
331
+ logger.debug({ migratedSessions: migratedCount }, 'bulk session migration complete');
332
+ // Cache device-level migrations
333
+ for (const op of migrationOps) {
334
+ if (sessionUpdates[op.toAddr.toString()]) {
335
+ const deviceKey = `${op.pnUser}.${op.deviceId}`;
336
+ migratedSessionCache.set(deviceKey, true);
337
+ }
338
+ }
339
+ }
340
+ const skippedCount = totalOps - migratedCount;
341
+ return { migrated: migratedCount, skipped: skippedCount, total: totalOps };
342
+ }, `migrate-${deviceJids.length}-sessions-${(0, index_js_2.jidDecode)(toJid)?.user}`);
343
+ }
344
+ };
345
+ return repository;
346
+ }
347
+ const jidToSignalProtocolAddress = (jid) => {
348
+ const decoded = (0, index_js_2.jidDecode)(jid);
349
+ const { user, device, server, domainType } = decoded;
350
+ if (!user) {
351
+ throw new Error(`JID decoded but user is empty: "${jid}" -> user: "${user}", server: "${server}", device: ${device}`);
352
+ }
353
+ const signalUser = domainType !== index_js_2.WAJIDDomains.WHATSAPP ? `${user}_${domainType}` : user;
354
+ const finalDevice = device || 0;
355
+ if (device === 99 && decoded.server !== 'hosted' && decoded.server !== 'hosted.lid') {
356
+ throw new Error('Unexpected non-hosted device JID with device 99. This ID seems invalid. ID:' + jid);
357
+ }
358
+ return new libsignal.ProtocolAddress(signalUser, finalDevice);
359
+ };
360
+ const jidToSignalSenderKeyName = (group, user) => {
361
+ return new sender_key_name_js_1.SenderKeyName(group, jidToSignalProtocolAddress(user));
362
+ };
363
+ function signalStorage({ creds, keys }, lidMapping) {
364
+ // Shared function to resolve PN signal address to LID if mapping exists
365
+ const resolveLIDSignalAddress = async (id) => {
366
+ if (id.includes('.')) {
367
+ const [deviceId, device] = id.split('.');
368
+ const [user, domainType_] = deviceId.split('_');
369
+ const domainType = parseInt(domainType_ || '0');
370
+ if (domainType === index_js_2.WAJIDDomains.LID || domainType === index_js_2.WAJIDDomains.HOSTED_LID)
371
+ return id;
372
+ const pnJid = `${user}${device !== '0' ? `:${device}` : ''}@${domainType === index_js_2.WAJIDDomains.HOSTED ? 'hosted' : 's.whatsapp.net'}`;
373
+ const lidForPN = await lidMapping.getLIDForPN(pnJid);
374
+ if (lidForPN) {
375
+ const lidAddr = jidToSignalProtocolAddress(lidForPN);
376
+ return lidAddr.toString();
377
+ }
378
+ }
379
+ return id;
380
+ };
381
+ return {
382
+ loadSession: async (id) => {
383
+ try {
384
+ const wireJid = await resolveLIDSignalAddress(id);
385
+ const { [wireJid]: sess } = await keys.get('session', [wireJid]);
386
+ if (sess) {
387
+ return libsignal.SessionRecord.deserialize(sess);
388
+ }
389
+ }
390
+ catch (e) {
391
+ return null;
392
+ }
393
+ return null;
394
+ },
395
+ storeSession: async (id, session) => {
396
+ const wireJid = await resolveLIDSignalAddress(id);
397
+ await keys.set({ session: { [wireJid]: session.serialize() } });
398
+ },
399
+ isTrustedIdentity: () => {
400
+ return true; // TOFU - Trust on First Use (same as WhatsApp Web)
401
+ },
402
+ loadIdentityKey: async (id) => {
403
+ const wireJid = await resolveLIDSignalAddress(id);
404
+ const { [wireJid]: key } = await keys.get('identity-key', [wireJid]);
405
+ return key || undefined;
406
+ },
407
+ saveIdentity: async (id, identityKey) => {
408
+ const wireJid = await resolveLIDSignalAddress(id);
409
+ const { [wireJid]: existingKey } = await keys.get('identity-key', [wireJid]);
410
+ const keysMatch = existingKey?.length === identityKey.length && existingKey.every((byte, i) => byte === identityKey[i]);
411
+ if (existingKey && !keysMatch) {
412
+ // Identity changed - clear session and update key
413
+ await keys.set({
414
+ session: { [wireJid]: null },
415
+ 'identity-key': { [wireJid]: identityKey }
416
+ });
417
+ return true;
418
+ }
419
+ if (!existingKey) {
420
+ // New contact - Trust on First Use (TOFU)
421
+ await keys.set({ 'identity-key': { [wireJid]: identityKey } });
422
+ return true;
423
+ }
424
+ return false;
425
+ },
426
+ loadPreKey: async (id) => {
427
+ const keyId = id.toString();
428
+ const { [keyId]: key } = await keys.get('pre-key', [keyId]);
429
+ if (key) {
430
+ return {
431
+ privKey: Buffer.from(key.private),
432
+ pubKey: Buffer.from(key.public)
433
+ };
434
+ }
435
+ },
436
+ removePreKey: (id) => keys.set({ 'pre-key': { [id]: null } }),
437
+ loadSignedPreKey: () => {
438
+ const key = creds.signedPreKey;
439
+ return {
440
+ privKey: Buffer.from(key.keyPair.private),
441
+ pubKey: Buffer.from(key.keyPair.public)
442
+ };
443
+ },
444
+ loadSenderKey: async (senderKeyName) => {
445
+ const keyId = senderKeyName.toString();
446
+ const { [keyId]: key } = await keys.get('sender-key', [keyId]);
447
+ if (key) {
448
+ return sender_key_record_js_1.SenderKeyRecord.deserialize(key);
449
+ }
450
+ return new sender_key_record_js_1.SenderKeyRecord();
451
+ },
452
+ storeSenderKey: async (senderKeyName, key) => {
453
+ const keyId = senderKeyName.toString();
454
+ const serialized = JSON.stringify(key.serialize());
455
+ await keys.set({ 'sender-key': { [keyId]: Buffer.from(serialized, 'utf-8') } });
456
+ },
457
+ getOurRegistrationId: () => creds.registrationId,
458
+ getOurIdentity: () => {
459
+ const { signedIdentityKey } = creds;
460
+ return {
461
+ privKey: Buffer.from(signedIdentityKey.private),
462
+ pubKey: Buffer.from((0, index_js_1.generateSignalPubKey)(signedIdentityKey.public))
463
+ };
464
+ }
465
+ };
466
+ }
467
+ //# sourceMappingURL=libsignal.js.map