UNPKG

@catbee/utils

Version:

A modular, production-grade utility toolkit for Node.js and TypeScript, designed for robust, scalable applications (including Express-based services). All utilities are tree-shakable and can be imported independently.

249 lines (245 loc) 10.4 kB
/* * The MIT License * * Copyright (c) 2026 Catbee Technologies. https://catbee.in/license * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import { BinaryToTextEncoding, CipherGCMTypes } from 'node:crypto'; type BufferEncoding = 'ascii' | 'utf8' | 'utf-8' | 'utf16le' | 'utf-16le' | 'ucs2' | 'ucs-2' | 'base64' | 'base64url' | 'latin1' | 'binary' | 'hex'; /** * Generates an HMAC digest using the specified algorithm and secret key. * * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'sha1'). * @param {string} input - The string to hash. * @param {string} secret - The secret key for HMAC. * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc). * @returns {string} HMAC digest as a string. */ declare function hmac(algorithm: string, input: string, secret: string, encoding?: BinaryToTextEncoding): string; /** * Generates a hash digest using the specified algorithm. * * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'md5'). * @param {string} input - The string to hash. * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc). * @returns {string} Hash digest as a string. */ declare function hash(algorithm: string, input: string, encoding?: BinaryToTextEncoding): string; /** * Generates an HMAC-SHA256 digest. * * @param {string} input - The string to hash. * @param {string} secret - The secret key. * @returns {string} SHA-256 HMAC digest as a string. */ declare function sha256Hmac(input: string, secret: string): string; /** * Generates a SHA1 hash digest. * * @param {string} input - The string to hash. * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding. * @returns {string} SHA-1 hash as a string. */ declare function sha1(input: string, encoding?: BinaryToTextEncoding): string; /** * Generates a SHA256 hash digest. * * @param {string} input - The string to hash. * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding. * @returns {string} SHA-256 hash as a string. */ declare function sha256(input: string, encoding?: BinaryToTextEncoding): string; /** * Generates an MD5 hash digest. * * @param {string} input - The string to hash. * @returns {string} MD5 hash as a string. */ declare function md5(input: string): string; /** * Generates a cryptographically strong random string by hashing a random UUID with SHA-256. * * @returns {string} Random string hashed with SHA-256 (hex encoding). */ declare function randomString(): string; /** * Generates a secure random buffer of specified byte length. * * @param {number} [byteLength=32] - Number of random bytes to generate. * @returns {Buffer} Buffer containing random bytes. */ declare function generateRandomBytes(byteLength?: number): Buffer; /** * Generates a secure random string of specified byte length with specified encoding. * * @param {number} [byteLength=32] - Number of random bytes to generate. * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding. * @returns {string} Random string in specified encoding. */ declare function generateRandomBytesAsString(byteLength?: number, encoding?: BinaryToTextEncoding): string; /** * Generates a secure API key with a specified format. * * @param {string} [prefix=''] - Optional prefix for the key. * @param {number} [byteLength=24] - Number of random bytes to generate. * @returns {string} Formatted API key. */ declare function generateApiKey(prefix?: string, byteLength?: number): string; /** * Compares two strings, arrays, or buffers in constant time to prevent timing attacks. * * @param {string | Buffer | Uint8Array} a - First value to compare * @param {string | Buffer | Uint8Array} b - Second value to compare * @returns {boolean} True if values are equal */ declare function safeCompare(a: string | Buffer | Uint8Array, b: string | Buffer | Uint8Array): boolean; /** * Interface for encryption options */ interface EncryptionOptions { /** Algorithm to use (default: aes-256-gcm) */ algorithm?: CipherGCMTypes; /** Input encoding for plaintext if string (default: utf8) */ inputEncoding?: BufferEncoding; /** Output encoding for ciphertext (default: hex) */ outputEncoding?: BinaryToTextEncoding; } /** * Interface for decryption options */ interface DecryptionOptions { /** Algorithm to use (default: aes-256-gcm) */ algorithm?: CipherGCMTypes; /** Input encoding for ciphertext if string (default: hex) */ inputEncoding?: BinaryToTextEncoding; /** Output encoding for plaintext (default: utf8) */ outputEncoding?: BufferEncoding; } /** * Result of encryption operation including all data needed for decryption */ interface EncryptionResult { /** Encrypted data (string or Buffer based on options) */ ciphertext: string | Buffer; /** Initialization vector */ iv: Buffer; /** Authentication tag (for GCM mode) */ authTag?: Buffer; /** Algorithm used */ algorithm: string; /** Salt used for key derivation */ salt: Buffer; } /** * Encrypts data using a symmetric key with secure defaults (AES-256-GCM). * * @param {string | Buffer} data - Data to encrypt * @param {string | Buffer} key - Encryption key or passphrase * @param {EncryptionOptions} [options] - Encryption options * @returns {Promise<EncryptionResult>} Encrypted data with metadata */ declare function encrypt(data: string | Buffer, key: string | Buffer, options?: EncryptionOptions): Promise<EncryptionResult>; /** * Decrypts data that was encrypted with the encrypt function. * * @param {EncryptionResult} encryptedData - The encrypted data and metadata * @param {string | Buffer} key - Decryption key or passphrase * @param {DecryptionOptions} [options] - Decryption options * @returns {Promise<string | Buffer>} Decrypted data */ declare function decrypt(encryptedData: EncryptionResult, key: string | Buffer, options?: DecryptionOptions): Promise<string | Buffer>; /** * Creates a signed token with an expiration time and payload. * * @param {object} payload - Data to include in the token * @param {string} secret - Secret key for signing * @param {number} [expiresInSeconds=3600] - Token expiration in seconds * @returns {string} Signed token string */ declare function createSignedToken(payload: Record<string, any>, secret: string, expiresInSeconds?: number): string; /** * Verifies and decodes a signed token. * * @param {string} token - The token to verify * @param {string} secret - Secret key for verification * @returns {object | null} Decoded payload if valid, null if invalid */ declare function verifySignedToken(token: string, secret: string): Record<string, any> | null; /** * Derives a cryptographic key using PBKDF2 (SHA-256). * * @param password - Password to derive key from * @param salt - Cryptographic salt (use unique per password) * @param keyLength - Output key length in bytes (default 32) * @param iterations - Number of hashing iterations (default 310000, OWASP recommended) * @returns Derived key as Buffer * * @example * const key = await pbkdf2Hash('myPassword', 'mySalt'); */ declare function pbkdf2Hash(password: string, salt: string | Buffer, keyLength?: number, iterations?: number): Promise<Buffer>; /** * Generates a cryptographically secure nonce (number used once). * * @param {number} [byteLength=16] - Length of nonce in bytes. * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding. * @returns {string} Nonce string. * * @example * const nonce = generateNonce(16, 'base64'); // Random nonce */ declare function generateNonce(byteLength?: number, encoding?: BinaryToTextEncoding): string; /** * Generates a cryptographically secure random integer in a range. * * @param {number} min - Minimum value (inclusive). * @param {number} max - Maximum value (inclusive). * @returns {number} Random integer. * * @example * const random = secureRandomInt(1, 100); // Random number 1-100 */ declare function secureRandomInt(min: number, max: number): number; /** * Hashes a password using scrypt (memory-hard function). * * @param {string} password - The password to hash. * @param {number} [saltLength=16] - Length of salt in bytes. * @param {number} [keyLength=32] - Length of derived key. * @returns {Promise<string>} Hash string containing salt and key. * * @example * const hash = await hashPassword('myPassword'); * // Returns format: salt:hash (both base64) */ declare function hashPassword(password: string, saltLength?: number, keyLength?: number): Promise<string>; /** * Verifies a password against a scrypt hash. * * @param {string} password - The password to verify. * @param {string} hash - The hash to verify against (from hashPassword). * @returns {Promise<boolean>} True if password matches. * * @example * const isValid = await verifyPassword('myPassword', storedHash); */ declare function verifyPassword(password: string, hash: string): Promise<boolean>; export { createSignedToken, decrypt, encrypt, generateApiKey, generateNonce, generateRandomBytes, generateRandomBytesAsString, hash, hashPassword, hmac, md5, pbkdf2Hash, randomString, safeCompare, secureRandomInt, sha1, sha256, sha256Hmac, verifyPassword, verifySignedToken }; export type { BufferEncoding, DecryptionOptions, EncryptionOptions, EncryptionResult };