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