@skyzopedia/baileys-mod 3.0.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.
- package/LICENSE +21 -0
- package/WAProto/WAProto.proto +5311 -0
- package/WAProto/index.js +94091 -0
- package/lib/Defaults/index.js +123 -0
- package/lib/KeyDB/BinarySearch.js +20 -0
- package/lib/KeyDB/KeyedDB.js +167 -0
- package/lib/KeyDB/index.js +4 -0
- package/lib/Signal/Group/ciphertext-message.js +13 -0
- package/lib/Signal/Group/group-session-builder.js +32 -0
- package/lib/Signal/Group/group_cipher.js +84 -0
- package/lib/Signal/Group/index.js +13 -0
- package/lib/Signal/Group/keyhelper.js +20 -0
- package/lib/Signal/Group/sender-chain-key.js +28 -0
- package/lib/Signal/Group/sender-key-distribution-message.js +65 -0
- package/lib/Signal/Group/sender-key-message.js +68 -0
- package/lib/Signal/Group/sender-key-name.js +52 -0
- package/lib/Signal/Group/sender-key-record.js +43 -0
- package/lib/Signal/Group/sender-key-state.js +86 -0
- package/lib/Signal/Group/sender-message-key.js +28 -0
- package/lib/Signal/libsignal.js +324 -0
- package/lib/Signal/lid-mapping.js +155 -0
- package/lib/Socket/Client/index.js +4 -0
- package/lib/Socket/Client/types.js +13 -0
- package/lib/Socket/Client/websocket.js +52 -0
- package/lib/Socket/business.js +377 -0
- package/lib/Socket/chats.js +881 -0
- package/lib/Socket/communities.js +413 -0
- package/lib/Socket/groups.js +312 -0
- package/lib/Socket/index.js +16 -0
- package/lib/Socket/messages-recv.js +1163 -0
- package/lib/Socket/messages-send.js +1082 -0
- package/lib/Socket/mex.js +45 -0
- package/lib/Socket/newsletter.js +259 -0
- package/lib/Socket/socket.js +781 -0
- package/lib/Store/index.js +6 -0
- package/lib/Store/make-cache-manager-store.js +75 -0
- package/lib/Store/make-in-memory-store.js +290 -0
- package/lib/Store/make-ordered-dictionary.js +79 -0
- package/lib/Store/object-repository.js +25 -0
- package/lib/Types/Auth.js +3 -0
- package/lib/Types/Bussines.js +3 -0
- package/lib/Types/Call.js +3 -0
- package/lib/Types/Chat.js +9 -0
- package/lib/Types/Contact.js +3 -0
- package/lib/Types/Events.js +3 -0
- package/lib/Types/GroupMetadata.js +3 -0
- package/lib/Types/Label.js +25 -0
- package/lib/Types/LabelAssociation.js +7 -0
- package/lib/Types/Message.js +12 -0
- package/lib/Types/Newsletter.js +33 -0
- package/lib/Types/Newsletter.js.bak +33 -0
- package/lib/Types/Product.js +3 -0
- package/lib/Types/Signal.js +3 -0
- package/lib/Types/Socket.js +4 -0
- package/lib/Types/State.js +11 -0
- package/lib/Types/USync.js +3 -0
- package/lib/Types/index.js +28 -0
- package/lib/Utils/auth-utils.js +219 -0
- package/lib/Utils/baileys-event-stream.js +44 -0
- package/lib/Utils/browser-utils.js +17 -0
- package/lib/Utils/business.js +233 -0
- package/lib/Utils/chat-utils.js +752 -0
- package/lib/Utils/crypto.js +130 -0
- package/lib/Utils/decode-wa-message.js +267 -0
- package/lib/Utils/event-buffer.js +528 -0
- package/lib/Utils/generics.js +355 -0
- package/lib/Utils/history.js +87 -0
- package/lib/Utils/index.js +21 -0
- package/lib/Utils/link-preview.js +81 -0
- package/lib/Utils/logger.js +5 -0
- package/lib/Utils/lt-hash.js +45 -0
- package/lib/Utils/make-mutex.js +36 -0
- package/lib/Utils/message-retry-manager.js +113 -0
- package/lib/Utils/messages-media.js +601 -0
- package/lib/Utils/messages.js +776 -0
- package/lib/Utils/noise-handler.js +144 -0
- package/lib/Utils/pre-key-manager.js +85 -0
- package/lib/Utils/process-message.js +341 -0
- package/lib/Utils/signal.js +161 -0
- package/lib/Utils/use-multi-file-auth-state.js +111 -0
- package/lib/Utils/validate-connection.js +200 -0
- package/lib/WABinary/constants.js +1303 -0
- package/lib/WABinary/decode.js +240 -0
- package/lib/WABinary/encode.js +218 -0
- package/lib/WABinary/generic-utils.js +113 -0
- package/lib/WABinary/index.js +7 -0
- package/lib/WABinary/jid-utils.js +93 -0
- package/lib/WABinary/types.js +3 -0
- package/lib/WAM/BinaryInfo.js +11 -0
- package/lib/WAM/constants.js +22853 -0
- package/lib/WAM/encode.js +154 -0
- package/lib/WAM/index.js +5 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +30 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +29 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +39 -0
- package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +30 -0
- package/lib/WAUSync/Protocols/index.js +6 -0
- package/lib/WAUSync/USyncQuery.js +90 -0
- package/lib/WAUSync/USyncUser.js +24 -0
- package/lib/WAUSync/index.js +5 -0
- package/lib/index.js +15 -0
- package/package.json +102 -0
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
//=======================================================//
|
|
2
|
+
function isNull(str) {
|
|
3
|
+
return str === null || str === "";
|
|
4
|
+
}
|
|
5
|
+
//=======================================================//
|
|
6
|
+
function intValue(num) {
|
|
7
|
+
const MAX_VALUE = 0x7fffffff;
|
|
8
|
+
const MIN_VALUE = -0x80000000;
|
|
9
|
+
if (num > MAX_VALUE || num < MIN_VALUE) {
|
|
10
|
+
return num & 0xffffffff;
|
|
11
|
+
}
|
|
12
|
+
return num;
|
|
13
|
+
}
|
|
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
|
+
//=======================================================//
|
|
26
|
+
export class SenderKeyName {
|
|
27
|
+
constructor(groupId, sender) {
|
|
28
|
+
this.groupId = groupId;
|
|
29
|
+
this.sender = sender;
|
|
30
|
+
}
|
|
31
|
+
getGroupId() {
|
|
32
|
+
return this.groupId;
|
|
33
|
+
}
|
|
34
|
+
getSender() {
|
|
35
|
+
return this.sender;
|
|
36
|
+
}
|
|
37
|
+
serialize() {
|
|
38
|
+
return `${this.groupId}::${this.sender.id}::${this.sender.deviceId}`;
|
|
39
|
+
}
|
|
40
|
+
toString() {
|
|
41
|
+
return this.serialize();
|
|
42
|
+
}
|
|
43
|
+
equals(other) {
|
|
44
|
+
if (other === null)
|
|
45
|
+
return false;
|
|
46
|
+
return this.groupId === other.groupId && this.sender.toString() === other.sender.toString();
|
|
47
|
+
}
|
|
48
|
+
hashCode() {
|
|
49
|
+
return hashCode(this.groupId) ^ hashCode(this.sender.toString());
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
//=======================================================//
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
//=======================================================//
|
|
2
|
+
import { SenderKeyState } from "./sender-key-state.js";
|
|
3
|
+
import { BufferJSON } from "../../Utils/generics.js";
|
|
4
|
+
//=======================================================//
|
|
5
|
+
export class SenderKeyRecord {
|
|
6
|
+
constructor(serialized) {
|
|
7
|
+
this.MAX_STATES = 5;
|
|
8
|
+
this.senderKeyStates = [];
|
|
9
|
+
if (serialized) {
|
|
10
|
+
for (const structure of serialized) {
|
|
11
|
+
this.senderKeyStates.push(new SenderKeyState(null, null, null, null, null, null, structure));
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
isEmpty() {
|
|
16
|
+
return this.senderKeyStates.length === 0;
|
|
17
|
+
}
|
|
18
|
+
getSenderKeyState(keyId) {
|
|
19
|
+
if (keyId === undefined && this.senderKeyStates.length) {
|
|
20
|
+
return this.senderKeyStates[this.senderKeyStates.length - 1];
|
|
21
|
+
}
|
|
22
|
+
return this.senderKeyStates.find(state => state.getKeyId() === keyId);
|
|
23
|
+
}
|
|
24
|
+
addSenderKeyState(id, iteration, chainKey, signatureKey) {
|
|
25
|
+
this.senderKeyStates.push(new SenderKeyState(id, iteration, chainKey, null, signatureKey));
|
|
26
|
+
if (this.senderKeyStates.length > this.MAX_STATES) {
|
|
27
|
+
this.senderKeyStates.shift();
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
setSenderKeyState(id, iteration, chainKey, keyPair) {
|
|
31
|
+
this.senderKeyStates.length = 0;
|
|
32
|
+
this.senderKeyStates.push(new SenderKeyState(id, iteration, chainKey, keyPair));
|
|
33
|
+
}
|
|
34
|
+
serialize() {
|
|
35
|
+
return this.senderKeyStates.map(state => state.getStructure());
|
|
36
|
+
}
|
|
37
|
+
static deserialize(data) {
|
|
38
|
+
const str = Buffer.from(data).toString("utf-8");
|
|
39
|
+
const parsed = JSON.parse(str, BufferJSON.reviver);
|
|
40
|
+
return new SenderKeyRecord(parsed);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
//=======================================================//
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
//=======================================================//
|
|
2
|
+
import { SenderMessageKey } from "./sender-message-key.js";
|
|
3
|
+
import { SenderChainKey } from "./sender-chain-key.js";
|
|
4
|
+
//=======================================================//
|
|
5
|
+
export class SenderKeyState {
|
|
6
|
+
constructor(id, iteration, chainKey, signatureKeyPair, signatureKeyPublic, signatureKeyPrivate, senderKeyStateStructure) {
|
|
7
|
+
this.MAX_MESSAGE_KEYS = 2000;
|
|
8
|
+
if (senderKeyStateStructure) {
|
|
9
|
+
this.senderKeyStateStructure = {
|
|
10
|
+
...senderKeyStateStructure,
|
|
11
|
+
senderMessageKeys: Array.isArray(senderKeyStateStructure.senderMessageKeys)
|
|
12
|
+
? senderKeyStateStructure.senderMessageKeys
|
|
13
|
+
: []
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
else {
|
|
17
|
+
if (signatureKeyPair) {
|
|
18
|
+
signatureKeyPublic = signatureKeyPair.public;
|
|
19
|
+
signatureKeyPrivate = signatureKeyPair.private;
|
|
20
|
+
}
|
|
21
|
+
this.senderKeyStateStructure = {
|
|
22
|
+
senderKeyId: id || 0,
|
|
23
|
+
senderChainKey: {
|
|
24
|
+
iteration: iteration || 0,
|
|
25
|
+
seed: Buffer.from(chainKey || [])
|
|
26
|
+
},
|
|
27
|
+
senderSigningKey: {
|
|
28
|
+
public: Buffer.from(signatureKeyPublic || []),
|
|
29
|
+
private: Buffer.from(signatureKeyPrivate || [])
|
|
30
|
+
},
|
|
31
|
+
senderMessageKeys: []
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
getKeyId() {
|
|
36
|
+
return this.senderKeyStateStructure.senderKeyId;
|
|
37
|
+
}
|
|
38
|
+
getSenderChainKey() {
|
|
39
|
+
return new SenderChainKey(this.senderKeyStateStructure.senderChainKey.iteration, this.senderKeyStateStructure.senderChainKey.seed);
|
|
40
|
+
}
|
|
41
|
+
setSenderChainKey(chainKey) {
|
|
42
|
+
this.senderKeyStateStructure.senderChainKey = {
|
|
43
|
+
iteration: chainKey.getIteration(),
|
|
44
|
+
seed: chainKey.getSeed()
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
getSigningKeyPublic() {
|
|
48
|
+
const publicKey = Buffer.from(this.senderKeyStateStructure.senderSigningKey.public);
|
|
49
|
+
if (publicKey.length === 32) {
|
|
50
|
+
const fixed = Buffer.alloc(33);
|
|
51
|
+
fixed[0] = 0x05;
|
|
52
|
+
publicKey.copy(fixed, 1);
|
|
53
|
+
return fixed;
|
|
54
|
+
}
|
|
55
|
+
return publicKey;
|
|
56
|
+
}
|
|
57
|
+
getSigningKeyPrivate() {
|
|
58
|
+
const privateKey = this.senderKeyStateStructure.senderSigningKey.private;
|
|
59
|
+
return Buffer.from(privateKey || []);
|
|
60
|
+
}
|
|
61
|
+
hasSenderMessageKey(iteration) {
|
|
62
|
+
return this.senderKeyStateStructure.senderMessageKeys.some(key => key.iteration === iteration);
|
|
63
|
+
}
|
|
64
|
+
addSenderMessageKey(senderMessageKey) {
|
|
65
|
+
this.senderKeyStateStructure.senderMessageKeys.push({
|
|
66
|
+
iteration: senderMessageKey.getIteration(),
|
|
67
|
+
seed: senderMessageKey.getSeed()
|
|
68
|
+
});
|
|
69
|
+
if (this.senderKeyStateStructure.senderMessageKeys.length > this.MAX_MESSAGE_KEYS) {
|
|
70
|
+
this.senderKeyStateStructure.senderMessageKeys.shift();
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
removeSenderMessageKey(iteration) {
|
|
74
|
+
const index = this.senderKeyStateStructure.senderMessageKeys.findIndex(key => key.iteration === iteration);
|
|
75
|
+
if (index !== -1) {
|
|
76
|
+
const messageKey = this.senderKeyStateStructure.senderMessageKeys[index];
|
|
77
|
+
this.senderKeyStateStructure.senderMessageKeys.splice(index, 1);
|
|
78
|
+
return new SenderMessageKey(messageKey.iteration, messageKey.seed);
|
|
79
|
+
}
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
getStructure() {
|
|
83
|
+
return this.senderKeyStateStructure;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
//=======================================================//
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
//=======================================================//
|
|
2
|
+
import { deriveSecrets } from "libsignal-xeuka/src/crypto.js";
|
|
3
|
+
//=======================================================//
|
|
4
|
+
export class SenderMessageKey {
|
|
5
|
+
constructor(iteration, seed) {
|
|
6
|
+
const derivative = deriveSecrets(seed, Buffer.alloc(32), Buffer.from("WhisperGroup"));
|
|
7
|
+
const keys = new Uint8Array(32);
|
|
8
|
+
keys.set(new Uint8Array(derivative[0].slice(16)));
|
|
9
|
+
keys.set(new Uint8Array(derivative[1].slice(0, 16)), 16);
|
|
10
|
+
this.iv = Buffer.from(derivative[0].slice(0, 16));
|
|
11
|
+
this.cipherKey = Buffer.from(keys.buffer);
|
|
12
|
+
this.iteration = iteration;
|
|
13
|
+
this.seed = seed;
|
|
14
|
+
}
|
|
15
|
+
getIteration() {
|
|
16
|
+
return this.iteration;
|
|
17
|
+
}
|
|
18
|
+
getIv() {
|
|
19
|
+
return this.iv;
|
|
20
|
+
}
|
|
21
|
+
getCipherKey() {
|
|
22
|
+
return this.cipherKey;
|
|
23
|
+
}
|
|
24
|
+
getSeed() {
|
|
25
|
+
return this.seed;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
//=======================================================//
|
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
//=======================================================//
|
|
2
|
+
import { isHostedLidUser, isHostedPnUser, isLidUser, isPnUser, jidDecode, transferDevice, WAJIDDomains } from "../WABinary/index.js";
|
|
3
|
+
import { GroupCipher, GroupSessionBuilder, SenderKeyDistributionMessage } from "./Group/index.js";
|
|
4
|
+
import { SenderKeyRecord } from "./Group/sender-key-record.js";
|
|
5
|
+
import { SenderKeyName } from "./Group/sender-key-name.js";
|
|
6
|
+
import { generateSignalPubKey } from "../Utils/index.js";
|
|
7
|
+
import { LIDMappingStore } from "./lid-mapping.js";
|
|
8
|
+
import * as libsignal from "libsignal-xeuka";
|
|
9
|
+
import { LRUCache } from "lru-cache";
|
|
10
|
+
//=======================================================//
|
|
11
|
+
export function makeLibSignalRepository(auth, logger, pnToLIDFunc) {
|
|
12
|
+
const lidMapping = new LIDMappingStore(auth.keys, logger, pnToLIDFunc);
|
|
13
|
+
const storage = signalStorage(auth, lidMapping);
|
|
14
|
+
const parsedKeys = auth.keys;
|
|
15
|
+
const migratedSessionCache = new LRUCache({
|
|
16
|
+
ttl: 7 * 24 * 60 * 60 * 1000,
|
|
17
|
+
ttlAutopurge: true,
|
|
18
|
+
updateAgeOnGet: true
|
|
19
|
+
});
|
|
20
|
+
const repository = {
|
|
21
|
+
decryptGroupMessage({ group, authorJid, msg }) {
|
|
22
|
+
const senderName = jidToSignalSenderKeyName(group, authorJid);
|
|
23
|
+
const cipher = new GroupCipher(storage, senderName);
|
|
24
|
+
return parsedKeys.transaction(async () => {
|
|
25
|
+
return cipher.decrypt(msg);
|
|
26
|
+
}, group);
|
|
27
|
+
},
|
|
28
|
+
async processSenderKeyDistributionMessage({ item, authorJid }) {
|
|
29
|
+
const builder = new GroupSessionBuilder(storage);
|
|
30
|
+
if (!item.groupId) {
|
|
31
|
+
throw new Error("Group ID is required for sender key distribution message");
|
|
32
|
+
}
|
|
33
|
+
const senderName = jidToSignalSenderKeyName(item.groupId, authorJid);
|
|
34
|
+
const senderMsg = new SenderKeyDistributionMessage(null, null, null, null, item.axolotlSenderKeyDistributionMessage);
|
|
35
|
+
const senderNameStr = senderName.toString();
|
|
36
|
+
const { [senderNameStr]: senderKey } = await auth.keys.get("sender-key", [senderNameStr]);
|
|
37
|
+
if (!senderKey) {
|
|
38
|
+
await storage.storeSenderKey(senderName, new SenderKeyRecord());
|
|
39
|
+
}
|
|
40
|
+
return parsedKeys.transaction(async () => {
|
|
41
|
+
const { [senderNameStr]: senderKey } = await auth.keys.get("sender-key", [senderNameStr]);
|
|
42
|
+
if (!senderKey) {
|
|
43
|
+
await storage.storeSenderKey(senderName, new SenderKeyRecord());
|
|
44
|
+
}
|
|
45
|
+
await builder.process(senderName, senderMsg);
|
|
46
|
+
}, item.groupId);
|
|
47
|
+
},
|
|
48
|
+
async decryptMessage({ jid, type, ciphertext }) {
|
|
49
|
+
const addr = jidToSignalProtocolAddress(jid);
|
|
50
|
+
const session = new libsignal.SessionCipher(storage, addr);
|
|
51
|
+
async function doDecrypt() {
|
|
52
|
+
let result;
|
|
53
|
+
switch (type) {
|
|
54
|
+
case "pkmsg":
|
|
55
|
+
result = await session.decryptPreKeyWhisperMessage(ciphertext);
|
|
56
|
+
break;
|
|
57
|
+
case "msg":
|
|
58
|
+
result = await session.decryptWhisperMessage(ciphertext);
|
|
59
|
+
break;
|
|
60
|
+
}
|
|
61
|
+
return result;
|
|
62
|
+
}
|
|
63
|
+
return parsedKeys.transaction(async () => {
|
|
64
|
+
return await doDecrypt();
|
|
65
|
+
}, jid);
|
|
66
|
+
},
|
|
67
|
+
async encryptMessage({ jid, data }) {
|
|
68
|
+
const addr = jidToSignalProtocolAddress(jid);
|
|
69
|
+
const cipher = new libsignal.SessionCipher(storage, addr);
|
|
70
|
+
return parsedKeys.transaction(async () => {
|
|
71
|
+
const { type: sigType, body } = await cipher.encrypt(data);
|
|
72
|
+
const type = sigType === 3 ? "pkmsg" : "msg";
|
|
73
|
+
return { type, ciphertext: Buffer.from(body, "binary") };
|
|
74
|
+
}, jid);
|
|
75
|
+
},
|
|
76
|
+
async encryptGroupMessage({ group, meId, data }) {
|
|
77
|
+
const senderName = jidToSignalSenderKeyName(group, meId);
|
|
78
|
+
const builder = new GroupSessionBuilder(storage);
|
|
79
|
+
const senderNameStr = senderName.toString();
|
|
80
|
+
return parsedKeys.transaction(async () => {
|
|
81
|
+
const { [senderNameStr]: senderKey } = await auth.keys.get("sender-key", [senderNameStr]);
|
|
82
|
+
if (!senderKey) {
|
|
83
|
+
await storage.storeSenderKey(senderName, new SenderKeyRecord());
|
|
84
|
+
}
|
|
85
|
+
const senderKeyDistributionMessage = await builder.create(senderName);
|
|
86
|
+
const session = new GroupCipher(storage, senderName);
|
|
87
|
+
const ciphertext = await session.encrypt(data);
|
|
88
|
+
return {
|
|
89
|
+
ciphertext,
|
|
90
|
+
senderKeyDistributionMessage: senderKeyDistributionMessage.serialize()
|
|
91
|
+
};
|
|
92
|
+
}, group);
|
|
93
|
+
},
|
|
94
|
+
async injectE2ESession({ jid, session }) {
|
|
95
|
+
logger.trace({ jid }, "injecting E2EE session");
|
|
96
|
+
const cipher = new libsignal.SessionBuilder(storage, jidToSignalProtocolAddress(jid));
|
|
97
|
+
return parsedKeys.transaction(async () => {
|
|
98
|
+
await cipher.initOutgoing(session);
|
|
99
|
+
}, jid);
|
|
100
|
+
},
|
|
101
|
+
jidToSignalProtocolAddress(jid) {
|
|
102
|
+
return jidToSignalProtocolAddress(jid).toString();
|
|
103
|
+
},
|
|
104
|
+
lidMapping,
|
|
105
|
+
async validateSession(jid) {
|
|
106
|
+
try {
|
|
107
|
+
const addr = jidToSignalProtocolAddress(jid);
|
|
108
|
+
const session = await storage.loadSession(addr.toString());
|
|
109
|
+
if (!session) {
|
|
110
|
+
return { exists: false, reason: "no session" };
|
|
111
|
+
}
|
|
112
|
+
if (!session.haveOpenSession()) {
|
|
113
|
+
return { exists: false, reason: "no open session" };
|
|
114
|
+
}
|
|
115
|
+
return { exists: true };
|
|
116
|
+
}
|
|
117
|
+
catch (error) {
|
|
118
|
+
return { exists: false, reason: "validation error" };
|
|
119
|
+
}
|
|
120
|
+
},
|
|
121
|
+
async deleteSession(jids) {
|
|
122
|
+
if (!jids.length)
|
|
123
|
+
return;
|
|
124
|
+
const sessionUpdates = {};
|
|
125
|
+
jids.forEach(jid => {
|
|
126
|
+
const addr = jidToSignalProtocolAddress(jid);
|
|
127
|
+
sessionUpdates[addr.toString()] = null;
|
|
128
|
+
});
|
|
129
|
+
return parsedKeys.transaction(async () => {
|
|
130
|
+
await auth.keys.set({ session: sessionUpdates });
|
|
131
|
+
}, `delete-${jids.length}-sessions`);
|
|
132
|
+
},
|
|
133
|
+
async migrateSession(fromJid, toJid) {
|
|
134
|
+
if (!fromJid || (!isLidUser(toJid) && !isHostedLidUser(toJid)))
|
|
135
|
+
return { migrated: 0, skipped: 0, total: 0 };
|
|
136
|
+
if (!isPnUser(fromJid) && !isHostedPnUser(fromJid)) {
|
|
137
|
+
return { migrated: 0, skipped: 0, total: 1 };
|
|
138
|
+
}
|
|
139
|
+
const { user } = jidDecode(fromJid);
|
|
140
|
+
logger.debug({ fromJid }, "bulk device migration - loading all user devices");
|
|
141
|
+
const { [user]: userDevices } = await parsedKeys.get("device-list", [user]);
|
|
142
|
+
if (!userDevices) {
|
|
143
|
+
return { migrated: 0, skipped: 0, total: 0 };
|
|
144
|
+
}
|
|
145
|
+
const { device: fromDevice } = jidDecode(fromJid);
|
|
146
|
+
const fromDeviceStr = fromDevice?.toString() || "0";
|
|
147
|
+
if (!userDevices.includes(fromDeviceStr)) {
|
|
148
|
+
userDevices.push(fromDeviceStr);
|
|
149
|
+
}
|
|
150
|
+
const uncachedDevices = userDevices.filter(device => {
|
|
151
|
+
const deviceKey = `${user}.${device}`;
|
|
152
|
+
return !migratedSessionCache.has(deviceKey);
|
|
153
|
+
});
|
|
154
|
+
const deviceSessionKeys = uncachedDevices.map(device => `${user}.${device}`);
|
|
155
|
+
const existingSessions = await parsedKeys.get("session", deviceSessionKeys);
|
|
156
|
+
const deviceJids = [];
|
|
157
|
+
for (const [sessionKey, sessionData] of Object.entries(existingSessions)) {
|
|
158
|
+
if (sessionData) {
|
|
159
|
+
const deviceStr = sessionKey.split(".")[1];
|
|
160
|
+
if (!deviceStr)
|
|
161
|
+
continue;
|
|
162
|
+
const deviceNum = parseInt(deviceStr);
|
|
163
|
+
let jid = deviceNum === 0 ? `${user}@s.whatsapp.net` : `${user}:${deviceNum}@s.whatsapp.net`;
|
|
164
|
+
if (deviceNum === 99) {
|
|
165
|
+
jid = `${user}:99@hosted`;
|
|
166
|
+
}
|
|
167
|
+
deviceJids.push(jid);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
logger.debug({
|
|
171
|
+
fromJid,
|
|
172
|
+
totalDevices: userDevices.length,
|
|
173
|
+
devicesWithSessions: deviceJids.length,
|
|
174
|
+
devices: deviceJids
|
|
175
|
+
}, "bulk device migration complete - all user devices processed");
|
|
176
|
+
return parsedKeys.transaction(async () => {
|
|
177
|
+
const migrationOps = deviceJids.map(jid => {
|
|
178
|
+
const lidWithDevice = transferDevice(jid, toJid);
|
|
179
|
+
const fromDecoded = jidDecode(jid);
|
|
180
|
+
const toDecoded = jidDecode(lidWithDevice);
|
|
181
|
+
return {
|
|
182
|
+
fromJid: jid,
|
|
183
|
+
toJid: lidWithDevice,
|
|
184
|
+
pnUser: fromDecoded.user,
|
|
185
|
+
lidUser: toDecoded.user,
|
|
186
|
+
deviceId: fromDecoded.device || 0,
|
|
187
|
+
fromAddr: jidToSignalProtocolAddress(jid),
|
|
188
|
+
toAddr: jidToSignalProtocolAddress(lidWithDevice)
|
|
189
|
+
};
|
|
190
|
+
});
|
|
191
|
+
const totalOps = migrationOps.length;
|
|
192
|
+
let migratedCount = 0;
|
|
193
|
+
const pnAddrStrings = Array.from(new Set(migrationOps.map(op => op.fromAddr.toString())));
|
|
194
|
+
const pnSessions = await parsedKeys.get("session", pnAddrStrings);
|
|
195
|
+
const sessionUpdates = {};
|
|
196
|
+
for (const op of migrationOps) {
|
|
197
|
+
const pnAddrStr = op.fromAddr.toString();
|
|
198
|
+
const lidAddrStr = op.toAddr.toString();
|
|
199
|
+
const pnSession = pnSessions[pnAddrStr];
|
|
200
|
+
if (pnSession) {
|
|
201
|
+
const fromSession = libsignal.SessionRecord.deserialize(pnSession);
|
|
202
|
+
if (fromSession.haveOpenSession()) {
|
|
203
|
+
sessionUpdates[lidAddrStr] = fromSession.serialize();
|
|
204
|
+
sessionUpdates[pnAddrStr] = null;
|
|
205
|
+
migratedCount++;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
if (Object.keys(sessionUpdates).length > 0) {
|
|
210
|
+
await parsedKeys.set({ session: sessionUpdates });
|
|
211
|
+
logger.debug({ migratedSessions: migratedCount }, "bulk session migration complete");
|
|
212
|
+
for (const op of migrationOps) {
|
|
213
|
+
if (sessionUpdates[op.toAddr.toString()]) {
|
|
214
|
+
const deviceKey = `${op.pnUser}.${op.deviceId}`;
|
|
215
|
+
migratedSessionCache.set(deviceKey, true);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
const skippedCount = totalOps - migratedCount;
|
|
220
|
+
return { migrated: migratedCount, skipped: skippedCount, total: totalOps };
|
|
221
|
+
}, `migrate-${deviceJids.length}-sessions-${jidDecode(toJid)?.user}`);
|
|
222
|
+
}
|
|
223
|
+
};
|
|
224
|
+
return repository;
|
|
225
|
+
}
|
|
226
|
+
//=======================================================//
|
|
227
|
+
const jidToSignalProtocolAddress = (jid) => {
|
|
228
|
+
const decoded = jidDecode(jid);
|
|
229
|
+
const { user, device, server, domainType } = decoded;
|
|
230
|
+
if (!user) {
|
|
231
|
+
throw new Error(`JID decoded but user is empty: "${jid}" -> user: "${user}", server: "${server}", device: ${device}`);
|
|
232
|
+
}
|
|
233
|
+
const signalUser = domainType !== WAJIDDomains.WHATSAPP ? `${user}_${domainType}` : user;
|
|
234
|
+
const finalDevice = device || 0;
|
|
235
|
+
if (device === 99 && decoded.server !== "hosted" && decoded.server !== "hosted.lid") {
|
|
236
|
+
throw new Error("Unexpected non-hosted device JID with device 99. This ID seems invalid. ID:" + jid);
|
|
237
|
+
}
|
|
238
|
+
return new libsignal.ProtocolAddress(signalUser, finalDevice);
|
|
239
|
+
};
|
|
240
|
+
//=======================================================//
|
|
241
|
+
const jidToSignalSenderKeyName = (group, user) => {
|
|
242
|
+
return new SenderKeyName(group, jidToSignalProtocolAddress(user));
|
|
243
|
+
};
|
|
244
|
+
//=======================================================//
|
|
245
|
+
function signalStorage({ creds, keys }, lidMapping) {
|
|
246
|
+
const resolveLIDSignalAddress = async (id) => {
|
|
247
|
+
if (id.includes(".")) {
|
|
248
|
+
const [deviceId, device] = id.split(".");
|
|
249
|
+
const [user, domainType_] = deviceId.split("_");
|
|
250
|
+
const domainType = parseInt(domainType_ || "0");
|
|
251
|
+
if (domainType === WAJIDDomains.LID || domainType === WAJIDDomains.HOSTED_LID)
|
|
252
|
+
return id;
|
|
253
|
+
const pnJid = `${user}${device !== "0" ? `:${device}` : ""}@${domainType === WAJIDDomains.HOSTED ? "hosted" : "s.whatsapp.net"}`;
|
|
254
|
+
const lidForPN = await lidMapping.getLIDForPN(pnJid);
|
|
255
|
+
if (lidForPN) {
|
|
256
|
+
const lidAddr = jidToSignalProtocolAddress(lidForPN);
|
|
257
|
+
return lidAddr.toString();
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
return id;
|
|
261
|
+
};
|
|
262
|
+
return {
|
|
263
|
+
loadSession: async (id) => {
|
|
264
|
+
try {
|
|
265
|
+
const wireJid = await resolveLIDSignalAddress(id);
|
|
266
|
+
const { [wireJid]: sess } = await keys.get("session", [wireJid]);
|
|
267
|
+
if (sess) {
|
|
268
|
+
return libsignal.SessionRecord.deserialize(sess);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
catch (e) {
|
|
272
|
+
return null;
|
|
273
|
+
}
|
|
274
|
+
return null;
|
|
275
|
+
},
|
|
276
|
+
storeSession: async (id, session) => {
|
|
277
|
+
const wireJid = await resolveLIDSignalAddress(id);
|
|
278
|
+
await keys.set({ session: { [wireJid]: session.serialize() } });
|
|
279
|
+
},
|
|
280
|
+
isTrustedIdentity: () => {
|
|
281
|
+
return true;
|
|
282
|
+
},
|
|
283
|
+
loadPreKey: async (id) => {
|
|
284
|
+
const keyId = id.toString();
|
|
285
|
+
const { [keyId]: key } = await keys.get("pre-key", [keyId]);
|
|
286
|
+
if (key) {
|
|
287
|
+
return {
|
|
288
|
+
privKey: Buffer.from(key.private),
|
|
289
|
+
pubKey: Buffer.from(key.public)
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
},
|
|
293
|
+
removePreKey: (id) => keys.set({ "pre-key": { [id]: null } }),
|
|
294
|
+
loadSignedPreKey: () => {
|
|
295
|
+
const key = creds.signedPreKey;
|
|
296
|
+
return {
|
|
297
|
+
privKey: Buffer.from(key.keyPair.private),
|
|
298
|
+
pubKey: Buffer.from(key.keyPair.public)
|
|
299
|
+
};
|
|
300
|
+
},
|
|
301
|
+
loadSenderKey: async (senderKeyName) => {
|
|
302
|
+
const keyId = senderKeyName.toString();
|
|
303
|
+
const { [keyId]: key } = await keys.get("sender-key", [keyId]);
|
|
304
|
+
if (key) {
|
|
305
|
+
return SenderKeyRecord.deserialize(key);
|
|
306
|
+
}
|
|
307
|
+
return new SenderKeyRecord();
|
|
308
|
+
},
|
|
309
|
+
storeSenderKey: async (senderKeyName, key) => {
|
|
310
|
+
const keyId = senderKeyName.toString();
|
|
311
|
+
const serialized = JSON.stringify(key.serialize());
|
|
312
|
+
await keys.set({ "sender-key": { [keyId]: Buffer.from(serialized, "utf-8") } });
|
|
313
|
+
},
|
|
314
|
+
getOurRegistrationId: () => creds.registrationId,
|
|
315
|
+
getOurIdentity: () => {
|
|
316
|
+
const { signedIdentityKey } = creds;
|
|
317
|
+
return {
|
|
318
|
+
privKey: Buffer.from(signedIdentityKey.private),
|
|
319
|
+
pubKey: Buffer.from(generateSignalPubKey(signedIdentityKey.public))
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
//=======================================================//
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
//=======================================================//
|
|
2
|
+
import { isHostedPnUser, isLidUser, isPnUser, jidDecode, jidNormalizedUser, WAJIDDomains } from "../WABinary/index.js";
|
|
3
|
+
import { LRUCache } from "lru-cache";
|
|
4
|
+
//=======================================================//
|
|
5
|
+
export class LIDMappingStore {
|
|
6
|
+
constructor(keys, logger, pnToLIDFunc) {
|
|
7
|
+
this.mappingCache = new LRUCache({
|
|
8
|
+
ttl: 7 * 24 * 60 * 60 * 1000,
|
|
9
|
+
ttlAutopurge: true,
|
|
10
|
+
updateAgeOnGet: true
|
|
11
|
+
});
|
|
12
|
+
this.keys = keys;
|
|
13
|
+
this.pnToLIDFunc = pnToLIDFunc;
|
|
14
|
+
this.logger = logger;
|
|
15
|
+
}
|
|
16
|
+
async storeLIDPNMappings(pairs) {
|
|
17
|
+
const pairMap = {};
|
|
18
|
+
for (const { lid, pn } of pairs) {
|
|
19
|
+
if (!((isLidUser(lid) && isPnUser(pn)) || (isPnUser(lid) && isLidUser(pn)))) {
|
|
20
|
+
this.logger.warn(`Invalid LID-PN mapping: ${lid}, ${pn}`);
|
|
21
|
+
continue;
|
|
22
|
+
}
|
|
23
|
+
const lidDecoded = jidDecode(lid);
|
|
24
|
+
const pnDecoded = jidDecode(pn);
|
|
25
|
+
if (!lidDecoded || !pnDecoded)
|
|
26
|
+
return;
|
|
27
|
+
const pnUser = pnDecoded.user;
|
|
28
|
+
const lidUser = lidDecoded.user;
|
|
29
|
+
let existingLidUser = this.mappingCache.get(`pn:${pnUser}`);
|
|
30
|
+
if (!existingLidUser) {
|
|
31
|
+
this.logger.trace(`Cache miss for PN user ${pnUser}; checking database`);
|
|
32
|
+
const stored = await this.keys.get("lid-mapping", [pnUser]);
|
|
33
|
+
existingLidUser = stored[pnUser];
|
|
34
|
+
if (existingLidUser) {
|
|
35
|
+
this.mappingCache.set(`pn:${pnUser}`, existingLidUser);
|
|
36
|
+
this.mappingCache.set(`lid:${existingLidUser}`, pnUser);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
if (existingLidUser === lidUser) {
|
|
40
|
+
this.logger.debug({ pnUser, lidUser }, "LID mapping already exists, skipping");
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
pairMap[pnUser] = lidUser;
|
|
44
|
+
}
|
|
45
|
+
this.logger.trace({ pairMap }, `Storing ${Object.keys(pairMap).length} pn mappings`);
|
|
46
|
+
await this.keys.transaction(async () => {
|
|
47
|
+
for (const [pnUser, lidUser] of Object.entries(pairMap)) {
|
|
48
|
+
await this.keys.set({
|
|
49
|
+
"lid-mapping": {
|
|
50
|
+
[pnUser]: lidUser,
|
|
51
|
+
[`${lidUser}_reverse`]: pnUser
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
this.mappingCache.set(`pn:${pnUser}`, lidUser);
|
|
55
|
+
this.mappingCache.set(`lid:${lidUser}`, pnUser);
|
|
56
|
+
}
|
|
57
|
+
}, "lid-mapping");
|
|
58
|
+
}
|
|
59
|
+
async getLIDForPN(pn) {
|
|
60
|
+
return (await this.getLIDsForPNs([pn]))?.[0]?.lid || null;
|
|
61
|
+
}
|
|
62
|
+
async getLIDsForPNs(pns) {
|
|
63
|
+
const usyncFetch = {};
|
|
64
|
+
const successfulPairs = {};
|
|
65
|
+
for (const pn of pns) {
|
|
66
|
+
if (!isPnUser(pn) && !isHostedPnUser(pn))
|
|
67
|
+
continue;
|
|
68
|
+
const decoded = jidDecode(pn);
|
|
69
|
+
if (!decoded)
|
|
70
|
+
continue;
|
|
71
|
+
const pnUser = decoded.user;
|
|
72
|
+
let lidUser = this.mappingCache.get(`pn:${pnUser}`);
|
|
73
|
+
if (!lidUser) {
|
|
74
|
+
const stored = await this.keys.get("lid-mapping", [pnUser]);
|
|
75
|
+
lidUser = stored[pnUser];
|
|
76
|
+
if (lidUser) {
|
|
77
|
+
this.mappingCache.set(`pn:${pnUser}`, lidUser);
|
|
78
|
+
this.mappingCache.set(`lid:${lidUser}`, pnUser);
|
|
79
|
+
}
|
|
80
|
+
else {
|
|
81
|
+
this.logger.trace(`No LID mapping found for PN user ${pnUser}; batch getting from USync`);
|
|
82
|
+
const device = decoded.device || 0;
|
|
83
|
+
let normalizedPn = jidNormalizedUser(pn);
|
|
84
|
+
if (isHostedPnUser(normalizedPn)) {
|
|
85
|
+
normalizedPn = `${pnUser}@s.whatsapp.net`;
|
|
86
|
+
}
|
|
87
|
+
if (!usyncFetch[normalizedPn]) {
|
|
88
|
+
usyncFetch[normalizedPn] = [device];
|
|
89
|
+
}
|
|
90
|
+
else {
|
|
91
|
+
usyncFetch[normalizedPn]?.push(device);
|
|
92
|
+
}
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
lidUser = lidUser.toString();
|
|
97
|
+
if (!lidUser) {
|
|
98
|
+
this.logger.warn(`Invalid or empty LID user for PN ${pn}: lidUser = "${lidUser}"`);
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
const pnDevice = decoded.device !== undefined ? decoded.device : 0;
|
|
102
|
+
const deviceSpecificLid = `${lidUser}${!!pnDevice ? `:${pnDevice}` : ``}@${decoded.server === "hosted" ? "hosted.lid" : "lid"}`;
|
|
103
|
+
this.logger.trace(`getLIDForPN: ${pn} → ${deviceSpecificLid} (user mapping with device ${pnDevice})`);
|
|
104
|
+
successfulPairs[pn] = { lid: deviceSpecificLid, pn };
|
|
105
|
+
}
|
|
106
|
+
if (Object.keys(usyncFetch).length > 0) {
|
|
107
|
+
const result = await this.pnToLIDFunc?.(Object.keys(usyncFetch));
|
|
108
|
+
if (result && result.length > 0) {
|
|
109
|
+
this.storeLIDPNMappings(result);
|
|
110
|
+
for (const pair of result) {
|
|
111
|
+
const pnDecoded = jidDecode(pair.pn);
|
|
112
|
+
const pnUser = pnDecoded?.user;
|
|
113
|
+
if (!pnUser)
|
|
114
|
+
continue;
|
|
115
|
+
const lidUser = jidDecode(pair.lid)?.user;
|
|
116
|
+
if (!lidUser)
|
|
117
|
+
continue;
|
|
118
|
+
for (const device of usyncFetch[pair.pn]) {
|
|
119
|
+
const deviceSpecificLid = `${lidUser}${!!device ? `:${device}` : ``}@${device === 99 ? "hosted.lid" : "lid"}`;
|
|
120
|
+
this.logger.trace(`getLIDForPN: USYNC success for ${pair.pn} → ${deviceSpecificLid} (user mapping with device ${device})`);
|
|
121
|
+
const deviceSpecificPn = `${pnUser}${!!device ? `:${device}` : ``}@${device === 99 ? "hosted" : "s.whatsapp.net"}`;
|
|
122
|
+
successfulPairs[deviceSpecificPn] = { lid: deviceSpecificLid, pn: deviceSpecificPn };
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
else {
|
|
127
|
+
return null;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return Object.values(successfulPairs);
|
|
131
|
+
}
|
|
132
|
+
async getPNForLID(lid) {
|
|
133
|
+
if (!isLidUser(lid))
|
|
134
|
+
return null;
|
|
135
|
+
const decoded = jidDecode(lid);
|
|
136
|
+
if (!decoded)
|
|
137
|
+
return null;
|
|
138
|
+
const lidUser = decoded.user;
|
|
139
|
+
let pnUser = this.mappingCache.get(`lid:${lidUser}`);
|
|
140
|
+
if (!pnUser || typeof pnUser !== "string") {
|
|
141
|
+
const stored = await this.keys.get("lid-mapping", [`${lidUser}_reverse`]);
|
|
142
|
+
pnUser = stored[`${lidUser}_reverse`];
|
|
143
|
+
if (!pnUser || typeof pnUser !== "string") {
|
|
144
|
+
this.logger.trace(`No reverse mapping found for LID user: ${lidUser}`);
|
|
145
|
+
return null;
|
|
146
|
+
}
|
|
147
|
+
this.mappingCache.set(`lid:${lidUser}`, pnUser);
|
|
148
|
+
}
|
|
149
|
+
const lidDevice = decoded.device !== undefined ? decoded.device : 0;
|
|
150
|
+
const pnJid = `${pnUser}:${lidDevice}@${decoded.domainType === WAJIDDomains.HOSTED_LID ? "hosted" : "s.whatsapp.net"}`;
|
|
151
|
+
this.logger.trace(`Found reverse mapping: ${lid} → ${pnJid}`);
|
|
152
|
+
return pnJid;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
//=======================================================//
|