@reldens/server-utils 0.36.0 → 0.38.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/README.md CHANGED
@@ -1,388 +1,687 @@
1
- # Reldens - Server Utils
2
-
3
- A Node.js server toolkit providing secure application server creation, file handling, encryption, and file upload capabilities for production-ready applications with modular security configurations.
4
-
5
- [![Reldens - GitHub - Release](https://www.dwdeveloper.com/media/reldens/reldens-mmorpg-platform.png)](https://github.com/damian-pastorini/reldens)
6
-
7
- ## Features
8
-
9
- ### AppServerFactory
10
- - Complete Express.js server configuration with modular security
11
- - HTTPS/HTTP server creation with SSL certificate management
12
- - Optimized static asset caching for CSS, JS, fonts, and images
13
- - SNI (Server Name Indication) support for multi-domain hosting
14
- - Virtual host management with domain mapping
15
- - Development mode detection with appropriate configurations
16
- - CORS configuration with flexible origin management
17
- - Rate limiting with customizable thresholds
18
- - Security headers and XSS protection
19
- - Helmet integration for enhanced security
20
- - Protocol enforcement (HTTP to HTTPS redirection)
21
- - Trusted proxy configuration
22
- - Request parsing with size limits and validation
23
- - Static file serving with security headers
24
- - Compression middleware with smart filtering
25
- - Input validation utilities
26
-
27
- #### Modular Security Components
28
- The AppServerFactory now uses specialized security configurers:
29
-
30
- - **CorsConfigurer** - Dynamic CORS origin validation with development domain support
31
- - **DevelopmentModeDetector** - Automatic development environment detection
32
- - **ProtocolEnforcer** - Protocol redirection with development mode awareness
33
- - **RateLimitConfigurer** - Global and endpoint-specific rate limiting
34
- - **SecurityConfigurer** - Helmet integration with CSP management and XSS protection
35
-
36
- ### FileHandler
37
- - Secure file system operations with path validation
38
- - File and folder creation, copying, and removal
39
- - JSON file parsing and validation
40
- - File type detection based on magic numbers
41
- - Secure filename generation
42
- - Path sanitization and traversal protection
43
- - File permissions checking
44
- - Folder content listing and filtering
45
- - Temporary file creation
46
- - File quarantine functionality for security threats
47
- - Binary file head reading for type detection
48
- - Directory walking with callback processing
49
- - File comparison and relative path calculations
50
- - Comprehensive error handling with detailed context
51
-
52
- ### Encryptor
53
- - Password hashing using PBKDF2 with configurable iterations
54
- - Password validation against stored hashes
55
- - AES-256-GCM data encryption and decryption
56
- - Secure token generation with a customizable length
57
- - TOTP (Time-based One-Time Password) generation
58
- - Data hashing with multiple algorithms (SHA-256, SHA-512, MD5)
59
- - HMAC generation and verification
60
- - Constant-time string comparison for security
61
- - Cryptographically secure random value generation
62
-
63
- ### UploaderFactory
64
- - Multer-based file upload handling with security validation
65
- - Multiple file upload support with field mapping
66
- - File type validation using MIME types and extensions
67
- - Filename security validation and sanitization
68
- - File size limits and upload count restrictions
69
- - Secure filename generation option
70
- - File content validation based on magic numbers
71
- - Dangerous file extension filtering
72
- - Automatic file cleanup on validation failure
73
- - Custom error response handling
74
- - Upload destination mapping per field
75
-
76
- ## Installation
77
-
78
- ```bash
79
- npm install @reldens/server-utils
80
- ```
81
-
82
- ## Quick Start
83
-
84
- ### Basic Server Setup
85
-
86
- ```javascript
87
- const { AppServerFactory } = require('@reldens/server-utils');
88
-
89
- let appServerFactory = new AppServerFactory();
90
- let serverResult = appServerFactory.createAppServer({
91
- port: 3000,
92
- useHttps: false,
93
- autoListen: true,
94
- useCompression: true
95
- });
96
-
97
- if(serverResult){
98
- let { app, appServer } = serverResult;
99
- console.log('Server running on port 3000');
100
- }
101
- ```
102
-
103
- ### HTTPS Server with Optimized Caching
104
-
105
- ```javascript
106
- let appServerFactory = new AppServerFactory();
107
- let serverResult = appServerFactory.createAppServer({
108
- port: 443,
109
- useHttps: true,
110
- keyPath: '/ssl/server.key',
111
- certPath: '/ssl/server.crt',
112
- autoListen: true
113
- });
114
- ```
115
-
116
- Cache configuration is automatic with defaults:
117
- - CSS/JS: 1 year
118
- - Fonts: 1 year
119
- - Images: 30 days
120
-
121
- Override cache settings if needed:
122
-
123
- ```javascript
124
- let appServerFactory = new AppServerFactory();
125
- appServerFactory.cacheConfig = {
126
- '.css': 86400,
127
- '.js': 86400,
128
- '.png': 604800
129
- };
130
- let serverResult = appServerFactory.createAppServer({
131
- useHttps: true,
132
- });
133
- ```
134
-
135
- ### File Operations
136
-
137
- ```javascript
138
- const { FileHandler } = require('@reldens/server-utils');
139
-
140
- // Read a JSON configuration file
141
- let config = FileHandler.fetchFileJson('/path/to/config.json');
142
- if(config){
143
- console.log('Configuration loaded:', config);
144
- }
145
-
146
- // Create a folder securely
147
- if(FileHandler.createFolder('/path/to/new/folder')){
148
- console.log('Folder created successfully');
149
- }
150
-
151
- // Generate a secure filename
152
- let secureFilename = FileHandler.generateSecureFilename('user-upload.jpg');
153
- console.log('Secure filename:', secureFilename);
154
- ```
155
-
156
- ### Password Encryption
157
-
158
- ```javascript
159
- const { Encryptor } = require('@reldens/server-utils');
160
-
161
- // Hash a password
162
- let hashedPassword = Encryptor.encryptPassword('userPassword123');
163
- if(hashedPassword){
164
- console.log('Password hashed:', hashedPassword);
165
- }
166
-
167
- // Validate password
168
- let isValid = Encryptor.validatePassword('userPassword123', hashedPassword);
169
- console.log('Password valid:', isValid);
170
-
171
- // Generate secure token
172
- let secureToken = Encryptor.generateSecureToken(32);
173
- console.log('Secure token:', secureToken);
174
- ```
175
-
176
- ### File Upload Configuration
177
-
178
- ```javascript
179
- const { UploaderFactory } = require('@reldens/server-utils');
180
-
181
- let uploaderFactory = new UploaderFactory({
182
- maxFileSize: 10 * 1024 * 1024, // 10MB
183
- mimeTypes: {
184
- image: ['image/jpeg', 'image/png', 'image/gif'],
185
- document: ['application/pdf', 'text/plain']
186
- },
187
- allowedExtensions: {
188
- image: ['.jpg', '.jpeg', '.png', '.gif'],
189
- document: ['.pdf', '.txt']
190
- },
191
- applySecureFileNames: true
192
- });
193
-
194
- let uploader = uploaderFactory.createUploader(
195
- [{ name: 'avatar' }, { name: 'document' }],
196
- { avatar: '/uploads/avatars', document: '/uploads/docs' },
197
- { avatar: 'image', document: 'document' }
198
- );
199
-
200
- // Use with Express
201
- app.post('/upload', uploader, (req, res) => {
202
- console.log('Files uploaded:', req.files);
203
- res.json({ success: true });
204
- });
205
- ```
206
-
207
- ## Advanced Configuration
208
-
209
- ### HTTPS Server with Multiple Domains
210
-
211
- ```javascript
212
- let appServerFactory = new AppServerFactory();
213
-
214
- appServerFactory.addDomain({
215
- hostname: 'example.com',
216
- keyPath: '/ssl/example.com.key',
217
- certPath: '/ssl/example.com.crt',
218
- aliases: ['www.example.com']
219
- });
220
-
221
- appServerFactory.addDomain({
222
- hostname: 'api.example.com',
223
- keyPath: '/ssl/api.example.com.key',
224
- certPath: '/ssl/api.example.com.crt'
225
- });
226
-
227
- let serverResult = appServerFactory.createAppServer({
228
- useHttps: true,
229
- useVirtualHosts: true,
230
- keyPath: '/ssl/default.key',
231
- certPath: '/ssl/default.crt',
232
- port: 443,
233
- enforceProtocol: true,
234
- developmentMultiplier: 10
235
- });
236
- ```
237
-
238
- ### Development Mode Configuration
239
-
240
- ```javascript
241
- let appServerFactory = new AppServerFactory();
242
-
243
- // Add development domains (automatically detected)
244
- appServerFactory.addDevelopmentDomain('localhost');
245
- appServerFactory.addDevelopmentDomain('dev.myapp.local');
246
-
247
- let serverResult = appServerFactory.createAppServer({
248
- port: 3000,
249
- corsOrigin: ['http://localhost:3000', 'http://dev.myapp.local:3000'],
250
- developmentMultiplier: 5, // More lenient rate limiting in dev
251
- developmentPorts: [3000, 3001, 8080],
252
- developmentExternalDomains: {
253
- 'script-src': ['https://cdn.example.com'],
254
- 'style-src': ['https://fonts.googleapis.com']
255
- }
256
- });
257
- ```
258
-
259
- ### Custom Security Configuration
260
-
261
- ```javascript
262
- let appServerFactory = new AppServerFactory();
263
-
264
- let serverResult = appServerFactory.createAppServer({
265
- useHelmet: true,
266
- helmetConfig: {
267
- contentSecurityPolicy: {
268
- directives: {
269
- defaultSrc: ["'self'"],
270
- styleSrc: ["'self'", "'unsafe-inline'"],
271
- scriptSrc: ["'self'"]
272
- }
273
- }
274
- },
275
- globalRateLimit: 100, // requests per window
276
- windowMs: 60000, // 1 minute
277
- maxRequests: 30,
278
- trustedProxy: '127.0.0.1',
279
- useXssProtection: true,
280
- sanitizeOptions: {allowedTags: [], allowedAttributes: {}}
281
- });
282
- ```
283
-
284
- ## API Reference
285
-
286
- ### AppServerFactory Methods
287
-
288
- - `createAppServer(config)` - Creates and configures Express server
289
- - `addDomain(domainConfig)` - Adds domain configuration for virtual hosting
290
- - `addDevelopmentDomain(domain)` - Adds development domain pattern
291
- - `setDomainMapping(mapping)` - Sets domain to configuration mapping
292
- - `enableServeHome(app, callback)` - Enables homepage serving
293
- - `serveStatics(app, staticPath)` - Serves static files
294
- - `serveStaticsPath(app, route, staticPath)` - Serves static files on specific route
295
- - `enableCSP(cspOptions)` - Enables Content Security Policy
296
- - `listen(port)` - Starts server listening
297
- - `close()` - Gracefully closes server
298
-
299
- ### FileHandler Methods
300
-
301
- - `exists(path)` - Checks if file or folder exists
302
- - `createFolder(path)` - Creates folder with a recursive option
303
- - `remove(path)` - Removes file or folder recursively
304
- - `removeMultiple(filePaths)` - Removes multiple files from an array of paths
305
- - `copyFile(source, destination)` - Copies file to destination
306
- - `copyFolderSync(source, destination)` - Copies folder recursively
307
- - `readFile(path)` - Reads file contents as string
308
- - `writeFile(path, content)` - Writes content to file
309
- - `fetchFileJson(path)` - Reads and parses JSON file
310
- - `fetchFileContents(path)` - Reads file with validation
311
- - `updateFileContents(path, content)` - Updates existing file
312
- - `isFile(path)` - Checks if a path is a file
313
- - `isFolder(path)` - Checks if a path is folder
314
- - `getFilesInFolder(path, extensions)` - Lists files with optional filtering
315
- - `validateFileType(path, type, allowedTypes, maxSize)` - Validates file type and size
316
- - `detectFileType(path)` - Detects MIME type from file signature
317
- - `generateSecureFilename(originalName)` - Generates cryptographically secure filename
318
- - `quarantineFile(path, reason)` - Moves file to quarantine folder
319
- - `createTempFile(prefix, extension)` - Creates a temporary file path
320
- - `moveFile(from, to)` - Moves file to new location
321
- - `getFileSize(path)` - Gets file size in bytes
322
- - `compareFiles(file1, file2)` - Compares file contents
323
- - `getRelativePath(from, to)` - Calculates relative path
324
- - `walkDirectory(path, callback)` - Recursively processes directory tree
325
- - `getDirectorySize(path)` - Calculates total directory size
326
- - `emptyDirectory(path)` - Removes all contents from directory
327
-
328
- ### Encryptor Methods
329
-
330
- - `encryptPassword(password)` - Hashes password with salt
331
- - `validatePassword(password, hash)` - Validates password against hash
332
- - `generateSecretKey()` - Generates 256-bit secret key
333
- - `encryptData(data, key)` - Encrypts data with AES-256-GCM
334
- - `decryptData(encryptedData, key)` - Decrypts AES-256-GCM data
335
- - `generateSecureToken(length)` - Generates base64url token
336
- - `generateTOTP(secret, timeStep)` - Generates time-based OTP
337
- - `hashData(data, algorithm)` - Hashes data with specified algorithm
338
- - `generateHMAC(data, secret, algorithm)` - Generates HMAC signature
339
- - `verifyHMAC(data, secret, signature, algorithm)` - Verifies HMAC signature
340
- - `constantTimeCompare(a, b)` - Performs constant-time string comparison
341
-
342
- ### UploaderFactory Methods
343
-
344
- - `createUploader(fields, buckets, allowedTypes)` - Creates multer upload middleware
345
- - `validateFilenameSecurity(filename)` - Validates filename for security
346
- - `validateFile(file, allowedType, callback)` - Validates a file during upload
347
- - `validateFileContents(file, allowedType)` - Validates file content after upload
348
- - `convertToRegex(key)` - Converts MIME type patterns to regex
349
-
350
- ## Security Features
351
-
352
- ### Path Traversal Protection
353
- All file operations include comprehensive path validation to prevent directory traversal attacks and access to system files.
354
-
355
- ### Secure File Upload
356
- File uploads are validated at multiple levels including filename, MIME type, file extension, file size, and content validation using magic number detection. Failed uploads are automatically cleaned up using efficient file removal.
357
-
358
- ### Rate Limiting
359
- Configurable rate limiting with development mode detection for appropriate thresholds in different environments.
360
-
361
- ### HTTPS Support
362
- Full SSL/TLS support with SNI for multi-domain hosting and automatic certificate management.
363
-
364
- ### Input Validation
365
- Built-in validators for common input types including email, username, strong passwords, alphanumeric strings, and IP addresses.
366
-
367
- ### Cryptographic Security
368
- Industry-standard encryption using PBKDF2 for passwords, AES-256-GCM for data encryption, and secure random generation for tokens.
369
-
370
- ## Error Handling
371
-
372
- All methods include comprehensive error handling with detailed error objects containing context information. Errors are logged appropriately and never expose sensitive system information.
373
-
374
- ---
375
-
376
- ## Documentation
377
-
378
- [https://www.reldens.com/documentation/utils/](https://www.reldens.com/documentation/utils/)
379
-
380
- Need something specific?
381
-
382
- [Request a feature here: https://www.reldens.com/features-request](https://www.reldens.com/features-request)
383
-
384
- ---
385
-
386
- ### [Reldens](https://github.com/damian-pastorini/reldens/ "Reldens")
387
-
388
- ##### [By DwDeveloper](https://www.dwdeveloper.com/ "DwDeveloper")
1
+ # Reldens - Server Utils
2
+
3
+ A Node.js server toolkit providing secure application server creation, HTTP/2 CDN support, file handling, encryption, and file upload capabilities for production-ready applications with modular security configurations.
4
+
5
+ [![Reldens - GitHub - Release](https://www.dwdeveloper.com/media/reldens/reldens-mmorpg-platform.png)](https://github.com/damian-pastorini/reldens)
6
+
7
+ ## Features
8
+
9
+ ### AppServerFactory
10
+ - Complete Express.js server configuration with modular security
11
+ - HTTPS/HTTP server creation with SSL certificate management
12
+ - HTTP/2 CDN server with optimized static asset delivery
13
+ - Optimized static asset caching for CSS, JS, fonts, and images
14
+ - SNI (Server Name Indication) support for multi-domain hosting
15
+ - Virtual host management with domain mapping
16
+ - Development mode detection with appropriate configurations
17
+ - CORS configuration with flexible origin management
18
+ - Rate limiting with customizable thresholds
19
+ - Reverse proxy support for routing multiple domains to backend servers
20
+ - Security headers and XSS protection
21
+ - Helmet integration for enhanced security
22
+ - Protocol enforcement (HTTP to HTTPS redirection)
23
+ - Trusted proxy configuration
24
+ - Request parsing with size limits and validation
25
+ - Static file serving with security headers
26
+ - Compression middleware with smart filtering
27
+ - Input validation utilities
28
+
29
+ ### Http2CdnServer
30
+ - Dedicated HTTP/2 server for static asset delivery
31
+ - Optimized for serving CSS, JavaScript, images, and fonts
32
+ - Dynamic CORS origin validation with regex pattern support
33
+ - Configurable cache headers per file extension
34
+ - Comprehensive MIME type detection
35
+ - HTTP/1.1 fallback support
36
+ - Security headers (X-Content-Type-Options, X-Frame-Options, Vary)
37
+ - Standalone or integrated with AppServerFactory
38
+ - Multiple static path support
39
+ - Separate SSL certificate support from main server
40
+
41
+ #### Modular Security Components
42
+ The AppServerFactory now uses specialized security configurers:
43
+
44
+ - **CorsConfigurer** - Dynamic CORS origin validation with development domain support
45
+ - **DevelopmentModeDetector** - Automatic development environment detection
46
+ - **ProtocolEnforcer** - Protocol redirection with development mode awareness
47
+ - **RateLimitConfigurer** - Global and endpoint-specific rate limiting
48
+ - **ReverseProxyConfigurer** - Domain-based reverse proxy with WebSocket support
49
+ - **SecurityConfigurer** - Helmet integration with CSP management and XSS protection
50
+
51
+ ### FileHandler
52
+ - Secure file system operations with path validation
53
+ - File and folder creation, copying, and removal
54
+ - JSON file parsing and validation
55
+ - File type detection based on magic numbers
56
+ - Secure filename generation
57
+ - Path sanitization and traversal protection
58
+ - File permissions checking
59
+ - Folder content listing and filtering
60
+ - Temporary file creation
61
+ - File quarantine functionality for security threats
62
+ - Binary file head reading for type detection
63
+ - Directory walking with callback processing
64
+ - File comparison and relative path calculations
65
+ - Comprehensive error handling with detailed context
66
+
67
+ ### Encryptor
68
+ - Password hashing using PBKDF2 with configurable iterations
69
+ - Password validation against stored hashes
70
+ - AES-256-GCM data encryption and decryption
71
+ - Secure token generation with a customizable length
72
+ - TOTP (Time-based One-Time Password) generation
73
+ - Data hashing with multiple algorithms (SHA-256, SHA-512, MD5)
74
+ - HMAC generation and verification
75
+ - Constant-time string comparison for security
76
+ - Cryptographically secure random value generation
77
+
78
+ ### UploaderFactory
79
+ - Multer-based file upload handling with security validation
80
+ - Multiple file upload support with field mapping
81
+ - File type validation using MIME types and extensions
82
+ - Filename security validation and sanitization
83
+ - File size limits and upload count restrictions
84
+ - Secure filename generation option
85
+ - File content validation based on magic numbers
86
+ - Dangerous file extension filtering
87
+ - Automatic file cleanup on validation failure
88
+ - Custom error response handling
89
+ - Upload destination mapping per field
90
+
91
+ ## Installation
92
+
93
+ ```bash
94
+ npm install @reldens/server-utils
95
+ ```
96
+
97
+ ## Quick Start
98
+
99
+ ### Basic Server Setup
100
+
101
+ ```javascript
102
+ const { AppServerFactory } = require('@reldens/server-utils');
103
+
104
+ let appServerFactory = new AppServerFactory();
105
+ let serverResult = appServerFactory.createAppServer({
106
+ port: 3000,
107
+ useHttps: false,
108
+ autoListen: true,
109
+ useCompression: true
110
+ });
111
+
112
+ if(serverResult){
113
+ let { app, appServer } = serverResult;
114
+ console.log('Server running on port 3000');
115
+ }
116
+ ```
117
+
118
+ ### HTTP/2 CDN Server with Express
119
+
120
+ Serve your main application through Express on port 443, and static assets through HTTP/2 CDN on port 8443:
121
+
122
+ ```javascript
123
+ let appServerFactory = new AppServerFactory();
124
+ let serverResult = appServerFactory.createAppServer({
125
+ port: 443,
126
+ useHttps: true,
127
+ keyPath: '/ssl/main-server.key',
128
+ certPath: '/ssl/main-server.crt',
129
+ http2CdnEnabled: true,
130
+ http2CdnPort: 8443,
131
+ http2CdnKeyPath: '/ssl/cdn-server.key',
132
+ http2CdnCertPath: '/ssl/cdn-server.crt',
133
+ http2CdnStaticPaths: ['/var/www/public'],
134
+ http2CdnCorsOrigins: [
135
+ 'https://example.com',
136
+ /^https:\/\/(www\.)?example\.(com|net)$/
137
+ ],
138
+ autoListen: true
139
+ });
140
+
141
+ if(serverResult){
142
+ let { app, appServer, http2CdnServer } = serverResult;
143
+ console.log('Express server on port 443');
144
+ console.log('HTTP/2 CDN server on port 8443');
145
+ }
146
+ ```
147
+
148
+ **Note:** If `http2CdnKeyPath` and `http2CdnCertPath` are not specified, the CDN server will use the same certificates as the main server (`keyPath` and `certPath`).
149
+
150
+ Browser usage:
151
+ ```html
152
+ <link rel="stylesheet" href="https://cdn.example.com:8443/css/style.css">
153
+ <script src="https://cdn.example.com:8443/js/app.js"></script>
154
+ ```
155
+
156
+ ### Standalone HTTP/2 CDN Server
157
+
158
+ ```javascript
159
+ const { Http2CdnServer } = require('@reldens/server-utils');
160
+
161
+ let cdnServer = new Http2CdnServer();
162
+ cdnServer.port = 8443;
163
+ cdnServer.keyPath = '/ssl/cdn.key';
164
+ cdnServer.certPath = '/ssl/cdn.crt';
165
+ cdnServer.staticPaths = ['/var/www/public', '/var/www/assets'];
166
+ cdnServer.corsOrigins = [
167
+ 'https://main-site.com',
168
+ /^https:\/\/(new\.)?((site1|site2)\.(com|net))$/
169
+ ];
170
+
171
+ if(cdnServer.create()){
172
+ cdnServer.listen();
173
+ console.log('HTTP/2 CDN running on port 8443');
174
+ }
175
+ ```
176
+
177
+ ### HTTPS Server with Optimized Caching
178
+
179
+ ```javascript
180
+ let appServerFactory = new AppServerFactory();
181
+ let serverResult = appServerFactory.createAppServer({
182
+ port: 443,
183
+ useHttps: true,
184
+ keyPath: '/ssl/server.key',
185
+ certPath: '/ssl/server.crt',
186
+ autoListen: true
187
+ });
188
+ ```
189
+
190
+ Cache configuration is automatic with defaults:
191
+ - CSS/JS: 1 year
192
+ - Fonts: 1 year
193
+ - Images: 30 days
194
+
195
+ Override cache settings if needed:
196
+
197
+ ```javascript
198
+ let appServerFactory = new AppServerFactory();
199
+ appServerFactory.cacheConfig = {
200
+ '.css': 86400,
201
+ '.js': 86400,
202
+ '.png': 604800
203
+ };
204
+ let serverResult = appServerFactory.createAppServer({
205
+ useHttps: true,
206
+ });
207
+ ```
208
+
209
+ ### File Operations
210
+
211
+ ```javascript
212
+ const { FileHandler } = require('@reldens/server-utils');
213
+
214
+ // Read a JSON configuration file
215
+ let config = FileHandler.fetchFileJson('/path/to/config.json');
216
+ if(config){
217
+ console.log('Configuration loaded:', config);
218
+ }
219
+
220
+ // Create a folder securely
221
+ if(FileHandler.createFolder('/path/to/new/folder')){
222
+ console.log('Folder created successfully');
223
+ }
224
+
225
+ // Generate a secure filename
226
+ let secureFilename = FileHandler.generateSecureFilename('user-upload.jpg');
227
+ console.log('Secure filename:', secureFilename);
228
+ ```
229
+
230
+ ### Password Encryption
231
+
232
+ ```javascript
233
+ const { Encryptor } = require('@reldens/server-utils');
234
+
235
+ // Hash a password
236
+ let hashedPassword = Encryptor.encryptPassword('userPassword123');
237
+ if(hashedPassword){
238
+ console.log('Password hashed:', hashedPassword);
239
+ }
240
+
241
+ // Validate password
242
+ let isValid = Encryptor.validatePassword('userPassword123', hashedPassword);
243
+ console.log('Password valid:', isValid);
244
+
245
+ // Generate secure token
246
+ let secureToken = Encryptor.generateSecureToken(32);
247
+ console.log('Secure token:', secureToken);
248
+ ```
249
+
250
+ ### File Upload Configuration
251
+
252
+ ```javascript
253
+ const { UploaderFactory } = require('@reldens/server-utils');
254
+
255
+ let uploaderFactory = new UploaderFactory({
256
+ maxFileSize: 10 * 1024 * 1024, // 10MB
257
+ mimeTypes: {
258
+ image: ['image/jpeg', 'image/png', 'image/gif'],
259
+ document: ['application/pdf', 'text/plain']
260
+ },
261
+ allowedExtensions: {
262
+ image: ['.jpg', '.jpeg', '.png', '.gif'],
263
+ document: ['.pdf', '.txt']
264
+ },
265
+ applySecureFileNames: true
266
+ });
267
+
268
+ let uploader = uploaderFactory.createUploader(
269
+ [{ name: 'avatar' }, { name: 'document' }],
270
+ { avatar: '/uploads/avatars', document: '/uploads/docs' },
271
+ { avatar: 'image', document: 'document' }
272
+ );
273
+
274
+ // Use with Express
275
+ app.post('/upload', uploader, (req, res) => {
276
+ console.log('Files uploaded:', req.files);
277
+ res.json({ success: true });
278
+ });
279
+ ```
280
+
281
+ ## Advanced Configuration
282
+
283
+ ### HTTP/2 CDN with Separate Certificates
284
+
285
+ Configure separate SSL certificates for your CDN server:
286
+
287
+ ```javascript
288
+ let appServerFactory = new AppServerFactory();
289
+ let serverResult = appServerFactory.createAppServer({
290
+ useHttps: true,
291
+ port: 443,
292
+ keyPath: '/ssl/app-server.key',
293
+ certPath: '/ssl/app-server.crt',
294
+ http2CdnEnabled: true,
295
+ http2CdnPort: 8443,
296
+ http2CdnKeyPath: '/ssl/cdn-server.key',
297
+ http2CdnCertPath: '/ssl/cdn-server.crt',
298
+ http2CdnHttpsChain: '/ssl/cdn-chain.pem',
299
+ http2CdnStaticPaths: ['/var/www/public'],
300
+ http2CdnCorsOrigins: [
301
+ 'https://main-site.com',
302
+ 'https://app.main-site.com',
303
+ /^https:\/\/(new\.)?main-site\.(com|net)$/
304
+ ],
305
+ http2CdnCacheConfig: {
306
+ '.css': 31536000,
307
+ '.js': 31536000,
308
+ '.woff2': 31536000,
309
+ '.png': 2592000
310
+ }
311
+ });
312
+ ```
313
+
314
+ ### HTTP/2 CDN with Multiple Origins
315
+
316
+ The HTTP/2 CDN server supports multiple origin validation methods:
317
+
318
+ ```javascript
319
+ let appServerFactory = new AppServerFactory();
320
+ let serverResult = appServerFactory.createAppServer({
321
+ http2CdnEnabled: true,
322
+ http2CdnPort: 8443,
323
+ http2CdnStaticPaths: ['/var/www/public'],
324
+ http2CdnCorsOrigins: [
325
+ 'https://main-site.com',
326
+ 'https://app.main-site.com',
327
+ /^https:\/\/(new\.)?main-site\.(com|net)$/,
328
+ /^https:\/\/(app|admin)\.secondary-site\.com$/
329
+ ]
330
+ });
331
+ ```
332
+
333
+ ### HTTPS Server with Multiple Domains
334
+
335
+ ```javascript
336
+ let appServerFactory = new AppServerFactory();
337
+
338
+ appServerFactory.addDomain({
339
+ hostname: 'example.com',
340
+ keyPath: '/ssl/example.com.key',
341
+ certPath: '/ssl/example.com.crt',
342
+ aliases: ['www.example.com']
343
+ });
344
+
345
+ appServerFactory.addDomain({
346
+ hostname: 'api.example.com',
347
+ keyPath: '/ssl/api.example.com.key',
348
+ certPath: '/ssl/api.example.com.crt'
349
+ });
350
+
351
+ let serverResult = appServerFactory.createAppServer({
352
+ useHttps: true,
353
+ useVirtualHosts: true,
354
+ keyPath: '/ssl/default.key',
355
+ certPath: '/ssl/default.crt',
356
+ port: 443,
357
+ enforceProtocol: true,
358
+ developmentMultiplier: 10
359
+ });
360
+ ```
361
+
362
+ ### Development Mode Configuration
363
+
364
+ ```javascript
365
+ let appServerFactory = new AppServerFactory();
366
+
367
+ // Add development domains (automatically detected)
368
+ appServerFactory.addDevelopmentDomain('localhost');
369
+ appServerFactory.addDevelopmentDomain('dev.myapp.local');
370
+
371
+ let serverResult = appServerFactory.createAppServer({
372
+ port: 3000,
373
+ corsOrigin: ['http://localhost:3000', 'http://dev.myapp.local:3000'],
374
+ developmentMultiplier: 5, // More lenient rate limiting in dev
375
+ developmentPorts: [3000, 3001, 8080],
376
+ developmentExternalDomains: {
377
+ 'script-src': ['https://cdn.example.com'],
378
+ 'style-src': ['https://fonts.googleapis.com']
379
+ }
380
+ });
381
+ ```
382
+
383
+ ### Custom Security Configuration
384
+
385
+ ```javascript
386
+ let appServerFactory = new AppServerFactory();
387
+
388
+ let serverResult = appServerFactory.createAppServer({
389
+ useHelmet: true,
390
+ helmetConfig: {
391
+ contentSecurityPolicy: {
392
+ directives: {
393
+ defaultSrc: ["'self'"],
394
+ styleSrc: ["'self'", "'unsafe-inline'"],
395
+ scriptSrc: ["'self'"]
396
+ }
397
+ }
398
+ },
399
+ globalRateLimit: 100, // requests per window
400
+ windowMs: 60000, // 1 minute
401
+ maxRequests: 30,
402
+ trustedProxy: '127.0.0.1',
403
+ useXssProtection: true,
404
+ sanitizeOptions: {allowedTags: [], allowedAttributes: {}}
405
+ });
406
+ ```
407
+
408
+ ### External Domains Configuration
409
+
410
+ When using `developmentExternalDomains` to configure CSP policies, keys can be specified in either kebab-case or camelCase format. The system automatically converts kebab-case keys to the appropriate camelCase format:
411
+
412
+ ```javascript
413
+ let serverResult = appServerFactory.createAppServer({
414
+ developmentExternalDomains: {
415
+ // Both formats work - choose whichever you prefer
416
+ 'scriptSrc': ['https://cdn.example.com'], // camelCase
417
+ 'script-src': ['https://platform-api.example.com'], // kebab-case (auto-converted)
418
+ 'styleSrc': ['https://fonts.googleapis.com'], // camelCase
419
+ 'font-src': ['https://fonts.gstatic.com'] // kebab-case (auto-converted)
420
+ }
421
+ });
422
+ ```
423
+
424
+ The system automatically adds these domains to both the base directive and the corresponding `-elem` variant (e.g., `scriptSrc` and `scriptSrcElem`).
425
+
426
+ ### Helmet CSP Configuration Options
427
+
428
+ The security configurer provides flexible CSP directive handling with merge or override behavior:
429
+
430
+ #### Merging Directives (Default)
431
+
432
+ By default, custom CSP directives are merged with the security defaults, allowing you to add additional sources without redefining all directives:
433
+
434
+ ```javascript
435
+ let serverResult = appServerFactory.createAppServer({
436
+ useHelmet: true,
437
+ helmetConfig: {
438
+ contentSecurityPolicy: {
439
+ directives: {
440
+ // These will be ADDED to the default directives
441
+ scriptSrc: ['https://analytics.example.com'],
442
+ styleSrc: ['https://cdn.example.com']
443
+ }
444
+ }
445
+ }
446
+ });
447
+
448
+ // Result: default directives + your additional sources
449
+ ```
450
+
451
+ #### Overriding Directives
452
+
453
+ Set `overrideDirectives: true` to completely replace the default directives with your custom configuration:
454
+
455
+ ```javascript
456
+ let serverResult = appServerFactory.createAppServer({
457
+ useHelmet: true,
458
+ helmetConfig: {
459
+ contentSecurityPolicy: {
460
+ overrideDirectives: true, // Replace defaults entirely
461
+ directives: {
462
+ defaultSrc: ["'self'"],
463
+ scriptSrc: ["'self'", "https://trusted-cdn.com"],
464
+ styleSrc: ["'self'", "'unsafe-inline'"],
465
+ imgSrc: ["'self'", "data:", "https:"],
466
+ fontSrc: ["'self'"],
467
+ connectSrc: ["'self'"],
468
+ frameAncestors: ["'none'"],
469
+ baseUri: ["'self'"],
470
+ formAction: ["'self'"]
471
+ }
472
+ }
473
+ }
474
+ });
475
+ ```
476
+
477
+ ### Reverse Proxy Configuration
478
+
479
+ Route multiple domains to different backend servers through a single SSL-enabled entry point:
480
+
481
+ ```javascript
482
+ let appServerFactory = new AppServerFactory();
483
+
484
+ let serverResult = appServerFactory.createAppServer({
485
+ port: 443,
486
+ useHttps: true,
487
+ useVirtualHosts: true,
488
+ keyPath: '/ssl/server.key',
489
+ certPath: '/ssl/server.crt',
490
+ reverseProxyEnabled: true,
491
+ reverseProxyRules: [
492
+ {
493
+ hostname: 'demo.reldens.com',
494
+ target: 'https://localhost:8444',
495
+ pathPrefix: '/',
496
+ websocket: true,
497
+ secure: false
498
+ },
499
+ {
500
+ hostname: 'api.example.com',
501
+ target: 'https://localhost:8445',
502
+ pathPrefix: '/',
503
+ websocket: false
504
+ }
505
+ ],
506
+ autoListen: true
507
+ });
508
+ ```
509
+
510
+ #### Reverse Proxy Features
511
+
512
+ - Multiple backend routing with independent configuration per domain
513
+ - WebSocket support for real-time applications
514
+ - SSL termination at entry point
515
+ - Header preservation (X-Forwarded-For, X-Forwarded-Proto, X-Forwarded-Host)
516
+ - Virtual host integration
517
+ - Path-based routing
518
+ - Graceful error handling
519
+
520
+ #### Rule Properties
521
+
522
+ - `hostname` (string, required) - Domain to match
523
+ - `target` (string, required) - Backend URL
524
+ - `pathPrefix` (string, optional) - Path prefix, default: '/'
525
+ - `websocket` (boolean, optional) - Enable WebSocket, default: true
526
+ - `changeOrigin` (boolean, optional) - Change origin header, default: true
527
+ - `secure` (boolean, optional) - Verify SSL certificates, default: false
528
+ - `logLevel` (string, optional) - 'debug', 'info', 'warn', 'error', 'silent'
529
+
530
+ #### Example: Multiple Game Servers
531
+
532
+ ```javascript
533
+ reverseProxyRules: [
534
+ { hostname: 'demo.game.com', target: 'https://localhost:8444', websocket: true },
535
+ { hostname: 'staging.game.com', target: 'https://localhost:8445', websocket: true }
536
+ ]
537
+ ```
538
+
539
+ ## API Reference
540
+
541
+ ### AppServerFactory Methods
542
+
543
+ - `createAppServer(config)` - Creates and configures Express server
544
+ - `addDomain(domainConfig)` - Adds domain configuration for virtual hosting
545
+ - `addDevelopmentDomain(domain)` - Adds development domain pattern
546
+ - `setDomainMapping(mapping)` - Sets domain to configuration mapping
547
+ - `enableServeHome(app, callback)` - Enables homepage serving
548
+ - `serveStatics(app, staticPath)` - Serves static files
549
+ - `serveStaticsPath(app, route, staticPath)` - Serves static files on specific route
550
+ - `enableCSP(cspOptions)` - Enables Content Security Policy
551
+ - `listen(port)` - Starts server listening
552
+ - `close()` - Gracefully closes server
553
+
554
+ ### AppServerFactory HTTP/2 CDN Configuration
555
+
556
+ - `http2CdnEnabled` - Enable HTTP/2 CDN server (default: false)
557
+ - `http2CdnPort` - HTTP/2 CDN port (default: 8443)
558
+ - `http2CdnKeyPath` - CDN SSL private key path (falls back to `keyPath`)
559
+ - `http2CdnCertPath` - CDN SSL certificate path (falls back to `certPath`)
560
+ - `http2CdnHttpsChain` - CDN certificate chain path (falls back to `httpsChain`)
561
+ - `http2CdnStaticPaths` - Paths to serve from CDN (default: [])
562
+ - `http2CdnCorsOrigins` - Allowed CORS origins for CDN (default: [])
563
+ - `http2CdnCorsAllowAll` - Allow all origins (default: false)
564
+ - `http2CdnMimeTypes` - Override default MIME types (default: {})
565
+ - `http2CdnCacheConfig` - Override default cache config (default: {})
566
+
567
+ ### AppServerFactory Reverse Proxy Configuration
568
+
569
+ - `reverseProxyEnabled` - Enable reverse proxy (default: false)
570
+ - `reverseProxyRules` - Array of proxy rules (default: [])
571
+
572
+ ### Http2CdnServer Methods
573
+
574
+ - `create()` - Creates HTTP/2 secure server
575
+ - `listen()` - Starts listening on configured port
576
+ - `close()` - Gracefully closes HTTP/2 server
577
+
578
+ ### Http2CdnServer Configuration
579
+
580
+ - `port` - Server port (default: 8443)
581
+ - `keyPath` - SSL private key path
582
+ - `certPath` - SSL certificate path
583
+ - `httpsChain` - Certificate chain path (optional)
584
+ - `staticPaths` - Array of static file directories
585
+ - `cacheConfig` - Cache max-age per extension
586
+ - `allowHTTP1` - Allow HTTP/1.1 fallback (default: true)
587
+ - `corsOrigins` - Array of allowed origins (strings or RegExp)
588
+ - `corsAllowAll` - Allow all origins (default: false)
589
+ - `corsMethods` - Allowed HTTP methods (default: 'GET, OPTIONS')
590
+ - `corsHeaders` - Allowed request headers (default: 'Content-Type')
591
+ - `securityHeaders` - Custom security headers
592
+ - `varyHeader` - Vary header value (default: 'Accept-Encoding, Origin')
593
+ - `mimeTypes` - MIME type mappings
594
+
595
+ ### FileHandler Methods
596
+
597
+ - `exists(path)` - Checks if file or folder exists
598
+ - `createFolder(path)` - Creates folder with a recursive option
599
+ - `remove(path)` - Removes file or folder recursively
600
+ - `removeMultiple(filePaths)` - Removes multiple files from an array of paths
601
+ - `copyFile(source, destination)` - Copies file to destination
602
+ - `copyFolderSync(source, destination)` - Copies folder recursively
603
+ - `readFile(path)` - Reads file contents as string
604
+ - `writeFile(path, content)` - Writes content to file
605
+ - `fetchFileJson(path)` - Reads and parses JSON file
606
+ - `fetchFileContents(path)` - Reads file with validation
607
+ - `updateFileContents(path, content)` - Updates existing file
608
+ - `isFile(path)` - Checks if a path is a file
609
+ - `isFolder(path)` - Checks if a path is folder
610
+ - `getFilesInFolder(path, extensions)` - Lists files with optional filtering
611
+ - `validateFileType(path, type, allowedTypes, maxSize)` - Validates file type and size
612
+ - `detectFileType(path)` - Detects MIME type from file signature
613
+ - `generateSecureFilename(originalName)` - Generates cryptographically secure filename
614
+ - `quarantineFile(path, reason)` - Moves file to quarantine folder
615
+ - `createTempFile(prefix, extension)` - Creates a temporary file path
616
+ - `moveFile(from, to)` - Moves a file to new location
617
+ - `getFileSize(path)` - Gets file size in bytes
618
+ - `compareFiles(file1, file2)` - Compares file contents
619
+ - `getRelativePath(from, to)` - Calculates a relative path
620
+ - `walkDirectory(path, callback)` - Recursively processes a directory tree
621
+ - `getDirectorySize(path)` - Calculates total directory size
622
+ - `emptyDirectory(path)` - Removes all contents from directory
623
+
624
+ ### Encryptor Methods
625
+
626
+ - `encryptPassword(password)` - Hashes password with salt
627
+ - `validatePassword(password, hash)` - Validates password against hash
628
+ - `generateSecretKey()` - Generates 256-bit secret key
629
+ - `encryptData(data, key)` - Encrypts data with AES-256-GCM
630
+ - `decryptData(encryptedData, key)` - Decrypts AES-256-GCM data
631
+ - `generateSecureToken(length)` - Generates base64url token
632
+ - `generateTOTP(secret, timeStep)` - Generates time-based OTP
633
+ - `hashData(data, algorithm)` - Hashes data with specified algorithm
634
+ - `generateHMAC(data, secret, algorithm)` - Generates HMAC signature
635
+ - `verifyHMAC(data, secret, signature, algorithm)` - Verifies HMAC signature
636
+ - `constantTimeCompare(a, b)` - Performs constant-time string comparison
637
+
638
+ ### UploaderFactory Methods
639
+
640
+ - `createUploader(fields, buckets, allowedTypes)` - Creates multer upload middleware
641
+ - `validateFilenameSecurity(filename)` - Validates filename for security
642
+ - `validateFile(file, allowedType, callback)` - Validates a file during upload
643
+ - `validateFileContents(file, allowedType)` - Validates file content after upload
644
+ - `convertToRegex(key)` - Converts MIME type patterns to regex
645
+
646
+ ## Security Features
647
+
648
+ ### Path Traversal Protection
649
+ All file operations include comprehensive path validation to prevent directory traversal attacks and access to system files.
650
+
651
+ ### Secure File Upload
652
+ File uploads are validated at multiple levels including filename, MIME type, file extension, file size, and content validation using magic number detection. Failed uploads are automatically cleaned up using efficient file removal.
653
+
654
+ ### Rate Limiting
655
+ Configurable rate limiting with development mode detection for appropriate thresholds in different environments.
656
+
657
+ ### HTTPS Support
658
+ Full SSL/TLS support with SNI for multi-domain hosting and automatic certificate management.
659
+
660
+ ### HTTP/2 CDN Security
661
+ The HTTP/2 CDN server includes security headers, CORS validation with pattern matching, and query string stripping to prevent cache poisoning.
662
+
663
+ ### Input Validation
664
+ Built-in validators for common input types including email, username, strong passwords, alphanumeric strings, and IP addresses.
665
+
666
+ ### Cryptographic Security
667
+ Industry-standard encryption using PBKDF2 for passwords, AES-256-GCM for data encryption, and secure random generation for tokens.
668
+
669
+ ## Error Handling
670
+
671
+ All methods include comprehensive error handling with detailed error objects containing context information. Errors are logged appropriately and never expose sensitive system information.
672
+
673
+ ---
674
+
675
+ ## Documentation
676
+
677
+ [https://www.reldens.com/documentation/utils/](https://www.reldens.com/documentation/utils/)
678
+
679
+ Need something specific?
680
+
681
+ [Request a feature here: https://www.reldens.com/features-request](https://www.reldens.com/features-request)
682
+
683
+ ---
684
+
685
+ ### [Reldens](https://github.com/damian-pastorini/reldens/ "Reldens")
686
+
687
+ ##### [By DwDeveloper](https://www.dwdeveloper.com/ "DwDeveloper")