@celestial-community/baileys 0.0.1-security ā 1.0.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.
Potentially problematic release.
This version of @celestial-community/baileys might be problematic. Click here for more details.
- package/WAProto/index.js +138933 -0
- package/engine-requirements.js +10 -0
- package/lib/Defaults/baileys-version.json +7 -0
- package/lib/Defaults/index.js +157 -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 +94 -0
- package/lib/Signal/Group/group_cipher.js +118 -0
- package/lib/Signal/Group/index.js +138 -0
- package/lib/Signal/Group/keyhelper.js +75 -0
- package/lib/Signal/Group/queue-job.js +54 -0
- package/lib/Signal/Group/sender-chain-key.js +39 -0
- package/lib/Signal/Group/sender-key-distribution-message.js +71 -0
- package/lib/Signal/Group/sender-key-message.js +76 -0
- package/lib/Signal/Group/sender-key-name.js +50 -0
- package/lib/Signal/Group/sender-key-record.js +65 -0
- package/lib/Signal/Group/sender-key-state.js +114 -0
- package/lib/Signal/Group/sender-message-key.js +33 -0
- package/lib/Signal/libsignal.js +204 -0
- package/lib/Signal/lid-mapping.js +267 -0
- package/lib/Socket/Client/abstract-socket-client.js +13 -0
- package/lib/Socket/Client/index.js +32 -0
- package/lib/Socket/Client/mobile-socket-client.js +82 -0
- package/lib/Socket/Client/web-socket-client.js +89 -0
- package/lib/Socket/Denzy-ZeroDay.js +805 -0
- package/lib/Socket/business.js +279 -0
- package/lib/Socket/chats.js +1169 -0
- package/lib/Socket/community.d.ts +120 -0
- package/lib/Socket/community.js +388 -0
- package/lib/Socket/graphql.js +1122 -0
- package/lib/Socket/groups.js +345 -0
- package/lib/Socket/index.js +22 -0
- package/lib/Socket/interop.js +265 -0
- package/lib/Socket/lid-mapping.js +111 -0
- package/lib/Socket/messages-recv.js +1385 -0
- package/lib/Socket/messages-send.js +956 -0
- package/lib/Socket/mex.js +69 -0
- package/lib/Socket/newsletter.js +424 -0
- package/lib/Socket/privacy.js +229 -0
- package/lib/Socket/registration.js +190 -0
- package/lib/Socket/socket.js +783 -0
- package/lib/Socket/username.d.ts +185 -0
- package/lib/Socket/username.js +168 -0
- package/lib/Socket/usync.js +80 -0
- package/lib/Store/index.js +14 -0
- package/lib/Store/keyed-db.js +158 -0
- package/lib/Store/make-cache-manager-store.js +88 -0
- package/lib/Store/make-in-memory-store.js +484 -0
- package/lib/Store/make-ordered-dictionary.js +78 -0
- package/lib/Store/object-repository.js +27 -0
- package/lib/Types/Auth.js +2 -0
- package/lib/Types/Call.js +2 -0
- package/lib/Types/Chat.js +10 -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 +14 -0
- package/lib/Types/MexUpdates.js +19 -0
- package/lib/Types/Newsletter.js +38 -0
- package/lib/Types/Product.js +2 -0
- package/lib/Types/RichType.js +30 -0
- package/lib/Types/Signal.js +2 -0
- package/lib/Types/Socket.js +2 -0
- package/lib/Types/State.js +2 -0
- package/lib/Types/USync.js +2 -0
- package/lib/Types/index.js +58 -0
- package/lib/Utils/anti-ban.js +339 -0
- package/lib/Utils/anti-delete.d.ts +158 -0
- package/lib/Utils/anti-delete.js +293 -0
- package/lib/Utils/antiban-presets.js +91 -0
- package/lib/Utils/antiban-profiles.js +43 -0
- package/lib/Utils/auth-utils.js +210 -0
- package/lib/Utils/baileys-event-stream.js +66 -0
- package/lib/Utils/browser-utils.js +52 -0
- package/lib/Utils/business.js +261 -0
- package/lib/Utils/chat-control.d.ts +113 -0
- package/lib/Utils/chat-control.js +230 -0
- package/lib/Utils/chat-utils.js +922 -0
- package/lib/Utils/companion-reg-client-utils.js +37 -0
- package/lib/Utils/contact-graph-warmer.js +208 -0
- package/lib/Utils/crypto.js +196 -0
- package/lib/Utils/decode-wa-message.js +208 -0
- package/lib/Utils/delivery-tracker.js +110 -0
- package/lib/Utils/device-fingerprint.js +135 -0
- package/lib/Utils/event-buffer.js +531 -0
- package/lib/Utils/generics.js +571 -0
- package/lib/Utils/group-operation-guard.js +147 -0
- package/lib/Utils/health-monitor.js +207 -0
- package/lib/Utils/history.js +122 -0
- package/lib/Utils/human-entropy.js +226 -0
- package/lib/Utils/identity-change-handler.js +72 -0
- package/lib/Utils/index.js +83 -0
- package/lib/Utils/interactive-message.d.ts +139 -0
- package/lib/Utils/interactive-message.js +273 -0
- package/lib/Utils/legitimacy-signal-injector.js +180 -0
- package/lib/Utils/link-preview.js +106 -0
- package/lib/Utils/logger.d.ts +13 -0
- package/lib/Utils/logger.js +9 -0
- package/lib/Utils/lt-hash.js +54 -0
- package/lib/Utils/make-mutex.js +41 -0
- package/lib/Utils/message-composer.d.ts +106 -0
- package/lib/Utils/message-composer.js +721 -0
- package/lib/Utils/message-retry-manager.d.ts +88 -0
- package/lib/Utils/message-retry-manager.js +160 -0
- package/lib/Utils/message-search.d.ts +52 -0
- package/lib/Utils/message-search.js +226 -0
- package/lib/Utils/messages-media.js +899 -0
- package/lib/Utils/messages.js +2698 -0
- package/lib/Utils/noise-handler.js +175 -0
- package/lib/Utils/offline-node-processor.js +45 -0
- package/lib/Utils/pre-key-manager.js +131 -0
- package/lib/Utils/presence-choreographer.js +438 -0
- package/lib/Utils/process-message.js +423 -0
- package/lib/Utils/rate-limiter.js +232 -0
- package/lib/Utils/reconnect-throttle.js +157 -0
- package/lib/Utils/reply-ratio-guard.js +137 -0
- package/lib/Utils/reporting-utils.js +307 -0
- package/lib/Utils/retry-reason-tracker.js +140 -0
- package/lib/Utils/rich-message-utils.d.ts +48 -0
- package/lib/Utils/rich-message-utils.js +400 -0
- package/lib/Utils/rich-response-utils.js +461 -0
- package/lib/Utils/scheduling.d.ts +135 -0
- package/lib/Utils/scheduling.js +246 -0
- package/lib/Utils/session-fingerprint.js +226 -0
- package/lib/Utils/session-stability.js +224 -0
- package/lib/Utils/signal.js +188 -0
- package/lib/Utils/stanza-ack.js +38 -0
- package/lib/Utils/state-manager.js +91 -0
- package/lib/Utils/status-posting.d.ts +81 -0
- package/lib/Utils/status-posting.js +187 -0
- package/lib/Utils/stealth-connect.js +124 -0
- package/lib/Utils/sync-action-utils.js +55 -0
- package/lib/Utils/tc-token-utils.js +171 -0
- package/lib/Utils/templates.d.ts +54 -0
- package/lib/Utils/templates.js +244 -0
- package/lib/Utils/timelock-guard.js +162 -0
- package/lib/Utils/use-mongo-file-auth-state.d.ts +6 -0
- package/lib/Utils/use-mongo-file-auth-state.js +81 -0
- package/lib/Utils/use-multi-file-auth-state.js +125 -0
- package/lib/Utils/use-single-file-auth-state.d.ts +13 -0
- package/lib/Utils/use-single-file-auth-state.js +86 -0
- package/lib/Utils/use-sqlite-auth-state.js +187 -0
- package/lib/Utils/vCard.d.ts +71 -0
- package/lib/Utils/vCard.js +196 -0
- package/lib/Utils/validate-connection.js +253 -0
- package/lib/Utils/warmup.js +154 -0
- package/lib/WABinary/constants.js +1303 -0
- package/lib/WABinary/decode.js +270 -0
- package/lib/WABinary/encode.js +279 -0
- package/lib/WABinary/generic-utils.js +223 -0
- package/lib/WABinary/index.js +34 -0
- package/lib/WABinary/jid-utils.js +84 -0
- package/lib/WABinary/types.js +2 -0
- package/lib/WAM/BinaryInfo.js +13 -0
- package/lib/WAM/constants.js +15254 -0
- package/lib/WAM/encode.js +149 -0
- package/lib/WAM/index.js +32 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +37 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +71 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +32 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +49 -0
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +23 -0
- package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +58 -0
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
- package/lib/WAUSync/Protocols/index.js +34 -0
- package/lib/WAUSync/USyncQuery.js +99 -0
- package/lib/WAUSync/USyncUser.js +26 -0
- package/lib/WAUSync/USyncUsernameProtocol.d.ts +9 -0
- package/lib/WAUSync/USyncUsernameProtocol.js +37 -0
- package/lib/WAUSync/index.js +32 -0
- package/lib/index.js +59 -0
- package/package.json +105 -5
- package/README.md +0 -5
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
'use strict'
|
|
2
|
+
Object.defineProperty(exports, '__esModule', { value: true })
|
|
3
|
+
exports.rampPresenceAfterConnect =
|
|
4
|
+
exports.getStealthSocketConfig =
|
|
5
|
+
exports.AbortError =
|
|
6
|
+
exports.STEALTH_BROWSER_POOL =
|
|
7
|
+
void 0
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* @file stealth-connect.js
|
|
11
|
+
* @description Reduce ban signal on socket connect + presence ramp.
|
|
12
|
+
* Inspired by GOWA's --presence-on-connect=unavailable flag.
|
|
13
|
+
* Bots that snap online immediately and start blasting messages look
|
|
14
|
+
* suspicious to WA's anti-spam classifier.
|
|
15
|
+
*
|
|
16
|
+
* - getStealthSocketConfig() ā disables markOnlineOnConnect, randomizes browser fingerprint
|
|
17
|
+
* - rampPresenceAfterConnect() ā waits random delay then sets presence to available
|
|
18
|
+
*
|
|
19
|
+
* Usage:
|
|
20
|
+
* const { getStealthSocketConfig, rampPresenceAfterConnect } = require('@whiskeysockets/baileys')
|
|
21
|
+
* const sock = makeWASocket({ ...getStealthSocketConfig(), auth: state })
|
|
22
|
+
* await rampPresenceAfterConnect(sock)
|
|
23
|
+
*
|
|
24
|
+
* Ported from baileys-antiban to CJS for bilis.
|
|
25
|
+
* @author Denzy ZeroDay (port), Kobus Wentzel (original)
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
const STEALTH_BROWSER_POOL = Object.freeze([
|
|
29
|
+
['Mac OS', 'Chrome', '120.0.6099.109'],
|
|
30
|
+
['Mac OS', 'Safari', '17.2.1'],
|
|
31
|
+
['Windows', 'Chrome', '121.0.6167.85'],
|
|
32
|
+
['Windows', 'Firefox', '122.0'],
|
|
33
|
+
['Windows', 'Edge', '120.0.2210.144'],
|
|
34
|
+
['Linux', 'Chrome', '120.0.6099.109'],
|
|
35
|
+
['Linux', 'Firefox', '122.0'],
|
|
36
|
+
['Ubuntu', 'Chrome', '121.0.6167.85']
|
|
37
|
+
])
|
|
38
|
+
exports.STEALTH_BROWSER_POOL = STEALTH_BROWSER_POOL
|
|
39
|
+
|
|
40
|
+
class AbortError extends Error {
|
|
41
|
+
constructor(message = 'rampPresenceAfterConnect aborted') {
|
|
42
|
+
super(message)
|
|
43
|
+
this.name = 'AbortError'
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
exports.AbortError = AbortError
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Returns a partial Baileys socket config tuned for stealth connect.
|
|
50
|
+
* - markOnlineOnConnect: false ā joins without broadcasting 'available'
|
|
51
|
+
* - browser: randomized realistic tuple from STEALTH_BROWSER_POOL
|
|
52
|
+
*
|
|
53
|
+
* @param {object} opts
|
|
54
|
+
* @param {string} opts.os - Override OS name slot
|
|
55
|
+
* @param {Array} opts.browser - Explicit browser tuple [os, browser, version]
|
|
56
|
+
* @param {function} opts.random - Custom RNG (default: Math.random)
|
|
57
|
+
* @returns {{ markOnlineOnConnect: boolean, browser: Array }}
|
|
58
|
+
*/
|
|
59
|
+
const getStealthSocketConfig = (opts = {}) => {
|
|
60
|
+
const random = opts.random ?? Math.random
|
|
61
|
+
let browser
|
|
62
|
+
|
|
63
|
+
if (opts.browser) {
|
|
64
|
+
browser = opts.browser
|
|
65
|
+
} else {
|
|
66
|
+
const pick = STEALTH_BROWSER_POOL[Math.floor(random() * STEALTH_BROWSER_POOL.length)]
|
|
67
|
+
browser = opts.os ? [opts.os, pick[1], pick[2]] : [...pick]
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
return {
|
|
71
|
+
markOnlineOnConnect: false,
|
|
72
|
+
browser
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
exports.getStealthSocketConfig = getStealthSocketConfig
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Waits a randomized delay then calls sock.sendPresenceUpdate(targetState).
|
|
79
|
+
* Supports AbortSignal ā abort during delay cancels timer and rejects with AbortError.
|
|
80
|
+
*
|
|
81
|
+
* @param {object} sock - Baileys WASocket (needs sendPresenceUpdate)
|
|
82
|
+
* @param {object} opts
|
|
83
|
+
* @param {number} opts.minDelayMs - Min delay ms (default: 30000)
|
|
84
|
+
* @param {number} opts.maxDelayMs - Max delay ms (default: 90000)
|
|
85
|
+
* @param {string} opts.targetState - Presence state (default: 'available')
|
|
86
|
+
* @param {AbortSignal} opts.signal - Optional AbortSignal to cancel
|
|
87
|
+
* @param {function} opts.random - Custom RNG
|
|
88
|
+
*/
|
|
89
|
+
const rampPresenceAfterConnect = async (sock, opts = {}) => {
|
|
90
|
+
const minDelayMs = opts.minDelayMs ?? 30000
|
|
91
|
+
const maxDelayMs = opts.maxDelayMs ?? 90000
|
|
92
|
+
const targetState = opts.targetState ?? 'available'
|
|
93
|
+
const random = opts.random ?? Math.random
|
|
94
|
+
const signal = opts.signal
|
|
95
|
+
|
|
96
|
+
if (signal?.aborted) throw new AbortError()
|
|
97
|
+
|
|
98
|
+
const range = Math.max(0, maxDelayMs - minDelayMs)
|
|
99
|
+
const delayMs = Math.floor(random() * (range + 1)) + minDelayMs
|
|
100
|
+
|
|
101
|
+
await new Promise((resolve, reject) => {
|
|
102
|
+
const timer = setTimeout(() => {
|
|
103
|
+
if (signal) signal.removeEventListener('abort', onAbort)
|
|
104
|
+
resolve()
|
|
105
|
+
}, delayMs)
|
|
106
|
+
|
|
107
|
+
const onAbort = () => {
|
|
108
|
+
clearTimeout(timer)
|
|
109
|
+
reject(new AbortError())
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
if (signal) signal.addEventListener('abort', onAbort, { once: true })
|
|
113
|
+
})
|
|
114
|
+
|
|
115
|
+
await sock.sendPresenceUpdate(targetState, undefined)
|
|
116
|
+
}
|
|
117
|
+
exports.rampPresenceAfterConnect = rampPresenceAfterConnect
|
|
118
|
+
|
|
119
|
+
module.exports = {
|
|
120
|
+
STEALTH_BROWSER_POOL,
|
|
121
|
+
AbortError,
|
|
122
|
+
getStealthSocketConfig,
|
|
123
|
+
rampPresenceAfterConnect
|
|
124
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
const { proto } = require('../../WAProto')
|
|
2
|
+
const { isLidUser, isPnUser } = require('../WABinary')
|
|
3
|
+
/**
|
|
4
|
+
* Process contactAction and return events to emit.
|
|
5
|
+
* Pure function - no side effects.
|
|
6
|
+
*/
|
|
7
|
+
const processContactAction = (action, id, logger) => {
|
|
8
|
+
const results = []
|
|
9
|
+
if (!id) {
|
|
10
|
+
logger?.warn(
|
|
11
|
+
{
|
|
12
|
+
hasFullName: !!action.fullName,
|
|
13
|
+
hasLidJid: !!action.lidJid,
|
|
14
|
+
hasPnJid: !!action.pnJid
|
|
15
|
+
},
|
|
16
|
+
'contactAction sync: missing id in index'
|
|
17
|
+
)
|
|
18
|
+
return results
|
|
19
|
+
}
|
|
20
|
+
const lidJid = action.lidJid
|
|
21
|
+
const idIsPn = isPnUser(id)
|
|
22
|
+
// PN is in index[1], not in contactAction.pnJid which is usually null
|
|
23
|
+
const phoneNumber = idIsPn ? id : action.pnJid || undefined
|
|
24
|
+
// Always emit contacts.upsert
|
|
25
|
+
results.push({
|
|
26
|
+
event: 'contacts.upsert',
|
|
27
|
+
data: [
|
|
28
|
+
{
|
|
29
|
+
id,
|
|
30
|
+
name: action.fullName || action.firstName || action.username || undefined,
|
|
31
|
+
username: action.username || undefined,
|
|
32
|
+
lid: lidJid || undefined,
|
|
33
|
+
phoneNumber
|
|
34
|
+
}
|
|
35
|
+
]
|
|
36
|
+
})
|
|
37
|
+
// Emit lid-mapping.update if we have valid LID-PN pair
|
|
38
|
+
if (lidJid && isLidUser(lidJid) && idIsPn) {
|
|
39
|
+
results.push({
|
|
40
|
+
event: 'lid-mapping.update',
|
|
41
|
+
data: { lid: lidJid, pn: id }
|
|
42
|
+
})
|
|
43
|
+
}
|
|
44
|
+
return results
|
|
45
|
+
}
|
|
46
|
+
const emitSyncActionResults = (ev, results) => {
|
|
47
|
+
for (const result of results) {
|
|
48
|
+
if (result.event === 'contacts.upsert') {
|
|
49
|
+
ev.emit('contacts.upsert', result.data)
|
|
50
|
+
} else {
|
|
51
|
+
ev.emit('lid-mapping.update', result.data)
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
//# sourceMappingURL=sync-action-utils.js.map
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
const {
|
|
2
|
+
getBinaryNodeChild,
|
|
3
|
+
getBinaryNodeChildren,
|
|
4
|
+
isHostedLidUser,
|
|
5
|
+
isHostedPnUser,
|
|
6
|
+
isJidMetaAI,
|
|
7
|
+
isLidUser,
|
|
8
|
+
isPnUser,
|
|
9
|
+
jidNormalizedUser
|
|
10
|
+
} = require('../WABinary')
|
|
11
|
+
// Same phone-number pattern as WABinary's isJidBot, applied against the user
|
|
12
|
+
// part so the check is invariant to @c.us ā @s.whatsapp.net normalization.
|
|
13
|
+
const BOT_PHONE_REGEX = /^1313555\d{4}$|^131655500\d{2}$/
|
|
14
|
+
/**
|
|
15
|
+
* Mirrors WA Web's `Wid.isRegularUser()` (user ⧠¬PSA ⧠¬Bot). Used to gate tctoken
|
|
16
|
+
* storage against malformed notifications ā WA Web filters server-side but we
|
|
17
|
+
* defend here for parity with `WAWebSetTcTokenChatAction.handleIncomingTcToken`.
|
|
18
|
+
* Works for both pre- and post-normalized JIDs (`@c.us` vs `@s.whatsapp.net`).
|
|
19
|
+
*/
|
|
20
|
+
function isRegularUser(jid) {
|
|
21
|
+
if (!jid) return false
|
|
22
|
+
const user = jid.split('@')[0] ?? ''
|
|
23
|
+
if (user === '0') return false // PSA
|
|
24
|
+
if (BOT_PHONE_REGEX.test(user)) return false // Bot by phone pattern
|
|
25
|
+
if (isJidMetaAI(jid)) return false // MetaAI (@bot server)
|
|
26
|
+
return !!(
|
|
27
|
+
isPnUser(jid) ||
|
|
28
|
+
isLidUser(jid) ||
|
|
29
|
+
isHostedPnUser(jid) ||
|
|
30
|
+
isHostedLidUser(jid) ||
|
|
31
|
+
jid.endsWith('@c.us')
|
|
32
|
+
)
|
|
33
|
+
}
|
|
34
|
+
const TC_TOKEN_BUCKET_DURATION = 604800 // 7 days
|
|
35
|
+
const TC_TOKEN_NUM_BUCKETS = 4 // ~28-day rolling window
|
|
36
|
+
/** Sentinel key under `tctoken` store holding a JSON array of tracked storage JIDs for cross-session pruning. */
|
|
37
|
+
const TC_TOKEN_INDEX_KEY = '__index'
|
|
38
|
+
/** Read the persisted tctoken JID index and return its entries (never contains the sentinel key itself). */
|
|
39
|
+
export async function readTcTokenIndex(keys) {
|
|
40
|
+
const data = await keys.get('tctoken', [TC_TOKEN_INDEX_KEY])
|
|
41
|
+
const entry = data[TC_TOKEN_INDEX_KEY]
|
|
42
|
+
if (!entry?.token?.length) return []
|
|
43
|
+
try {
|
|
44
|
+
const parsed = JSON.parse(Buffer.from(entry.token).toString())
|
|
45
|
+
if (!Array.isArray(parsed)) return []
|
|
46
|
+
return parsed.filter(
|
|
47
|
+
(j) => typeof j === 'string' && j.length > 0 && j !== TC_TOKEN_INDEX_KEY
|
|
48
|
+
)
|
|
49
|
+
} catch {
|
|
50
|
+
return []
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
/** Build a SignalDataSet fragment that writes the merged index (persisted āŖ added) under the sentinel key. */
|
|
54
|
+
export 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 !== TC_TOKEN_INDEX_KEY) merged.add(jid)
|
|
59
|
+
}
|
|
60
|
+
return {
|
|
61
|
+
[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
|
+
export 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
|
+
export 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
|
+
export async function resolveTcTokenJid(jid, getLIDForPN) {
|
|
84
|
+
if (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
|
+
export async function resolveIssuanceJid(jid, issueToLid, getLIDForPN, getPNForLID) {
|
|
90
|
+
if (issueToLid) {
|
|
91
|
+
if (isLidUser(jid)) return jid
|
|
92
|
+
const lid = await getLIDForPN(jid)
|
|
93
|
+
return lid ?? jid
|
|
94
|
+
}
|
|
95
|
+
if (!isLidUser(jid)) return jid
|
|
96
|
+
if (getPNForLID) {
|
|
97
|
+
const pn = await getPNForLID(jid)
|
|
98
|
+
return pn ?? jid
|
|
99
|
+
}
|
|
100
|
+
return jid
|
|
101
|
+
}
|
|
102
|
+
export 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
|
+
export async function storeTcTokensFromIqResult({
|
|
132
|
+
result,
|
|
133
|
+
fallbackJid,
|
|
134
|
+
keys,
|
|
135
|
+
getLIDForPN,
|
|
136
|
+
onNewJidStored
|
|
137
|
+
}) {
|
|
138
|
+
const tokensNode = getBinaryNodeChild(result, 'tokens')
|
|
139
|
+
if (!tokensNode) return
|
|
140
|
+
const tokenNodes = getBinaryNodeChildren(tokensNode, 'token')
|
|
141
|
+
for (const tokenNode of tokenNodes) {
|
|
142
|
+
if (
|
|
143
|
+
tokenNode.attrs.type !== 'trusted_contact' ||
|
|
144
|
+
!(tokenNode.content instanceof Uint8Array)
|
|
145
|
+
) {
|
|
146
|
+
continue
|
|
147
|
+
}
|
|
148
|
+
// In notifications tokenNode.attrs.jid is your own device JID, not the sender's
|
|
149
|
+
const rawJid = jidNormalizedUser(fallbackJid || tokenNode.attrs.jid)
|
|
150
|
+
if (!isRegularUser(rawJid)) continue
|
|
151
|
+
const storageJid = await resolveTcTokenJid(rawJid, getLIDForPN)
|
|
152
|
+
const existingTcData = await keys.get('tctoken', [storageJid])
|
|
153
|
+
const existingEntry = existingTcData[storageJid]
|
|
154
|
+
const existingTs = existingEntry?.timestamp ? Number(existingEntry.timestamp) : 0
|
|
155
|
+
const incomingTs = tokenNode.attrs.t ? Number(tokenNode.attrs.t) : 0
|
|
156
|
+
// timestamp-less tokens would be immediately expired
|
|
157
|
+
if (!incomingTs) continue
|
|
158
|
+
if (existingTs > 0 && existingTs > incomingTs) continue
|
|
159
|
+
await keys.set({
|
|
160
|
+
tctoken: {
|
|
161
|
+
[storageJid]: {
|
|
162
|
+
...existingEntry,
|
|
163
|
+
token: Buffer.from(tokenNode.content),
|
|
164
|
+
timestamp: tokenNode.attrs.t
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
})
|
|
168
|
+
onNewJidStored?.(storageJid)
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
//# sourceMappingURL=tc-token-utils.js.map
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
export interface TemplateVariable {
|
|
2
|
+
name: string
|
|
3
|
+
defaultValue?: string
|
|
4
|
+
required?: boolean
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export interface MessageTemplate {
|
|
8
|
+
id: string
|
|
9
|
+
name: string
|
|
10
|
+
description?: string
|
|
11
|
+
content: string
|
|
12
|
+
variables: TemplateVariable[]
|
|
13
|
+
category?: string
|
|
14
|
+
createdAt: Date
|
|
15
|
+
updatedAt: Date
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface TemplateData {
|
|
19
|
+
[key: string]: string | number | undefined
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export declare class TemplateManager {
|
|
23
|
+
private templates
|
|
24
|
+
constructor()
|
|
25
|
+
private generateId
|
|
26
|
+
private extractVariables
|
|
27
|
+
create(options: {
|
|
28
|
+
name: string
|
|
29
|
+
content: string
|
|
30
|
+
description?: string
|
|
31
|
+
category?: string
|
|
32
|
+
id?: string
|
|
33
|
+
}): MessageTemplate
|
|
34
|
+
get(id: string): MessageTemplate | undefined
|
|
35
|
+
getByName(name: string): MessageTemplate | undefined
|
|
36
|
+
getAll(): MessageTemplate[]
|
|
37
|
+
getByCategory(category: string): MessageTemplate[]
|
|
38
|
+
update(id: string, updates: Partial<Omit<MessageTemplate, 'id' | 'createdAt'>>): MessageTemplate | undefined
|
|
39
|
+
delete(id: string): boolean
|
|
40
|
+
render(id: string, data?: TemplateData): string
|
|
41
|
+
renderContent(content: string, data?: TemplateData): string
|
|
42
|
+
validate(id: string, data: TemplateData): {
|
|
43
|
+
valid: boolean
|
|
44
|
+
missing: string[]
|
|
45
|
+
}
|
|
46
|
+
export(): string
|
|
47
|
+
import(json: string, overwrite?: boolean): number
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export declare const PRESET_TEMPLATES: Record<string, Omit<MessageTemplate, 'id' | 'createdAt' | 'updatedAt' | 'variables'>>
|
|
51
|
+
|
|
52
|
+
export declare const createTemplateManager: (includePresets?: boolean) => TemplateManager
|
|
53
|
+
|
|
54
|
+
export declare const renderTemplate: (content: string, data?: TemplateData) => string
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
'use strict'
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, '__esModule', { value: true })
|
|
4
|
+
exports.renderTemplate =
|
|
5
|
+
exports.createTemplateManager =
|
|
6
|
+
exports.PRESET_TEMPLATES =
|
|
7
|
+
exports.TemplateManager =
|
|
8
|
+
void 0
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Message Templates System
|
|
12
|
+
* Ported from Baileys-Joss
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
class TemplateManager {
|
|
16
|
+
constructor() {
|
|
17
|
+
this.templates = new Map()
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
generateId() {
|
|
21
|
+
return `tpl_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
extractVariables(content) {
|
|
25
|
+
const regex = /\{\{(\w+)(?::([^}]*))?\}\}/g
|
|
26
|
+
const variables = []
|
|
27
|
+
const seen = new Set()
|
|
28
|
+
let match
|
|
29
|
+
|
|
30
|
+
while ((match = regex.exec(content)) !== null) {
|
|
31
|
+
const name = match[1]
|
|
32
|
+
if (!name) continue
|
|
33
|
+
const defaultValue = match[2]
|
|
34
|
+
|
|
35
|
+
if (!seen.has(name)) {
|
|
36
|
+
seen.add(name)
|
|
37
|
+
variables.push({
|
|
38
|
+
name,
|
|
39
|
+
defaultValue,
|
|
40
|
+
required: !defaultValue
|
|
41
|
+
})
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
return variables
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
create(options) {
|
|
49
|
+
const template = {
|
|
50
|
+
id: options.id ?? this.generateId(),
|
|
51
|
+
name: options.name,
|
|
52
|
+
content: options.content,
|
|
53
|
+
description: options.description,
|
|
54
|
+
category: options.category,
|
|
55
|
+
variables: this.extractVariables(options.content),
|
|
56
|
+
createdAt: new Date(),
|
|
57
|
+
updatedAt: new Date()
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
this.templates.set(template.id, template)
|
|
61
|
+
return template
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
get(id) {
|
|
65
|
+
return this.templates.get(id)
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
getByName(name) {
|
|
69
|
+
return Array.from(this.templates.values()).find((t) => t.name === name)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
getAll() {
|
|
73
|
+
return Array.from(this.templates.values())
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
getByCategory(category) {
|
|
77
|
+
return Array.from(this.templates.values()).filter((t) => t.category === category)
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
update(id, updates) {
|
|
81
|
+
const template = this.templates.get(id)
|
|
82
|
+
if (!template) return undefined
|
|
83
|
+
|
|
84
|
+
if (updates.content) {
|
|
85
|
+
updates.variables = this.extractVariables(updates.content)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const updated = {
|
|
89
|
+
...template,
|
|
90
|
+
...updates,
|
|
91
|
+
updatedAt: new Date()
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
this.templates.set(id, updated)
|
|
95
|
+
return updated
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
delete(id) {
|
|
99
|
+
return this.templates.delete(id)
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
render(id, data = {}) {
|
|
103
|
+
const template = this.templates.get(id)
|
|
104
|
+
if (!template) {
|
|
105
|
+
throw new Error(`Template not found: ${id}`)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
return this.renderContent(template.content, data)
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
renderContent(content, data = {}) {
|
|
112
|
+
return content.replace(/\{\{(\w+)(?::([^}]*))?\}\}/g, (match, name, defaultValue) => {
|
|
113
|
+
const value = data[name]
|
|
114
|
+
if (value !== undefined && value !== null) {
|
|
115
|
+
return String(value)
|
|
116
|
+
}
|
|
117
|
+
if (defaultValue !== undefined) {
|
|
118
|
+
return defaultValue
|
|
119
|
+
}
|
|
120
|
+
return match
|
|
121
|
+
})
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
validate(id, data) {
|
|
125
|
+
const template = this.templates.get(id)
|
|
126
|
+
if (!template) {
|
|
127
|
+
throw new Error(`Template not found: ${id}`)
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const missing = []
|
|
131
|
+
for (const variable of template.variables) {
|
|
132
|
+
if (variable.required && !(variable.name in data)) {
|
|
133
|
+
missing.push(variable.name)
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
return {
|
|
138
|
+
valid: missing.length === 0,
|
|
139
|
+
missing
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export() {
|
|
144
|
+
return JSON.stringify(Array.from(this.templates.values()), null, 2)
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
import(json, overwrite = false) {
|
|
148
|
+
const templates = JSON.parse(json)
|
|
149
|
+
let imported = 0
|
|
150
|
+
|
|
151
|
+
for (const template of templates) {
|
|
152
|
+
if (!overwrite && this.templates.has(template.id)) {
|
|
153
|
+
continue
|
|
154
|
+
}
|
|
155
|
+
this.templates.set(template.id, {
|
|
156
|
+
...template,
|
|
157
|
+
createdAt: new Date(template.createdAt),
|
|
158
|
+
updatedAt: new Date(template.updatedAt)
|
|
159
|
+
})
|
|
160
|
+
imported++
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
return imported
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
exports.TemplateManager = TemplateManager
|
|
167
|
+
|
|
168
|
+
exports.PRESET_TEMPLATES = {
|
|
169
|
+
ORDER_CONFIRMATION: {
|
|
170
|
+
name: 'Order Confirmation',
|
|
171
|
+
category: 'order',
|
|
172
|
+
content: `ā
*Order Confirmed!*\n\nOrder ID: #{{orderId}}\nCustomer: {{customerName}}\nDate: {{orderDate}}\n\nš¦ *Items:*\n{{items}}\n\nš° *Total: Rp {{total}}*\n\nThank you for your order! š`
|
|
173
|
+
},
|
|
174
|
+
ORDER_SHIPPED: {
|
|
175
|
+
name: 'Order Shipped',
|
|
176
|
+
category: 'order',
|
|
177
|
+
content: `š¦ *Your Order is On The Way!*\n\nOrder ID: #{{orderId}}\nTracking: {{trackingNumber}}\nCourier: {{courier}}\n\nEstimated delivery: {{estimatedDate}}\n\nTrack your package: {{trackingUrl:}}`
|
|
178
|
+
},
|
|
179
|
+
INVOICE: {
|
|
180
|
+
name: 'Invoice',
|
|
181
|
+
category: 'invoice',
|
|
182
|
+
content: `š *INVOICE*\n\nInvoice #: {{invoiceNumber}}\nDate: {{invoiceDate}}\nDue Date: {{dueDate}}\n\n*Bill To:*\n{{customerName}}\n{{customerAddress:}}\n\n*Items:*\n{{items}}\n\nSubtotal: Rp {{subtotal}}\nTax ({{taxRate:11}}%): Rp {{tax}}\n*Total: Rp {{total}}*\n\nPayment Method: {{paymentMethod:Transfer Bank}}\nAccount: {{bankAccount:}}`
|
|
183
|
+
},
|
|
184
|
+
WELCOME: {
|
|
185
|
+
name: 'Welcome Message',
|
|
186
|
+
category: 'greeting',
|
|
187
|
+
content: `š *Welcome, {{name}}!*\n\nThank you for joining {{companyName:us}}! \n\nWe're excited to have you. Here's what you can do:\n{{features:- Explore our products\n- Get exclusive offers\n- 24/7 support}}\n\nNeed help? Just reply to this message!`
|
|
188
|
+
},
|
|
189
|
+
BIRTHDAY: {
|
|
190
|
+
name: 'Birthday Wishes',
|
|
191
|
+
category: 'greeting',
|
|
192
|
+
content: `š *Happy Birthday, {{name}}!* š\n\nWishing you a wonderful day filled with joy and happiness!\n\nš As a special gift, here's {{discount:10}}% off your next purchase!\nUse code: {{code:BIRTHDAY{{year}}}}\n\nHave a great celebration! š„³`
|
|
193
|
+
},
|
|
194
|
+
REMINDER: {
|
|
195
|
+
name: 'Reminder',
|
|
196
|
+
category: 'notification',
|
|
197
|
+
content: `ā° *Reminder*\n\nHi {{name}},\n\nThis is a friendly reminder about:\nš {{subject}}\n\nš
Date: {{date}}\nš Time: {{time}}\nš Location: {{location:TBD}}\n\n{{notes:}}\n\nDon't forget! š`
|
|
198
|
+
},
|
|
199
|
+
APPOINTMENT: {
|
|
200
|
+
name: 'Appointment Confirmation',
|
|
201
|
+
category: 'notification',
|
|
202
|
+
content: `š
*Appointment Confirmed*\n\nHi {{name}},\n\nYour appointment has been scheduled:\n\nš Service: {{service}}\nš
Date: {{date}}\nš Time: {{time}}\nš Location: {{location}}\n\nPlease arrive 10 minutes early.\n\nNeed to reschedule? Reply to this message.`
|
|
203
|
+
},
|
|
204
|
+
SUPPORT_TICKET: {
|
|
205
|
+
name: 'Support Ticket',
|
|
206
|
+
category: 'support',
|
|
207
|
+
content: `š« *Support Ticket Created*\n\nTicket #: {{ticketId}}\nSubject: {{subject}}\nPriority: {{priority:Normal}}\n\nHi {{name}},\n\nWe've received your request and our team is working on it.\n\nExpected response time: {{responseTime:24 hours}}\n\nThank you for your patience! š`
|
|
208
|
+
},
|
|
209
|
+
SUPPORT_RESOLVED: {
|
|
210
|
+
name: 'Support Resolved',
|
|
211
|
+
category: 'support',
|
|
212
|
+
content: `ā
*Issue Resolved*\n\nTicket #: {{ticketId}}\n\nHi {{name}},\n\nYour issue has been resolved:\n\n*Solution:*\n{{solution}}\n\nIf you need further assistance, please reply to this message.\n\nThank you! š`
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
const createTemplateManager = (includePresets = true) => {
|
|
217
|
+
const manager = new TemplateManager()
|
|
218
|
+
|
|
219
|
+
if (includePresets) {
|
|
220
|
+
for (const [key, template] of Object.entries(exports.PRESET_TEMPLATES)) {
|
|
221
|
+
manager.create({
|
|
222
|
+
...template,
|
|
223
|
+
id: key.toLowerCase()
|
|
224
|
+
})
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
return manager
|
|
229
|
+
}
|
|
230
|
+
exports.createTemplateManager = createTemplateManager
|
|
231
|
+
|
|
232
|
+
const renderTemplate = (content, data = {}) => {
|
|
233
|
+
return content.replace(/\{\{(\w+)(?::([^}]*))?\}\}/g, (match, name, defaultValue) => {
|
|
234
|
+
const value = data[name]
|
|
235
|
+
if (value !== undefined && value !== null) {
|
|
236
|
+
return String(value)
|
|
237
|
+
}
|
|
238
|
+
if (defaultValue !== undefined) {
|
|
239
|
+
return defaultValue
|
|
240
|
+
}
|
|
241
|
+
return match
|
|
242
|
+
})
|
|
243
|
+
}
|
|
244
|
+
exports.renderTemplate = renderTemplate
|