@skycodee/baileys 8.0.3 → 8.0.4

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 (114) hide show
  1. package/package.json +4 -4
  2. package/src/Defaults/baileys-version.json +1 -0
  3. package/src/Defaults/index.ts +149 -0
  4. package/src/Signal/Group/ciphertext-message.ts +9 -0
  5. package/src/Signal/Group/group-session-builder.ts +56 -0
  6. package/src/Signal/Group/group_cipher.ts +117 -0
  7. package/src/Signal/Group/index.ts +11 -0
  8. package/src/Signal/Group/keyhelper.ts +28 -0
  9. package/src/Signal/Group/sender-chain-key.ts +34 -0
  10. package/src/Signal/Group/sender-key-distribution-message.ts +95 -0
  11. package/src/Signal/Group/sender-key-message.ts +96 -0
  12. package/src/Signal/Group/sender-key-name.ts +66 -0
  13. package/src/Signal/Group/sender-key-record.ts +69 -0
  14. package/src/Signal/Group/sender-key-state.ts +134 -0
  15. package/src/Signal/Group/sender-message-key.ts +36 -0
  16. package/src/Signal/libsignal.ts +521 -0
  17. package/src/Signal/lid-mapping.ts +328 -0
  18. package/src/Socket/Client/index.ts +2 -0
  19. package/src/Socket/Client/types.ts +22 -0
  20. package/src/Socket/Client/websocket.ts +63 -0
  21. package/src/Socket/business.ts +424 -0
  22. package/src/Socket/chats.ts +1272 -0
  23. package/src/Socket/communities.ts +477 -0
  24. package/src/Socket/groups.ts +361 -0
  25. package/src/Socket/index.ts +15 -0
  26. package/src/Socket/messages-recv.ts +1668 -0
  27. package/src/Socket/messages-send.ts +1296 -0
  28. package/src/Socket/mex.ts +58 -0
  29. package/src/Socket/newsletter.ts +229 -0
  30. package/src/Socket/socket.ts +1184 -0
  31. package/src/Types/Auth.ts +116 -0
  32. package/src/Types/Bussines.ts +20 -0
  33. package/src/Types/Call.ts +15 -0
  34. package/src/Types/Chat.ts +138 -0
  35. package/src/Types/Contact.ts +24 -0
  36. package/src/Types/Events.ts +159 -0
  37. package/src/Types/GroupMetadata.ts +70 -0
  38. package/src/Types/Label.ts +48 -0
  39. package/src/Types/LabelAssociation.ts +35 -0
  40. package/src/Types/Message.ts +380 -0
  41. package/src/Types/Newsletter.ts +98 -0
  42. package/src/Types/Product.ts +85 -0
  43. package/src/Types/Signal.ts +76 -0
  44. package/src/Types/Socket.ts +150 -0
  45. package/src/Types/State.ts +43 -0
  46. package/src/Types/USync.ts +27 -0
  47. package/src/Types/globals.d.ts +8 -0
  48. package/src/Types/index.ts +67 -0
  49. package/src/Utils/auth-utils.ts +368 -0
  50. package/src/Utils/browser-utils.ts +31 -0
  51. package/src/Utils/business.ts +286 -0
  52. package/src/Utils/chat-utils.ts +974 -0
  53. package/src/Utils/crypto.ts +147 -0
  54. package/src/Utils/decode-wa-message.ts +355 -0
  55. package/src/Utils/event-buffer.ts +692 -0
  56. package/src/Utils/generics.ts +474 -0
  57. package/src/Utils/history.ts +161 -0
  58. package/src/Utils/identity-change-handler.ts +83 -0
  59. package/src/Utils/index.ts +19 -0
  60. package/src/Utils/link-preview.ts +111 -0
  61. package/src/Utils/logger.ts +13 -0
  62. package/src/Utils/lt-hash.ts +8 -0
  63. package/src/Utils/make-mutex.ts +42 -0
  64. package/src/Utils/message-retry-manager.ts +295 -0
  65. package/src/Utils/messages-media.ts +984 -0
  66. package/src/Utils/messages.ts +1097 -0
  67. package/src/Utils/noise-handler.ts +268 -0
  68. package/src/Utils/pre-key-manager.ts +126 -0
  69. package/src/Utils/process-message.ts +670 -0
  70. package/src/Utils/reporting-utils.ts +344 -0
  71. package/src/Utils/signal.ts +214 -0
  72. package/src/Utils/sync-action-utils.ts +74 -0
  73. package/src/Utils/tc-token-utils.ts +34 -0
  74. package/src/Utils/use-multi-file-auth-state.ts +136 -0
  75. package/src/Utils/validate-connection.ts +253 -0
  76. package/src/WABinary/constants.ts +1305 -0
  77. package/src/WABinary/decode.ts +308 -0
  78. package/src/WABinary/encode.ts +258 -0
  79. package/src/WABinary/generic-utils.ts +141 -0
  80. package/src/WABinary/index.ts +5 -0
  81. package/src/WABinary/jid-utils.ts +128 -0
  82. package/src/WABinary/types.ts +17 -0
  83. package/src/WAM/BinaryInfo.ts +12 -0
  84. package/src/WAM/constants.ts +22889 -0
  85. package/src/WAM/encode.ts +169 -0
  86. package/src/WAM/index.ts +3 -0
  87. package/src/WAUSync/Protocols/USyncContactProtocol.ts +32 -0
  88. package/src/WAUSync/Protocols/USyncDeviceProtocol.ts +78 -0
  89. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.ts +35 -0
  90. package/src/WAUSync/Protocols/USyncStatusProtocol.ts +44 -0
  91. package/src/WAUSync/Protocols/UsyncBotProfileProtocol.ts +76 -0
  92. package/src/WAUSync/Protocols/UsyncLIDProtocol.ts +33 -0
  93. package/src/WAUSync/Protocols/index.ts +4 -0
  94. package/src/WAUSync/USyncQuery.ts +133 -0
  95. package/src/WAUSync/USyncUser.ts +32 -0
  96. package/src/WAUSync/index.ts +3 -0
  97. package/src/__tests__/Signal/Group/sender-key-state-regression.test.ts +22 -0
  98. package/src/__tests__/Signal/lid-mapping.test.ts +47 -0
  99. package/src/__tests__/Socket/identity-change-handling.test.ts +207 -0
  100. package/src/__tests__/TestUtils/session.ts +47 -0
  101. package/src/__tests__/Utils/generics.test.ts +70 -0
  102. package/src/__tests__/Utils/history.test.ts +362 -0
  103. package/src/__tests__/Utils/messages-media.test.ts +405 -0
  104. package/src/__tests__/Utils/noise-handler.test.ts +339 -0
  105. package/src/__tests__/Utils/process-message.test.ts +138 -0
  106. package/src/__tests__/Utils/process-sync-action.test.ts +359 -0
  107. package/src/__tests__/Utils/reporting-utils.test.ts +160 -0
  108. package/src/__tests__/Utils/signal.test.ts +69 -0
  109. package/src/__tests__/Utils/sync-action-utils.test.ts +183 -0
  110. package/src/__tests__/binary/connection-deadlock.test.ts +54 -0
  111. package/src/__tests__/e2e/fetch-wa-web-version.test-e2e.ts +60 -0
  112. package/src/__tests__/e2e/send-receive-message.test-e2e.ts +644 -0
  113. package/src/__tests__/proto-tojson-long.test.ts +31 -0
  114. package/src/index.ts +13 -0
@@ -0,0 +1,136 @@
1
+ import { Mutex } from 'async-mutex'
2
+ import { mkdir, readFile, stat, unlink, writeFile } from 'fs/promises'
3
+ import { join } from 'path'
4
+ import { proto } from '../../WAProto/index.js'
5
+ import type { AuthenticationCreds, AuthenticationState, SignalDataTypeMap } from '../Types'
6
+ import { initAuthCreds } from './auth-utils'
7
+ import { BufferJSON } from './generics'
8
+
9
+ // We need to lock files due to the fact that we are using async functions to read and write files
10
+ // https://github.com/WhiskeySockets/Baileys/issues/794
11
+ // https://github.com/nodejs/node/issues/26338
12
+ // Use a Map to store mutexes for each file path
13
+ const fileLocks = new Map<string, Mutex>()
14
+
15
+ // Get or create a mutex for a specific file path
16
+ const getFileLock = (path: string): Mutex => {
17
+ let mutex = fileLocks.get(path)
18
+ if (!mutex) {
19
+ mutex = new Mutex()
20
+ fileLocks.set(path, mutex)
21
+ }
22
+
23
+ return mutex
24
+ }
25
+
26
+ /**
27
+ * stores the full authentication state in a single folder.
28
+ * Far more efficient than singlefileauthstate
29
+ *
30
+ * Again, I wouldn't endorse this for any production level use other than perhaps a bot.
31
+ * Would recommend writing an auth state for use with a proper SQL or No-SQL DB
32
+ * */
33
+ export const useMultiFileAuthState = async (
34
+ folder: string
35
+ ): Promise<{ state: AuthenticationState; saveCreds: () => Promise<void> }> => {
36
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
37
+ const writeData = async (data: any, file: string) => {
38
+ const filePath = join(folder, fixFileName(file)!)
39
+ const mutex = getFileLock(filePath)
40
+
41
+ return mutex.acquire().then(async release => {
42
+ try {
43
+ await writeFile(filePath, JSON.stringify(data, BufferJSON.replacer))
44
+ } finally {
45
+ release()
46
+ }
47
+ })
48
+ }
49
+
50
+ const readData = async (file: string) => {
51
+ try {
52
+ const filePath = join(folder, fixFileName(file)!)
53
+ const mutex = getFileLock(filePath)
54
+
55
+ return await mutex.acquire().then(async release => {
56
+ try {
57
+ const data = await readFile(filePath, { encoding: 'utf-8' })
58
+ return JSON.parse(data, BufferJSON.reviver)
59
+ } finally {
60
+ release()
61
+ }
62
+ })
63
+ } catch (error) {
64
+ return null
65
+ }
66
+ }
67
+
68
+ const removeData = async (file: string) => {
69
+ try {
70
+ const filePath = join(folder, fixFileName(file)!)
71
+ const mutex = getFileLock(filePath)
72
+
73
+ return mutex.acquire().then(async release => {
74
+ try {
75
+ await unlink(filePath)
76
+ } catch {
77
+ } finally {
78
+ release()
79
+ }
80
+ })
81
+ } catch {}
82
+ }
83
+
84
+ const folderInfo = await stat(folder).catch(() => {})
85
+ if (folderInfo) {
86
+ if (!folderInfo.isDirectory()) {
87
+ throw new Error(
88
+ `found something that is not a directory at ${folder}, either delete it or specify a different location`
89
+ )
90
+ }
91
+ } else {
92
+ await mkdir(folder, { recursive: true })
93
+ }
94
+
95
+ const fixFileName = (file?: string) => file?.replace(/\//g, '__')?.replace(/:/g, '-')
96
+
97
+ const creds: AuthenticationCreds = (await readData('creds.json')) || initAuthCreds()
98
+
99
+ return {
100
+ state: {
101
+ creds,
102
+ keys: {
103
+ get: async (type, ids) => {
104
+ const data: { [_: string]: SignalDataTypeMap[typeof type] } = {}
105
+ await Promise.all(
106
+ ids.map(async id => {
107
+ let value = await readData(`${type}-${id}.json`)
108
+ if (type === 'app-state-sync-key' && value) {
109
+ value = proto.Message.AppStateSyncKeyData.fromObject(value)
110
+ }
111
+
112
+ data[id] = value
113
+ })
114
+ )
115
+
116
+ return data
117
+ },
118
+ set: async data => {
119
+ const tasks: Promise<void>[] = []
120
+ for (const category in data) {
121
+ for (const id in data[category as keyof SignalDataTypeMap]) {
122
+ const value = data[category as keyof SignalDataTypeMap]![id]
123
+ const file = `${category}-${id}.json`
124
+ tasks.push(value ? writeData(value, file) : removeData(file))
125
+ }
126
+ }
127
+
128
+ await Promise.all(tasks)
129
+ }
130
+ }
131
+ },
132
+ saveCreds: async () => {
133
+ return writeData(creds, 'creds.json')
134
+ }
135
+ }
136
+ }
@@ -0,0 +1,253 @@
1
+ import { Boom } from '@hapi/boom'
2
+ import { createHash } from 'crypto'
3
+ import { proto } from '../../WAProto/index.js'
4
+ import {
5
+ KEY_BUNDLE_TYPE,
6
+ WA_ADV_ACCOUNT_SIG_PREFIX,
7
+ WA_ADV_DEVICE_SIG_PREFIX,
8
+ WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX
9
+ } from '../Defaults'
10
+ import type { AuthenticationCreds, SignalCreds, SocketConfig } from '../Types'
11
+ import { type BinaryNode, getBinaryNodeChild, jidDecode, S_WHATSAPP_NET } from '../WABinary'
12
+ import { Curve, hmacSign } from './crypto'
13
+ import { encodeBigEndian } from './generics'
14
+ import { createSignalIdentity } from './signal'
15
+
16
+ const getUserAgent = (config: SocketConfig): proto.ClientPayload.IUserAgent => {
17
+ return {
18
+ appVersion: {
19
+ primary: config.version[0],
20
+ secondary: config.version[1],
21
+ tertiary: config.version[2]
22
+ },
23
+ platform: proto.ClientPayload.UserAgent.Platform.WEB,
24
+ releaseChannel: proto.ClientPayload.UserAgent.ReleaseChannel.RELEASE,
25
+ osVersion: '0.1',
26
+ device: 'Desktop',
27
+ osBuildNumber: '0.1',
28
+ localeLanguageIso6391: 'en',
29
+
30
+ mnc: '000',
31
+ mcc: '000',
32
+ localeCountryIso31661Alpha2: config.countryCode
33
+ }
34
+ }
35
+
36
+ const PLATFORM_MAP = {
37
+ 'Mac OS': proto.ClientPayload.WebInfo.WebSubPlatform.DARWIN,
38
+ Windows: proto.ClientPayload.WebInfo.WebSubPlatform.WIN32
39
+ }
40
+
41
+ const getWebInfo = (config: SocketConfig): proto.ClientPayload.IWebInfo => {
42
+ let webSubPlatform = proto.ClientPayload.WebInfo.WebSubPlatform.WEB_BROWSER
43
+ if (
44
+ config.syncFullHistory &&
45
+ PLATFORM_MAP[config.browser[0] as keyof typeof PLATFORM_MAP] &&
46
+ config.browser[1] === 'Desktop'
47
+ ) {
48
+ webSubPlatform = PLATFORM_MAP[config.browser[0] as keyof typeof PLATFORM_MAP]
49
+ }
50
+
51
+ return { webSubPlatform }
52
+ }
53
+
54
+ const getClientPayload = (config: SocketConfig) => {
55
+ const payload: proto.IClientPayload = {
56
+ connectType: proto.ClientPayload.ConnectType.WIFI_UNKNOWN,
57
+ connectReason: proto.ClientPayload.ConnectReason.USER_ACTIVATED,
58
+ userAgent: getUserAgent(config)
59
+ }
60
+
61
+ payload.webInfo = getWebInfo(config)
62
+
63
+ return payload
64
+ }
65
+
66
+ export const generateLoginNode = (userJid: string, config: SocketConfig): proto.IClientPayload => {
67
+ const { user, device } = jidDecode(userJid)!
68
+ const payload: proto.IClientPayload = {
69
+ ...getClientPayload(config),
70
+ passive: true,
71
+ pull: true,
72
+ username: +user,
73
+ device: device,
74
+ // TODO: investigate (hard set as false atm)
75
+ lidDbMigrated: false
76
+ }
77
+ return proto.ClientPayload.fromObject(payload)
78
+ }
79
+
80
+ const getPlatformType = (platform: string): proto.DeviceProps.PlatformType => {
81
+ const platformType = platform.toUpperCase()
82
+ return (
83
+ proto.DeviceProps.PlatformType[platformType as keyof typeof proto.DeviceProps.PlatformType] ||
84
+ proto.DeviceProps.PlatformType.CHROME
85
+ )
86
+ }
87
+
88
+ export const generateRegistrationNode = (
89
+ { registrationId, signedPreKey, signedIdentityKey }: SignalCreds,
90
+ config: SocketConfig
91
+ ) => {
92
+ // the app version needs to be md5 hashed
93
+ // and passed in
94
+ const appVersionBuf = createHash('md5')
95
+ .update(config.version.join('.')) // join as string
96
+ .digest()
97
+
98
+ const companion: proto.IDeviceProps = {
99
+ os: config.browser[0],
100
+ platformType: getPlatformType(config.browser[1]),
101
+ requireFullSync: config.syncFullHistory,
102
+ historySyncConfig: {
103
+ storageQuotaMb: 10240,
104
+ inlineInitialPayloadInE2EeMsg: true,
105
+ recentSyncDaysLimit: undefined,
106
+ supportCallLogHistory: false,
107
+ supportBotUserAgentChatHistory: true,
108
+ supportCagReactionsAndPolls: true,
109
+ supportBizHostedMsg: true,
110
+ supportRecentSyncChunkMessageCountTuning: true,
111
+ supportHostedGroupMsg: true,
112
+ supportFbidBotChatHistory: true,
113
+ supportAddOnHistorySyncMigration: undefined,
114
+ supportMessageAssociation: true,
115
+ supportGroupHistory: false,
116
+ onDemandReady: undefined,
117
+ supportGuestChat: undefined
118
+ },
119
+ version: {
120
+ primary: 10,
121
+ secondary: 15,
122
+ tertiary: 7
123
+ }
124
+ }
125
+
126
+ const companionProto = proto.DeviceProps.encode(companion).finish()
127
+
128
+ const registerPayload: proto.IClientPayload = {
129
+ ...getClientPayload(config),
130
+ passive: false,
131
+ pull: false,
132
+ devicePairingData: {
133
+ buildHash: appVersionBuf,
134
+ deviceProps: companionProto,
135
+ eRegid: encodeBigEndian(registrationId),
136
+ eKeytype: KEY_BUNDLE_TYPE,
137
+ eIdent: signedIdentityKey.public,
138
+ eSkeyId: encodeBigEndian(signedPreKey.keyId, 3),
139
+ eSkeyVal: signedPreKey.keyPair.public,
140
+ eSkeySig: signedPreKey.signature
141
+ }
142
+ }
143
+
144
+ return proto.ClientPayload.fromObject(registerPayload)
145
+ }
146
+
147
+ export const configureSuccessfulPairing = (
148
+ stanza: BinaryNode,
149
+ {
150
+ advSecretKey,
151
+ signedIdentityKey,
152
+ signalIdentities
153
+ }: Pick<AuthenticationCreds, 'advSecretKey' | 'signedIdentityKey' | 'signalIdentities'>
154
+ ) => {
155
+ const msgId = stanza.attrs.id
156
+
157
+ const pairSuccessNode = getBinaryNodeChild(stanza, 'pair-success')
158
+
159
+ const deviceIdentityNode = getBinaryNodeChild(pairSuccessNode, 'device-identity')
160
+ const platformNode = getBinaryNodeChild(pairSuccessNode, 'platform')
161
+ const deviceNode = getBinaryNodeChild(pairSuccessNode, 'device')
162
+ const businessNode = getBinaryNodeChild(pairSuccessNode, 'biz')
163
+
164
+ if (!deviceIdentityNode || !deviceNode) {
165
+ throw new Boom('Missing device-identity or device in pair success node', { data: stanza })
166
+ }
167
+
168
+ const bizName = businessNode?.attrs.name
169
+ const jid = deviceNode.attrs.jid
170
+ const lid = deviceNode.attrs.lid
171
+
172
+ const { details, hmac, accountType } = proto.ADVSignedDeviceIdentityHMAC.decode(deviceIdentityNode.content as Buffer)
173
+
174
+ let hmacPrefix = Buffer.from([])
175
+ if (accountType !== undefined && accountType === proto.ADVEncryptionType.HOSTED) {
176
+ hmacPrefix = WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX
177
+ }
178
+
179
+ const advSign = hmacSign(Buffer.concat([hmacPrefix, details!]), Buffer.from(advSecretKey, 'base64'))
180
+ if (Buffer.compare(hmac!, advSign) !== 0) {
181
+ throw new Boom('Invalid account signature')
182
+ }
183
+
184
+ const account = proto.ADVSignedDeviceIdentity.decode(details!)
185
+ const { accountSignatureKey, accountSignature, details: deviceDetails } = account
186
+
187
+ const deviceIdentity = proto.ADVDeviceIdentity.decode(deviceDetails!)
188
+
189
+ const accountSignaturePrefix =
190
+ deviceIdentity.deviceType === proto.ADVEncryptionType.HOSTED
191
+ ? WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX
192
+ : WA_ADV_ACCOUNT_SIG_PREFIX
193
+ const accountMsg = Buffer.concat([accountSignaturePrefix, deviceDetails!, signedIdentityKey.public])
194
+ if (!Curve.verify(accountSignatureKey!, accountMsg, accountSignature!)) {
195
+ throw new Boom('Failed to verify account signature')
196
+ }
197
+
198
+ const deviceMsg = Buffer.concat([
199
+ WA_ADV_DEVICE_SIG_PREFIX,
200
+ deviceDetails!,
201
+ signedIdentityKey.public,
202
+ accountSignatureKey!
203
+ ])
204
+ account.deviceSignature = Curve.sign(signedIdentityKey.private, deviceMsg)
205
+
206
+ const identity = createSignalIdentity(lid!, accountSignatureKey!)
207
+ const accountEnc = encodeSignedDeviceIdentity(account, false)
208
+
209
+ const reply: BinaryNode = {
210
+ tag: 'iq',
211
+ attrs: {
212
+ to: S_WHATSAPP_NET,
213
+ type: 'result',
214
+ id: msgId!
215
+ },
216
+ content: [
217
+ {
218
+ tag: 'pair-device-sign',
219
+ attrs: {},
220
+ content: [
221
+ {
222
+ tag: 'device-identity',
223
+ attrs: { 'key-index': deviceIdentity.keyIndex!.toString() },
224
+ content: accountEnc
225
+ }
226
+ ]
227
+ }
228
+ ]
229
+ }
230
+
231
+ const authUpdate: Partial<AuthenticationCreds> = {
232
+ account,
233
+ me: { id: jid!, name: bizName, lid },
234
+ signalIdentities: [...(signalIdentities || []), identity],
235
+ platform: platformNode?.attrs.name
236
+ }
237
+
238
+ return {
239
+ creds: authUpdate,
240
+ reply
241
+ }
242
+ }
243
+
244
+ export const encodeSignedDeviceIdentity = (account: proto.IADVSignedDeviceIdentity, includeSignatureKey: boolean) => {
245
+ account = { ...account }
246
+ // set to null if we are not to include the signature key
247
+ // or if we are including the signature key but it is empty
248
+ if (!includeSignatureKey || !account.accountSignatureKey?.length) {
249
+ account.accountSignatureKey = null
250
+ }
251
+
252
+ return proto.ADVSignedDeviceIdentity.encode(account).finish()
253
+ }