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.
357 lines (354 loc) • 18.8 kB
JavaScript
import { FortifyJS } from './core/crypto.js';
import * as index$1 from './security/secure-string/index.js';
import { createSecureString } from './security/secure-string/index.js';
import * as index$2 from './security/secure-object/index.js';
import { createSecureObject } from './security/secure-object/index.js';
export { MODULE_INFO, SECURE_OBJECT_VERSION, cloneSecureObject, createReadOnlySecureObject, createSecureObjectWithSensitiveKeys } from './security/secure-object/index.js';
import * as index$3 from './security/secure-array/index.js';
import { createSecureArray } from './security/secure-array/index.js';
import { func, createFortifiedFunction } from './utils/fortified-function/index.js';
import * as index$4 from './security/cache/index.js';
export { CACHE_BUILD_DATE, CACHE_VERSION, Cache, cleanupFileCache, clearAllCache, clearFileCache, createOptimalCache, defaultFileCache, deleteFileCache, expireCache, filepath, generateFilePath, getCacheStats, getFileCacheStats, hasFileCache, readCache, readFileCache, removeFileCache, writeCache, writeFileCache } from './security/cache/index.js';
import * as ServerFactory from './integrations/express/ServerFactory.js';
export { UFSMiddleware, createCacheMiddleware, createServer, createServerInstance } from './integrations/express/ServerFactory.js';
import { 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';
import { EnhancedUint8Array } from './helpers/Uint8Array.js';
import { RandomTokens } from './core/random/random-tokens.js';
import { RandomCrypto } from './core/random/random-crypto.js';
import { Keys } from './core/keys.js';
import { Validators } from './core/validators.js';
import * as index from './security/index.js';
import { Hash } from './core/hash/hash-core.js';
import './core/hash/hash-types.js';
import * as encoding from './utils/encoding.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 'argon2';
import './algorithms/hash-algorithms.js';
import './core/password/index.js';
export { assessRSASecurity, benchmarkRSAPerformance, calculateRSAKeySize, generateProtectedRSAKeyPairForData, generateRSAKeyPairForData, getEncryptionSuggestion, getMaxDataSizeForRSAKey, getRSARecommendations, testRSAWithDataSize, validateDataSizeForRSAKey, validateRSAKeyPair } from './generators/rsaKeyCalculator.js';
export { contexts, sqlPatterns, xssPatterns } from './utils/patterns.js';
export { detectInjection } from './utils/detectInjection.js';
import { PasswordManager } from './core/password/password-core.js';
import { SecureString } from './security/secure-string/core/secure-string-core.js';
import { SecureObject } from './security/secure-object/core/secure-object-core.js';
import { SecureArray } from './security/secure-array/core/secure-array-core.js';
import { SecureBuffer } from './security/secure-memory.js';
export { secureWipe } from './security/secure-memory.js';
import { FortifiedFunction } from './utils/fortified-function/fortified-function.js';
export { cacheHarden, constantTimeEqual, faultResistantEqual, maskedAccess, randomDelay, secureModPow } from './security/side-channel.js';
export { argon2Derive, balloonDerive } from './security/memory-hard.js';
export { generateKyberKeyPair, kyberDecapsulate, kyberEncapsulate, lamportGenerateKeypair, lamportSign, lamportVerify, ringLweDecrypt, ringLweEncrypt, ringLweGenerateKeypair } from './security/post-quantum.js';
export { EntropyPool } from './security/entropy-augmentation.js';
export { createCanary, createCanaryFunction, createCanaryObject, triggerCanary } from './security/canary-tokens.js';
export { createAttestation, createLibraryAttestation, generateAttestationKey, verifyAttestation, verifyLibraryAttestation } from './security/attestation.js';
export { SecurityIssueType, verifyRuntimeSecurity } from './security/runtime-verification.js';
export { secureDeserialize, secureSerialize } from './security/secure-serialization.js';
export { LogLevel, TamperEvidentLogger } from './security/tamper-evident-logging.js';
export { DEFAULT_SENSITIVE_KEYS, SensitiveKeysManager } from './security/secure-object/encryption/sensitive-keys.js';
export { CryptoHandler } from './security/secure-object/encryption/crypto-handler.js';
export { MetadataManager } from './security/secure-object/metadata/metadata-manager.js';
export { EventManager } from './security/secure-object/events/event-manager.js';
export { SerializationHandler } from './security/secure-object/serialization/serialization-handler.js';
export { IdGenerator } from './security/secure-object/utils/id-generator.js';
export { ValidationUtils } from './security/secure-object/utils/validation.js';
export { CONFIG as DEFAULT_CACHE_CONFIG, DEFAULT_FILE_CACHE_CONFIG } from './security/cache/config/cache.config.js';
export { SecureInMemoryCache } from './security/cache/useCache.js';
export { UltraFastSecureInMemoryCache } from './security/cache/UFSIMC.js';
export { FileCache } from './security/cache/cacheSys.js';
/***************************************************************************
* 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 Main Module
*
* This is the main entry point for the FortifyJS library. It provides
* access to all the core and advanced security features of the library.
*
* FortifyJS is designed to be a comprehensive cryptographic security library
* that provides secure token generation, advanced hashing, key derivation,
* password utilities, and more.
*
* It is built with TypeScript and designed for maximum security, performance,
* and developer experience.
*
* @NEHONIX
* @augments FortifyJS
* @exports Fortify
* @author Nehonix
* @see https://lab.nehonix.space
* @name FortifyJS
* @example
* ```typescript
* import { FortifyJS } from "fortify-js";
*
* // Generate a secure token
* const token = FortifyJS.generateSecureToken({
* length: 32,
* entropy: "maximum",
* });
* console.log(token);
* // Output: "aK7mN9pQ2rS8tU3vW6xY1zB4cD5eF7gH"
* ```
*/
// Crypto compatibility exports for easy migration from crypto module
// Export individual methods to ensure they're available
const createSecureCipheriv = RandomCrypto.createSecureCipheriv;
const createSecureDecipheriv = RandomCrypto.createSecureDecipheriv;
const generateSecureIV = RandomCrypto.generateSecureIV;
const generateSecureIVBatch = RandomCrypto.generateSecureIVBatch;
const generateSecureIVForAlgorithm = RandomCrypto.generateSecureIVForAlgorithm;
const generateSecureIVBatchForAlgorithm = RandomCrypto.generateSecureIVBatchForAlgorithm;
const validateIV = RandomCrypto.validateIV;
const getRandomBytes = SecureRandom.getRandomBytes;
const generateSessionToken = RandomTokens.generateSessionToken;
const generateSecureUUID = SecureRandom.generateSecureUUID;
// Hash methods from Hash class
const createSecureHash = Hash.createSecureHash;
const createSecureHMAC = Hash.createSecureHMAC;
const verifyHash = Hash.verifyHash;
// alias for password manager (useful for legacy code)
/**
* Fast password manager access but use default configuration
* for custom config, use PasswordManager.create() or PasswordManager.getInstance()
*/
const pm = PasswordManager.getInstance();
/**
* @author iDevo
* @description Creates a secure string that can be explicitly cleared from memory
* @param str - The string to be converted to a secure string
* @returns A new SecureString instance
*/
function fString(...args) {
return createSecureString(...args);
}
/**
* @author iDevo
* @description Creates a secure object that can be explicitly cleared from memory
* @param initialData - The initial data to be stored in the secure object
* @returns A new SecureObject instance
*/
function fObject(...args) {
return createSecureObject(...args);
}
/**
* @author Nehonix
* @description Creates a secure array that can store sensitive data with enhanced security features
* @param initialData - The initial data to be stored in the secure array
* @returns A new SecureArray instance
*/
function fArray(...args) {
return createSecureArray(...args);
}
/**
* Encrypt a password with pepper and military-grade hashing
*
* This function provides an additional layer of security by applying a pepper (secret)
* before hashing the password with Argon2ID. This protects against rainbow table attacks
* even if the database is compromised.
*
* @author suppercodercodelover
* @param password - The plain text password to encrypt
* @param PEPPER - A secret pepper value (should be stored securely, not in database)
* @returns Promise<string> - The peppered and hashed password ready for database storage
* @throws Error if PEPPER is not provided
*
* @example
* ```typescript
* // Create pepper using Random
* console.log("PASSWORD_PEPPER: ", Random.getRandomBytes(16)) // replace "16" with desired length then store securely (example in a .env file)
* const pepper = process.env.PASSWORD_PEPPER; // Store securely!
* const hashedPassword = await encryptSecurePass("userPassword123", pepper);
* // Store hashedPassword in database
* ```
*
* @security
* - Uses HMAC-SHA256 for pepper application
* - Uses Argon2ID for final password hashing
* - Timing-safe operations prevent side-channel attacks
*/
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)
return await pm.hash(peppered, options);
}
/**
* Verify a password against a peppered hash with timing-safe comparison
*
* This function verifies a plain text password against a hash that was created
* using encryptSecurePass(). It applies the same pepper and uses constant-time
* verification to prevent timing attacks.
*
* @author suppercodercodelover
* @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
*
* @example
* ```typescript
* const pepper = process.env.PASSWORD_PEPPER; // Same pepper as encryption
* const isValid = await verifyEncryptedPassword(
* "userPassword123",
* storedHashFromDB,
* pepper
* );
*
* if (isValid) {
* console.log("Login successful!");
* } else {
* console.log("Invalid credentials");
* }
* ```
*
* @security
* - Uses timing-safe verification (constant-time comparison)
* - Applies same HMAC-SHA256 pepper as encryption
* - Resistant to timing attacks and side-channel analysis
* - Returns boolean only (no additional timing information leaked)
*/
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 result = await pm.verify(peppered, hashedPassword);
return result.isValid;
}
// For CommonJS compatibility
if (typeof module !== "undefined" && module.exports) {
//default
module.exports.default = FortifyJS;
//
module.exports = FortifyJS;
module.exports.FortifyJS = FortifyJS;
module.exports.ftfy = FortifyJS;
module.exports.Fortify = FortifyJS;
module.exports.pm = pm;
// Export SecureRandom class and methods
module.exports.SecureRandom = SecureRandom;
module.exports.Random = SecureRandom;
// Export individual methods for direct access (using correct classes)
module.exports.createSecureCipheriv = RandomCrypto.createSecureCipheriv;
module.exports.createSecureDecipheriv = RandomCrypto.createSecureDecipheriv;
module.exports.generateSecureIV = RandomCrypto.generateSecureIV;
module.exports.generateSecureIVBatch = RandomCrypto.generateSecureIVBatch;
module.exports.generateSecureIVForAlgorithm =
RandomCrypto.generateSecureIVForAlgorithm;
module.exports.generateSecureIVBatchForAlgorithm =
RandomCrypto.generateSecureIVBatchForAlgorithm;
module.exports.validateIV = RandomCrypto.validateIV;
module.exports.getRandomBytes = SecureRandom.getRandomBytes;
module.exports.generateSessionToken = RandomTokens.generateSessionToken;
module.exports.generateSecureUUID = SecureRandom.generateSecureUUID;
// Export Hash methods (consolidated from SecureRandom)
module.exports.createSecureHash = Hash.createSecureHash;
module.exports.createSecureHMAC = Hash.createSecureHMAC;
module.exports.verifyHash = Hash.verifyHash;
// Export other core classes
module.exports.Hash = Hash;
module.exports.Keys = Keys;
module.exports.Validators = Validators;
module.exports.SecureBuffer = SecureBuffer;
module.exports.Buffer = SecureBuffer;
module.exports.EnhancedUint8Array = EnhancedUint8Array;
// Export Password Management System
module.exports.PasswordManager = PasswordManager;
// Export Password Management Types and Enums (using imported modules)
module.exports.PasswordAlgorithm = PasswordAlgorithm;
module.exports.PasswordSecurityLevel = PasswordSecurityLevel;
// Export new password utility functions
module.exports.encryptSecurePass = encryptSecurePass;
module.exports.verifyEncryptedPassword = verifyEncryptedPassword;
// ===================== safe (String and Object) ====================
// Export String, Object, Array, and Function utilities
module.exports.fString = fString;
module.exports.fObject = fObject;
module.exports.fArray = fArray;
module.exports.func = func;
// Export fortified function utilities (using imported modules)
module.exports.createFortifiedFunction = createFortifiedFunction;
module.exports.FortifiedFunction = FortifiedFunction;
// Export Security Features (using imported modules)
globalThis.Object.keys(index).forEach((key) => {
if (key !== "default") {
module.exports[key] = index[key];
}
});
// Export Security Features (using imported modules)
globalThis.Object.keys(index$1).forEach((key) => {
if (key !== "default") {
module.exports[key] = index$1[key];
}
});
globalThis.Object.keys(index$2).forEach((key) => {
if (key !== "default") {
module.exports[key] = index$2[key];
}
});
globalThis.Object.keys(index$3).forEach((key) => {
if (key !== "default") {
module.exports[key] = index$3[key];
}
});
// Export Utils/Encoding (using imported modules)
globalThis.Object.keys(encoding).forEach((key) => {
if (key !== "default") {
module.exports[key] = encoding[key];
}
});
// Export SecureString, SecureObject, and SecureArray classes
module.exports.SecureString = SecureString;
module.exports.SecureObject = SecureObject;
module.exports.SecureArray = SecureArray;
// ======================= v4.x.y =================
// Cache system
globalThis.Object.keys(index$4).forEach((key) => {
if (key !== "default") {
module.exports[key] = index$4[key];
}
});
globalThis.Object.keys(ServerFactory).forEach((key) => {
if (key !== "default") {
module.exports[key] = ServerFactory[key];
}
});
}
export { SecureBuffer as Buffer, EnhancedUint8Array, FortifiedFunction, FortifyJS as Fortify, Hash, Keys, PasswordAlgorithm, PasswordManager, PasswordSecurityLevel, SecureRandom as Random, SecureArray, SecureBuffer, SecureObject, SecureString, Validators, createFortifiedFunction, createSecureCipheriv, createSecureDecipheriv, createSecureHMAC, createSecureHash, createSecureObject, encryptSecurePass, fArray, fObject, fString, FortifyJS as ftfy, func, generateSecureIV, generateSecureIVBatch, generateSecureIVBatchForAlgorithm, generateSecureIVForAlgorithm, generateSecureUUID, generateSessionToken, getRandomBytes, pm, validateIV, verifyEncryptedPassword, verifyHash };
//# sourceMappingURL=index.js.map