mirror of
https://github.com/FranP-code/Baileys.git
synced 2025-10-13 00:32:22 +00:00
feat: cleaner auth state management
1. removes the "auth-state.update" event since it was bloated and fairly unnecessary 2. adds "creds.update" event that only sends the updated properties of the auth credentials 3. ensure the auth creds are not mutated anywhere, but only with the "creds.update" event 4. Separates the signal credentials from the auth credentials (kinda in progress) 5. in memory key store requires a save function to let one know when to save the keys !BREAKING_CHANGE
This commit is contained in:
@@ -1,41 +1,16 @@
|
||||
import { readFileSync, writeFileSync } from "fs"
|
||||
import P from "pino"
|
||||
import { Boom } from "@hapi/boom"
|
||||
import makeWASocket, { AuthenticationState, DisconnectReason, AnyMessageContent, BufferJSON, initInMemoryKeyStore, delay } from '../src'
|
||||
import makeWASocket, { DisconnectReason, AnyMessageContent, delay, useSingleFileAuthState } from '../src'
|
||||
|
||||
// load authentication state from a file
|
||||
const loadState = () => {
|
||||
let state: AuthenticationState | undefined = undefined
|
||||
try {
|
||||
const value = JSON.parse(
|
||||
readFileSync('./auth_info_multi.json', { encoding: 'utf-8' }),
|
||||
BufferJSON.reviver
|
||||
)
|
||||
state = {
|
||||
creds: value.creds,
|
||||
// stores pre-keys, session & other keys in a JSON object
|
||||
// we deserialize it here
|
||||
keys: initInMemoryKeyStore(value.keys)
|
||||
}
|
||||
} catch{ }
|
||||
return state
|
||||
}
|
||||
// save the authentication state to a file
|
||||
const saveState = (state: any | undefined) => {
|
||||
console.log('saving auth state')
|
||||
writeFileSync(
|
||||
'./auth_info_multi.json',
|
||||
// BufferJSON replacer utility saves buffers nicely
|
||||
JSON.stringify(state, BufferJSON.replacer, 2)
|
||||
)
|
||||
}
|
||||
const { state, saveState } = useSingleFileAuthState('./auth_info_multi.json')
|
||||
|
||||
// start a connection
|
||||
const startSock = () => {
|
||||
|
||||
const sock = makeWASocket({
|
||||
logger: P({ level: 'trace' }),
|
||||
printQRInTerminal: true,
|
||||
auth: loadState()
|
||||
auth: state
|
||||
})
|
||||
|
||||
const sendMessageWTyping = async(msg: AnyMessageContent, jid: string) => {
|
||||
@@ -80,9 +55,8 @@ const startSock = () => {
|
||||
|
||||
console.log('connection update', update)
|
||||
})
|
||||
// listen for when the auth state is updated
|
||||
// it is imperative you save this data, it affects the signing keys you need to have conversations
|
||||
sock.ev.on('auth-state.update', () => saveState(sock.authState))
|
||||
// listen for when the auth credentials is updated
|
||||
sock.ev.on('creds.update', saveState)
|
||||
|
||||
return sock
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user