@x4r1s3/baileys 0.0.0-stage → 1.0.0

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