@tech-nuggets/sentinel
v0.0.3
Published
Tech Nuggets SDK: A collection of reusable utilities and helpers for web development projects, including crypto functions, response builders, and more.
Downloads
4
Readme
Tech Nuggets SDK
A collection of reusable utilities and helpers for web development projects, including crypto functions, response builders, and more.
🚀 Features
- Cryptography Utilities: AES encryption, RSA encryption, hashing, and digital signing
- Security Tools: Secure transport protocols and sentinel monitoring
- Helper Functions: Response builders and common utilities
- TypeScript Support: Full TypeScript support with type definitions
- Modern ES Modules: Built with modern JavaScript standards
📦 Installation
npm install @tech-nuggets/sentinelyarn add @tech-nuggets/sentinelpnpm add @tech-nuggets/sentinel🛠️ Usage
Crypto Utilities
import { encrypt, decrypt, generateAesKey, hashPassword, verifyPassword } from '@tech-nuggets/sentinel';
// AES Encryption - IMPORTANT: Use generateAesKey() for proper key format
const key = generateAesKey(); // Returns 64-character hex string (32 bytes)
const encrypted = encrypt('sensitive data', key);
const decrypted = decrypt(encrypted, key);
// Password Hashing
const hashedPassword = await hashPassword('user-password');
const isValid = await verifyPassword(hashedPassword, 'user-password');RSA Encryption
import { generateRSAKeyPair, rsaEncrypt, rsaDecrypt } from '@tech-nuggets/sentinel';
// Generate RSA key pair
const { publicKey, privateKey } = generateRSAKeyPair();
// RSA Encryption
const encrypted = rsaEncrypt('sensitive data', publicKey);
const decrypted = rsaDecrypt(encrypted, privateKey);Response Helpers
import { ok, err } from '@tech-nuggets/sentinel';
// Success Response
const success = ok('Operation completed successfully', { userId: 123 });
// Error Response
const error = err('Something went wrong', null, 'INTERNAL_ERROR');Security Tools
import { SecureTransport, Sentinel, generateAesKey, generateHmacSecret } from '@tech-nuggets/sentinel';
// IMPORTANT: Always use the generator functions for proper key format
const aesKey = generateAesKey(); // 64-character hex string (32 bytes)
const hmacSecret = generateHmacSecret(); // 64-character hex string (32 bytes)
// Secure transport with AES encryption
const transport = new SecureTransport(aesKey);
const encrypted = transport.encrypt({ message: 'Hello World' });
const decrypted = transport.decrypt(encrypted);
// Sentinel for secure request handling
const sentinel = new Sentinel({
hmacSecret: hmacSecret,
aesKey: aesKey, // optional encryption
maxAgeSeconds: 300
});
// Define your DTO types
interface CreateAssetDto {
name: string;
description: string;
value: number;
}
interface UserLoginDto {
username: string;
password: string;
}
// Generate secure requests with union types
const createAssetDto: SecureRequest<CreateAssetDto | EncryptedPayload> = sentinel.generateRequest({
name: "My Asset",
description: "A valuable asset",
value: 1000
});
const loginDto: SecureRequest<UserLoginDto | EncryptedPayload> = sentinel.generateRequest({
username: "john.doe",
password: "secret123"
});
// Validate and extract data
try {
const assetData: CreateAssetDto = await sentinel.extractAndValidate<CreateAssetDto>(createAssetDto);
console.log('Asset to create:', assetData);
const loginData: UserLoginDto = await sentinel.extractAndValidate<UserLoginDto>(loginDto);
console.log('Login attempt:', loginData.username);
} catch (error) {
console.error('Invalid request:', error.message);
}🔑 Key Requirements
IMPORTANT: All cryptographic keys must be in the correct format:
- AES Keys: 64 hex characters (32 bytes when decoded)
- HMAC Secrets: 64 hex characters (32 bytes when decoded)
- Format: Only characters 0-9, a-f, A-F are allowed
Always use the provided generator functions:
import { generateAesKey, generateHmacSecret } from '@tech-nuggets/sentinel';
// ✅ Correct way
const aesKey = generateAesKey();
const hmacSecret = generateHmacSecret();
// ❌ Wrong - will cause "Invalid key length" errors
const badKey = "mypassword123";
const anotherBadKey = "a1b2c3d4"; // too short📚 API Reference
Crypto Module
AES Encryption
generateAesKey(): string- Generate a secure AES keygenerateIv(): string- Generate a random initialization vectorencrypt(plainText: string, key: string): EncryptedPayload- Encrypt data using AES-GCMdecrypt(payload: EncryptedPayload, key: string): string- Decrypt AES-GCM payload
RSA Encryption
generateRSAKeyPair(): RSAKeyPair- Generate RSA public/private key pairrsaEncrypt(data: string, publicKey: string): string- Encrypt data with RSA public keyrsaDecrypt(encryptedData: string, privateKey: string): string- Decrypt data with RSA private key
Hashing
hashPassword(password: string): Promise<string>- Hash password using Argon2verifyPassword(hash: string, password: string): Promise<boolean>- Verify password against hash
Digital Signing
generateHmacSecret(): string- Generate HMAC secret for signinggenerateSignature(payload: string, timestamp: number, secret: string): string- Generate HMAC signatureverifySignature(payload: string, timestamp: number, provided: string, secret: string): boolean- Verify HMAC signature
Helper Module
Response Builders
ok<T>(message: string, data?: T): Response<T>- Create success responseerr<T>(message: string, data?: T, errors?: ErrorInfo[] | string): Response<T>- Create error response
Security Module
SecureTransport
SecureTransport(aesKey: string)- Constructor for AES-GCM transportencrypt<T>(data: T): EncryptedPayload- Encrypt JSON datadecrypt<T>(payload: EncryptedPayload): T- Decrypt to JSON data
Sentinel
Sentinel(options: SentinelOptions)- Constructor for secure request handlinggenerateRequest<T>(data: T): SecureRequest<T | EncryptedPayload>- Generate signed/encrypted requestvalidateRequest<T>(req: SecureRequest): ValidationResult<T>- Validate and decrypt requestextractAndValidate<T>(req: SecureRequest): Promise<T>- Extract data or throw on invalid request
🏗️ Development
Prerequisites
- Node.js (version 18 or higher)
- npm, yarn, or pnpm
Setup
- Clone the repository:
git clone https://gitlab.com/tech-nuggets/technuggets.io/technuggets-sdk.git
cd technuggets-sdk- Install dependencies:
npm install- Build the project:
npm run build- Run in development mode:
npm run devScripts
npm run build- Build the projectnpm run dev- Build and watch for changesnpm run clean- Clean the dist directorynpm run prepublishOnly- Prepare for publishing
🤝 Contributing
We welcome contributions! Please see our Contributing Guidelines for details.
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🔗 Links
📝 Changelog
See CHANGELOG.md for a list of changes and version history.
🙏 Acknowledgments
- Built with TypeScript
- Bundled with tsdown
- Uses Argon2 for secure password hashing
Made with ❤️ by the Tech Nuggets team
