xypriss-security 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,894 @@
1
+ export { XyPrissSecurity as XyPriss, XyPrissSecurity as ftfy } from './core/crypto.js';
2
+ import { createSecureObject } from './components/secure-object/index.js';
3
+ export { MODULE_INFO, SECURE_OBJECT_VERSION, cloneSecureObject, createReadOnlySecureObject, createSecureObjectWithSensitiveKeys } from './components/secure-object/index.js';
4
+ import { createSecureString } from './components/secure-string/index.js';
5
+ import { createSecureArray } from './components/secure-array/index.js';
6
+ export { PasswordAlgorithm, PasswordSecurityLevel } from './core/password/password-types.js';
7
+ export { EntropySource, HashAlgorithm, KeyDerivationAlgorithm, SecurityLevel, TokenType } from './types.js';
8
+ import { SecureRandom } from './core/random/random-core.js';
9
+ import './core/random/random-types.js';
10
+ import 'crypto';
11
+ import './core/random/random-sources.js';
12
+ export { EnhancedUint8Array } from './helpers/Uint8Array.js';
13
+ import { RandomTokens } from './core/random/random-tokens.js';
14
+ import { RandomCrypto } from './core/random/random-crypto.js';
15
+ import { Hash } from './core/hash/hash-core.js';
16
+ import './core/hash/hash-types.js';
17
+ 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';
18
+ import './core/hash/hash-security.js';
19
+ import './core/hash/hash-advanced.js';
20
+ import './algorithms/hash-algorithms.js';
21
+ export { Keys } from './core/keys.js';
22
+ export { Validators } from './core/validators.js';
23
+ import './core/password/index.js';
24
+ export { cacheHarden, constantTimeEqual, faultResistantEqual, maskedAccess, randomDelay, secureModPow } from './components/side-channel.js';
25
+ export { argon2Derive, balloonDerive } from './components/memory-hard.js';
26
+ export { generateKyberKeyPair, kyberDecapsulate, kyberEncapsulate, lamportGenerateKeypair, lamportSign, lamportVerify, ringLweDecrypt, ringLweEncrypt, ringLweGenerateKeypair } from './components/post-quantum.js';
27
+ export { SecureBuffer as Buffer, SecureBuffer, secureWipe } from './components/secure-memory.js';
28
+ export { EntropyPool } from './components/entropy-augmentation.js';
29
+ export { createCanary, createCanaryFunction, createCanaryObject, triggerCanary } from './components/canary-tokens.js';
30
+ export { createAttestation, createLibraryAttestation, generateAttestationKey, verifyAttestation, verifyLibraryAttestation } from './components/attestation.js';
31
+ export { SecurityIssueType, verifyRuntimeSecurity } from './components/runtime-verification.js';
32
+ export { secureDeserialize, secureSerialize } from './components/secure-serialization.js';
33
+ export { LogLevel, TamperEvidentLogger } from './components/tamper-evident-logging.js';
34
+ export { assessRSASecurity, benchmarkRSAPerformance, calculateRSAKeySize, generateProtectedRSAKeyPairForData, generateRSAKeyPairForData, getEncryptionSuggestion, getMaxDataSizeForRSAKey, getRSARecommendations, testRSAWithDataSize, validateDataSizeForRSAKey, validateRSAKeyPair } from './generators/rsaKeyCalculator.js';
35
+ export { commonPassword, contexts, detectContextInjection, detectSQLInjection, detectXSS, hasKeyboardPattern, isCommonPassword, keyboardPatterns, sqlPatterns, xssPatterns } from './utils/patterns.js';
36
+ export { detectInjection } from './utils/detectInjection.js';
37
+ export { createFortifiedFunction, func } from './components/fortified-function/index.js';
38
+ import { PasswordManager } from './core/password/password-core.js';
39
+ export { SecureString } from './components/secure-string/core/secure-string-core.js';
40
+ export { SecureArray } from './components/secure-array/core/secure-array-core.js';
41
+ export { FortifiedFunction } from './components/fortified-function/fortified-function.js';
42
+ export { SecureObject } from './components/secure-object/core/secure-object-core.js';
43
+ export { DEFAULT_SENSITIVE_KEYS, SensitiveKeysManager } from './components/secure-object/encryption/sensitive-keys.js';
44
+ export { CryptoHandler } from './components/secure-object/encryption/crypto-handler.js';
45
+ export { MetadataManager } from './components/secure-object/metadata/metadata-manager.js';
46
+ export { EventManager } from './components/secure-object/events/event-manager.js';
47
+ export { SerializationHandler } from './components/secure-object/serialization/serialization-handler.js';
48
+ export { IdGenerator } from './components/secure-object/utils/id-generator.js';
49
+ export { ValidationUtils } from './components/secure-object/utils/validation.js';
50
+
51
+ /***************************************************************************
52
+ * XyPrissSecurity - Ex xypriss2-js is an Advanced JavaScript Security Library designed for XyPriss
53
+ *
54
+ * This file contains the main entry point for the XyPrissSecurity library.
55
+ *
56
+ * @author Nehonix
57
+ * @license MIT
58
+ *
59
+ * Copyright (c) 2025 Nehonix. All rights reserved.
60
+ *
61
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
62
+ * of this software and associated documentation files (the "Software"), to deal
63
+ * in the Software without restriction, including without limitation the rights
64
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
65
+ * copies of the Software, and to permit persons to whom the Software is
66
+ * furnished to do so, subject to the following conditions:
67
+ *
68
+ * The above copyright notice and this permission notice shall be included in all
69
+ * copies or substantial portions of the Software.
70
+ *
71
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
72
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
73
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
74
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
75
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
76
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
77
+ * SOFTWARE.
78
+ ***************************************************************************** */
79
+ /**
80
+ * # XyPrissSecurity - Advanced JavaScript Security Library
81
+ *
82
+ * **The most comprehensive cryptographic security library for JavaScript applications**
83
+ *
84
+ * XyPrissSecurity provides enterprise-grade security features including military-grade encryption,
85
+ * secure data structures, advanced password management, and real-time security monitoring.
86
+ * Built with TypeScript for maximum type safety and developer experience.
87
+ *
88
+ * ## Core Features
89
+ *
90
+ * ### Secure Data Structures
91
+ * - **SecureArray**: Military-grade encrypted arrays with AES-256-CTR-HMAC
92
+ * - **SecureString**: Protected string handling with automatic memory cleanup
93
+ * - **SecureObject**: Encrypted object storage with metadata management
94
+ * - **SecureBuffer**: Protected memory allocation with secure wiping
95
+ *
96
+ * ### Cryptographic Operations
97
+ * - **Token Generation**: Secure random tokens with configurable entropy
98
+ * - **Password Management**: Argon2ID hashing with pepper support
99
+ * - **Hash Functions**: SHA-256/512, BLAKE3, with timing-safe operations
100
+ * - **Key Derivation**: PBKDF2, Argon2, scrypt with memory-hard algorithms
101
+ *
102
+ * ### Performance & Security
103
+ * - **FortifiedFunction**: Ultra-fast function execution with security monitoring
104
+ * - **Cache System**: High-performance caching with encryption support
105
+ * - **Memory Management**: Automatic cleanup and leak detection
106
+ * - **Side-Channel Protection**: Constant-time operations and fault resistance
107
+ *
108
+ * ### Advanced Security
109
+ * - **Post-Quantum Cryptography**: Lamport signatures and Ring-LWE
110
+ * - **Canary Tokens**: Intrusion detection and monitoring
111
+ * - **Attestation**: Code integrity verification
112
+ * - **Entropy Augmentation**: Enhanced randomness sources
113
+ *
114
+ * ## Quick Start Examples
115
+ *
116
+ * ### Basic Token Generation
117
+ * ```typescript
118
+ * import { XyPrissSecurity, generateSecureToken } from "xypriss-security";
119
+ *
120
+ * // Generate a secure API key
121
+ * const apiKey = XyPrissSecurity.generateSecureToken({
122
+ * length: 32,
123
+ * entropy: "maximum",
124
+ * includeSymbols: false
125
+ * });
126
+ * console.log(apiKey); // "aK7mN9pQ2rS8tU3vW6xY1zB4cD5eF7gH"
127
+ *
128
+ * // Quick token generation
129
+ * const sessionToken = generateSecureToken(64, "base64url");
130
+ * ```
131
+ *
132
+ * ### Secure Data Structures
133
+ * ```typescript
134
+ * import { fArray, fString, fObject } from "xypriss-security";
135
+ *
136
+ * // Secure array with encryption
137
+ * const sensitiveData = fArray(["api-key-1", "secret-token", "user-data"]);
138
+ * sensitiveData.setEncryptionKey("your-encryption-key-2025");
139
+ * sensitiveData.encryptAll();
140
+ *
141
+ * // Secure string with automatic cleanup
142
+ * const password = fString("user-password-123", {
143
+ * protectionLevel: "maximum",
144
+ * enableEncryption: true
145
+ * });
146
+ *
147
+ * // Secure object with metadata
148
+ * const userCredentials = fObject({
149
+ * username: "john_doe",
150
+ * apiKey: "secret-key-value"
151
+ * });
152
+ * ```
153
+ *
154
+ * ### Password Management
155
+ * ```typescript
156
+ * import { PasswordManager, encryptSecurePass, verifyEncryptedPassword } from "xypriss-security";
157
+ *
158
+ * // Advanced password hashing with pepper
159
+ * const pepper = process.env.PASSWORD_PEPPER;
160
+ * const hashedPassword = await encryptSecurePass("userPassword123", pepper);
161
+ *
162
+ * // Verify password with timing-safe comparison
163
+ * const isValid = await verifyEncryptedPassword("userPassword123", hashedPassword, pepper);
164
+ *
165
+ * // Password manager with custom configuration
166
+ * const pm = PasswordManager.create({
167
+ * algorithm: "argon2id",
168
+ * memoryCost: 65536,
169
+ * timeCost: 3
170
+ * });
171
+ * ```
172
+ *
173
+ * ### High-Performance Functions
174
+ * ```typescript
175
+ * import { func, createFortifiedFunction } from "xypriss-security";
176
+ *
177
+ * // Ultra-fast function with security monitoring
178
+ * const optimizedFunction = func(async (data: string) => {
179
+ * return data.toUpperCase();
180
+ * }, {
181
+ * ultraFast: "maximum",
182
+ * smartCaching: true,
183
+ * autoEncrypt: true
184
+ * });
185
+ *
186
+ * const result = await optimizedFunction.execute("hello world");
187
+ * const analytics = optimizedFunction.getAnalyticsData();
188
+ * ```
189
+ *
190
+ * ## Security Best Practices
191
+ *
192
+ * 1. **Always use environment variables for sensitive keys**
193
+ * 2. **Enable encryption for sensitive data structures**
194
+ * 3. **Use timing-safe operations for authentication**
195
+ * 4. **Implement proper memory cleanup with destroy() methods**
196
+ * 5. **Monitor security status with built-in analytics**
197
+ *
198
+ * @author Nehonix
199
+ * @version 4.2.0
200
+ * @license MIT
201
+ * @see {@link https://lab.nehonix.space/nehonix_viewer/_doc/Nehonix%20XyPrissSecurity} Official Documentation
202
+ * @see {@link https://github.com/Nehonix-Team/XyPriss} GitHub Repository
203
+ * @see {@link https://nodejs.org/api/crypto.html} Node.js Crypto Module
204
+ * @see {@link https://github.com/ranisalt/node-argon2} Argon2 Implementation
205
+ * @see {@link https://github.com/paulmillr/noble-hashes} Noble Hashes Library
206
+ * @see {@link https://libsodium.gitbook.io/doc/} Libsodium Documentation
207
+ * @see {@link https://github.com/jedisct1/libsodium.js} Libsodium.js
208
+ * @see {@link https://www.npmjs.com/package/bcryptjs} BCrypt.js Package
209
+ *
210
+ * @example
211
+ * ```typescript
212
+ * // Complete security setup example
213
+ * import { XyPrissSecurity, fArray, PasswordManager } from "xypriss-security";
214
+ *
215
+ * // 1. Generate secure tokens
216
+ * const apiKey = XyPrissSecurity.generateAPIKey(32, "api");
217
+ * const sessionToken = XyPrissSecurity.generateSessionToken();
218
+ *
219
+ * // 2. Secure data storage
220
+ * const userData = fArray([]);
221
+ * userData.setEncryptionKey(process.env.ENCRYPTION_KEY);
222
+ * userData.push("sensitive-user-data");
223
+ *
224
+ * // 3. Password management
225
+ * const pm = PasswordManager.getInstance();
226
+ * const hashedPassword = await pm.hash("userPassword");
227
+ *
228
+ * // 4. Security monitoring
229
+ * const stats = XyPrissSecurity.getStats();
230
+ * const securityStatus = XyPrissSecurity.verifyRuntimeSecurity();
231
+ *
232
+ * console.log("Security Status:", securityStatus.isSecure);
233
+ * console.log("Operations:", stats.totalOperations);
234
+ * ```
235
+ */
236
+ /**
237
+ * ## Crypto Compatibility Layer
238
+ *
239
+ * Direct function exports for easy migration from Node.js crypto module.
240
+ * These functions provide drop-in replacements with enhanced security features.
241
+ */
242
+ /**
243
+ * ### Secure Cipher Operations
244
+ *
245
+ * Enhanced cipher creation and management with automatic security hardening.
246
+ * Provides secure alternatives to Node.js crypto.createCipher functions.
247
+ *
248
+ * @example
249
+ * ```typescript
250
+ * import { createSecureCipheriv, createSecureDecipheriv, generateSecureIV } from "xypriss-security";
251
+ *
252
+ * // Create secure cipher with automatic IV generation
253
+ * const key = "your-encryption-key";
254
+ * const iv = generateSecureIV("aes-256-cbc");
255
+ * const cipher = createSecureCipheriv("aes-256-cbc", key, iv);
256
+ *
257
+ * // Encrypt data
258
+ * let encrypted = cipher.update("sensitive data", "utf8", "hex");
259
+ * encrypted += cipher.final("hex");
260
+ *
261
+ * // Decrypt data
262
+ * const decipher = createSecureDecipheriv("aes-256-cbc", key, iv);
263
+ * let decrypted = decipher.update(encrypted, "hex", "utf8");
264
+ * decrypted += decipher.final("utf8");
265
+ * ```
266
+ */
267
+ /** Create secure cipher with enhanced security features */
268
+ const createSecureCipheriv = RandomCrypto.createSecureCipheriv;
269
+ /** Create secure decipher with enhanced security features */
270
+ const createSecureDecipheriv = RandomCrypto.createSecureDecipheriv;
271
+ /** Generate cryptographically secure initialization vector */
272
+ const generateSecureIV = RandomCrypto.generateSecureIV;
273
+ /** Generate multiple secure IVs in batch for performance */
274
+ const generateSecureIVBatch = RandomCrypto.generateSecureIVBatch;
275
+ /** Generate secure IV for specific algorithm */
276
+ const generateSecureIVForAlgorithm = RandomCrypto.generateSecureIVForAlgorithm;
277
+ /** Generate multiple secure IVs for specific algorithm */
278
+ const generateSecureIVBatchForAlgorithm = RandomCrypto.generateSecureIVBatchForAlgorithm;
279
+ /** Validate initialization vector format and security */
280
+ const validateIV = RandomCrypto.validateIV;
281
+ /**
282
+ * ### Random Data Generation
283
+ *
284
+ * High-entropy random data generation for cryptographic operations.
285
+ *
286
+ * @example
287
+ * ```typescript
288
+ * import { getRandomBytes, generateSecureUUID } from "xypriss-security";
289
+ *
290
+ * // Generate random bytes
291
+ * const randomData = getRandomBytes(32);
292
+ *
293
+ * // Generate secure UUID
294
+ * const uuid = generateSecureUUID();
295
+ * ```
296
+ */
297
+ /** Generate cryptographically secure random bytes */
298
+ const getRandomBytes = SecureRandom.getRandomBytes;
299
+ /** Generate secure UUID with high entropy */
300
+ const generateSecureUUID = SecureRandom.generateSecureUUID;
301
+ /**
302
+ * ### Token Generation
303
+ *
304
+ * Secure token generation for sessions, API keys, and authentication.
305
+ *
306
+ * @example
307
+ * ```typescript
308
+ * import { generateSessionToken } from "xypriss-security";
309
+ *
310
+ * // Generate session token
311
+ * const sessionToken = generateSessionToken(64, "base64url");
312
+ * ```
313
+ */
314
+ /** Generate secure session token with configurable encoding */
315
+ const generateSessionToken = RandomTokens.generateSessionToken;
316
+ /**
317
+ * ### Hash Operations
318
+ *
319
+ * Military-grade hashing functions with timing-safe operations and
320
+ * automatic salt generation for maximum security.
321
+ *
322
+ * @example
323
+ * ```typescript
324
+ * import { createSecureHash, createSecureHMAC, verifyHash } from "xypriss-security";
325
+ *
326
+ * // Create secure hash with automatic salt
327
+ * const hash = createSecureHash("data to hash");
328
+ *
329
+ * // Create HMAC with secret key
330
+ * const hmac = createSecureHMAC("sha256", "secret-key", "data");
331
+ *
332
+ * // Verify hash with timing-safe comparison
333
+ * const isValid = verifyHash("original-data", hash);
334
+ * ```
335
+ *
336
+ * @see {@link https://github.com/paulmillr/noble-hashes} Noble Hashes - Modern Crypto Library
337
+ * @see {@link https://nodejs.org/api/crypto.html#cryptocreatehashstring-options} Node.js Hash Functions
338
+ * @see {@link https://tools.ietf.org/html/rfc2104} RFC 2104 - HMAC Specification
339
+ * @see {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf} NIST SHA Standards
340
+ */
341
+ /** Create secure hash with automatic salt generation */
342
+ const createSecureHash = Hash.createSecureHash;
343
+ /** Create secure HMAC with timing-safe operations */
344
+ const createSecureHMAC = Hash.createSecureHMAC;
345
+ /** Verify hash with constant-time comparison */
346
+ const verifyHash = Hash.verifyHash;
347
+ /**
348
+ * ### Password Manager Quick Access
349
+ *
350
+ * Convenient alias for password manager with default configuration.
351
+ * For production use with custom configuration, use PasswordManager.create()
352
+ * or PasswordManager.getInstance() with specific options.
353
+ *
354
+ * @example
355
+ * ```typescript
356
+ * import { pm } from "xypriss-security";
357
+ *
358
+ * // Quick password operations with default config
359
+ * const hash = await pm.hash("userPassword");
360
+ * const result = await pm.verify("userPassword", hash);
361
+ *
362
+ * // For custom configuration:
363
+ * // const customPM = PasswordManager.create({ memoryCost: 131072 });
364
+ * ```
365
+ *
366
+ * @deprecated Consider using PasswordManager.getInstance() for explicit configuration
367
+ */
368
+ const pm = PasswordManager.getInstance();
369
+ /**
370
+ * ## Secure Data Structure Factory Functions
371
+ *
372
+ * Convenient factory functions for creating secure data structures with
373
+ * enhanced security features and automatic memory management.
374
+ */
375
+ /**
376
+ * ### Create Secure String
377
+ *
378
+ * Creates a secure string instance with automatic memory management,
379
+ * encryption capabilities, and secure cleanup functionality.
380
+ *
381
+ * **Key Features:**
382
+ * - Automatic memory tracking and cleanup
383
+ * - Optional AES-256 encryption for sensitive data
384
+ * - Memory fragmentation protection
385
+ * - Secure wiping on destruction
386
+ * - Event-driven lifecycle management
387
+ *
388
+ * @param value - The initial string value to secure
389
+ * @param options - Configuration options for security level and features
390
+ * @returns A new SecureString instance with enhanced protection
391
+ *
392
+ * @example Basic Usage
393
+ * ```typescript
394
+ * import { fString } from "xypriss-security";
395
+ *
396
+ * // Create basic secure string
397
+ * const password = fString("userPassword123");
398
+ *
399
+ * // Access string value
400
+ * console.log(password.toString());
401
+ *
402
+ * // Secure cleanup
403
+ * password.destroy();
404
+ * ```
405
+ *
406
+ * @example Advanced Configuration
407
+ * ```typescript
408
+ * import { fString } from "xypriss-security";
409
+ *
410
+ * // Maximum security configuration
411
+ * const sensitiveData = fString("credit-card-4532-1234-5678-9012", {
412
+ * protectionLevel: "maximum",
413
+ * enableEncryption: true,
414
+ * enableFragmentation: true,
415
+ * enableMemoryTracking: true,
416
+ * autoCleanup: true
417
+ * });
418
+ *
419
+ * // String operations with automatic encryption/decryption
420
+ * sensitiveData.append("-VERIFIED");
421
+ * const masked = sensitiveData.mask(4, 12, "*");
422
+ *
423
+ * // Cryptographic operations
424
+ * const hash = await sensitiveData.hash("SHA-256");
425
+ * const isValid = sensitiveData.equals("other-string", true); // timing-safe
426
+ *
427
+ * // Automatic cleanup when done
428
+ * sensitiveData.destroy();
429
+ * ```
430
+ *
431
+ * @author Seth Eleazar
432
+ * @since 1.0.0
433
+ */
434
+ function fString(...args) {
435
+ return createSecureString(...args);
436
+ }
437
+ /**
438
+ * ### Create Secure Object
439
+ *
440
+ * Creates a secure object instance with encryption, metadata management,
441
+ * and comprehensive security features for sensitive data storage.
442
+ *
443
+ * **Key Features:**
444
+ * - Automatic encryption for sensitive values
445
+ * - Metadata tracking and management
446
+ * - Event-driven architecture
447
+ * - Secure serialization and deserialization
448
+ * - Memory protection and cleanup
449
+ *
450
+ * @param initialData - The initial data to store in the secure object
451
+ * @param options - Configuration options for encryption and security
452
+ * @returns A new SecureObject instance with enhanced protection
453
+ *
454
+ * @example Basic Usage
455
+ * ```typescript
456
+ * import { fObject } from "xypriss-security";
457
+ *
458
+ * // Create secure object with initial data
459
+ * const userCredentials = fObject({
460
+ * username: "john_doe",
461
+ * apiKey: "secret-api-key-12345",
462
+ * sessionToken: "session-token-abcdef"
463
+ * });
464
+ *
465
+ * // Access and modify data
466
+ * userCredentials.set("lastLogin", new Date().toISOString());
467
+ * const apiKey = userCredentials.get("apiKey");
468
+ *
469
+ * // Secure cleanup
470
+ * userCredentials.destroy();
471
+ * ```
472
+ *
473
+ * @example Advanced Configuration
474
+ * ```typescript
475
+ * import { fObject } from "xypriss-security";
476
+ *
477
+ * // Create with encryption and metadata tracking
478
+ * const secureConfig = fObject({
479
+ * databaseUrl: "postgresql://user:pass@localhost/db",
480
+ * encryptionKey: "master-encryption-key-2025",
481
+ * apiSecrets: {
482
+ * stripe: "sk_live_...",
483
+ * aws: "AKIA..."
484
+ * }
485
+ * }, {
486
+ * encryptionKey: process.env.OBJECT_ENCRYPTION_KEY,
487
+ * enableMetadata: true,
488
+ * autoCleanup: true
489
+ * });
490
+ *
491
+ * // Mark sensitive keys for special handling
492
+ * secureConfig.markSensitive("databaseUrl");
493
+ * secureConfig.markSensitive("encryptionKey");
494
+ * secureConfig.markSensitive("apiSecrets");
495
+ *
496
+ * // Export with encryption
497
+ * const encrypted = secureConfig.serialize({ encrypt: true });
498
+ *
499
+ * // Event handling
500
+ * secureConfig.on("accessed", (key) => {
501
+ * console.log(`Sensitive key accessed: ${key}`);
502
+ * });
503
+ * ```
504
+ *
505
+ * @author Seth Eleazar
506
+ * @since 1.0.0
507
+ */
508
+ function fObject(...args) {
509
+ return createSecureObject(...args);
510
+ }
511
+ /**
512
+ * ### Create Secure Array
513
+ *
514
+ * Creates a military-grade secure array with AES-256-CTR-HMAC encryption,
515
+ * comprehensive security features, and high-performance operations.
516
+ *
517
+ * **Key Features:**
518
+ * - Military-grade AES-256-CTR-HMAC encryption
519
+ * - Real-time security monitoring and analytics
520
+ * - Automatic memory management and cleanup
521
+ * - Snapshot and versioning capabilities
522
+ * - Event-driven architecture
523
+ * - Multiple export formats with integrity verification
524
+ * - Advanced array operations (unique, shuffle, min/max)
525
+ *
526
+ * @param initialData - The initial array data to secure
527
+ * @param options - Configuration options for encryption and security features
528
+ * @returns A new SecureArray instance with military-grade protection
529
+ *
530
+ * @example Basic Usage
531
+ * ```typescript
532
+ * import { fArray } from "xypriss-security";
533
+ *
534
+ * // Create secure array with sensitive data
535
+ * const apiKeys = fArray([
536
+ * "api-key-production-12345",
537
+ * "api-key-staging-67890",
538
+ * "api-key-development-abcdef"
539
+ * ]);
540
+ *
541
+ * // Set encryption key and encrypt all data
542
+ * apiKeys.setEncryptionKey("your-super-secret-key-2025");
543
+ * apiKeys.encryptAll();
544
+ *
545
+ * // Use like regular array - data automatically encrypted/decrypted
546
+ * apiKeys.push("new-api-key-xyz789");
547
+ * const firstKey = apiKeys.get(0); // Automatically decrypted
548
+ * const filtered = apiKeys.filter(key => key.includes("production"));
549
+ *
550
+ * // Secure cleanup
551
+ * apiKeys.destroy();
552
+ * ```
553
+ *
554
+ * @example Advanced Operations
555
+ * ```typescript
556
+ * import { fArray } from "xypriss-security";
557
+ * import { NehoID as ID } from "nehoid";
558
+ *
559
+ * // Create array for high-volume data processing
560
+ * const dataProcessor = fArray([] as string[], {
561
+ * encryptionKey: process.env.ARRAY_ENCRYPTION_KEY,
562
+ * enableCompression: true,
563
+ * maxSize: 100000,
564
+ * enableEvents: true
565
+ * });
566
+ *
567
+ * // Bulk data processing with automatic encryption
568
+ * const dataTypes = ["user", "transaction", "audit", "system"];
569
+ * const maxRecords = 10000;
570
+ *
571
+ * for (let i = 0; i < maxRecords; i++) {
572
+ * const randomType = dataTypes[Math.floor(Math.random() * dataTypes.length)];
573
+ * const record = `${randomType}-record-${i}-${Date.now()}`;
574
+ * dataProcessor.push(record);
575
+ * }
576
+ *
577
+ * // Advanced analytics and operations
578
+ * const stats = dataProcessor.getStats();
579
+ * const snapshot = dataProcessor.createSnapshot();
580
+ * const exported = dataProcessor.exportData("json");
581
+ *
582
+ * // Event monitoring
583
+ * dataProcessor.on("push", (index, value) => {
584
+ * console.log(`New record added at index ${index}`);
585
+ * });
586
+ *
587
+ * // Generate probability analysis
588
+ * console.log("Data distribution:", ID.probabilityCloud(dataProcessor.toArray()));
589
+ *
590
+ * // Secure cleanup - wipes all data and destroys array
591
+ * dataProcessor.destroy(); // Cannot be used after this
592
+ * ```
593
+ *
594
+ * @example Real-time Security Monitoring
595
+ * ```typescript
596
+ * import { fArray } from "xypriss-security";
597
+ *
598
+ * // Create array with comprehensive monitoring
599
+ * const secureData = fArray(["sensitive-data-1", "sensitive-data-2"], {
600
+ * enableRealTimeMonitoring: true,
601
+ * enableIntegrityChecks: true,
602
+ * enableAuditLogging: true
603
+ * });
604
+ *
605
+ * // Monitor security status
606
+ * const encryptionStatus = secureData.getEncryptionStatus();
607
+ * console.log(`Algorithm: ${encryptionStatus.algorithm}`);
608
+ * console.log(`Encrypted elements: ${encryptionStatus.encryptedCount}`);
609
+ *
610
+ * // Real-time analytics
611
+ * const analytics = secureData.getAnalytics();
612
+ * console.log(`Performance score: ${analytics.performanceScore}`);
613
+ * console.log(`Security level: ${analytics.securityLevel}`);
614
+ * ```
615
+ *
616
+ * @author Seth Eleazar
617
+ * @license MIT
618
+ * @since 1.0.0
619
+ * @see {@link https://github.com/paulmillr/noble-ciphers} Noble Ciphers - AES Implementation
620
+ * @see {@link https://tools.ietf.org/html/rfc3610} RFC 3610 - Counter with CBC-MAC (CCM)
621
+ * @see {@link https://csrc.nist.gov/publications/detail/sp/800-38a/final} NIST SP 800-38A
622
+ */
623
+ function fArray(...args) {
624
+ return createSecureArray(...args);
625
+ }
626
+ /**
627
+ * ## Advanced Password Security Functions
628
+ *
629
+ * Military-grade password encryption and verification with pepper support,
630
+ * timing-safe operations, and comprehensive security features.
631
+ */
632
+ /**
633
+ * ### Encrypt Password with Pepper
634
+ *
635
+ * Encrypts a password using military-grade security with pepper (secret) application
636
+ * before Argon2ID hashing. This provides maximum protection against rainbow table
637
+ * attacks and database compromise scenarios.
638
+ *
639
+ * **Security Features:**
640
+ * - HMAC-SHA256 pepper application for additional entropy
641
+ * - Argon2ID memory-hard hashing algorithm
642
+ * - Timing-safe operations to prevent side-channel attacks
643
+ * - Configurable memory and time costs for future-proofing
644
+ * - Automatic salt generation for each password
645
+ *
646
+ * **Important Security Notes:**
647
+ * - The PEPPER must be stored securely (environment variables, key management system)
648
+ * - PEPPER should never be stored in the same database as password hashes
649
+ * - Use a cryptographically secure random value for PEPPER generation
650
+ * - Consider key rotation policies for long-term security
651
+ *
652
+ * @param password - The plain text password to encrypt
653
+ * @param PEPPER - A secret pepper value (must be stored securely, not in database)
654
+ * @param options - Advanced hashing configuration options
655
+ * @returns Promise<string> - The peppered and hashed password ready for secure storage
656
+ * @throws {Error} If PEPPER is not provided or invalid
657
+ *
658
+ * @example Basic Usage
659
+ * ```typescript
660
+ * import { encryptSecurePass, Random } from "xypriss-security";
661
+ *
662
+ * // Generate secure pepper (do this once, store securely)
663
+ * const pepper = Random.getRandomBytes(32, "hex");
664
+ * console.log("Store this PEPPER securely:", pepper);
665
+ *
666
+ * // In your application (pepper from environment)
667
+ * const pepper = process.env.PASSWORD_PEPPER;
668
+ * const hashedPassword = await encryptSecurePass("userPassword123", pepper);
669
+ *
670
+ * // Store hashedPassword in database
671
+ * await database.users.update(userId, { passwordHash: hashedPassword });
672
+ * ```
673
+ *
674
+ * @example Advanced Configuration
675
+ * ```typescript
676
+ * import { encryptSecurePass, PasswordAlgorithm } from "xypriss-security";
677
+ *
678
+ * // Maximum security configuration
679
+ * const hashedPassword = await encryptSecurePass("userPassword123", pepper, {
680
+ * algorithm: PasswordAlgorithm.ARGON2ID,
681
+ * memoryCost: 131072, // 128 MB memory usage
682
+ * timeCost: 4, // 4 iterations
683
+ * parallelism: 2, // 2 parallel threads
684
+ * hashLength: 64, // 64-byte output
685
+ * saltLength: 32 // 32-byte salt
686
+ * });
687
+ * ```
688
+ *
689
+ * @example Production Setup
690
+ * ```typescript
691
+ * // .env file
692
+ * PASSWORD_PEPPER=your-cryptographically-secure-pepper-value-here
693
+ *
694
+ * // Application code
695
+ * import { encryptSecurePass } from "xypriss-security";
696
+ *
697
+ * const pepper = process.env.PASSWORD_PEPPER;
698
+ * if (!pepper) {
699
+ * throw new Error("PASSWORD_PEPPER environment variable is required");
700
+ * }
701
+ *
702
+ * // User registration
703
+ * const hashedPassword = await encryptSecurePass(userPassword, pepper);
704
+ * await saveUserToDatabase({ email, passwordHash: hashedPassword });
705
+ * ```
706
+ *
707
+ * @security
708
+ * - **HMAC-SHA256**: Applied to password with pepper for additional entropy
709
+ * - **Argon2ID**: Memory-hard algorithm resistant to GPU and ASIC attacks
710
+ * - **Timing Safety**: Constant-time operations prevent timing attacks
711
+ * - **Salt Generation**: Automatic unique salt for each password
712
+ * - **Memory Protection**: Secure memory handling throughout the process
713
+ *
714
+ * @author suppercodercodelover
715
+ * @since 2.0.0
716
+ */
717
+ async function encryptSecurePass(password, PEPPER, options = {}) {
718
+ if (!PEPPER) {
719
+ throw new Error("PEPPER must be defined when running password master. Store it securely in environment variables.");
720
+ }
721
+ // Apply pepper using HMAC-SHA256 for cryptographic security
722
+ const peppered = Hash.createSecureHMAC("sha256", PEPPER, password);
723
+ // Hash the peppered password with Argon2ID (military-grade)
724
+ const passwordManager = PasswordManager.getInstance();
725
+ return await passwordManager.hash(peppered, options);
726
+ }
727
+ /**
728
+ * ### Verify Encrypted Password
729
+ *
730
+ * Verifies a plain text password against a peppered hash using timing-safe comparison.
731
+ * This function must be used with passwords that were encrypted using encryptSecurePass()
732
+ * to ensure proper pepper application and security verification.
733
+ *
734
+ * **Security Features:**
735
+ * - Constant-time comparison to prevent timing attacks
736
+ * - Same HMAC-SHA256 pepper application as encryption
737
+ * - Resistant to side-channel analysis
738
+ * - No information leakage through execution time
739
+ * - Comprehensive error handling and validation
740
+ *
741
+ * **Important Security Notes:**
742
+ * - Must use the exact same PEPPER value as used in encryptSecurePass()
743
+ * - Verification time is constant regardless of password correctness
744
+ * - Function returns only boolean result to prevent information leakage
745
+ * - All intermediate values are securely cleared from memory
746
+ *
747
+ * @param password - The plain text password to verify
748
+ * @param hashedPassword - The peppered hash from database (created with encryptSecurePass)
749
+ * @param PEPPER - The same secret pepper value used during encryption
750
+ * @returns Promise<boolean> - true if password is valid, false otherwise
751
+ * @throws {Error} If PEPPER is not provided or verification fails
752
+ *
753
+ * @example Basic Login Verification
754
+ * ```typescript
755
+ * import { verifyEncryptedPassword } from "xypriss-security";
756
+ *
757
+ * // User login attempt
758
+ * const pepper = process.env.PASSWORD_PEPPER;
759
+ * const userPassword = "userPassword123";
760
+ * const storedHash = await database.users.getPasswordHash(userId);
761
+ *
762
+ * const isValid = await verifyEncryptedPassword(
763
+ * userPassword,
764
+ * storedHash,
765
+ * pepper
766
+ * );
767
+ *
768
+ * if (isValid) {
769
+ * // Login successful - create session
770
+ * const sessionToken = generateSessionToken();
771
+ * await createUserSession(userId, sessionToken);
772
+ * console.log("Login successful!");
773
+ * } else {
774
+ * // Login failed - log attempt and return error
775
+ * await logFailedLoginAttempt(userId);
776
+ * console.log("Invalid credentials");
777
+ * }
778
+ * ```
779
+ *
780
+ * @example Production Authentication Flow
781
+ * ```typescript
782
+ * import { verifyEncryptedPassword } from "xypriss-security";
783
+ *
784
+ * async function authenticateUser(email: string, password: string) {
785
+ * try {
786
+ * // Get user and password hash from database
787
+ * const user = await database.users.findByEmail(email);
788
+ * if (!user) {
789
+ * // Use timing-safe dummy verification to prevent user enumeration
790
+ * await verifyEncryptedPassword("dummy", "dummy-hash", pepper);
791
+ * return { success: false, error: "Invalid credentials" };
792
+ * }
793
+ *
794
+ * // Verify password with timing-safe comparison
795
+ * const pepper = process.env.PASSWORD_PEPPER;
796
+ * const isValid = await verifyEncryptedPassword(
797
+ * password,
798
+ * user.passwordHash,
799
+ * pepper
800
+ * );
801
+ *
802
+ * if (isValid) {
803
+ * // Update last login timestamp
804
+ * await database.users.updateLastLogin(user.id);
805
+ *
806
+ * // Create secure session
807
+ * const sessionToken = generateSessionToken(64, "base64url");
808
+ * await database.sessions.create({
809
+ * userId: user.id,
810
+ * token: sessionToken,
811
+ * expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000) // 24 hours
812
+ * });
813
+ *
814
+ * return {
815
+ * success: true,
816
+ * user: { id: user.id, email: user.email },
817
+ * sessionToken
818
+ * };
819
+ * } else {
820
+ * // Log failed attempt for security monitoring
821
+ * await database.auditLog.create({
822
+ * action: "failed_login",
823
+ * userId: user.id,
824
+ * ip: request.ip,
825
+ * timestamp: new Date()
826
+ * });
827
+ *
828
+ * return { success: false, error: "Invalid credentials" };
829
+ * }
830
+ * } catch (error) {
831
+ * console.error("Authentication error:", error);
832
+ * return { success: false, error: "Authentication failed" };
833
+ * }
834
+ * }
835
+ * ```
836
+ *
837
+ * @example Rate Limiting and Security
838
+ * ```typescript
839
+ * import { verifyEncryptedPassword } from "xypriss-security";
840
+ *
841
+ * async function secureLogin(email: string, password: string, clientIP: string) {
842
+ * // Check rate limiting first
843
+ * const attempts = await getFailedAttempts(clientIP);
844
+ * if (attempts >= 5) {
845
+ * throw new Error("Too many failed attempts. Please try again later.");
846
+ * }
847
+ *
848
+ * // Verify password
849
+ * const pepper = process.env.PASSWORD_PEPPER;
850
+ * const user = await getUserByEmail(email);
851
+ *
852
+ * if (!user) {
853
+ * // Timing-safe dummy operation
854
+ * await verifyEncryptedPassword("dummy", "dummy-hash", pepper);
855
+ * await incrementFailedAttempts(clientIP);
856
+ * return false;
857
+ * }
858
+ *
859
+ * const isValid = await verifyEncryptedPassword(password, user.passwordHash, pepper);
860
+ *
861
+ * if (isValid) {
862
+ * await clearFailedAttempts(clientIP);
863
+ * return true;
864
+ * } else {
865
+ * await incrementFailedAttempts(clientIP);
866
+ * return false;
867
+ * }
868
+ * }
869
+ * ```
870
+ *
871
+ * @security
872
+ * - **Timing Safety**: Constant execution time prevents timing attacks
873
+ * - **Pepper Consistency**: Uses same HMAC-SHA256 pepper as encryption
874
+ * - **Side-Channel Resistance**: No information leakage through execution patterns
875
+ * - **Memory Protection**: Secure handling of sensitive data throughout verification
876
+ * - **Error Handling**: Comprehensive validation without information disclosure
877
+ *
878
+ * @author suppercodercodelover
879
+ * @since 2.0.0
880
+ */
881
+ async function verifyEncryptedPassword(password, hashedPassword, PEPPER) {
882
+ if (!PEPPER) {
883
+ throw new Error("PEPPER must be defined when running password master. Use the same pepper as encryptSecurePass().");
884
+ }
885
+ // Apply the same pepper transformation as during encryption
886
+ const peppered = Hash.createSecureHMAC("sha256", PEPPER, password);
887
+ // Perform timing-safe verification
888
+ const passwordManager = PasswordManager.getInstance();
889
+ const result = await passwordManager.verify(peppered, hashedPassword);
890
+ return result.isValid;
891
+ }
892
+
893
+ 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 };
894
+ //# sourceMappingURL=index.js.map