@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,42 @@
1
+ import { SignalRepository } from '../Types'
2
+ import { AuthenticationCreds, AuthenticationState, KeyPair, SignalIdentity, SignalKeyStore, SignedKeyPair } from '../Types/Auth'
3
+ import { BinaryNode, JidWithDevice } from '../WABinary'
4
+ import { USyncQueryResultList } from '../WAUSync'
5
+
6
+ export declare const createSignalIdentity: (wid: string, accountSignatureKey: Uint8Array) => SignalIdentity
7
+
8
+ export declare const getPreKeys: ({ get }: SignalKeyStore, min: number, limit: number) => Promise<{
9
+ [id: string]: KeyPair
10
+ }>
11
+
12
+ export declare const generateOrGetPreKeys: (creds: AuthenticationCreds, range: number) => {
13
+ newPreKeys: {
14
+ [id: number]: KeyPair
15
+ }
16
+ lastPreKeyId: number
17
+ preKeysRange: readonly [number, number]
18
+ }
19
+
20
+ export declare const xmppSignedPreKey: (key: SignedKeyPair) => BinaryNode
21
+
22
+ export declare const xmppPreKey: (pair: KeyPair, id: number) => BinaryNode
23
+
24
+ export declare const parseAndInjectE2ESessions: (node: BinaryNode, repository: SignalRepository) => Promise<void>
25
+
26
+ export declare const extractDeviceJids: (result: USyncQueryResultList[], myJid: string, excludeZeroDevices: boolean) => JidWithDevice[]
27
+
28
+ /**
29
+ * get the next N keys for upload or processing
30
+ * @param count number of pre-keys to get or generate
31
+ */
32
+ export declare const getNextPreKeys: ({ creds, keys }: AuthenticationState, count: number) => Promise<{
33
+ update: Partial<AuthenticationCreds>
34
+ preKeys: {
35
+ [id: string]: KeyPair
36
+ }
37
+ }>
38
+
39
+ export declare const getNextPreKeysNode: (state: AuthenticationState, count: number) => Promise<{
40
+ update: Partial<AuthenticationCreds>
41
+ node: BinaryNode
42
+ }>
@@ -0,0 +1,168 @@
1
+ "use strict"
2
+
3
+ Object.defineProperty(exports, "__esModule", { value: true })
4
+
5
+ const lodash_1 = require("lodash")
6
+ const Defaults_1 = require("../Defaults")
7
+ const WABinary_1 = require("../WABinary")
8
+ const crypto_1 = require("./crypto")
9
+ const generics_1 = require("./generics")
10
+
11
+ const createSignalIdentity = (wid, accountSignatureKey) => {
12
+ return {
13
+ identifier: { name: wid, deviceId: 0 },
14
+ identifierKey: crypto_1.generateSignalPubKey(accountSignatureKey)
15
+ }
16
+ }
17
+
18
+ const getPreKeys = async ({ get }, min, limit) => {
19
+ const idList = []
20
+ for (let id = min; id < limit; id++) {
21
+ idList.push(id.toString())
22
+ }
23
+ return get('pre-key', idList)
24
+ }
25
+
26
+ const generateOrGetPreKeys = (creds, range) => {
27
+ const avaliable = creds.nextPreKeyId - creds.firstUnuploadedPreKeyId
28
+ const remaining = range - avaliable
29
+ const lastPreKeyId = creds.nextPreKeyId + remaining - 1
30
+ const newPreKeys = {}
31
+ if (remaining > 0) {
32
+ for (let i = creds.nextPreKeyId; i <= lastPreKeyId; i++) {
33
+ newPreKeys[i] = crypto_1.Curve.generateKeyPair()
34
+ }
35
+ }
36
+ return {
37
+ newPreKeys,
38
+ lastPreKeyId,
39
+ preKeysRange: [creds.firstUnuploadedPreKeyId, range],
40
+ }
41
+ }
42
+
43
+ const xmppSignedPreKey = (key) => ({
44
+ tag: 'skey',
45
+ attrs: {},
46
+ content: [
47
+ { tag: 'id', attrs: {}, content: generics_1.encodeBigEndian(key.keyId, 3) },
48
+ { tag: 'value', attrs: {}, content: key.keyPair.public },
49
+ { tag: 'signature', attrs: {}, content: key.signature }
50
+ ]
51
+ })
52
+
53
+ const xmppPreKey = (pair, id) => ({
54
+ tag: 'key',
55
+ attrs: {},
56
+ content: [
57
+ { tag: 'id', attrs: {}, content: generics_1.encodeBigEndian(id, 3) },
58
+ { tag: 'value', attrs: {}, content: pair.public }
59
+ ]
60
+ })
61
+
62
+ const parseAndInjectE2ESessions = async (node, repository) => {
63
+ const extractKey = (key) => (key ? ({
64
+ keyId: WABinary_1.getBinaryNodeChildUInt(key, 'id', 3),
65
+ publicKey: crypto_1.generateSignalPubKey(WABinary_1.getBinaryNodeChildBuffer(key, 'value')),
66
+ signature: WABinary_1.getBinaryNodeChildBuffer(key, 'signature')
67
+ }) : undefined)
68
+ const nodes = WABinary_1.getBinaryNodeChildren(WABinary_1.getBinaryNodeChild(node, 'list'), 'user')
69
+ for (const node of nodes) {
70
+ WABinary_1.assertNodeErrorFree(node)
71
+ }
72
+ // Most of the work in repository.injectE2ESession is CPU intensive, not IO
73
+ // So Promise.all doesn't really help here,
74
+ // but blocks even loop if we're using it inside keys.transaction, and it makes it "sync" actually
75
+ // This way we chunk it in smaller parts and between those parts we can yield to the event loop
76
+ // It's rare case when you need to E2E sessions for so many users, but it's possible
77
+ const chunkSize = 100
78
+ const chunks = lodash_1.chunk(nodes, chunkSize)
79
+ for (const nodesChunk of chunks) {
80
+ await Promise.all(nodesChunk.map(async (node) => {
81
+ const signedKey = WABinary_1.getBinaryNodeChild(node, 'skey')
82
+ const key = WABinary_1.getBinaryNodeChild(node, 'key')
83
+ const identity = WABinary_1.getBinaryNodeChildBuffer(node, 'identity')
84
+ const jid = node.attrs.jid
85
+ const registrationId = WABinary_1.getBinaryNodeChildUInt(node, 'registration', 4)
86
+ await repository.injectE2ESession({
87
+ jid,
88
+ session: {
89
+ registrationId: registrationId,
90
+ identityKey: crypto_1.generateSignalPubKey(identity),
91
+ signedPreKey: extractKey(signedKey),
92
+ preKey: extractKey(key)
93
+ }
94
+ })
95
+ }))
96
+ }
97
+ }
98
+
99
+ const extractDeviceJids = (result, myJid, myLid, excludeZeroDevices) => {
100
+ const { user: myUser, device: myDevice } = WABinary_1.jidDecode(myJid)
101
+ const myLidUser = myLid ? WABinary_1.jidDecode(myLid)?.user : undefined
102
+ const extracted = []
103
+ for (const userResult of result) {
104
+ const { devices, id } = userResult
105
+ const decoded = WABinary_1.jidDecode(id)
106
+ const { user, server } = decoded
107
+ const deviceList = devices?.deviceList
108
+ if (Array.isArray(deviceList)) {
109
+ for (const { id: device, keyIndex } of deviceList) {
110
+ if ((!excludeZeroDevices || device !== 0) && // if zero devices are not-excluded, or device is non zero
111
+ ((myUser !== user && myLidUser !== user) || myDevice !== device) && // either different user or if me user, not this device
112
+ (device === 0 || !!keyIndex) // ensure that "key-index" is specified for "non-zero" devices, produces a bad req otherwise
113
+ ) {
114
+ extracted.push({ user, device, server })
115
+ }
116
+ }
117
+ }
118
+ }
119
+ return extracted
120
+ }
121
+
122
+ /**
123
+ * get the next N keys for upload or processing
124
+ * @param count number of pre-keys to get or generate
125
+ */
126
+ const getNextPreKeys = async ({ creds, keys }, count) => {
127
+ const { newPreKeys, lastPreKeyId, preKeysRange } = generateOrGetPreKeys(creds, count)
128
+ const update = {
129
+ nextPreKeyId: Math.max(lastPreKeyId + 1, creds.nextPreKeyId),
130
+ firstUnuploadedPreKeyId: Math.max(creds.firstUnuploadedPreKeyId, lastPreKeyId + 1)
131
+ }
132
+ await keys.set({ 'pre-key': newPreKeys })
133
+ const preKeys = await getPreKeys(keys, preKeysRange[0], preKeysRange[0] + preKeysRange[1])
134
+ return { update, preKeys }
135
+ }
136
+
137
+ const getNextPreKeysNode = async (state, count) => {
138
+ const { creds } = state
139
+ const { update, preKeys } = await getNextPreKeys(state, count)
140
+ const node = {
141
+ tag: 'iq',
142
+ attrs: {
143
+ xmlns: 'encrypt',
144
+ type: 'set',
145
+ to: WABinary_1.S_WHATSAPP_NET,
146
+ },
147
+ content: [
148
+ { tag: 'registration', attrs: {}, content: generics_1.encodeBigEndian(creds.registrationId) },
149
+ { tag: 'type', attrs: {}, content: Defaults_1.KEY_BUNDLE_TYPE },
150
+ { tag: 'identity', attrs: {}, content: creds.signedIdentityKey.public },
151
+ { tag: 'list', attrs: {}, content: Object.keys(preKeys).map(k => xmppPreKey(preKeys[+k], +k)) },
152
+ xmppSignedPreKey(creds.signedPreKey)
153
+ ]
154
+ }
155
+ return { update, node }
156
+ }
157
+
158
+ module.exports = {
159
+ createSignalIdentity,
160
+ getPreKeys,
161
+ generateOrGetPreKeys,
162
+ xmppSignedPreKey,
163
+ xmppPreKey,
164
+ parseAndInjectE2ESessions,
165
+ extractDeviceJids,
166
+ getNextPreKeys,
167
+ getNextPreKeysNode
168
+ }
@@ -0,0 +1,6 @@
1
+ import { AuthenticationState } from '../Types'
2
+
3
+ export declare const useMongoFileAuthState: (collection: string) => Promise<{
4
+ state: AuthenticationState
5
+ saveCreds: () => Promise<void>
6
+ }>
@@ -0,0 +1,84 @@
1
+ "use strict"
2
+
3
+ Object.defineProperty(exports, "__esModule", { value: true })
4
+
5
+ const WAProto_1 = require("../../WAProto")
6
+ const auth_utils_1 = require("./auth-utils")
7
+ const generics_1 = require("./generics")
8
+
9
+ /*
10
+ code from amiruldev readjusted by @irull2nd, don't delete WM!
11
+ */
12
+ const useMongoFileAuthState = async (collection) => {
13
+ const writeData = (data,id) => {
14
+ const informationToStore = JSON.parse(
15
+ JSON.stringify(data, generics_1.BufferJSON.replacer)
16
+ )
17
+ const update = {
18
+ $set: {
19
+ ...informationToStore,
20
+ },
21
+ }
22
+
23
+ return collection.updateOne({_id: id},update, {upsert: true})
24
+ }
25
+
26
+ const readData = async (id) => {
27
+ try {
28
+ const data = JSON.stringify(await collection.findOne({_id: id}))
29
+ return JSON.parse(data, generics_1.BufferJSON.reviver)
30
+ } catch (err) {
31
+ console.log(err)
32
+ }
33
+ }
34
+
35
+ const removeData = async (id) => {
36
+ try{
37
+ await collection.deleteOne({_id: id})
38
+ }catch(err){
39
+ console.log('error',err)
40
+ }
41
+ }
42
+
43
+ const creds = (await readData('creds')) || auth_utils_1.initAuthCreds()
44
+
45
+ return{
46
+ state:{
47
+ creds,
48
+ keys: {
49
+ get: async (type,ids)=> {
50
+ const data = {}
51
+ await Promise
52
+ .all(
53
+ ids.map(async (id) => {
54
+ let value = await readData(`${type}-${id}`)
55
+ if(type === "app-state-sync-key"){
56
+ value = WAProto_1.proto.Message.AppStateSyncKeyData.fromObject(data)
57
+ }
58
+ data[id] = value
59
+ })
60
+ )
61
+ return data
62
+ },
63
+ set: async (data) => {
64
+ const tasks = []
65
+ for (const category of Object.keys(data)){
66
+ for (const id of Object.keys(data[category])){
67
+ const value = data[category][id]
68
+ const key = `${category}-${id}`
69
+ tasks.push(value? writeData(value,key) : removeData(key))
70
+ }
71
+ }
72
+ await Promise.all(tasks)
73
+ },
74
+ },
75
+ },
76
+ saveCreds: () => {
77
+ return writeData(creds, "creds")
78
+ }
79
+ }
80
+ }
81
+
82
+ module.exports = {
83
+ useMongoFileAuthState
84
+ }
@@ -0,0 +1,18 @@
1
+ import { AuthenticationState } from '../Types'
2
+
3
+ /**
4
+ * stores the full authentication state in a single folder.
5
+ * Far more efficient than singlefileauthstate
6
+ *
7
+ * Again, I wouldn't endorse this for any production level use other than perhaps a bot.
8
+ * Would recommend writing an auth state for use with a proper SQL or No-SQL DB
9
+ * */
10
+ export declare const useMultiFileAuthState: (folder: string) => Promise<{
11
+ state: AuthenticationState
12
+ saveCreds: () => Promise<void>
13
+ }>
14
+
15
+ export declare const useMultiFileAuthStateV2: (folder: string) => Promise<{
16
+ state: AuthenticationState
17
+ saveCreds: () => Promise<void>
18
+ }>
@@ -0,0 +1,249 @@
1
+ "use strict"
2
+
3
+ var __importDefault = (this && this.__importDefault) || function (mod) {
4
+ return (mod && mod.__esModule) ? mod : { "default": mod }
5
+ }
6
+
7
+ Object.defineProperty(exports, "__esModule", { value: true })
8
+
9
+ const async_mutex_1 = __importDefault(require("async-mutex"))
10
+ const promises_1 = require("fs/promises")
11
+ const path_1 = require("path")
12
+ const WAProto_1 = require("../../WAProto")
13
+ const auth_utils_1 = require("./auth-utils")
14
+ const generics_1 = require("./generics")
15
+ // We need to lock files due to the fact that we are using async functions to read and write files
16
+ // https://github.com/neelegirly/baileys/issues/794
17
+ // https://github.com/nodejs/node/issues/26338
18
+ // Use a Map to store mutexes for each file path
19
+ const fileLocks = new Map()
20
+
21
+ const atomicWriteFile = async(filePath, data) => {
22
+ const tempFilePath = `${filePath}.${process.pid}.${Date.now()}.tmp`
23
+ try {
24
+ await promises_1.writeFile(tempFilePath, data)
25
+ await promises_1.rename(tempFilePath, filePath)
26
+ } catch(error) {
27
+ await promises_1.unlink(tempFilePath).catch(() => { })
28
+ throw error
29
+ }
30
+ }
31
+
32
+ // Get or create a mutex for a specific file path
33
+ const getFileLock = (path) => {
34
+ let mutex = fileLocks.get(path)
35
+ if (!mutex) {
36
+ mutex = new async_mutex_1.Mutex()
37
+ fileLocks.set(path, mutex)
38
+ }
39
+
40
+ return mutex
41
+ }
42
+
43
+ /**
44
+ * stores the full authentication state in a single folder.
45
+ * Far more efficient than singlefileauthstate
46
+ *
47
+ * Again, I wouldn't endorse this for any production level use other than perhaps a bot.
48
+ * Would recommend writing an auth state for use with a proper SQL or No-SQL DB
49
+ * */
50
+ const useMultiFileAuthState = async (folder) => {
51
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
52
+ const writeData = async (data, file) => {
53
+ const filePath = path_1.join(folder, fixFileName(file))
54
+ const mutex = getFileLock(filePath)
55
+ return mutex.acquire().then(async (release) => {
56
+ try {
57
+ await atomicWriteFile(filePath, JSON.stringify(data, generics_1.BufferJSON.replacer))
58
+ } finally {
59
+ release()
60
+ }
61
+ })
62
+ }
63
+ const readData = async (file) => {
64
+ try {
65
+ const filePath = path_1.join(folder, fixFileName(file))
66
+ const mutex = getFileLock(filePath)
67
+ const data = await mutex.acquire().then(async (release) => {
68
+ try {
69
+ return await promises_1.readFile(filePath, { encoding: 'utf-8' })
70
+ } finally {
71
+ release()
72
+ }
73
+ })
74
+
75
+ return JSON.parse(data, generics_1.BufferJSON.reviver)
76
+ } catch (error) {
77
+ return null
78
+ }
79
+ }
80
+ const removeData = async (file) => {
81
+ try {
82
+ const filePath = path_1.join(folder, fixFileName(file))
83
+ const mutex = getFileLock(filePath)
84
+ await mutex.acquire().then(async (release) => {
85
+ try {
86
+ await promises_1.unlink(filePath)
87
+ } finally {
88
+ release()
89
+ }
90
+ })
91
+ } catch {}
92
+ }
93
+ const folderInfo = await promises_1.stat(folder).catch(() => { })
94
+ if (folderInfo) {
95
+ if (!folderInfo.isDirectory()) {
96
+ throw new Error(`found something that is not a directory at ${folder}, either delete it or specify a different location`)
97
+ }
98
+ }
99
+ else {
100
+ await promises_1.mkdir(folder, { recursive: true })
101
+ }
102
+ const fixFileName = (file) => {
103
+ return file?.replace(/\//g, '__')?.replace(/:/g, '-')
104
+ }
105
+ const creds = await readData('creds.json') || auth_utils_1.initAuthCreds()
106
+ return {
107
+ state: {
108
+ creds,
109
+ keys: {
110
+ get: async (type, ids) => {
111
+ const data = {}
112
+ await Promise.all(ids.map(async (id) => {
113
+ let value = await readData(`${type}-${id}.json`)
114
+ if (type === 'app-state-sync-key' && value) {
115
+ value = WAProto_1.proto.Message.AppStateSyncKeyData.fromObject(value)
116
+ }
117
+ data[id] = value
118
+ }))
119
+ return data
120
+ },
121
+ set: async (data) => {
122
+ const tasks = []
123
+ for (const category in data) {
124
+ for (const id in data[category]) {
125
+ const value = data[category][id]
126
+ const file = `${category}-${id}.json`
127
+ tasks.push(value ? writeData(value, file) : removeData(file))
128
+ }
129
+ }
130
+ await Promise.all(tasks)
131
+ }
132
+ }
133
+ },
134
+ saveCreds: async () => {
135
+ return writeData(creds, 'creds.json')
136
+ }
137
+ }
138
+ }
139
+
140
+ /**
141
+ * stores the full authentication state in a single folder.
142
+ * Far more efficient than singlefileauthstate
143
+ *
144
+ * Again, I wouldn't endorse this for any production level use other than perhaps a bot.
145
+ * Would recommend writing an auth state for use with a proper SQL or No-SQL DB
146
+ * */
147
+ const useMultiFileAuthStateV2 = async (folder) => {
148
+ const fixFileName = (file) => {
149
+ return file?.replace(/\//g, '__')?.replace(/:/g, '-')
150
+ }
151
+
152
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
153
+ const writeData = async (data, file) => {
154
+ const filePath = path_1.join(folder, fixFileName(file))
155
+ const mutex = getFileLock(filePath)
156
+ return mutex.acquire().then(async (release) => {
157
+ try {
158
+ await atomicWriteFile(
159
+ filePath,
160
+ JSON.stringify(data, generics_1.BufferJSON.replacer, 2) // <-- lesbar formatiert
161
+ )
162
+ } finally {
163
+ release()
164
+ }
165
+ })
166
+ }
167
+
168
+ const readData = async (file) => {
169
+ try {
170
+ const filePath = path_1.join(folder, fixFileName(file))
171
+ const mutex = getFileLock(filePath)
172
+ const data = await mutex.acquire().then(async (release) => {
173
+ try {
174
+ return await promises_1.readFile(filePath, { encoding: 'utf-8' })
175
+ } finally {
176
+ release()
177
+ }
178
+ })
179
+
180
+ return JSON.parse(data, generics_1.BufferJSON.reviver)
181
+ } catch (error) {
182
+ return null
183
+ }
184
+ }
185
+
186
+ const removeData = async (file) => {
187
+ try {
188
+ const filePath = path_1.join(folder, fixFileName(file))
189
+ const mutex = getFileLock(filePath)
190
+ await mutex.acquire().then(async (release) => {
191
+ try {
192
+ await promises_1.unlink(filePath)
193
+ } finally {
194
+ release()
195
+ }
196
+ })
197
+ } catch {}
198
+ }
199
+
200
+ const folderInfo = await promises_1.stat(folder).catch(() => {})
201
+ if (folderInfo) {
202
+ if (!folderInfo.isDirectory()) {
203
+ throw new Error(`found something that is not a directory at ${folder}, either delete it or specify a different location`)
204
+ }
205
+ } else {
206
+ await promises_1.mkdir(folder, { recursive: true })
207
+ }
208
+
209
+ const creds = await readData('creds.json') || auth_utils_1.initAuthCreds()
210
+
211
+ return {
212
+ state: {
213
+ creds,
214
+ keys: {
215
+ get: async (type, ids) => {
216
+ const data = {}
217
+ await Promise.all(ids.map(async (id) => {
218
+ let value = await readData(`${type}-${id}.json`)
219
+ if (type === 'app-state-sync-key' && value) {
220
+ value = WAProto_1.proto.Message.AppStateSyncKeyData.fromObject(value)
221
+ }
222
+ data[id] = value
223
+ }))
224
+ return data
225
+ },
226
+ set: async (data) => {
227
+ const tasks = []
228
+ for (const category in data) {
229
+ for (const id in data[category]) {
230
+ const value = data[category][id]
231
+ const file = `${category}-${id}.json`
232
+ tasks.push(value ? writeData(value, file) : removeData(file))
233
+ }
234
+ }
235
+ await Promise.all(tasks)
236
+ }
237
+ }
238
+ },
239
+ saveCreds: async () => {
240
+ return writeData(creds, 'creds.json')
241
+ }
242
+ }
243
+ }
244
+
245
+
246
+ module.exports = {
247
+ useMultiFileAuthState,
248
+ useMultiFileAuthStateV2
249
+ }
@@ -0,0 +1,13 @@
1
+ import { ILogger } from './logger'
2
+ import type { AuthenticationState } from '../Types'
3
+
4
+ /**
5
+ * @deprecated use multi file auth state instead please
6
+ * stores the full authentication state in a single JSON file
7
+ *
8
+ * DO NOT USE IN A PROD ENVIRONMENT, only meant to serve as an example
9
+ * */
10
+ export declare const useSingleFileAuthState: (filename: string, logger?: ILogger) => {
11
+ state: AuthenticationState
12
+ saveState: () => void
13
+ }
@@ -0,0 +1,80 @@
1
+ "use strict"
2
+
3
+ Object.defineProperty(exports, "__esModule", { value: true })
4
+
5
+ const WAProto_1 = require("../../WAProto")
6
+ const auth_utils_1 = require("./auth-utils")
7
+ const generics_1 = require("./generics")
8
+
9
+ // useless key map only there to maintain backwards compatibility
10
+ // do not use in your own systems please
11
+ const KEY_MAP = {
12
+ 'pre-key': 'preKeys',
13
+ 'session': 'sessions',
14
+ 'sender-key': 'senderKeys',
15
+ 'app-state-sync-key': 'appStateSyncKeys',
16
+ 'app-state-sync-version': 'appStateVersions',
17
+ 'sender-key-memory': 'senderKeyMemory'
18
+ }
19
+
20
+ /**
21
+ * @deprecated use multi file auth state instead please
22
+ * stores the full authentication state in a single JSON file
23
+ *
24
+ * DO NOT USE IN A PROD ENVIRONMENT, only meant to serve as an example
25
+ * */
26
+ const useSingleFileAuthState = (filename, logger) => {
27
+ // require fs here so that in case "fs" is not available -- the app does not crash
28
+ const { readFileSync, writeFileSync, existsSync } = require('fs')
29
+ let creds
30
+ let keys = {}
31
+ // save the authentication state to a file
32
+ const saveState = () => {
33
+ logger && logger.trace('saving auth state')
34
+ writeFileSync(filename,
35
+ // BufferJSON replacer utility saves buffers nicely
36
+ JSON.stringify({ creds, keys }, generics_1.BufferJSON.replacer, 2))
37
+ }
38
+ if (existsSync(filename)) {
39
+ const result = JSON.parse(readFileSync(filename, { encoding: 'utf-8' }), generics_1.BufferJSON.reviver)
40
+ creds = result.creds
41
+ keys = result.keys
42
+ }
43
+ else {
44
+ creds = auth_utils_1.initAuthCreds()
45
+ keys = {}
46
+ }
47
+ return {
48
+ state: {
49
+ creds,
50
+ keys: {
51
+ get: (type, ids) => {
52
+ const key = KEY_MAP[type]
53
+ return ids.reduce((dict, id) => {
54
+ let value = keys[key]?.[id]
55
+ if (value) {
56
+ if (type === 'app-state-sync-key') {
57
+ value = WAProto_1.proto.Message.AppStateSyncKeyData.fromObject(value)
58
+ }
59
+ dict[id] = value
60
+ }
61
+ return dict
62
+ }, {})
63
+ },
64
+ set: (data) => {
65
+ for (const _key in data) {
66
+ const key = KEY_MAP[_key]
67
+ keys[key] = keys[key] || {}
68
+ Object.assign(keys[key], data[_key])
69
+ }
70
+ saveState()
71
+ }
72
+ }
73
+ },
74
+ saveState
75
+ }
76
+ }
77
+
78
+ module.exports = {
79
+ useSingleFileAuthState
80
+ }
@@ -0,0 +1,13 @@
1
+ import { proto } from '../../WAProto'
2
+ import type { AuthenticationCreds, SignalCreds, SocketConfig } from '../Types'
3
+ import { BinaryNode } from '../WABinary'
4
+
5
+ export declare const generateLoginNode: (userJid: string, config: SocketConfig) => proto.IClientPayload
6
+
7
+ export declare const generateRegistrationNode: ({ registrationId, signedPreKey, signedIdentityKey }: SignalCreds, config: SocketConfig) => proto.ClientPayload
8
+
9
+ export declare const configureSuccessfulPairing: (stanza: BinaryNode, { advSecretKey, signedIdentityKey, signalIdentities }: Pick<AuthenticationCreds, 'advSecretKey' | 'signedIdentityKey' | 'signalIdentities'>) => {
10
+ creds: Partial<AuthenticationCreds>
11
+ reply: BinaryNode
12
+ }
13
+ export declare const encodeSignedDeviceIdentity: (account: proto.IADVSignedDeviceIdentity, includeSignatureKey: boolean) => Uint8Array