Skip to content

fmartini23/secure-localdb

Repository files navigation

Secure-LocalDB 🔐

NPM Version License: MIT

Secure-LocalDB is a simple, fast, and secure local database for Node.js applications.
It provides a familiar API similar to other file-based databases but with a critical addition: strong, built-in encryption.

All data is stored in a single file, fully encrypted at rest using AES-256-GCM, with a key derived from your password via Argon2.
It's designed to be resilient, performant, and easy to use, offering both synchronous and asynchronous APIs to fit any use case.


✨ Key Features

  • 🔒 Strong Encryption: End-to-end encryption using AES-256-GCM.\
  • 🔑 Secure Key Derivation: Argon2id to derive encryption keys from passwords.\
  • 🛡️ Data Integrity: GCM mode prevents tampering and corruption.\
  • Fast In-Memory Cache: Reads directly from memory.\
  • 💪 Resilient & Atomic Writes: No corruption --- always consistent.\
  • 🤝 Flexible API: Asynchronous (ideal for servers) & synchronous (ideal for CLIs).\
  • 📦 Extensible with Plugins: UUIDs, timestamps, and custom plugins.\
  • Modern & Typed: Fully written in TypeScript.

📦 Installation

npm install secure-localdb

🚀 How to Use

1. Asynchronous API (Recommended for Servers)

import { SecureDBAsync } from 'secure-localdb';
import { join } from 'path';

const dbFile = join(__dirname, 'my-app-database.db.enc');

async function main() {
  const db = new SecureDBAsync(dbFile, {
    password: 'a-very-strong-and-secret-password',
  });

  await db.init();
  console.log('Database initialized!');

  await db.insert({ id: 1, user: 'alice', role: 'admin' });
  await db.insert({ id: 2, user: 'bob', role: 'user' });

  const admin = await db.findOne(doc => doc.role === 'admin');
  console.log('Admin user:', admin);

  await db.update(doc => doc.user === 'bob', { role: 'editor' });

  await db.remove(doc => doc.user === 'alice');
  console.log('Alice removed.');
}

main().catch(console.error);

2. Synchronous API (Ideal for Scripts)

import { SecureDB } from 'secure-localdb';
import { join } from 'path';

const dbFile = join(__dirname, 'my-script-database.db.enc');

try {
  const db = new SecureDB(dbFile, {
    password: 'another-secret-for-my-script',
  });

  db.insert({ item: 'Laptop', stock: 20 });
  db.insert({ item: 'Mouse', stock: 150 });

  const lowStock = db.find(doc => doc.stock < 50);
  console.log('Low stock:', lowStock);

  db.update(doc => doc.item === 'Laptop', { stock: 25 });
  db.remove(doc => doc.stock > 100);

  console.log('Final inventory:', db.find(() => true));
} catch (err) {
  console.error('Error:', err);
}

3. Plugins

Secure-LocalDB supports plugins like uuidPlugin and timestampsPlugin.

import { SecureDBAsync, uuidPlugin, timestampsPlugin } from 'secure-localdb';
import { join } from 'path';

const dbFile = join(__dirname, 'tasks.db.enc');

async function main() {
  const db = new SecureDBAsync(dbFile, {
    password: 'plugins-secret',
    plugins: [
      uuidPlugin(),
      timestampsPlugin(),
    ],
  });

  await db.init();
  await db.insert({ title: 'My first task' });

  const task = await db.findOne(doc => doc.title === 'My first task');
  console.log('Task with plugins:', task);
}

main().catch(console.error);

You can also customize:

uuidPlugin({ idField: '_id' });
timestampsPlugin({ createdAtField: 'created', updatedAtField: 'modified' });

📖 API Reference

SecureDBAsync(filePath, options)

  • filePath: string -- Path to the encrypted database file.\
  • options.password: string -- Password used for encryption/decryption.\
  • options.plugins?: PluginFunction[] -- Optional plugins.

Methods: - init(): Promise<void>\

  • insert(doc): Promise<void>\
  • find(predicate): Promise<Document[]>\
  • findOne(predicate): Promise<Document | undefined>\
  • update(predicate, newData): Promise<void>\
  • remove(predicate): Promise<void>

SecureDB(filePath, options)

Synchronous version with same options. Initialization happens in constructor.

Methods: - insert(doc): void\

  • find(predicate): Document[]\
  • findOne(predicate): Document | undefined\
  • update(predicate, newData): void\
  • remove(predicate): void

📜 License

This project is licensed under the MIT License.

About

Secure-LocalDB is a simple, fast, and secure local database for Node.js applications.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published