@rizzxdc/baileys 8.0.10 → 8.1.0

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