@badzz88/baileys 8.4.7 → 8.5.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 (144) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1055 -337
  3. package/WAProto/index.js +5 -5
  4. package/lib/Defaults/index.js +187 -127
  5. package/lib/Defaults/phonenumber-mcc.json +223 -0
  6. package/lib/Signal/Group/ciphertext-message.js +14 -11
  7. package/lib/Signal/Group/group-session-builder.js +91 -29
  8. package/lib/Signal/Group/group_cipher.js +88 -81
  9. package/lib/Signal/Group/index.js +136 -12
  10. package/lib/Signal/Group/keyhelper.js +70 -15
  11. package/lib/Signal/Group/sender-chain-key.js +31 -25
  12. package/lib/Signal/Group/sender-key-distribution-message.js +65 -62
  13. package/lib/Signal/Group/sender-key-message.js +68 -65
  14. package/lib/Signal/Group/sender-key-name.js +43 -41
  15. package/lib/Signal/Group/sender-key-record.js +43 -40
  16. package/lib/Signal/Group/sender-key-state.js +96 -83
  17. package/lib/Signal/Group/sender-message-key.js +29 -25
  18. package/lib/Signal/libsignal.js +483 -424
  19. package/lib/Signal/lid-mapping.js +261 -276
  20. package/lib/Socket/Client/index.js +30 -3
  21. package/lib/Socket/Client/types.js +12 -10
  22. package/lib/Socket/Client/websocket.js +61 -53
  23. package/lib/Socket/aigroups.js +240 -0
  24. package/lib/Socket/business.js +422 -379
  25. package/lib/Socket/chats.js +1816 -1193
  26. package/lib/Socket/communities.js +549 -431
  27. package/lib/Socket/graphql.js +656 -0
  28. package/lib/Socket/groups.js +764 -374
  29. package/lib/Socket/index.js +38 -11
  30. package/lib/Socket/interactive-handler.js +522 -0
  31. package/lib/Socket/interop.js +549 -0
  32. package/lib/Socket/luxu.js +6 -5
  33. package/lib/Socket/managed-account.js +183 -0
  34. package/lib/Socket/messages-recv.js +2439 -1915
  35. package/lib/Socket/messages-send.js +1642 -1242
  36. package/lib/Socket/mex.js +59 -40
  37. package/lib/Socket/newsletter.js +812 -249
  38. package/lib/Socket/privacy.js +449 -0
  39. package/lib/Socket/registration.js +427 -0
  40. package/lib/Socket/socket.js +1077 -965
  41. package/lib/Socket/text-router.js +83 -0
  42. package/lib/Socket/username.js +237 -140
  43. package/lib/Store/index.js +36 -10
  44. package/lib/Store/make-cache-manager-store.js +85 -80
  45. package/lib/Store/make-in-memory-store.js +591 -185
  46. package/lib/Store/make-ordered-dictionary.js +78 -72
  47. package/lib/Store/object-repository.js +25 -28
  48. package/lib/Types/Auth.js +38 -2
  49. package/lib/Types/Bussines.js +2 -2
  50. package/lib/Types/Call.js +2 -2
  51. package/lib/Types/Chat.js +4 -8
  52. package/lib/Types/Contact.js +2 -2
  53. package/lib/Types/Events.js +2 -2
  54. package/lib/Types/GroupMetadata.js +2 -2
  55. package/lib/Types/Label.js +26 -24
  56. package/lib/Types/LabelAssociation.js +8 -6
  57. package/lib/Types/Message.js +95 -11
  58. package/lib/Types/Mex.js +112 -37
  59. package/lib/Types/Newsletter.js +121 -0
  60. package/lib/Types/Product.js +2 -2
  61. package/lib/Types/Signal.js +2 -2
  62. package/lib/Types/Socket.js +2 -3
  63. package/lib/Types/State.js +70 -56
  64. package/lib/Types/USync.js +2 -2
  65. package/lib/Types/index.js +55 -26
  66. package/lib/Utils/auth-utils.js +292 -288
  67. package/lib/Utils/browser-utils.js +113 -48
  68. package/lib/Utils/business.js +240 -224
  69. package/lib/Utils/chat-utils.js +1205 -869
  70. package/lib/Utils/command-loader.d.ts +31 -0
  71. package/lib/Utils/command-loader.js +100 -0
  72. package/lib/Utils/companion-reg-client-utils.js +41 -34
  73. package/lib/Utils/consumer-application.js +107 -0
  74. package/lib/Utils/crypto.js +144 -107
  75. package/lib/Utils/curve25519-js.js +275 -0
  76. package/lib/Utils/decode-wa-message.js +518 -308
  77. package/lib/Utils/event-buffer.js +596 -611
  78. package/lib/Utils/generics.js +514 -354
  79. package/lib/Utils/group-history.js +60 -0
  80. package/lib/Utils/history.js +244 -134
  81. package/lib/Utils/identity-change-handler.js +51 -49
  82. package/lib/Utils/index.js +57 -23
  83. package/lib/Utils/jid-display-normalization.js +218 -0
  84. package/lib/Utils/link-preview.js +135 -77
  85. package/lib/Utils/logger.js +9 -3
  86. package/lib/Utils/lt-hash.js +37 -6
  87. package/lib/Utils/make-mutex.js +36 -33
  88. package/lib/Utils/message-composer.js +439 -233
  89. package/lib/Utils/message-retry-manager.js +265 -260
  90. package/lib/Utils/messages-media.js +855 -747
  91. package/lib/Utils/messages.js +2528 -884
  92. package/lib/Utils/meta-ai-msmsg.js +262 -0
  93. package/lib/Utils/native-bridge.js +82 -0
  94. package/lib/Utils/noise-handler.js +195 -200
  95. package/lib/Utils/offline-node-processor.js +35 -33
  96. package/lib/Utils/pre-key-manager.js +103 -102
  97. package/lib/Utils/process-message.js +978 -560
  98. package/lib/Utils/reporting-utils.js +257 -253
  99. package/lib/Utils/session-pool.d.ts +16 -0
  100. package/lib/Utils/session-pool.js +94 -0
  101. package/lib/Utils/signal.js +218 -195
  102. package/lib/Utils/stanza-ack.js +31 -29
  103. package/lib/Utils/sticker.d.ts +17 -0
  104. package/lib/Utils/sticker.js +145 -0
  105. package/lib/Utils/sync-action-utils.js +50 -45
  106. package/lib/Utils/tc-token-utils.js +137 -139
  107. package/lib/Utils/use-multi-file-auth-state.js +109 -109
  108. package/lib/Utils/validate-connection.js +218 -202
  109. package/lib/Utils/view-once-cache.d.ts +9 -0
  110. package/lib/Utils/view-once-cache.js +79 -0
  111. package/lib/Utils/voip-rekey.js +22 -0
  112. package/lib/WABinary/constants.js +1302 -1299
  113. package/lib/WABinary/decode.js +343 -262
  114. package/lib/WABinary/encode.js +12 -4
  115. package/lib/WABinary/generic-utils.js +223 -187
  116. package/lib/WABinary/index.js +33 -6
  117. package/lib/WABinary/jid-utils.js +351 -88
  118. package/lib/WABinary/types.js +2 -2
  119. package/lib/WAM/BinaryInfo.js +12 -9
  120. package/lib/WAM/constants.js +39486 -22853
  121. package/lib/WAM/encode.js +132 -140
  122. package/lib/WAM/index.js +31 -4
  123. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +55 -0
  124. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +43 -0
  125. package/lib/WAUSync/Protocols/USyncContactProtocol.js +53 -51
  126. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +56 -53
  127. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +29 -26
  128. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +59 -0
  129. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +31 -0
  130. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +32 -0
  131. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +29 -0
  132. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -37
  133. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +38 -0
  134. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +26 -24
  135. package/lib/WAUSync/Protocols/index.js +39 -6
  136. package/lib/WAUSync/USyncQuery.js +132 -97
  137. package/lib/WAUSync/USyncUser.js +49 -30
  138. package/lib/WAUSync/index.js +31 -4
  139. package/lib/antiban.js +4637 -0
  140. package/lib/index.js +48 -15
  141. package/package.json +55 -92
  142. package/lib/WAUSync/Protocols/USyncNewsletterProtocol.js +0 -263
  143. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +0 -51
  144. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +0 -29
@@ -0,0 +1,145 @@
1
+ 'use strict'
2
+ Object.defineProperty(exports, '__esModule', { value: true })
3
+ exports.imageToWebpSticker = exports.videoToWebpSticker = exports.addExifToWebp = void 0
4
+ const os = require('os')
5
+ const path = require('path')
6
+ const fs = require('fs')
7
+ const crypto = require('crypto')
8
+ const { exec } = require('child_process')
9
+
10
+ /**
11
+ * Builds and writes the EXIF metadata WhatsApp expects on sticker webp files
12
+ * (pack name / author, shown when a user long-presses a sticker).
13
+ * Converts the file to the "extended" (VP8X) WebP container if it isn't already,
14
+ * since that's the container format that actually carries an EXIF chunk.
15
+ * Returns the new buffer with EXIF attached.
16
+ */
17
+ const addExifToWebp = async (webpBuffer, { packName = '', packPublisher = '', categories = [] } = {}) => {
18
+ const json = {
19
+ 'sticker-pack-id': crypto.randomBytes(16).toString('hex'),
20
+ 'sticker-pack-name': packName,
21
+ 'sticker-pack-publisher': packPublisher,
22
+ emojis: categories.length ? categories : ['😀']
23
+ }
24
+ const jsonBuffer = Buffer.from(JSON.stringify(json), 'utf-8')
25
+ // TIFF header + IFD entry pointing at a single custom tag (0x5741 "AW") holding
26
+ // the JSON payload -- this is the exact structure WhatsApp's client parses.
27
+ const exifAttr = Buffer.from([
28
+ 0x49, 0x49, 0x2a, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x41, 0x57, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16,
29
+ 0x00, 0x00, 0x00
30
+ ])
31
+ exifAttr.writeUIntLE(jsonBuffer.length, 14, 4)
32
+ const exifPayload = Buffer.concat([exifAttr, jsonBuffer])
33
+ const pad = buf => (buf.length % 2 === 1 ? Buffer.concat([buf, Buffer.from([0x00])]) : buf)
34
+ const makeChunk = (tag, data) => {
35
+ const sizeField = Buffer.alloc(4)
36
+ sizeField.writeUInt32LE(data.length, 0)
37
+ return Buffer.concat([Buffer.from(tag, 'ascii'), sizeField, pad(data)])
38
+ }
39
+ const exifChunk = makeChunk('EXIF', exifPayload)
40
+ if (webpBuffer.slice(0, 4).toString('ascii') !== 'RIFF' || webpBuffer.slice(8, 12).toString('ascii') !== 'WEBP') {
41
+ throw new Error('addExifToWebp expects a valid WebP buffer')
42
+ }
43
+ let offset = 12
44
+ let vp8xChunk = null
45
+ let vp8xOffset = -1
46
+ const otherChunks = []
47
+ while (offset < webpBuffer.length) {
48
+ const tag = webpBuffer.slice(offset, offset + 4).toString('ascii')
49
+ const size = webpBuffer.readUInt32LE(offset + 4)
50
+ const dataStart = offset + 8
51
+ const dataEnd = dataStart + size
52
+ const chunkTotal = 8 + size + (size % 2)
53
+ if (tag === 'VP8X') {
54
+ vp8xChunk = webpBuffer.slice(offset, offset + chunkTotal)
55
+ vp8xOffset = offset
56
+ } else if (tag !== 'EXIF') {
57
+ // drop any pre-existing EXIF chunk, keep everything else (VP8/VP8L/ANIM/ANMF/ICCP/...)
58
+ otherChunks.push(webpBuffer.slice(offset, offset + chunkTotal))
59
+ }
60
+ offset += chunkTotal
61
+ }
62
+ let flags
63
+ let canvasWidth
64
+ let canvasHeight
65
+ if (vp8xChunk) {
66
+ flags = vp8xChunk.readUInt8(8)
67
+ canvasWidth = vp8xChunk.readUIntLE(12, 3) + 1
68
+ canvasHeight = vp8xChunk.readUIntLE(15, 3) + 1
69
+ } else {
70
+ flags = 0
71
+ let sharp
72
+ try {
73
+ sharp = require('sharp')
74
+ } catch (error) {
75
+ throw new Error('addExifToWebp needs the optional "sharp" dependency to read image dimensions')
76
+ }
77
+ const meta = await sharp(webpBuffer).metadata()
78
+ canvasWidth = meta.width
79
+ canvasHeight = meta.height
80
+ }
81
+ flags |= 0x08 // set the "has EXIF metadata" bit
82
+ const vp8xData = Buffer.alloc(10)
83
+ vp8xData.writeUInt8(flags, 0)
84
+ vp8xData.writeUIntLE(canvasWidth - 1, 4, 3)
85
+ vp8xData.writeUIntLE(canvasHeight - 1, 7, 3)
86
+ const newVp8xChunk = makeChunk('VP8X', vp8xData)
87
+ const body = Buffer.concat([newVp8xChunk, ...otherChunks, exifChunk])
88
+ const fileSize = Buffer.alloc(4)
89
+ fileSize.writeUInt32LE(4 + body.length, 0) // 4 = 'WEBP'
90
+ return Buffer.concat([Buffer.from('RIFF', 'ascii'), fileSize, Buffer.from('WEBP', 'ascii'), body])
91
+ }
92
+ exports.addExifToWebp = addExifToWebp
93
+
94
+ /**
95
+ * Converts a static image buffer to a WhatsApp sticker-ready webp buffer using `sharp`.
96
+ * @param {Buffer} imageBuffer
97
+ * @param {{ packName?: string, packPublisher?: string, categories?: string[], quality?: number }} [options]
98
+ * @returns {Promise<Buffer>}
99
+ */
100
+ const imageToWebpSticker = async (imageBuffer, options = {}) => {
101
+ let sharp
102
+ try {
103
+ sharp = require('sharp')
104
+ } catch (error) {
105
+ throw new Error('imageToWebpSticker requires the optional "sharp" dependency to be installed')
106
+ }
107
+ const webp = await sharp(imageBuffer)
108
+ .resize(512, 512, { fit: 'contain', background: { r: 0, g: 0, b: 0, alpha: 0 } })
109
+ .webp({ quality: options.quality ?? 80 })
110
+ .toBuffer()
111
+ return addExifToWebp(webp, options)
112
+ }
113
+ exports.imageToWebpSticker = imageToWebpSticker
114
+
115
+ /**
116
+ * Converts a video buffer to an animated WhatsApp sticker-ready webp buffer.
117
+ * Requires the `ffmpeg` binary to be available on PATH.
118
+ * @param {Buffer} videoBuffer
119
+ * @param {{ packName?: string, packPublisher?: string, categories?: string[], fps?: number, seconds?: number }} [options]
120
+ * @returns {Promise<Buffer>}
121
+ */
122
+ const videoToWebpSticker = async (videoBuffer, options = {}) => {
123
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'xazbails-sticker-'))
124
+ const inputPath = path.join(tmpDir, 'input.mp4')
125
+ const outputPath = path.join(tmpDir, 'output.webp')
126
+ fs.writeFileSync(inputPath, videoBuffer)
127
+ const fps = options.fps ?? 10
128
+ const seconds = options.seconds ?? 5
129
+ const cmd =
130
+ `ffmpeg -y -i ${inputPath} -t ${seconds} -vf ` +
131
+ `"fps=${fps},scale=512:512:force_original_aspect_ratio=decrease,` +
132
+ `pad=512:512:(ow-iw)/2:(oh-ih)/2:color=0x00000000,split[a][b];` +
133
+ `[a]palettegen=reserve_transparent=1[p];[b][p]paletteuse" ` +
134
+ `-loop 0 -preset default -an -vsync 0 ${outputPath}`
135
+ try {
136
+ await new Promise((resolve, reject) => {
137
+ exec(cmd, err => (err ? reject(err) : resolve()))
138
+ })
139
+ const webp = fs.readFileSync(outputPath)
140
+ return await addExifToWebp(webp, options)
141
+ } finally {
142
+ fs.rmSync(tmpDir, { recursive: true, force: true })
143
+ }
144
+ }
145
+ exports.videoToWebpSticker = videoToWebpSticker
@@ -1,49 +1,54 @@
1
- import { proto } from '../../WAProto/index.js';
2
- import { isLidUser, isPnUser } from '../WABinary/index.js';
1
+ 'use strict'
2
+ Object.defineProperty(exports, '__esModule', { value: true })
3
+ exports.emitSyncActionResults = exports.processContactAction = void 0
4
+ const WABinary_1 = require('../WABinary')
3
5
  /**
4
6
  * Process contactAction and return events to emit.
5
7
  * Pure function - no side effects.
6
8
  */
7
- export const processContactAction = (action, id, logger) => {
8
- const results = [];
9
- if (!id) {
10
- logger?.warn({ hasFullName: !!action.fullName, hasLidJid: !!action.lidJid, hasPnJid: !!action.pnJid }, 'contactAction sync: missing id in index');
11
- return results;
12
- }
13
- const lidJid = action.lidJid;
14
- const idIsPn = isPnUser(id);
15
- // PN is in index[1], not in contactAction.pnJid which is usually null
16
- const phoneNumber = idIsPn ? id : action.pnJid || undefined;
17
- // Always emit contacts.upsert
18
- results.push({
19
- event: 'contacts.upsert',
20
- data: [
21
- {
22
- id,
23
- name: action.fullName || action.firstName || action.username || undefined,
24
- username: action.username || undefined,
25
- lid: lidJid || undefined,
26
- phoneNumber
27
- }
28
- ]
29
- });
30
- // Emit lid-mapping.update if we have valid LID-PN pair
31
- if (lidJid && isLidUser(lidJid) && idIsPn) {
32
- results.push({
33
- event: 'lid-mapping.update',
34
- data: { lid: lidJid, pn: id }
35
- });
36
- }
37
- return results;
38
- };
39
- export const emitSyncActionResults = (ev, results) => {
40
- for (const result of results) {
41
- if (result.event === 'contacts.upsert') {
42
- ev.emit('contacts.upsert', result.data);
43
- }
44
- else {
45
- ev.emit('lid-mapping.update', result.data);
46
- }
47
- }
48
- };
49
- //# sourceMappingURL=sync-action-utils.js.map
9
+ const processContactAction = (action, id, logger) => {
10
+ const results = []
11
+ if (!id) {
12
+ logger?.warn(
13
+ { hasFullName: !!action.fullName, hasLidJid: !!action.lidJid, hasPnJid: !!action.pnJid },
14
+ 'contactAction sync: missing id in index'
15
+ )
16
+ return results
17
+ }
18
+ const lidJid = action.lidJid
19
+ const idIsPn = (0, WABinary_1.isPnUser)(id)
20
+ // PN is in index[1], not in contactAction.pnJid which is usually null
21
+ const phoneNumber = idIsPn ? id : action.pnJid || undefined
22
+ // Always emit contacts.upsert
23
+ results.push({
24
+ event: 'contacts.upsert',
25
+ data: [
26
+ {
27
+ id,
28
+ name: action.fullName || action.firstName || action.username || undefined,
29
+ username: action.username || undefined,
30
+ lid: lidJid || undefined,
31
+ phoneNumber
32
+ }
33
+ ]
34
+ })
35
+ // Emit lid-mapping.update if we have valid LID-PN pair
36
+ if (lidJid && (0, WABinary_1.isLidUser)(lidJid) && idIsPn) {
37
+ results.push({
38
+ event: 'lid-mapping.update',
39
+ data: { lid: lidJid, pn: id }
40
+ })
41
+ }
42
+ return results
43
+ }
44
+ exports.processContactAction = processContactAction
45
+ const emitSyncActionResults = (ev, results) => {
46
+ for (const result of results) {
47
+ if (result.event === 'contacts.upsert') {
48
+ ev.emit('contacts.upsert', result.data)
49
+ } else {
50
+ ev.emit('lid-mapping.update', result.data)
51
+ }
52
+ }
53
+ }
54
+ exports.emitSyncActionResults = emitSyncActionResults
@@ -1,7 +1,18 @@
1
- import { getBinaryNodeChild, getBinaryNodeChildren, isHostedLidUser, isHostedPnUser, isJidMetaAI, isLidUser, isPnUser, jidNormalizedUser } from '../WABinary/index.js';
1
+ 'use strict'
2
+ Object.defineProperty(exports, '__esModule', { value: true })
3
+ exports.TC_TOKEN_INDEX_KEY = void 0
4
+ exports.readTcTokenIndex = readTcTokenIndex
5
+ exports.buildMergedTcTokenIndexWrite = buildMergedTcTokenIndexWrite
6
+ exports.isTcTokenExpired = isTcTokenExpired
7
+ exports.shouldSendNewTcToken = shouldSendNewTcToken
8
+ exports.resolveTcTokenJid = resolveTcTokenJid
9
+ exports.resolveIssuanceJid = resolveIssuanceJid
10
+ exports.buildTcTokenFromJid = buildTcTokenFromJid
11
+ exports.storeTcTokensFromIqResult = storeTcTokensFromIqResult
12
+ const WABinary_1 = require('../WABinary')
2
13
  // Same phone-number pattern as WABinary's isJidBot, applied against the user
3
14
  // part so the check is invariant to @c.us ↔ @s.whatsapp.net normalization.
4
- const BOT_PHONE_REGEX = /^1313555\d{4}$|^131655500\d{2}$/;
15
+ const BOT_PHONE_REGEX = /^1313555\d{4}$|^131655500\d{2}$/
5
16
  /**
6
17
  * Mirrors WA Web's `Wid.isRegularUser()` (user ∧ ¬PSA ∧ ¬Bot). Used to gate tctoken
7
18
  * storage against malformed notifications — WA Web filters server-side but we
@@ -9,155 +20,142 @@ const BOT_PHONE_REGEX = /^1313555\d{4}$|^131655500\d{2}$/;
9
20
  * Works for both pre- and post-normalized JIDs (`@c.us` vs `@s.whatsapp.net`).
10
21
  */
11
22
  function isRegularUser(jid) {
12
- if (!jid)
13
- return false;
14
- const user = jid.split('@')[0] ?? '';
15
- if (user === '0')
16
- return false; // PSA
17
- if (BOT_PHONE_REGEX.test(user))
18
- return false; // Bot by phone pattern
19
- if (isJidMetaAI(jid))
20
- return false; // MetaAI (@bot server)
21
- return !!(isPnUser(jid) || isLidUser(jid) || isHostedPnUser(jid) || isHostedLidUser(jid) || jid.endsWith('@c.us'));
23
+ if (!jid) return false
24
+ const user = jid.split('@')[0] ?? ''
25
+ if (user === '0') return false // PSA
26
+ if (BOT_PHONE_REGEX.test(user)) return false // Bot by phone pattern
27
+ if ((0, WABinary_1.isJidMetaAI)(jid)) return false // MetaAI (@bot server)
28
+ return !!(
29
+ (0, WABinary_1.isPnUser)(jid) ||
30
+ (0, WABinary_1.isLidUser)(jid) ||
31
+ (0, WABinary_1.isHostedPnUser)(jid) ||
32
+ (0, WABinary_1.isHostedLidUser)(jid) ||
33
+ jid.endsWith('@c.us')
34
+ )
22
35
  }
23
- const TC_TOKEN_BUCKET_DURATION = 604800; // 7 days
24
- const TC_TOKEN_NUM_BUCKETS = 4; // ~28-day rolling window
36
+ const TC_TOKEN_BUCKET_DURATION = 604800 // 7 days
37
+ const TC_TOKEN_NUM_BUCKETS = 4 // ~28-day rolling window
25
38
  /** Sentinel key under `tctoken` store holding a JSON array of tracked storage JIDs for cross-session pruning. */
26
- export const TC_TOKEN_INDEX_KEY = '__index';
39
+ exports.TC_TOKEN_INDEX_KEY = '__index'
27
40
  /** Read the persisted tctoken JID index and return its entries (never contains the sentinel key itself). */
28
- export async function readTcTokenIndex(keys) {
29
- const data = await keys.get('tctoken', [TC_TOKEN_INDEX_KEY]);
30
- const entry = data[TC_TOKEN_INDEX_KEY];
31
- if (!entry?.token?.length)
32
- return [];
33
- try {
34
- const parsed = JSON.parse(Buffer.from(entry.token).toString());
35
- if (!Array.isArray(parsed))
36
- return [];
37
- return parsed.filter((j) => typeof j === 'string' && j.length > 0 && j !== TC_TOKEN_INDEX_KEY);
38
- }
39
- catch {
40
- return [];
41
- }
41
+ async function readTcTokenIndex(keys) {
42
+ const data = await keys.get('tctoken', [exports.TC_TOKEN_INDEX_KEY])
43
+ const entry = data[exports.TC_TOKEN_INDEX_KEY]
44
+ if (!entry?.token?.length) return []
45
+ try {
46
+ const parsed = JSON.parse(Buffer.from(entry.token).toString())
47
+ if (!Array.isArray(parsed)) return []
48
+ return parsed.filter(j => typeof j === 'string' && j.length > 0 && j !== exports.TC_TOKEN_INDEX_KEY)
49
+ } catch {
50
+ return []
51
+ }
42
52
  }
43
53
  /** Build a SignalDataSet fragment that writes the merged index (persisted ∪ added) under the sentinel key. */
44
- export async function buildMergedTcTokenIndexWrite(keys, addedJids) {
45
- const persisted = await readTcTokenIndex(keys);
46
- const merged = new Set(persisted);
47
- for (const jid of addedJids) {
48
- if (jid && jid !== TC_TOKEN_INDEX_KEY)
49
- merged.add(jid);
50
- }
51
- return {
52
- [TC_TOKEN_INDEX_KEY]: { token: Buffer.from(JSON.stringify([...merged])) }
53
- };
54
+ async function buildMergedTcTokenIndexWrite(keys, addedJids) {
55
+ const persisted = await readTcTokenIndex(keys)
56
+ const merged = new Set(persisted)
57
+ for (const jid of addedJids) {
58
+ if (jid && jid !== exports.TC_TOKEN_INDEX_KEY) merged.add(jid)
59
+ }
60
+ return {
61
+ [exports.TC_TOKEN_INDEX_KEY]: { token: Buffer.from(JSON.stringify([...merged])) }
62
+ }
54
63
  }
55
64
  // WA Web has separate sender/receiver AB props for these but they're identical today
56
- export function isTcTokenExpired(timestamp) {
57
- if (timestamp === null || timestamp === undefined)
58
- return true;
59
- const ts = typeof timestamp === 'string' ? parseInt(timestamp) : timestamp;
60
- if (isNaN(ts))
61
- return true;
62
- const now = Math.floor(Date.now() / 1000);
63
- const currentBucket = Math.floor(now / TC_TOKEN_BUCKET_DURATION);
64
- const cutoffBucket = currentBucket - (TC_TOKEN_NUM_BUCKETS - 1);
65
- const cutoffTimestamp = cutoffBucket * TC_TOKEN_BUCKET_DURATION;
66
- return ts < cutoffTimestamp;
65
+ function isTcTokenExpired(timestamp) {
66
+ if (timestamp === null || timestamp === undefined) return true
67
+ const ts = typeof timestamp === 'string' ? parseInt(timestamp) : timestamp
68
+ if (isNaN(ts)) return true
69
+ const now = Math.floor(Date.now() / 1000)
70
+ const currentBucket = Math.floor(now / TC_TOKEN_BUCKET_DURATION)
71
+ const cutoffBucket = currentBucket - (TC_TOKEN_NUM_BUCKETS - 1)
72
+ const cutoffTimestamp = cutoffBucket * TC_TOKEN_BUCKET_DURATION
73
+ return ts < cutoffTimestamp
67
74
  }
68
- export function shouldSendNewTcToken(senderTimestamp) {
69
- if (senderTimestamp === undefined)
70
- return true;
71
- const now = Math.floor(Date.now() / 1000);
72
- const currentBucket = Math.floor(now / TC_TOKEN_BUCKET_DURATION);
73
- const senderBucket = Math.floor(senderTimestamp / TC_TOKEN_BUCKET_DURATION);
74
- return currentBucket > senderBucket;
75
+ function shouldSendNewTcToken(senderTimestamp) {
76
+ if (senderTimestamp === undefined) return true
77
+ const now = Math.floor(Date.now() / 1000)
78
+ const currentBucket = Math.floor(now / TC_TOKEN_BUCKET_DURATION)
79
+ const senderBucket = Math.floor(senderTimestamp / TC_TOKEN_BUCKET_DURATION)
80
+ return currentBucket > senderBucket
75
81
  }
76
82
  /** Resolve JID to LID for tctoken storage (WA Web stores under LID) */
77
- export async function resolveTcTokenJid(jid, getLIDForPN) {
78
- if (isLidUser(jid))
79
- return jid;
80
- const lid = await getLIDForPN(jid);
81
- return lid ?? jid;
83
+ async function resolveTcTokenJid(jid, getLIDForPN) {
84
+ if ((0, WABinary_1.isLidUser)(jid)) return jid
85
+ const lid = await getLIDForPN(jid)
86
+ return lid ?? jid
82
87
  }
83
88
  /** Resolve target JID for issuing privacy token based on AB prop 14303 */
84
- export async function resolveIssuanceJid(jid, issueToLid, getLIDForPN, getPNForLID) {
85
- if (issueToLid) {
86
- if (isLidUser(jid))
87
- return jid;
88
- const lid = await getLIDForPN(jid);
89
- return lid ?? jid;
90
- }
91
- if (!isLidUser(jid))
92
- return jid;
93
- if (getPNForLID) {
94
- const pn = await getPNForLID(jid);
95
- return pn ?? jid;
96
- }
97
- return jid;
89
+ async function resolveIssuanceJid(jid, issueToLid, getLIDForPN, getPNForLID) {
90
+ if (issueToLid) {
91
+ if ((0, WABinary_1.isLidUser)(jid)) return jid
92
+ const lid = await getLIDForPN(jid)
93
+ return lid ?? jid
94
+ }
95
+ if (!(0, WABinary_1.isLidUser)(jid)) return jid
96
+ if (getPNForLID) {
97
+ const pn = await getPNForLID(jid)
98
+ return pn ?? jid
99
+ }
100
+ return jid
98
101
  }
99
- export async function buildTcTokenFromJid({ authState, jid, baseContent = [], getLIDForPN }) {
100
- try {
101
- const storageJid = await resolveTcTokenJid(jid, getLIDForPN);
102
- const tcTokenData = await authState.keys.get('tctoken', [storageJid]);
103
- const entry = tcTokenData?.[storageJid];
104
- const tcTokenBuffer = entry?.token;
105
- if (!tcTokenBuffer?.length || isTcTokenExpired(entry?.timestamp)) {
106
- if (tcTokenBuffer) {
107
- // Preserve senderTimestamp so shouldSendNewTcToken() keeps its dedupe state
108
- // after we drop the unusable peer token. Only wipe the record entirely when
109
- // there's nothing worth keeping.
110
- const cleared = entry?.senderTimestamp !== undefined
111
- ? { token: Buffer.alloc(0), senderTimestamp: entry.senderTimestamp }
112
- : null;
113
- await authState.keys.set({ tctoken: { [storageJid]: cleared } });
114
- }
115
- return baseContent.length > 0 ? baseContent : undefined;
116
- }
117
- baseContent.push({
118
- tag: 'tctoken',
119
- attrs: {},
120
- content: tcTokenBuffer
121
- });
122
- return baseContent;
123
- }
124
- catch (error) {
125
- return baseContent.length > 0 ? baseContent : undefined;
126
- }
102
+ async function buildTcTokenFromJid({ authState, jid, baseContent = [], getLIDForPN }) {
103
+ try {
104
+ const storageJid = await resolveTcTokenJid(jid, getLIDForPN)
105
+ const tcTokenData = await authState.keys.get('tctoken', [storageJid])
106
+ const entry = tcTokenData?.[storageJid]
107
+ const tcTokenBuffer = entry?.token
108
+ if (!tcTokenBuffer?.length || isTcTokenExpired(entry?.timestamp)) {
109
+ if (tcTokenBuffer) {
110
+ // Preserve senderTimestamp so shouldSendNewTcToken() keeps its dedupe state
111
+ // after we drop the unusable peer token. Only wipe the record entirely when
112
+ // there's nothing worth keeping.
113
+ const cleared =
114
+ entry?.senderTimestamp !== undefined
115
+ ? { token: Buffer.alloc(0), senderTimestamp: entry.senderTimestamp }
116
+ : null
117
+ await authState.keys.set({ tctoken: { [storageJid]: cleared } })
118
+ }
119
+ return baseContent.length > 0 ? baseContent : undefined
120
+ }
121
+ baseContent.push({
122
+ tag: 'tctoken',
123
+ attrs: {},
124
+ content: tcTokenBuffer
125
+ })
126
+ return baseContent
127
+ } catch (error) {
128
+ return baseContent.length > 0 ? baseContent : undefined
129
+ }
127
130
  }
128
- export async function storeTcTokensFromIqResult({ result, fallbackJid, keys, getLIDForPN, onNewJidStored }) {
129
- const tokensNode = getBinaryNodeChild(result, 'tokens');
130
- if (!tokensNode)
131
- return;
132
- const tokenNodes = getBinaryNodeChildren(tokensNode, 'token');
133
- for (const tokenNode of tokenNodes) {
134
- if (tokenNode.attrs.type !== 'trusted_contact' || !(tokenNode.content instanceof Uint8Array)) {
135
- continue;
136
- }
137
- // In notifications tokenNode.attrs.jid is your own device JID, not the sender's
138
- const rawJid = jidNormalizedUser(fallbackJid || tokenNode.attrs.jid);
139
- if (!isRegularUser(rawJid))
140
- continue;
141
- const storageJid = await resolveTcTokenJid(rawJid, getLIDForPN);
142
- const existingTcData = await keys.get('tctoken', [storageJid]);
143
- const existingEntry = existingTcData[storageJid];
144
- const existingTs = existingEntry?.timestamp ? Number(existingEntry.timestamp) : 0;
145
- const incomingTs = tokenNode.attrs.t ? Number(tokenNode.attrs.t) : 0;
146
- // timestamp-less tokens would be immediately expired
147
- if (!incomingTs)
148
- continue;
149
- if (existingTs > 0 && existingTs > incomingTs)
150
- continue;
151
- await keys.set({
152
- tctoken: {
153
- [storageJid]: {
154
- ...existingEntry,
155
- token: Buffer.from(tokenNode.content),
156
- timestamp: tokenNode.attrs.t
157
- }
158
- }
159
- });
160
- onNewJidStored?.(storageJid);
161
- }
131
+ async function storeTcTokensFromIqResult({ result, fallbackJid, keys, getLIDForPN, onNewJidStored }) {
132
+ const tokensNode = (0, WABinary_1.getBinaryNodeChild)(result, 'tokens')
133
+ if (!tokensNode) return
134
+ const tokenNodes = (0, WABinary_1.getBinaryNodeChildren)(tokensNode, 'token')
135
+ for (const tokenNode of tokenNodes) {
136
+ if (tokenNode.attrs.type !== 'trusted_contact' || !(tokenNode.content instanceof Uint8Array)) {
137
+ continue
138
+ }
139
+ // In notifications tokenNode.attrs.jid is your own device JID, not the sender's
140
+ const rawJid = (0, WABinary_1.jidNormalizedUser)(fallbackJid || tokenNode.attrs.jid)
141
+ if (!isRegularUser(rawJid)) continue
142
+ const storageJid = await resolveTcTokenJid(rawJid, getLIDForPN)
143
+ const existingTcData = await keys.get('tctoken', [storageJid])
144
+ const existingEntry = existingTcData[storageJid]
145
+ const existingTs = existingEntry?.timestamp ? Number(existingEntry.timestamp) : 0
146
+ const incomingTs = tokenNode.attrs.t ? Number(tokenNode.attrs.t) : 0
147
+ // timestamp-less tokens would be immediately expired
148
+ if (!incomingTs) continue
149
+ if (existingTs > 0 && existingTs > incomingTs) continue
150
+ await keys.set({
151
+ tctoken: {
152
+ [storageJid]: {
153
+ ...existingEntry,
154
+ token: Buffer.from(tokenNode.content),
155
+ timestamp: tokenNode.attrs.t
156
+ }
157
+ }
158
+ })
159
+ onNewJidStored?.(storageJid)
160
+ }
162
161
  }
163
- //# sourceMappingURL=tc-token-utils.js.map