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:
Adhiraj Singh
2021-11-20 16:21:56 +05:30
parent c2c27a5dea
commit 3d0704a317
13 changed files with 229 additions and 201 deletions

View File

@@ -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
}