@zervonexx/baileys 5.0.0 → 5.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +22 -22
- package/README.md +4124 -4112
- package/WAProto/WAProto.json +1 -0
- package/WAProto/WAProto.proto +7160 -0
- package/WAProto/WAProtoCompile.js +264 -322
- package/WAProto/index.js +55 -95
- package/lib/Builders/AIRich.js +673 -673
- package/lib/Builders/auto.js +49 -49
- package/lib/Builders/base.js +144 -144
- package/lib/Builders/builders.js +588 -588
- package/lib/Builders/index.js +3 -3
- package/lib/Defaults/index.js +249 -248
- package/lib/Signal/index.js +2 -2
- package/lib/Signal/libsignal.js +526 -526
- package/lib/Signal/lid-mapping.js +282 -282
- package/lib/Socket/Client/index.js +1 -1
- package/lib/Socket/Client/types.js +9 -9
- package/lib/Socket/Client/websocket.js +83 -83
- package/lib/Socket/business.js +151 -151
- package/lib/Socket/chats.js +854 -854
- package/lib/Socket/communities.js +146 -146
- package/lib/Socket/groups.js +293 -293
- package/lib/Socket/index.js +17 -14
- package/lib/Socket/messages-recv.js +993 -993
- package/lib/Socket/messages-send.js +722 -722
- package/lib/Socket/mex.js +33 -33
- package/lib/Socket/newsletter.js +783 -783
- package/lib/Socket/registration.js +154 -154
- package/lib/Socket/socket.js +797 -797
- package/lib/Socket/spam-report.js +143 -143
- package/lib/Socket/username.js +81 -81
- package/lib/Socket/zervonex-handler.js +57 -57
- package/lib/Store/index.js +6 -6
- package/lib/Store/make-cache-manager-store.js +80 -80
- package/lib/Store/make-in-memory-store.js +426 -426
- package/lib/Store/make-ordered-dictionary.js +81 -81
- package/lib/Store/object-repository.js +30 -30
- package/lib/Store/reporting-info-store.js +37 -37
- package/lib/Types/Auth.js +1 -1
- package/lib/Types/Bussines.js +1 -1
- package/lib/Types/Call.js +1 -1
- package/lib/Types/Chat.js +7 -7
- package/lib/Types/Contact.js +1 -1
- package/lib/Types/Events.js +1 -1
- package/lib/Types/GroupMetadata.js +1 -1
- package/lib/Types/Label.js +24 -24
- package/lib/Types/LabelAssociation.js +6 -6
- package/lib/Types/Message.js +14 -14
- package/lib/Types/Newsletter.js +99 -99
- package/lib/Types/Product.js +1 -1
- package/lib/Types/Signal.js +1 -1
- package/lib/Types/Socket.js +14 -14
- package/lib/Types/State.js +26 -26
- package/lib/Types/USync.js +1 -1
- package/lib/Types/index.js +30 -30
- package/lib/Utils/auth-utils.js +159 -159
- package/lib/Utils/baileys-event-stream.js +32 -32
- package/lib/Utils/bot-capabilities.js +40 -40
- package/lib/Utils/bot-planning-replay.js +43 -43
- package/lib/Utils/browser-utils.js +29 -29
- package/lib/Utils/business.js +74 -74
- package/lib/Utils/chat-utils.js +316 -316
- package/lib/Utils/companion-reg-client-utils.js +19 -19
- package/lib/Utils/consumer-application.js +37 -37
- package/lib/Utils/crypto.js +52 -52
- package/lib/Utils/cstoken.js +14 -14
- package/lib/Utils/decode-wa-message.js +199 -199
- package/lib/Utils/event-buffer.js +272 -272
- package/lib/Utils/extras.js +186 -186
- package/lib/Utils/generics.js +195 -194
- package/lib/Utils/history.js +50 -50
- package/lib/Utils/identity-change-handler.js +18 -18
- package/lib/Utils/index.js +40 -40
- package/lib/Utils/link-preview.js +50 -50
- package/lib/Utils/logger.js +3 -2
- package/lib/Utils/lt-hash.js +3 -3
- package/lib/Utils/make-mutex.js +15 -15
- package/lib/Utils/message-composer.js +61 -61
- package/lib/Utils/message-retry-manager.js +47 -47
- package/lib/Utils/messages-media.js +501 -501
- package/lib/Utils/messages.js +944 -942
- package/lib/Utils/meta-ai-msmsg.js +121 -121
- package/lib/Utils/meta-compositing.js +74 -74
- package/lib/Utils/modern-messages.js +234 -234
- package/lib/Utils/native-flow.js +80 -80
- package/lib/Utils/noise-handler.js +160 -160
- package/lib/Utils/pre-key-manager.js +75 -75
- package/lib/Utils/process-message.js +400 -400
- package/lib/Utils/reporting-utils.js +170 -170
- package/lib/Utils/signal.js +166 -166
- package/lib/Utils/spam-report-utils.js +165 -165
- package/lib/Utils/sync-action-utils.js +33 -33
- package/lib/Utils/tc-token-utils.js +153 -153
- package/lib/Utils/use-keyv-auth-state.js +199 -199
- package/lib/Utils/use-multi-file-auth-state.js +83 -83
- package/lib/Utils/validate-connection.js +171 -171
- package/lib/WABinary/constants.js +1320 -1320
- package/lib/WABinary/decode.js +151 -151
- package/lib/WABinary/encode.js +139 -139
- package/lib/WABinary/generic-utils.js +202 -202
- package/lib/WABinary/index.js +6 -6
- package/lib/WABinary/jid-utils.js +235 -235
- package/lib/WABinary/types.js +4 -4
- package/lib/WAM/BinaryInfo.js +9 -9
- package/lib/WAM/constants.js +22852 -22852
- package/lib/WAM/encode.js +149 -149
- package/lib/WAM/index.js +3 -3
- package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +30 -30
- package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +48 -48
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +23 -23
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +28 -28
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +15 -15
- package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +24 -24
- package/lib/WAUSync/Protocols/USyncLIDProtocol.js +9 -9
- package/lib/WAUSync/Protocols/USyncPictureProtocol.js +21 -21
- package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +19 -19
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +19 -19
- package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +22 -22
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +16 -16
- package/lib/WAUSync/Protocols/index.js +12 -12
- package/lib/WAUSync/USyncQuery.js +88 -88
- package/lib/WAUSync/USyncUser.js +20 -20
- package/lib/WAUSync/index.js +3 -3
- package/lib/index.js +66 -66
- package/package.json +187 -192
- package/WAProto/fetcher.js +0 -68
- package/WAProto/parser.js +0 -334
|
@@ -1,200 +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
|
-
|
|
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
200
|
export { Keyv }
|
|
@@ -1,84 +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
|
-
}
|
|
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
84
|
}
|