@itznomo/baileys 0.0.0-stage → 0.0.1
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/BUTTONS.md +153 -0
- package/Example/call-bot.mjs +38 -0
- package/Example/example.mjs +36 -0
- package/Example/full-bot-commands.mjs +319 -0
- package/Example/full-bot.mjs +77 -0
- package/LICENSE +21 -0
- package/README.md +543 -2
- package/WAProto/@dnuzi +1 -0
- package/WAProto/index.d.ts +15932 -0
- package/WAProto/index.js +113300 -0
- package/assets/banner.svg +17 -0
- package/assets/devider.svg +1 -0
- package/assets/features.svg +21 -0
- package/docs/CALLS.md +106 -0
- package/docs/FEATURES.md +1152 -0
- package/engine-requirements.js +19 -0
- package/index.d.ts +815 -0
- package/package.json +51 -4
- package/src/binary/wa-binary-constants.js +1300 -0
- package/src/binary/wa-binary.js +627 -0
- package/src/constants.js +147 -0
- package/src/defaults.js +106 -0
- package/src/foundation/ai-rich.js +654 -0
- package/src/foundation/audio-duration.js +470 -0
- package/src/foundation/audio-samples.js +250 -0
- package/src/foundation/boom.js +39 -0
- package/src/foundation/builders.js +851 -0
- package/src/foundation/cache.js +134 -0
- package/src/foundation/concurrency.js +69 -0
- package/src/foundation/curve25519.js +189 -0
- package/src/foundation/image-thumb.js +65 -0
- package/src/foundation/link-preview.js +278 -0
- package/src/foundation/logger.js +78 -0
- package/src/foundation/long.js +130 -0
- package/src/foundation/performance.js +385 -0
- package/src/foundation/protobuf-minimal.js +587 -0
- package/src/foundation/qrcode-terminal.js +273 -0
- package/src/foundation/sql-database.js +716 -0
- package/src/foundation/wa-crypto.js +47 -0
- package/src/foundation/zip.js +108 -0
- package/src/index.js +67 -0
- package/src/signal/libsignal.js +996 -0
- package/src/signal/signal-group.js +455 -0
- package/src/signal/signal-repository.js +635 -0
- package/src/socket/business-communities.js +811 -0
- package/src/socket/chats.js +702 -0
- package/src/socket/groups-newsletter.js +524 -0
- package/src/socket/messages-recv.js +1815 -0
- package/src/socket/messages-send.js +1526 -0
- package/src/socket/socket-builder.js +131 -0
- package/src/socket/socket-core.js +913 -0
- package/src/socket/usync.js +287 -0
- package/src/socket-client/native-websocket.js +344 -0
- package/src/socket-client/websocket-client.js +170 -0
- package/src/utils/auth-state-core.js +731 -0
- package/src/utils/auth-state-storage.js +594 -0
- package/src/utils/chat-sync.js +1046 -0
- package/src/utils/check-status.js +159 -0
- package/src/utils/cstoken.js +17 -0
- package/src/utils/media.js +807 -0
- package/src/utils/message-compose.js +1747 -0
- package/src/utils/message-processing.js +912 -0
- package/src/utils/modern-messages.js +435 -0
- package/src/utils/nomo-buttons.js +138 -0
- package/src/utils/nomo-commands.js +168 -0
- package/src/utils/spam-report-utils.js +136 -0
- package/src/utils/use-keyv-auth-state.js +307 -0
- package/src/utils/username.js +19 -0
- package/src/utils/wa-protocol-core.js +1227 -0
- package/src/voip/WaVoipCoordinator.js +158 -0
- package/src/voip/app-data/WaAppDataStream.js +193 -0
- package/src/voip/app-data/protocol.js +172 -0
- package/src/voip/auto.js +139 -0
- package/src/voip/bytes.js +63 -0
- package/src/voip/call/WaCallManager.js +442 -0
- package/src/voip/call/WaCallMediaSession.js +1727 -0
- package/src/voip/call/call-state.js +203 -0
- package/src/voip/crypto/encryption.js +13 -0
- package/src/voip/crypto/primitives.js +21 -0
- package/src/voip/crypto/rtcp.js +66 -0
- package/src/voip/crypto/srtp.js +180 -0
- package/src/voip/crypto/ssrc.js +15 -0
- package/src/voip/index.js +730 -0
- package/src/voip/media/WaAudioEngine.js +486 -0
- package/src/voip/media/WaVideoEngine.js +275 -0
- package/src/voip/media/audio-codec.js +0 -0
- package/src/voip/media/audio-reorder.js +107 -0
- package/src/voip/media/h264.js +246 -0
- package/src/voip/media/mlow-codec.js +465 -0
- package/src/voip/media/rtcp.js +68 -0
- package/src/voip/media/rtp.js +242 -0
- package/src/voip/protobuf.js +30 -0
- package/src/voip/relay/WaManualRelay.js +609 -0
- package/src/voip/relay/datachannel/pre-negotiated.js +25 -0
- package/src/voip/relay/dtls/aead.js +46 -0
- package/src/voip/relay/dtls/cert-builder.js +102 -0
- package/src/voip/relay/dtls/der.js +98 -0
- package/src/voip/relay/dtls/ecdhe.js +37 -0
- package/src/voip/relay/dtls/handshake-framing.js +100 -0
- package/src/voip/relay/dtls/handshake-messages.js +158 -0
- package/src/voip/relay/dtls/handshake.js +582 -0
- package/src/voip/relay/dtls/prf.js +39 -0
- package/src/voip/relay/dtls/record.js +56 -0
- package/src/voip/relay/relay-ack.js +141 -0
- package/src/voip/relay/sctp/association.js +434 -0
- package/src/voip/relay/sctp/crc32c.js +21 -0
- package/src/voip/relay/sctp/wire.js +226 -0
- package/src/voip/relay/stun.js +463 -0
- package/src/voip/shim/baileys-resolve.js +7 -0
- package/src/voip/shim/core.js +66 -0
- package/src/voip/shim/crypto.js +6 -0
- package/src/voip/shim/proto.js +10 -0
- package/src/voip/shim/protocol.js +130 -0
- package/src/voip/shim/transport.js +82 -0
- package/src/voip/shim/util.js +207 -0
- package/src/voip/signaling/bridge.js +102 -0
- package/src/voip/signaling/screen-share.js +60 -0
- package/src/voip/signaling/signaling.js +491 -0
- package/src/voip/types.js +69 -0
- package/src/voip/voip-deps.js +243 -0
- package/src/voip/voipClient.js +314 -0
- package/src/wam/wam-constants.js +22852 -0
- package/src/wam/wam.js +146 -0
- package/voip.d.ts +144 -0
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import { getButtonReply, quickReplyButton, singleSelectButton } from './nomo-buttons.js'
|
|
2
|
+
|
|
3
|
+
const FUTURE_PROOF = ['ephemeralMessage', 'viewOnceMessage', 'viewOnceMessageV2', 'viewOnceMessageV2Extension', 'documentWithCaptionMessage', 'editedMessage']
|
|
4
|
+
|
|
5
|
+
const unwrap = content => {
|
|
6
|
+
for (let i = 0; i < 5 && content; i++) {
|
|
7
|
+
const key = FUTURE_PROOF.find(k => content[k]?.message)
|
|
8
|
+
if (!key) break
|
|
9
|
+
content = content[key].message
|
|
10
|
+
}
|
|
11
|
+
return content
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const digits = value => String(value ?? '').split('@')[0].split(':')[0].replace(/\D/g, '')
|
|
15
|
+
|
|
16
|
+
/** plain text of a message, or the id of the button / list row the user tapped */
|
|
17
|
+
export const getMessageText = msg => {
|
|
18
|
+
const reply = getButtonReply(msg)
|
|
19
|
+
if (reply?.id) return reply.id
|
|
20
|
+
const c = unwrap(msg?.message)
|
|
21
|
+
if (!c) return ''
|
|
22
|
+
return (
|
|
23
|
+
c.conversation ??
|
|
24
|
+
c.extendedTextMessage?.text ??
|
|
25
|
+
c.imageMessage?.caption ??
|
|
26
|
+
c.videoMessage?.caption ??
|
|
27
|
+
c.documentMessage?.caption ??
|
|
28
|
+
c.buttonsMessage?.contentText ??
|
|
29
|
+
''
|
|
30
|
+
)
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Small command router for bots that use buttons and lists.
|
|
35
|
+
*
|
|
36
|
+
* const bot = createCommandRouter(sock, { prefix: '.', owners: ['947XXXXXXXX'] })
|
|
37
|
+
* bot.command('ping', ctx => ctx.reply('pong'), { description: 'Latency' })
|
|
38
|
+
* bot.command(['song', 'play'], handler, { description: 'Download audio', category: 'Tools', cooldownMs: 5000 })
|
|
39
|
+
* bot.attach() // listens to messages.upsert, button taps arrive as commands too
|
|
40
|
+
* await bot.sendMenu(jid, { title: 'Menu' })
|
|
41
|
+
*
|
|
42
|
+
* handler(ctx): ctx = { sock, msg, jid, sender, text, args, command, isGroup, isOwner, buttonReply, reply(content) }
|
|
43
|
+
* meta: { description, category, ownerOnly, groupOnly, privateOnly, cooldownMs, hidden }
|
|
44
|
+
*/
|
|
45
|
+
export const createCommandRouter = (sock, options = {}) => {
|
|
46
|
+
const prefix = options.prefix ?? '.'
|
|
47
|
+
const owners = (options.owners ?? []).map(digits)
|
|
48
|
+
const commands = new Map() // name -> entry
|
|
49
|
+
const entries = []
|
|
50
|
+
const lastUsed = new Map()
|
|
51
|
+
|
|
52
|
+
const router = {
|
|
53
|
+
prefix,
|
|
54
|
+
commands: entries,
|
|
55
|
+
|
|
56
|
+
command(names, handler, meta = {}) {
|
|
57
|
+
const list = (Array.isArray(names) ? names : [names]).map(n => String(n).toLowerCase())
|
|
58
|
+
const entry = { names: list, handler, meta }
|
|
59
|
+
entries.push(entry)
|
|
60
|
+
for (const name of list) commands.set(name, entry)
|
|
61
|
+
return router
|
|
62
|
+
},
|
|
63
|
+
|
|
64
|
+
parse(text) {
|
|
65
|
+
const trimmed = String(text ?? '').trim()
|
|
66
|
+
if (!trimmed.startsWith(prefix)) return undefined
|
|
67
|
+
const [first, ...args] = trimmed.slice(prefix.length).trim().split(/\s+/)
|
|
68
|
+
if (!first) return undefined
|
|
69
|
+
return { name: first.toLowerCase(), args }
|
|
70
|
+
},
|
|
71
|
+
|
|
72
|
+
async handle(msg) {
|
|
73
|
+
if (!msg?.message || msg.key?.fromMe) return false
|
|
74
|
+
const text = getMessageText(msg)
|
|
75
|
+
const parsed = router.parse(text)
|
|
76
|
+
if (!parsed) return false
|
|
77
|
+
|
|
78
|
+
const jid = msg.key.remoteJid
|
|
79
|
+
const isGroup = jid?.endsWith('@g.us') ?? false
|
|
80
|
+
const sender = isGroup ? (msg.key.participant ?? msg.participant) : jid
|
|
81
|
+
const isOwner = owners.length > 0 && owners.includes(digits(sender))
|
|
82
|
+
const entry = commands.get(parsed.name)
|
|
83
|
+
const ctx = {
|
|
84
|
+
sock,
|
|
85
|
+
msg,
|
|
86
|
+
jid,
|
|
87
|
+
sender,
|
|
88
|
+
text,
|
|
89
|
+
args: parsed.args,
|
|
90
|
+
command: parsed.name,
|
|
91
|
+
isGroup,
|
|
92
|
+
isOwner,
|
|
93
|
+
buttonReply: getButtonReply(msg),
|
|
94
|
+
reply: content => sock.sendMessage(jid, typeof content === 'string' ? { text: content } : content, { quoted: msg })
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
try {
|
|
98
|
+
if (!entry) {
|
|
99
|
+
await options.onUnknown?.(ctx)
|
|
100
|
+
return false
|
|
101
|
+
}
|
|
102
|
+
const { meta } = entry
|
|
103
|
+
if (meta.ownerOnly && !isOwner) return void (await options.onDenied?.(ctx, 'owner_only'))
|
|
104
|
+
if (meta.groupOnly && !isGroup) return void (await options.onDenied?.(ctx, 'group_only'))
|
|
105
|
+
if (meta.privateOnly && isGroup) return void (await options.onDenied?.(ctx, 'private_only'))
|
|
106
|
+
const cooldown = meta.cooldownMs ?? options.cooldownMs ?? 0
|
|
107
|
+
if (cooldown > 0 && !isOwner) {
|
|
108
|
+
const key = `${entry.names[0]}:${sender}`
|
|
109
|
+
const now = Date.now()
|
|
110
|
+
const wait = (lastUsed.get(key) ?? 0) + cooldown - now
|
|
111
|
+
if (wait > 0) return void (await options.onDenied?.(ctx, 'cooldown', wait))
|
|
112
|
+
lastUsed.set(key, now)
|
|
113
|
+
}
|
|
114
|
+
await entry.handler(ctx)
|
|
115
|
+
return true
|
|
116
|
+
} catch (error) {
|
|
117
|
+
if (options.onError) await options.onError(error, ctx)
|
|
118
|
+
else throw error
|
|
119
|
+
return false
|
|
120
|
+
}
|
|
121
|
+
},
|
|
122
|
+
|
|
123
|
+
/** listen to messages.upsert, returns a function that stops listening */
|
|
124
|
+
attach() {
|
|
125
|
+
const listener = async ({ messages, type }) => {
|
|
126
|
+
if (type && type !== 'notify') return
|
|
127
|
+
for (const msg of messages ?? []) {
|
|
128
|
+
try {
|
|
129
|
+
await router.handle(msg)
|
|
130
|
+
} catch (error) {
|
|
131
|
+
options.logger?.error?.(error)
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
sock.ev.on('messages.upsert', listener)
|
|
136
|
+
return () => sock.ev.off?.('messages.upsert', listener)
|
|
137
|
+
},
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Sends the command list as a drop-down menu (default) or as quick reply buttons (up to 3 commands).
|
|
141
|
+
* Commands with meta.description and without meta.hidden are listed, grouped by meta.category.
|
|
142
|
+
*/
|
|
143
|
+
async sendMenu(jid, menu = {}) {
|
|
144
|
+
const visible = entries.filter(e => e.meta.description && !e.meta.hidden)
|
|
145
|
+
const text = menu.text ?? 'Pick a command'
|
|
146
|
+
if (menu.style === 'buttons' || (visible.length > 0 && visible.length <= 3 && menu.style !== 'list')) {
|
|
147
|
+
return sock.sendMessage(jid, {
|
|
148
|
+
text,
|
|
149
|
+
footer: menu.footer,
|
|
150
|
+
interactiveButtons: visible.slice(0, 3).map(e => quickReplyButton(e.meta.title ?? e.names[0], `${prefix}${e.names[0]}`))
|
|
151
|
+
})
|
|
152
|
+
}
|
|
153
|
+
const groups = new Map()
|
|
154
|
+
for (const e of visible) {
|
|
155
|
+
const category = e.meta.category ?? 'Commands'
|
|
156
|
+
if (!groups.has(category)) groups.set(category, [])
|
|
157
|
+
groups.get(category).push({ id: `${prefix}${e.names[0]}`, title: e.meta.title ?? e.names[0], description: e.meta.description })
|
|
158
|
+
}
|
|
159
|
+
return sock.sendMessage(jid, {
|
|
160
|
+
text,
|
|
161
|
+
title: menu.title,
|
|
162
|
+
footer: menu.footer,
|
|
163
|
+
interactiveButtons: [singleSelectButton(menu.buttonText ?? 'Open menu', [...groups].map(([title, rows]) => ({ title, rows })))]
|
|
164
|
+
})
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
return router
|
|
168
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { getBinaryNodeChild, getBinaryNodeChildString, isLidUser, isHostedLidUser, isJidGroup, S_WHATSAPP_NET } from '../binary/wa-binary.js'
|
|
2
|
+
import { extractMessageContent } from './message-compose.js'
|
|
3
|
+
|
|
4
|
+
export const SPAM_FLOWS = {
|
|
5
|
+
ACCOUNT_INFO_REPORT: 'account_info_report',
|
|
6
|
+
ACCOUNT_INFO_BLOCK: 'account_info_block',
|
|
7
|
+
GROUP_INFO_REPORT: 'group_info_report',
|
|
8
|
+
CONTACT_INFO_REPORT: 'contact_info_report',
|
|
9
|
+
ONE_TO_ONE_SPAM_BANNER_REPORT: '1_1_spam_banner_report',
|
|
10
|
+
MESSAGE_MENU: 'message_menu',
|
|
11
|
+
OVERFLOW_MENU_REPORT: 'overflow_menu_report'
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export const REPORT_REASON_CODES = {
|
|
15
|
+
spam: 1,
|
|
16
|
+
harassment: 2,
|
|
17
|
+
impersonation: 3,
|
|
18
|
+
scam: 4,
|
|
19
|
+
other: 5
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const toBuffer = data => {
|
|
23
|
+
if (!data) return null
|
|
24
|
+
if (Buffer.isBuffer(data)) return data
|
|
25
|
+
if (data instanceof Uint8Array) return Buffer.from(data)
|
|
26
|
+
if (typeof data === 'string') return Buffer.from(data, 'base64')
|
|
27
|
+
return null
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export const resolveReportJid = async (jid, lidMapping) => {
|
|
31
|
+
if (!jid) throw new Error('resolveReportJid: jid required')
|
|
32
|
+
if (isJidGroup(jid) || isLidUser(jid) || isHostedLidUser(jid)) return jid
|
|
33
|
+
const lid = lidMapping?.getLIDForPN ? await lidMapping.getLIDForPN(jid) : null
|
|
34
|
+
return lid ?? jid
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export const resolveReportContext = async (jid, lidMapping) => {
|
|
38
|
+
if (!jid) throw new Error('resolveReportContext: jid required')
|
|
39
|
+
if (isJidGroup(jid)) return { reportJid: jid, spamFlow: SPAM_FLOWS.GROUP_INFO_REPORT, isGroup: true }
|
|
40
|
+
return { reportJid: await resolveReportJid(jid, lidMapping), spamFlow: SPAM_FLOWS.ACCOUNT_INFO_REPORT, isGroup: false }
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export const normalizeReportingTag = tag => {
|
|
44
|
+
const buf = toBuffer(tag)
|
|
45
|
+
return buf?.length ? buf : null
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export const extractMessageText = msg => {
|
|
49
|
+
if (!msg?.message) return ''
|
|
50
|
+
const c = extractMessageContent(msg.message)
|
|
51
|
+
if (!c) return ''
|
|
52
|
+
return c.conversation ?? c.extendedTextMessage?.text ?? c.imageMessage?.caption ?? c.videoMessage?.caption ?? ''
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export const buildSpamReportMessageNodes = (messages, logger) => {
|
|
56
|
+
const ts = () => Math.floor(Date.now() / 1000)
|
|
57
|
+
const nodes = (messages || []).slice(0, 5).reduce((acc, m) => {
|
|
58
|
+
const reportingTag = normalizeReportingTag(m.reportingTag)
|
|
59
|
+
if (!reportingTag) {
|
|
60
|
+
logger?.warn?.({ stanzaId: m.stanzaId }, 'buildSpamReportMessageNodes: skipping — missing reportingTag')
|
|
61
|
+
return acc
|
|
62
|
+
}
|
|
63
|
+
const t = String(m.timestamp || ts())
|
|
64
|
+
acc.push({
|
|
65
|
+
tag: 'message',
|
|
66
|
+
attrs: { t, id: m.stanzaId, reported_push_name: m.pushName || '', type: m.messageType || 'text', from: m.fromJid },
|
|
67
|
+
content: [
|
|
68
|
+
{ tag: 'raw', attrs: { local_message_type: '0', v: '2' }, content: m.text != null ? String(m.text) : '' },
|
|
69
|
+
{
|
|
70
|
+
tag: 'reporting',
|
|
71
|
+
attrs: {},
|
|
72
|
+
content: [{ tag: 'reporting_validation', attrs: {}, content: [{ tag: 'reporting_tag', attrs: { id: m.stanzaId, ts_s: t }, content: reportingTag }] }]
|
|
73
|
+
}
|
|
74
|
+
]
|
|
75
|
+
})
|
|
76
|
+
return acc
|
|
77
|
+
}, [])
|
|
78
|
+
if (!nodes.length) {
|
|
79
|
+
throw new Error('reportSpam: no valid messages with reportingTag found')
|
|
80
|
+
}
|
|
81
|
+
return nodes
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export const buildSpamReportIq = (jid, messages, spamFlow = SPAM_FLOWS.ACCOUNT_INFO_REPORT, logger) => {
|
|
85
|
+
if (!messages?.length) {
|
|
86
|
+
throw new Error('reportSpam: at least one message with reporting_tag required')
|
|
87
|
+
}
|
|
88
|
+
return {
|
|
89
|
+
tag: 'iq',
|
|
90
|
+
attrs: { type: 'set', xmlns: 'spam', to: S_WHATSAPP_NET },
|
|
91
|
+
content: [{ tag: 'spam_list', attrs: { jid, spam_flow: spamFlow }, content: buildSpamReportMessageNodes(messages, logger) }]
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export const buildSimpleReportNode = (jid, messageKeys) => ({
|
|
96
|
+
tag: 'report',
|
|
97
|
+
attrs: { jid, type: 'spam' },
|
|
98
|
+
content: (messageKeys || []).map(key => ({ tag: 'message', attrs: { id: key.id || key, ...(key.fromMe ? {} : { from: jid }) } }))
|
|
99
|
+
})
|
|
100
|
+
|
|
101
|
+
export const parseSpamReportResponse = result => {
|
|
102
|
+
if (!result) return { success: false, error: 'empty response' }
|
|
103
|
+
if (result.attrs?.type === 'error') {
|
|
104
|
+
const errNode = getBinaryNodeChild(result, 'error')
|
|
105
|
+
const code = errNode?.attrs?.code
|
|
106
|
+
const text = errNode?.content?.toString?.() || errNode?.attrs?.text
|
|
107
|
+
return { success: false, error: `spam IQ error${code ? ` ${code}` : ''}${text ? `: ${text}` : ''}` }
|
|
108
|
+
}
|
|
109
|
+
const reportNode = getBinaryNodeChild(result, 'report')
|
|
110
|
+
const reportId = reportNode?.attrs?.id || getBinaryNodeChildString(reportNode, 'id')
|
|
111
|
+
if (reportId) return { success: true, reportId: String(reportId) }
|
|
112
|
+
if (result.attrs?.type === 'result') return { success: true }
|
|
113
|
+
return { success: false, error: 'unexpected spam IQ response' }
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Creates a fake quoted message structure for replying or spoofing context
|
|
118
|
+
* without requiring an actual original message.
|
|
119
|
+
*
|
|
120
|
+
* @param {string|object} content - string for conversation or proto message object
|
|
121
|
+
* @param {object} options - custom key properties (remoteJid, fromMe, id, participant)
|
|
122
|
+
* @returns {object} fake quoted message object
|
|
123
|
+
*/
|
|
124
|
+
export const createFakeQuoted = (content, options = {}) => {
|
|
125
|
+
const text = typeof content === 'string' ? content : content?.text
|
|
126
|
+
const message = typeof content === 'object' && !content?.text ? content : { conversation: text || 'Fake quoted message' }
|
|
127
|
+
return {
|
|
128
|
+
key: {
|
|
129
|
+
remoteJid: options.remoteJid || 'status@broadcast',
|
|
130
|
+
fromMe: options.fromMe ?? false,
|
|
131
|
+
id: options.id || 'FAKE_' + Date.now() + '_' + Math.floor(Math.random() * 10000),
|
|
132
|
+
participant: options.participant || (options.fromMe ? undefined : '0@s.whatsapp.net')
|
|
133
|
+
},
|
|
134
|
+
message
|
|
135
|
+
}
|
|
136
|
+
}
|
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
import { DEFAULT_CACHE_TTLS } from '../defaults.js'
|
|
2
|
+
import { initAuthCreds } from './auth-state-core.js'
|
|
3
|
+
import { BufferJSON } from './wa-protocol-core.js'
|
|
4
|
+
import { proto } from '../../WAProto/index.js'
|
|
5
|
+
import logger from '../foundation/logger.js'
|
|
6
|
+
|
|
7
|
+
// ── Default constants ─────────────────────────────────────────────────────────
|
|
8
|
+
|
|
9
|
+
export const DEFAULT_PREKEY_RETENTION = 100
|
|
10
|
+
export const DEFAULT_CLEANUP_THRESHOLD = 50
|
|
11
|
+
export const CLEANUP_INTERVAL_MS = 10 * 60 * 1000 // 10 minutes
|
|
12
|
+
export const DEFAULT_COLLECTION_NAME = 'baileys_auth'
|
|
13
|
+
|
|
14
|
+
// Protocol adapters mapping connection string protocols to keyv packages
|
|
15
|
+
export const PROTOCOL_ADAPTERS = {
|
|
16
|
+
'redis:': '@keyv/redis',
|
|
17
|
+
'rediss:': '@keyv/redis',
|
|
18
|
+
'mongodb:': '@keyv/mongo',
|
|
19
|
+
'mongodb+srv:': '@keyv/mongo',
|
|
20
|
+
'postgresql:': '@keyv/postgres',
|
|
21
|
+
'postgres:': '@keyv/postgres',
|
|
22
|
+
'mysql:': '@keyv/mysql',
|
|
23
|
+
'sqlite:': '@keyv/sqlite',
|
|
24
|
+
'etcd:': '@keyv/etcd',
|
|
25
|
+
'memcache:': '@keyv/memcache',
|
|
26
|
+
'memcached:': '@keyv/memcache'
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const COLLECTION_KEY = {
|
|
30
|
+
'@keyv/mongo': 'collection',
|
|
31
|
+
'@keyv/postgres': 'table',
|
|
32
|
+
'@keyv/mysql': 'table',
|
|
33
|
+
'@keyv/sqlite': 'table'
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// ── Helper Serialization ──────────────────────────────────────────────────────
|
|
37
|
+
|
|
38
|
+
export const bootstrapCreds = raw => raw ?? initAuthCreds()
|
|
39
|
+
export const patchAppStateKey = (type, v) => (type === 'app-state-sync-key' && v ? proto.Message.AppStateSyncKeyData.fromObject(v) : v)
|
|
40
|
+
export const ser = v => (v == null ? null : JSON.parse(JSON.stringify(v, BufferJSON.replacer)))
|
|
41
|
+
export const deser = raw => {
|
|
42
|
+
if (raw == null) return null
|
|
43
|
+
let p = typeof raw === 'string'
|
|
44
|
+
? (() => { try { return JSON.parse(raw) } catch { return raw } })()
|
|
45
|
+
: raw
|
|
46
|
+
let depth = 0
|
|
47
|
+
while (depth++ < 3 && p && typeof p === 'object' && !Array.isArray(p) && Object.keys(p).length === 1 && 'value' in p) p = p.value
|
|
48
|
+
if (p == null) return null
|
|
49
|
+
if (typeof p === 'object' && '__checksum' in p && 'data' in p) p = p.data
|
|
50
|
+
return JSON.parse(JSON.stringify(p), BufferJSON.reviver)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// ── Adapter resolution ────────────────────────────────────────────────────────
|
|
54
|
+
|
|
55
|
+
const _adapterCache = new Map()
|
|
56
|
+
export const clearAdapterCache = () => _adapterCache.clear()
|
|
57
|
+
|
|
58
|
+
const resolveAdapter = async (conn, col, namespace) => {
|
|
59
|
+
const ck = `${conn}::${col ?? ''}::${namespace ?? ''}`
|
|
60
|
+
if (_adapterCache.has(ck)) return _adapterCache.get(ck)
|
|
61
|
+
let protocol
|
|
62
|
+
try {
|
|
63
|
+
protocol = new URL(conn).protocol
|
|
64
|
+
} catch {
|
|
65
|
+
throw new Error(`[Auth] Invalid connection string: "${conn}"`)
|
|
66
|
+
}
|
|
67
|
+
const pkg = PROTOCOL_ADAPTERS[protocol]
|
|
68
|
+
if (!pkg) {
|
|
69
|
+
throw new Error(`[Auth] Unsupported protocol "${protocol}" — supported: ${Object.keys(PROTOCOL_ADAPTERS).map(p => p.replace(':', '')).join(', ')}`)
|
|
70
|
+
}
|
|
71
|
+
let mod
|
|
72
|
+
try {
|
|
73
|
+
mod = await import(pkg)
|
|
74
|
+
} catch (e) {
|
|
75
|
+
if (e.code === 'ERR_MODULE_NOT_FOUND') {
|
|
76
|
+
throw new Error(`[Auth] "${pkg}" adapter is required — please run: npm i ${pkg}`)
|
|
77
|
+
}
|
|
78
|
+
throw e
|
|
79
|
+
}
|
|
80
|
+
const Adapter = mod.default ?? mod[Object.keys(mod)[0]]
|
|
81
|
+
const optKey = COLLECTION_KEY[pkg]
|
|
82
|
+
const adapter = col && optKey ? new Adapter({ url: conn, uri: conn, [optKey]: col }) : new Adapter(conn)
|
|
83
|
+
adapter.setMaxListeners?.(0)
|
|
84
|
+
if (namespace) adapter.namespace = namespace
|
|
85
|
+
_adapterCache.set(ck, adapter)
|
|
86
|
+
return adapter
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const resolveStore = async (backend, col, namespace) => {
|
|
90
|
+
if (backend == null) return null
|
|
91
|
+
if (typeof backend === 'string') return resolveAdapter(backend, col, namespace)
|
|
92
|
+
|
|
93
|
+
let KeyvClass
|
|
94
|
+
try {
|
|
95
|
+
const keyvMod = await import('keyv')
|
|
96
|
+
KeyvClass = keyvMod.Keyv || keyvMod.default
|
|
97
|
+
} catch {
|
|
98
|
+
// Keyv not imported yet
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
if (KeyvClass && backend instanceof KeyvClass) {
|
|
102
|
+
return backend.opts?.store ?? backend.store ?? null
|
|
103
|
+
}
|
|
104
|
+
// Scoped prototype namespace so we don't mutate the original store instance
|
|
105
|
+
const scoped = Object.create(backend)
|
|
106
|
+
if (namespace) scoped.namespace = namespace
|
|
107
|
+
return scoped
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const makeKeyv = async (store, namespace) => {
|
|
111
|
+
let KeyvClass
|
|
112
|
+
try {
|
|
113
|
+
const keyvMod = await import('keyv')
|
|
114
|
+
KeyvClass = keyvMod.Keyv || keyvMod.default
|
|
115
|
+
} catch (e) {
|
|
116
|
+
throw new Error('[Auth] The "keyv" package is required to use useKeyvAuthState — please run: npm i keyv')
|
|
117
|
+
}
|
|
118
|
+
const keyv = store ? new KeyvClass({ store, namespace }) : new KeyvClass({ namespace })
|
|
119
|
+
keyv.setMaxListeners?.(0)
|
|
120
|
+
return keyv
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// ── Keyv instance cache ───────────────────────────────────────────────────────
|
|
124
|
+
|
|
125
|
+
const _keyvCache = new WeakMap()
|
|
126
|
+
|
|
127
|
+
const getKeyv = async (store, namespace) => {
|
|
128
|
+
const bind = k => (k.on?.('error', err => logger.warn({ err: err?.message, namespace }, '[Auth] store error')), k)
|
|
129
|
+
if (!store) return bind(await makeKeyv(null, namespace))
|
|
130
|
+
if (!_keyvCache.has(store)) _keyvCache.set(store, new Map())
|
|
131
|
+
const nsMap = _keyvCache.get(store)
|
|
132
|
+
const key = namespace ?? ''
|
|
133
|
+
if (nsMap.has(key)) return nsMap.get(key)
|
|
134
|
+
const keyv = bind(await makeKeyv(store, namespace))
|
|
135
|
+
nsMap.set(key, keyv)
|
|
136
|
+
return keyv
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// ── Multi-backend support (Per-Type Routing) ──────────────────────────────────
|
|
140
|
+
|
|
141
|
+
const isMultiBackend = backend =>
|
|
142
|
+
backend !== null &&
|
|
143
|
+
typeof backend === 'object' &&
|
|
144
|
+
!Array.isArray(backend) &&
|
|
145
|
+
typeof backend.get !== 'function'
|
|
146
|
+
|
|
147
|
+
const resolveBackendMap = async (backend, sessionId, collectionName) => {
|
|
148
|
+
if (!isMultiBackend(backend)) {
|
|
149
|
+
const store = await resolveStore(backend, collectionName, sessionId)
|
|
150
|
+
const keyv = await getKeyv(store, sessionId)
|
|
151
|
+
return { get: () => keyv, all: [keyv], stores: [store] }
|
|
152
|
+
}
|
|
153
|
+
const entries = Object.entries(backend)
|
|
154
|
+
if (!entries.length) throw new Error('[Auth] backend map must have at least one entry')
|
|
155
|
+
const resolved = new Map()
|
|
156
|
+
for (const [, b] of entries) {
|
|
157
|
+
if (!resolved.has(b)) {
|
|
158
|
+
const store = await resolveStore(b, collectionName, sessionId)
|
|
159
|
+
resolved.set(b, { store, keyv: await getKeyv(store, sessionId) })
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
const typeMap = Object.fromEntries(entries.map(([type, b]) => [type, resolved.get(b).keyv]))
|
|
163
|
+
const defaultKeyv = resolved.get(entries[0][1]).keyv
|
|
164
|
+
return {
|
|
165
|
+
get: type => typeMap[type] ?? defaultKeyv,
|
|
166
|
+
all: [...new Set([...resolved.values()].map(r => r.keyv))],
|
|
167
|
+
stores: [...new Set([...resolved.values()].map(r => r.store))]
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// ── Keyv-backed auth state ────────────────────────────────────────────────────
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* useKeyvAuthState:
|
|
175
|
+
* Keyv-backed storage adapter supporting single-backend or advanced per-type routing.
|
|
176
|
+
*
|
|
177
|
+
* Example per-type routing:
|
|
178
|
+
* ```javascript
|
|
179
|
+
* const { state, saveCreds, clearSession } = await useKeyvAuthState('bot1', {
|
|
180
|
+
* 'creds': 'postgresql://user:pass@localhost/db',
|
|
181
|
+
* 'pre-key': 'redis://localhost:6379',
|
|
182
|
+
* 'session': 'redis://localhost:6379',
|
|
183
|
+
* 'app-state-sync-key': 'mongodb://localhost/baileys',
|
|
184
|
+
* 'app-state-sync-version': 'mongodb://localhost/baileys',
|
|
185
|
+
* 'sender-key': 'redis://localhost:6379',
|
|
186
|
+
* 'sender-key-memory': 'redis://localhost:6379',
|
|
187
|
+
* })
|
|
188
|
+
* ```
|
|
189
|
+
*/
|
|
190
|
+
export const useKeyvAuthState = async (sessionId, backend, opts = {}) => {
|
|
191
|
+
const {
|
|
192
|
+
preKeyRetention = DEFAULT_PREKEY_RETENTION,
|
|
193
|
+
cleanupThreshold = DEFAULT_CLEANUP_THRESHOLD,
|
|
194
|
+
collectionName = DEFAULT_COLLECTION_NAME
|
|
195
|
+
} = opts
|
|
196
|
+
const bmap = await resolveBackendMap(backend, sessionId, collectionName)
|
|
197
|
+
const credsKeyv = bmap.get('creds')
|
|
198
|
+
|
|
199
|
+
const kn = (type, id) => `${type}-${id}`
|
|
200
|
+
const credsKey = 'creds'
|
|
201
|
+
let creds = bootstrapCreds(deser(await credsKeyv.get(credsKey)))
|
|
202
|
+
let cleanupRunning = false,
|
|
203
|
+
lastCleanupAt = 0,
|
|
204
|
+
lastCleanedId = creds.nextPreKeyId
|
|
205
|
+
|
|
206
|
+
const cleanOldPreKeys = async () => {
|
|
207
|
+
if (cleanupRunning || Date.now() - lastCleanupAt < CLEANUP_INTERVAL_MS) return
|
|
208
|
+
cleanupRunning = true
|
|
209
|
+
try {
|
|
210
|
+
const minId = creds.nextPreKeyId - preKeyRetention
|
|
211
|
+
if (minId <= 0) return
|
|
212
|
+
const ids = []
|
|
213
|
+
for (let id = Math.max(0, lastCleanedId - preKeyRetention); id < minId; id++) {
|
|
214
|
+
ids.push(kn('pre-key', id))
|
|
215
|
+
}
|
|
216
|
+
if (ids.length) {
|
|
217
|
+
const preKeyBackend = bmap.get('pre-key')
|
|
218
|
+
if (typeof preKeyBackend.deleteMany === 'function') {
|
|
219
|
+
await preKeyBackend.deleteMany(ids)
|
|
220
|
+
} else {
|
|
221
|
+
await Promise.all(ids.map(id => preKeyBackend.delete(id)))
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
lastCleanupAt = Date.now()
|
|
225
|
+
lastCleanedId = creds.nextPreKeyId
|
|
226
|
+
} catch (e) {
|
|
227
|
+
logger.warn({ err: e.message, sessionId }, '[Auth] prekey cleanup failed')
|
|
228
|
+
} finally {
|
|
229
|
+
cleanupRunning = false
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
cleanOldPreKeys().catch(() => {})
|
|
233
|
+
|
|
234
|
+
const keys = {
|
|
235
|
+
get: async (type, ids) => {
|
|
236
|
+
if (!ids.length) return {}
|
|
237
|
+
const keyv = bmap.get(type)
|
|
238
|
+
let raws
|
|
239
|
+
if (typeof keyv.getMany === 'function') {
|
|
240
|
+
raws = await keyv.getMany(ids.map(id => kn(type, id)))
|
|
241
|
+
} else {
|
|
242
|
+
raws = await Promise.all(ids.map(id => keyv.get(kn(type, id))))
|
|
243
|
+
}
|
|
244
|
+
return Object.fromEntries(ids.map((id, i) => [id, patchAppStateKey(type, deser(raws[i]))]))
|
|
245
|
+
},
|
|
246
|
+
set: async data => {
|
|
247
|
+
const byKeyv = new Map()
|
|
248
|
+
for (const type in data) {
|
|
249
|
+
const keyv = bmap.get(type)
|
|
250
|
+
if (!byKeyv.has(keyv)) byKeyv.set(keyv, { sets: [], dels: [] })
|
|
251
|
+
const bucket = byKeyv.get(keyv)
|
|
252
|
+
for (const id in data[type]) {
|
|
253
|
+
const v = data[type][id],
|
|
254
|
+
k = kn(type, id)
|
|
255
|
+
if (v != null) bucket.sets.push({ key: k, value: ser(v) })
|
|
256
|
+
else bucket.dels.push(k)
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
await Promise.all(
|
|
260
|
+
[...byKeyv.entries()].map(([keyv, { sets, dels }]) =>
|
|
261
|
+
Promise.all([
|
|
262
|
+
sets.length
|
|
263
|
+
? typeof keyv.setMany === 'function'
|
|
264
|
+
? keyv.setMany(sets)
|
|
265
|
+
: Promise.all(sets.map(s => keyv.set(s.key, s.value)))
|
|
266
|
+
: null,
|
|
267
|
+
dels.length
|
|
268
|
+
? typeof keyv.deleteMany === 'function'
|
|
269
|
+
? keyv.deleteMany(dels)
|
|
270
|
+
: Promise.all(dels.map(k => keyv.delete(k)))
|
|
271
|
+
: null
|
|
272
|
+
])
|
|
273
|
+
)
|
|
274
|
+
)
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
const saveCreds = async () => {
|
|
279
|
+
if (creds.nextPreKeyId - lastCleanedId >= cleanupThreshold) cleanOldPreKeys().catch(() => {})
|
|
280
|
+
await credsKeyv.set(credsKey, ser(creds))
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
const clearSession = async () => {
|
|
284
|
+
try {
|
|
285
|
+
await Promise.all(bmap.all.map(keyv => keyv.clear?.()))
|
|
286
|
+
} catch (e) {
|
|
287
|
+
logger.warn({ err: e.message, sessionId }, '[Auth] clearSession failed')
|
|
288
|
+
}
|
|
289
|
+
bmap.stores?.forEach(store => {
|
|
290
|
+
const nsMap = _keyvCache.get(store)
|
|
291
|
+
if (nsMap) nsMap.delete(sessionId)
|
|
292
|
+
})
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
return { state: { creds, keys }, saveCreds, clearSession }
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
export const hasKeyvAuth = async (sessionId, backend, opts = {}) => {
|
|
299
|
+
try {
|
|
300
|
+
const b = isMultiBackend(backend) ? Object.values(backend)[0] : backend
|
|
301
|
+
const bmap = await resolveBackendMap(b, sessionId, opts.collectionName ?? DEFAULT_COLLECTION_NAME)
|
|
302
|
+
const parsed = deser(await bmap.get('creds').get('creds'))
|
|
303
|
+
return !!(parsed?.noiseKey && parsed?.signedIdentityKey)
|
|
304
|
+
} catch {
|
|
305
|
+
return false
|
|
306
|
+
}
|
|
307
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export const USERNAME_MIN_LENGTH = 4
|
|
2
|
+
export const USERNAME_MAX_LENGTH = 30
|
|
3
|
+
|
|
4
|
+
const USERNAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9._]*$/
|
|
5
|
+
|
|
6
|
+
export function normalizeUsername(input) {
|
|
7
|
+
if (typeof input !== 'string') return ''
|
|
8
|
+
return input.trim().replace(/^@/, '')
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function isValidUsername(input) {
|
|
12
|
+
const handle = normalizeUsername(input)
|
|
13
|
+
if (handle.length < USERNAME_MIN_LENGTH || handle.length > USERNAME_MAX_LENGTH) return false
|
|
14
|
+
return USERNAME_PATTERN.test(handle)
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function isValidUsernameKey(key) {
|
|
18
|
+
return typeof key === 'string' && /^\d{4}$/.test(key)
|
|
19
|
+
}
|