Package Exports
- @reldens/server-utils
- @reldens/server-utils/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@reldens/server-utils) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
Reldens - Server Utils
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.
Features
AppServerFactory
- Complete Express.js server configuration with modular security
- HTTPS/HTTP server creation with SSL certificate management
- HTTP/2 CDN server with optimized static asset delivery
- Optimized static asset caching for CSS, JS, fonts, and images
- SNI (Server Name Indication) support for multi-domain hosting
- Virtual host management with domain mapping
- Development mode detection with appropriate configurations
- CORS configuration with flexible origin management
- Rate limiting with customizable thresholds
- Reverse proxy support for routing multiple domains to backend servers
- Security headers and XSS protection
- Helmet integration for enhanced security
- Protocol enforcement (HTTP to HTTPS redirection)
- Trusted proxy configuration
- Request parsing with size limits and validation
- Static file serving with security headers
- Compression middleware with smart filtering
- Input validation utilities
- Custom error handling with callback support
Http2CdnServer
- Dedicated HTTP/2 server for static asset delivery
- Optimized for serving CSS, JavaScript, images, and fonts
- Dynamic CORS origin validation with regex pattern support
- Configurable cache headers per file extension
- Comprehensive MIME type detection
- HTTP/1.1 fallback support
- Security headers (X-Content-Type-Options, X-Frame-Options, Vary)
- Standalone or integrated with AppServerFactory
- Multiple static path support
- Separate SSL certificate support from main server
- Comprehensive error handling (server, TLS, session, stream errors)
- Custom error handler callback support
Modular Security Components
The AppServerFactory now uses specialized security configurers:
- CorsConfigurer - Dynamic CORS origin validation with development domain support
- DevelopmentModeDetector - Automatic development environment detection
- ProtocolEnforcer - Protocol redirection with development mode awareness
- RateLimitConfigurer - Global and endpoint-specific rate limiting
- ReverseProxyConfigurer - Domain-based reverse proxy with WebSocket support
- SecurityConfigurer - Helmet integration with CSP management and XSS protection
- ServerErrorHandler - Centralized error handling with custom callback support
FileHandler
- Secure file system operations with path validation
- File and folder creation, copying, and removal
- JSON file parsing and validation
- File type detection based on magic numbers
- Secure filename generation
- Path sanitization and traversal protection
- File permissions checking
- Folder content listing and filtering
- Temporary file creation
- File quarantine functionality for security threats
- Binary file head reading for type detection
- Directory walking with callback processing
- File comparison and relative path calculations
- Comprehensive error handling with detailed context
- Read stream creation for efficient file streaming
- File modification time retrieval
Encryptor
- Password hashing using PBKDF2 with configurable iterations
- Password validation against stored hashes
- AES-256-GCM data encryption and decryption
- Secure token generation with a customizable length
- TOTP (Time-based One-Time Password) generation
- Data hashing with multiple algorithms (SHA-256, SHA-512, MD5)
- HMAC generation and verification
- Constant-time string comparison for security
- Cryptographically secure random value generation
UploaderFactory
- Multer-based file upload handling with security validation
- Multiple file upload support with field mapping
- File type validation using MIME types and extensions
- Filename security validation and sanitization
- File size limits and upload count restrictions
- Secure filename generation option
- File content validation based on magic numbers
- Dangerous file extension filtering
- Automatic file cleanup on validation failure
- Custom error response handling
- Upload destination mapping per field
Installation
npm install @reldens/server-utilsQuick Start
Basic Server Setup
const { AppServerFactory } = require('@reldens/server-utils');
let appServerFactory = new AppServerFactory();
let serverResult = appServerFactory.createAppServer({
port: 3000,
useHttps: false,
autoListen: true,
useCompression: true
});
if(serverResult){
let { app, appServer } = serverResult;
console.log('Server running on port 3000');
}HTTP/2 CDN Server with Express
Serve your main application through Express on port 443, and static assets through HTTP/2 CDN on port 8443:
let appServerFactory = new AppServerFactory();
let serverResult = appServerFactory.createAppServer({
port: 443,
useHttps: true,
keyPath: '/ssl/main-server.key',
certPath: '/ssl/main-server.crt',
http2CdnEnabled: true,
http2CdnPort: 8443,
http2CdnKeyPath: '/ssl/cdn-server.key',
http2CdnCertPath: '/ssl/cdn-server.crt',
http2CdnStaticPaths: ['/var/www/public'],
http2CdnCorsOrigins: [
'https://example.com',
/^https:\/\/(www\.)?example\.(com|net)$/
],
autoListen: true
});
if(serverResult){
let { app, appServer, http2CdnServer } = serverResult;
console.log('Express server on port 443');
console.log('HTTP/2 CDN server on port 8443');
}Note: If http2CdnKeyPath and http2CdnCertPath are not specified, the CDN server will use the same certificates as the main server (keyPath and certPath).
Browser usage:
<link rel="stylesheet" href="https://cdn.example.com:8443/css/style.css">
<script src="https://cdn.example.com:8443/js/app.js"></script>Standalone HTTP/2 CDN Server
const { Http2CdnServer } = require('@reldens/server-utils');
let cdnServer = new Http2CdnServer();
cdnServer.port = 8443;
cdnServer.keyPath = '/ssl/cdn.key';
cdnServer.certPath = '/ssl/cdn.crt';
cdnServer.staticPaths = ['/var/www/public', '/var/www/assets'];
cdnServer.corsOrigins = [
'https://main-site.com',
/^https:\/\/(new\.)?((site1|site2)\.(com|net))$/
];
if(cdnServer.create()){
cdnServer.listen();
console.log('HTTP/2 CDN running on port 8443');
}Custom Error Handling
Configure custom error handlers for server errors:
let appServerFactory = new AppServerFactory();
appServerFactory.onError = (errorData) => {
console.error('Server error:', errorData.key);
console.error('Error details:', errorData.error);
console.error('Context:', errorData);
};
let serverResult = appServerFactory.createAppServer({
port: 443,
useHttps: true,
http2CdnEnabled: true,
autoListen: true
});The onError callback receives structured error data:
instanceName- Name of the component (e.g., 'http2CdnServer', 'appServerFactory')instance- Reference to the component instancekey- Error type identifier (e.g., 'server-error', 'tls-client-error', 'proxy-error')error- The actual error object...context- Additional context data (port, path, hostname, etc.)
HTTPS Server with Optimized Caching
let appServerFactory = new AppServerFactory();
let serverResult = appServerFactory.createAppServer({
port: 443,
useHttps: true,
keyPath: '/ssl/server.key',
certPath: '/ssl/server.crt',
autoListen: true
});Cache configuration is automatic with defaults:
- CSS/JS: 1 year
- Fonts: 1 year
- Images: 30 days
Override cache settings if needed:
let appServerFactory = new AppServerFactory();
appServerFactory.cacheConfig = {
'.css': 86400,
'.js': 86400,
'.png': 604800
};
let serverResult = appServerFactory.createAppServer({
useHttps: true,
});File Operations
const { FileHandler } = require('@reldens/server-utils');
// Read a JSON configuration file
let config = FileHandler.fetchFileJson('/path/to/config.json');
if(config){
console.log('Configuration loaded:', config);
}
// Create a folder securely
if(FileHandler.createFolder('/path/to/new/folder')){
console.log('Folder created successfully');
}
// Generate a secure filename
let secureFilename = FileHandler.generateSecureFilename('user-upload.jpg');
console.log('Secure filename:', secureFilename);
// Create a read stream for efficient file handling
let stream = FileHandler.createReadStream('/path/to/large-file.txt');
if(stream){
stream.pipe(response);
}
// Get file modification time
let modTime = FileHandler.getFileModificationTime('/path/to/file.txt');
if(modTime){
console.log('Last modified:', modTime);
}Password Encryption
const { Encryptor } = require('@reldens/server-utils');
// Hash a password
let hashedPassword = Encryptor.encryptPassword('userPassword123');
if(hashedPassword){
console.log('Password hashed:', hashedPassword);
}
// Validate password
let isValid = Encryptor.validatePassword('userPassword123', hashedPassword);
console.log('Password valid:', isValid);
// Generate secure token
let secureToken = Encryptor.generateSecureToken(32);
console.log('Secure token:', secureToken);File Upload Configuration
const { UploaderFactory } = require('@reldens/server-utils');
let uploaderFactory = new UploaderFactory({
maxFileSize: 10 * 1024 * 1024, // 10MB
mimeTypes: {
image: ['image/jpeg', 'image/png', 'image/gif'],
document: ['application/pdf', 'text/plain']
},
allowedExtensions: {
image: ['.jpg', '.jpeg', '.png', '.gif'],
document: ['.pdf', '.txt']
},
applySecureFileNames: true
});
let uploader = uploaderFactory.createUploader(
[{ name: 'avatar' }, { name: 'document' }],
{ avatar: '/uploads/avatars', document: '/uploads/docs' },
{ avatar: 'image', document: 'document' }
);
// Use with Express
app.post('/upload', uploader, (req, res) => {
console.log('Files uploaded:', req.files);
res.json({ success: true });
});Advanced Configuration
HTTP/2 CDN with Separate Certificates
Configure separate SSL certificates for your CDN server:
let appServerFactory = new AppServerFactory();
let serverResult = appServerFactory.createAppServer({
useHttps: true,
port: 443,
keyPath: '/ssl/app-server.key',
certPath: '/ssl/app-server.crt',
http2CdnEnabled: true,
http2CdnPort: 8443,
http2CdnKeyPath: '/ssl/cdn-server.key',
http2CdnCertPath: '/ssl/cdn-server.crt',
http2CdnHttpsChain: '/ssl/cdn-chain.pem',
http2CdnStaticPaths: ['/var/www/public'],
http2CdnCorsOrigins: [
'https://main-site.com',
'https://app.main-site.com',
/^https:\/\/(new\.)?main-site\.(com|net)$/
],
http2CdnCacheConfig: {
'.css': 31536000,
'.js': 31536000,
'.woff2': 31536000,
'.png': 2592000
}
});HTTP/2 CDN with Multiple Origins
The HTTP/2 CDN server supports multiple origin validation methods:
let appServerFactory = new AppServerFactory();
let serverResult = appServerFactory.createAppServer({
http2CdnEnabled: true,
http2CdnPort: 8443,
http2CdnStaticPaths: ['/var/www/public'],
http2CdnCorsOrigins: [
'https://main-site.com',
'https://app.main-site.com',
/^https:\/\/(new\.)?main-site\.(com|net)$/,
/^https:\/\/(app|admin)\.secondary-site\.com$/
]
});HTTPS Server with Multiple Domains
let appServerFactory = new AppServerFactory();
appServerFactory.addDomain({
hostname: 'example.com',
keyPath: '/ssl/example.com.key',
certPath: '/ssl/example.com.crt',
aliases: ['www.example.com']
});
appServerFactory.addDomain({
hostname: 'api.example.com',
keyPath: '/ssl/api.example.com.key',
certPath: '/ssl/api.example.com.crt'
});
let serverResult = appServerFactory.createAppServer({
useHttps: true,
useVirtualHosts: true,
keyPath: '/ssl/default.key',
certPath: '/ssl/default.crt',
port: 443,
enforceProtocol: true,
developmentMultiplier: 10
});Development Mode Configuration
let appServerFactory = new AppServerFactory();
// Add development domains (automatically detected)
appServerFactory.addDevelopmentDomain('localhost');
appServerFactory.addDevelopmentDomain('dev.myapp.local');
let serverResult = appServerFactory.createAppServer({
port: 3000,
corsOrigin: ['http://localhost:3000', 'http://dev.myapp.local:3000'],
developmentMultiplier: 5, // More lenient rate limiting in dev
developmentPorts: [3000, 3001, 8080],
developmentExternalDomains: {
'script-src': ['https://cdn.example.com'],
'style-src': ['https://fonts.googleapis.com']
}
});Custom Security Configuration
let appServerFactory = new AppServerFactory();
let serverResult = appServerFactory.createAppServer({
useHelmet: true,
helmetConfig: {
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
styleSrc: ["'self'", "'unsafe-inline'"],
scriptSrc: ["'self'"]
}
}
},
globalRateLimit: 100, // requests per window
windowMs: 60000, // 1 minute
maxRequests: 30,
trustedProxy: '127.0.0.1',
useXssProtection: true,
sanitizeOptions: {allowedTags: [], allowedAttributes: {}}
});External Domains Configuration
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:
let serverResult = appServerFactory.createAppServer({
developmentExternalDomains: {
// Both formats work - choose whichever you prefer
'scriptSrc': ['https://cdn.example.com'], // camelCase
'script-src': ['https://platform-api.example.com'], // kebab-case (auto-converted)
'styleSrc': ['https://fonts.googleapis.com'], // camelCase
'font-src': ['https://fonts.gstatic.com'] // kebab-case (auto-converted)
}
});The system automatically adds these domains to both the base directive and the corresponding -elem variant (e.g., scriptSrc and scriptSrcElem).
Helmet CSP Configuration Options
The security configurer provides flexible CSP directive handling with merge or override behavior:
Merging Directives (Default)
By default, custom CSP directives are merged with the security defaults, allowing you to add additional sources without redefining all directives:
let serverResult = appServerFactory.createAppServer({
useHelmet: true,
helmetConfig: {
contentSecurityPolicy: {
directives: {
// These will be ADDED to the default directives
scriptSrc: ['https://analytics.example.com'],
styleSrc: ['https://cdn.example.com']
}
}
}
});
// Result: default directives + your additional sourcesOverriding Directives
Set overrideDirectives: true to completely replace the default directives with your custom configuration:
let serverResult = appServerFactory.createAppServer({
useHelmet: true,
helmetConfig: {
contentSecurityPolicy: {
overrideDirectives: true, // Replace defaults entirely
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "https://trusted-cdn.com"],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", "data:", "https:"],
fontSrc: ["'self'"],
connectSrc: ["'self'"],
frameAncestors: ["'none'"],
baseUri: ["'self'"],
formAction: ["'self'"]
}
}
}
});Reverse Proxy Configuration
Route multiple domains to different backend servers through a single SSL-enabled entry point:
let appServerFactory = new AppServerFactory();
let serverResult = appServerFactory.createAppServer({
port: 443,
useHttps: true,
useVirtualHosts: true,
keyPath: '/ssl/server.key',
certPath: '/ssl/server.crt',
reverseProxyEnabled: true,
reverseProxyRules: [
{
hostname: 'demo.reldens.com',
target: 'https://localhost:8444',
pathPrefix: '/',
websocket: true,
secure: false
},
{
hostname: 'api.example.com',
target: 'https://localhost:8445',
pathPrefix: '/',
websocket: false
}
],
autoListen: true
});Reverse Proxy Features
- Multiple backend routing with independent configuration per domain
- WebSocket support for real-time applications
- SSL termination at entry point
- Header preservation (X-Forwarded-For, X-Forwarded-Proto, X-Forwarded-Host)
- Virtual host integration
- Path-based routing
- Comprehensive error handling with proper HTTP status codes:
- 502 Bad Gateway for connection refused errors
- 504 Gateway Timeout for timeout errors
- 500 Internal Server Error for other proxy errors
Rule Properties
hostname(string, required) - Domain to matchtarget(string, required) - Backend URLpathPrefix(string, optional) - Path prefix, default: '/'websocket(boolean, optional) - Enable WebSocket, default: truechangeOrigin(boolean, optional) - Change origin header, default: truesecure(boolean, optional) - Verify SSL certificates, default: falselogLevel(string, optional) - 'debug', 'info', 'warn', 'error', 'silent'
Example: Multiple Game Servers
reverseProxyRules: [
{ hostname: 'demo.game.com', target: 'https://localhost:8444', websocket: true },
{ hostname: 'staging.game.com', target: 'https://localhost:8445', websocket: true }
]API Reference
AppServerFactory Methods
createAppServer(config)- Creates and configures Express serveraddDomain(domainConfig)- Adds domain configuration for virtual hostingaddDevelopmentDomain(domain)- Adds development domain patternsetDomainMapping(mapping)- Sets domain to configuration mappingenableServeHome(app, callback)- Enables homepage servingserveStatics(app, staticPath)- Serves static filesserveStaticsPath(app, route, staticPath)- Serves static files on specific routeenableCSP(cspOptions)- Enables Content Security Policylisten(port)- Starts server listeningclose()- Gracefully closes server
AppServerFactory HTTP/2 CDN Configuration
http2CdnEnabled- Enable HTTP/2 CDN server (default: false)http2CdnPort- HTTP/2 CDN port (default: 8443)http2CdnKeyPath- CDN SSL private key path (falls back tokeyPath)http2CdnCertPath- CDN SSL certificate path (falls back tocertPath)http2CdnHttpsChain- CDN certificate chain path (falls back tohttpsChain)http2CdnStaticPaths- Paths to serve from CDN (default: [])http2CdnCorsOrigins- Allowed CORS origins for CDN (default: [])http2CdnCorsAllowAll- Allow all origins (default: false)http2CdnMimeTypes- Override default MIME types (default: {})http2CdnCacheConfig- Override default cache config (default: {})
AppServerFactory Reverse Proxy Configuration
reverseProxyEnabled- Enable reverse proxy (default: false)reverseProxyRules- Array of proxy rules (default: [])
AppServerFactory Error Handling
onError- Custom error handler callback function receiving error data:instanceName- Component name (e.g., 'appServerFactory', 'http2CdnServer')instance- Component instance referencekey- Error type identifier (e.g., 'server-error', 'virtual-host-error')error- The error object- Additional context data (port, hostname, path, etc.)
Http2CdnServer Methods
create()- Creates HTTP/2 secure serverlisten()- Starts listening on configured portclose()- Gracefully closes HTTP/2 server
Http2CdnServer Configuration
port- Server port (default: 8443)keyPath- SSL private key pathcertPath- SSL certificate pathhttpsChain- Certificate chain path (optional)staticPaths- Array of static file directoriescacheConfig- Cache max-age per extensionallowHTTP1- Allow HTTP/1.1 fallback (default: true)corsOrigins- Array of allowed origins (strings or RegExp)corsAllowAll- Allow all origins (default: false)corsMethods- Allowed HTTP methods (default: 'GET, OPTIONS')corsHeaders- Allowed request headers (default: 'Content-Type')securityHeaders- Custom security headersvaryHeader- Vary header value (default: 'Accept-Encoding, Origin')mimeTypes- MIME type mappingsonError- Custom error handler callback
FileHandler Methods
exists(path)- Checks if file or folder existscreateFolder(path)- Creates folder with a recursive optionremove(path)- Removes file or folder recursivelyremoveMultiple(filePaths)- Removes multiple files from an array of pathscopyFile(source, destination)- Copies file to destinationcopyFolderSync(source, destination)- Copies folder recursivelyreadFile(path)- Reads file contents as stringwriteFile(path, content)- Writes content to filefetchFileJson(path)- Reads and parses JSON filefetchFileContents(path)- Reads file with validationupdateFileContents(path, content)- Updates existing fileisFile(path)- Checks if a path is a fileisFolder(path)- Checks if a path is foldergetFilesInFolder(path, extensions)- Lists files with optional filteringvalidateFileType(path, type, allowedTypes, maxSize)- Validates file type and sizedetectFileType(path)- Detects MIME type from file signaturegenerateSecureFilename(originalName)- Generates cryptographically secure filenamequarantineFile(path, reason)- Moves file to quarantine foldercreateTempFile(prefix, extension)- Creates a temporary file pathmoveFile(from, to)- Moves a file to new locationgetFileSize(path)- Gets file size in bytescompareFiles(file1, file2)- Compares file contentsgetRelativePath(from, to)- Calculates a relative pathwalkDirectory(path, callback)- Recursively processes a directory treegetDirectorySize(path)- Calculates total directory sizeemptyDirectory(path)- Removes all contents from directorycreateReadStream(path, options)- Creates readable stream for filegetFileModificationTime(path)- Gets file last modification time
Encryptor Methods
encryptPassword(password)- Hashes password with saltvalidatePassword(password, hash)- Validates password against hashgenerateSecretKey()- Generates 256-bit secret keyencryptData(data, key)- Encrypts data with AES-256-GCMdecryptData(encryptedData, key)- Decrypts AES-256-GCM datagenerateSecureToken(length)- Generates base64url tokengenerateTOTP(secret, timeStep)- Generates time-based OTPhashData(data, algorithm)- Hashes data with specified algorithmgenerateHMAC(data, secret, algorithm)- Generates HMAC signatureverifyHMAC(data, secret, signature, algorithm)- Verifies HMAC signatureconstantTimeCompare(a, b)- Performs constant-time string comparison
UploaderFactory Methods
createUploader(fields, buckets, allowedTypes)- Creates multer upload middlewarevalidateFilenameSecurity(filename)- Validates filename for securityvalidateFile(file, allowedType, callback)- Validates a file during uploadvalidateFileContents(file, allowedType)- Validates file content after uploadconvertToRegex(key)- Converts MIME type patterns to regex
ServerErrorHandler Methods
handleError(onErrorCallback, instanceName, instance, key, error, context)- Static method for centralized error handlingonErrorCallback- Custom error handler function (optional)instanceName- Name of the component ('http2CdnServer', 'appServerFactory', etc.)instance- Reference to the component instancekey- Error type identifiererror- The error objectcontext- Additional context object (port, hostname, path, etc.)
Security Features
Path Traversal Protection
All file operations include comprehensive path validation to prevent directory traversal attacks and access to system files.
Secure File Upload
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.
Rate Limiting
Configurable rate limiting with development mode detection for appropriate thresholds in different environments.
HTTPS Support
Full SSL/TLS support with SNI for multi-domain hosting and automatic certificate management.
HTTP/2 CDN Security
The HTTP/2 CDN server includes security headers, CORS validation with pattern matching, and query string stripping to prevent cache poisoning.
Input Validation
Built-in validators for common input types including email, username, strong passwords, alphanumeric strings, and IP addresses.
Cryptographic Security
Industry-standard encryption using PBKDF2 for passwords, AES-256-GCM for data encryption, and secure random generation for tokens.
Error Handling
All server components include comprehensive error handling with centralized error management through the ServerErrorHandler class. Custom error handlers can be configured via the onError callback to process errors according to application requirements. Errors are logged appropriately and never expose sensitive system information.
Error handling features:
- Centralized error management with ServerErrorHandler
- Custom error callback support across all components
- Structured error context with instance details and metadata
- Graceful HTTP status codes for proxy errors (502, 504, 500)
- TLS and session error handling for HTTP/2 servers
- Virtual host and SNI certificate error handling
Documentation
https://www.reldens.com/documentation/utils/
Need something specific?
Request a feature here: https://www.reldens.com/features-request
