UNPKG

xypriss-security

Version:

XyPriss Security is an advanced JavaScript security library designed for enterprise applications. It provides military-grade encryption, secure data structures, quantum-resistant cryptography, and comprehensive security utilities for modern web applicatio

294 lines (291 loc) 10.5 kB
import { SecureRandom } from '../random/random-core.js'; import '../random/random-types.js'; import 'crypto'; import '../random/random-sources.js'; import 'nehonix-uri-processor'; import '../../utils/memory/index.js'; import '../../types.js'; import '../random/random-security.js'; import '../hash/hash-core.js'; import '../hash/hash-types.js'; import '../hash/hash-security.js'; import '../hash/hash-advanced.js'; import '../../algorithms/hash-algorithms.js'; import 'argon2'; import 'child_process'; import { secureWipe } from '../../components/secure-memory.js'; import 'https'; import '../../components/runtime-verification.js'; import '../../components/tamper-evident-logging.js'; import { PasswordAlgorithm, PasswordSecurityLevel } from './password-types.js'; import { PasswordAlgorithms } from './password-algorithms.js'; import { PasswordSecurity } from './password-security.js'; import { PasswordMigration } from './password-migration.js'; import { PasswordGenerator } from './password-generator.js'; import { PasswordUtils } from './password-utils.js'; /** * PasswordManager - Core Password Management Class * * A modular, military-grade password management system * Short name: PasswordManager (instead of SecurePasswordManager) */ /** * @author Supper Coder * PasswordManager * * Main class for secure password management with modular architecture */ class PasswordManager { constructor(config) { this.config = { defaultAlgorithm: PasswordAlgorithm.ARGON2ID, defaultSecurityLevel: PasswordSecurityLevel.HIGH, timingSafeVerification: true, secureMemoryWipe: true, enableMigration: true, ...config, }; // Initialize modular components this.algorithms = new PasswordAlgorithms(this.config); this.security = new PasswordSecurity(this.config); this.migration = new PasswordMigration(this.config); this.generator = new PasswordGenerator(this.config); this.utils = new PasswordUtils(this.config); } /** * Get singleton instance */ static getInstance(config) { if (!PasswordManager.instance) { PasswordManager.instance = new PasswordManager(config); } return PasswordManager.instance; } /** * Create a new instance (for multiple configurations) */ static create(config) { return new PasswordManager(config); } /** * Hash a password with advanced security */ async hash(password, options = {}) { // Input validation if (!password || password.length === 0) { throw new Error("Password cannot be empty"); } const opts = this.mergeOptions(options); try { // Apply pepper if configured const processedPassword = this.applyPepper(password); // Generate salt const salt = SecureRandom.generateSalt(opts.saltLength); // Hash using selected algorithm const hash = await this.algorithms.hash(processedPassword, salt, opts); // Create metadata const metadata = this.createMetadata(opts); // Combine hash with metadata const result = this.utils.combineHashWithMetadata(hash, salt, metadata); // Encrypt if encryption key is available if (this.config.encryptionKey && opts.securityLevel !== PasswordSecurityLevel.STANDARD) { return await this.utils.encryptPasswordHash(result, this.config.encryptionKey); } return result; } finally { // Secure cleanup if (opts.secureWipe) { secureWipe(Buffer.from(password)); } } } /** * Verify a password against a hash */ async verify(password, hash) { const startTime = Date.now(); try { // Decrypt hash if needed let actualHash = hash; if (this.config.encryptionKey && this.utils.isEncryptedHash(hash)) { actualHash = await this.utils.decryptPasswordHash(hash, this.config.encryptionKey); } // Parse metadata const { hash: extractedHash, salt, metadata, } = this.utils.parseHashWithMetadata(actualHash); // Apply pepper if configured const processedPassword = this.applyPepper(password); // Verify using the same algorithm const isValid = await this.algorithms.verify(processedPassword, extractedHash, salt, metadata); const timeTaken = Date.now() - startTime; // Check if rehashing is needed const needsRehash = this.shouldRehash(metadata); // Generate recommendations const recommendations = this.generateRecommendations(metadata, timeTaken); return { isValid, needsRehash, securityLevel: metadata.securityLevel, algorithm: metadata.algorithm, timeTaken, recommendations, }; } catch (error) { // Timing-safe error handling if (this.config.timingSafeVerification) { await this.constantTimeDelay(); } return { isValid: false, securityLevel: PasswordSecurityLevel.STANDARD, algorithm: PasswordAlgorithm.PBKDF2_SHA512, timeTaken: Date.now() - startTime, recommendations: ["Password verification failed"], }; } } /** * Generate a secure password */ generatePassword(options = {}) { return this.generator.generate(options); } /** * Analyze password strength */ analyzeStrength(password) { return this.security.analyzeStrength(password); } /** * Migrate from bcrypt or other systems */ async migrate(password, oldHash, options = {}) { return this.migration.fromBcrypt(password, oldHash, options); } /** * Validate password against policy */ validatePolicy(password) { return this.security.validatePolicy(password); } /** * Rehash password with updated security */ async rehash(password, oldHash, newOptions = {}) { // First verify the old password const verification = await this.verify(password, oldHash); if (!verification.isValid) { return { newHash: oldHash, upgraded: false }; } // Create new hash with enhanced options const enhancedOptions = { ...this.config, algorithm: PasswordAlgorithm.ARGON2ID, securityLevel: PasswordSecurityLevel.MAXIMUM, ...newOptions, }; const newHash = await this.hash(password, enhancedOptions); return { newHash, upgraded: true }; } /** * Audit password security */ async auditSecurity(hashes) { return this.security.auditPasswords(hashes); } /** * Configure global settings */ configure(config) { this.config = { ...this.config, ...config }; // Update modular components this.algorithms.updateConfig(this.config); this.security.updateConfig(this.config); this.migration.updateConfig(this.config); this.generator.updateConfig(this.config); this.utils.updateConfig(this.config); } /** * Get current configuration */ getConfig() { return { ...this.config }; } // ===== PRIVATE HELPER METHODS ===== mergeOptions(options) { return { algorithm: this.config.defaultAlgorithm, securityLevel: this.config.defaultSecurityLevel, iterations: 100000, memorySize: 65536, // 64MB parallelism: 4, saltLength: 32, quantumResistant: false, timingSafe: this.config.timingSafeVerification, secureWipe: this.config.secureMemoryWipe, ...options, }; } applyPepper(password) { return this.config.globalPepper ? password + this.config.globalPepper : password; } createMetadata(options) { return { algorithm: options.algorithm, securityLevel: options.securityLevel, iterations: options.iterations, memorySize: options.memorySize, parallelism: options.parallelism, saltLength: options.saltLength, hasEncryption: !!this.config.encryptionKey, hasPepper: !!this.config.globalPepper, timestamp: Date.now(), version: "2.0.0", }; } shouldRehash(metadata) { // Check if algorithm is outdated if (metadata.algorithm === PasswordAlgorithm.PBKDF2_SHA512 && metadata.iterations < 100000) { return true; } // Check if security level is below current default if (metadata.securityLevel === PasswordSecurityLevel.STANDARD && this.config.defaultSecurityLevel !== PasswordSecurityLevel.STANDARD) { return true; } // Check age (if policy specifies max age) if (this.config.policy?.maxAge) { const ageInDays = (Date.now() - metadata.timestamp) / (1000 * 60 * 60 * 24); if (ageInDays > this.config.policy.maxAge) { return true; } } return false; } generateRecommendations(metadata, timeTaken) { const recommendations = []; if (this.shouldRehash(metadata)) { recommendations.push("Consider upgrading password hash"); } if (timeTaken > 1000) { recommendations.push("Verification time is high, consider optimizing"); } if (!metadata.hasEncryption && metadata.securityLevel === PasswordSecurityLevel.MILITARY) { recommendations.push("Consider enabling encryption for military-grade security"); } return recommendations; } async constantTimeDelay() { // Add a small random delay to prevent timing attacks const delay = 50 + Math.floor(Math.random() * 100); await new Promise((resolve) => setTimeout(resolve, delay)); } } export { PasswordManager }; //# sourceMappingURL=password-core.js.map