sr-lockbox
v1.1.2
Published
Secure password encryption with deterministic AES-256-CBC padding - Hybrid crypto solution for Node.js
Maintainers
Readme
🔒 sr-lockbox
The Ultimate Utility Toolkit for Node.js. Secure password encryption with deterministic AES-256-CBC padding, plus essential utilities for OTP, unique IDs, and currency conversion.
📑 Table of Contents
- ✨ Features
- 📦 Installation
- 🚀 Quick Start
- 🛠️ Utility Toolkit
- 📚 API Documentation
- 🔧 Environment Setup
- 💡 Use Cases
- 🛡️ Security
- 📄 License
✨ Features
- 🔐 AES-256-CBC Encryption: Industry standard deterministic encryption.
- 🎲 Random Padding: Adds an extra layer of security by obfuscating password length.
- ⏳ TTL (Time-To-Live): Support for expiring hashes (perfect for reset tokens).
- 📝 Metadata Support: Store extra data directly inside the encrypted payload.
- 🔢 OTP Generation: Numeric OTPs with custom length and expiry.
- 🆔 Custom ID Generator: Prefix-based unique random IDs.
- 💰 Currency Converter: Real-time BNB/USDT conversion via Binance API.
- 🖼️ ImageKit Uploader: Effortless image uploads to ImageKit.
- 📊 Logging System: Winston-based request and error logging middleware.
- ✅ Response Standardizer: Standard
res.ok()andres.fail()for Express. - 🎭 Data Masking: Privacy utilities for emails and phone numbers.
- 🔑 Simple JWT Auth: Easy sign/verify wrappers for JWT.
- 📦 Zero Internal Dependencies: Main engine is lightweight.
📦 Installation
npm install sr-lockbox🚀 Quick Start
Basic Encryption
const { SrPassword } = require('sr-lockbox');
const lockbox = new SrPassword({
secret: 'your-secret-key-here',
length: 20
});
// Hash password
const encrypted = lockbox.hash('mySecretPass123');
// Compare password
const isValid = lockbox.compare(encrypted, 'mySecretPass123');🛠️ Utility Toolkit
sr-lockbox provides a set of handy utilities for modern applications:
🔢 Generate OTP
const { otp } = require('sr-lockbox');
const otpData = otp.generate({ length: 6, expiresIn: 5 });
console.log(otpData.otp); // e.g. "482910"🆔 Custom ID Generator
const { uniqueId } = require('sr-lockbox');
const userId = uniqueId.generate({ prefix: 'USR', min: 10, max: 12 });
console.log(userId); // e.g. "USR4829104829"💰 Live Currency Conversion
const { currency } = require('sr-lockbox');
const usdt = await currency.fetchBNBtoUSDT(0.5);
console.log(`0.5 BNB is worth ${usdt} USDT`);📊 Advanced Logging (Express Middleware)
sr-lockbox provides a powerful Winston-based logging system that automatically tracks requests and errors.
const express = require('express');
const { logger, asyncHandler } = require('sr-lockbox');
const app = express();
// 1. Create a custom logger
const myLogger = logger.create({ logDir: 'my-app-logs' });
// 2. Get the middleware
const { requestLogger, errorLogger } = logger.middleware(myLogger);
// 3. Use in Express
app.use(express.json());
app.use(requestLogger);
// Example route using asyncHandler
app.get('/user', asyncHandler(async (req, res) => {
// No need for try-catch! Errors are caught by asyncHandler
const user = { name: "John Doe" };
res.json(user);
}));
app.use(errorLogger);Note: Logs are saved in
my-app-logs/error.logandmy-app-logs/combined.log.
⚡ Async Error Handler (asyncHandler)
Stop writing try-catch in every single controller. Wrap your async functions with asyncHandler to automatically catch errors and pass them to your Express error middleware.
Before (Messy):
app.get('/data', async (req, res, next) => {
try {
const data = await FetchData();
res.json(data);
} catch (error) {
next(error);
}
});After (Clean ✨):
const { asyncHandler, response } = require('sr-lockbox');
app.use(response.handler); // Enable standard response helpers
app.get('/data', asyncHandler(async (req, res) => {
const data = await FetchData();
res.ok(data, "Data fetched successfully"); // Uses standard response format!
}));📚 API Documentation
Detailed documentation is available in the docs/API.md file.
Summary
| Method | Description |
| :--- | :--- |
| .hash(pass, opts) | Encrypt + Pad with optional TTL/Metadata |
| .compare(enc, pass) | Verify password or extract data |
| .isEncrypted(str) | Validate if string matches lockbox format |
| .otp.generate(opts) | Generate numeric OTP and expiry |
| .uniqueId.generate() | Generate random unique ID with prefix |
| .asyncHandler() | Wrapper to catch async Express errors |
| .currency.fetchBNBtoUSDT() | Get live BNB value in USDT |
| .imagekit.upload() | Upload image to ImageKit storage |
| .logger.create() | Create a custom Winston logger |
| .response.handler | Middleware for standard API responses |
| .mask.email(addr) | Mask email address (ex***@mail.com) |
| .auth.sign(data) | Sign a new JWT token |
| .logger.middleware()| Get Express request/error middleware |
🔧 Environment Setup
You can set your secret globally using environment variables:
# .env file
ENCRYPT_DATA_SECRET=your-super-secret-key-here💡 Use Cases
- User Authentication: Secure password storage with recovery.
- Sensitive Data: URL parameters, tokens, and cookie encryption.
- Microservices: Generating unique IDs across systems.
- FinTech Apps: Quick currency conversion and OTP handling.
🚀 Roadmap / Upcoming Features
We are constantly working to make sr-lockbox the only utility you'll ever need. Here's what's coming next:
- ☁️ Cloudinary Support: While we love ImageKit, adding Cloudinary gives developers more choices for advanced image transformations and optimization.
- 🔑 Advanced Auth: We plan to add OAuth2 wrappers (Google, GitHub) and specialized session management to handle user authentication end-to-end.
- 📊 Bulk Operations: High-performance utilities to encrypt or process large arrays of data efficiently, perfect for enterprise-grade migrations.
- 🌐 Multi-language Docs: To make this toolkit accessible worldwide, we are bringing documentation in Hindi and other regional languages.
🛡️ Security Note
sr-lockbox is designed for non-critical applications and deterministic requirements. For standard user authentication in production web apps, consider libraries like bcrypt or argon2.
👤 Author & Founder
ABHAY GAUTAM
Founder of Srappltd
Developed with ❤️ by Abhay Gautam.
📄 License
MIT © ABHAY GAUTAM
GitHub Repository: srappltd/sr-lockbox
