@itznomo/baileys 0.0.0-stage → 0.0.3
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,594 @@
|
|
|
1
|
+
import { mkdir, readFile, rename, stat, unlink, writeFile } from 'node:fs/promises'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import { proto } from '../../WAProto/index.js'
|
|
4
|
+
import { initAuthCreds } from './auth-state-core.js'
|
|
5
|
+
import { BufferJSON } from './wa-protocol-core.js'
|
|
6
|
+
import { Cache } from '../foundation/cache.js'
|
|
7
|
+
import { makeKeyedMutex } from '../foundation/concurrency.js'
|
|
8
|
+
import { SqlDatabase } from '../foundation/sql-database.js'
|
|
9
|
+
|
|
10
|
+
export const useMultiFileAuthState = async folder => {
|
|
11
|
+
const fileLock = makeKeyedMutex()
|
|
12
|
+
|
|
13
|
+
const fixFileName = file => file?.replace(/\//g, '__')?.replace(/:/g, '-')
|
|
14
|
+
|
|
15
|
+
const writeData = async (data, file) => {
|
|
16
|
+
const filePath = join(folder, fixFileName(file))
|
|
17
|
+
return fileLock.mutex(filePath, () => writeFile(filePath, JSON.stringify(data, BufferJSON.replacer)))
|
|
18
|
+
}
|
|
19
|
+
const readData = async file => {
|
|
20
|
+
try {
|
|
21
|
+
const filePath = join(folder, fixFileName(file))
|
|
22
|
+
return await fileLock.mutex(filePath, async () => {
|
|
23
|
+
const data = await readFile(filePath, { encoding: 'utf-8' })
|
|
24
|
+
return JSON.parse(data, BufferJSON.reviver)
|
|
25
|
+
})
|
|
26
|
+
} catch {
|
|
27
|
+
return null
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
const removeData = async file => {
|
|
31
|
+
try {
|
|
32
|
+
const filePath = join(folder, fixFileName(file))
|
|
33
|
+
await fileLock.mutex(filePath, async () => {
|
|
34
|
+
try {
|
|
35
|
+
await unlink(filePath)
|
|
36
|
+
} catch {
|
|
37
|
+
|
|
38
|
+
}
|
|
39
|
+
})
|
|
40
|
+
} catch {
|
|
41
|
+
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const folderInfo = await stat(folder).catch(() => {})
|
|
46
|
+
if (folderInfo) {
|
|
47
|
+
if (!folderInfo.isDirectory()) {
|
|
48
|
+
throw new Error(`found something that is not a directory at ${folder}, either delete it or specify a different location`)
|
|
49
|
+
}
|
|
50
|
+
} else {
|
|
51
|
+
await mkdir(folder, { recursive: true })
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const creds = (await readData('creds.json')) || initAuthCreds()
|
|
55
|
+
|
|
56
|
+
return {
|
|
57
|
+
state: {
|
|
58
|
+
creds,
|
|
59
|
+
keys: {
|
|
60
|
+
get: async (type, ids) => {
|
|
61
|
+
const data = {}
|
|
62
|
+
await Promise.all(
|
|
63
|
+
ids.map(async id => {
|
|
64
|
+
let value = await readData(`${type}-${id}.json`)
|
|
65
|
+
if (type === 'app-state-sync-key' && value) value = proto.Message.AppStateSyncKeyData.fromObject(value)
|
|
66
|
+
data[id] = value
|
|
67
|
+
})
|
|
68
|
+
)
|
|
69
|
+
return data
|
|
70
|
+
},
|
|
71
|
+
set: async data => {
|
|
72
|
+
const tasks = []
|
|
73
|
+
for (const category in data) {
|
|
74
|
+
for (const id in data[category]) {
|
|
75
|
+
const value = data[category][id]
|
|
76
|
+
const file = `${category}-${id}.json`
|
|
77
|
+
tasks.push(value ? writeData(value, file) : removeData(file))
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
await Promise.all(tasks)
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
},
|
|
84
|
+
saveCreds: async () => writeData(creds, 'creds.json')
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const SIGNAL_STORE_TTL_MS = 5 * 60 * 1000
|
|
89
|
+
const FLUSH_TIMEOUT_MS = 3000
|
|
90
|
+
|
|
91
|
+
export const useSingleFileAuthState = async fileName => {
|
|
92
|
+
const cache = new Cache({ max: 10000, ttl: SIGNAL_STORE_TTL_MS })
|
|
93
|
+
const mutex = makeKeyedMutex()
|
|
94
|
+
let fileData = {}
|
|
95
|
+
let isLoaded = false
|
|
96
|
+
let flushTimeout = null
|
|
97
|
+
|
|
98
|
+
const loadKey = () =>
|
|
99
|
+
mutex.mutex('__file__', async () => {
|
|
100
|
+
if (isLoaded) return
|
|
101
|
+
try {
|
|
102
|
+
const data = JSON.parse(await readFile(fileName, 'utf-8'), BufferJSON.reviver)
|
|
103
|
+
fileData = data || {}
|
|
104
|
+
for (const [keyName, value] of Object.entries(fileData)) cache.set(keyName, value)
|
|
105
|
+
} catch {
|
|
106
|
+
fileData = {}
|
|
107
|
+
}
|
|
108
|
+
isLoaded = true
|
|
109
|
+
})
|
|
110
|
+
|
|
111
|
+
const flushKey = () => {
|
|
112
|
+
if (flushTimeout) return
|
|
113
|
+
flushTimeout = setTimeout(async () => {
|
|
114
|
+
flushTimeout = null
|
|
115
|
+
await mutex.mutex('__file__', async () => {
|
|
116
|
+
try {
|
|
117
|
+
const tempFile = fileName + '.temp'
|
|
118
|
+
await writeFile(tempFile, JSON.stringify(fileData, BufferJSON.replacer))
|
|
119
|
+
await rename(tempFile, fileName)
|
|
120
|
+
} catch {
|
|
121
|
+
|
|
122
|
+
}
|
|
123
|
+
})
|
|
124
|
+
}, FLUSH_TIMEOUT_MS)
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const writeKey = (keyName, value) => {
|
|
128
|
+
cache.set(keyName, value)
|
|
129
|
+
fileData[keyName] = value
|
|
130
|
+
flushKey()
|
|
131
|
+
}
|
|
132
|
+
const removeKey = keyName => {
|
|
133
|
+
cache.delete(keyName)
|
|
134
|
+
delete fileData[keyName]
|
|
135
|
+
flushKey()
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const fileInfo = await stat(fileName).catch(() => null)
|
|
139
|
+
if (!fileInfo) {
|
|
140
|
+
await writeFile(fileName, '{}')
|
|
141
|
+
} else if (!fileInfo.isFile()) {
|
|
142
|
+
throw new Error(`found something that is not a file at ${fileName}, either delete it or specify a different location`)
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
await loadKey()
|
|
146
|
+
const creds = fileData['creds'] || initAuthCreds()
|
|
147
|
+
|
|
148
|
+
return {
|
|
149
|
+
state: {
|
|
150
|
+
creds,
|
|
151
|
+
keys: {
|
|
152
|
+
get: (type, ids) => {
|
|
153
|
+
const data = {}
|
|
154
|
+
for (const id of ids) {
|
|
155
|
+
const keyName = type + id
|
|
156
|
+
let value = cache.get(keyName)
|
|
157
|
+
if (value === undefined && fileData[keyName] !== undefined) {
|
|
158
|
+
value = fileData[keyName]
|
|
159
|
+
cache.set(keyName, value)
|
|
160
|
+
}
|
|
161
|
+
if (type === 'app-state-sync-key' && value) value = proto.Message.AppStateSyncKeyData.fromObject(value)
|
|
162
|
+
data[id] = value
|
|
163
|
+
}
|
|
164
|
+
return data
|
|
165
|
+
},
|
|
166
|
+
set: data => {
|
|
167
|
+
for (const category in data) {
|
|
168
|
+
for (const id in data[category]) {
|
|
169
|
+
const keyName = category + id
|
|
170
|
+
const value = data[category][id]
|
|
171
|
+
value ? writeKey(keyName, value) : removeKey(keyName)
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
},
|
|
177
|
+
saveCreds: () => writeKey('creds', creds)
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function adaptDb(db) {
|
|
182
|
+
const pragma = typeof db.pragma === 'function' ? stmt => db.pragma(stmt) : stmt => db.exec(`PRAGMA ${stmt}`)
|
|
183
|
+
const transaction =
|
|
184
|
+
typeof db.transaction === 'function'
|
|
185
|
+
? fn => db.transaction(fn)
|
|
186
|
+
: fn =>
|
|
187
|
+
(...args) => {
|
|
188
|
+
db.exec('BEGIN')
|
|
189
|
+
try {
|
|
190
|
+
const result = fn(...args)
|
|
191
|
+
db.exec('COMMIT')
|
|
192
|
+
return result
|
|
193
|
+
} catch (err) {
|
|
194
|
+
db.exec('ROLLBACK')
|
|
195
|
+
throw err
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
return { db, pragma, transaction }
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const CREDS_ROW_KEY = '__creds__'
|
|
202
|
+
const CREATE_SCHEMA_SQL = `
|
|
203
|
+
CREATE TABLE IF NOT EXISTS creds (
|
|
204
|
+
key TEXT PRIMARY KEY,
|
|
205
|
+
value TEXT NOT NULL
|
|
206
|
+
);
|
|
207
|
+
CREATE TABLE IF NOT EXISTS signal_keys (
|
|
208
|
+
type TEXT NOT NULL,
|
|
209
|
+
id TEXT NOT NULL,
|
|
210
|
+
value TEXT NOT NULL,
|
|
211
|
+
PRIMARY KEY (type, id)
|
|
212
|
+
);
|
|
213
|
+
CREATE INDEX IF NOT EXISTS signal_keys_type_idx ON signal_keys(type);
|
|
214
|
+
`
|
|
215
|
+
|
|
216
|
+
export async function useSqliteAuthState(opts) {
|
|
217
|
+
const rawDb = opts.database ?? new SqlDatabase(opts.dbPath)
|
|
218
|
+
const { db, pragma, transaction } = adaptDb(rawDb)
|
|
219
|
+
|
|
220
|
+
pragma('journal_mode = WAL')
|
|
221
|
+
pragma('synchronous = NORMAL')
|
|
222
|
+
db.exec(CREATE_SCHEMA_SQL)
|
|
223
|
+
|
|
224
|
+
const stmts = {
|
|
225
|
+
credsSelect: db.prepare('SELECT value FROM creds WHERE key = ?'),
|
|
226
|
+
credsUpsert: db.prepare('INSERT INTO creds (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value'),
|
|
227
|
+
keySelect: db.prepare('SELECT value FROM signal_keys WHERE type = ? AND id = ?'),
|
|
228
|
+
keyUpsert: db.prepare('INSERT INTO signal_keys (type, id, value) VALUES (?, ?, ?) ON CONFLICT(type, id) DO UPDATE SET value = excluded.value'),
|
|
229
|
+
keyDelete: db.prepare('DELETE FROM signal_keys WHERE type = ? AND id = ?'),
|
|
230
|
+
keyListIds: db.prepare('SELECT id FROM signal_keys WHERE type = ?'),
|
|
231
|
+
keyList: db.prepare('SELECT id, value FROM signal_keys WHERE type = ?'),
|
|
232
|
+
clearKeys: db.prepare('DELETE FROM signal_keys')
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const loadCreds = () => {
|
|
236
|
+
const row = stmts.credsSelect.get(CREDS_ROW_KEY)
|
|
237
|
+
if (!row) return initAuthCreds()
|
|
238
|
+
return JSON.parse(row.value, BufferJSON.reviver)
|
|
239
|
+
}
|
|
240
|
+
const persistCreds = creds => {
|
|
241
|
+
stmts.credsUpsert.run(CREDS_ROW_KEY, JSON.stringify(creds, BufferJSON.replacer))
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
const creds = loadCreds()
|
|
245
|
+
|
|
246
|
+
return {
|
|
247
|
+
state: {
|
|
248
|
+
creds,
|
|
249
|
+
keys: {
|
|
250
|
+
get: async (type, ids) => {
|
|
251
|
+
const data = {}
|
|
252
|
+
for (const id of ids) {
|
|
253
|
+
const row = stmts.keySelect.get(type, id)
|
|
254
|
+
if (row) {
|
|
255
|
+
let value = JSON.parse(row.value, BufferJSON.reviver)
|
|
256
|
+
if (type === 'app-state-sync-key' && value) value = proto.Message.AppStateSyncKeyData.fromObject(value)
|
|
257
|
+
data[id] = value
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
return data
|
|
261
|
+
},
|
|
262
|
+
set: async data => {
|
|
263
|
+
const writeTx = transaction(() => {
|
|
264
|
+
for (const category in data) {
|
|
265
|
+
for (const id in data[category]) {
|
|
266
|
+
const value = data[category][id]
|
|
267
|
+
if (value) {
|
|
268
|
+
stmts.keyUpsert.run(category, id, JSON.stringify(value, BufferJSON.replacer))
|
|
269
|
+
} else {
|
|
270
|
+
stmts.keyDelete.run(category, id)
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
})
|
|
275
|
+
writeTx()
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
},
|
|
279
|
+
saveCreds: async () => persistCreds(creds)
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
async function resolveMongoCollection(opts, secondArg) {
|
|
284
|
+
let collection = null
|
|
285
|
+
let client = null
|
|
286
|
+
let sessionId = null
|
|
287
|
+
|
|
288
|
+
if (typeof opts === 'string') {
|
|
289
|
+
if (opts.startsWith('mongodb://') || opts.startsWith('mongodb+srv://')) {
|
|
290
|
+
opts = { url: opts }
|
|
291
|
+
if (typeof secondArg === 'string') {
|
|
292
|
+
sessionId = secondArg
|
|
293
|
+
} else if (secondArg && typeof secondArg === 'object') {
|
|
294
|
+
opts = { ...opts, ...secondArg }
|
|
295
|
+
sessionId = opts.sessionId
|
|
296
|
+
}
|
|
297
|
+
} else {
|
|
298
|
+
throw new Error(`Invalid MongoDB connection string: "${opts}"`)
|
|
299
|
+
}
|
|
300
|
+
} else if (typeof secondArg === 'string') {
|
|
301
|
+
sessionId = secondArg
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
if (!opts) {
|
|
305
|
+
throw new Error('useMongoDBAuthState requires a MongoDB collection, database, client, or connection options')
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
if (opts.sessionId && !sessionId) {
|
|
309
|
+
sessionId = opts.sessionId
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
// 1. Direct MongoDB Collection or Mongoose Model
|
|
313
|
+
if (typeof opts.findOne === 'function' && (typeof opts.updateOne === 'function' || typeof opts.findOneAndUpdate === 'function')) {
|
|
314
|
+
collection = opts
|
|
315
|
+
} else if (opts.collection) {
|
|
316
|
+
if (typeof opts.collection === 'object' && typeof opts.collection.findOne === 'function') {
|
|
317
|
+
collection = opts.collection
|
|
318
|
+
} else if (typeof opts.collection === 'function' && typeof opts.databaseName === 'string') {
|
|
319
|
+
const colName = opts.collectionName || 'auth_state'
|
|
320
|
+
collection = opts.collection(colName)
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
// 2. Mongoose model unwrapping
|
|
325
|
+
if (!collection && opts.schema && opts.collection && typeof opts.collection.findOne === 'function') {
|
|
326
|
+
collection = opts.collection
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// 3. opts.db or opts.database as a Db instance
|
|
330
|
+
if (!collection && opts.db && typeof opts.db.collection === 'function') {
|
|
331
|
+
const colName = opts.collectionName || 'auth_state'
|
|
332
|
+
collection = opts.db.collection(colName)
|
|
333
|
+
}
|
|
334
|
+
if (!collection && opts.database && typeof opts.database.collection === 'function') {
|
|
335
|
+
const colName = opts.collectionName || 'auth_state'
|
|
336
|
+
collection = opts.database.collection(colName)
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// 4. opts.client or direct MongoClient instance
|
|
340
|
+
if (!collection && typeof opts.db === 'function' && typeof opts.connect === 'function') {
|
|
341
|
+
client = opts
|
|
342
|
+
const dbName = opts.dbName || opts.databaseName || undefined
|
|
343
|
+
const db = client.db(dbName)
|
|
344
|
+
const colName = opts.collectionName || 'auth_state'
|
|
345
|
+
collection = db.collection(colName)
|
|
346
|
+
} else if (!collection && opts.client && typeof opts.client.db === 'function') {
|
|
347
|
+
client = opts.client
|
|
348
|
+
const dbName = opts.dbName || opts.databaseName || (typeof opts.database === 'string' ? opts.database : undefined)
|
|
349
|
+
const db = client.db(dbName)
|
|
350
|
+
const colName = opts.collectionName || 'auth_state'
|
|
351
|
+
collection = db.collection(colName)
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
// 5. Connection URL / URI
|
|
355
|
+
if (!collection && (opts.url || opts.uri)) {
|
|
356
|
+
const connectionUrl = opts.url || opts.uri
|
|
357
|
+
let mongodb
|
|
358
|
+
try {
|
|
359
|
+
mongodb = await import('mongodb')
|
|
360
|
+
} catch {
|
|
361
|
+
throw new Error(
|
|
362
|
+
'The "mongodb" package is required to connect to MongoDB via URL. Please install it using: npm install mongodb'
|
|
363
|
+
)
|
|
364
|
+
}
|
|
365
|
+
const MongoClient = mongodb.MongoClient || mongodb.default?.MongoClient || mongodb.default
|
|
366
|
+
client = new MongoClient(connectionUrl, opts.mongoOptions)
|
|
367
|
+
await client.connect()
|
|
368
|
+
const dbName = opts.dbName || opts.databaseName || (typeof opts.database === 'string' ? opts.database : undefined)
|
|
369
|
+
const db = client.db(dbName)
|
|
370
|
+
const colName = opts.collectionName || 'auth_state'
|
|
371
|
+
collection = db.collection(colName)
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
if (!collection) {
|
|
375
|
+
throw new Error(
|
|
376
|
+
'Could not resolve MongoDB collection. Please provide a collection, db, client, or { url } in options.'
|
|
377
|
+
)
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
return { collection, client, sessionId }
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
export async function useMongoDBAuthState(opts, secondArg) {
|
|
384
|
+
const { collection, client, sessionId } = await resolveMongoCollection(opts, secondArg)
|
|
385
|
+
|
|
386
|
+
if (typeof collection.createIndex === 'function') {
|
|
387
|
+
collection.createIndex({ sessionId: 1, type: 1 }, { background: true }).catch(() => {})
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
const makeDocId = (type, id) => {
|
|
391
|
+
const key = id ? `${type}-${id}` : type
|
|
392
|
+
return sessionId ? `${sessionId}:${key}` : key
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
const getAltDocId = (type, id) => {
|
|
396
|
+
if (!sessionId) return null
|
|
397
|
+
const key = id ? `${type}-${id}` : type
|
|
398
|
+
return `${sessionId}_${key}`
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
const parseDocValue = (doc, type) => {
|
|
402
|
+
if (!doc) return undefined
|
|
403
|
+
const raw = doc.value !== undefined ? doc.value : doc.data
|
|
404
|
+
if (raw === undefined || raw === null) return undefined
|
|
405
|
+
let value
|
|
406
|
+
if (typeof raw === 'string') {
|
|
407
|
+
value = JSON.parse(raw, BufferJSON.reviver)
|
|
408
|
+
} else if (typeof raw === 'object') {
|
|
409
|
+
value = JSON.parse(JSON.stringify(raw), BufferJSON.reviver)
|
|
410
|
+
} else {
|
|
411
|
+
value = raw
|
|
412
|
+
}
|
|
413
|
+
if (type === 'app-state-sync-key' && value) {
|
|
414
|
+
value = proto.Message.AppStateSyncKeyData.fromObject(value)
|
|
415
|
+
}
|
|
416
|
+
return value
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
const credsDocId = makeDocId('creds')
|
|
420
|
+
|
|
421
|
+
const loadCreds = async () => {
|
|
422
|
+
let doc = await collection.findOne({ _id: credsDocId })
|
|
423
|
+
if (!doc && sessionId) {
|
|
424
|
+
const altId = getAltDocId('creds')
|
|
425
|
+
if (altId) doc = await collection.findOne({ _id: altId })
|
|
426
|
+
}
|
|
427
|
+
if (!doc && !sessionId) {
|
|
428
|
+
doc = await collection.findOne({ _id: '__creds__' })
|
|
429
|
+
}
|
|
430
|
+
if (!doc) return initAuthCreds()
|
|
431
|
+
const value = parseDocValue(doc, 'creds')
|
|
432
|
+
return value || initAuthCreds()
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
const persistCreds = async currentCreds => {
|
|
436
|
+
const serialized = JSON.stringify(currentCreds, BufferJSON.replacer)
|
|
437
|
+
await collection.updateOne(
|
|
438
|
+
{ _id: credsDocId },
|
|
439
|
+
{
|
|
440
|
+
$set: {
|
|
441
|
+
_id: credsDocId,
|
|
442
|
+
type: 'creds',
|
|
443
|
+
keyId: 'creds',
|
|
444
|
+
sessionId: sessionId || null,
|
|
445
|
+
value: serialized
|
|
446
|
+
}
|
|
447
|
+
},
|
|
448
|
+
{ upsert: true }
|
|
449
|
+
)
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
const creds = (await loadCreds()) || initAuthCreds()
|
|
453
|
+
|
|
454
|
+
return {
|
|
455
|
+
state: {
|
|
456
|
+
creds,
|
|
457
|
+
keys: {
|
|
458
|
+
get: async (type, ids) => {
|
|
459
|
+
const data = {}
|
|
460
|
+
if (!ids || ids.length === 0) return data
|
|
461
|
+
|
|
462
|
+
const idMap = new Map()
|
|
463
|
+
const queryIds = []
|
|
464
|
+
for (const id of ids) {
|
|
465
|
+
const docId = makeDocId(type, id)
|
|
466
|
+
queryIds.push(docId)
|
|
467
|
+
idMap.set(docId, id)
|
|
468
|
+
const altId = getAltDocId(type, id)
|
|
469
|
+
if (altId) {
|
|
470
|
+
queryIds.push(altId)
|
|
471
|
+
idMap.set(altId, id)
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
let docs = []
|
|
476
|
+
try {
|
|
477
|
+
const cursor = collection.find({ _id: { $in: queryIds } })
|
|
478
|
+
docs = typeof cursor?.toArray === 'function' ? await cursor.toArray() : await cursor
|
|
479
|
+
} catch {
|
|
480
|
+
docs = await Promise.all(
|
|
481
|
+
queryIds.map(async qId => {
|
|
482
|
+
try {
|
|
483
|
+
return await collection.findOne({ _id: qId })
|
|
484
|
+
} catch {
|
|
485
|
+
return null
|
|
486
|
+
}
|
|
487
|
+
})
|
|
488
|
+
)
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
if (Array.isArray(docs)) {
|
|
492
|
+
for (const doc of docs) {
|
|
493
|
+
if (!doc) continue
|
|
494
|
+
const id = idMap.get(doc._id) ?? doc.keyId ?? doc.id
|
|
495
|
+
if (id !== undefined) {
|
|
496
|
+
const value = parseDocValue(doc, type)
|
|
497
|
+
if (value !== undefined) {
|
|
498
|
+
data[id] = value
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
return data
|
|
505
|
+
},
|
|
506
|
+
set: async data => {
|
|
507
|
+
const writes = []
|
|
508
|
+
const deletes = []
|
|
509
|
+
const bulkOps = []
|
|
510
|
+
|
|
511
|
+
for (const category in data) {
|
|
512
|
+
for (const id in data[category]) {
|
|
513
|
+
const value = data[category][id]
|
|
514
|
+
const docId = makeDocId(category, id)
|
|
515
|
+
if (value) {
|
|
516
|
+
const serialized = JSON.stringify(value, BufferJSON.replacer)
|
|
517
|
+
const updateDoc = {
|
|
518
|
+
_id: docId,
|
|
519
|
+
type: category,
|
|
520
|
+
keyId: id,
|
|
521
|
+
sessionId: sessionId || null,
|
|
522
|
+
value: serialized
|
|
523
|
+
}
|
|
524
|
+
bulkOps.push({
|
|
525
|
+
updateOne: {
|
|
526
|
+
filter: { _id: docId },
|
|
527
|
+
update: { $set: updateDoc },
|
|
528
|
+
upsert: true
|
|
529
|
+
}
|
|
530
|
+
})
|
|
531
|
+
writes.push({ filter: { _id: docId }, update: { $set: updateDoc } })
|
|
532
|
+
} else {
|
|
533
|
+
bulkOps.push({
|
|
534
|
+
deleteOne: {
|
|
535
|
+
filter: { _id: docId }
|
|
536
|
+
}
|
|
537
|
+
})
|
|
538
|
+
deletes.push({ filter: { _id: docId } })
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
if (bulkOps.length === 0) return
|
|
544
|
+
|
|
545
|
+
let bulkSucceeded = false
|
|
546
|
+
if (typeof collection.bulkWrite === 'function') {
|
|
547
|
+
try {
|
|
548
|
+
await collection.bulkWrite(bulkOps, { ordered: false })
|
|
549
|
+
bulkSucceeded = true
|
|
550
|
+
} catch {
|
|
551
|
+
bulkSucceeded = false
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
if (!bulkSucceeded) {
|
|
556
|
+
await Promise.all([
|
|
557
|
+
...writes.map(w => collection.updateOne(w.filter, w.update, { upsert: true })),
|
|
558
|
+
...deletes.map(d => collection.deleteOne(d.filter))
|
|
559
|
+
])
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
},
|
|
564
|
+
saveCreds: async newCreds => {
|
|
565
|
+
if (newCreds) Object.assign(creds, newCreds)
|
|
566
|
+
await persistCreds(creds)
|
|
567
|
+
},
|
|
568
|
+
collection,
|
|
569
|
+
client,
|
|
570
|
+
clearState: async () => {
|
|
571
|
+
if (sessionId) {
|
|
572
|
+
const filter = {
|
|
573
|
+
$or: [
|
|
574
|
+
{ sessionId },
|
|
575
|
+
{ _id: { $regex: `^${sessionId}[:_]` } }
|
|
576
|
+
]
|
|
577
|
+
}
|
|
578
|
+
if (typeof collection.deleteMany === 'function') {
|
|
579
|
+
await collection.deleteMany(filter)
|
|
580
|
+
}
|
|
581
|
+
} else {
|
|
582
|
+
if (typeof collection.deleteMany === 'function') {
|
|
583
|
+
await collection.deleteMany({})
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
export const useMongoAuthState = useMongoDBAuthState
|
|
591
|
+
export const useMongoDbAuthState = useMongoDBAuthState
|
|
592
|
+
|
|
593
|
+
|
|
594
|
+
export { useKeyvAuthState, hasKeyvAuth, clearAdapterCache } from './use-keyv-auth-state.js'
|