@bellaxchuu/flowred 0.8.6
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.
- package/LICENSE +21 -0
- package/README.md +214 -0
- package/WAProto/GenerateStatics.sh +3 -0
- package/WAProto/WAProto.proto +6902 -0
- package/WAProto/fix-imports.js +85 -0
- package/WAProto/index.js +242946 -0
- package/engine-requirements.js +10 -0
- package/lib/Defaults/index.js +190 -0
- package/lib/Defaults/phonenumber-mcc.json +223 -0
- package/lib/Signal/Group/ciphertext-message.js +15 -0
- package/lib/Signal/Group/group-session-builder.js +92 -0
- package/lib/Signal/Group/group_cipher.js +89 -0
- package/lib/Signal/Group/index.js +136 -0
- package/lib/Signal/Group/keyhelper.js +73 -0
- package/lib/Signal/Group/sender-chain-key.js +32 -0
- package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
- package/lib/Signal/Group/sender-key-message.js +69 -0
- package/lib/Signal/Group/sender-key-name.js +50 -0
- package/lib/Signal/Group/sender-key-record.js +44 -0
- package/lib/Signal/Group/sender-key-state.js +97 -0
- package/lib/Signal/Group/sender-message-key.js +30 -0
- package/lib/Signal/libsignal.js +490 -0
- package/lib/Signal/lid-mapping.js +262 -0
- package/lib/Socket/Client/index.js +30 -0
- package/lib/Socket/Client/types.js +13 -0
- package/lib/Socket/Client/websocket.js +62 -0
- package/lib/Socket/aigroups.js +240 -0
- package/lib/Socket/business.js +422 -0
- package/lib/Socket/chats.js +1816 -0
- package/lib/Socket/communities.js +549 -0
- package/lib/Socket/graphql.js +656 -0
- package/lib/Socket/groups.js +764 -0
- package/lib/Socket/index.js +39 -0
- package/lib/Socket/interactive-handler.js +522 -0
- package/lib/Socket/interop.js +549 -0
- package/lib/Socket/luxu.js +387 -0
- package/lib/Socket/managed-account.js +183 -0
- package/lib/Socket/messages-recv.js +2440 -0
- package/lib/Socket/messages-send.js +1853 -0
- package/lib/Socket/mex.js +60 -0
- package/lib/Socket/newsletter.js +820 -0
- package/lib/Socket/privacy.js +449 -0
- package/lib/Socket/registration.js +427 -0
- package/lib/Socket/socket.js +1092 -0
- package/lib/Socket/text-router.js +83 -0
- package/lib/Socket/username.js +243 -0
- package/lib/Store/index.js +36 -0
- package/lib/Store/keyed-db.js +108 -0
- package/lib/Store/make-cache-manager-store.js +90 -0
- package/lib/Store/make-in-memory-store.js +604 -0
- package/lib/Store/make-ordered-dictionary.js +81 -0
- package/lib/Store/object-repository.js +29 -0
- package/lib/Types/Auth.js +38 -0
- package/lib/Types/Bussines.js +2 -0
- package/lib/Types/Call.js +2 -0
- package/lib/Types/Chat.js +4 -0
- package/lib/Types/Contact.js +2 -0
- package/lib/Types/Events.js +2 -0
- package/lib/Types/GroupMetadata.js +2 -0
- package/lib/Types/Label.js +27 -0
- package/lib/Types/LabelAssociation.js +9 -0
- package/lib/Types/Message.js +95 -0
- package/lib/Types/Mex.js +112 -0
- package/lib/Types/Newsletter.js +121 -0
- package/lib/Types/Product.js +2 -0
- package/lib/Types/Signal.js +2 -0
- package/lib/Types/Socket.js +2 -0
- package/lib/Types/State.js +70 -0
- package/lib/Types/USync.js +2 -0
- package/lib/Types/index.js +55 -0
- package/lib/Utils/auth-utils.js +306 -0
- package/lib/Utils/browser-utils.js +114 -0
- package/lib/Utils/business.js +247 -0
- package/lib/Utils/chat-utils.js +1208 -0
- package/lib/Utils/command-loader.js +100 -0
- package/lib/Utils/companion-reg-client-utils.js +42 -0
- package/lib/Utils/consumer-application.js +107 -0
- package/lib/Utils/crypto.js +155 -0
- package/lib/Utils/curve25519-js.js +275 -0
- package/lib/Utils/decode-wa-message.js +560 -0
- package/lib/Utils/event-buffer.js +607 -0
- package/lib/Utils/generics.js +563 -0
- package/lib/Utils/group-history.js +60 -0
- package/lib/Utils/history.js +244 -0
- package/lib/Utils/identity-change-handler.js +52 -0
- package/lib/Utils/index.js +57 -0
- package/lib/Utils/jid-display-normalization.js +218 -0
- package/lib/Utils/link-preview.js +143 -0
- package/lib/Utils/logger.js +9 -0
- package/lib/Utils/lt-hash.js +39 -0
- package/lib/Utils/make-mutex.js +36 -0
- package/lib/Utils/message-composer.js +479 -0
- package/lib/Utils/message-retry-manager.js +270 -0
- package/lib/Utils/messages-media.js +896 -0
- package/lib/Utils/messages.js +2904 -0
- package/lib/Utils/meta-ai-msmsg.js +262 -0
- package/lib/Utils/native-bridge.js +82 -0
- package/lib/Utils/noise-handler.js +196 -0
- package/lib/Utils/offline-node-processor.js +42 -0
- package/lib/Utils/pre-key-manager.js +107 -0
- package/lib/Utils/process-message.js +1048 -0
- package/lib/Utils/reporting-utils.js +262 -0
- package/lib/Utils/session-pool.js +94 -0
- package/lib/Utils/signal.js +224 -0
- package/lib/Utils/stanza-ack.js +40 -0
- package/lib/Utils/sticker.js +145 -0
- package/lib/Utils/sync-action-utils.js +54 -0
- package/lib/Utils/tc-token-utils.js +161 -0
- package/lib/Utils/use-multi-file-auth-state.js +121 -0
- package/lib/Utils/validate-connection.js +219 -0
- package/lib/Utils/view-once-cache.js +79 -0
- package/lib/Utils/voip-rekey.js +22 -0
- package/lib/WABinary/constants.js +1304 -0
- package/lib/WABinary/decode.js +343 -0
- package/lib/WABinary/encode.js +228 -0
- package/lib/WABinary/generic-utils.js +240 -0
- package/lib/WABinary/index.js +33 -0
- package/lib/WABinary/jid-utils.js +361 -0
- package/lib/WABinary/types.js +2 -0
- package/lib/WAM/BinaryInfo.js +13 -0
- package/lib/WAM/constants.js +39486 -0
- package/lib/WAM/encode.js +142 -0
- package/lib/WAM/index.js +31 -0
- package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +55 -0
- package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +43 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +54 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
- package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +59 -0
- package/lib/WAUSync/Protocols/USyncLIDProtocol.js +31 -0
- package/lib/WAUSync/Protocols/USyncPictureProtocol.js +32 -0
- package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +29 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +39 -0
- package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +38 -0
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +27 -0
- package/lib/WAUSync/Protocols/index.js +39 -0
- package/lib/WAUSync/USyncQuery.js +133 -0
- package/lib/WAUSync/USyncUser.js +50 -0
- package/lib/WAUSync/index.js +31 -0
- package/lib/antiban.js +4637 -0
- package/lib/index.js +45 -0
- package/package.json +107 -0
|
@@ -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
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
'use strict'
|
|
2
|
+
Object.defineProperty(exports, '__esModule', { value: true })
|
|
3
|
+
exports.emitSyncActionResults = exports.processContactAction = void 0
|
|
4
|
+
const WABinary_1 = require('../WABinary')
|
|
5
|
+
/**
|
|
6
|
+
* Process contactAction and return events to emit.
|
|
7
|
+
* Pure function - no side effects.
|
|
8
|
+
*/
|
|
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
|
|
@@ -0,0 +1,161 @@
|
|
|
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')
|
|
13
|
+
// Same phone-number pattern as WABinary's isJidBot, applied against the user
|
|
14
|
+
// part so the check is invariant to @c.us ↔ @s.whatsapp.net normalization.
|
|
15
|
+
const BOT_PHONE_REGEX = /^1313555\d{4}$|^131655500\d{2}$/
|
|
16
|
+
/**
|
|
17
|
+
* Mirrors WA Web's `Wid.isRegularUser()` (user ∧ ¬PSA ∧ ¬Bot). Used to gate tctoken
|
|
18
|
+
* storage against malformed notifications — WA Web filters server-side but we
|
|
19
|
+
* defend here for parity with `WAWebSetTcTokenChatAction.handleIncomingTcToken`.
|
|
20
|
+
* Works for both pre- and post-normalized JIDs (`@c.us` vs `@s.whatsapp.net`).
|
|
21
|
+
*/
|
|
22
|
+
function isRegularUser(jid) {
|
|
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
|
+
)
|
|
35
|
+
}
|
|
36
|
+
const TC_TOKEN_BUCKET_DURATION = 604800 // 7 days
|
|
37
|
+
const TC_TOKEN_NUM_BUCKETS = 4 // ~28-day rolling window
|
|
38
|
+
/** Sentinel key under `tctoken` store holding a JSON array of tracked storage JIDs for cross-session pruning. */
|
|
39
|
+
exports.TC_TOKEN_INDEX_KEY = '__index'
|
|
40
|
+
/** Read the persisted tctoken JID index and return its entries (never contains the sentinel key itself). */
|
|
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
|
+
}
|
|
52
|
+
}
|
|
53
|
+
/** Build a SignalDataSet fragment that writes the merged index (persisted ∪ added) under the sentinel key. */
|
|
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
|
+
}
|
|
63
|
+
}
|
|
64
|
+
// WA Web has separate sender/receiver AB props for these but they're identical today
|
|
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
|
|
74
|
+
}
|
|
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
|
|
81
|
+
}
|
|
82
|
+
/** Resolve JID to LID for tctoken storage (WA Web stores under LID) */
|
|
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
|
|
87
|
+
}
|
|
88
|
+
/** Resolve target JID for issuing privacy token based on AB prop 14303 */
|
|
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
|
|
101
|
+
}
|
|
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
|
+
}
|
|
130
|
+
}
|
|
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
|
+
}
|
|
161
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
'use strict'
|
|
2
|
+
Object.defineProperty(exports, '__esModule', { value: true })
|
|
3
|
+
exports.useMultiFileAuthState = void 0
|
|
4
|
+
const async_mutex_1 = require('async-mutex')
|
|
5
|
+
const promises_1 = require('fs/promises')
|
|
6
|
+
const path_1 = require('path')
|
|
7
|
+
const index_js_1 = require('../../WAProto/index.js')
|
|
8
|
+
const auth_utils_1 = require('./auth-utils')
|
|
9
|
+
const generics_1 = require('./generics')
|
|
10
|
+
// We need to lock files due to the fact that we are using async functions to read and write files
|
|
11
|
+
// https://github.com/WhiskeySockets/Baileys/issues/794
|
|
12
|
+
// https://github.com/nodejs/node/issues/26338
|
|
13
|
+
// Use a Map to store mutexes for each file path
|
|
14
|
+
const fileLocks = new Map()
|
|
15
|
+
// Get or create a mutex for a specific file path
|
|
16
|
+
const getFileLock = path => {
|
|
17
|
+
let mutex = fileLocks.get(path)
|
|
18
|
+
if (!mutex) {
|
|
19
|
+
mutex = new async_mutex_1.Mutex()
|
|
20
|
+
fileLocks.set(path, mutex)
|
|
21
|
+
}
|
|
22
|
+
return mutex
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* stores the full authentication state in a single folder.
|
|
26
|
+
* Far more efficient than singlefileauthstate
|
|
27
|
+
*
|
|
28
|
+
* Again, I wouldn't endorse this for any production level use other than perhaps a bot.
|
|
29
|
+
* Would recommend writing an auth state for use with a proper SQL or No-SQL DB
|
|
30
|
+
* */
|
|
31
|
+
const useMultiFileAuthState = async folder => {
|
|
32
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
33
|
+
const writeData = async (data, file) => {
|
|
34
|
+
const filePath = (0, path_1.join)(folder, fixFileName(file))
|
|
35
|
+
const mutex = getFileLock(filePath)
|
|
36
|
+
return mutex.acquire().then(async release => {
|
|
37
|
+
try {
|
|
38
|
+
await (0, promises_1.writeFile)(filePath, JSON.stringify(data, generics_1.BufferJSON.replacer))
|
|
39
|
+
} finally {
|
|
40
|
+
release()
|
|
41
|
+
}
|
|
42
|
+
})
|
|
43
|
+
}
|
|
44
|
+
const readData = async file => {
|
|
45
|
+
try {
|
|
46
|
+
const filePath = (0, path_1.join)(folder, fixFileName(file))
|
|
47
|
+
const mutex = getFileLock(filePath)
|
|
48
|
+
return await mutex.acquire().then(async release => {
|
|
49
|
+
try {
|
|
50
|
+
const data = await (0, promises_1.readFile)(filePath, { encoding: 'utf-8' })
|
|
51
|
+
return JSON.parse(data, generics_1.BufferJSON.reviver)
|
|
52
|
+
} finally {
|
|
53
|
+
release()
|
|
54
|
+
}
|
|
55
|
+
})
|
|
56
|
+
} catch (error) {
|
|
57
|
+
return null
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
const removeData = async file => {
|
|
61
|
+
try {
|
|
62
|
+
const filePath = (0, path_1.join)(folder, fixFileName(file))
|
|
63
|
+
const mutex = getFileLock(filePath)
|
|
64
|
+
return mutex.acquire().then(async release => {
|
|
65
|
+
try {
|
|
66
|
+
await (0, promises_1.unlink)(filePath)
|
|
67
|
+
} catch {
|
|
68
|
+
} finally {
|
|
69
|
+
release()
|
|
70
|
+
}
|
|
71
|
+
})
|
|
72
|
+
} catch {}
|
|
73
|
+
}
|
|
74
|
+
const folderInfo = await (0, promises_1.stat)(folder).catch(() => {})
|
|
75
|
+
if (folderInfo) {
|
|
76
|
+
if (!folderInfo.isDirectory()) {
|
|
77
|
+
throw new Error(
|
|
78
|
+
`found something that is not a directory at ${folder}, either delete it or specify a different location`
|
|
79
|
+
)
|
|
80
|
+
}
|
|
81
|
+
} else {
|
|
82
|
+
await (0, promises_1.mkdir)(folder, { recursive: true })
|
|
83
|
+
}
|
|
84
|
+
const fixFileName = file => file?.replace(/\//g, '__')?.replace(/:/g, '-')
|
|
85
|
+
const creds = (await readData('creds.json')) || (0, auth_utils_1.initAuthCreds)()
|
|
86
|
+
return {
|
|
87
|
+
state: {
|
|
88
|
+
creds,
|
|
89
|
+
keys: {
|
|
90
|
+
get: async (type, ids) => {
|
|
91
|
+
const data = {}
|
|
92
|
+
await Promise.all(
|
|
93
|
+
ids.map(async id => {
|
|
94
|
+
let value = await readData(`${type}-${id}.json`)
|
|
95
|
+
if (type === 'app-state-sync-key' && value) {
|
|
96
|
+
value = index_js_1.proto.Message.AppStateSyncKeyData.fromObject(value)
|
|
97
|
+
}
|
|
98
|
+
data[id] = value
|
|
99
|
+
})
|
|
100
|
+
)
|
|
101
|
+
return data
|
|
102
|
+
},
|
|
103
|
+
set: async data => {
|
|
104
|
+
const tasks = []
|
|
105
|
+
for (const category in data) {
|
|
106
|
+
for (const id in data[category]) {
|
|
107
|
+
const value = data[category][id]
|
|
108
|
+
const file = `${category}-${id}.json`
|
|
109
|
+
tasks.push(value ? writeData(value, file) : removeData(file))
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
await Promise.all(tasks)
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
},
|
|
116
|
+
saveCreds: async () => {
|
|
117
|
+
return writeData(creds, 'creds.json')
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
exports.useMultiFileAuthState = useMultiFileAuthState
|