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.

1,136 lines (1,132 loc) 46 kB
'use strict'; var crypto = require('./core/crypto.js'); var index$1 = require('./components/secure-object/index.js'); var index$3 = require('./components/secure-string/index.js'); var index$4 = require('./components/secure-array/index.js'); var passwordTypes = require('./core/password/password-types.js'); var types = require('./types.js'); var randomCore = require('./core/random/random-core.js'); require('./core/random/random-types.js'); require('crypto'); require('./core/random/random-sources.js'); var Uint8Array = require('./helpers/Uint8Array.js'); var randomTokens = require('./core/random/random-tokens.js'); var randomCrypto = require('./core/random/random-crypto.js'); var hashCore = require('./core/hash/hash-core.js'); require('./core/hash/hash-types.js'); var encoding = require('./utils/encoding.js'); require('./core/hash/hash-security.js'); require('./core/hash/hash-advanced.js'); require('./algorithms/hash-algorithms.js'); var keys = require('./core/keys.js'); var validators = require('./core/validators.js'); require('./core/password/index.js'); var sideChannel = require('./components/side-channel.js'); var memoryHard = require('./components/memory-hard.js'); var postQuantum = require('./components/post-quantum.js'); var secureMemory = require('./components/secure-memory.js'); var entropyAugmentation = require('./components/entropy-augmentation.js'); var canaryTokens = require('./components/canary-tokens.js'); var attestation = require('./components/attestation.js'); var runtimeVerification = require('./components/runtime-verification.js'); var secureSerialization = require('./components/secure-serialization.js'); var tamperEvidentLogging = require('./components/tamper-evident-logging.js'); var rsaKeyCalculator = require('./generators/rsaKeyCalculator.js'); var patterns = require('./utils/patterns.js'); var detectInjection = require('./utils/detectInjection.js'); var index = require('./components/fortified-function/index.js'); var index$2 = require('./components/cache/index.js'); var ServerFactory = require('./integrations/express/ServerFactory.js'); var passwordCore = require('./core/password/password-core.js'); var secureStringCore = require('./components/secure-string/core/secure-string-core.js'); var secureArrayCore = require('./components/secure-array/core/secure-array-core.js'); var fortifiedFunction = require('./components/fortified-function/fortified-function.js'); var secureObjectCore = require('./components/secure-object/core/secure-object-core.js'); var sensitiveKeys = require('./components/secure-object/encryption/sensitive-keys.js'); var cryptoHandler = require('./components/secure-object/encryption/crypto-handler.js'); var metadataManager = require('./components/secure-object/metadata/metadata-manager.js'); var eventManager = require('./components/secure-object/events/event-manager.js'); var serializationHandler = require('./components/secure-object/serialization/serialization-handler.js'); var idGenerator = require('./components/secure-object/utils/id-generator.js'); var validation = require('./components/secure-object/utils/validation.js'); var cache_config = require('./components/cache/config/cache.config.js'); var useCache = require('./components/cache/useCache.js'); var UFSIMC = require('./components/cache/UFSIMC.js'); var cacheSys = require('./components/cache/cacheSys.js'); var safeJsonMiddleware = require('./integrations/express/middleware/safe-json-middleware.js'); var safeSerializer = require('./components/fortified-function/serializer/safe-serializer.js'); var express = require('express'); /*************************************************************************** * FortifyJS - Secure Array Types * * This file contains type definitions for the SecureArray architecture * * @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.RandomCrypto.createSecureCipheriv; /** Create secure decipher with enhanced security features */ const createSecureDecipheriv = randomCrypto.RandomCrypto.createSecureDecipheriv; /** Generate cryptographically secure initialization vector */ const generateSecureIV = randomCrypto.RandomCrypto.generateSecureIV; /** Generate multiple secure IVs in batch for performance */ const generateSecureIVBatch = randomCrypto.RandomCrypto.generateSecureIVBatch; /** Generate secure IV for specific algorithm */ const generateSecureIVForAlgorithm = randomCrypto.RandomCrypto.generateSecureIVForAlgorithm; /** Generate multiple secure IVs for specific algorithm */ const generateSecureIVBatchForAlgorithm = randomCrypto.RandomCrypto.generateSecureIVBatchForAlgorithm; /** Validate initialization vector format and security */ const validateIV = randomCrypto.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 = randomCore.SecureRandom.getRandomBytes; /** Generate secure UUID with high entropy */ const generateSecureUUID = randomCore.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.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 = hashCore.Hash.createSecureHash; /** Create secure HMAC with timing-safe operations */ const createSecureHMAC = hashCore.Hash.createSecureHMAC; /** Verify hash with constant-time comparison */ const verifyHash = hashCore.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 = passwordCore.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 index$3.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 index$1.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 index$4.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 = hashCore.Hash.createSecureHMAC("sha256", PEPPER, password); // Hash the peppered password with Argon2ID (military-grade) const passwordManager = passwordCore.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 = hashCore.Hash.createSecureHMAC("sha256", PEPPER, password); // Perform timing-safe verification const passwordManager = passwordCore.PasswordManager.getInstance(); const result = await passwordManager.verify(peppered, hashedPassword); return result.isValid; } exports.Fortify = crypto.FortifyJS; exports.ftfy = crypto.FortifyJS; exports.MODULE_INFO = index$1.MODULE_INFO; exports.SECURE_OBJECT_VERSION = index$1.SECURE_OBJECT_VERSION; exports.cloneSecureObject = index$1.cloneSecureObject; exports.createReadOnlySecureObject = index$1.createReadOnlySecureObject; exports.createSecureObject = index$1.createSecureObject; exports.createSecureObjectWithSensitiveKeys = index$1.createSecureObjectWithSensitiveKeys; Object.defineProperty(exports, 'PasswordAlgorithm', { enumerable: true, get: function () { return passwordTypes.PasswordAlgorithm; } }); Object.defineProperty(exports, 'PasswordSecurityLevel', { enumerable: true, get: function () { return passwordTypes.PasswordSecurityLevel; } }); Object.defineProperty(exports, 'EntropySource', { enumerable: true, get: function () { return types.EntropySource; } }); Object.defineProperty(exports, 'HashAlgorithm', { enumerable: true, get: function () { return types.HashAlgorithm; } }); Object.defineProperty(exports, 'KeyDerivationAlgorithm', { enumerable: true, get: function () { return types.KeyDerivationAlgorithm; } }); Object.defineProperty(exports, 'SecurityLevel', { enumerable: true, get: function () { return types.SecurityLevel; } }); Object.defineProperty(exports, 'TokenType', { enumerable: true, get: function () { return types.TokenType; } }); exports.Random = randomCore.SecureRandom; exports.EnhancedUint8Array = Uint8Array.EnhancedUint8Array; exports.Hash = hashCore.Hash; exports.asciiToString = encoding.asciiToString; exports.base32ToBuffer = encoding.base32ToBuffer; exports.base58ToBuffer = encoding.base58ToBuffer; exports.base64ToBase64Url = encoding.base64ToBase64Url; exports.base64ToBuffer = encoding.base64ToBuffer; exports.base64ToString = encoding.base64ToString; exports.base64UrlToBase64 = encoding.base64UrlToBase64; exports.base64UrlToBuffer = encoding.base64UrlToBuffer; exports.base64UrlToString = encoding.base64UrlToString; exports.baseToNumber = encoding.baseToNumber; exports.binaryToBuffer = encoding.binaryToBuffer; exports.binaryToNumber = encoding.binaryToNumber; exports.bufferToBase32 = encoding.bufferToBase32; exports.bufferToBase58 = encoding.bufferToBase58; exports.bufferToBase64 = encoding.bufferToBase64; exports.bufferToBase64Url = encoding.bufferToBase64Url; exports.bufferToBinary = encoding.bufferToBinary; exports.bufferToHex = encoding.bufferToHex; exports.bufferToOctal = encoding.bufferToOctal; exports.bufferToString = encoding.bufferToString; exports.bufferToUrlEncoded = encoding.bufferToUrlEncoded; exports.buffersEqual = encoding.buffersEqual; exports.bytesToUint16 = encoding.bytesToUint16; exports.bytesToUint32 = encoding.bytesToUint32; exports.chunkBuffer = encoding.chunkBuffer; exports.concatBuffers = encoding.concatBuffers; exports.convertBase = encoding.convertBase; exports.detectEncoding = encoding.detectEncoding; exports.formatBytes = encoding.formatBytes; exports.hexToBuffer = encoding.hexToBuffer; exports.hexToString = encoding.hexToString; exports.numberToBase = encoding.numberToBase; exports.numberToBinary = encoding.numberToBinary; exports.numberToOctal = encoding.numberToOctal; exports.octalToBuffer = encoding.octalToBuffer; exports.octalToNumber = encoding.octalToNumber; exports.padBuffer = encoding.padBuffer; exports.randomBuffer = encoding.randomBuffer; exports.reverseBytes = encoding.reverseBytes; exports.simpleChecksum = encoding.simpleChecksum; exports.stringToAscii = encoding.stringToAscii; exports.stringToBase64 = encoding.stringToBase64; exports.stringToBase64Url = encoding.stringToBase64Url; exports.stringToBuffer = encoding.stringToBuffer; exports.stringToHex = encoding.stringToHex; exports.uint16ToBytes = encoding.uint16ToBytes; exports.uint32ToBytes = encoding.uint32ToBytes; exports.urlDecode = encoding.urlDecode; exports.urlEncode = encoding.urlEncode; exports.xorBuffers = encoding.xorBuffers; exports.Keys = keys.Keys; exports.Validators = validators.Validators; exports.cacheHarden = sideChannel.cacheHarden; exports.constantTimeEqual = sideChannel.constantTimeEqual; exports.faultResistantEqual = sideChannel.faultResistantEqual; exports.maskedAccess = sideChannel.maskedAccess; exports.randomDelay = sideChannel.randomDelay; exports.secureModPow = sideChannel.secureModPow; exports.argon2Derive = memoryHard.argon2Derive; exports.balloonDerive = memoryHard.balloonDerive; exports.generateKyberKeyPair = postQuantum.generateKyberKeyPair; exports.kyberDecapsulate = postQuantum.kyberDecapsulate; exports.kyberEncapsulate = postQuantum.kyberEncapsulate; exports.lamportGenerateKeypair = postQuantum.lamportGenerateKeypair; exports.lamportSign = postQuantum.lamportSign; exports.lamportVerify = postQuantum.lamportVerify; exports.ringLweDecrypt = postQuantum.ringLweDecrypt; exports.ringLweEncrypt = postQuantum.ringLweEncrypt; exports.ringLweGenerateKeypair = postQuantum.ringLweGenerateKeypair; exports.Buffer = secureMemory.SecureBuffer; exports.SecureBuffer = secureMemory.SecureBuffer; exports.secureWipe = secureMemory.secureWipe; exports.EntropyPool = entropyAugmentation.EntropyPool; exports.createCanary = canaryTokens.createCanary; exports.createCanaryFunction = canaryTokens.createCanaryFunction; exports.createCanaryObject = canaryTokens.createCanaryObject; exports.triggerCanary = canaryTokens.triggerCanary; exports.createAttestation = attestation.createAttestation; exports.createLibraryAttestation = attestation.createLibraryAttestation; exports.generateAttestationKey = attestation.generateAttestationKey; exports.verifyAttestation = attestation.verifyAttestation; exports.verifyLibraryAttestation = attestation.verifyLibraryAttestation; Object.defineProperty(exports, 'SecurityIssueType', { enumerable: true, get: function () { return runtimeVerification.SecurityIssueType; } }); exports.verifyRuntimeSecurity = runtimeVerification.verifyRuntimeSecurity; exports.secureDeserialize = secureSerialization.secureDeserialize; exports.secureSerialize = secureSerialization.secureSerialize; Object.defineProperty(exports, 'LogLevel', { enumerable: true, get: function () { return tamperEvidentLogging.LogLevel; } }); exports.TamperEvidentLogger = tamperEvidentLogging.TamperEvidentLogger; exports.assessRSASecurity = rsaKeyCalculator.assessRSASecurity; exports.benchmarkRSAPerformance = rsaKeyCalculator.benchmarkRSAPerformance; exports.calculateRSAKeySize = rsaKeyCalculator.calculateRSAKeySize; exports.generateProtectedRSAKeyPairForData = rsaKeyCalculator.generateProtectedRSAKeyPairForData; exports.generateRSAKeyPairForData = rsaKeyCalculator.generateRSAKeyPairForData; exports.getEncryptionSuggestion = rsaKeyCalculator.getEncryptionSuggestion; exports.getMaxDataSizeForRSAKey = rsaKeyCalculator.getMaxDataSizeForRSAKey; exports.getRSARecommendations = rsaKeyCalculator.getRSARecommendations; exports.testRSAWithDataSize = rsaKeyCalculator.testRSAWithDataSize; exports.validateDataSizeForRSAKey = rsaKeyCalculator.validateDataSizeForRSAKey; exports.validateRSAKeyPair = rsaKeyCalculator.validateRSAKeyPair; exports.commonPassword = patterns.commonPassword; exports.contexts = patterns.contexts; exports.detectContextInjection = patterns.detectContextInjection; exports.detectSQLInjection = patterns.detectSQLInjection; exports.detectXSS = patterns.detectXSS; exports.hasKeyboardPattern = patterns.hasKeyboardPattern; exports.isCommonPassword = patterns.isCommonPassword; exports.keyboardPatterns = patterns.keyboardPatterns; exports.sqlPatterns = patterns.sqlPatterns; exports.xssPatterns = patterns.xssPatterns; exports.detectInjection = detectInjection.detectInjection; exports.createFortifiedFunction = index.createFortifiedFunction; exports.func = index.func; exports.CACHE_BUILD_DATE = index$2.CACHE_BUILD_DATE; exports.CACHE_VERSION = index$2.CACHE_VERSION; exports.Cache = index$2.Cache; exports.SCC = index$2.SecureCacheClient; exports.SecureCacheClient = index$2.SecureCacheClient; exports.cleanupFileCache = index$2.cleanupFileCache; exports.clearAllCache = index$2.clearAllCache; exports.clearFileCache = index$2.clearFileCache; exports.createOptimalCache = index$2.createOptimalCache; exports.defaultFileCache = index$2.defaultFileCache; exports.deleteFileCache = index$2.deleteFileCache; exports.expireCache = index$2.expireCache; exports.filepath = index$2.filepath; exports.generateFilePath = index$2.generateFilePath; exports.getCacheStats = index$2.getCacheStats; exports.getFileCacheStats = index$2.getFileCacheStats; exports.hasFileCache = index$2.hasFileCache; exports.readCache = index$2.readCache; exports.readFileCache = index$2.readFileCache; exports.removeFileCache = index$2.removeFileCache; exports.writeCache = index$2.writeCache; exports.writeFileCache = index$2.writeFileCache; exports.UFSMiddleware = ServerFactory.UFSMiddleware; exports.createCacheMiddleware = ServerFactory.createCacheMiddleware; exports.createServer = ServerFactory.createServer; exports.createServerInstance = ServerFactory.createServerInstance; exports.PasswordManager = passwordCore.PasswordManager; exports.SecureString = secureStringCore.SecureString; exports.SecureArray = secureArrayCore.SecureArray; exports.FortifiedFunction = fortifiedFunction.FortifiedFunction; exports.SecureObject = secureObjectCore.SecureObject; exports.DEFAULT_SENSITIVE_KEYS = sensitiveKeys.DEFAULT_SENSITIVE_KEYS; exports.SensitiveKeysManager = sensitiveKeys.SensitiveKeysManager; exports.CryptoHandler = cryptoHandler.CryptoHandler; exports.MetadataManager = metadataManager.MetadataManager; exports.EventManager = eventManager.EventManager; exports.SerializationHandler = serializationHandler.SerializationHandler; exports.IdGenerator = idGenerator.IdGenerator; exports.ValidationUtils = validation.ValidationUtils; exports.DEFAULT_CACHE_CONFIG = cache_config.CONFIG; exports.DEFAULT_FILE_CACHE_CONFIG = cache_config.DEFAULT_FILE_CACHE_CONFIG; exports.SecureInMemoryCache = useCache.SecureInMemoryCache; exports.UltraFastSecureInMemoryCache = UFSIMC.UltraFastSecureInMemoryCache; exports.FileCache = cacheSys.FileCache; exports.createCircularRefDebugger = safeJsonMiddleware.createCircularRefDebugger; exports.createSafeJsonMiddleware = safeJsonMiddleware.createSafeJsonMiddleware; exports.safeJsonStringify = safeJsonMiddleware.safeJsonStringify; exports.sendSafeJson = safeJsonMiddleware.sendSafeJson; exports.setupSafeJson = safeJsonMiddleware.setupSafeJson; exports.expressStringify = safeSerializer.expressStringify; exports.fastStringify = safeSerializer.fastStringify; exports.safeStringify = safeSerializer.safeStringify; Object.defineProperty(exports, 'Router', { enumerable: true, get: function () { return express.Router; } }); exports.createSecureCipheriv = createSecureCipheriv; exports.createSecureDecipheriv = createSecureDecipheriv; exports.createSecureHMAC = createSecureHMAC; exports.createSecureHash = createSecureHash; exports.encryptSecurePass = encryptSecurePass; exports.fArray = fArray; exports.fObject = fObject; exports.fString = fString; exports.generateSecureIV = generateSecureIV; exports.generateSecureIVBatch = generateSecureIVBatch; exports.generateSecureIVBatchForAlgorithm = generateSecureIVBatchForAlgorithm; exports.generateSecureIVForAlgorithm = generateSecureIVForAlgorithm; exports.generateSecureUUID = generateSecureUUID; exports.generateSessionToken = generateSessionToken; exports.getRandomBytes = getRandomBytes; exports.pm = pm; exports.validateIV = validateIV; exports.verifyEncryptedPassword = verifyEncryptedPassword; exports.verifyHash = verifyHash; //# sourceMappingURL=index.js.map