@neelegirl/baileys 1.5.5 → 1.5.7

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 (203) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +183 -10
  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 +3 -0
  7. package/lib/Defaults/index.d.ts +68 -0
  8. package/lib/Defaults/index.js +137 -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 +21 -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 +162 -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 +1113 -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 +1764 -0
  52. package/lib/Socket/messages-send.d.ts +168 -0
  53. package/lib/Socket/messages-send.js +1303 -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 +766 -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/Call.d.ts +14 -0
  77. package/lib/Types/Call.js +3 -0
  78. package/lib/Types/Chat.d.ts +138 -0
  79. package/lib/Types/Chat.js +9 -0
  80. package/lib/Types/Contact.d.ts +20 -0
  81. package/lib/Types/Contact.js +3 -0
  82. package/lib/Types/Events.d.ts +229 -0
  83. package/lib/Types/Events.js +3 -0
  84. package/lib/Types/GroupMetadata.d.ts +66 -0
  85. package/lib/Types/GroupMetadata.js +3 -0
  86. package/lib/Types/Label.d.ts +48 -0
  87. package/lib/Types/Label.js +31 -0
  88. package/lib/Types/LabelAssociation.d.ts +35 -0
  89. package/lib/Types/LabelAssociation.js +13 -0
  90. package/lib/Types/Message.d.ts +473 -0
  91. package/lib/Types/Message.js +13 -0
  92. package/lib/Types/MexUpdates.d.ts +9 -0
  93. package/lib/Types/MexUpdates.js +18 -0
  94. package/lib/Types/Newsletter.d.ts +109 -0
  95. package/lib/Types/Newsletter.js +40 -0
  96. package/lib/Types/Product.d.ts +92 -0
  97. package/lib/Types/Product.js +3 -0
  98. package/lib/Types/Signal.d.ts +68 -0
  99. package/lib/Types/Signal.js +3 -0
  100. package/lib/Types/Socket.d.ts +122 -0
  101. package/lib/Types/Socket.js +3 -0
  102. package/lib/Types/State.d.ts +41 -0
  103. package/lib/Types/State.js +14 -0
  104. package/lib/Types/USync.d.ts +26 -0
  105. package/lib/Types/USync.js +3 -0
  106. package/lib/Types/index.d.ts +79 -0
  107. package/lib/Types/index.js +48 -0
  108. package/lib/Utils/auth-utils.d.ts +21 -0
  109. package/lib/Utils/auth-utils.js +205 -0
  110. package/lib/Utils/baileys-event-stream.d.ts +18 -0
  111. package/lib/Utils/baileys-event-stream.js +70 -0
  112. package/lib/Utils/business.d.ts +29 -0
  113. package/lib/Utils/business.js +255 -0
  114. package/lib/Utils/chat-utils.d.ts +82 -0
  115. package/lib/Utils/chat-utils.js +781 -0
  116. package/lib/Utils/check-npm-version.d.ts +15 -0
  117. package/lib/Utils/check-npm-version.js +52 -0
  118. package/lib/Utils/crypto.d.ts +56 -0
  119. package/lib/Utils/crypto.js +179 -0
  120. package/lib/Utils/decode-wa-message.d.ts +41 -0
  121. package/lib/Utils/decode-wa-message.js +253 -0
  122. package/lib/Utils/event-buffer.d.ts +39 -0
  123. package/lib/Utils/event-buffer.js +565 -0
  124. package/lib/Utils/generics.d.ts +129 -0
  125. package/lib/Utils/generics.js +618 -0
  126. package/lib/Utils/history.d.ts +23 -0
  127. package/lib/Utils/history.js +110 -0
  128. package/lib/Utils/index.d.ts +19 -0
  129. package/lib/Utils/index.js +41 -0
  130. package/lib/Utils/link-preview.d.ts +23 -0
  131. package/lib/Utils/link-preview.js +120 -0
  132. package/lib/Utils/logger.d.ts +13 -0
  133. package/lib/Utils/logger.js +7 -0
  134. package/lib/Utils/lt-hash.d.ts +14 -0
  135. package/lib/Utils/lt-hash.js +58 -0
  136. package/lib/Utils/make-mutex.d.ts +9 -0
  137. package/lib/Utils/make-mutex.js +49 -0
  138. package/lib/Utils/message-retry-manager.d.ts +82 -0
  139. package/lib/Utils/message-retry-manager.js +177 -0
  140. package/lib/Utils/messages-media.d.ts +129 -0
  141. package/lib/Utils/messages-media.js +806 -0
  142. package/lib/Utils/messages.d.ts +103 -0
  143. package/lib/Utils/messages.js +1579 -0
  144. package/lib/Utils/noise-handler.d.ts +20 -0
  145. package/lib/Utils/noise-handler.js +155 -0
  146. package/lib/Utils/process-message.d.ts +49 -0
  147. package/lib/Utils/process-message.js +428 -0
  148. package/lib/Utils/signal.d.ts +42 -0
  149. package/lib/Utils/signal.js +166 -0
  150. package/lib/Utils/use-mongo-file-auth-state.d.ts +6 -0
  151. package/lib/Utils/use-mongo-file-auth-state.js +84 -0
  152. package/lib/Utils/use-multi-file-auth-state.d.ts +18 -0
  153. package/lib/Utils/use-multi-file-auth-state.js +238 -0
  154. package/lib/Utils/use-single-file-auth-state.d.ts +13 -0
  155. package/lib/Utils/use-single-file-auth-state.js +80 -0
  156. package/lib/Utils/validate-connection.d.ts +13 -0
  157. package/lib/Utils/validate-connection.js +187 -0
  158. package/lib/WABinary/constants.d.ts +30 -0
  159. package/lib/WABinary/constants.js +1316 -0
  160. package/lib/WABinary/decode.d.ts +9 -0
  161. package/lib/WABinary/decode.js +288 -0
  162. package/lib/WABinary/encode.d.ts +3 -0
  163. package/lib/WABinary/encode.js +265 -0
  164. package/lib/WABinary/generic-utils.d.ts +28 -0
  165. package/lib/WABinary/generic-utils.js +142 -0
  166. package/lib/WABinary/index.d.ts +5 -0
  167. package/lib/WABinary/index.js +25 -0
  168. package/lib/WABinary/jid-utils.d.ts +53 -0
  169. package/lib/WABinary/jid-utils.js +92 -0
  170. package/lib/WABinary/types.d.ts +22 -0
  171. package/lib/WABinary/types.js +3 -0
  172. package/lib/WAM/BinaryInfo.d.ts +16 -0
  173. package/lib/WAM/BinaryInfo.js +17 -0
  174. package/lib/WAM/constants.d.ts +47 -0
  175. package/lib/WAM/constants.js +15371 -0
  176. package/lib/WAM/encode.d.ts +3 -0
  177. package/lib/WAM/encode.js +165 -0
  178. package/lib/WAM/index.d.ts +3 -0
  179. package/lib/WAM/index.js +23 -0
  180. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.d.ts +28 -0
  181. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +69 -0
  182. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  183. package/lib/WAUSync/Protocols/USyncContactProtocol.js +36 -0
  184. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +26 -0
  185. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +62 -0
  186. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +14 -0
  187. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +35 -0
  188. package/lib/WAUSync/Protocols/USyncLIDProtocol.d.ts +9 -0
  189. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +30 -0
  190. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +14 -0
  191. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +46 -0
  192. package/lib/WAUSync/Protocols/index.d.ts +6 -0
  193. package/lib/WAUSync/Protocols/index.js +26 -0
  194. package/lib/WAUSync/USyncQuery.d.ts +31 -0
  195. package/lib/WAUSync/USyncQuery.js +92 -0
  196. package/lib/WAUSync/USyncUser.d.ts +12 -0
  197. package/lib/WAUSync/USyncUser.js +30 -0
  198. package/lib/WAUSync/index.d.ts +3 -0
  199. package/lib/WAUSync/index.js +23 -0
  200. package/lib/index.d.ts +13 -0
  201. package/lib/index.js +33 -0
  202. package/package.json +88 -10
  203. package/index.js +0 -38
@@ -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,166 @@
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, excludeZeroDevices) => {
100
+ const { user: myUser, device: myDevice } = WABinary_1.jidDecode(myJid)
101
+ const extracted = []
102
+ for (const userResult of result) {
103
+ const { devices, id } = userResult
104
+ const { user } = WABinary_1.jidDecode(id)
105
+ const deviceList = devices?.deviceList
106
+ if (Array.isArray(deviceList)) {
107
+ for (const { id: device, keyIndex } of deviceList) {
108
+ if ((!excludeZeroDevices || device !== 0) && // if zero devices are not-excluded, or device is non zero
109
+ (myUser !== user || myDevice !== device) && // either different user or if me user, not this device
110
+ (device === 0 || !!keyIndex) // ensure that "key-index" is specified for "non-zero" devices, produces a bad req otherwise
111
+ ) {
112
+ extracted.push({ user, device })
113
+ }
114
+ }
115
+ }
116
+ }
117
+ return extracted
118
+ }
119
+
120
+ /**
121
+ * get the next N keys for upload or processing
122
+ * @param count number of pre-keys to get or generate
123
+ */
124
+ const getNextPreKeys = async ({ creds, keys }, count) => {
125
+ const { newPreKeys, lastPreKeyId, preKeysRange } = generateOrGetPreKeys(creds, count)
126
+ const update = {
127
+ nextPreKeyId: Math.max(lastPreKeyId + 1, creds.nextPreKeyId),
128
+ firstUnuploadedPreKeyId: Math.max(creds.firstUnuploadedPreKeyId, lastPreKeyId + 1)
129
+ }
130
+ await keys.set({ 'pre-key': newPreKeys })
131
+ const preKeys = await getPreKeys(keys, preKeysRange[0], preKeysRange[0] + preKeysRange[1])
132
+ return { update, preKeys }
133
+ }
134
+
135
+ const getNextPreKeysNode = async (state, count) => {
136
+ const { creds } = state
137
+ const { update, preKeys } = await getNextPreKeys(state, count)
138
+ const node = {
139
+ tag: 'iq',
140
+ attrs: {
141
+ xmlns: 'encrypt',
142
+ type: 'set',
143
+ to: WABinary_1.S_WHATSAPP_NET,
144
+ },
145
+ content: [
146
+ { tag: 'registration', attrs: {}, content: generics_1.encodeBigEndian(creds.registrationId) },
147
+ { tag: 'type', attrs: {}, content: Defaults_1.KEY_BUNDLE_TYPE },
148
+ { tag: 'identity', attrs: {}, content: creds.signedIdentityKey.public },
149
+ { tag: 'list', attrs: {}, content: Object.keys(preKeys).map(k => xmppPreKey(preKeys[+k], +k)) },
150
+ xmppSignedPreKey(creds.signedPreKey)
151
+ ]
152
+ }
153
+ return { update, node }
154
+ }
155
+
156
+ module.exports = {
157
+ createSignalIdentity,
158
+ getPreKeys,
159
+ generateOrGetPreKeys,
160
+ xmppSignedPreKey,
161
+ xmppPreKey,
162
+ parseAndInjectE2ESessions,
163
+ extractDeviceJids,
164
+ getNextPreKeys,
165
+ getNextPreKeysNode
166
+ }
@@ -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,238 @@
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/WhiskeySockets/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
+ // Get or create a mutex for a specific file path
22
+ const getFileLock = (path) => {
23
+ let mutex = fileLocks.get(path)
24
+ if (!mutex) {
25
+ mutex = new async_mutex_1.Mutex()
26
+ fileLocks.set(path, mutex)
27
+ }
28
+
29
+ return mutex
30
+ }
31
+
32
+ /**
33
+ * stores the full authentication state in a single folder.
34
+ * Far more efficient than singlefileauthstate
35
+ *
36
+ * Again, I wouldn't endorse this for any production level use other than perhaps a bot.
37
+ * Would recommend writing an auth state for use with a proper SQL or No-SQL DB
38
+ * */
39
+ const useMultiFileAuthState = async (folder) => {
40
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
41
+ const writeData = async (data, file) => {
42
+ const filePath = path_1.join(folder, fixFileName(file))
43
+ const mutex = getFileLock(filePath)
44
+ return mutex.acquire().then(async (release) => {
45
+ try {
46
+ await promises_1.writeFile(filePath, JSON.stringify(data, generics_1.BufferJSON.replacer))
47
+ } finally {
48
+ release()
49
+ }
50
+ })
51
+ }
52
+ const readData = async (file) => {
53
+ try {
54
+ const filePath = path_1.join(folder, fixFileName(file))
55
+ const mutex = getFileLock(filePath)
56
+ const data = await mutex.acquire().then(async (release) => {
57
+ try {
58
+ return await promises_1.readFile(filePath, { encoding: 'utf-8' })
59
+ } finally {
60
+ release()
61
+ }
62
+ })
63
+
64
+ return JSON.parse(data, generics_1.BufferJSON.reviver)
65
+ } catch (error) {
66
+ return null
67
+ }
68
+ }
69
+ const removeData = async (file) => {
70
+ try {
71
+ const filePath = path_1.join(folder, fixFileName(file))
72
+ const mutex = getFileLock(filePath)
73
+ await mutex.acquire().then(async (release) => {
74
+ try {
75
+ await promises_1.unlink(filePath)
76
+ } finally {
77
+ release()
78
+ }
79
+ })
80
+ } catch {}
81
+ }
82
+ const folderInfo = await promises_1.stat(folder).catch(() => { })
83
+ if (folderInfo) {
84
+ if (!folderInfo.isDirectory()) {
85
+ throw new Error(`found something that is not a directory at ${folder}, either delete it or specify a different location`)
86
+ }
87
+ }
88
+ else {
89
+ await promises_1.mkdir(folder, { recursive: true })
90
+ }
91
+ const fixFileName = (file) => {
92
+ return file?.replace(/\//g, '__')?.replace(/:/g, '-')
93
+ }
94
+ const creds = await readData('creds.json') || auth_utils_1.initAuthCreds()
95
+ return {
96
+ state: {
97
+ creds,
98
+ keys: {
99
+ get: async (type, ids) => {
100
+ const data = {}
101
+ await Promise.all(ids.map(async (id) => {
102
+ let value = await readData(`${type}-${id}.json`)
103
+ if (type === 'app-state-sync-key' && value) {
104
+ value = WAProto_1.proto.Message.AppStateSyncKeyData.fromObject(value)
105
+ }
106
+ data[id] = value
107
+ }))
108
+ return data
109
+ },
110
+ set: async (data) => {
111
+ const tasks = []
112
+ for (const category in data) {
113
+ for (const id in data[category]) {
114
+ const value = data[category][id]
115
+ const file = `${category}-${id}.json`
116
+ tasks.push(value ? writeData(value, file) : removeData(file))
117
+ }
118
+ }
119
+ await Promise.all(tasks)
120
+ }
121
+ }
122
+ },
123
+ saveCreds: async () => {
124
+ return writeData(creds, 'creds.json')
125
+ }
126
+ }
127
+ }
128
+
129
+ /**
130
+ * stores the full authentication state in a single folder.
131
+ * Far more efficient than singlefileauthstate
132
+ *
133
+ * Again, I wouldn't endorse this for any production level use other than perhaps a bot.
134
+ * Would recommend writing an auth state for use with a proper SQL or No-SQL DB
135
+ * */
136
+ const useMultiFileAuthStateV2 = async (folder) => {
137
+ const fixFileName = (file) => {
138
+ return file?.replace(/\//g, '__')?.replace(/:/g, '-')
139
+ }
140
+
141
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
142
+ const writeData = async (data, file) => {
143
+ const filePath = path_1.join(folder, fixFileName(file))
144
+ const mutex = getFileLock(filePath)
145
+ return mutex.acquire().then(async (release) => {
146
+ try {
147
+ await promises_1.writeFile(
148
+ filePath,
149
+ JSON.stringify(data, generics_1.BufferJSON.replacer, 2) // <-- lesbar formatiert
150
+ )
151
+ } finally {
152
+ release()
153
+ }
154
+ })
155
+ }
156
+
157
+ const readData = async (file) => {
158
+ try {
159
+ const filePath = path_1.join(folder, fixFileName(file))
160
+ const mutex = getFileLock(filePath)
161
+ const data = await mutex.acquire().then(async (release) => {
162
+ try {
163
+ return await promises_1.readFile(filePath, { encoding: 'utf-8' })
164
+ } finally {
165
+ release()
166
+ }
167
+ })
168
+
169
+ return JSON.parse(data, generics_1.BufferJSON.reviver)
170
+ } catch (error) {
171
+ return null
172
+ }
173
+ }
174
+
175
+ const removeData = async (file) => {
176
+ try {
177
+ const filePath = path_1.join(folder, fixFileName(file))
178
+ const mutex = getFileLock(filePath)
179
+ await mutex.acquire().then(async (release) => {
180
+ try {
181
+ await promises_1.unlink(filePath)
182
+ } finally {
183
+ release()
184
+ }
185
+ })
186
+ } catch {}
187
+ }
188
+
189
+ const folderInfo = await promises_1.stat(folder).catch(() => {})
190
+ if (folderInfo) {
191
+ if (!folderInfo.isDirectory()) {
192
+ throw new Error(`found something that is not a directory at ${folder}, either delete it or specify a different location`)
193
+ }
194
+ } else {
195
+ await promises_1.mkdir(folder, { recursive: true })
196
+ }
197
+
198
+ const creds = await readData('creds.json') || auth_utils_1.initAuthCreds()
199
+
200
+ return {
201
+ state: {
202
+ creds,
203
+ keys: {
204
+ get: async (type, ids) => {
205
+ const data = {}
206
+ await Promise.all(ids.map(async (id) => {
207
+ let value = await readData(`${type}-${id}.json`)
208
+ if (type === 'app-state-sync-key' && value) {
209
+ value = WAProto_1.proto.Message.AppStateSyncKeyData.fromObject(value)
210
+ }
211
+ data[id] = value
212
+ }))
213
+ return data
214
+ },
215
+ set: async (data) => {
216
+ const tasks = []
217
+ for (const category in data) {
218
+ for (const id in data[category]) {
219
+ const value = data[category][id]
220
+ const file = `${category}-${id}.json`
221
+ tasks.push(value ? writeData(value, file) : removeData(file))
222
+ }
223
+ }
224
+ await Promise.all(tasks)
225
+ }
226
+ }
227
+ },
228
+ saveCreds: async () => {
229
+ return writeData(creds, 'creds.json')
230
+ }
231
+ }
232
+ }
233
+
234
+
235
+ module.exports = {
236
+ useMultiFileAuthState,
237
+ useMultiFileAuthStateV2
238
+ }
@@ -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