@sixcore/baileys 1.0.0 → 1.0.2

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 (228) hide show
  1. package/WAProto/index.js +14270 -302
  2. package/jessica.js +91 -0
  3. package/lib/Defaults/baileys-version.json +1 -1
  4. package/lib/Defaults/index.js +117 -79
  5. package/lib/Defaults/phonenumber-mcc.json +223 -0
  6. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  7. package/lib/Signal/Group/ciphertext-message.js +15 -0
  8. package/lib/Signal/Group/group-session-builder.d.ts +14 -0
  9. package/lib/Signal/Group/group-session-builder.js +64 -0
  10. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  11. package/lib/Signal/Group/group_cipher.js +96 -0
  12. package/lib/Signal/Group/index.d.ts +11 -0
  13. package/lib/Signal/Group/index.js +57 -0
  14. package/lib/Signal/Group/keyhelper.d.ts +10 -0
  15. package/lib/Signal/Group/keyhelper.js +55 -0
  16. package/lib/Signal/Group/queue-job.d.ts +1 -0
  17. package/lib/Signal/Group/queue-job.js +57 -0
  18. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  19. package/lib/Signal/Group/sender-chain-key.js +34 -0
  20. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  21. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  22. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  23. package/lib/Signal/Group/sender-key-message.js +69 -0
  24. package/lib/Signal/Group/sender-key-name.d.ts +17 -0
  25. package/lib/Signal/Group/sender-key-name.js +51 -0
  26. package/lib/Signal/Group/sender-key-record.d.ts +30 -0
  27. package/lib/Signal/Group/sender-key-record.js +53 -0
  28. package/lib/Signal/Group/sender-key-state.d.ts +38 -0
  29. package/lib/Signal/Group/sender-key-state.js +99 -0
  30. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  31. package/{WASignalGroup/sender_message_key.js → lib/Signal/Group/sender-message-key.js} +6 -16
  32. package/lib/Signal/libsignal.js +51 -29
  33. package/lib/Socket/business.d.ts +43 -42
  34. package/lib/Socket/chats.d.ts +222 -36
  35. package/lib/Socket/chats.js +173 -153
  36. package/lib/Socket/dugong.d.ts +254 -0
  37. package/lib/Socket/dugong.js +484 -0
  38. package/lib/Socket/groups.d.ts +7 -7
  39. package/lib/Socket/groups.js +37 -35
  40. package/lib/Socket/index.d.ts +52 -51
  41. package/lib/Socket/index.js +1 -0
  42. package/lib/Socket/messages-recv.d.ts +37 -34
  43. package/lib/Socket/messages-recv.js +175 -37
  44. package/lib/Socket/messages-send.d.ts +12 -18
  45. package/lib/Socket/messages-send.js +396 -574
  46. package/lib/Socket/newsletter.d.ts +28 -26
  47. package/lib/Socket/newsletter.js +132 -121
  48. package/lib/Socket/registration.d.ts +52 -49
  49. package/lib/Socket/registration.js +7 -7
  50. package/lib/Socket/socket.d.ts +0 -1
  51. package/lib/Socket/socket.js +49 -27
  52. package/lib/Socket/usync.d.ts +10 -11
  53. package/lib/Store/make-cache-manager-store.d.ts +1 -2
  54. package/lib/Store/make-in-memory-store.d.ts +2 -2
  55. package/lib/Store/make-in-memory-store.js +1 -5
  56. package/lib/Store/make-ordered-dictionary.js +2 -2
  57. package/lib/Types/Auth.d.ts +1 -0
  58. package/lib/Types/Call.d.ts +1 -1
  59. package/lib/Types/Chat.d.ts +7 -12
  60. package/lib/Types/Events.d.ts +2 -17
  61. package/lib/Types/GroupMetadata.d.ts +2 -3
  62. package/lib/Types/Label.d.ts +0 -11
  63. package/lib/Types/Label.js +1 -1
  64. package/lib/Types/LabelAssociation.js +1 -1
  65. package/lib/Types/Message.d.ts +10 -170
  66. package/lib/Types/Newsletter.d.ts +97 -86
  67. package/lib/Types/Newsletter.js +38 -32
  68. package/lib/Types/Socket.d.ts +2 -7
  69. package/lib/Types/index.d.ts +0 -9
  70. package/lib/Types/index.js +1 -1
  71. package/lib/Utils/auth-utils.js +14 -35
  72. package/lib/Utils/business.d.ts +1 -1
  73. package/lib/Utils/business.js +2 -2
  74. package/lib/Utils/chat-utils.d.ts +12 -11
  75. package/lib/Utils/chat-utils.js +36 -52
  76. package/lib/Utils/crypto.d.ts +16 -15
  77. package/lib/Utils/crypto.js +26 -74
  78. package/lib/Utils/decode-wa-message.d.ts +0 -17
  79. package/lib/Utils/decode-wa-message.js +17 -53
  80. package/lib/Utils/event-buffer.js +7 -10
  81. package/lib/Utils/generics.d.ts +17 -13
  82. package/lib/Utils/generics.js +79 -58
  83. package/lib/Utils/history.d.ts +2 -6
  84. package/lib/Utils/history.js +6 -4
  85. package/lib/Utils/logger.d.ts +3 -1
  86. package/lib/Utils/lt-hash.js +12 -12
  87. package/lib/Utils/make-mutex.d.ts +2 -2
  88. package/lib/Utils/messages-media.d.ts +28 -25
  89. package/lib/Utils/messages-media.js +733 -557
  90. package/lib/Utils/messages.js +68 -473
  91. package/lib/Utils/noise-handler.d.ts +5 -4
  92. package/lib/Utils/noise-handler.js +14 -19
  93. package/lib/Utils/process-message.d.ts +5 -5
  94. package/lib/Utils/process-message.js +23 -75
  95. package/lib/Utils/signal.d.ts +1 -2
  96. package/lib/Utils/signal.js +26 -32
  97. package/lib/Utils/use-multi-file-auth-state.d.ts +1 -0
  98. package/lib/Utils/use-multi-file-auth-state.js +66 -242
  99. package/lib/Utils/validate-connection.d.ts +1 -1
  100. package/lib/Utils/validate-connection.js +88 -64
  101. package/lib/WABinary/constants.d.ts +27 -24
  102. package/lib/WABinary/decode.d.ts +2 -1
  103. package/lib/WABinary/decode.js +11 -23
  104. package/lib/WABinary/encode.d.ts +2 -1
  105. package/lib/WABinary/encode.js +147 -134
  106. package/lib/WABinary/generic-utils.d.ts +5 -2
  107. package/lib/WABinary/generic-utils.js +125 -37
  108. package/lib/WABinary/jid-utils.d.ts +1 -1
  109. package/lib/WAM/BinaryInfo.d.ts +11 -2
  110. package/lib/WAM/encode.d.ts +2 -1
  111. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +3 -3
  112. package/lib/WAUSync/USyncUser.d.ts +2 -0
  113. package/lib/index.d.ts +12 -0
  114. package/lib/index.js +64 -1
  115. package/package.json +113 -51
  116. package/WAProto/GenerateStatics.sh +0 -4
  117. package/WAProto/WAProto.proto +0 -4357
  118. package/WAProto/index.d.ts +0 -50383
  119. package/WASignalGroup/GroupProtocol.js +0 -1697
  120. package/WASignalGroup/ciphertext_message.js +0 -16
  121. package/WASignalGroup/generate-proto.sh +0 -1
  122. package/WASignalGroup/group.proto +0 -42
  123. package/WASignalGroup/group_cipher.js +0 -120
  124. package/WASignalGroup/group_session_builder.js +0 -46
  125. package/WASignalGroup/index.js +0 -5
  126. package/WASignalGroup/keyhelper.js +0 -21
  127. package/WASignalGroup/protobufs.js +0 -3
  128. package/WASignalGroup/queue_job.js +0 -69
  129. package/WASignalGroup/sender_chain_key.js +0 -50
  130. package/WASignalGroup/sender_key_distribution_message.js +0 -78
  131. package/WASignalGroup/sender_key_message.js +0 -92
  132. package/WASignalGroup/sender_key_name.js +0 -70
  133. package/WASignalGroup/sender_key_record.js +0 -56
  134. package/WASignalGroup/sender_key_state.js +0 -129
  135. package/lib/Utils/use-single-file-auth-state.d.ts +0 -12
  136. package/lib/Utils/use-single-file-auth-state.js +0 -75
  137. package/src/Defaults/baileys-version.json +0 -3
  138. package/src/Defaults/index.ts +0 -133
  139. package/src/Signal/Group/ciphertext-message.ts +0 -9
  140. package/src/Signal/Group/group-session-builder.ts +0 -56
  141. package/src/Signal/Group/group_cipher.ts +0 -117
  142. package/src/Signal/Group/index.ts +0 -11
  143. package/src/Signal/Group/keyhelper.ts +0 -28
  144. package/src/Signal/Group/sender-chain-key.ts +0 -34
  145. package/src/Signal/Group/sender-key-distribution-message.ts +0 -95
  146. package/src/Signal/Group/sender-key-message.ts +0 -96
  147. package/src/Signal/Group/sender-key-name.ts +0 -66
  148. package/src/Signal/Group/sender-key-record.ts +0 -69
  149. package/src/Signal/Group/sender-key-state.ts +0 -134
  150. package/src/Signal/Group/sender-message-key.ts +0 -36
  151. package/src/Signal/libsignal.ts +0 -447
  152. package/src/Signal/lid-mapping.ts +0 -209
  153. package/src/Socket/Client/index.ts +0 -2
  154. package/src/Socket/Client/types.ts +0 -22
  155. package/src/Socket/Client/websocket.ts +0 -56
  156. package/src/Socket/business.ts +0 -421
  157. package/src/Socket/chats.ts +0 -1223
  158. package/src/Socket/communities.ts +0 -477
  159. package/src/Socket/groups.ts +0 -361
  160. package/src/Socket/index.ts +0 -22
  161. package/src/Socket/messages-recv.ts +0 -1563
  162. package/src/Socket/messages-send.ts +0 -1210
  163. package/src/Socket/mex.ts +0 -58
  164. package/src/Socket/newsletter.ts +0 -229
  165. package/src/Socket/socket.ts +0 -1072
  166. package/src/Types/Auth.ts +0 -115
  167. package/src/Types/Bussines.ts +0 -20
  168. package/src/Types/Call.ts +0 -14
  169. package/src/Types/Chat.ts +0 -138
  170. package/src/Types/Contact.ts +0 -24
  171. package/src/Types/Events.ts +0 -132
  172. package/src/Types/GroupMetadata.ts +0 -70
  173. package/src/Types/Label.ts +0 -48
  174. package/src/Types/LabelAssociation.ts +0 -35
  175. package/src/Types/Message.ts +0 -424
  176. package/src/Types/Newsletter.ts +0 -98
  177. package/src/Types/Product.ts +0 -85
  178. package/src/Types/Signal.ts +0 -76
  179. package/src/Types/Socket.ts +0 -150
  180. package/src/Types/State.ts +0 -43
  181. package/src/Types/USync.ts +0 -27
  182. package/src/Types/globals.d.ts +0 -8
  183. package/src/Types/index.ts +0 -67
  184. package/src/Utils/auth-utils.ts +0 -331
  185. package/src/Utils/browser-utils.ts +0 -31
  186. package/src/Utils/business.ts +0 -286
  187. package/src/Utils/chat-utils.ts +0 -933
  188. package/src/Utils/crypto.ts +0 -184
  189. package/src/Utils/decode-wa-message.ts +0 -355
  190. package/src/Utils/event-buffer.ts +0 -662
  191. package/src/Utils/generics.ts +0 -470
  192. package/src/Utils/history.ts +0 -114
  193. package/src/Utils/index.ts +0 -18
  194. package/src/Utils/link-preview.ts +0 -111
  195. package/src/Utils/logger.ts +0 -13
  196. package/src/Utils/lt-hash.ts +0 -65
  197. package/src/Utils/make-mutex.ts +0 -45
  198. package/src/Utils/message-retry-manager.ts +0 -229
  199. package/src/Utils/messages-media.ts +0 -820
  200. package/src/Utils/messages.ts +0 -1137
  201. package/src/Utils/noise-handler.ts +0 -192
  202. package/src/Utils/pre-key-manager.ts +0 -126
  203. package/src/Utils/process-message.ts +0 -622
  204. package/src/Utils/signal.ts +0 -214
  205. package/src/Utils/use-multi-file-auth-state.ts +0 -136
  206. package/src/Utils/validate-connection.ts +0 -253
  207. package/src/WABinary/constants.ts +0 -1305
  208. package/src/WABinary/decode.ts +0 -281
  209. package/src/WABinary/encode.ts +0 -253
  210. package/src/WABinary/generic-utils.ts +0 -127
  211. package/src/WABinary/index.ts +0 -5
  212. package/src/WABinary/jid-utils.ts +0 -128
  213. package/src/WABinary/types.ts +0 -17
  214. package/src/WAM/BinaryInfo.ts +0 -12
  215. package/src/WAM/constants.ts +0 -22889
  216. package/src/WAM/encode.ts +0 -169
  217. package/src/WAM/index.ts +0 -3
  218. package/src/WAUSync/Protocols/USyncContactProtocol.ts +0 -32
  219. package/src/WAUSync/Protocols/USyncDeviceProtocol.ts +0 -78
  220. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.ts +0 -35
  221. package/src/WAUSync/Protocols/USyncStatusProtocol.ts +0 -44
  222. package/src/WAUSync/Protocols/UsyncBotProfileProtocol.ts +0 -76
  223. package/src/WAUSync/Protocols/UsyncLIDProtocol.ts +0 -33
  224. package/src/WAUSync/Protocols/index.ts +0 -4
  225. package/src/WAUSync/USyncQuery.ts +0 -133
  226. package/src/WAUSync/USyncUser.ts +0 -32
  227. package/src/WAUSync/index.ts +0 -3
  228. package/src/index.ts +0 -13
@@ -1,150 +0,0 @@
1
- import type { Agent } from 'https'
2
- import type { URL } from 'url'
3
- import { proto } from '../../WAProto/index.js'
4
- import type { ILogger } from '../Utils/logger'
5
- import type { AuthenticationState, LIDMapping, SignalAuthState, TransactionCapabilityOptions } from './Auth'
6
- import type { GroupMetadata } from './GroupMetadata'
7
- import { type MediaConnInfo, type WAMessageKey } from './Message'
8
- import type { SignalRepositoryWithLIDStore } from './Signal'
9
-
10
- export type WAVersion = [number, number, number]
11
- export type WABrowserDescription = [string, string, string]
12
-
13
- export type CacheStore = {
14
- /** get a cached key and change the stats */
15
- get<T>(key: string): Promise<T> | T | undefined
16
- /** set a key in the cache */
17
- set<T>(key: string, value: T): Promise<void> | void | number | boolean
18
- /** delete a key from the cache */
19
- del(key: string): void | Promise<void> | number | boolean
20
- /** flush all data */
21
- flushAll(): void | Promise<void>
22
- }
23
-
24
- export type PossiblyExtendedCacheStore = CacheStore & {
25
- mget?: <T>(keys: string[]) => Promise<Record<string, T | undefined>>
26
- mset?: <T>(entries: { key: string; value: T }[]) => Promise<void> | void | number | boolean
27
- mdel?: (keys: string[]) => void | Promise<void> | number | boolean
28
- }
29
-
30
- export type PatchedMessageWithRecipientJID = proto.IMessage & { recipientJid?: string }
31
-
32
- export type SocketConfig = {
33
- /** the WS url to connect to WA */
34
- waWebSocketUrl: string | URL
35
- /** Fails the connection if the socket times out in this interval */
36
- connectTimeoutMs: number
37
- /** Default timeout for queries, undefined for no timeout */
38
- defaultQueryTimeoutMs: number | undefined
39
- /** ping-pong interval for WS connection */
40
- keepAliveIntervalMs: number
41
- /** should baileys use the mobile api instead of the multi device api
42
- * @deprecated This feature has been removed
43
- */
44
- mobile?: boolean
45
- /** proxy agent */
46
- agent?: Agent
47
- /** logger */
48
- logger: ILogger
49
- /** version to connect with */
50
- version: WAVersion
51
- /** override browser config */
52
- browser: WABrowserDescription
53
- /** agent used for fetch requests -- uploading/downloading media */
54
- fetchAgent?: Agent
55
- /** should the QR be printed in the terminal
56
- * @deprecated This feature has been removed
57
- */
58
- printQRInTerminal?: boolean
59
- /** should events be emitted for actions done by this socket connection */
60
- emitOwnEvents: boolean
61
- /** custom upload hosts to upload media to */
62
- customUploadHosts: MediaConnInfo['hosts']
63
- /** time to wait between sending new retry requests */
64
- retryRequestDelayMs: number
65
- /** max retry count */
66
- maxMsgRetryCount: number
67
- /** time to wait for the generation of the next QR in ms */
68
- qrTimeout?: number
69
- /** provide an auth state object to maintain the auth state */
70
- auth: AuthenticationState
71
- /** manage history processing with this control; by default will sync up everything */
72
- shouldSyncHistoryMessage: (msg: proto.Message.IHistorySyncNotification) => boolean
73
- /** transaction capability options for SignalKeyStore */
74
- transactionOpts: TransactionCapabilityOptions
75
- /** marks the client as online whenever the socket successfully connects */
76
- markOnlineOnConnect: boolean
77
- /** alphanumeric country code (USA -> US) for the number used */
78
- countryCode: string
79
- /** provide a cache to store media, so does not have to be re-uploaded */
80
- mediaCache?: CacheStore
81
- /**
82
- * map to store the retry counts for failed messages;
83
- * used to determine whether to retry a message or not */
84
- msgRetryCounterCache?: CacheStore
85
- /** provide a cache to store a user's device list */
86
- userDevicesCache?: PossiblyExtendedCacheStore
87
- /** cache to store call offers */
88
- callOfferCache?: CacheStore
89
- /** cache to track placeholder resends */
90
- placeholderResendCache?: CacheStore
91
- /** width for link preview images */
92
- linkPreviewImageThumbnailWidth: number
93
- /** Should Baileys ask the phone for full history, will be received async */
94
- syncFullHistory: boolean
95
- /** Should baileys fire init queries automatically, default true */
96
- fireInitQueries: boolean
97
- /**
98
- * generate a high quality link preview,
99
- * entails uploading the jpegThumbnail to WA
100
- * */
101
- generateHighQualityLinkPreview: boolean
102
-
103
- /** Enable automatic session recreation for failed messages */
104
- enableAutoSessionRecreation: boolean
105
-
106
- /** Enable recent message caching for retry handling */
107
- enableRecentMessageCache: boolean
108
-
109
- /**
110
- * Returns if a jid should be ignored,
111
- * no event for that jid will be triggered.
112
- * Messages from that jid will also not be decrypted
113
- * */
114
- shouldIgnoreJid: (jid: string) => boolean | undefined
115
-
116
- /**
117
- * Optionally patch the message before sending out
118
- * */
119
- patchMessageBeforeSending: (
120
- msg: proto.IMessage,
121
- recipientJids?: string[]
122
- ) =>
123
- | Promise<PatchedMessageWithRecipientJID[] | PatchedMessageWithRecipientJID>
124
- | PatchedMessageWithRecipientJID[]
125
- | PatchedMessageWithRecipientJID
126
-
127
- /** verify app state MACs */
128
- appStateMacVerification: {
129
- patch: boolean
130
- snapshot: boolean
131
- }
132
-
133
- /** options for HTTP fetch requests */
134
- options: RequestInit
135
- /**
136
- * fetch a message from your store
137
- * implement this so that messages failed to send
138
- * (solves the "this message can take a while" issue) can be retried
139
- * */
140
- getMessage: (key: WAMessageKey) => Promise<proto.IMessage | undefined>
141
-
142
- /** cached group metadata, use to prevent redundant requests to WA & speed up msg sending */
143
- cachedGroupMetadata: (jid: string) => Promise<GroupMetadata | undefined>
144
-
145
- makeSignalRepository: (
146
- auth: SignalAuthState,
147
- logger: ILogger,
148
- pnToLIDFunc?: (jids: string[]) => Promise<LIDMapping[] | undefined>
149
- ) => SignalRepositoryWithLIDStore
150
- }
@@ -1,43 +0,0 @@
1
- import { Boom } from '@hapi/boom'
2
- import type { Contact } from './Contact'
3
-
4
- export enum SyncState {
5
- /** The socket is connecting, but we haven't received pending notifications yet. */
6
- Connecting,
7
- /** Pending notifications received. Buffering events until we decide whether to sync or not. */
8
- AwaitingInitialSync,
9
- /** The initial app state sync (history, etc.) is in progress. Buffering continues. */
10
- Syncing,
11
- /** Initial sync is complete, or was skipped. The socket is fully operational and events are processed in real-time. */
12
- Online
13
- }
14
-
15
- export type WAConnectionState = 'open' | 'connecting' | 'close'
16
-
17
- export type ConnectionState = {
18
- /** connection is now open, connecting or closed */
19
- connection: WAConnectionState
20
-
21
- /** the error that caused the connection to close */
22
- lastDisconnect?: {
23
- // TODO: refactor and gain independence from Boom
24
- error: Boom | Error | undefined
25
- date: Date
26
- }
27
- /** is this a new login */
28
- isNewLogin?: boolean
29
- /** the current QR code */
30
- qr?: string
31
- /** has the device received all pending notifications while it was offline */
32
- receivedPendingNotifications?: boolean
33
- /** legacy connection options */
34
- legacy?: {
35
- phoneConnected: boolean
36
- user?: Contact
37
- }
38
- /**
39
- * if the client is shown as an active, online client.
40
- * If this is false, the primary phone and other devices will receive notifs
41
- * */
42
- isOnline?: boolean
43
- }
@@ -1,27 +0,0 @@
1
- import type { BinaryNode } from '../WABinary'
2
- import { USyncUser } from '../WAUSync'
3
-
4
- /**
5
- * Defines the interface for a USyncQuery protocol
6
- */
7
- export interface USyncQueryProtocol {
8
- /**
9
- * The name of the protocol
10
- */
11
- name: string
12
- /**
13
- * Defines what goes inside the query part of a USyncQuery
14
- */
15
- getQueryElement: () => BinaryNode
16
- /**
17
- * Defines what goes inside the user part of a USyncQuery
18
- */
19
- getUserElement: (user: USyncUser) => BinaryNode | null
20
-
21
- /**
22
- * Parse the result of the query
23
- * @param data Data from the result
24
- * @returns Whatever the protocol is supposed to return
25
- */
26
- parser: (data: BinaryNode) => unknown
27
- }
@@ -1,8 +0,0 @@
1
- declare global {
2
- interface RequestInit {
3
- dispatcher?: any
4
- duplex?: 'half' | 'full'
5
- }
6
- }
7
-
8
- export {}
@@ -1,67 +0,0 @@
1
- export * from './Auth'
2
- export * from './GroupMetadata'
3
- export * from './Chat'
4
- export * from './Contact'
5
- export * from './State'
6
- export * from './Message'
7
- export * from './Socket'
8
- export * from './Events'
9
- export * from './Product'
10
- export * from './Call'
11
- export * from './Signal'
12
- export * from './Newsletter'
13
-
14
- import type { AuthenticationState } from './Auth'
15
- import type { SocketConfig } from './Socket'
16
-
17
- export type UserFacingSocketConfig = Partial<SocketConfig> & { auth: AuthenticationState }
18
-
19
- export type BrowsersMap = {
20
- ubuntu(browser: string): [string, string, string]
21
- macOS(browser: string): [string, string, string]
22
- baileys(browser: string): [string, string, string]
23
- windows(browser: string): [string, string, string]
24
- appropriate(browser: string): [string, string, string]
25
- }
26
-
27
- export enum DisconnectReason {
28
- connectionClosed = 428,
29
- connectionLost = 408,
30
- connectionReplaced = 440,
31
- timedOut = 408,
32
- loggedOut = 401,
33
- badSession = 500,
34
- restartRequired = 515,
35
- multideviceMismatch = 411,
36
- forbidden = 403,
37
- unavailableService = 503
38
- }
39
-
40
- export type WAInitResponse = {
41
- ref: string
42
- ttl: number
43
- status: 200
44
- }
45
-
46
- export type WABusinessHoursConfig = {
47
- day_of_week: string
48
- mode: string
49
- open_time?: number
50
- close_time?: number
51
- }
52
-
53
- export type WABusinessProfile = {
54
- description: string
55
- email: string | undefined
56
- business_hours: {
57
- timezone?: string
58
- config?: WABusinessHoursConfig[]
59
- business_config?: WABusinessHoursConfig[]
60
- }
61
- website: string[]
62
- category?: string
63
- wid?: string
64
- address?: string
65
- }
66
-
67
- export type CurveKeyPair = { private: Uint8Array; public: Uint8Array }
@@ -1,331 +0,0 @@
1
- import NodeCache from '@cacheable/node-cache'
2
- import { AsyncLocalStorage } from 'async_hooks'
3
- import { Mutex } from 'async-mutex'
4
- import { randomBytes } from 'crypto'
5
- import PQueue from 'p-queue'
6
- import { DEFAULT_CACHE_TTLS } from '../Defaults'
7
- import type {
8
- AuthenticationCreds,
9
- CacheStore,
10
- SignalDataSet,
11
- SignalDataTypeMap,
12
- SignalKeyStore,
13
- SignalKeyStoreWithTransaction,
14
- TransactionCapabilityOptions
15
- } from '../Types'
16
- import { Curve, signedKeyPair } from './crypto'
17
- import { delay, generateRegistrationId } from './generics'
18
- import type { ILogger } from './logger'
19
- import { PreKeyManager } from './pre-key-manager'
20
-
21
- /**
22
- * Transaction context stored in AsyncLocalStorage
23
- */
24
- interface TransactionContext {
25
- cache: SignalDataSet
26
- mutations: SignalDataSet
27
- dbQueries: number
28
- }
29
-
30
- /**
31
- * Adds caching capability to a SignalKeyStore
32
- * @param store the store to add caching to
33
- * @param logger to log trace events
34
- * @param _cache cache store to use
35
- */
36
- export function makeCacheableSignalKeyStore(
37
- store: SignalKeyStore,
38
- logger?: ILogger,
39
- _cache?: CacheStore
40
- ): SignalKeyStore {
41
- const cache =
42
- _cache ||
43
- new NodeCache<SignalDataTypeMap[keyof SignalDataTypeMap]>({
44
- stdTTL: DEFAULT_CACHE_TTLS.SIGNAL_STORE, // 5 minutes
45
- useClones: false,
46
- deleteOnExpire: true
47
- })
48
-
49
- // Mutex for protecting cache operations
50
- const cacheMutex = new Mutex()
51
-
52
- function getUniqueId(type: string, id: string) {
53
- return `${type}.${id}`
54
- }
55
-
56
- return {
57
- async get(type, ids) {
58
- return cacheMutex.runExclusive(async () => {
59
- const data: { [_: string]: SignalDataTypeMap[typeof type] } = {}
60
- const idsToFetch: string[] = []
61
-
62
- for (const id of ids) {
63
- const item = (await cache.get<SignalDataTypeMap[typeof type]>(getUniqueId(type, id))) as any
64
- if (typeof item !== 'undefined') {
65
- data[id] = item
66
- } else {
67
- idsToFetch.push(id)
68
- }
69
- }
70
-
71
- if (idsToFetch.length) {
72
- logger?.trace({ items: idsToFetch.length }, 'loading from store')
73
- const fetched = await store.get(type, idsToFetch)
74
- for (const id of idsToFetch) {
75
- const item = fetched[id]
76
- if (item) {
77
- data[id] = item
78
- await cache.set(getUniqueId(type, id), item as SignalDataTypeMap[keyof SignalDataTypeMap])
79
- }
80
- }
81
- }
82
-
83
- return data
84
- })
85
- },
86
- async set(data) {
87
- return cacheMutex.runExclusive(async () => {
88
- let keys = 0
89
- for (const type in data) {
90
- for (const id in data[type as keyof SignalDataTypeMap]) {
91
- await cache.set(getUniqueId(type, id), data[type as keyof SignalDataTypeMap]![id]!)
92
- keys += 1
93
- }
94
- }
95
-
96
- logger?.trace({ keys }, 'updated cache')
97
- await store.set(data)
98
- })
99
- },
100
- async clear() {
101
- await cache.flushAll()
102
- await store.clear?.()
103
- }
104
- }
105
- }
106
-
107
- /**
108
- * Adds DB-like transaction capability to the SignalKeyStore
109
- * Uses AsyncLocalStorage for automatic context management
110
- * @param state the key store to apply this capability to
111
- * @param logger logger to log events
112
- * @returns SignalKeyStore with transaction capability
113
- */
114
- export const addTransactionCapability = (
115
- state: SignalKeyStore,
116
- logger: ILogger,
117
- { maxCommitRetries, delayBetweenTriesMs }: TransactionCapabilityOptions
118
- ): SignalKeyStoreWithTransaction => {
119
- const txStorage = new AsyncLocalStorage<TransactionContext>()
120
-
121
- // Queues for concurrency control
122
- const keyQueues = new Map<string, PQueue>()
123
- const txMutexes = new Map<string, Mutex>()
124
-
125
- // Pre-key manager for specialized operations
126
- const preKeyManager = new PreKeyManager(state, logger)
127
-
128
- /**
129
- * Get or create a queue for a specific key type
130
- */
131
- function getQueue(key: string): PQueue {
132
- if (!keyQueues.has(key)) {
133
- keyQueues.set(key, new PQueue({ concurrency: 1 }))
134
- }
135
-
136
- return keyQueues.get(key)!
137
- }
138
-
139
- /**
140
- * Get or create a transaction mutex
141
- */
142
- function getTxMutex(key: string): Mutex {
143
- if (!txMutexes.has(key)) {
144
- txMutexes.set(key, new Mutex())
145
- }
146
-
147
- return txMutexes.get(key)!
148
- }
149
-
150
- /**
151
- * Check if currently in a transaction
152
- */
153
- function isInTransaction(): boolean {
154
- return !!txStorage.getStore()
155
- }
156
-
157
- /**
158
- * Commit transaction with retries
159
- */
160
- async function commitWithRetry(mutations: SignalDataSet): Promise<void> {
161
- if (Object.keys(mutations).length === 0) {
162
- logger.trace('no mutations in transaction')
163
- return
164
- }
165
-
166
- logger.trace('committing transaction')
167
-
168
- for (let attempt = 0; attempt < maxCommitRetries; attempt++) {
169
- try {
170
- await state.set(mutations)
171
- logger.trace({ mutationCount: Object.keys(mutations).length }, 'committed transaction')
172
- return
173
- } catch (error) {
174
- const retriesLeft = maxCommitRetries - attempt - 1
175
- logger.warn(`failed to commit mutations, retries left=${retriesLeft}`)
176
-
177
- if (retriesLeft === 0) {
178
- throw error
179
- }
180
-
181
- await delay(delayBetweenTriesMs)
182
- }
183
- }
184
- }
185
-
186
- return {
187
- get: async (type, ids) => {
188
- const ctx = txStorage.getStore()
189
-
190
- if (!ctx) {
191
- // No transaction - direct read without exclusive lock for concurrency
192
- return state.get(type, ids)
193
- }
194
-
195
- // In transaction - check cache first
196
- const cached = ctx.cache[type] || {}
197
- const missing = ids.filter(id => !(id in cached))
198
-
199
- if (missing.length > 0) {
200
- ctx.dbQueries++
201
- logger.trace({ type, count: missing.length }, 'fetching missing keys in transaction')
202
-
203
- const fetched = await getTxMutex(type).runExclusive(() => state.get(type, missing))
204
-
205
- // Update cache
206
- ctx.cache[type] = ctx.cache[type] || ({} as any)
207
- Object.assign(ctx.cache[type]!, fetched)
208
- }
209
-
210
- // Return requested ids from cache
211
- const result: { [key: string]: any } = {}
212
- for (const id of ids) {
213
- const value = ctx.cache[type]?.[id]
214
- if (value !== undefined && value !== null) {
215
- result[id] = value
216
- }
217
- }
218
-
219
- return result
220
- },
221
-
222
- set: async data => {
223
- const ctx = txStorage.getStore()
224
-
225
- if (!ctx) {
226
- // No transaction - direct write with queue protection
227
- const types = Object.keys(data)
228
-
229
- // Process pre-keys with validation
230
- for (const type_ of types) {
231
- const type = type_ as keyof SignalDataTypeMap
232
- if (type === 'pre-key') {
233
- await preKeyManager.validateDeletions(data, type)
234
- }
235
- }
236
-
237
- // Write all data in parallel
238
- await Promise.all(
239
- types.map(type =>
240
- getQueue(type).add(async () => {
241
- const typeData = { [type]: data[type as keyof SignalDataTypeMap] } as SignalDataSet
242
- await state.set(typeData)
243
- })
244
- )
245
- )
246
- return
247
- }
248
-
249
- // In transaction - update cache and mutations
250
- logger.trace({ types: Object.keys(data) }, 'caching in transaction')
251
-
252
- for (const key_ in data) {
253
- const key = key_ as keyof SignalDataTypeMap
254
-
255
- // Ensure structures exist
256
- ctx.cache[key] = ctx.cache[key] || ({} as any)
257
- ctx.mutations[key] = ctx.mutations[key] || ({} as any)
258
-
259
- // Special handling for pre-keys
260
- if (key === 'pre-key') {
261
- await preKeyManager.processOperations(data, key, ctx.cache, ctx.mutations, true)
262
- } else {
263
- // Normal key types
264
- Object.assign(ctx.cache[key]!, data[key])
265
- Object.assign(ctx.mutations[key]!, data[key])
266
- }
267
- }
268
- },
269
-
270
- isInTransaction,
271
-
272
- transaction: async (work, key) => {
273
- const existing = txStorage.getStore()
274
-
275
- // Nested transaction - reuse existing context
276
- if (existing) {
277
- logger.trace('reusing existing transaction context')
278
- return work()
279
- }
280
-
281
- // New transaction - acquire mutex and create context
282
- return getTxMutex(key).runExclusive(async () => {
283
- const ctx: TransactionContext = {
284
- cache: {},
285
- mutations: {},
286
- dbQueries: 0
287
- }
288
-
289
- logger.trace('entering transaction')
290
-
291
- try {
292
- const result = await txStorage.run(ctx, work)
293
-
294
- // Commit mutations
295
- await commitWithRetry(ctx.mutations)
296
-
297
- logger.trace({ dbQueries: ctx.dbQueries }, 'transaction completed')
298
-
299
- return result
300
- } catch (error) {
301
- logger.error({ error }, 'transaction failed, rolling back')
302
- throw error
303
- }
304
- })
305
- }
306
- }
307
- }
308
-
309
- export const initAuthCreds = (): AuthenticationCreds => {
310
- const identityKey = Curve.generateKeyPair()
311
- return {
312
- noiseKey: Curve.generateKeyPair(),
313
- pairingEphemeralKeyPair: Curve.generateKeyPair(),
314
- signedIdentityKey: identityKey,
315
- signedPreKey: signedKeyPair(identityKey, 1),
316
- registrationId: generateRegistrationId(),
317
- advSecretKey: randomBytes(32).toString('base64'),
318
- processedHistoryMessages: [],
319
- nextPreKeyId: 1,
320
- firstUnuploadedPreKeyId: 1,
321
- accountSyncCounter: 0,
322
- accountSettings: {
323
- unarchiveChats: false
324
- },
325
- registered: false,
326
- pairingCode: undefined,
327
- lastPropHash: undefined,
328
- routingInfo: undefined,
329
- additionalData: undefined
330
- }
331
- }
@@ -1,31 +0,0 @@
1
- import { platform, release } from 'os'
2
- import { proto } from '../../WAProto/index.js'
3
- import type { BrowsersMap } from '../Types'
4
-
5
- const PLATFORM_MAP = {
6
- aix: 'AIX',
7
- darwin: 'Mac OS',
8
- win32: 'Windows',
9
- android: 'Android',
10
- freebsd: 'FreeBSD',
11
- openbsd: 'OpenBSD',
12
- sunos: 'Solaris',
13
- linux: undefined,
14
- haiku: undefined,
15
- cygwin: undefined,
16
- netbsd: undefined
17
- }
18
-
19
- export const Browsers: BrowsersMap = {
20
- ubuntu: browser => ['Ubuntu', browser, '22.04.4'],
21
- macOS: browser => ['Mac OS', browser, '14.4.1'],
22
- baileys: browser => ['Baileys', browser, '6.5.0'],
23
- windows: browser => ['Windows', browser, '10.0.22631'],
24
- /** The appropriate browser based on your OS & release */
25
- appropriate: browser => [PLATFORM_MAP[platform()] || 'Ubuntu', browser, release()]
26
- }
27
-
28
- export const getPlatformId = (browser: string) => {
29
- const platformType = proto.DeviceProps.PlatformType[browser.toUpperCase() as any]
30
- return platformType ? platformType.toString() : '1' //chrome
31
- }