@zervonexx/baileys 0.0.0-stage → 5.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.
Files changed (125) hide show
  1. package/LICENSE +23 -0
  2. package/README.md +4113 -3
  3. package/WAProto/WAProtoCompile.js +323 -0
  4. package/WAProto/fetcher.js +68 -0
  5. package/WAProto/index.js +96 -0
  6. package/WAProto/parser.js +334 -0
  7. package/lib/Builders/AIRich.js +674 -0
  8. package/lib/Builders/auto.js +50 -0
  9. package/lib/Builders/base.js +145 -0
  10. package/lib/Builders/builders.js +589 -0
  11. package/lib/Builders/index.js +4 -0
  12. package/lib/Defaults/index.js +248 -0
  13. package/lib/Signal/index.js +2 -0
  14. package/lib/Signal/libsignal.js +527 -0
  15. package/lib/Signal/lid-mapping.js +283 -0
  16. package/lib/Socket/Client/index.js +2 -0
  17. package/lib/Socket/Client/types.js +10 -0
  18. package/lib/Socket/Client/websocket.js +84 -0
  19. package/lib/Socket/business.js +152 -0
  20. package/lib/Socket/chats.js +855 -0
  21. package/lib/Socket/communities.js +147 -0
  22. package/lib/Socket/groups.js +294 -0
  23. package/lib/Socket/index.js +15 -0
  24. package/lib/Socket/messages-recv.js +994 -0
  25. package/lib/Socket/messages-send.js +723 -0
  26. package/lib/Socket/mex.js +34 -0
  27. package/lib/Socket/newsletter.js +784 -0
  28. package/lib/Socket/registration.js +155 -0
  29. package/lib/Socket/socket.js +798 -0
  30. package/lib/Socket/spam-report.js +144 -0
  31. package/lib/Socket/username.js +82 -0
  32. package/lib/Socket/zervonex-handler.js +58 -0
  33. package/lib/Store/index.js +6 -0
  34. package/lib/Store/make-cache-manager-store.js +80 -0
  35. package/lib/Store/make-in-memory-store.js +426 -0
  36. package/lib/Store/make-ordered-dictionary.js +82 -0
  37. package/lib/Store/object-repository.js +31 -0
  38. package/lib/Store/reporting-info-store.js +38 -0
  39. package/lib/Types/Auth.js +2 -0
  40. package/lib/Types/Bussines.js +2 -0
  41. package/lib/Types/Call.js +2 -0
  42. package/lib/Types/Chat.js +8 -0
  43. package/lib/Types/Contact.js +2 -0
  44. package/lib/Types/Events.js +2 -0
  45. package/lib/Types/GroupMetadata.js +2 -0
  46. package/lib/Types/Label.js +25 -0
  47. package/lib/Types/LabelAssociation.js +7 -0
  48. package/lib/Types/Message.js +15 -0
  49. package/lib/Types/Newsletter.js +100 -0
  50. package/lib/Types/Product.js +2 -0
  51. package/lib/Types/Signal.js +2 -0
  52. package/lib/Types/Socket.js +14 -0
  53. package/lib/Types/State.js +26 -0
  54. package/lib/Types/USync.js +2 -0
  55. package/lib/Types/index.js +30 -0
  56. package/lib/Utils/auth-utils.js +159 -0
  57. package/lib/Utils/baileys-event-stream.js +33 -0
  58. package/lib/Utils/bot-capabilities.js +41 -0
  59. package/lib/Utils/bot-planning-replay.js +44 -0
  60. package/lib/Utils/browser-utils.js +30 -0
  61. package/lib/Utils/business.js +75 -0
  62. package/lib/Utils/chat-utils.js +317 -0
  63. package/lib/Utils/companion-reg-client-utils.js +20 -0
  64. package/lib/Utils/consumer-application.js +38 -0
  65. package/lib/Utils/crypto.js +53 -0
  66. package/lib/Utils/cstoken.js +15 -0
  67. package/lib/Utils/decode-wa-message.js +200 -0
  68. package/lib/Utils/event-buffer.js +273 -0
  69. package/lib/Utils/extras.js +186 -0
  70. package/lib/Utils/generics.js +195 -0
  71. package/lib/Utils/history.js +51 -0
  72. package/lib/Utils/identity-change-handler.js +19 -0
  73. package/lib/Utils/index.js +40 -0
  74. package/lib/Utils/link-preview.js +51 -0
  75. package/lib/Utils/logger.js +3 -0
  76. package/lib/Utils/lt-hash.js +3 -0
  77. package/lib/Utils/make-mutex.js +16 -0
  78. package/lib/Utils/message-composer.js +62 -0
  79. package/lib/Utils/message-retry-manager.js +48 -0
  80. package/lib/Utils/messages-media.js +502 -0
  81. package/lib/Utils/messages.js +943 -0
  82. package/lib/Utils/meta-ai-msmsg.js +122 -0
  83. package/lib/Utils/meta-compositing.js +75 -0
  84. package/lib/Utils/modern-messages.js +235 -0
  85. package/lib/Utils/native-flow.js +81 -0
  86. package/lib/Utils/noise-handler.js +161 -0
  87. package/lib/Utils/pre-key-manager.js +76 -0
  88. package/lib/Utils/process-message.js +401 -0
  89. package/lib/Utils/reporting-utils.js +171 -0
  90. package/lib/Utils/signal.js +167 -0
  91. package/lib/Utils/spam-report-utils.js +166 -0
  92. package/lib/Utils/sync-action-utils.js +33 -0
  93. package/lib/Utils/tc-token-utils.js +154 -0
  94. package/lib/Utils/use-keyv-auth-state.js +200 -0
  95. package/lib/Utils/use-multi-file-auth-state.js +84 -0
  96. package/lib/Utils/validate-connection.js +172 -0
  97. package/lib/WABinary/constants.js +1321 -0
  98. package/lib/WABinary/decode.js +152 -0
  99. package/lib/WABinary/encode.js +140 -0
  100. package/lib/WABinary/generic-utils.js +203 -0
  101. package/lib/WABinary/index.js +6 -0
  102. package/lib/WABinary/jid-utils.js +235 -0
  103. package/lib/WABinary/types.js +4 -0
  104. package/lib/WAM/BinaryInfo.js +10 -0
  105. package/lib/WAM/constants.js +22853 -0
  106. package/lib/WAM/encode.js +150 -0
  107. package/lib/WAM/index.js +3 -0
  108. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +30 -0
  109. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +48 -0
  110. package/lib/WAUSync/Protocols/USyncContactProtocol.js +23 -0
  111. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +28 -0
  112. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +15 -0
  113. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +24 -0
  114. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +9 -0
  115. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +21 -0
  116. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +19 -0
  117. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +19 -0
  118. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +22 -0
  119. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +16 -0
  120. package/lib/WAUSync/Protocols/index.js +12 -0
  121. package/lib/WAUSync/USyncQuery.js +88 -0
  122. package/lib/WAUSync/USyncUser.js +20 -0
  123. package/lib/WAUSync/index.js +3 -0
  124. package/lib/index.js +67 -0
  125. package/package.json +191 -5
@@ -0,0 +1,154 @@
1
+ import { randomBytes } from 'crypto'
2
+ import { getBinaryNodeChild, getBinaryNodeChildren, isHostedLidUser, isHostedPnUser, isJidMetaAI, isLidUser, isPnUser, jidNormalizedUser } from '../WABinary/index.js'
3
+ import { unixTimestampSeconds } from './generics.js'
4
+
5
+ // ─── Constants ────────────────────────────────────────────────────────────────
6
+ export const TC_TOKEN_INDEX_KEY = '__index'
7
+ const BOT_PHONE_REGEX = /^1313555\d{4}$|^131655500\d{2}$/
8
+ const TC_TOKEN_BUCKET_DURATION = 604800 // 7 days
9
+ const TC_TOKEN_NUM_BUCKETS = 4 // ~28-day rolling window
10
+ const TC_TOKEN_MIN_BYTES = 1
11
+ const TC_TOKEN_MAX_BYTES = 120 // DMW layer constraint
12
+ const TC_TOKEN_MAX_RECIPIENTS = 5 // feature flag 20606 default cap
13
+
14
+ const currentBucket = () => Math.floor(unixTimestampSeconds() / TC_TOKEN_BUCKET_DURATION)
15
+ const generateTcToken = () => randomBytes(32) // local pre-seed fallback only; real tokens are server-issued
16
+
17
+ // ─── JID helpers ──────────────────────────────────────────────────────────────
18
+
19
+ export const isRegularUser = jid => {
20
+ if (!jid) return false
21
+ const user = jid.split('@')[0] ?? ''
22
+ if (user === '0' || BOT_PHONE_REGEX.test(user) || isJidMetaAI(jid)) return false
23
+ return !!(isPnUser(jid) || isLidUser(jid) || isHostedPnUser(jid) || isHostedLidUser(jid) || jid.endsWith('@c.us'))
24
+ }
25
+
26
+ // storage key is always LID when resolvable
27
+ export const resolveTcTokenJid = async (jid, getLIDForPN) =>
28
+ isLidUser(jid) ? jid : (await getLIDForPN(jid) || null)
29
+
30
+ // bidirectional — respects useLidForEncryption flag
31
+ export const resolveIssuanceJid = async (jid, issueToLid, getLIDForPN, getPNForLID) => {
32
+ if (issueToLid) return isLidUser(jid) ? jid : (await getLIDForPN(jid)) ?? jid
33
+ if (!isLidUser(jid)) return jid
34
+ return getPNForLID ? (await getPNForLID(jid)) ?? jid : jid
35
+ }
36
+
37
+ // ─── Expiry ───────────────────────────────────────────────────────────────────
38
+
39
+ export const isTcTokenExpired = timestamp => {
40
+ if (timestamp == null) return true
41
+ const ts = typeof timestamp === 'string' ? parseInt(timestamp) : timestamp
42
+ return isNaN(ts) || ts < (currentBucket() - (TC_TOKEN_NUM_BUCKETS - 1)) * TC_TOKEN_BUCKET_DURATION
43
+ }
44
+
45
+ // re-issue only if sender crossed into a new bucket since last issuance
46
+ export const shouldSendNewTcToken = senderTimestamp => {
47
+ if (senderTimestamp === undefined) return true
48
+ return currentBucket() > Math.floor(senderTimestamp / TC_TOKEN_BUCKET_DURATION)
49
+ }
50
+
51
+ // ─── Index ────────────────────────────────────────────────────────────────────
52
+
53
+ export const readTcTokenIndex = async keys => {
54
+ for (const key of [TC_TOKEN_INDEX_KEY, 'index']) {
55
+ const entry = (await keys.get('tctoken', [key]))[key]
56
+ if (!entry?.token?.length) continue
57
+ try {
58
+ const parsed = JSON.parse(Buffer.from(entry.token).toString())
59
+ if (!Array.isArray(parsed)) continue
60
+ return parsed.filter(j => typeof j === 'string' && j.length > 0 && j !== TC_TOKEN_INDEX_KEY && j !== 'index')
61
+ } catch { continue }
62
+ }
63
+ return []
64
+ }
65
+
66
+ export const buildMergedTcTokenIndexWrite = async (keys, addedJids) => {
67
+ const merged = new Set(await readTcTokenIndex(keys))
68
+ for (const jid of addedJids) if (jid && jid !== TC_TOKEN_INDEX_KEY && jid !== 'index') merged.add(jid)
69
+ return { [TC_TOKEN_INDEX_KEY]: { token: Buffer.from(JSON.stringify([...merged])) } }
70
+ }
71
+
72
+ // ─── Pre-seed ─────────────────────────────────────────────────────────────────
73
+
74
+ export const preSeedTcToken = async ({ authState, jid, getLIDForPN, logger }) => {
75
+ const tcTokenJid = await resolveTcTokenJid(jid, getLIDForPN)
76
+ const existing = await authState.keys.get('tctoken', [tcTokenJid])
77
+ if (existing[tcTokenJid]?.token?.length) return { token: existing[tcTokenJid].token, storageJid: tcTokenJid }
78
+ const token = generateTcToken()
79
+ const timestamp = String(unixTimestampSeconds())
80
+ const indexWrite = await buildMergedTcTokenIndexWrite(authState.keys, [tcTokenJid])
81
+ await authState.keys.set({ tctoken: { [tcTokenJid]: { ...(existing[tcTokenJid] || {}), token, timestamp }, ...indexWrite } })
82
+ logger?.debug({ jid, tcTokenJid }, 'pre-seeded locally generated tctoken')
83
+ return { token, storageJid: tcTokenJid }
84
+ }
85
+
86
+ // ─── Outgoing nodes ───────────────────────────────────────────────────────────
87
+ // confirmed wire format: <tctoken>bytes</tctoken> — flat, identical to fanout format, no smax:any wrapper
88
+ // timestamp attr is internal only, never sent on wire
89
+ export const buildTcTokenFromJid = async ({ authState, jid, baseContent = [], getLIDForPN }) => {
90
+ try {
91
+ const storageJid = await resolveTcTokenJid(jid, getLIDForPN)
92
+ const entry = (await authState.keys.get('tctoken', [storageJid]))?.[storageJid]
93
+ const { token: tcTokenBuffer, timestamp, senderTimestamp } = entry ?? {}
94
+ if (!tcTokenBuffer?.length || timestamp === undefined || isTcTokenExpired(timestamp)) {
95
+ if (tcTokenBuffer) {
96
+ const cleared = senderTimestamp !== undefined ? { token: Buffer.alloc(0), senderTimestamp } : null
97
+ await authState.keys.set({ tctoken: { [storageJid]: cleared } })
98
+ }
99
+ return baseContent.length > 0 ? baseContent : undefined
100
+ }
101
+ if (tcTokenBuffer.length < TC_TOKEN_MIN_BYTES || tcTokenBuffer.length > TC_TOKEN_MAX_BYTES) return baseContent.length > 0 ? baseContent : undefined
102
+ baseContent.push({ tag: 'tctoken', attrs: {}, content: tcTokenBuffer })
103
+ return baseContent
104
+ } catch { return baseContent.length > 0 ? baseContent : undefined }
105
+ }
106
+
107
+ // fanout <to> node — confirmed wire format: <tctoken>bytes</tctoken> (no smax:any wrapper)
108
+ // enforces per-send JID dedup (EOC.A01 Set guard) and flag-20606 recipient cap
109
+ export const buildFanoutTcTokenNode = ({ tokenBuffer, recipientsSeen, userJid }) => {
110
+ if (
111
+ !tokenBuffer?.length
112
+ || tokenBuffer.length < TC_TOKEN_MIN_BYTES
113
+ || tokenBuffer.length > TC_TOKEN_MAX_BYTES
114
+ || recipientsSeen.size >= TC_TOKEN_MAX_RECIPIENTS
115
+ || recipientsSeen.has(userJid)
116
+ ) return null
117
+ recipientsSeen.add(userJid)
118
+ return { tag: 'tctoken', attrs: {}, content: tokenBuffer }
119
+ }
120
+
121
+ // ─── Incoming storage ─────────────────────────────────────────────────────────
122
+
123
+ // handles both IQ result and privacy_token notification (same <tokens> structure)
124
+ // wire format: <token type="trusted_contact" t="timestamp">bytes</token>
125
+ export const storeTcTokensFromIqResult = async ({ result, fallbackJid, keys, getLIDForPN, onNewJidStored }) => {
126
+ const tokensNode = getBinaryNodeChild(result, 'tokens')
127
+ if (!tokensNode) return
128
+ for (const tokenNode of getBinaryNodeChildren(tokensNode, 'token')) {
129
+ if (tokenNode.attrs.type !== 'trusted_contact') continue
130
+ if (!(tokenNode.content instanceof Uint8Array) || !tokenNode.content.length) continue
131
+ const tokenBytes = tokenNode.content
132
+ if (tokenBytes.length > TC_TOKEN_MAX_BYTES) continue
133
+ const rawJid = jidNormalizedUser(fallbackJid || tokenNode.attrs.jid)
134
+ if (!isRegularUser(rawJid)) continue
135
+ const storageJid = await resolveTcTokenJid(rawJid, getLIDForPN)
136
+ const existingEntry = (await keys.get('tctoken', [storageJid]))[storageJid]
137
+ const existingTs = existingEntry?.timestamp ? Number(existingEntry.timestamp) : 0
138
+ const incomingTs = tokenNode.attrs.t ? Number(tokenNode.attrs.t) : 0
139
+ if (!incomingTs || (existingTs > 0 && existingTs > incomingTs)) continue
140
+ await keys.set({ tctoken: { [storageJid]: { ...existingEntry, token: Buffer.from(tokenBytes), timestamp: tokenNode.attrs.t } } })
141
+ onNewJidStored?.(storageJid)
142
+ }
143
+ }
144
+
145
+ // ─── Content binding ──────────────────────────────────────────────────────────
146
+
147
+ // URL-type messages only — confirmed from AbstractC2052DmX.A00()
148
+ // wire format: <content_binding>bytes</content_binding> (flat, no wrapper)
149
+ export const buildContentBindingNode = ({ userJid, contentBindingMap, messageType }) => {
150
+ if (messageType !== 'url' || !contentBindingMap?.has(userJid)) return null
151
+ const bytes = contentBindingMap.get(userJid)
152
+ if (!bytes?.length) return null
153
+ return { tag: 'content_binding', attrs: {}, content: bytes }
154
+ }
@@ -0,0 +1,200 @@
1
+ import { Keyv, detectKeyvStorage } from 'keyv'
2
+ import { DEFAULT_PREKEY_RETENTION, DEFAULT_CLEANUP_THRESHOLD, CLEANUP_INTERVAL_MS, DEFAULT_COLLECTION_NAME } from '../Defaults/index.js'
3
+ import { bootstrapCreds, patchAppStateKey, ser, deser } from './auth-utils.js'
4
+ import { PROTOCOL_ADAPTERS } from '../WABinary/index.js'
5
+ import logger from './logger.js'
6
+
7
+ // ── Adapter resolution ────────────────────────────────────────────────────────
8
+
9
+ // Only these adapters accept a named collection/table — redis, valkey, etcd etc do not
10
+ const COLLECTION_KEY = { '@keyv/mongo': 'collection', '@keyv/postgres': 'table', '@keyv/mysql': 'table', '@keyv/sqlite': 'table' }
11
+
12
+ // Cached per conn::col::namespace — each session gets its own adapter instance so
13
+ // clear() never bleeds across sessions. Underlying drivers manage their own connection
14
+ // pools so multiple adapters on the same URI still share one real connection.
15
+ const _adapterCache = new Map()
16
+ export const clearAdapterCache = () => _adapterCache.clear()
17
+
18
+ const resolveAdapter = async (conn, col, namespace) => {
19
+ const ck = `${conn}::${col ?? ''}::${namespace ?? ''}`
20
+ if (_adapterCache.has(ck)) return _adapterCache.get(ck)
21
+ let protocol
22
+ try { protocol = new URL(conn).protocol } catch { throw new Error(`[Auth] Invalid connection string: "${conn}"`) }
23
+ const pkg = PROTOCOL_ADAPTERS[protocol]
24
+ if (!pkg) throw new Error(`[Auth] Unsupported protocol "${protocol}" — supported: ${Object.keys(PROTOCOL_ADAPTERS).map(p => p.replace(':', '')).join(', ')}`)
25
+ let mod
26
+ try { mod = await import(pkg) } catch (e) {
27
+ if (e.code === 'ERR_MODULE_NOT_FOUND') throw new Error(`[Auth] "${pkg}" required — npm i ${pkg}`)
28
+ throw e
29
+ }
30
+ const Adapter = mod.default ?? mod[Object.keys(mod)[0]]
31
+ const optKey = COLLECTION_KEY[pkg]
32
+ const adapter = col && optKey ? new Adapter({ url: conn, uri: conn, [optKey]: col }) : new Adapter(conn)
33
+ adapter.setMaxListeners?.(0)
34
+ if (namespace) adapter.namespace = namespace
35
+ _adapterCache.set(ck, adapter)
36
+ return adapter
37
+ }
38
+
39
+ const resolveStore = async (backend, col, namespace) => {
40
+ if (backend == null) return null
41
+ if (typeof backend === 'string') return resolveAdapter(backend, col, namespace)
42
+ if (backend instanceof Keyv) return backend.opts?.store ?? backend.store ?? null
43
+ const { compatible } = detectKeyvStorage(backend)
44
+ if (!compatible) throw new Error('[Auth] backend must be a connection string, Keyv instance, or KeyvStoreAdapter')
45
+ // scope namespace via prototype so we don't mutate the original store instance
46
+ const scoped = Object.create(backend)
47
+ if (namespace) scoped.namespace = namespace
48
+ return scoped
49
+ }
50
+
51
+ const makeKeyv = (store, namespace) => {
52
+ const keyv = store ? new Keyv({ store, namespace }) : new Keyv({ namespace })
53
+ keyv.setMaxListeners?.(0)
54
+ return keyv
55
+ }
56
+
57
+ // ── Keyv instance cache ───────────────────────────────────────────────────────
58
+
59
+ // Keyv's setStore() attaches a new 'error' listener on every call. Without caching,
60
+ // every useKeyvAuthState/hasKeyvAuth call creates a fresh Keyv, causing listener
61
+ // accumulation on the underlying store across reconnects and saveCreds bursts.
62
+ // WeakMap keyed by store so entries GC naturally when the store is dropped.
63
+ const _keyvCache = new WeakMap()
64
+
65
+ const getKeyv = (store, namespace) => {
66
+ // bind a default error listener so unhandled 'error' emissions never throw,
67
+ // regardless of whether useKeyvAuthState or hasKeyvAuth created this instance
68
+ const bind = k => (k.on('error', err => logger.warn({ err: err?.message, namespace }, '[Auth] store error')), k)
69
+ if (!store) return bind(makeKeyv(null, namespace))
70
+ if (!_keyvCache.has(store)) _keyvCache.set(store, new Map())
71
+ const nsMap = _keyvCache.get(store)
72
+ const key = namespace ?? ''
73
+ if (nsMap.has(key)) return nsMap.get(key)
74
+ const keyv = bind(makeKeyv(store, namespace))
75
+ nsMap.set(key, keyv)
76
+ return keyv
77
+ }
78
+
79
+ // ── Multi-backend support ─────────────────────────────────────────────────────
80
+
81
+ // Multi-backend map: { 'creds': pgBackend, 'pre-key': mongoBackend, ... }
82
+ // Anything else (string, Keyv, raw store adapter) is treated as single backend
83
+ const isMultiBackend = backend =>
84
+ backend !== null
85
+ && typeof backend === 'object'
86
+ && !Array.isArray(backend)
87
+ && !(backend instanceof Keyv)
88
+ && !detectKeyvStorage(backend).compatible
89
+
90
+ // Returns { get(type) → Keyv, all → Keyv[], stores → raw store refs }
91
+ // get(type) falls back to first entry if type not in map
92
+ // all is deduplicated — shared backends only clear once
93
+ // stores is exposed so clearSession can evict only this session from _keyvCache
94
+ const resolveBackendMap = async (backend, sessionId, collectionName) => {
95
+ if (!isMultiBackend(backend)) {
96
+ const store = await resolveStore(backend, collectionName, sessionId)
97
+ const keyv = getKeyv(store, sessionId)
98
+ return { get: () => keyv, all: [keyv], stores: [store] }
99
+ }
100
+ const entries = Object.entries(backend)
101
+ if (!entries.length) throw new Error('[Auth] backend map must have at least one entry')
102
+ // track { store, keyv } per backend so stores can be exposed for cache eviction
103
+ const resolved = new Map()
104
+ for (const [, b] of entries) {
105
+ if (!resolved.has(b)) {
106
+ const store = await resolveStore(b, collectionName, sessionId)
107
+ resolved.set(b, { store, keyv: getKeyv(store, sessionId) })
108
+ }
109
+ }
110
+ const typeMap = Object.fromEntries(entries.map(([type, b]) => [type, resolved.get(b).keyv]))
111
+ const defaultKeyv = resolved.get(entries[0][1]).keyv
112
+ return {
113
+ get: type => typeMap[type] ?? defaultKeyv,
114
+ all: [...new Set([...resolved.values()].map(r => r.keyv))],
115
+ stores: [...new Set([...resolved.values()].map(r => r.store))],
116
+ }
117
+ }
118
+
119
+ // ── Keyv-backed auth state ────────────────────────────────────────────────────
120
+
121
+ export const useKeyvAuthState = async (sessionId, backend, opts = {}) => {
122
+ const { preKeyRetention = DEFAULT_PREKEY_RETENTION, cleanupThreshold = DEFAULT_CLEANUP_THRESHOLD, collectionName = DEFAULT_COLLECTION_NAME } = opts
123
+ const bmap = await resolveBackendMap(backend, sessionId, collectionName)
124
+ const credsKeyv = bmap.get('creds')
125
+
126
+ const kn = (type, id) => `${type}-${id}`
127
+ const credsKey = 'creds'
128
+ let creds = bootstrapCreds(deser(await credsKeyv.get(credsKey)))
129
+ let cleanupRunning = false, lastCleanupAt = 0, lastCleanedId = creds.nextPreKeyId
130
+
131
+ const cleanOldPreKeys = async () => {
132
+ if (cleanupRunning || Date.now() - lastCleanupAt < CLEANUP_INTERVAL_MS) return
133
+ cleanupRunning = true
134
+ try {
135
+ const minId = creds.nextPreKeyId - preKeyRetention
136
+ if (minId <= 0) return
137
+ const ids = []
138
+ for (let id = Math.max(0, lastCleanedId - preKeyRetention); id < minId; id++) ids.push(kn('pre-key', id))
139
+ if (ids.length) await bmap.get('pre-key').deleteMany(ids)
140
+ lastCleanupAt = Date.now(); lastCleanedId = creds.nextPreKeyId
141
+ } catch (e) { logger.warn({ err: e.message, sessionId }, '[Auth] prekey cleanup failed') }
142
+ finally { cleanupRunning = false }
143
+ }
144
+ cleanOldPreKeys().catch(() => { })
145
+
146
+ const keys = {
147
+ get: async (type, ids) => {
148
+ if (!ids.length) return {}
149
+ const keyv = bmap.get(type)
150
+ const raws = await keyv.getMany(ids.map(id => kn(type, id)))
151
+ return Object.fromEntries(ids.map((id, i) => [id, patchAppStateKey(type, deser(raws[i]))]))
152
+ },
153
+ set: async data => {
154
+ // group by Keyv instance to batch writes per backend
155
+ const byKeyv = new Map()
156
+ for (const type in data) {
157
+ const keyv = bmap.get(type)
158
+ if (!byKeyv.has(keyv)) byKeyv.set(keyv, { sets: [], dels: [] })
159
+ const bucket = byKeyv.get(keyv)
160
+ for (const id in data[type]) {
161
+ const v = data[type][id], k = kn(type, id)
162
+ if (v != null) bucket.sets.push({ key: k, value: ser(v) })
163
+ else bucket.dels.push(k)
164
+ }
165
+ }
166
+ await Promise.all([...byKeyv.entries()].map(([keyv, { sets, dels }]) =>
167
+ Promise.all([sets.length ? keyv.setMany(sets) : null, dels.length ? keyv.deleteMany(dels) : null])
168
+ ))
169
+ }
170
+ }
171
+
172
+ const saveCreds = async () => {
173
+ if (creds.nextPreKeyId - lastCleanedId >= cleanupThreshold) cleanOldPreKeys().catch(() => { })
174
+ await credsKeyv.set(credsKey, ser(creds))
175
+ }
176
+
177
+ const clearSession = async () => {
178
+ try { await Promise.all(bmap.all.map(keyv => keyv.clear())) }
179
+ catch (e) { logger.warn({ err: e.message, sessionId }, '[Auth] clearSession failed') }
180
+ // evict only this session from _keyvCache so its Keyv instance and listener are released
181
+ bmap.stores?.forEach(store => {
182
+ const nsMap = _keyvCache.get(store)
183
+ if (nsMap) nsMap.delete(sessionId)
184
+ })
185
+ }
186
+
187
+ return { state: { creds, keys }, saveCreds, clearSession }
188
+ }
189
+
190
+ // Lightweight check — reads only the creds key without full state init
191
+ export const hasKeyvAuth = async (sessionId, backend, opts = {}) => {
192
+ try {
193
+ const b = isMultiBackend(backend) ? Object.values(backend)[0] : backend
194
+ const bmap = await resolveBackendMap(b, sessionId, opts.collectionName ?? DEFAULT_COLLECTION_NAME)
195
+ const parsed = deser(await bmap.get('creds').get('creds'))
196
+ return !!(parsed?.noiseKey && parsed?.signedIdentityKey)
197
+ } catch { return false }
198
+ }
199
+
200
+ export { Keyv }
@@ -0,0 +1,84 @@
1
+ import { mkdir, readFile, rename, stat, unlink, writeFile, readdir } from 'fs/promises'
2
+ import { join } from 'path'
3
+ import { DEFAULT_PREKEY_RETENTION, DEFAULT_CLEANUP_THRESHOLD, CLEANUP_INTERVAL_MS } from '../Defaults/index.js'
4
+ import { bootstrapCreds, patchAppStateKey } from './auth-utils.js'
5
+ import { BufferJSON } from './generics.js'
6
+ import logger from './logger.js'
7
+
8
+ export const useMultiFileAuthState = async (folder, opts = {}) => {
9
+ const { preKeyRetention = DEFAULT_PREKEY_RETENTION, cleanupThreshold = DEFAULT_CLEANUP_THRESHOLD } = opts
10
+ const fix = f => f?.replace(/\//g, '__')?.replace(/:/g, '-')
11
+ const fp = f => join(folder, fix(f))
12
+
13
+ const info = await stat(folder).catch(() => null)
14
+ if (info) { if (!info.isDirectory()) throw new Error(`Not a directory: ${folder}`) }
15
+ else await mkdir(folder, { recursive: true })
16
+
17
+ const write = async (data, file) => {
18
+ const [p, t, payload] = [fp(file), fp(file) + '.tmp', JSON.stringify(data, BufferJSON.replacer)]
19
+ await writeFile(t, payload)
20
+ try { await rename(t, p) } catch { await writeFile(p, payload); await unlink(t).catch(() => { }) }
21
+ }
22
+ const read = async file => {
23
+ const raw = await readFile(fp(file), 'utf-8').catch(() => null)
24
+ if (!raw) return null
25
+ try {
26
+ const p = JSON.parse(raw, BufferJSON.reviver)
27
+ return p && typeof p === 'object' && '__checksum' in p && 'data' in p ? p.data : p
28
+ } catch (e) {
29
+ logger.warn({ err: e.message, file }, 'auth file corrupt — reinitializing')
30
+ await unlink(fp(file)).catch(() => { })
31
+ return null
32
+ }
33
+ }
34
+ const remove = f => unlink(fp(f)).catch(() => { })
35
+
36
+ let creds = bootstrapCreds(await read('creds.json'))
37
+ let cleanupPromise = null, lastCleanupAt = 0, lastCleanedId = creds.nextPreKeyId
38
+
39
+ const cleanOldPreKeys = async () => {
40
+ if (cleanupPromise || Date.now() - lastCleanupAt < CLEANUP_INTERVAL_MS) return
41
+ cleanupPromise = (async () => {
42
+ try {
43
+ const minId = creds.nextPreKeyId - preKeyRetention
44
+ if (minId <= 0) return
45
+ const targets = (await readdir(folder))
46
+ .map(f => f.match(/^pre-key-(\d+)\.json(\.tmp)?$/))
47
+ .filter(m => m && parseInt(m[1], 10) < minId)
48
+ .map(m => join(folder, m[0]))
49
+ if (targets.length) await Promise.all(targets.map(f => unlink(f).catch(() => { })))
50
+ lastCleanupAt = Date.now(); lastCleanedId = creds.nextPreKeyId
51
+ } catch (e) { logger.warn({ err: e.message }, 'prekey cleanup failed') }
52
+ finally { cleanupPromise = null }
53
+ })()
54
+ await cleanupPromise
55
+ }
56
+ cleanOldPreKeys().catch(() => { })
57
+
58
+ return {
59
+ state: {
60
+ creds,
61
+ keys: {
62
+ get: async (type, ids) => {
63
+ const data = {}
64
+ await Promise.all(ids.map(async id => { const v = await read(`${type}-${id}.json`); data[id] = patchAppStateKey(type, v) }))
65
+ return data
66
+ },
67
+ set: async data => {
68
+ const tasks = []
69
+ for (const cat in data)
70
+ for (const id in data[cat]) { const v = data[cat][id]; tasks.push(v ? write(v, `${cat}-${id}.json`) : remove(`${cat}-${id}.json`)) }
71
+ await Promise.all(tasks)
72
+ }
73
+ }
74
+ },
75
+ saveCreds: async () => {
76
+ if (creds.nextPreKeyId - lastCleanedId >= cleanupThreshold) cleanOldPreKeys().catch(() => { })
77
+ return write(creds, 'creds.json')
78
+ },
79
+ getStats: async () => {
80
+ const files = await readdir(folder).catch(() => [])
81
+ return { totalFiles: files.length, preKeyCount: files.filter(f => /^pre-key-\d+\.json$/.test(f)).length, nextPreKeyId: creds.nextPreKeyId, lastCleanupAt: lastCleanupAt ? new Date(lastCleanupAt).toISOString() : null }
82
+ }
83
+ }
84
+ }
@@ -0,0 +1,172 @@
1
+ import { Boom } from '@hapi/boom'
2
+ import { createHash } from 'crypto'
3
+ import { proto } from '../../WAProto/index.js'
4
+ import { KEY_BUNDLE_TYPE, WA_ADV_ACCOUNT_SIG_PREFIX, WA_ADV_DEVICE_SIG_PREFIX, WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX } from '../Defaults/index.js'
5
+ import { getBinaryNodeChild, jidDecode, S_WHATSAPP_NET } from '../WABinary/index.js'
6
+ import { Curve, hmacSign } from './crypto.js'
7
+ import { encodeBigEndian } from './generics.js'
8
+ import { createSignalIdentity } from './signal.js'
9
+ import { getPlatformType } from './browser-utils.js'
10
+
11
+ const PLATFORM_MAP = {
12
+ 'Mac OS': proto.ClientPayload.WebInfo.WebSubPlatform.DARWIN,
13
+ 'Windows': proto.ClientPayload.WebInfo.WebSubPlatform.WIN_HYBRID,
14
+ 'WindowsStore': proto.ClientPayload.WebInfo.WebSubPlatform.WIN_STORE,
15
+ }
16
+
17
+ const getUserAgent = (config) => ({
18
+ appVersion: {
19
+ primary: config.version[0],
20
+ secondary: config.version[1],
21
+ tertiary: config.version[2],
22
+ },
23
+ platform: proto.ClientPayload.UserAgent.Platform.WEB,
24
+ releaseChannel: proto.ClientPayload.UserAgent.ReleaseChannel.RELEASE,
25
+ osVersion: '0.1',
26
+ device: 'Desktop',
27
+ deviceType: proto.ClientPayload.UserAgent.DeviceType.DESKTOP,
28
+ osBuildNumber: '0.1',
29
+ localeLanguageIso6391: 'en',
30
+ mnc: '000',
31
+ mcc: '000',
32
+ localeCountryIso31661Alpha2: config.countryCode,
33
+ })
34
+
35
+ const getWebInfo = (config) => {
36
+ let webSubPlatform = proto.ClientPayload.WebInfo.WebSubPlatform.WEB_BROWSER
37
+ if (config.syncFullHistory && PLATFORM_MAP[config.browser[0]] && config.browser[1] === 'Desktop')
38
+ webSubPlatform = PLATFORM_MAP[config.browser[0]]
39
+ return { webSubPlatform }
40
+ }
41
+
42
+ const getClientPayload = (config) => {
43
+ const payload = {
44
+ connectType: proto.ClientPayload.ConnectType.WIFI_UNKNOWN,
45
+ connectReason: proto.ClientPayload.ConnectReason.USER_ACTIVATED,
46
+ userAgent: getUserAgent(config),
47
+ }
48
+ if (!config.browser[1].toLowerCase().includes('android')) payload.webInfo = getWebInfo(config)
49
+ return payload
50
+ }
51
+
52
+ const buildHistorySyncConfig = () => {
53
+ const fields = proto.DeviceProps.HistorySyncConfig.fields
54
+ const config = {}
55
+ for (const [name, field] of Object.entries(fields)) {
56
+ if (field.type === 'bool') config[name] = true
57
+ }
58
+ config.storageQuotaMb = 569150
59
+ config.supportCallLogHistory = false
60
+ config.supportGroupHistory = true
61
+ return config
62
+ }
63
+
64
+ export const generateLoginNode = (userJid, config) => {
65
+ const { user, device } = jidDecode(userJid)
66
+ return proto.ClientPayload.fromObject({
67
+ ...getClientPayload(config),
68
+ passive: true,
69
+ pull: true,
70
+ username: +user,
71
+ device,
72
+ lidDbMigrated: false, // hard-set; behaviour under true is unknown
73
+ })
74
+ }
75
+
76
+ export const generateRegistrationNode = ({ registrationId, signedPreKey, signedIdentityKey }, config) => {
77
+ const appVersionBuf = createHash('md5').update(config.version.join('.')).digest()
78
+ const companionProto = proto.DeviceProps.encode({
79
+ os: config.browser[0],
80
+ platformType: getPlatformType(config.browser[1]),
81
+ requireFullSync: config.syncFullHistory,
82
+ historySyncConfig: buildHistorySyncConfig(),
83
+ version: { primary: config.version[0], secondary: config.version[1], tertiary: config.version[2] },
84
+ }).finish()
85
+
86
+ return proto.ClientPayload.fromObject({
87
+ ...getClientPayload(config),
88
+ passive: false,
89
+ pull: false,
90
+ devicePairingData: {
91
+ eRegid: encodeBigEndian(registrationId),
92
+ eKeytype: KEY_BUNDLE_TYPE,
93
+ eIdent: signedIdentityKey.public,
94
+ eSkeyId: encodeBigEndian(signedPreKey.keyId, 3),
95
+ eSkeyVal: signedPreKey.keyPair.public,
96
+ eSkeySig: signedPreKey.signature,
97
+ buildHash: appVersionBuf,
98
+ deviceProps: companionProto,
99
+ },
100
+ })
101
+ }
102
+
103
+ export const configureSuccessfulPairing = (stanza, { advSecretKey, signedIdentityKey, signalIdentities }) => {
104
+ const msgId = stanza.attrs.id
105
+ const pairSuccessNode = getBinaryNodeChild(stanza, 'pair-success')
106
+ const deviceIdentityNode = getBinaryNodeChild(pairSuccessNode, 'device-identity')
107
+ const platformNode = getBinaryNodeChild(pairSuccessNode, 'platform')
108
+ const deviceNode = getBinaryNodeChild(pairSuccessNode, 'device')
109
+ const businessNode = getBinaryNodeChild(pairSuccessNode, 'biz')
110
+
111
+ if (!deviceIdentityNode || !deviceNode)
112
+ throw new Boom('Missing device-identity or device in pair success node', { data: stanza })
113
+
114
+ const jid = deviceNode.attrs.jid
115
+ const lid = deviceNode.attrs.lid
116
+ const bizName = businessNode?.attrs.name
117
+
118
+ const { details, hmac, accountType } = proto.ADVSignedDeviceIdentityHMAC.decode(deviceIdentityNode.content)
119
+ const hmacPrefix = (accountType !== undefined && accountType === proto.ADVEncryptionType.HOSTED)
120
+ ? WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX
121
+ : Buffer.from([])
122
+
123
+ if (Buffer.compare(hmac, hmacSign(Buffer.concat([hmacPrefix, details]), Buffer.from(advSecretKey, 'base64'))) !== 0)
124
+ throw new Boom('Invalid account signature')
125
+
126
+ const account = proto.ADVSignedDeviceIdentity.decode(details)
127
+ const { accountSignatureKey, accountSignature, details: deviceDetails } = account
128
+ const deviceIdentity = proto.ADVDeviceIdentity.decode(deviceDetails)
129
+
130
+ const accountSignaturePrefix = deviceIdentity.deviceType === proto.ADVEncryptionType.HOSTED
131
+ ? WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX
132
+ : WA_ADV_ACCOUNT_SIG_PREFIX
133
+
134
+ if (!Curve.verify(accountSignatureKey, Buffer.concat([accountSignaturePrefix, deviceDetails, signedIdentityKey.public]), accountSignature))
135
+ throw new Boom('Failed to verify account signature')
136
+
137
+ account.deviceSignature = Curve.sign(
138
+ signedIdentityKey.private,
139
+ Buffer.concat([WA_ADV_DEVICE_SIG_PREFIX, deviceDetails, signedIdentityKey.public, accountSignatureKey])
140
+ )
141
+
142
+ const identity = createSignalIdentity(lid, accountSignatureKey)
143
+ const accountEnc = encodeSignedDeviceIdentity(account, false)
144
+
145
+ return {
146
+ creds: {
147
+ account,
148
+ me: { id: jid, name: bizName, lid },
149
+ signalIdentities: [...(signalIdentities ?? []), identity],
150
+ platform: platformNode?.attrs.name,
151
+ },
152
+ reply: {
153
+ tag: 'iq',
154
+ attrs: { to: S_WHATSAPP_NET, type: 'result', id: msgId },
155
+ content: [{
156
+ tag: 'pair-device-sign',
157
+ attrs: {},
158
+ content: [{
159
+ tag: 'device-identity',
160
+ attrs: { 'key-index': deviceIdentity.keyIndex.toString() },
161
+ content: accountEnc,
162
+ }],
163
+ }],
164
+ },
165
+ }
166
+ }
167
+
168
+ export const encodeSignedDeviceIdentity = (account, includeSignatureKey) => {
169
+ account = { ...account }
170
+ if (!includeSignatureKey || !account.accountSignatureKey?.length) account.accountSignatureKey = null
171
+ return proto.ADVSignedDeviceIdentity.encode(account).finish()
172
+ }