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

296 lines (292 loc) 10.8 kB
'use strict'; var randomCore = require('../random/random-core.js'); require('../random/random-types.js'); require('crypto'); require('../random/random-sources.js'); require('nehonix-uri-processor'); require('../../utils/memory/index.js'); require('../../types.js'); require('../random/random-security.js'); require('../hash/hash-core.js'); require('../hash/hash-types.js'); require('../hash/hash-security.js'); require('../hash/hash-advanced.js'); require('../../algorithms/hash-algorithms.js'); require('argon2'); require('child_process'); var secureMemory = require('../../components/secure-memory.js'); require('https'); require('../../components/runtime-verification.js'); require('../../components/tamper-evident-logging.js'); var passwordTypes = require('./password-types.js'); var passwordAlgorithms = require('./password-algorithms.js'); var passwordSecurity = require('./password-security.js'); var passwordMigration = require('./password-migration.js'); var passwordGenerator = require('./password-generator.js'); var passwordUtils = require('./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: passwordTypes.PasswordAlgorithm.ARGON2ID, defaultSecurityLevel: passwordTypes.PasswordSecurityLevel.HIGH, timingSafeVerification: true, secureMemoryWipe: true, enableMigration: true, ...config, }; // Initialize modular components this.algorithms = new passwordAlgorithms.PasswordAlgorithms(this.config); this.security = new passwordSecurity.PasswordSecurity(this.config); this.migration = new passwordMigration.PasswordMigration(this.config); this.generator = new passwordGenerator.PasswordGenerator(this.config); this.utils = new passwordUtils.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 = randomCore.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 !== passwordTypes.PasswordSecurityLevel.STANDARD) { return await this.utils.encryptPasswordHash(result, this.config.encryptionKey); } return result; } finally { // Secure cleanup if (opts.secureWipe) { secureMemory.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: passwordTypes.PasswordSecurityLevel.STANDARD, algorithm: passwordTypes.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: passwordTypes.PasswordAlgorithm.ARGON2ID, securityLevel: passwordTypes.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 === passwordTypes.PasswordAlgorithm.PBKDF2_SHA512 && metadata.iterations < 100000) { return true; } // Check if security level is below current default if (metadata.securityLevel === passwordTypes.PasswordSecurityLevel.STANDARD && this.config.defaultSecurityLevel !== passwordTypes.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 === passwordTypes.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)); } } exports.PasswordManager = PasswordManager; //# sourceMappingURL=password-core.js.map