@reldens/server-utils 0.39.0 → 0.40.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.
Files changed (2) hide show
  1. package/CLAUDE.md +235 -0
  2. package/package.json +2 -2
package/CLAUDE.md ADDED
@@ -0,0 +1,235 @@
1
+ # CLAUDE.md
2
+
3
+ This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
4
+
5
+ ## Package Overview
6
+
7
+ **@reldens/server-utils** is a core utility package for server-side operations in Reldens. It provides:
8
+ - File system operations (FileHandler)
9
+ - HTTP/HTTPS server creation (AppServerFactory)
10
+ - File encryption (Encryptor)
11
+ - File upload handling (UploaderFactory)
12
+ - HTTP/2 CDN server (Http2CdnServer)
13
+ - Server configuration utilities
14
+
15
+ ## Key Commands
16
+
17
+ ```bash
18
+ # Run tests (if configured)
19
+ npm test
20
+ ```
21
+
22
+ ## Architecture
23
+
24
+ ### Core Classes
25
+
26
+ **FileHandler** (`lib/file-handler.js`):
27
+ - Singleton wrapper for Node.js fs and path modules
28
+ - Used instead of direct require('fs') or require('path') throughout Reldens
29
+ - Key file operations:
30
+ - `exists(filePath)` - Check if file/directory exists
31
+ - `readFile(filePath)` - Read file contents
32
+ - `writeFile(filePath, content)` - Write file
33
+ - `createFolder(folderPath)` - Create directory recursively
34
+ - `remove(fullPath)` - Remove file/folder recursively
35
+ - `copyFile(from, to)` - Copy file
36
+ - `copyFolderSync(from, to)` - Copy folder recursively
37
+ - `moveFile(from, to)` - Move/rename file
38
+ - Path operations:
39
+ - `joinPaths(...paths)` - Join path segments
40
+ - `getFileName(filePath)` - Get file name (basename)
41
+ - `getFolderName(filePath)` - Get directory name (dirname)
42
+ - `getRelativePath(from, to)` - Calculate relative path
43
+ - `normalizePath(filePath)` - Normalize path
44
+ - `isAbsolutePath(filePath)` - Check if path is absolute
45
+ - File inspection:
46
+ - `isFile(filePath)` - Check if path is a file
47
+ - `isFolder(dirPath)` - Check if path is a folder
48
+ - `getFileSize(filePath)` - Get file size in bytes
49
+ - `getFileStats(filePath)` - Get file stats
50
+ - `getFilesInFolder(dirPath, extensions)` - List files with optional filtering
51
+ - `fetchSubFoldersList(folder, options)` - Get subfolder list
52
+ - JSON operations:
53
+ - `fetchFileJson(filePath)` - Read and parse JSON file
54
+ - `isValidJson(filePath)` - Validate JSON file
55
+ - Security features:
56
+ - `generateSecureFilename(originalName)` - Generate secure random filename
57
+ - `validateFileType(filePath, type, allowedTypes, maxSize)` - Validate file
58
+ - `detectFileType(filePath)` - Detect MIME type from magic numbers
59
+ - `quarantineFile(filePath, reason)` - Move suspicious file to quarantine
60
+ - `isValidPath(filePath)` - Validate path for security
61
+ - `sanitizePath(filePath)` - Sanitize path string
62
+ - Advanced operations:
63
+ - `walkDirectory(dirPath, callback)` - Recursively process directory tree
64
+ - `getDirectorySize(dirPath)` - Calculate total directory size
65
+ - `emptyDirectory(dirPath)` - Remove all contents from directory
66
+ - `compareFiles(file1, file2)` - Compare file contents
67
+ - `appendToFile(filePath, content)` - Append to file
68
+ - `prependToFile(filePath, content)` - Prepend to file
69
+ - `replaceInFile(filePath, searchValue, replaceValue)` - Replace in file
70
+ - All methods include built-in error handling, no need for try/catch
71
+ - DO NOT use FileHandler.exists to validate other FileHandler methods
72
+ - DO NOT enclose FileHandler methods in try/catch blocks
73
+
74
+ **AppServerFactory** (`lib/app-server-factory.js`):
75
+ - Creates Express app servers with modular security components
76
+ - Supports HTTP, HTTPS, HTTP/2
77
+ - Key features:
78
+ - Virtual host management with SNI support
79
+ - HTTP/2 CDN server integration
80
+ - Reverse proxy with WebSocket support
81
+ - Development mode detection and configuration
82
+ - Security configurers (modular):
83
+ - `DevelopmentModeDetector` - Auto-detect development environment
84
+ - `ProtocolEnforcer` - HTTP/HTTPS protocol enforcement
85
+ - `SecurityConfigurer` - Helmet integration and XSS protection
86
+ - `CorsConfigurer` - CORS with dynamic origin validation
87
+ - `RateLimitConfigurer` - Global and endpoint-specific rate limiting
88
+ - `ReverseProxyConfigurer` - Domain-based reverse proxy
89
+ - Methods:
90
+ - `createAppServer(config)` - Create and configure server
91
+ - `addDomain(domainConfig)` - Add virtual host domain
92
+ - `addDevelopmentDomain(domain)` - Add development domain
93
+ - `enableServeHome(app, callback)` - Enable homepage serving
94
+ - `serveStatics(app, staticPath)` - Serve static files
95
+ - `enableCSP(cspOptions)` - Enable Content Security Policy
96
+ - `listen(port)` - Start server listening
97
+ - `close()` - Gracefully close server
98
+
99
+ **Encryptor** (`lib/encryptor.js`):
100
+ - Singleton for cryptographic operations
101
+ - Password hashing:
102
+ - `encryptPassword(password)` - Hash password with PBKDF2 (100k iterations, SHA-512)
103
+ - `validatePassword(password, storedPassword)` - Validate password against hash
104
+ - Data encryption:
105
+ - `encryptData(data, key)` - Encrypt data with AES-256-GCM
106
+ - `decryptData(encryptedData, key)` - Decrypt AES-256-GCM data
107
+ - `generateSecretKey()` - Generate 256-bit secret key
108
+ - Token generation:
109
+ - `generateSecureToken(length)` - Generate cryptographically secure token
110
+ - `generateTOTP(secret, timeStep)` - Generate time-based OTP
111
+ - Hashing and verification:
112
+ - `hashData(data, algorithm)` - Hash with SHA-256, SHA-512, or MD5
113
+ - `generateHMAC(data, secret, algorithm)` - Generate HMAC signature
114
+ - `verifyHMAC(data, secret, signature, algorithm)` - Verify HMAC signature
115
+ - `constantTimeCompare(a, b)` - Constant-time string comparison
116
+
117
+ **UploaderFactory** (`lib/uploader-factory.js`):
118
+ - File upload handling with Multer
119
+ - Multi-level security validation:
120
+ - Filename security validation
121
+ - MIME type validation
122
+ - File extension validation
123
+ - File size validation
124
+ - Content validation using magic numbers
125
+ - Dangerous extension filtering
126
+ - Features:
127
+ - Multiple file upload support with field mapping
128
+ - Secure filename generation option
129
+ - Automatic cleanup on validation failure
130
+ - Custom error response handling
131
+ - Per-field destination mapping
132
+ - Methods:
133
+ - `createUploader(fields, buckets, allowedFileTypes)` - Create upload middleware
134
+ - `validateFilenameSecurity(filename)` - Validate filename
135
+ - `validateFile(file, allowedType, callback)` - Validate during upload
136
+ - `validateFileContents(file, allowedType)` - Validate after upload
137
+ - `convertToRegex(key)` - Convert MIME type patterns to regex
138
+
139
+ **Http2CdnServer** (`lib/http2-cdn-server.js`):
140
+ - HTTP/2 secure server for CDN-like static file serving
141
+ - Features:
142
+ - Optimized for CSS, JavaScript, images, and fonts
143
+ - Dynamic CORS origin validation with regex pattern support
144
+ - Configurable cache headers per file extension
145
+ - Comprehensive MIME type detection
146
+ - HTTP/1.1 fallback support
147
+ - Security headers (X-Content-Type-Options, X-Frame-Options, Vary)
148
+ - Query string stripping for cache optimization
149
+ - Methods:
150
+ - `create()` - Create HTTP/2 secure server
151
+ - `listen()` - Start listening on configured port
152
+ - `close()` - Gracefully close server
153
+ - `handleStream(stream, headers)` - Handle HTTP/2 stream
154
+ - `resolveFilePath(requestPath)` - Resolve file path from request
155
+
156
+ ### Utility Classes
157
+
158
+ **ServerDefaultConfigurations** (`lib/server-default-configurations.js`):
159
+ - Static class providing default configurations
160
+ - `mimeTypes` - Comprehensive MIME type mappings for common file extensions
161
+ - `cacheConfig` - Default cache max-age settings (1 year for CSS/JS/fonts, 30 days for images)
162
+
163
+ **ServerFactoryUtils** (`lib/server-factory-utils.js`):
164
+ - Static utility methods for server operations
165
+ - `getCacheConfigForPath(path, cacheConfig)` - Get cache config for file path
166
+ - `validateOrigin(origin, corsOrigins, corsAllowAll)` - Validate CORS origin (supports strings and RegExp)
167
+ - `stripQueryString(url)` - Remove query string from URL
168
+
169
+ **ServerHeaders** (`lib/server-headers.js`):
170
+ - Centralized header management
171
+ - HTTP/2 headers configuration
172
+ - Express security headers
173
+ - Cache control headers
174
+ - Proxy forwarding headers
175
+ - `buildCacheControlHeader(maxAge)` - Build cache control header string
176
+
177
+ ### Security Configurers (in `lib/app-server-factory/`)
178
+
179
+ **DevelopmentModeDetector** (`development-mode-detector.js`):
180
+ - Auto-detects development environment
181
+ - Checks NODE_ENV, domain patterns, and configured domains
182
+ - Built-in patterns: localhost, 127.0.0.1, .local, .test, .dev, .staging, etc.
183
+ - `detect(config)` - Detect if in development mode
184
+ - `matchesPattern(domain)` - Check if domain matches development pattern
185
+
186
+ **ProtocolEnforcer** (`protocol-enforcer.js`):
187
+ - Enforces HTTP/HTTPS protocol consistency
188
+ - Development mode awareness
189
+ - Automatic redirects when protocol doesn't match configuration
190
+ - `setup(app, config)` - Setup protocol enforcement middleware
191
+
192
+ **SecurityConfigurer** (`security-configurer.js`):
193
+ - Helmet integration with CSP management
194
+ - XSS protection with request body sanitization
195
+ - Development-friendly CSP configuration
196
+ - Supports CSP directive merging or override
197
+ - `setupHelmet(app, config)` - Setup Helmet middleware
198
+ - `setupXssProtection(app, config)` - Setup XSS protection
199
+ - `enableCSP(app, cspOptions)` - Enable Content Security Policy
200
+ - `addExternalDomainsToCsp(directives, externalDomains)` - Add external domains to CSP
201
+
202
+ **CorsConfigurer** (`cors-configurer.js`):
203
+ - Dynamic CORS origin validation
204
+ - Development domain support with automatic port variations
205
+ - Credential support configuration
206
+ - `setup(app, config)` - Setup CORS middleware
207
+ - `extractDevelopmentOrigins(domainMapping)` - Extract development origins
208
+ - `normalizeHost(originOrHost)` - Normalize host string
209
+
210
+ **RateLimitConfigurer** (`rate-limit-configurer.js`):
211
+ - Global and endpoint-specific rate limiting
212
+ - Development mode multiplier for lenient limits
213
+ - IP-based key generation option
214
+ - `setup(app, config)` - Setup global rate limiting
215
+ - `createHomeLimiter()` - Create homepage-specific limiter
216
+
217
+ **ReverseProxyConfigurer** (`reverse-proxy-configurer.js`):
218
+ - Domain-based reverse proxy routing
219
+ - WebSocket support
220
+ - SSL termination
221
+ - Header preservation (X-Forwarded-For, X-Forwarded-Proto, X-Forwarded-Host)
222
+ - Virtual host integration
223
+ - Graceful error handling (502 Bad Gateway, 504 Gateway Timeout)
224
+ - `setup(app, config)` - Setup reverse proxy
225
+ - `createProxyMiddleware(rule)` - Create proxy middleware for rule
226
+ - `handleProxyError(err, req, res)` - Handle proxy errors
227
+
228
+ ## Important Notes
229
+
230
+ - **ALWAYS use FileHandler** instead of Node.js fs/path modules
231
+ - FileHandler methods have built-in error handling - no try/catch needed
232
+ - DO NOT enclose FileHandler methods in try/catch blocks
233
+ - DO NOT use FileHandler.exists to validate other FileHandler methods (e.g., before createFolder)
234
+ - AppServerFactory handles all Express server configuration
235
+ - All server utilities support both HTTP and HTTPS
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@reldens/server-utils",
3
3
  "scope": "@reldens",
4
- "version": "0.39.0",
4
+ "version": "0.40.0",
5
5
  "description": "Reldens - Server Utils",
6
6
  "author": "Damian A. Pastorini",
7
7
  "license": "MIT",
@@ -40,7 +40,7 @@
40
40
  "compression": "1.8.1",
41
41
  "cors": "2.8.5",
42
42
  "express": "4.21.2",
43
- "express-rate-limit": "8.1.0",
43
+ "express-rate-limit": "8.2.1",
44
44
  "express-session": "1.18.2",
45
45
  "helmet": "8.1.0",
46
46
  "http-proxy-middleware": "3.0.5",