@hiroosy/baileys-lite 0.3.3 → 0.3.5

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 (242) hide show
  1. package/WAProto/index.js +247 -113252
  2. package/WAProto/parts/ADVDeviceIdentity.part +201 -0
  3. package/WAProto/parts/ADVEncryptionType.part +6 -0
  4. package/WAProto/parts/ADVKeyIndexList.part +201 -0
  5. package/WAProto/parts/ADVSignedDeviceIdentity.part +150 -0
  6. package/WAProto/parts/ADVSignedDeviceIdentityHMAC.part +142 -0
  7. package/WAProto/parts/ADVSignedKeyIndexList.part +128 -0
  8. package/WAProto/parts/AIHomeState.part +405 -0
  9. package/WAProto/parts/AIMediaCollectionMessage.part +119 -0
  10. package/WAProto/parts/AIMediaCollectionMetadata.part +100 -0
  11. package/WAProto/parts/AIMetadataOperation.part +83 -0
  12. package/WAProto/parts/AIQueryFanout.part +133 -0
  13. package/WAProto/parts/AIRegenerateMetadata.part +112 -0
  14. package/WAProto/parts/AIRichResponseCodeMetadata.part +252 -0
  15. package/WAProto/parts/AIRichResponseContentItemsMetadata.part +354 -0
  16. package/WAProto/parts/AIRichResponseDynamicMetadata.part +172 -0
  17. package/WAProto/parts/AIRichResponseGridImageMetadata.part +114 -0
  18. package/WAProto/parts/AIRichResponseImageURL.part +119 -0
  19. package/WAProto/parts/AIRichResponseInlineImageMetadata.part +164 -0
  20. package/WAProto/parts/AIRichResponseLatexMetadata.part +346 -0
  21. package/WAProto/parts/AIRichResponseMapMetadata.part +346 -0
  22. package/WAProto/parts/AIRichResponseMessage.part +167 -0
  23. package/WAProto/parts/AIRichResponseMessageType.part +5 -0
  24. package/WAProto/parts/AIRichResponseSubMessage.part +313 -0
  25. package/WAProto/parts/AIRichResponseSubMessageType.part +13 -0
  26. package/WAProto/parts/AIRichResponseTableMetadata.part +223 -0
  27. package/WAProto/parts/AIRichResponseUnifiedResponse.part +84 -0
  28. package/WAProto/parts/AISubscriptionRequestType.part +7 -0
  29. package/WAProto/parts/AISubscriptionUpsellMetadata.part +102 -0
  30. package/WAProto/parts/AIThreadInfo.part +316 -0
  31. package/WAProto/parts/Account.part +138 -0
  32. package/WAProto/parts/ActionLink.part +100 -0
  33. package/WAProto/parts/AutoDownloadSettings.part +138 -0
  34. package/WAProto/parts/AvatarUserSettings.part +100 -0
  35. package/WAProto/parts/BizAccountLinkInfo.part +210 -0
  36. package/WAProto/parts/BizAccountPayload.part +105 -0
  37. package/WAProto/parts/BizIdentityInfo.part +298 -0
  38. package/WAProto/parts/BotAgeCollectionMetadata.part +138 -0
  39. package/WAProto/parts/BotAgentDeepLinkMetadata.part +81 -0
  40. package/WAProto/parts/BotAgentMetadata.part +83 -0
  41. package/WAProto/parts/BotCapabilityMetadata.part +437 -0
  42. package/WAProto/parts/BotCommandMetadata.part +119 -0
  43. package/WAProto/parts/BotDocumentMessageMetadata.part +100 -0
  44. package/WAProto/parts/BotFeedbackMessage.part +1366 -0
  45. package/WAProto/parts/BotGroupMetadata.part +92 -0
  46. package/WAProto/parts/BotGroupParticipantMetadata.part +81 -0
  47. package/WAProto/parts/BotImagineMetadata.part +134 -0
  48. package/WAProto/parts/BotInfrastructureDiagnostics.part +148 -0
  49. package/WAProto/parts/BotLinkedAccount.part +95 -0
  50. package/WAProto/parts/BotLinkedAccountsMetadata.part +134 -0
  51. package/WAProto/parts/BotMediaMetadata.part +229 -0
  52. package/WAProto/parts/BotMemoryFact.part +100 -0
  53. package/WAProto/parts/BotMemoryMetadata.part +141 -0
  54. package/WAProto/parts/BotMemuMetadata.part +92 -0
  55. package/WAProto/parts/BotMessageOrigin.part +95 -0
  56. package/WAProto/parts/BotMessageOriginMetadata.part +92 -0
  57. package/WAProto/parts/BotMessageSharingInfo.part +297 -0
  58. package/WAProto/parts/BotMetadata.part +934 -0
  59. package/WAProto/parts/BotMetricsEntryPoint.part +51 -0
  60. package/WAProto/parts/BotMetricsMetadata.part +341 -0
  61. package/WAProto/parts/BotMetricsThreadEntryPoint.part +8 -0
  62. package/WAProto/parts/BotModeSelectionMetadata.part +151 -0
  63. package/WAProto/parts/BotModelMetadata.part +167 -0
  64. package/WAProto/parts/BotPluginMetadata.part +379 -0
  65. package/WAProto/parts/BotProgressIndicatorMetadata.part +837 -0
  66. package/WAProto/parts/BotPromotionMessageMetadata.part +124 -0
  67. package/WAProto/parts/BotPromptSuggestion.part +100 -0
  68. package/WAProto/parts/BotPromptSuggestions.part +92 -0
  69. package/WAProto/parts/BotPttPromptMetadata.part +81 -0
  70. package/WAProto/parts/BotQuotaMetadata.part +241 -0
  71. package/WAProto/parts/BotReminderMetadata.part +232 -0
  72. package/WAProto/parts/BotRenderingConfigMetadata.part +100 -0
  73. package/WAProto/parts/BotRenderingMetadata.part +203 -0
  74. package/WAProto/parts/BotResolvedToolCallMetadata.part +100 -0
  75. package/WAProto/parts/BotSessionMetadata.part +137 -0
  76. package/WAProto/parts/BotSessionSource.part +11 -0
  77. package/WAProto/parts/BotSignatureVerificationMetadata.part +92 -0
  78. package/WAProto/parts/BotSignatureVerificationUseCaseProof.part +183 -0
  79. package/WAProto/parts/BotSourcesMetadata.part +322 -0
  80. package/WAProto/parts/BotSuggestedPromptMetadata.part +150 -0
  81. package/WAProto/parts/BotUnifiedResponseMutation.part +339 -0
  82. package/WAProto/parts/CallLogRecord.part +646 -0
  83. package/WAProto/parts/CertChain.part +392 -0
  84. package/WAProto/parts/ChatLockSettings.part +102 -0
  85. package/WAProto/parts/ChatRowOpaqueData.part +712 -0
  86. package/WAProto/parts/Citation.part +119 -0
  87. package/WAProto/parts/ClientPairingProps.part +160 -0
  88. package/WAProto/parts/ClientPayload.part +2892 -0
  89. package/WAProto/parts/CollectionName.part +9 -0
  90. package/WAProto/parts/CommentMetadata.part +102 -0
  91. package/WAProto/parts/CompanionCommitment.part +84 -0
  92. package/WAProto/parts/CompanionEphemeralIdentity.part +227 -0
  93. package/WAProto/parts/Config.part +136 -0
  94. package/WAProto/parts/ContextInfo.part +4137 -0
  95. package/WAProto/parts/Conversation.part +1472 -0
  96. package/WAProto/parts/DeviceCapabilities.part +670 -0
  97. package/WAProto/parts/DeviceConsistencyCodeMessage.part +103 -0
  98. package/WAProto/parts/DeviceListMetadata.part +306 -0
  99. package/WAProto/parts/DeviceProps.part +982 -0
  100. package/WAProto/parts/DisappearingMode.part +206 -0
  101. package/WAProto/parts/EmbeddedContent.part +100 -0
  102. package/WAProto/parts/EmbeddedMessage.part +102 -0
  103. package/WAProto/parts/EmbeddedMusic.part +370 -0
  104. package/WAProto/parts/EncryptedPairingRequest.part +106 -0
  105. package/WAProto/parts/EphemeralSetting.part +110 -0
  106. package/WAProto/parts/EventAdditionalMetadata.part +81 -0
  107. package/WAProto/parts/EventResponse.part +152 -0
  108. package/WAProto/parts/ExitCode.part +110 -0
  109. package/WAProto/parts/ExternalBlobReference.part +195 -0
  110. package/WAProto/parts/Field.part +193 -0
  111. package/WAProto/parts/ForwardedAIBotMessageInfo.part +119 -0
  112. package/WAProto/parts/GlobalSettings.part +497 -0
  113. package/WAProto/parts/GroupHistoryBundleInfo.part +141 -0
  114. package/WAProto/parts/GroupHistoryIndividualMessageInfo.part +102 -0
  115. package/WAProto/parts/GroupMention.part +100 -0
  116. package/WAProto/parts/GroupParticipant.part +142 -0
  117. package/WAProto/parts/GroupRootKeyShare.part +92 -0
  118. package/WAProto/parts/GroupRootKeyShareEntry.part +161 -0
  119. package/WAProto/parts/HandshakeMessage.part +815 -0
  120. package/WAProto/parts/HatchMetadataSync.part +132 -0
  121. package/WAProto/parts/HistorySync.part +605 -0
  122. package/WAProto/parts/HistorySyncMsg.part +112 -0
  123. package/WAProto/parts/HydratedTemplateButton.part +501 -0
  124. package/WAProto/parts/IdentityKeyPairStructure.part +106 -0
  125. package/WAProto/parts/InThreadSurveyMetadata.part +779 -0
  126. package/WAProto/parts/InlineContact.part +157 -0
  127. package/WAProto/parts/InteractiveAnnotation.part +246 -0
  128. package/WAProto/parts/InteractiveMessageAdditionalMetadata.part +81 -0
  129. package/WAProto/parts/KeepInChat.part +225 -0
  130. package/WAProto/parts/KeepType.part +6 -0
  131. package/WAProto/parts/KeyExchangeMessage.part +169 -0
  132. package/WAProto/parts/KeyId.part +84 -0
  133. package/WAProto/parts/LIDMigrationMapping.part +149 -0
  134. package/WAProto/parts/LIDMigrationMappingSyncMessage.part +84 -0
  135. package/WAProto/parts/LIDMigrationMappingSyncPayload.part +122 -0
  136. package/WAProto/parts/LegacyMessage.part +104 -0
  137. package/WAProto/parts/LimitSharing.part +177 -0
  138. package/WAProto/parts/LocalizedName.part +119 -0
  139. package/WAProto/parts/Location.part +119 -0
  140. package/WAProto/parts/MediaData.part +81 -0
  141. package/WAProto/parts/MediaDomainInfo.part +120 -0
  142. package/WAProto/parts/MediaKeyDomain.part +6 -0
  143. package/WAProto/parts/MediaNotifyMessage.part +132 -0
  144. package/WAProto/parts/MediaRetryNotification.part +170 -0
  145. package/WAProto/parts/MediaVisibility.part +6 -0
  146. package/WAProto/parts/MemberLabel.part +110 -0
  147. package/WAProto/parts/Message.part +32376 -0
  148. package/WAProto/parts/MessageAddOn.part +305 -0
  149. package/WAProto/parts/MessageAddOnContextInfo.part +113 -0
  150. package/WAProto/parts/MessageAssociation.part +235 -0
  151. package/WAProto/parts/MessageContextInfo.part +451 -0
  152. package/WAProto/parts/MessageKey.part +138 -0
  153. package/WAProto/parts/MessageSecretMessage.part +125 -0
  154. package/WAProto/parts/Money.part +129 -0
  155. package/WAProto/parts/MsgOpaqueData.part +1732 -0
  156. package/WAProto/parts/MsgRowOpaqueData.part +104 -0
  157. package/WAProto/parts/MutationProps.part +89 -0
  158. package/WAProto/parts/NoiseCertificate.part +277 -0
  159. package/WAProto/parts/NotificationMessageInfo.part +152 -0
  160. package/WAProto/parts/NotificationSettings.part +176 -0
  161. package/WAProto/parts/PairingRequest.part +128 -0
  162. package/WAProto/parts/PastParticipant.part +148 -0
  163. package/WAProto/parts/PastParticipants.part +112 -0
  164. package/WAProto/parts/PatchDebugData.part +358 -0
  165. package/WAProto/parts/PaymentBackground.part +460 -0
  166. package/WAProto/parts/PaymentInfo.part +602 -0
  167. package/WAProto/parts/PhoneNumberToLIDMapping.part +100 -0
  168. package/WAProto/parts/PhotoChange.part +125 -0
  169. package/WAProto/parts/PinInChat.part +205 -0
  170. package/WAProto/parts/Point.part +138 -0
  171. package/WAProto/parts/PollAdditionalMetadata.part +216 -0
  172. package/WAProto/parts/PollEncValue.part +106 -0
  173. package/WAProto/parts/PollUpdate.part +202 -0
  174. package/WAProto/parts/PreKeyRecordStructure.part +125 -0
  175. package/WAProto/parts/PreKeySignalMessage.part +185 -0
  176. package/WAProto/parts/PremiumMessageInfo.part +81 -0
  177. package/WAProto/parts/PrimaryEphemeralIdentity.part +106 -0
  178. package/WAProto/parts/PrivacySystemMessage.part +6 -0
  179. package/WAProto/parts/ProcessedVideo.part +266 -0
  180. package/WAProto/parts/ProloguePayload.part +105 -0
  181. package/WAProto/parts/Pushname.part +100 -0
  182. package/WAProto/parts/QuarantinedMessage.part +103 -0
  183. package/WAProto/parts/Reaction.part +169 -0
  184. package/WAProto/parts/RecentEmojiWeight.part +100 -0
  185. package/WAProto/parts/RecordStructure.part +114 -0
  186. package/WAProto/parts/Reportable.part +138 -0
  187. package/WAProto/parts/ReportingTokenInfo.part +84 -0
  188. package/WAProto/parts/ScheduledMessageMetadata.part +132 -0
  189. package/WAProto/parts/SenderKeyDistributionMessage.part +144 -0
  190. package/WAProto/parts/SenderKeyMessage.part +122 -0
  191. package/WAProto/parts/SenderKeyRecordStructure.part +92 -0
  192. package/WAProto/parts/SenderKeyStateStructure.part +469 -0
  193. package/WAProto/parts/ServerErrorReceipt.part +81 -0
  194. package/WAProto/parts/SessionStructure.part +1087 -0
  195. package/WAProto/parts/SessionTransparencyMetadata.part +132 -0
  196. package/WAProto/parts/SessionTransparencyType.part +5 -0
  197. package/WAProto/parts/SignalMessage.part +144 -0
  198. package/WAProto/parts/SignedPreKeyRecordStructure.part +176 -0
  199. package/WAProto/parts/StatusAttribution.part +1235 -0
  200. package/WAProto/parts/StatusMentionMessage.part +83 -0
  201. package/WAProto/parts/StatusPSA.part +121 -0
  202. package/WAProto/parts/StickerMetadata.part +357 -0
  203. package/WAProto/parts/SyncActionData.part +146 -0
  204. package/WAProto/parts/SyncActionValue.part +12959 -0
  205. package/WAProto/parts/SyncdIndex.part +84 -0
  206. package/WAProto/parts/SyncdMutation.part +121 -0
  207. package/WAProto/parts/SyncdMutations.part +92 -0
  208. package/WAProto/parts/SyncdPatch.part +262 -0
  209. package/WAProto/parts/SyncdRecord.part +125 -0
  210. package/WAProto/parts/SyncdSnapshot.part +157 -0
  211. package/WAProto/parts/SyncdValue.part +84 -0
  212. package/WAProto/parts/SyncdVersion.part +91 -0
  213. package/WAProto/parts/TapLinkAction.part +100 -0
  214. package/WAProto/parts/TemplateButton.part +449 -0
  215. package/WAProto/parts/ThreadID.part +126 -0
  216. package/WAProto/parts/UrlTrackingMap.part +231 -0
  217. package/WAProto/parts/UserPassword.part +399 -0
  218. package/WAProto/parts/UserReceipt.part +221 -0
  219. package/WAProto/parts/VerifiedNameCertificate.part +318 -0
  220. package/WAProto/parts/WallpaperSettings.part +119 -0
  221. package/WAProto/parts/WebFeatures.part +1870 -0
  222. package/WAProto/parts/WebLinkRenderConfig.part +5 -0
  223. package/WAProto/parts/WebMessageInfo.part +2851 -0
  224. package/WAProto/parts/WebNotificationsInfo.part +160 -0
  225. package/package.json +1 -1
  226. package/src/binary/wa-binary.js +4 -2
  227. package/src/defaults.js +2 -1
  228. package/src/foundation/cache.js +99 -24
  229. package/src/foundation/memory.js +103 -0
  230. package/src/signal/libsignal.js +1 -8
  231. package/src/signal/signal-repository.js +6 -4
  232. package/src/socket/chats.js +2 -0
  233. package/src/socket/messages-recv.js +5 -3
  234. package/src/socket/messages-send.js +2 -2
  235. package/src/socket/socket-core.js +3 -0
  236. package/src/utils/auth-state-core.js +2 -1
  237. package/src/utils/chat-sync.js +4 -0
  238. package/src/utils/media.js +13 -8
  239. package/src/utils/message-processing.js +22 -6
  240. package/src/utils/wa-protocol-core.js +6 -5
  241. package/src/wam/wam-constants.js +22 -22851
  242. package/src/wam/wam-data.json +1 -0
@@ -8,6 +8,7 @@ import { aesDecrypt, aesEncrypt, hmacSign, toNumber, trimUndefined, LT_HASH_ANTI
8
8
  import { downloadContentFromMessage } from './media.js'
9
9
  import { updateMessageWithReaction, updateMessageWithReceipt } from './message-compose.js'
10
10
  import { isRealMessage, shouldIncrementChatUnread } from './message-processing.js'
11
+ import { requestTrim } from '../foundation/memory.js'
11
12
 
12
13
  const mutationKeys = keydata => {
13
14
  const keys = expandAppStateKeys(keydata)
@@ -897,6 +898,7 @@ export const makeEventBuffer = logger => {
897
898
  let flushPendingTimeout = null
898
899
  let bufferCount = 0
899
900
  const MAX_HISTORY_CACHE_SIZE = 10000
901
+ const HEAVY_FLUSH_MESSAGES = 200
900
902
  const BUFFER_TIMEOUT_MS = 30000
901
903
 
902
904
  ev.on('event', map => {
@@ -947,7 +949,9 @@ export const makeEventBuffer = logger => {
947
949
  }
948
950
  }
949
951
  const consolidatedData = consolidateEvents(data)
952
+ const heavy = !!consolidatedData['messaging-history.set'] || (consolidatedData['messages.upsert']?.messages.length ?? 0) > HEAVY_FLUSH_MESSAGES
950
953
  if (Object.keys(consolidatedData).length) ev.emit('event', consolidatedData)
954
+ if (heavy) requestTrim(3000)
951
955
  data = newData
952
956
  logger.trace({ conditionalChatUpdatesLeft }, 'released buffered events')
953
957
  return true
@@ -85,7 +85,13 @@ export const getImageProcessingLibrary = async () => {
85
85
  import('@napi-rs/image').catch(() => {}),
86
86
  import('jimp').catch(() => {})
87
87
  ])
88
- if (sharp) imageProcessingLibrary = { sharp }
88
+ if (sharp) {
89
+ try {
90
+ sharp.default.cache(false)
91
+ sharp.default.concurrency(1)
92
+ } catch {}
93
+ imageProcessingLibrary = { sharp }
94
+ }
89
95
  else if (image) imageProcessingLibrary = { image }
90
96
  else if (jimp) imageProcessingLibrary = { jimp }
91
97
  else {
@@ -167,15 +173,13 @@ export const extractVideoThumb = async (path, time, size) => {
167
173
  ],
168
174
  { stdio: ['ignore', 'pipe', 'pipe'] }
169
175
  )
170
- let buffer = Buffer.alloc(0)
176
+ const stdoutChunks = []
171
177
  const stderrChunks = []
172
- ffmpeg.stdout.on('data', chunk => {
173
- buffer = Buffer.concat([buffer, chunk])
174
- })
178
+ ffmpeg.stdout.on('data', chunk => stdoutChunks.push(chunk))
175
179
  ffmpeg.stderr.on('data', chunk => stderrChunks.push(chunk))
176
180
  const [code] = await once(ffmpeg, 'close')
177
181
  if (code !== 0) throw new Boom(`FFmpeg failed (code ${code}):\n` + Buffer.concat(stderrChunks).toString('utf8'))
178
- return buffer
182
+ return Buffer.concat(stdoutChunks)
179
183
  }
180
184
 
181
185
  const thumbWithLibrary = async (lib, bufferOrFilePath, width) => {
@@ -574,9 +578,10 @@ export const uploadWithNodeHttp = async ({ url, filePath, headers, timeoutMs, ag
574
578
  resolve(uploadWithNodeHttp({ url: newUrl, filePath, headers, timeoutMs, agent }, redirectCount + 1))
575
579
  return
576
580
  }
577
- let body = ''
578
- res.on('data', chunk => (body += chunk))
581
+ const bodyChunks = []
582
+ res.on('data', chunk => bodyChunks.push(chunk))
579
583
  res.on('end', () => {
584
+ const body = Buffer.concat(bodyChunks).toString('utf8')
580
585
  try {
581
586
  resolve(JSON.parse(body))
582
587
  } catch {
@@ -28,8 +28,10 @@ import { aesDecryptGCM, hmacSign, getKeyAuthor, toNumber, generateMessageIDV2 }
28
28
  import { getContentType, normalizeMessageContent } from './message-compose.js'
29
29
  import { downloadContentFromMessage, getStream, getUrlFromDirectPath } from './media.js'
30
30
  import { buildMergedTcTokenIndexWrite, resolveTcTokenJid } from './auth-state-core.js'
31
+ import { requestTrim } from '../foundation/memory.js'
31
32
 
32
33
  const inflatePromise = promisify(inflate)
34
+ const MAX_PROCESSED_HISTORY_MESSAGES = 64
33
35
 
34
36
  const REAL_MSG_STUB_TYPES = new Set([
35
37
  WAMessageStubType.CALL_MISSED_GROUP_VIDEO,
@@ -207,7 +209,7 @@ const processMessage = async (message, { shouldProcessHistoryMsg, placeholderRes
207
209
  if (process) {
208
210
  if (histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND) {
209
211
  ev.emit('creds.update', {
210
- processedHistoryMessages: [...(creds.processedHistoryMessages || []), { key: message.key, messageTimestamp: message.messageTimestamp }]
212
+ processedHistoryMessages: [...(creds.processedHistoryMessages || []), { key: message.key, messageTimestamp: message.messageTimestamp }].slice(-MAX_PROCESSED_HISTORY_MESSAGES)
211
213
  })
212
214
  }
213
215
  const data = await downloadAndProcessHistorySyncNotification(histNotification, options, logger)
@@ -222,6 +224,7 @@ const processMessage = async (message, { shouldProcessHistoryMsg, placeholderRes
222
224
  chunkOrder: histNotification.chunkOrder,
223
225
  peerDataRequestSessionId: histNotification.peerDataRequestSessionId
224
226
  })
227
+ requestTrim(4000)
225
228
  }
226
229
  break
227
230
  }
@@ -480,7 +483,8 @@ const processMessage = async (message, { shouldProcessHistoryMsg, placeholderRes
480
483
 
481
484
  export default processMessage
482
485
 
483
- const RECENT_MESSAGES_SIZE = 1024
486
+ const RECENT_MESSAGES_SIZE = 512
487
+ const RECENT_MESSAGES_BYTES = 4 * 1024 * 1024
484
488
  const MESSAGE_KEY_SEPARATOR = '\u0000'
485
489
  const RECREATE_SESSION_TIMEOUT = 60 * 60 * 1000
486
490
  const PHONE_REQUEST_DELAY = 3000
@@ -511,6 +515,7 @@ export class MessageRetryManager {
511
515
  this.logger = logger
512
516
  this.recentMessagesMap = new Cache({
513
517
  max: RECENT_MESSAGES_SIZE,
518
+ maxBytes: RECENT_MESSAGES_BYTES,
514
519
  ttl: 5 * 60 * 1000,
515
520
  dispose: (_value, key) => {
516
521
  const separatorIndex = key.lastIndexOf(MESSAGE_KEY_SEPARATOR)
@@ -519,9 +524,9 @@ export class MessageRetryManager {
519
524
  })
520
525
  this.messageKeyIndex = new Map()
521
526
 
522
- this.sessionRecreateHistory = new Cache({ max: 4096, ttl: RECREATE_SESSION_TIMEOUT * 2 })
523
- this.retryCounters = new Cache({ max: 4096, ttl: 15 * 60 * 1000, updateAgeOnGet: true })
524
- this.baseKeys = new Cache({ max: 1024, ttl: 15 * 60 * 1000 })
527
+ this.sessionRecreateHistory = new Cache({ max: 2048, ttl: RECREATE_SESSION_TIMEOUT * 2 })
528
+ this.retryCounters = new Cache({ max: 2048, ttl: 15 * 60 * 1000, updateAgeOnGet: true })
529
+ this.baseKeys = new Cache({ max: 512, ttl: 15 * 60 * 1000 })
525
530
  this.pendingPhoneRequests = {}
526
531
  this.maxMsgRetryCount = maxMsgRetryCount
527
532
  this.statistics = { totalRetries: 0, successfulRetries: 0, failedRetries: 0, mediaRetries: 0, sessionRecreations: 0, phoneRequests: 0 }
@@ -646,6 +651,15 @@ export class MessageRetryManager {
646
651
  this.statistics = { totalRetries: 0, successfulRetries: 0, failedRetries: 0, mediaRetries: 0, sessionRecreations: 0, phoneRequests: 0 }
647
652
  }
648
653
 
654
+ close() {
655
+ this.clear()
656
+ this.recentMessagesMap.close()
657
+ this.sessionRecreateHistory.close()
658
+ this.retryCounters.close()
659
+ this.baseKeys.close()
660
+ this.invalidatedMessages.close()
661
+ }
662
+
649
663
  saveBaseKey(addr, msgId, baseKey) {
650
664
  this.baseKeys.set(`${addr}:${msgId}`, baseKey)
651
665
  }
@@ -719,7 +733,9 @@ export const downloadHistory = async (msg, options) => {
719
733
  const chunks = []
720
734
  inflater.on('data', chunk => chunks.push(chunk))
721
735
  await pipeline(stream, inflater)
722
- return proto.HistorySync.decode(Buffer.concat(chunks))
736
+ const inflated = Buffer.concat(chunks)
737
+ chunks.length = 0
738
+ return proto.HistorySync.decode(inflated)
723
739
  }
724
740
 
725
741
  export const processHistoryMessage = (item, logger) => {
@@ -717,7 +717,8 @@ export const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publi
717
717
  let decKey = hash
718
718
  let counter = 0
719
719
  let sentIntro = false
720
- let inBytes = Buffer.alloc(0)
720
+ const EMPTY_BYTES = Buffer.alloc(0)
721
+ let inBytes = EMPTY_BYTES
721
722
  let transport = null
722
723
  let isWaitingForTransport = false
723
724
  let pendingOnFrame = null
@@ -785,7 +786,7 @@ export const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publi
785
786
  size = (inBytes[0] << 16) | (inBytes[1] << 8) | inBytes[2]
786
787
  if (inBytes.length < size + 3) return
787
788
  let frame = inBytes.subarray(3, size + 3)
788
- inBytes = inBytes.subarray(size + 3)
789
+ inBytes = inBytes.length === size + 3 ? EMPTY_BYTES : inBytes.subarray(size + 3)
789
790
  if (transport) {
790
791
  const result = transport.decrypt(frame) // gagal decrypt = counter tidak sinkron lagi -> biarkan melempar (fatal)
791
792
  try {
@@ -863,11 +864,11 @@ export const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publi
863
864
  inBytes = Buffer.concat([inBytes, newData])
864
865
  pendingOnFrame = onFrame
865
866
  } else {
866
- inBytes = inBytes.length === 0 ? Buffer.from(newData) : Buffer.concat([inBytes, newData])
867
+ inBytes = inBytes.length === 0 ? newData : Buffer.concat([inBytes, newData])
867
868
  }
868
869
  if (inBytes.length > MAX_IN_BYTES) {
869
870
  logger.error({ bufferedBytes: inBytes.length, max: MAX_IN_BYTES }, 'noise handler inBytes buffer exceeded cap, clearing')
870
- inBytes = Buffer.alloc(0)
871
+ inBytes = EMPTY_BYTES
871
872
  pendingOnFrame = null
872
873
  return
873
874
  }
@@ -882,7 +883,7 @@ export const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publi
882
883
 
883
884
  destroy: () => {
884
885
  destroyed = true
885
- inBytes = Buffer.alloc(0)
886
+ inBytes = EMPTY_BYTES
886
887
  pendingOnFrame = null
887
888
  transport = null
888
889
  }