@neelegirly/baileys 2.2.16

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 (206) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +108 -0
  3. package/WAProto/WAProto.proto +5007 -0
  4. package/WAProto/index.d.ts +57712 -0
  5. package/WAProto/index.js +178969 -0
  6. package/lib/Defaults/baileys-version.json +1 -0
  7. package/lib/Defaults/index.d.ts +68 -0
  8. package/lib/Defaults/index.js +155 -0
  9. package/lib/Defaults/phonenumber-mcc.json +223 -0
  10. package/lib/Signal/WASignalGroup/GroupProtocol.js +1909 -0
  11. package/lib/Signal/WASignalGroup/ciphertext_message.js +16 -0
  12. package/lib/Signal/WASignalGroup/generate-proto.sh +1 -0
  13. package/lib/Signal/WASignalGroup/group.proto +42 -0
  14. package/lib/Signal/WASignalGroup/group_cipher.js +120 -0
  15. package/lib/Signal/WASignalGroup/group_session_builder.js +46 -0
  16. package/lib/Signal/WASignalGroup/index.js +6 -0
  17. package/lib/Signal/WASignalGroup/keyhelper.js +22 -0
  18. package/lib/Signal/WASignalGroup/protobufs.js +3 -0
  19. package/lib/Signal/WASignalGroup/queue_job.js +69 -0
  20. package/lib/Signal/WASignalGroup/readme.md +6 -0
  21. package/lib/Signal/WASignalGroup/sender_chain_key.js +50 -0
  22. package/lib/Signal/WASignalGroup/sender_key_distribution_message.js +78 -0
  23. package/lib/Signal/WASignalGroup/sender_key_message.js +92 -0
  24. package/lib/Signal/WASignalGroup/sender_key_name.js +70 -0
  25. package/lib/Signal/WASignalGroup/sender_key_record.js +56 -0
  26. package/lib/Signal/WASignalGroup/sender_key_state.js +129 -0
  27. package/lib/Signal/WASignalGroup/sender_message_key.js +39 -0
  28. package/lib/Signal/libsignal.d.ts +4 -0
  29. package/lib/Signal/libsignal.js +427 -0
  30. package/lib/Socket/Client/abstract-socket-client.d.ts +15 -0
  31. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  32. package/lib/Socket/Client/index.d.ts +2 -0
  33. package/lib/Socket/Client/index.js +22 -0
  34. package/lib/Socket/Client/mobile-socket-client.d.ts +12 -0
  35. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  36. package/lib/Socket/Client/types.d.ts +16 -0
  37. package/lib/Socket/Client/types.js +18 -0
  38. package/lib/Socket/Client/websocket.d.ts +13 -0
  39. package/lib/Socket/Client/websocket.js +62 -0
  40. package/lib/Socket/business.d.ts +187 -0
  41. package/lib/Socket/business.js +268 -0
  42. package/lib/Socket/chats.d.ts +98 -0
  43. package/lib/Socket/chats.js +1133 -0
  44. package/lib/Socket/communities.d.ts +223 -0
  45. package/lib/Socket/communities.js +433 -0
  46. package/lib/Socket/groups.d.ts +131 -0
  47. package/lib/Socket/groups.js +352 -0
  48. package/lib/Socket/index.d.ts +191 -0
  49. package/lib/Socket/index.js +23 -0
  50. package/lib/Socket/messages-recv.d.ts +177 -0
  51. package/lib/Socket/messages-recv.js +1826 -0
  52. package/lib/Socket/messages-send.d.ts +168 -0
  53. package/lib/Socket/messages-send.js +1537 -0
  54. package/lib/Socket/mex.d.ts +2 -0
  55. package/lib/Socket/mex.js +47 -0
  56. package/lib/Socket/newsletter.d.ts +147 -0
  57. package/lib/Socket/newsletter.js +286 -0
  58. package/lib/Socket/registration.d.ts +266 -0
  59. package/lib/Socket/registration.js +166 -0
  60. package/lib/Socket/socket.d.ts +45 -0
  61. package/lib/Socket/socket.js +928 -0
  62. package/lib/Socket/usync.d.ts +37 -0
  63. package/lib/Socket/usync.js +83 -0
  64. package/lib/Store/index.d.ts +4 -0
  65. package/lib/Store/index.js +24 -0
  66. package/lib/Store/make-cache-manager-store.d.ts +14 -0
  67. package/lib/Store/make-cache-manager-store.js +90 -0
  68. package/lib/Store/make-in-memory-store.d.ts +123 -0
  69. package/lib/Store/make-in-memory-store.js +429 -0
  70. package/lib/Store/make-ordered-dictionary.d.ts +12 -0
  71. package/lib/Store/make-ordered-dictionary.js +86 -0
  72. package/lib/Store/object-repository.d.ts +10 -0
  73. package/lib/Store/object-repository.js +31 -0
  74. package/lib/Types/Auth.d.ts +120 -0
  75. package/lib/Types/Auth.js +3 -0
  76. package/lib/Types/Bussines.d.ts +20 -0
  77. package/lib/Types/Bussines.js +2 -0
  78. package/lib/Types/Call.d.ts +14 -0
  79. package/lib/Types/Call.js +3 -0
  80. package/lib/Types/Chat.d.ts +141 -0
  81. package/lib/Types/Chat.js +9 -0
  82. package/lib/Types/Contact.d.ts +20 -0
  83. package/lib/Types/Contact.js +3 -0
  84. package/lib/Types/Events.d.ts +237 -0
  85. package/lib/Types/Events.js +3 -0
  86. package/lib/Types/GroupMetadata.d.ts +66 -0
  87. package/lib/Types/GroupMetadata.js +3 -0
  88. package/lib/Types/Label.d.ts +48 -0
  89. package/lib/Types/Label.js +31 -0
  90. package/lib/Types/LabelAssociation.d.ts +35 -0
  91. package/lib/Types/LabelAssociation.js +13 -0
  92. package/lib/Types/Message.d.ts +473 -0
  93. package/lib/Types/Message.js +13 -0
  94. package/lib/Types/MexUpdates.d.ts +9 -0
  95. package/lib/Types/MexUpdates.js +18 -0
  96. package/lib/Types/Newsletter.d.ts +109 -0
  97. package/lib/Types/Newsletter.js +40 -0
  98. package/lib/Types/Product.d.ts +92 -0
  99. package/lib/Types/Product.js +3 -0
  100. package/lib/Types/Signal.d.ts +68 -0
  101. package/lib/Types/Signal.js +3 -0
  102. package/lib/Types/Socket.d.ts +122 -0
  103. package/lib/Types/Socket.js +3 -0
  104. package/lib/Types/State.d.ts +41 -0
  105. package/lib/Types/State.js +14 -0
  106. package/lib/Types/USync.d.ts +26 -0
  107. package/lib/Types/USync.js +3 -0
  108. package/lib/Types/index.d.ts +80 -0
  109. package/lib/Types/index.js +48 -0
  110. package/lib/Utils/auth-utils.d.ts +21 -0
  111. package/lib/Utils/auth-utils.js +205 -0
  112. package/lib/Utils/baileys-event-stream.d.ts +18 -0
  113. package/lib/Utils/baileys-event-stream.js +70 -0
  114. package/lib/Utils/branding.d.ts +24 -0
  115. package/lib/Utils/branding.js +209 -0
  116. package/lib/Utils/business.d.ts +29 -0
  117. package/lib/Utils/business.js +255 -0
  118. package/lib/Utils/chat-utils.d.ts +82 -0
  119. package/lib/Utils/chat-utils.js +798 -0
  120. package/lib/Utils/check-npm-version.d.ts +18 -0
  121. package/lib/Utils/check-npm-version.js +130 -0
  122. package/lib/Utils/crypto.d.ts +56 -0
  123. package/lib/Utils/crypto.js +179 -0
  124. package/lib/Utils/decode-wa-message.d.ts +41 -0
  125. package/lib/Utils/decode-wa-message.js +288 -0
  126. package/lib/Utils/event-buffer.d.ts +39 -0
  127. package/lib/Utils/event-buffer.js +565 -0
  128. package/lib/Utils/generics.d.ts +129 -0
  129. package/lib/Utils/generics.js +630 -0
  130. package/lib/Utils/history.d.ts +23 -0
  131. package/lib/Utils/history.js +110 -0
  132. package/lib/Utils/index.d.ts +22 -0
  133. package/lib/Utils/index.js +42 -0
  134. package/lib/Utils/link-preview.d.ts +23 -0
  135. package/lib/Utils/link-preview.js +120 -0
  136. package/lib/Utils/logger.d.ts +13 -0
  137. package/lib/Utils/logger.js +7 -0
  138. package/lib/Utils/lt-hash.d.ts +14 -0
  139. package/lib/Utils/lt-hash.js +58 -0
  140. package/lib/Utils/make-mutex.d.ts +9 -0
  141. package/lib/Utils/make-mutex.js +49 -0
  142. package/lib/Utils/message-retry-manager.d.ts +84 -0
  143. package/lib/Utils/message-retry-manager.js +179 -0
  144. package/lib/Utils/messages-media.d.ts +129 -0
  145. package/lib/Utils/messages-media.js +806 -0
  146. package/lib/Utils/messages.d.ts +103 -0
  147. package/lib/Utils/messages.js +1579 -0
  148. package/lib/Utils/noise-handler.d.ts +20 -0
  149. package/lib/Utils/noise-handler.js +155 -0
  150. package/lib/Utils/process-message.d.ts +49 -0
  151. package/lib/Utils/process-message.js +443 -0
  152. package/lib/Utils/signal.d.ts +42 -0
  153. package/lib/Utils/signal.js +168 -0
  154. package/lib/Utils/use-mongo-file-auth-state.d.ts +6 -0
  155. package/lib/Utils/use-mongo-file-auth-state.js +84 -0
  156. package/lib/Utils/use-multi-file-auth-state.d.ts +18 -0
  157. package/lib/Utils/use-multi-file-auth-state.js +249 -0
  158. package/lib/Utils/use-single-file-auth-state.d.ts +13 -0
  159. package/lib/Utils/use-single-file-auth-state.js +80 -0
  160. package/lib/Utils/validate-connection.d.ts +13 -0
  161. package/lib/Utils/validate-connection.js +218 -0
  162. package/lib/WABinary/constants.d.ts +30 -0
  163. package/lib/WABinary/constants.js +1316 -0
  164. package/lib/WABinary/decode.d.ts +9 -0
  165. package/lib/WABinary/decode.js +288 -0
  166. package/lib/WABinary/encode.d.ts +3 -0
  167. package/lib/WABinary/encode.js +265 -0
  168. package/lib/WABinary/generic-utils.d.ts +28 -0
  169. package/lib/WABinary/generic-utils.js +142 -0
  170. package/lib/WABinary/index.d.ts +5 -0
  171. package/lib/WABinary/index.js +25 -0
  172. package/lib/WABinary/jid-utils.d.ts +59 -0
  173. package/lib/WABinary/jid-utils.js +105 -0
  174. package/lib/WABinary/types.d.ts +22 -0
  175. package/lib/WABinary/types.js +3 -0
  176. package/lib/WAM/BinaryInfo.d.ts +16 -0
  177. package/lib/WAM/BinaryInfo.js +17 -0
  178. package/lib/WAM/constants.d.ts +47 -0
  179. package/lib/WAM/constants.js +15371 -0
  180. package/lib/WAM/encode.d.ts +3 -0
  181. package/lib/WAM/encode.js +165 -0
  182. package/lib/WAM/index.d.ts +3 -0
  183. package/lib/WAM/index.js +23 -0
  184. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.d.ts +28 -0
  185. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +69 -0
  186. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  187. package/lib/WAUSync/Protocols/USyncContactProtocol.js +36 -0
  188. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +26 -0
  189. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +62 -0
  190. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +14 -0
  191. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +35 -0
  192. package/lib/WAUSync/Protocols/USyncLIDProtocol.d.ts +9 -0
  193. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +30 -0
  194. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +14 -0
  195. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +46 -0
  196. package/lib/WAUSync/Protocols/index.d.ts +6 -0
  197. package/lib/WAUSync/Protocols/index.js +26 -0
  198. package/lib/WAUSync/USyncQuery.d.ts +31 -0
  199. package/lib/WAUSync/USyncQuery.js +82 -0
  200. package/lib/WAUSync/USyncUser.d.ts +12 -0
  201. package/lib/WAUSync/USyncUser.js +30 -0
  202. package/lib/WAUSync/index.d.ts +3 -0
  203. package/lib/WAUSync/index.js +23 -0
  204. package/lib/index.d.ts +13 -0
  205. package/lib/index.js +33 -0
  206. package/package.json +120 -0
@@ -0,0 +1,129 @@
1
+ const SenderChainKey = require('./sender_chain_key');
2
+ const SenderMessageKey = require('./sender_message_key');
3
+
4
+ const protobufs = require('./protobufs');
5
+
6
+ class SenderKeyState {
7
+ MAX_MESSAGE_KEYS = 2000;
8
+
9
+ constructor(
10
+ id = null,
11
+ iteration = null,
12
+ chainKey = null,
13
+ signatureKeyPair = null,
14
+ signatureKeyPublic = null,
15
+ signatureKeyPrivate = null,
16
+ senderKeyStateStructure = null
17
+ ) {
18
+ if (senderKeyStateStructure) {
19
+ this.senderKeyStateStructure = senderKeyStateStructure;
20
+ } else {
21
+ if (signatureKeyPair) {
22
+ signatureKeyPublic = signatureKeyPair.public;
23
+ signatureKeyPrivate = signatureKeyPair.private;
24
+ }
25
+
26
+ chainKey = typeof chainKey === 'string' ? Buffer.from(chainKey, 'base64') : chainKey;
27
+ this.senderKeyStateStructure = protobufs.SenderKeyStateStructure.create();
28
+ const senderChainKeyStructure = protobufs.SenderChainKey.create();
29
+ senderChainKeyStructure.iteration = iteration;
30
+ senderChainKeyStructure.seed = chainKey;
31
+ this.senderKeyStateStructure.senderChainKey = senderChainKeyStructure;
32
+
33
+ const signingKeyStructure = protobufs.SenderSigningKey.create();
34
+ signingKeyStructure.public =
35
+ typeof signatureKeyPublic === 'string' ?
36
+ Buffer.from(signatureKeyPublic, 'base64') :
37
+ signatureKeyPublic;
38
+ if (signatureKeyPrivate) {
39
+ signingKeyStructure.private =
40
+ typeof signatureKeyPrivate === 'string' ?
41
+ Buffer.from(signatureKeyPrivate, 'base64') :
42
+ signatureKeyPrivate;
43
+ }
44
+ this.senderKeyStateStructure.senderKeyId = id;
45
+ this.senderChainKey = senderChainKeyStructure;
46
+ this.senderKeyStateStructure.senderSigningKey = signingKeyStructure;
47
+ }
48
+ this.senderKeyStateStructure.senderMessageKeys =
49
+ this.senderKeyStateStructure.senderMessageKeys || [];
50
+ }
51
+
52
+ SenderKeyState(senderKeyStateStructure) {
53
+ this.senderKeyStateStructure = senderKeyStateStructure;
54
+ }
55
+
56
+ getKeyId() {
57
+ return this.senderKeyStateStructure.senderKeyId;
58
+ }
59
+
60
+ getSenderChainKey() {
61
+ return new SenderChainKey(
62
+ this.senderKeyStateStructure.senderChainKey.iteration,
63
+ this.senderKeyStateStructure.senderChainKey.seed
64
+ );
65
+ }
66
+
67
+ setSenderChainKey(chainKey) {
68
+ const senderChainKeyStructure = protobufs.SenderChainKey.create({
69
+ iteration: chainKey.getIteration(),
70
+ seed: chainKey.getSeed(),
71
+ });
72
+ this.senderKeyStateStructure.senderChainKey = senderChainKeyStructure;
73
+ }
74
+
75
+ getSigningKeyPublic() {
76
+ return typeof this.senderKeyStateStructure.senderSigningKey.public === 'string' ?
77
+ Buffer.from(this.senderKeyStateStructure.senderSigningKey.public, 'base64') :
78
+ this.senderKeyStateStructure.senderSigningKey.public;
79
+ }
80
+
81
+ getSigningKeyPrivate() {
82
+ return typeof this.senderKeyStateStructure.senderSigningKey.private === 'string' ?
83
+ Buffer.from(this.senderKeyStateStructure.senderSigningKey.private, 'base64') :
84
+ this.senderKeyStateStructure.senderSigningKey.private;
85
+ }
86
+
87
+ hasSenderMessageKey(iteration) {
88
+ const list = this.senderKeyStateStructure.senderMessageKeys;
89
+ for (let o = 0; o < list.length; o++) {
90
+ const senderMessageKey = list[o];
91
+ if (senderMessageKey.iteration === iteration) return true;
92
+ }
93
+ return false;
94
+ }
95
+
96
+ addSenderMessageKey(senderMessageKey) {
97
+ const senderMessageKeyStructure = protobufs.SenderKeyStateStructure.create({
98
+ iteration: senderMessageKey.getIteration(),
99
+ seed: senderMessageKey.getSeed(),
100
+ });
101
+ this.senderKeyStateStructure.senderMessageKeys.push(senderMessageKeyStructure);
102
+
103
+ if (this.senderKeyStateStructure.senderMessageKeys.length > this.MAX_MESSAGE_KEYS) {
104
+ this.senderKeyStateStructure.senderMessageKeys.shift();
105
+ }
106
+ }
107
+
108
+ removeSenderMessageKey(iteration) {
109
+ let result = null;
110
+
111
+ this.senderKeyStateStructure.senderMessageKeys = this.senderKeyStateStructure.senderMessageKeys.filter(
112
+ senderMessageKey => {
113
+ if (senderMessageKey.iteration === iteration) result = senderMessageKey;
114
+ return senderMessageKey.iteration !== iteration;
115
+ }
116
+ );
117
+
118
+ if (result != null) {
119
+ return new SenderMessageKey(result.iteration, result.seed);
120
+ }
121
+ return null;
122
+ }
123
+
124
+ getStructure() {
125
+ return this.senderKeyStateStructure;
126
+ }
127
+ }
128
+
129
+ module.exports = SenderKeyState;
@@ -0,0 +1,39 @@
1
+ const { deriveSecrets } = require('@neelegirly/libsignal/src/crypto');
2
+ class SenderMessageKey {
3
+ iteration = 0;
4
+
5
+ iv = Buffer.alloc(0);
6
+
7
+ cipherKey = Buffer.alloc(0);
8
+
9
+ seed = Buffer.alloc(0);
10
+
11
+ constructor(iteration, seed) {
12
+ const derivative = deriveSecrets(seed, Buffer.alloc(32), Buffer.from('WhisperGroup'));
13
+ const keys = new Uint8Array(32);
14
+ keys.set(new Uint8Array(derivative[0].slice(16)));
15
+ keys.set(new Uint8Array(derivative[1].slice(0, 16)), 16);
16
+ this.iv = Buffer.from(derivative[0].slice(0, 16));
17
+ this.cipherKey = Buffer.from(keys.buffer);
18
+
19
+ this.iteration = iteration;
20
+ this.seed = seed;
21
+ }
22
+
23
+ getIteration() {
24
+ return this.iteration;
25
+ }
26
+
27
+ getIv() {
28
+ return this.iv;
29
+ }
30
+
31
+ getCipherKey() {
32
+ return this.cipherKey;
33
+ }
34
+
35
+ getSeed() {
36
+ return this.seed;
37
+ }
38
+ }
39
+ module.exports = SenderMessageKey;
@@ -0,0 +1,4 @@
1
+ import { SignalAuthState } from '../Types'
2
+ import { SignalRepository } from '../Types/Signal'
3
+
4
+ export declare function makeLibSignalRepository(auth: SignalAuthState): SignalRepository
@@ -0,0 +1,427 @@
1
+ "use strict"
2
+
3
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
+ if (k2 === undefined) k2 = k
5
+ var desc = Object.getOwnPropertyDescriptor(m, k)
6
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
+ desc = { enumerable: true, get: function() { return m[k] } }
8
+ }
9
+ Object.defineProperty(o, k2, desc)
10
+ }) : (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k
12
+ o[k2] = m[k]
13
+ }))
14
+
15
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
16
+ Object.defineProperty(o, "default", { enumerable: true, value: v })
17
+ }) : function(o, v) {
18
+ o["default"] = v
19
+ })
20
+
21
+ var __importStar = (this && this.__importStar) || function (mod) {
22
+ if (mod && mod.__esModule) return mod
23
+ var result = {}
24
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k)
25
+ __setModuleDefault(result, mod)
26
+ return result
27
+ }
28
+ Object.defineProperty(exports, "__esModule", { value: true })
29
+
30
+ const libsignal = __importStar(require("@neelegirly/libsignal"))
31
+ const WASignalGroup_1 = require("./WASignalGroup")
32
+ const Utils_1 = require("../Utils")
33
+ const WABinary_1 = require("../WABinary")
34
+
35
+ function makeLibSignalRepository(auth, logger, pnFromLIDUSync) {
36
+ const normalizeMappingJid = (jid = '') => String(jid || '').trim().replace(/:\d+(?=@)/, '')
37
+ const getAddressUserAndDevice = (id = '') => {
38
+ const raw = String(id || '').trim()
39
+ if (!raw) {
40
+ return { user: '', device: '0' }
41
+ }
42
+ const parts = raw.split('.')
43
+ if (parts.length === 1) {
44
+ return { user: parts[0], device: '0' }
45
+ }
46
+ const device = String(parts.pop() || '0')
47
+ return { user: parts.join('.'), device: device || '0' }
48
+ }
49
+ const jidUserPart = (jid = '') => normalizeMappingJid(jid).split('@')[0] || ''
50
+ const withDevice = (jid = '', reference = '') => {
51
+ const normalized = normalizeMappingJid(jid)
52
+ if (!normalized || !normalized.includes('@')) {
53
+ return normalized
54
+ }
55
+ if (/:\d+(?=@)/.test(String(jid || ''))) {
56
+ return normalized
57
+ }
58
+ const decoded = reference ? WABinary_1.jidDecode(reference) : null
59
+ if (!decoded?.device && decoded?.device !== 0) {
60
+ return normalized
61
+ }
62
+ const [local, domain = ''] = normalized.split('@')
63
+ return `${local}:${decoded.device}@${domain}`
64
+ }
65
+ const unique = (values = []) => Array.from(new Set(values.filter(Boolean)))
66
+ const sessionAddressCache = new Map()
67
+ const invalidateSessionAddressCache = () => {
68
+ sessionAddressCache.clear()
69
+ }
70
+ const hasExplicitDevice = (jid = '') => {
71
+ const decoded = WABinary_1.jidDecode(String(jid || '').trim())
72
+ return typeof decoded?.device === 'number'
73
+ }
74
+ const lidMapping = {
75
+ async storeLIDPNMappings(mappings = []) {
76
+ const lidUpdates = {}
77
+ const pnUpdates = {}
78
+ for (const entry of mappings || []) {
79
+ const lid = normalizeMappingJid(entry?.lid)
80
+ const pn = normalizeMappingJid(entry?.pn)
81
+ if (!/@lid$/i.test(lid) || !/@(s\.whatsapp\.net|c\.us)$/i.test(pn)) {
82
+ continue
83
+ }
84
+ lidUpdates[lid] = { lid, pn, updatedAt: Date.now() }
85
+ pnUpdates[pn] = { lid, pn, updatedAt: Date.now() }
86
+ }
87
+ if (!Object.keys(lidUpdates).length && !Object.keys(pnUpdates).length) {
88
+ return false
89
+ }
90
+ await auth.keys.set({
91
+ ...(Object.keys(lidUpdates).length ? { 'lid-mapping': lidUpdates } : {}),
92
+ ...(Object.keys(pnUpdates).length ? { 'pn-mapping': pnUpdates } : {})
93
+ })
94
+ return true
95
+ },
96
+ async getPNForLID(lid = '') {
97
+ const normalizedLid = normalizeMappingJid(lid)
98
+ if (!/@lid$/i.test(normalizedLid)) {
99
+ return null
100
+ }
101
+ const { [normalizedLid]: mapping } = await auth.keys.get('lid-mapping', [normalizedLid])
102
+ return normalizeMappingJid(mapping?.pn || '') || null
103
+ },
104
+ async getLIDForPN(pn = '') {
105
+ const normalizedPn = normalizeMappingJid(pn)
106
+ if (!/@(s\.whatsapp\.net|c\.us)$/i.test(normalizedPn)) {
107
+ return null
108
+ }
109
+ const { [normalizedPn]: mapping } = await auth.keys.get('pn-mapping', [normalizedPn])
110
+ const cachedLid = normalizeMappingJid(mapping?.lid || '')
111
+ if (cachedLid) {
112
+ return cachedLid
113
+ }
114
+ if (typeof pnFromLIDUSync === 'function') {
115
+ try {
116
+ const fetched = await pnFromLIDUSync([normalizedPn])
117
+ const resolved = normalizeMappingJid(fetched?.[0]?.lid || '')
118
+ if (resolved) {
119
+ await lidMapping.storeLIDPNMappings([{ lid: resolved, pn: normalizedPn }])
120
+ return resolved
121
+ }
122
+ } catch (error) {
123
+ logger?.debug?.({ error, pn: normalizedPn }, 'failed to fetch PN->LID mapping via usync')
124
+ }
125
+ }
126
+ return null
127
+ },
128
+ async getLIDsForPNs(pns = []) {
129
+ const results = []
130
+ for (const rawPn of pns || []) {
131
+ const normalizedPn = normalizeMappingJid(rawPn)
132
+ if (!normalizedPn) {
133
+ continue
134
+ }
135
+ const lid = await lidMapping.getLIDForPN(normalizedPn)
136
+ if (lid) {
137
+ results.push({ pn: normalizedPn, lid })
138
+ }
139
+ }
140
+ return results
141
+ }
142
+ }
143
+ const resolveMappedSessionIds = async (id = '') => {
144
+ const { user, device } = getAddressUserAndDevice(id)
145
+ if (!user) {
146
+ return []
147
+ }
148
+ const resolved = []
149
+ const mappedPn = await lidMapping.getPNForLID(`${user}@lid`)
150
+ if (mappedPn) {
151
+ const pnUser = jidUserPart(mappedPn)
152
+ if (pnUser) {
153
+ resolved.push(`${pnUser}.${device || '0'}`)
154
+ if ((device || '0') !== '0') {
155
+ resolved.push(`${pnUser}.0`)
156
+ }
157
+ }
158
+ }
159
+ const mappedLid = await lidMapping.getLIDForPN(`${user}@s.whatsapp.net`)
160
+ if (mappedLid) {
161
+ const lidUser = jidUserPart(mappedLid)
162
+ if (lidUser) {
163
+ resolved.push(`${lidUser}.${device || '0'}`)
164
+ if ((device || '0') !== '0') {
165
+ resolved.push(`${lidUser}.0`)
166
+ }
167
+ }
168
+ }
169
+ return unique(resolved.filter((candidate) => candidate !== id))
170
+ }
171
+ const getSessionAddressIdsForJid = async (jid = '', type = 'msg') => {
172
+ const normalized = normalizeMappingJid(jid)
173
+ if (!normalized || !normalized.includes('@')) {
174
+ return []
175
+ }
176
+ if (type !== 'msg' || hasExplicitDevice(jid)) {
177
+ return [jidToSignalProtocolAddress(String(jid || '').trim()).toString()]
178
+ }
179
+ const relatedJids = [normalized]
180
+ if (/@lid$/i.test(normalized)) {
181
+ const mappedPn = await lidMapping.getPNForLID(normalized)
182
+ if (mappedPn) {
183
+ relatedJids.push(mappedPn)
184
+ }
185
+ }
186
+ else if (/@(s\.whatsapp\.net|c\.us)$/i.test(normalized)) {
187
+ const mappedLid = await lidMapping.getLIDForPN(normalized)
188
+ if (mappedLid) {
189
+ relatedJids.push(mappedLid)
190
+ }
191
+ }
192
+ const sessionUsers = unique(relatedJids.map((value) => jidUserPart(value)).filter(Boolean))
193
+ if (!sessionUsers.length) {
194
+ return [jidToSignalProtocolAddress(normalized).toString()]
195
+ }
196
+ const cacheKey = sessionUsers.slice().sort().join('|')
197
+ const cached = sessionAddressCache.get(cacheKey)
198
+ if (cached?.length) {
199
+ return [...cached]
200
+ }
201
+ const candidateIds = []
202
+ for (const user of sessionUsers) {
203
+ for (let device = 0; device <= 99; device += 1) {
204
+ candidateIds.push(`${user}.${device}`)
205
+ }
206
+ }
207
+ const existing = candidateIds.length
208
+ ? await auth.keys.get('session', candidateIds)
209
+ : {}
210
+ const orderedIds = candidateIds.filter((candidateId) => !!existing?.[candidateId])
211
+ const finalIds = orderedIds.length
212
+ ? orderedIds
213
+ : [jidToSignalProtocolAddress(normalized).toString()]
214
+ sessionAddressCache.set(cacheKey, finalIds)
215
+ return [...finalIds]
216
+ }
217
+ const toSignalId = (jid = '') => {
218
+ const normalized = String(jid || '').trim()
219
+ if (!normalized || !normalized.includes('@')) {
220
+ return ''
221
+ }
222
+ return jidToSignalProtocolAddress(normalized).toString()
223
+ }
224
+ const buildSessionCandidates = (jid = '', reference = '') => {
225
+ const normalized = normalizeMappingJid(jid)
226
+ if (!normalized || !normalized.includes('@')) {
227
+ return []
228
+ }
229
+ return unique([
230
+ toSignalId(withDevice(normalized, reference)),
231
+ toSignalId(normalized)
232
+ ])
233
+ }
234
+ const storage = signalStorage(auth, { resolveMappedSessionIds, invalidateSessionAddressCache })
235
+ return {
236
+ lidMapping,
237
+ async migrateSession(fromJid, toJid) {
238
+ const normalizedFrom = normalizeMappingJid(fromJid)
239
+ const normalizedTo = normalizeMappingJid(toJid)
240
+ if (!normalizedFrom || !normalizedTo || normalizedFrom === normalizedTo) {
241
+ return false
242
+ }
243
+ const fromCandidates = buildSessionCandidates(normalizedFrom, normalizedTo)
244
+ const toCandidates = buildSessionCandidates(normalizedTo, normalizedFrom)
245
+ const existing = await auth.keys.get('session', unique([...fromCandidates, ...toCandidates]))
246
+ const sourceId = fromCandidates.find((candidate) => !!existing?.[candidate])
247
+ if (!sourceId) {
248
+ return false
249
+ }
250
+ const updates = {}
251
+ for (const candidate of toCandidates) {
252
+ if (candidate && candidate !== sourceId && !existing?.[candidate]) {
253
+ updates[candidate] = existing[sourceId]
254
+ }
255
+ }
256
+ if (Object.keys(updates).length > 0) {
257
+ await auth.keys.set({ 'session': updates })
258
+ invalidateSessionAddressCache()
259
+ }
260
+ if (/@lid$/i.test(normalizedTo) && /@(s\.whatsapp\.net|c\.us)$/i.test(normalizedFrom)) {
261
+ await lidMapping.storeLIDPNMappings([{ lid: normalizedTo, pn: normalizedFrom }])
262
+ } else if (/@lid$/i.test(normalizedFrom) && /@(s\.whatsapp\.net|c\.us)$/i.test(normalizedTo)) {
263
+ await lidMapping.storeLIDPNMappings([{ lid: normalizedFrom, pn: normalizedTo }])
264
+ }
265
+ return true
266
+ },
267
+ decryptGroupMessage({ group, authorJid, msg }) {
268
+ const senderName = jidToSignalSenderKeyName(group, authorJid)
269
+ const cipher = new WASignalGroup_1.GroupCipher(storage, senderName)
270
+ return cipher.decrypt(msg)
271
+ },
272
+ async processSenderKeyDistributionMessage({ item, authorJid }) {
273
+ const builder = new WASignalGroup_1.GroupSessionBuilder(storage)
274
+ const senderName = jidToSignalSenderKeyName(item.groupId, authorJid)
275
+ const senderMsg = new WASignalGroup_1.SenderKeyDistributionMessage(null, null, null, null, item.axolotlSenderKeyDistributionMessage)
276
+ const { [senderName]: senderKey } = await auth.keys.get('sender-key', [senderName])
277
+ if (!senderKey) {
278
+ await storage.storeSenderKey(senderName, new WASignalGroup_1.SenderKeyRecord())
279
+ }
280
+ await builder.process(senderName, senderMsg)
281
+ },
282
+ async decryptMessage({ jid, type, ciphertext }) {
283
+ const signalIds = await getSessionAddressIdsForJid(jid, type)
284
+ let lastError
285
+ for (const signalId of signalIds) {
286
+ const { user, device } = getAddressUserAndDevice(signalId)
287
+ const addr = new libsignal.ProtocolAddress(user, Number(device || '0'))
288
+ const session = new libsignal.SessionCipher(storage, addr)
289
+ try {
290
+ switch (type) {
291
+ case 'pkmsg':
292
+ return await session.decryptPreKeyWhisperMessage(ciphertext)
293
+ case 'msg':
294
+ return await session.decryptWhisperMessage(ciphertext)
295
+ }
296
+ }
297
+ catch (error) {
298
+ lastError = error
299
+ }
300
+ }
301
+ throw lastError || new Error('Failed to decrypt message')
302
+ },
303
+ async encryptMessage({ jid, data }) {
304
+ const addr = jidToSignalProtocolAddress(jid)
305
+ const cipher = new libsignal.SessionCipher(storage, addr)
306
+ const { type: sigType, body } = await cipher.encrypt(data)
307
+ const type = sigType === 3 ? 'pkmsg' : 'msg'
308
+ return { type, ciphertext: Buffer.from(body, 'binary') }
309
+ },
310
+ async encryptGroupMessage({ group, meId, data }) {
311
+ const senderName = jidToSignalSenderKeyName(group, meId)
312
+ const builder = new WASignalGroup_1.GroupSessionBuilder(storage)
313
+ const { [senderName]: senderKey } = await auth.keys.get('sender-key', [senderName])
314
+ if (!senderKey) {
315
+ await storage.storeSenderKey(senderName, new WASignalGroup_1.SenderKeyRecord())
316
+ }
317
+ const senderKeyDistributionMessage = await builder.create(senderName)
318
+ const session = new WASignalGroup_1.GroupCipher(storage, senderName)
319
+ const ciphertext = await session.encrypt(data)
320
+ return {
321
+ ciphertext,
322
+ senderKeyDistributionMessage: senderKeyDistributionMessage.serialize(),
323
+ }
324
+ },
325
+ async injectE2ESession({ jid, session }) {
326
+ const cipher = new libsignal.SessionBuilder(storage, jidToSignalProtocolAddress(jid))
327
+ await cipher.initOutgoing(session)
328
+ invalidateSessionAddressCache()
329
+ },
330
+ jidToSignalProtocolAddress(jid) {
331
+ return jidToSignalProtocolAddress(jid).toString()
332
+ },
333
+ async validateSession(jid) {
334
+ try {
335
+ const addr = jidToSignalProtocolAddress(jid)
336
+ const session = await storage.loadSession(addr.toString())
337
+ if (!session) {
338
+ return { exists: false, reason: 'no session' }
339
+ }
340
+ if (typeof session.haveOpenSession === 'function' && !session.haveOpenSession()) {
341
+ return { exists: false, reason: 'no open session' }
342
+ }
343
+ return { exists: true }
344
+ } catch (_error) {
345
+ return { exists: false, reason: 'validation error' }
346
+ }
347
+ },
348
+ }
349
+ }
350
+
351
+ const jidToSignalProtocolAddress = (jid) => {
352
+ const { user, device } = WABinary_1.jidDecode(jid)
353
+ return new libsignal.ProtocolAddress(user, device || 0)
354
+ }
355
+
356
+ const jidToSignalSenderKeyName = (group, user) => {
357
+ return new WASignalGroup_1.SenderKeyName(group, jidToSignalProtocolAddress(user)).toString()
358
+ }
359
+
360
+ function signalStorage({ creds, keys }, helpers = {}) {
361
+ const { resolveMappedSessionIds, invalidateSessionAddressCache } = helpers
362
+ return {
363
+ loadSession: async (id) => {
364
+ const { [id]: sess } = await keys.get('session', [id])
365
+ if (sess) {
366
+ return libsignal.SessionRecord.deserialize(sess)
367
+ }
368
+ const fallbackIds = typeof resolveMappedSessionIds === 'function' ? await resolveMappedSessionIds(id) : []
369
+ if (fallbackIds.length) {
370
+ const fallbackSessions = await keys.get('session', fallbackIds)
371
+ for (const fallbackId of fallbackIds) {
372
+ if (fallbackSessions?.[fallbackId]) {
373
+ return libsignal.SessionRecord.deserialize(fallbackSessions[fallbackId])
374
+ }
375
+ }
376
+ }
377
+ },
378
+ storeSession: async (id, session) => {
379
+ await keys.set({ 'session': { [id]: session.serialize() } })
380
+ if (typeof invalidateSessionAddressCache === 'function') {
381
+ invalidateSessionAddressCache()
382
+ }
383
+ },
384
+ isTrustedIdentity: () => {
385
+ return true
386
+ },
387
+ loadPreKey: async (id) => {
388
+ const keyId = id.toString()
389
+ const { [keyId]: key } = await keys.get('pre-key', [keyId])
390
+ if (key) {
391
+ return {
392
+ privKey: Buffer.from(key.private),
393
+ pubKey: Buffer.from(key.public)
394
+ }
395
+ }
396
+ },
397
+ removePreKey: (id) => keys.set({ 'pre-key': { [id]: null } }),
398
+ loadSignedPreKey: () => {
399
+ const key = creds.signedPreKey
400
+ return {
401
+ privKey: Buffer.from(key.keyPair.private),
402
+ pubKey: Buffer.from(key.keyPair.public)
403
+ }
404
+ },
405
+ loadSenderKey: async (keyId) => {
406
+ const { [keyId]: key } = await keys.get('sender-key', [keyId])
407
+ if (key) {
408
+ return new WASignalGroup_1.SenderKeyRecord(key)
409
+ }
410
+ },
411
+ storeSenderKey: async (keyId, key) => {
412
+ await keys.set({ 'sender-key': { [keyId]: key.serialize() } })
413
+ },
414
+ getOurRegistrationId: () => (creds.registrationId),
415
+ getOurIdentity: () => {
416
+ const { signedIdentityKey } = creds
417
+ return {
418
+ privKey: Buffer.from(signedIdentityKey.private),
419
+ pubKey: Utils_1.generateSignalPubKey(signedIdentityKey.public),
420
+ }
421
+ }
422
+ }
423
+ }
424
+
425
+ module.exports = {
426
+ makeLibSignalRepository
427
+ }
@@ -0,0 +1,15 @@
1
+ import { EventEmitter } from 'events';
2
+ import { URL } from 'url';
3
+ import { SocketConfig } from '../../Types';
4
+ export declare abstract class AbstractSocketClient extends EventEmitter {
5
+ url: URL;
6
+ config: SocketConfig;
7
+ abstract get isOpen(): boolean;
8
+ abstract get isClosed(): boolean;
9
+ abstract get isClosing(): boolean;
10
+ abstract get isConnecting(): boolean;
11
+ constructor(url: URL, config: SocketConfig);
12
+ abstract connect(): Promise<void>;
13
+ abstract close(): Promise<void>;
14
+ abstract send(str: Uint8Array | string, cb?: (err?: Error) => void): boolean;
15
+ }
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AbstractSocketClient = void 0;
4
+ const events_1 = require("events");
5
+ class AbstractSocketClient extends events_1.EventEmitter {
6
+ constructor(url, config) {
7
+ super();
8
+ this.url = url;
9
+ this.config = config;
10
+ this.setMaxListeners(0);
11
+ }
12
+ }
13
+ exports.AbstractSocketClient = AbstractSocketClient;
@@ -0,0 +1,2 @@
1
+ export * from './types'
2
+ export * from './websocket'
@@ -0,0 +1,22 @@
1
+ "use strict"
2
+
3
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
+ if (k2 === undefined) k2 = k
5
+ var desc = Object.getOwnPropertyDescriptor(m, k)
6
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
+ desc = { enumerable: true, get: function() { return m[k] } }
8
+ }
9
+ Object.defineProperty(o, k2, desc)
10
+ }) : (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k
12
+ o[k2] = m[k]
13
+ }))
14
+
15
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
16
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p)
17
+ }
18
+
19
+ Object.defineProperty(exports, "__esModule", { value: true })
20
+
21
+ __exportStar(require("./types"), exports)
22
+ __exportStar(require("./websocket"), exports)
@@ -0,0 +1,12 @@
1
+ import { Socket } from 'net';
2
+ import { AbstractSocketClient } from './abstract-socket-client';
3
+ export declare class MobileSocketClient extends AbstractSocketClient {
4
+ protected socket: Socket | null;
5
+ get isOpen(): boolean;
6
+ get isClosed(): boolean;
7
+ get isClosing(): boolean;
8
+ get isConnecting(): boolean;
9
+ connect(): Promise<void>;
10
+ close(): Promise<void>;
11
+ send(str: string | Uint8Array, cb?: (err?: Error) => void): boolean;
12
+ }