UNPKG

fortify2-js

Version:

MOST POWERFUL JavaScript Security Library! Military-grade cryptography + 19 enhanced object methods + quantum-resistant algorithms + perfect TypeScript support. More powerful than Lodash with built-in security.

904 lines (901 loc) 37.2 kB
export { FortifyJS as Fortify, FortifyJS as ftfy } from './core/crypto.js'; import { createSecureObject } from './components/secure-object/index.js'; export { MODULE_INFO, SECURE_OBJECT_VERSION, cloneSecureObject, createReadOnlySecureObject, createSecureObjectWithSensitiveKeys } from './components/secure-object/index.js'; import { createSecureString } from './components/secure-string/index.js'; import { createSecureArray } from './components/secure-array/index.js'; export { PasswordAlgorithm, PasswordSecurityLevel } from './core/password/password-types.js'; export { EntropySource, HashAlgorithm, KeyDerivationAlgorithm, SecurityLevel, TokenType } from './types.js'; import { SecureRandom } from './core/random/random-core.js'; import './core/random/random-types.js'; import 'crypto'; import './core/random/random-sources.js'; export { EnhancedUint8Array } from './helpers/Uint8Array.js'; import { RandomTokens } from './core/random/random-tokens.js'; import { RandomCrypto } from './core/random/random-crypto.js'; import { Hash } from './core/hash/hash-core.js'; import './core/hash/hash-types.js'; export { asciiToString, base32ToBuffer, base58ToBuffer, base64ToBase64Url, base64ToBuffer, base64ToString, base64UrlToBase64, base64UrlToBuffer, base64UrlToString, baseToNumber, binaryToBuffer, binaryToNumber, bufferToBase32, bufferToBase58, bufferToBase64, bufferToBase64Url, bufferToBinary, bufferToHex, bufferToOctal, bufferToString, bufferToUrlEncoded, buffersEqual, bytesToUint16, bytesToUint32, chunkBuffer, concatBuffers, convertBase, detectEncoding, formatBytes, hexToBuffer, hexToString, numberToBase, numberToBinary, numberToOctal, octalToBuffer, octalToNumber, padBuffer, randomBuffer, reverseBytes, simpleChecksum, stringToAscii, stringToBase64, stringToBase64Url, stringToBuffer, stringToHex, uint16ToBytes, uint32ToBytes, urlDecode, urlEncode, xorBuffers } from './utils/encoding.js'; import './core/hash/hash-security.js'; import './core/hash/hash-advanced.js'; import './algorithms/hash-algorithms.js'; export { Keys } from './core/keys.js'; export { Validators } from './core/validators.js'; import './core/password/index.js'; export { cacheHarden, constantTimeEqual, faultResistantEqual, maskedAccess, randomDelay, secureModPow } from './components/side-channel.js'; export { argon2Derive, balloonDerive } from './components/memory-hard.js'; export { generateKyberKeyPair, kyberDecapsulate, kyberEncapsulate, lamportGenerateKeypair, lamportSign, lamportVerify, ringLweDecrypt, ringLweEncrypt, ringLweGenerateKeypair } from './components/post-quantum.js'; export { SecureBuffer as Buffer, SecureBuffer, secureWipe } from './components/secure-memory.js'; export { EntropyPool } from './components/entropy-augmentation.js'; export { createCanary, createCanaryFunction, createCanaryObject, triggerCanary } from './components/canary-tokens.js'; export { createAttestation, createLibraryAttestation, generateAttestationKey, verifyAttestation, verifyLibraryAttestation } from './components/attestation.js'; export { SecurityIssueType, verifyRuntimeSecurity } from './components/runtime-verification.js'; export { secureDeserialize, secureSerialize } from './components/secure-serialization.js'; export { LogLevel, TamperEvidentLogger } from './components/tamper-evident-logging.js'; export { assessRSASecurity, benchmarkRSAPerformance, calculateRSAKeySize, generateProtectedRSAKeyPairForData, generateRSAKeyPairForData, getEncryptionSuggestion, getMaxDataSizeForRSAKey, getRSARecommendations, testRSAWithDataSize, validateDataSizeForRSAKey, validateRSAKeyPair } from './generators/rsaKeyCalculator.js'; export { commonPassword, contexts, detectContextInjection, detectSQLInjection, detectXSS, hasKeyboardPattern, isCommonPassword, keyboardPatterns, sqlPatterns, xssPatterns } from './utils/patterns.js'; export { detectInjection } from './utils/detectInjection.js'; export { createFortifiedFunction, func } from './components/fortified-function/index.js'; export { CACHE_BUILD_DATE, CACHE_VERSION, Cache, SecureCacheClient as SCC, SecureCacheClient, cleanupFileCache, clearAllCache, clearFileCache, createOptimalCache, createTypedFortifiedFunction, defaultFileCache, deleteFileCache, expireCache, filepath, generateFilePath, getCacheStats, getFileCacheStats, hasFileCache, readCache, readFileCache, removeFileCache, writeCache, writeFileCache } from './components/cache/index.js'; export { UFSMiddleware, createCacheMiddleware, createServer, createServerInstance } from './integrations/express/ServerFactory.js'; import { PasswordManager } from './core/password/password-core.js'; export { SecureString } from './components/secure-string/core/secure-string-core.js'; export { SecureArray } from './components/secure-array/core/secure-array-core.js'; export { FortifiedFunction } from './components/fortified-function/fortified-function.js'; export { SecureObject } from './components/secure-object/core/secure-object-core.js'; export { DEFAULT_SENSITIVE_KEYS, SensitiveKeysManager } from './components/secure-object/encryption/sensitive-keys.js'; export { CryptoHandler } from './components/secure-object/encryption/crypto-handler.js'; export { MetadataManager } from './components/secure-object/metadata/metadata-manager.js'; export { EventManager } from './components/secure-object/events/event-manager.js'; export { SerializationHandler } from './components/secure-object/serialization/serialization-handler.js'; export { IdGenerator } from './components/secure-object/utils/id-generator.js'; export { ValidationUtils } from './components/secure-object/utils/validation.js'; export { CONFIG as DEFAULT_CACHE_CONFIG, DEFAULT_FILE_CACHE_CONFIG } from './components/cache/config/cache.config.js'; export { SecureInMemoryCache } from './components/cache/useCache.js'; export { UltraFastSecureInMemoryCache } from './components/cache/UFSIMC.js'; export { FileCache } from './components/cache/cacheSys.js'; export { createCircularRefDebugger, createSafeJsonMiddleware, safeJsonStringify, sendSafeJson, setupSafeJson } from './integrations/express/middleware/safe-json-middleware.js'; export { expressStringify, fastStringify, safeStringify } from './components/fortified-function/serializer/safe-serializer.js'; export { Router } from 'express'; /*************************************************************************** * FortifyJS - Advanced JavaScript Security Library * * This file contains the main entry point for the FortifyJS library. * * @author Nehonix * @license MIT * * Copyright (c) 2025 Nehonix. All rights reserved. * * 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. ***************************************************************************** */ /** * # FortifyJS - Advanced JavaScript Security Library * * **The most comprehensive cryptographic security library for JavaScript applications** * * FortifyJS provides enterprise-grade security features including military-grade encryption, * secure data structures, advanced password management, and real-time security monitoring. * Built with TypeScript for maximum type safety and developer experience. * * ## Core Features * * ### Secure Data Structures * - **SecureArray**: Military-grade encrypted arrays with AES-256-CTR-HMAC * - **SecureString**: Protected string handling with automatic memory cleanup * - **SecureObject**: Encrypted object storage with metadata management * - **SecureBuffer**: Protected memory allocation with secure wiping * * ### Cryptographic Operations * - **Token Generation**: Secure random tokens with configurable entropy * - **Password Management**: Argon2ID hashing with pepper support * - **Hash Functions**: SHA-256/512, BLAKE3, with timing-safe operations * - **Key Derivation**: PBKDF2, Argon2, scrypt with memory-hard algorithms * * ### Performance & Security * - **FortifiedFunction**: Ultra-fast function execution with security monitoring * - **Cache System**: High-performance caching with encryption support * - **Memory Management**: Automatic cleanup and leak detection * - **Side-Channel Protection**: Constant-time operations and fault resistance * * ### Advanced Security * - **Post-Quantum Cryptography**: Lamport signatures and Ring-LWE * - **Canary Tokens**: Intrusion detection and monitoring * - **Attestation**: Code integrity verification * - **Entropy Augmentation**: Enhanced randomness sources * * ## Quick Start Examples * * ### Basic Token Generation * ```typescript * import { FortifyJS, generateSecureToken } from "fortify2-js"; * * // Generate a secure API key * const apiKey = FortifyJS.generateSecureToken({ * length: 32, * entropy: "maximum", * includeSymbols: false * }); * console.log(apiKey); // "aK7mN9pQ2rS8tU3vW6xY1zB4cD5eF7gH" * * // Quick token generation * const sessionToken = generateSecureToken(64, "base64url"); * ``` * * ### Secure Data Structures * ```typescript * import { fArray, fString, fObject } from "fortify2-js"; * * // Secure array with encryption * const sensitiveData = fArray(["api-key-1", "secret-token", "user-data"]); * sensitiveData.setEncryptionKey("your-encryption-key-2025"); * sensitiveData.encryptAll(); * * // Secure string with automatic cleanup * const password = fString("user-password-123", { * protectionLevel: "maximum", * enableEncryption: true * }); * * // Secure object with metadata * const userCredentials = fObject({ * username: "john_doe", * apiKey: "secret-key-value" * }); * ``` * * ### Password Management * ```typescript * import { PasswordManager, encryptSecurePass, verifyEncryptedPassword } from "fortify2-js"; * * // Advanced password hashing with pepper * const pepper = process.env.PASSWORD_PEPPER; * const hashedPassword = await encryptSecurePass("userPassword123", pepper); * * // Verify password with timing-safe comparison * const isValid = await verifyEncryptedPassword("userPassword123", hashedPassword, pepper); * * // Password manager with custom configuration * const pm = PasswordManager.create({ * algorithm: "argon2id", * memoryCost: 65536, * timeCost: 3 * }); * ``` * * ### High-Performance Functions * ```typescript * import { func, createFortifiedFunction } from "fortify2-js"; * * // Ultra-fast function with security monitoring * const optimizedFunction = func(async (data: string) => { * return data.toUpperCase(); * }, { * ultraFast: "maximum", * smartCaching: true, * autoEncrypt: true * }); * * const result = await optimizedFunction.execute("hello world"); * const analytics = optimizedFunction.getAnalyticsData(); * ``` * * ## Security Best Practices * * 1. **Always use environment variables for sensitive keys** * 2. **Enable encryption for sensitive data structures** * 3. **Use timing-safe operations for authentication** * 4. **Implement proper memory cleanup with destroy() methods** * 5. **Monitor security status with built-in analytics** * * @author Nehonix * @version 4.2.0 * @license MIT * @see {@link https://lab.nehonix.space/nehonix_viewer/_doc/Nehonix%20FortifyJs} Official Documentation * @see {@link https://github.com/NEHONIX/fortifyjs} GitHub Repository * @see {@link https://nodejs.org/api/crypto.html} Node.js Crypto Module * @see {@link https://github.com/ranisalt/node-argon2} Argon2 Implementation * @see {@link https://github.com/paulmillr/noble-hashes} Noble Hashes Library * @see {@link https://libsodium.gitbook.io/doc/} Libsodium Documentation * @see {@link https://github.com/jedisct1/libsodium.js} Libsodium.js * @see {@link https://www.npmjs.com/package/bcryptjs} BCrypt.js Package * * @example * ```typescript * // Complete security setup example * import { FortifyJS, fArray, PasswordManager } from "fortify2-js"; * * // 1. Generate secure tokens * const apiKey = FortifyJS.generateAPIKey(32, "api"); * const sessionToken = FortifyJS.generateSessionToken(); * * // 2. Secure data storage * const userData = fArray([]); * userData.setEncryptionKey(process.env.ENCRYPTION_KEY); * userData.push("sensitive-user-data"); * * // 3. Password management * const pm = PasswordManager.getInstance(); * const hashedPassword = await pm.hash("userPassword"); * * // 4. Security monitoring * const stats = FortifyJS.getStats(); * const securityStatus = FortifyJS.verifyRuntimeSecurity(); * * console.log("Security Status:", securityStatus.isSecure); * console.log("Operations:", stats.totalOperations); * ``` */ /** * ## Crypto Compatibility Layer * * Direct function exports for easy migration from Node.js crypto module. * These functions provide drop-in replacements with enhanced security features. */ /** * ### Secure Cipher Operations * * Enhanced cipher creation and management with automatic security hardening. * Provides secure alternatives to Node.js crypto.createCipher functions. * * @example * ```typescript * import { createSecureCipheriv, createSecureDecipheriv, generateSecureIV } from "fortify2-js"; * * // Create secure cipher with automatic IV generation * const key = "your-encryption-key"; * const iv = generateSecureIV("aes-256-cbc"); * const cipher = createSecureCipheriv("aes-256-cbc", key, iv); * * // Encrypt data * let encrypted = cipher.update("sensitive data", "utf8", "hex"); * encrypted += cipher.final("hex"); * * // Decrypt data * const decipher = createSecureDecipheriv("aes-256-cbc", key, iv); * let decrypted = decipher.update(encrypted, "hex", "utf8"); * decrypted += decipher.final("utf8"); * ``` */ /** Create secure cipher with enhanced security features */ const createSecureCipheriv = RandomCrypto.createSecureCipheriv; /** Create secure decipher with enhanced security features */ const createSecureDecipheriv = RandomCrypto.createSecureDecipheriv; /** Generate cryptographically secure initialization vector */ const generateSecureIV = RandomCrypto.generateSecureIV; /** Generate multiple secure IVs in batch for performance */ const generateSecureIVBatch = RandomCrypto.generateSecureIVBatch; /** Generate secure IV for specific algorithm */ const generateSecureIVForAlgorithm = RandomCrypto.generateSecureIVForAlgorithm; /** Generate multiple secure IVs for specific algorithm */ const generateSecureIVBatchForAlgorithm = RandomCrypto.generateSecureIVBatchForAlgorithm; /** Validate initialization vector format and security */ const validateIV = RandomCrypto.validateIV; /** * ### Random Data Generation * * High-entropy random data generation for cryptographic operations. * * @example * ```typescript * import { getRandomBytes, generateSecureUUID } from "fortify2-js"; * * // Generate random bytes * const randomData = getRandomBytes(32); * * // Generate secure UUID * const uuid = generateSecureUUID(); * ``` */ /** Generate cryptographically secure random bytes */ const getRandomBytes = SecureRandom.getRandomBytes; /** Generate secure UUID with high entropy */ const generateSecureUUID = SecureRandom.generateSecureUUID; /** * ### Token Generation * * Secure token generation for sessions, API keys, and authentication. * * @example * ```typescript * import { generateSessionToken } from "fortify2-js"; * * // Generate session token * const sessionToken = generateSessionToken(64, "base64url"); * ``` */ /** Generate secure session token with configurable encoding */ const generateSessionToken = RandomTokens.generateSessionToken; /** * ### Hash Operations * * Military-grade hashing functions with timing-safe operations and * automatic salt generation for maximum security. * * @example * ```typescript * import { createSecureHash, createSecureHMAC, verifyHash } from "fortify2-js"; * * // Create secure hash with automatic salt * const hash = createSecureHash("data to hash"); * * // Create HMAC with secret key * const hmac = createSecureHMAC("sha256", "secret-key", "data"); * * // Verify hash with timing-safe comparison * const isValid = verifyHash("original-data", hash); * ``` * * @see {@link https://github.com/paulmillr/noble-hashes} Noble Hashes - Modern Crypto Library * @see {@link https://nodejs.org/api/crypto.html#cryptocreatehashstring-options} Node.js Hash Functions * @see {@link https://tools.ietf.org/html/rfc2104} RFC 2104 - HMAC Specification * @see {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf} NIST SHA Standards */ /** Create secure hash with automatic salt generation */ const createSecureHash = Hash.createSecureHash; /** Create secure HMAC with timing-safe operations */ const createSecureHMAC = Hash.createSecureHMAC; /** Verify hash with constant-time comparison */ const verifyHash = Hash.verifyHash; /** * ### Password Manager Quick Access * * Convenient alias for password manager with default configuration. * For production use with custom configuration, use PasswordManager.create() * or PasswordManager.getInstance() with specific options. * * @example * ```typescript * import { pm } from "fortify2-js"; * * // Quick password operations with default config * const hash = await pm.hash("userPassword"); * const result = await pm.verify("userPassword", hash); * * // For custom configuration: * // const customPM = PasswordManager.create({ memoryCost: 131072 }); * ``` * * @deprecated Consider using PasswordManager.getInstance() for explicit configuration */ const pm = PasswordManager.getInstance(); /** * ## Secure Data Structure Factory Functions * * Convenient factory functions for creating secure data structures with * enhanced security features and automatic memory management. */ /** * ### Create Secure String * * Creates a secure string instance with automatic memory management, * encryption capabilities, and secure cleanup functionality. * * **Key Features:** * - Automatic memory tracking and cleanup * - Optional AES-256 encryption for sensitive data * - Memory fragmentation protection * - Secure wiping on destruction * - Event-driven lifecycle management * * @param value - The initial string value to secure * @param options - Configuration options for security level and features * @returns A new SecureString instance with enhanced protection * * @example Basic Usage * ```typescript * import { fString } from "fortify2-js"; * * // Create basic secure string * const password = fString("userPassword123"); * * // Access string value * console.log(password.toString()); * * // Secure cleanup * password.destroy(); * ``` * * @example Advanced Configuration * ```typescript * import { fString } from "fortify2-js"; * * // Maximum security configuration * const sensitiveData = fString("credit-card-4532-1234-5678-9012", { * protectionLevel: "maximum", * enableEncryption: true, * enableFragmentation: true, * enableMemoryTracking: true, * autoCleanup: true * }); * * // String operations with automatic encryption/decryption * sensitiveData.append("-VERIFIED"); * const masked = sensitiveData.mask(4, 12, "*"); * * // Cryptographic operations * const hash = await sensitiveData.hash("SHA-256"); * const isValid = sensitiveData.equals("other-string", true); // timing-safe * * // Automatic cleanup when done * sensitiveData.destroy(); * ``` * * @author Seth Eleazar * @since 1.0.0 */ function fString(...args) { return createSecureString(...args); } /** * ### Create Secure Object * * Creates a secure object instance with encryption, metadata management, * and comprehensive security features for sensitive data storage. * * **Key Features:** * - Automatic encryption for sensitive values * - Metadata tracking and management * - Event-driven architecture * - Secure serialization and deserialization * - Memory protection and cleanup * * @param initialData - The initial data to store in the secure object * @param options - Configuration options for encryption and security * @returns A new SecureObject instance with enhanced protection * * @example Basic Usage * ```typescript * import { fObject } from "fortify2-js"; * * // Create secure object with initial data * const userCredentials = fObject({ * username: "john_doe", * apiKey: "secret-api-key-12345", * sessionToken: "session-token-abcdef" * }); * * // Access and modify data * userCredentials.set("lastLogin", new Date().toISOString()); * const apiKey = userCredentials.get("apiKey"); * * // Secure cleanup * userCredentials.destroy(); * ``` * * @example Advanced Configuration * ```typescript * import { fObject } from "fortify2-js"; * * // Create with encryption and metadata tracking * const secureConfig = fObject({ * databaseUrl: "postgresql://user:pass@localhost/db", * encryptionKey: "master-encryption-key-2025", * apiSecrets: { * stripe: "sk_live_...", * aws: "AKIA..." * } * }, { * encryptionKey: process.env.OBJECT_ENCRYPTION_KEY, * enableMetadata: true, * autoCleanup: true * }); * * // Mark sensitive keys for special handling * secureConfig.markSensitive("databaseUrl"); * secureConfig.markSensitive("encryptionKey"); * secureConfig.markSensitive("apiSecrets"); * * // Export with encryption * const encrypted = secureConfig.serialize({ encrypt: true }); * * // Event handling * secureConfig.on("accessed", (key) => { * console.log(`Sensitive key accessed: ${key}`); * }); * ``` * * @author Seth Eleazar * @since 1.0.0 */ function fObject(...args) { return createSecureObject(...args); } /** * ### Create Secure Array * * Creates a military-grade secure array with AES-256-CTR-HMAC encryption, * comprehensive security features, and high-performance operations. * * **Key Features:** * - Military-grade AES-256-CTR-HMAC encryption * - Real-time security monitoring and analytics * - Automatic memory management and cleanup * - Snapshot and versioning capabilities * - Event-driven architecture * - Multiple export formats with integrity verification * - Advanced array operations (unique, shuffle, min/max) * * @param initialData - The initial array data to secure * @param options - Configuration options for encryption and security features * @returns A new SecureArray instance with military-grade protection * * @example Basic Usage * ```typescript * import { fArray } from "fortify2-js"; * * // Create secure array with sensitive data * const apiKeys = fArray([ * "api-key-production-12345", * "api-key-staging-67890", * "api-key-development-abcdef" * ]); * * // Set encryption key and encrypt all data * apiKeys.setEncryptionKey("your-super-secret-key-2025"); * apiKeys.encryptAll(); * * // Use like regular array - data automatically encrypted/decrypted * apiKeys.push("new-api-key-xyz789"); * const firstKey = apiKeys.get(0); // Automatically decrypted * const filtered = apiKeys.filter(key => key.includes("production")); * * // Secure cleanup * apiKeys.destroy(); * ``` * * @example Advanced Operations * ```typescript * import { fArray } from "fortify2-js"; * import { NehoID as ID } from "nehoid"; * * // Create array for high-volume data processing * const dataProcessor = fArray([] as string[], { * encryptionKey: process.env.ARRAY_ENCRYPTION_KEY, * enableCompression: true, * maxSize: 100000, * enableEvents: true * }); * * // Bulk data processing with automatic encryption * const dataTypes = ["user", "transaction", "audit", "system"]; * const maxRecords = 10000; * * for (let i = 0; i < maxRecords; i++) { * const randomType = dataTypes[Math.floor(Math.random() * dataTypes.length)]; * const record = `${randomType}-record-${i}-${Date.now()}`; * dataProcessor.push(record); * } * * // Advanced analytics and operations * const stats = dataProcessor.getStats(); * const snapshot = dataProcessor.createSnapshot(); * const exported = dataProcessor.exportData("json"); * * // Event monitoring * dataProcessor.on("push", (index, value) => { * console.log(`New record added at index ${index}`); * }); * * // Generate probability analysis * console.log("Data distribution:", ID.probabilityCloud(dataProcessor.toArray())); * * // Secure cleanup - wipes all data and destroys array * dataProcessor.destroy(); // Cannot be used after this * ``` * * @example Real-time Security Monitoring * ```typescript * import { fArray } from "fortify2-js"; * * // Create array with comprehensive monitoring * const secureData = fArray(["sensitive-data-1", "sensitive-data-2"], { * enableRealTimeMonitoring: true, * enableIntegrityChecks: true, * enableAuditLogging: true * }); * * // Monitor security status * const encryptionStatus = secureData.getEncryptionStatus(); * console.log(`Algorithm: ${encryptionStatus.algorithm}`); * console.log(`Encrypted elements: ${encryptionStatus.encryptedCount}`); * * // Real-time analytics * const analytics = secureData.getAnalytics(); * console.log(`Performance score: ${analytics.performanceScore}`); * console.log(`Security level: ${analytics.securityLevel}`); * ``` * * @author Seth Eleazar * @license MIT * @since 1.0.0 * @see {@link https://github.com/paulmillr/noble-ciphers} Noble Ciphers - AES Implementation * @see {@link https://tools.ietf.org/html/rfc3610} RFC 3610 - Counter with CBC-MAC (CCM) * @see {@link https://csrc.nist.gov/publications/detail/sp/800-38a/final} NIST SP 800-38A */ function fArray(...args) { return createSecureArray(...args); } /** * ## Advanced Password Security Functions * * Military-grade password encryption and verification with pepper support, * timing-safe operations, and comprehensive security features. */ /** * ### Encrypt Password with Pepper * * Encrypts a password using military-grade security with pepper (secret) application * before Argon2ID hashing. This provides maximum protection against rainbow table * attacks and database compromise scenarios. * * **Security Features:** * - HMAC-SHA256 pepper application for additional entropy * - Argon2ID memory-hard hashing algorithm * - Timing-safe operations to prevent side-channel attacks * - Configurable memory and time costs for future-proofing * - Automatic salt generation for each password * * **Important Security Notes:** * - The PEPPER must be stored securely (environment variables, key management system) * - PEPPER should never be stored in the same database as password hashes * - Use a cryptographically secure random value for PEPPER generation * - Consider key rotation policies for long-term security * * @param password - The plain text password to encrypt * @param PEPPER - A secret pepper value (must be stored securely, not in database) * @param options - Advanced hashing configuration options * @returns Promise<string> - The peppered and hashed password ready for secure storage * @throws {Error} If PEPPER is not provided or invalid * * @example Basic Usage * ```typescript * import { encryptSecurePass, Random } from "fortify2-js"; * * // Generate secure pepper (do this once, store securely) * const pepper = Random.getRandomBytes(32, "hex"); * console.log("Store this PEPPER securely:", pepper); * * // In your application (pepper from environment) * const pepper = process.env.PASSWORD_PEPPER; * const hashedPassword = await encryptSecurePass("userPassword123", pepper); * * // Store hashedPassword in database * await database.users.update(userId, { passwordHash: hashedPassword }); * ``` * * @example Advanced Configuration * ```typescript * import { encryptSecurePass, PasswordAlgorithm } from "fortify2-js"; * * // Maximum security configuration * const hashedPassword = await encryptSecurePass("userPassword123", pepper, { * algorithm: PasswordAlgorithm.ARGON2ID, * memoryCost: 131072, // 128 MB memory usage * timeCost: 4, // 4 iterations * parallelism: 2, // 2 parallel threads * hashLength: 64, // 64-byte output * saltLength: 32 // 32-byte salt * }); * ``` * * @example Production Setup * ```typescript * // .env file * PASSWORD_PEPPER=your-cryptographically-secure-pepper-value-here * * // Application code * import { encryptSecurePass } from "fortify2-js"; * * const pepper = process.env.PASSWORD_PEPPER; * if (!pepper) { * throw new Error("PASSWORD_PEPPER environment variable is required"); * } * * // User registration * const hashedPassword = await encryptSecurePass(userPassword, pepper); * await saveUserToDatabase({ email, passwordHash: hashedPassword }); * ``` * * @security * - **HMAC-SHA256**: Applied to password with pepper for additional entropy * - **Argon2ID**: Memory-hard algorithm resistant to GPU and ASIC attacks * - **Timing Safety**: Constant-time operations prevent timing attacks * - **Salt Generation**: Automatic unique salt for each password * - **Memory Protection**: Secure memory handling throughout the process * * @author suppercodercodelover * @since 2.0.0 */ async function encryptSecurePass(password, PEPPER, options = {}) { if (!PEPPER) { throw new Error("PEPPER must be defined when running password master. Store it securely in environment variables."); } // Apply pepper using HMAC-SHA256 for cryptographic security const peppered = Hash.createSecureHMAC("sha256", PEPPER, password); // Hash the peppered password with Argon2ID (military-grade) const passwordManager = PasswordManager.getInstance(); return await passwordManager.hash(peppered, options); } /** * ### Verify Encrypted Password * * Verifies a plain text password against a peppered hash using timing-safe comparison. * This function must be used with passwords that were encrypted using encryptSecurePass() * to ensure proper pepper application and security verification. * * **Security Features:** * - Constant-time comparison to prevent timing attacks * - Same HMAC-SHA256 pepper application as encryption * - Resistant to side-channel analysis * - No information leakage through execution time * - Comprehensive error handling and validation * * **Important Security Notes:** * - Must use the exact same PEPPER value as used in encryptSecurePass() * - Verification time is constant regardless of password correctness * - Function returns only boolean result to prevent information leakage * - All intermediate values are securely cleared from memory * * @param password - The plain text password to verify * @param hashedPassword - The peppered hash from database (created with encryptSecurePass) * @param PEPPER - The same secret pepper value used during encryption * @returns Promise<boolean> - true if password is valid, false otherwise * @throws {Error} If PEPPER is not provided or verification fails * * @example Basic Login Verification * ```typescript * import { verifyEncryptedPassword } from "fortify2-js"; * * // User login attempt * const pepper = process.env.PASSWORD_PEPPER; * const userPassword = "userPassword123"; * const storedHash = await database.users.getPasswordHash(userId); * * const isValid = await verifyEncryptedPassword( * userPassword, * storedHash, * pepper * ); * * if (isValid) { * // Login successful - create session * const sessionToken = generateSessionToken(); * await createUserSession(userId, sessionToken); * console.log("Login successful!"); * } else { * // Login failed - log attempt and return error * await logFailedLoginAttempt(userId); * console.log("Invalid credentials"); * } * ``` * * @example Production Authentication Flow * ```typescript * import { verifyEncryptedPassword } from "fortify2-js"; * * async function authenticateUser(email: string, password: string) { * try { * // Get user and password hash from database * const user = await database.users.findByEmail(email); * if (!user) { * // Use timing-safe dummy verification to prevent user enumeration * await verifyEncryptedPassword("dummy", "dummy-hash", pepper); * return { success: false, error: "Invalid credentials" }; * } * * // Verify password with timing-safe comparison * const pepper = process.env.PASSWORD_PEPPER; * const isValid = await verifyEncryptedPassword( * password, * user.passwordHash, * pepper * ); * * if (isValid) { * // Update last login timestamp * await database.users.updateLastLogin(user.id); * * // Create secure session * const sessionToken = generateSessionToken(64, "base64url"); * await database.sessions.create({ * userId: user.id, * token: sessionToken, * expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000) // 24 hours * }); * * return { * success: true, * user: { id: user.id, email: user.email }, * sessionToken * }; * } else { * // Log failed attempt for security monitoring * await database.auditLog.create({ * action: "failed_login", * userId: user.id, * ip: request.ip, * timestamp: new Date() * }); * * return { success: false, error: "Invalid credentials" }; * } * } catch (error) { * console.error("Authentication error:", error); * return { success: false, error: "Authentication failed" }; * } * } * ``` * * @example Rate Limiting and Security * ```typescript * import { verifyEncryptedPassword } from "fortify2-js"; * * async function secureLogin(email: string, password: string, clientIP: string) { * // Check rate limiting first * const attempts = await getFailedAttempts(clientIP); * if (attempts >= 5) { * throw new Error("Too many failed attempts. Please try again later."); * } * * // Verify password * const pepper = process.env.PASSWORD_PEPPER; * const user = await getUserByEmail(email); * * if (!user) { * // Timing-safe dummy operation * await verifyEncryptedPassword("dummy", "dummy-hash", pepper); * await incrementFailedAttempts(clientIP); * return false; * } * * const isValid = await verifyEncryptedPassword(password, user.passwordHash, pepper); * * if (isValid) { * await clearFailedAttempts(clientIP); * return true; * } else { * await incrementFailedAttempts(clientIP); * return false; * } * } * ``` * * @security * - **Timing Safety**: Constant execution time prevents timing attacks * - **Pepper Consistency**: Uses same HMAC-SHA256 pepper as encryption * - **Side-Channel Resistance**: No information leakage through execution patterns * - **Memory Protection**: Secure handling of sensitive data throughout verification * - **Error Handling**: Comprehensive validation without information disclosure * * @author suppercodercodelover * @since 2.0.0 */ async function verifyEncryptedPassword(password, hashedPassword, PEPPER) { if (!PEPPER) { throw new Error("PEPPER must be defined when running password master. Use the same pepper as encryptSecurePass()."); } // Apply the same pepper transformation as during encryption const peppered = Hash.createSecureHMAC("sha256", PEPPER, password); // Perform timing-safe verification const passwordManager = PasswordManager.getInstance(); const result = await passwordManager.verify(peppered, hashedPassword); return result.isValid; } export { Hash, PasswordManager, SecureRandom as Random, createSecureCipheriv, createSecureDecipheriv, createSecureHMAC, createSecureHash, createSecureObject, encryptSecurePass, fArray, fObject, fString, generateSecureIV, generateSecureIVBatch, generateSecureIVBatchForAlgorithm, generateSecureIVForAlgorithm, generateSecureUUID, generateSessionToken, getRandomBytes, pm, validateIV, verifyEncryptedPassword, verifyHash }; //# sourceMappingURL=index.js.map