@hiroosy/baileys-lite 0.0.3 → 0.3.0

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 (116) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +660 -12
  3. package/WAProto/index.js +2 -2558
  4. package/engine-requirements.js +3 -4
  5. package/package.json +8 -3
  6. package/src/binary/wa-binary.js +3 -25
  7. package/src/constants.js +7 -15
  8. package/src/defaults.js +2 -5
  9. package/src/foundation/ai-rich.js +530 -0
  10. package/src/foundation/audio-duration.js +43 -103
  11. package/src/foundation/audio-samples.js +19 -37
  12. package/src/foundation/boom.js +0 -7
  13. package/src/foundation/cache.js +4 -26
  14. package/src/foundation/concurrency.js +1 -19
  15. package/src/foundation/curve25519.js +7 -39
  16. package/src/foundation/link-preview.js +15 -57
  17. package/src/foundation/logger.js +0 -11
  18. package/src/foundation/long.js +4 -14
  19. package/src/foundation/protobuf-minimal.js +21 -53
  20. package/src/foundation/qrcode-terminal.js +273 -0
  21. package/src/foundation/sql-database.js +702 -0
  22. package/src/foundation/wa-crypto.js +2 -31
  23. package/src/foundation/zip.js +25 -41
  24. package/src/index.js +8 -18
  25. package/src/signal/libsignal.js +23 -78
  26. package/src/signal/signal-group.js +0 -35
  27. package/src/signal/signal-repository.js +10 -29
  28. package/src/socket/business-communities.js +12 -31
  29. package/src/socket/chats.js +5 -8
  30. package/src/socket/groups-newsletter.js +18 -17
  31. package/src/socket/messages-recv.js +81 -127
  32. package/src/socket/messages-send.js +372 -139
  33. package/src/socket/socket-core.js +227 -157
  34. package/src/socket/usync.js +2 -6
  35. package/src/socket-client/native-websocket.js +344 -0
  36. package/src/socket-client/websocket-client.js +84 -38
  37. package/src/utils/auth-state-core.js +14 -56
  38. package/src/utils/auth-state-storage.js +7 -42
  39. package/src/utils/chat-sync.js +4 -26
  40. package/src/utils/media.js +15 -71
  41. package/src/utils/message-compose.js +208 -85
  42. package/src/utils/message-processing.js +10 -65
  43. package/src/utils/username.js +19 -0
  44. package/src/utils/wa-protocol-core.js +71 -127
  45. package/src/vendor/jpeg-js/decoder.js +75 -136
  46. package/src/vendor/jpeg-js/encoder.js +179 -264
  47. package/src/vendor/pngjs/bitmapper.js +5 -27
  48. package/src/vendor/pngjs/bitpacker.js +4 -12
  49. package/src/vendor/pngjs/constants.js +3 -11
  50. package/src/vendor/pngjs/crc.js +0 -6
  51. package/src/vendor/pngjs/filter-pack.js +1 -7
  52. package/src/vendor/pngjs/filter-parse-sync.js +0 -6
  53. package/src/vendor/pngjs/filter-parse.js +1 -11
  54. package/src/vendor/pngjs/format-normaliser.js +5 -11
  55. package/src/vendor/pngjs/interlace.js +7 -24
  56. package/src/vendor/pngjs/packer-sync.js +0 -11
  57. package/src/vendor/pngjs/packer.js +7 -15
  58. package/src/vendor/pngjs/paeth-predictor.js +0 -6
  59. package/src/vendor/pngjs/parser-sync.js +0 -8
  60. package/src/vendor/pngjs/parser.js +5 -29
  61. package/src/vendor/pngjs/png-sync.js +0 -7
  62. package/src/vendor/pngjs/sync-inflate.js +7 -16
  63. package/src/vendor/pngjs/sync-reader.js +4 -11
  64. package/src/voip/WaVoipCoordinator.js +158 -0
  65. package/src/voip/app-data/WaAppDataStream.js +193 -0
  66. package/src/voip/app-data/protocol.js +172 -0
  67. package/src/voip/bytes.js +63 -0
  68. package/src/voip/call/WaCallManager.js +442 -0
  69. package/src/voip/call/WaCallMediaSession.js +1705 -0
  70. package/src/voip/call/call-state.js +203 -0
  71. package/src/voip/crypto/encryption.js +13 -0
  72. package/src/voip/crypto/primitives.js +21 -0
  73. package/src/voip/crypto/rtcp.js +66 -0
  74. package/src/voip/crypto/srtp.js +180 -0
  75. package/src/voip/crypto/ssrc.js +15 -0
  76. package/src/voip/index.js +628 -0
  77. package/src/voip/media/WaAudioEngine.js +486 -0
  78. package/src/voip/media/WaVideoEngine.js +275 -0
  79. package/src/voip/media/audio-codec.js +0 -0
  80. package/src/voip/media/audio-reorder.js +107 -0
  81. package/src/voip/media/h264.js +246 -0
  82. package/src/voip/media/mlow-codec.js +465 -0
  83. package/src/voip/media/rtcp.js +68 -0
  84. package/src/voip/media/rtp.js +242 -0
  85. package/src/voip/protobuf.js +30 -0
  86. package/src/voip/relay/WaManualRelay.js +609 -0
  87. package/src/voip/relay/datachannel/pre-negotiated.js +25 -0
  88. package/src/voip/relay/dtls/aead.js +46 -0
  89. package/src/voip/relay/dtls/cert-builder.js +102 -0
  90. package/src/voip/relay/dtls/der.js +98 -0
  91. package/src/voip/relay/dtls/ecdhe.js +37 -0
  92. package/src/voip/relay/dtls/handshake-framing.js +100 -0
  93. package/src/voip/relay/dtls/handshake-messages.js +158 -0
  94. package/src/voip/relay/dtls/handshake.js +582 -0
  95. package/src/voip/relay/dtls/prf.js +39 -0
  96. package/src/voip/relay/dtls/record.js +56 -0
  97. package/src/voip/relay/relay-ack.js +141 -0
  98. package/src/voip/relay/sctp/association.js +434 -0
  99. package/src/voip/relay/sctp/crc32c.js +21 -0
  100. package/src/voip/relay/sctp/wire.js +226 -0
  101. package/src/voip/relay/stun.js +463 -0
  102. package/src/voip/shim/baileys-resolve.js +7 -0
  103. package/src/voip/shim/core.js +66 -0
  104. package/src/voip/shim/crypto.js +6 -0
  105. package/src/voip/shim/proto.js +10 -0
  106. package/src/voip/shim/protocol.js +130 -0
  107. package/src/voip/shim/transport.js +82 -0
  108. package/src/voip/shim/util.js +207 -0
  109. package/src/voip/signaling/bridge.js +102 -0
  110. package/src/voip/signaling/screen-share.js +60 -0
  111. package/src/voip/signaling/signaling.js +491 -0
  112. package/src/voip/types.js +69 -0
  113. package/src/voip/voip-deps.js +243 -0
  114. package/src/voip/voipClient.js +314 -0
  115. package/src/wam/wam-constants.js +0 -1
  116. package/src/wam/wam.js +2 -7
@@ -1,7 +1,3 @@
1
- /**
2
- * Message processing pipeline. Combines what used to be process-message.js,
3
- * message-retry-manager.js, offline-node-processor.js, history.js, and business.js.
4
- */
5
1
  import { createHash } from 'node:crypto'
6
2
  import { createWriteStream, promises as fs } from 'node:fs'
7
3
  import { tmpdir } from 'node:os'
@@ -35,10 +31,6 @@ import { buildMergedTcTokenIndexWrite, resolveTcTokenJid } from './auth-state-co
35
31
 
36
32
  const inflatePromise = promisify(inflate)
37
33
 
38
- /* ------------------------------------------------------------------ */
39
- /* Incoming-message cleanup / classification */
40
- /* ------------------------------------------------------------------ */
41
-
42
34
  const REAL_MSG_STUB_TYPES = new Set([
43
35
  WAMessageStubType.CALL_MISSED_GROUP_VIDEO,
44
36
  WAMessageStubType.CALL_MISSED_GROUP_VOICE,
@@ -79,7 +71,6 @@ async function storeTcTokensFromHistorySync(chats, signalRepository, keyStore, l
79
71
  }
80
72
  }
81
73
 
82
- /** Cleans a received message to further processing */
83
74
  export const cleanMessage = (message, meId, meLid) => {
84
75
  if (isHostedPnUser(message.key.remoteJid) || isHostedLidUser(message.key.remoteJid)) {
85
76
  message.key.remoteJid = jidEncode(jidDecode(message.key?.remoteJid)?.user, isHostedPnUser(message.key.remoteJid) ? 's.whatsapp.net' : 'lid')
@@ -120,7 +111,6 @@ export const isRealMessage = message => {
120
111
 
121
112
  export const shouldIncrementChatUnread = message => !message.key.fromMe && !message.messageStubType
122
113
 
123
- /** Get the ID of the chat from the given key. Typically the remoteJid, but for broadcasts, the participant. */
124
114
  export const getChatId = ({ remoteJid, participant, fromMe }) => {
125
115
  if (!remoteJid) throw new Boom('Cannot derive chat id: message key is missing remoteJid', { data: { remoteJid, participant, fromMe } })
126
116
  if (isJidBroadcast(remoteJid) && !isJidStatusBroadcast(remoteJid) && !fromMe) {
@@ -130,10 +120,6 @@ export const getChatId = ({ remoteJid, participant, fromMe }) => {
130
120
  return remoteJid
131
121
  }
132
122
 
133
- /* ------------------------------------------------------------------ */
134
- /* Encrypted-payload decryption (poll votes, event responses, edits) */
135
- /* ------------------------------------------------------------------ */
136
-
137
123
  export function decryptPollVote({ encPayload, encIv }, { pollCreatorJid, pollMsgId, pollEncKey, voterJid }) {
138
124
  const toBinary = txt => Buffer.from(txt)
139
125
  const sign = Buffer.concat([toBinary(pollMsgId), toBinary(pollCreatorJid), toBinary(voterJid), toBinary('Poll Vote'), new Uint8Array([1])])
@@ -154,17 +140,12 @@ export function decryptEventResponse({ encPayload, encIv }, { eventCreatorJid, e
154
140
  return proto.Message.EventResponseMessage.decode(decrypted)
155
141
  }
156
142
 
157
- /**
158
- * Decrypt a `secretEncryptedMessage` carrying a `MESSAGE_EDIT` payload.
159
- * info = msgId || origSenderJid || editorJid || "Message Edit"; aad = (empty);
160
- * key = HKDF-SHA256(salt=zeros, ikm=messageSecret, info, L=32).
161
- */
162
143
  export function decryptMessageEdit({ encPayload, encIv }, { originalSenderJid, originalMsgId, editEncKey, editorJid }) {
163
144
  const toBinary = txt => Buffer.from(txt)
164
145
  const sign = Buffer.concat([toBinary(originalMsgId), toBinary(originalSenderJid), toBinary(editorJid), toBinary('Message Edit'), new Uint8Array([1])])
165
146
  const key0 = hmacSign(editEncKey, new Uint8Array(32), 'sha256')
166
147
  const decKey = hmacSign(sign, key0, 'sha256')
167
- const aad = Buffer.alloc(0) // intentionally empty, unlike Poll Vote / Event Response
148
+ const aad = Buffer.alloc(0)
168
149
  const decrypted = aesDecryptGCM(encPayload, decKey, encIv, aad)
169
150
  return proto.Message.decode(decrypted)
170
151
  }
@@ -189,10 +170,6 @@ const buildEditUpdate = args => {
189
170
  }
190
171
  }
191
172
 
192
- /* ------------------------------------------------------------------ */
193
- /* Main incoming-message processor */
194
- /* ------------------------------------------------------------------ */
195
-
196
173
  const processMessage = async (message, { shouldProcessHistoryMsg, placeholderResendCache, ev, creds, signalRepository, keyStore, logger, options, getMessage }) => {
197
174
  const meId = creds.me.id
198
175
  const { accountSettings } = creds
@@ -210,9 +187,7 @@ const processMessage = async (message, { shouldProcessHistoryMsg, placeholderRes
210
187
  }
211
188
  const protocolMsg = content?.protocolMessage
212
189
  if (protocolMsg) {
213
- // Self-only protocol message types must be dropped if not fromMe (spoofing guard) — mirrors
214
- // whatsmeow's handleProtocolMessage. Cross-user types (REVOKE, MESSAGE_EDIT, EPHEMERAL_SETTING,
215
- // GROUP_MEMBER_LABEL_CHANGE) legitimately arrive from others and are NOT in this set.
190
+
216
191
  const SELF_ONLY_TYPES = new Set([
217
192
  proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION,
218
193
  proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE,
@@ -505,25 +480,20 @@ const processMessage = async (message, { shouldProcessHistoryMsg, placeholderRes
505
480
 
506
481
  export default processMessage
507
482
 
508
- /* ------------------------------------------------------------------ */
509
- /* Message retry manager */
510
- /* ------------------------------------------------------------------ */
511
-
512
483
  const RECENT_MESSAGES_SIZE = 1024
513
484
  const MESSAGE_KEY_SEPARATOR = '\u0000'
514
485
  const RECREATE_SESSION_TIMEOUT = 60 * 60 * 1000
515
486
  const PHONE_REQUEST_DELAY = 3000
516
487
 
517
- /** Retry reason codes matching WhatsApp Web's Signal error codes. */
518
488
  export const RetryReason = {
519
489
  UnknownError: 0,
520
490
  SignalErrorNoSession: 1,
521
491
  SignalErrorInvalidKey: 2,
522
492
  SignalErrorInvalidKeyId: 3,
523
- SignalErrorInvalidMessage: 4, // MAC verification failed - most common cause of decryption failures
493
+ SignalErrorInvalidMessage: 4,
524
494
  SignalErrorInvalidSignature: 5,
525
495
  SignalErrorFutureMessage: 6,
526
- SignalErrorBadMac: 7, // Explicit MAC failure - session is definitely out of sync
496
+ SignalErrorBadMac: 7,
527
497
  SignalErrorInvalidSession: 8,
528
498
  SignalErrorInvalidMsgKey: 9,
529
499
  BadBroadcastEphemeralSetting: 10,
@@ -531,7 +501,7 @@ export const RetryReason = {
531
501
  AdvFailure: 12,
532
502
  StatusRevokeDelay: 13
533
503
  }
534
- // reverse lookup for logging, mirrors the old TS enum's string access
504
+
535
505
  for (const [name, value] of Object.entries({ ...RetryReason })) RetryReason[value] = name
536
506
 
537
507
  const MAC_ERROR_CODES = new Set([RetryReason.SignalErrorInvalidMessage, RetryReason.SignalErrorBadMac])
@@ -548,17 +518,14 @@ export class MessageRetryManager {
548
518
  }
549
519
  })
550
520
  this.messageKeyIndex = new Map()
551
- this.sessionRecreateHistory = new Cache({ ttl: RECREATE_SESSION_TIMEOUT * 2 })
552
- this.retryCounters = new Cache({ ttl: 15 * 60 * 1000, updateAgeOnGet: true })
521
+
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 })
553
524
  this.baseKeys = new Cache({ max: 1024, ttl: 15 * 60 * 1000 })
554
525
  this.pendingPhoneRequests = {}
555
526
  this.maxMsgRetryCount = maxMsgRetryCount
556
527
  this.statistics = { totalRetries: 0, successfulRetries: 0, failedRetries: 0, mediaRetries: 0, sessionRecreations: 0, phoneRequests: 0 }
557
- // Tracks messages that were locally edited or revoked, so a late-arriving retry
558
- // receipt for the pre-edit/pre-revoke version doesn't resend stale content (e.g.
559
- // a deleted message reappearing, or an edit getting overwritten by its own
560
- // pre-edit body). Bounded TTL: only need to cover the window a stale retry could
561
- // realistically still be in flight.
528
+
562
529
  this.invalidatedMessages = new Cache({ max: 512, ttl: 5 * 60 * 1000 })
563
530
  }
564
531
 
@@ -566,7 +533,6 @@ export class MessageRetryManager {
566
533
  return this.keyToString({ to, id })
567
534
  }
568
535
 
569
- /** Mark (to, id) as edited/revoked so a subsequent resend request for it is dropped. */
570
536
  invalidateMessage(to, id) {
571
537
  if (!to || !id) return
572
538
  this.invalidatedMessages.set(this.invalidatedKey(to, id), true)
@@ -588,7 +554,6 @@ export class MessageRetryManager {
588
554
  return this.recentMessagesMap.get(this.keyToString({ to, id }))
589
555
  }
590
556
 
591
- /** MAC errors (codes 4 and 7) trigger immediate session recreation regardless of timeout. */
592
557
  shouldRecreateSession(jid, hasSession, errorCode) {
593
558
  if (!hasSession) {
594
559
  this.sessionRecreateHistory.set(jid, Date.now())
@@ -708,16 +673,6 @@ export class MessageRetryManager {
708
673
  }
709
674
  }
710
675
 
711
- /* ------------------------------------------------------------------ */
712
- /* Offline node processor */
713
- /* ------------------------------------------------------------------ */
714
-
715
- /**
716
- * Creates a processor for offline stanza nodes that:
717
- * - Queues nodes for sequential processing
718
- * - Yields to the event loop periodically to avoid blocking
719
- * - Catches handler errors to prevent the processing loop from crashing
720
- */
721
676
  export function makeOfflineNodeProcessor(nodeProcessorMap, deps, batchSize = 10) {
722
677
  const nodes = []
723
678
  let isProcessing = false
@@ -748,10 +703,6 @@ export function makeOfflineNodeProcessor(nodeProcessorMap, deps, batchSize = 10)
748
703
  return { enqueue }
749
704
  }
750
705
 
751
- /* ------------------------------------------------------------------ */
752
- /* History sync */
753
- /* ------------------------------------------------------------------ */
754
-
755
706
  const extractPnFromMessages = messages => {
756
707
  for (const msgItem of messages) {
757
708
  const message = msgItem.message
@@ -801,7 +752,7 @@ export const processHistoryMessage = (item, logger) => {
801
752
  for (const item_ of msgs) {
802
753
  const message = item_.message
803
754
  messages.push(message)
804
- if (!chat.messages?.length) chat.messages = [{ message }] // keep only the most recent message in the chat array
755
+ if (!chat.messages?.length) chat.messages = [{ message }]
805
756
  if (!message.key.fromMe && !chat.lastMessageRecvTimestamp) chat.lastMessageRecvTimestamp = toNumber(message.messageTimestamp)
806
757
  if (
807
758
  (message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP || message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB) &&
@@ -832,10 +783,6 @@ export const getHistoryMsg = message => {
832
783
  return normalizedContent?.protocolMessage?.historySyncNotification
833
784
  }
834
785
 
835
- /* ------------------------------------------------------------------ */
836
- /* Business / catalog */
837
- /* ------------------------------------------------------------------ */
838
-
839
786
  export const parseCatalogNode = node => {
840
787
  const catalogNode = getBinaryNodeChild(node, 'product_catalog')
841
788
  const products = getBinaryNodeChildren(catalogNode, 'product').map(parseProductNode)
@@ -918,12 +865,10 @@ export const parseProductNode = productNode => {
918
865
  }
919
866
  }
920
867
 
921
- /** Uploads images not already uploaded to WA's servers */
922
868
  export async function uploadingNecessaryImagesOfProduct(product, waUploadToServer, timeoutMs = 30000) {
923
869
  return { ...product, images: product.images ? await uploadingNecessaryImages(product.images, waUploadToServer, timeoutMs) : product.images }
924
870
  }
925
871
 
926
- /** Uploads images not already uploaded to WA's servers */
927
872
  export const uploadingNecessaryImages = async (images, waUploadToServer, timeoutMs = 30000) => {
928
873
  return Promise.all(
929
874
  images.map(async img => {
@@ -0,0 +1,19 @@
1
+ export const USERNAME_MIN_LENGTH = 4
2
+ export const USERNAME_MAX_LENGTH = 30
3
+
4
+ const USERNAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9._]*$/
5
+
6
+ export function normalizeUsername(input) {
7
+ if (typeof input !== 'string') return ''
8
+ return input.trim().replace(/^@/, '')
9
+ }
10
+
11
+ export function isValidUsername(input) {
12
+ const handle = normalizeUsername(input)
13
+ if (handle.length < USERNAME_MIN_LENGTH || handle.length > USERNAME_MAX_LENGTH) return false
14
+ return USERNAME_PATTERN.test(handle)
15
+ }
16
+
17
+ export function isValidUsernameKey(key) {
18
+ return typeof key === 'string' && /^\d{4}$/.test(key)
19
+ }