@nevi-dev/sqlite-auth
v1.0.0
Published
Proveedor de estado de autenticación SQLite de alto rendimiento para @whiskeysockets/baileys
Maintainers
Readme
@nevi-dev/sqlite-auth
Developed with ❤️ by Nevi Dev
English
🌍 The Problem with Multi-File Auth
By default, Baileys uses useMultiFileAuthState, which creates a separate JSON file for every single pre-key, session, and sender-key. When running a bot for a long time—or hosting multiple sub-bots—this behavior generates thousands of tiny files.
This causes serious issues:
- High Disk I/O: Constantly reading and writing thousands of files degrades server performance.
- File System Bloat: Cloud providers or OS file systems can hit inode limits, crashing the server.
- Slow Backups/Deletions: Deleting or moving a session folder with 50,000 JSON files can take minutes.
💡 The Solution by Nevi Dev
@nevi-dev/sqlite-auth completely replaces the file system layer. It intercepts Baileys read/write operations and pipes them directly into a single, highly-optimized SQLite database file powered by better-sqlite3.
🌟 Features
- Single-File Storage: Credentials and keys live safely inside one
.dbfile per bot. - WAL Mode Natively Enabled: Uses SQLite's Write-Ahead Logging. This allows concurrent reads and writes without blocking the Node.js event loop, ensuring peak performance even under heavy message load.
- Smart Legacy Purge: Before initializing the database, it automatically scans and wipes out old JSON files (
pre-key-,sender-key-, etc.) to free up space. - Agnostic & Scalable: Perfectly tailored for multi-bot managers, panels, or distributed worker threads.
🚀 Installation
npm install @nevi-dev/sqlite-auth better-sqlite3Note:
@whiskeysockets/baileysmust be installed in your project.
🛠️ Basic Usage
import makeWASocket from '@whiskeysockets/baileys';
import { useSQLiteAuthState } from '@nevi-dev/sqlite-auth';
// Initialize the SQLite session state
const { state, saveCreds } = useSQLiteAuthState('./sessions/main_bot', {
dbName: 'auth.db', // Optional: Database filename (Default: auth.db)
cleanOldFiles: true // Optional: Automatically purges legacy JSON files (Default: true)
});
// Create the Baileys connection using the SQLite state
const sock = makeWASocket({
auth: state,
printQRInTerminal: true
});
// Save credentials automatically on updates
sock.ev.on('creds.update', saveCreds);🤖 Advanced Multi-Bot Control (System Registry)
If you manage dynamic sub-bots or multiple client instances, you can spin up a central database using createManagerDatabase to keep track of every connection state.
import { createManagerDatabase } from '@nevi-dev/sqlite-auth';
// Initialize the central controller DB
const systemDb = createManagerDatabase({
dbPath: './sessions/system.db', // Optional: Custom path for system db
tableName: 'bot_registry' // Optional: Custom table name
});
// Example: Inserting or updating a sub-bot status using better-sqlite3
systemDb.prepare('INSERT OR REPLACE INTO bot_registry (id, jid, status, metadata) VALUES (?, ?, ?, ?)')
.run('subbot_99', '[email protected]', 'online', JSON.stringify({ plan: 'Premium' }));Español
🌍 El Problema con el Estado Multi-Archivo
Por defecto, Baileys utiliza useMultiFileAuthState, el cual crea un archivo JSON independiente para cada pre-key, sesión y llave de remitente. Al mantener un bot activo por mucho tiempo—o al alojar múltiples sub-bots— este comportamiento genera miles de archivos diminutos.
Esto provoca fallos críticos:
- Alto Impacto en I/O de Disco: Leer y escribir constantemente miles de archivos degrada el rendimiento del servidor.
- Saturación del Sistema de Archivos: Los servidores en la nube pueden agotar sus límites de nodos-i (inodes), congelando el sistema.
- Lentitud en Backups/Eliminaciones: Borrar una sola carpeta de sesión con 50,000 JSONs puede tomar minutos enteros de procesamiento.
💡 La Solución de Nevi Dev
@nevi-dev/sqlite-auth reemplaza por completo la capa del sistema de archivos. Intercepta las operaciones de lectura y escritura de Baileys y las redirige directamente hacia un único archivo de base de datos SQLite, optimizado mediante better-sqlite3.
🌟 Características
- Almacenamiento en un Solo Archivo: Las credenciales y llaves residen de forma segura dentro de un único archivo
.dbpor bot. - Modo WAL Activado Nativamente: Utiliza el método Write-Ahead Logging de SQLite. Esto permite lecturas y escrituras concurrentes instantáneas sin bloquear el bucle de eventos de Node.js, garantizando fluidez ante ráfagas masivas de mensajes.
- Purga Inteligente de Basura: Antes de inicializar la base de datos, escanea y elimina archivos JSON antiguos (
pre-key-,sender-key-, etc.) para liberar espacio en disco inmediatamente. - Agnóstico y Escalable: Diseñado meticulosamente para integrarse con gestores multi-bots, paneles web o hilos de trabajo (
worker_threads).
🚀 Instalación
npm install @nevi-dev/sqlite-auth better-sqlite3Nota: Debes tener
@whiskeysockets/baileysinstalado en tu proyecto.
🛠️ Uso Básico
import makeWASocket from '@whiskeysockets/baileys';
import { useSQLiteAuthState } from '@nevi-dev/sqlite-auth';
// Inicializa el estado de la sesión en SQLite
const { state, saveCreds } = useSQLiteAuthState('./sessions/main_bot', {
dbName: 'auth.db', // Opcional: Nombre del archivo de base de datos (Por defecto: auth.db)
cleanOldFiles: true // Opcional: Borra automáticamente archivos JSON heredados de Baileys (Por defecto: true)
});
// Crea la conexión del socket de Baileys pasándole el estado
const sock = makeWASocket({
auth: state,
printQRInTerminal: true
});
// Escucha las actualizaciones de credenciales y guárdalas en SQLite
sock.ev.on('creds.update', saveCreds);🤖 Control Avanzado Multi-Bot (Registro de Sistema)
Si estás construyendo un panel multi-cuentas o un sistema dinámico de sub-bots, utiliza createManagerDatabase para centralizar y monitorear los estados de tus instancias desde un solo lugar:
import { createManagerDatabase } from '@nevi-dev/sqlite-auth';
// Inicializa una base de datos central de control
const systemDb = createManagerDatabase({
dbPath: './sessions/system.db', // Opcional: Ruta personalizada para la DB del sistema
tableName: 'bot_registry' // Opcional: Nombre personalizado para la tabla
});
// Ejemplo: Insertar o actualizar el estado de un sub-bot usando consultas nativas de better-sqlite3
systemDb.prepare('INSERT OR REPLACE INTO bot_registry (id, jid, status, metadata) VALUES (?, ?, ?, ?)')
.run('subbot_99', '[email protected]', 'online', JSON.stringify({ plan: 'Premium' }));⚙️ Configuration Options / Opciones de Configuración
useSQLiteAuthState(sessionDir, options)
| Option / Opcional | Type / Tipo | Default / Defecto | Description / Descripción |
| :--- | :--- | :--- | :--- |
| dbName | String | 'auth.db' | The name of the SQLite file inside the session folder. / El nombre del archivo SQLite dentro de la carpeta de sesión. |
| cleanOldFiles | Boolean | true | Deletes legacy JSON files from Baileys if they exist. / Elimina los archivos JSON antiguos de Baileys si existen. |
createManagerDatabase(options)
| Option / Opcional | Type / Tipo | Default / Defecto | Description / Descripción |
| :--- | :--- | :--- | :--- |
| dbPath | String | './sessions/system.db' | Global path to store the manager database. / Ruta global para almacenar la base de datos del administrador. |
| tableName | String | 'bot_registry' | Table name inside the manager database. / Nombre de la tabla dentro de la base de datos del administrador. |
📄 License / Licencia
Distributed under the MIT License. Created and maintained by Nevi Dev.
Distribuido bajo la Licencia MIT. Creado y mantenido por Nevi Dev.
