@reldens/server-utils API Reference
Complete API documentation for @reldens/server-utils classes used throughout Reldens.
FileHandler (lib/file-handler.js)
Singleton wrapper for Node.js fs and path modules. Used instead of direct require('fs') or require('path') throughout Reldens.
File operations
- exists(filePath) - check if a file or directory exists.
- readFile(filePath) - read the file contents.
- writeFile(filePath, content) - write a file.
- createFolder(folderPath) - create a directory recursively.
- remove(fullPath) - remove a file or folder recursively.
- copyFile(from, to) - copy a file.
- copyFolderSync(from, to) - copy a folder recursively.
- moveFile(from, to) - move or rename a file.
Path operations
- joinPaths(...paths) - join path segments.
- getFileName(filePath) - file name (basename).
- getFolderName(filePath) - directory name (dirname).
- getRelativePath(from, to) - calculate a relative path.
- normalizePath(filePath) - normalize a path.
- isAbsolutePath(filePath) - check if a path is absolute.
File inspection
- isFile(filePath) - check if a path is a file.
- isFolder(dirPath) - check if a path is a folder.
- getFileSize(filePath) - file size in bytes.
- getFileStats(filePath) - file stats.
- getFilesInFolder(dirPath, extensions) - list files with optional extension filtering.
- fetchSubFoldersList(folder, options) - subfolders list.
JSON operations
- fetchFileJson(filePath) - read and parse a JSON file.
- isValidJson(filePath) - validate a JSON file.
Security features
- generateSecureFilename(originalName) - generate a secure random filename.
- validateFileType(filePath, type, allowedTypes, maxSize) - validate a file.
- detectFileType(filePath) - detect the MIME type from magic numbers.
- quarantineFile(filePath, reason) - move a suspicious file to quarantine.
- isValidPath(filePath) - validate a path for security.
- sanitizePath(filePath) - sanitize a path string.
Advanced operations
- walkDirectory(dirPath, callback) - recursively process a directory tree.
- getDirectorySize(dirPath) - total directory size.
- emptyDirectory(dirPath) - remove all the contents of a directory.
- compareFiles(file1, file2) - compare file contents.
- appendToFile(filePath, content), prependToFile(filePath, content) - append or prepend to a file.
- replaceInFile(filePath, searchValue, replaceValue) - replace in a file.
- createReadStream(filePath, options) - readable stream for a file.
- getFileModificationTime(filePath) - file last modification time.
Important notes
- All methods include built-in error handling - no need for try / catch.
- Do NOT use FileHandler.exists to validate other FileHandler methods.
- Do NOT enclose FileHandler methods in try / catch blocks.
AppServerFactory (lib/app-server-factory.js)
Creates Express app servers with modular security components. Supports HTTP, HTTPS, HTTP/2.
Features:
- Virtual host management with SNI support.
- HTTP/2 CDN server integration.
- Reverse proxy with WebSocket support.
- Development mode detection and configuration.
- Request logging middleware.
- Lifecycle event dispatching.
Key configuration properties
- useVirtualHosts and domains - virtual hosts with their certificates (SNI), one entry per domain.
- http2CdnDomains - array of domain configurations for HTTP/2 CDN multi-certificate SNI (optional).
- http2CdnSecurityHeaders - replaces the default security headers sent by the HTTP/2 CDN server.
- reverseProxyEnabled and reverseProxyRules - per-host proxy rules.
- helmetConfig - Helmet middleware options (CSP, HSTS, etc.).
- trustedProxy - the only source of trust for the forwarding headers; the client address is resolved from the socket peer otherwise. The same trust function is used by the reverse proxy, the HTTP/2 CDN server and the ClientAddressGuard.
- ipLists - allow and deny address lists ({enabled, allow, deny}).
- globalRateLimit - switch for the global rate limiter (off by default), with maxRequests (30) requests per windowMs (60000), multiplied by developmentMultiplier (10) in development mode. The proxied requests and WebSocket upgrades count in the same limit.
- onError - custom error handler callback for server errors.
- onRequestSuccess - callback for successful requests.
- onRequestError - callback for failed requests.
- onEvent - callback for lifecycle events.
The callbacks and their data structures are described in @reldens/server-utils Architecture.
Methods
- createAppServer(config) - create and configure the server, then attach the reverse proxy WebSocket upgrade listener to it.
- createHttp2CdnServer() - create the HTTP/2 CDN server with optional multi-certificate SNI.
- addDomain(domainConfig) - add a virtual host domain.
- addDevelopmentDomain(domain) - add a development domain.
- dispatch(eventName, eventData) - dispatch a lifecycle event (wrapper for EventDispatcher).
- handleError(errorType, error, context) - handle and report an error (wrapper for ServerErrorHandler).
- enableServeHome(app, callback) - enable homepage serving.
- serveStatics(app, statics) - serve static files.
- serveStaticsPath(app, staticsPath, statics) - serve static files under a path.
- setDomainMapping(mapping) - set the domain mapping passed to the CorsConfigurer for the development origins.
- enableCSP(cspOptions) - enable the Content Security Policy.
- listen(port) - start listening.
- attachClientAddressGuard(server) - attach a ClientAddressGuard to a server already bound by the application (for example the Colyseus transport server, after its listen), using the app trust proxy function and the IP lists.
- close() - gracefully close the server.
Security configurers
- DevelopmentModeDetector - auto-detect the development environment.
- ProtocolEnforcer - HTTP / HTTPS protocol enforcement.
- SecurityConfigurer - Helmet integration and XSS protection.
- CorsConfigurer - CORS with dynamic origin validation.
- RateLimitConfigurer - global and endpoint-specific rate limiting.
- ReverseProxyConfigurer - domain-based reverse proxy.
- IpListsConfigurer - allow and deny address lists.
- ClientAddressGuard - client address resolution for the raw server requests.
Their methods are listed in the Security Configurers section below.
Encryptor (lib/encryptor.js)
Singleton for cryptographic operations.
Password hashing
- encryptPassword(password) - hash a password with PBKDF2 (100k iterations, SHA-512).
- validatePassword(password, storedPassword) - async, validates a password against the stored hash with the asynchronous pbkdf2, so it does not block the event loop. Always await it: an un-awaited Promise is truthy.
Data encryption
- encryptData(data, key) - encrypt data with AES-256-GCM.
- decryptData(encryptedData, key) - decrypt AES-256-GCM data.
- generateSecretKey() - generate a 256-bit secret key.
Token generation
- generateSecureToken(length) - generate a cryptographically secure token.
- generateTOTP(secret, timeStep) - generate a time-based OTP.
Hashing and verification
- hashData(data, algorithm) - hash with SHA-256, SHA-512 or MD5.
- generateHMAC(data, secret, algorithm) - generate an HMAC signature.
- verifyHMAC(data, secret, signature, algorithm) - verify an HMAC signature through constantTimeCompare.
- constantTimeCompare(a, b) - constant-time string comparison, returns false (never throws) when the byte lengths differ.
UploaderFactory (lib/uploader-factory.js)
File upload handling with Multer.
Security validation
- Filename security validation.
- MIME type validation.
- File extension validation.
- File size validation.
- Content validation using magic numbers.
- Dangerous extension filtering.
Features
- Multiple file upload support with field mapping.
- Secure filename generation option, through FileHandler.generateSecureFilename.
- Automatic cleanup on validation failure.
- Custom error response handling.
- Per-field destination mapping.
Methods
- createUploader(fields, buckets, allowedFileTypes) - create the upload middleware.
- validateFilenameSecurity(filename) - validate a filename.
- validateFile(file, allowedType, callback) - validate during the upload.
- validateFileContents(file, allowedType) - validate after the upload.
- convertToRegex(key) - convert MIME type patterns to regex.
Http2CdnServer (lib/http2-cdn-server.js)
HTTP/2 secure server for CDN-like static file serving.
Features
- Multi-certificate SNI support for multiple domains.
- Client address and hostname resolved from the socket and the Host header. The X-Forwarded-For and X-Forwarded-Host values are only used when the socket peer passes trustProxyFunction, set by AppServerFactory from the app trust proxy setting (trustedProxy).
- Optimized for 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 (allowHTTP1: true).
- Security headers (X-Content-Type-Options, X-Frame-Options, Vary), replaceable through securityHeaders, for example to send a Cross-Origin-Resource-Policy header.
- Query string stripping for cache optimization.
- Comprehensive error handling (server, TLS, session, stream errors).
Configuration properties
- domains - array of domain configurations for multi-certificate SNI (optional).
- keyPath - path to the SSL key file (backward compatibility, single certificate mode).
- certPath - path to the SSL certificate file (backward compatibility, single certificate mode).
- onError - custom error handler callback for server errors.
- onRequestSuccess - callback for successful requests.
- onRequestError - callback for failed requests.
- onEvent - callback for lifecycle events.
Multi-certificate configuration example:
domains: [
{hostname: 'cdn.domain1.com', keyPath: '/path/to/key1.pem', certPath: '/path/to/cert1.pem'},
{hostname: 'cdn.domain2.com', keyPath: '/path/to/key2.pem', certPath: '/path/to/cert2.pem'}
]
Methods
- create() - create the HTTP/2 secure server with SNI support.
- listen() - start listening on the configured port.
- close() - gracefully close the server.
- dispatch(eventName, eventData) - dispatch a lifecycle event (wrapper for EventDispatcher).
- handleError(errorType, error, context) - handle and report an error (wrapper for ServerErrorHandler).
- handleStream(stream, headers) - handle an HTTP/2 stream.
- handleHttp1Request(req, res) - handle HTTP/1.1 fallback requests.
- resolveRequestOrigin(headers, socket, hostHeaderName) - resolve the {hostname, ip} sent to the request callbacks, with the forwarding headers only from a trusted peer.
- resolveFilePath(requestPath) - resolve the file path from the request.
- setupEventHandlers() - configure the server error event handlers.
- setupDomainConfiguration() - configure single or multi-certificate mode.
- validateCertificates() - validate that all the domain certificates exist.
- buildSniContexts() - build the TLS contexts for each domain.
- getSniCallback() - SNI callback for the certificate selection.
- buildServerOptions() - build the HTTP/2 server options with SNI support.
Utility Classes
PackageResolver (lib/package-resolver.js)
Singleton that loads a package from the project node_modules, used for the optional packages (storage drivers, mailer services) that are only available when the project installs them.
- loadPackage(packageName, projectPath) - returns the loaded package, or false when it can not be resolved.
- resolvePath(packageName, projectPath) - resolves the package path from projectPath (or the package name itself when no path is given).
- error property - {message: ''} on success, or {message, packageName, projectPath, error} after a failed load; the message includes the npm install command.
The class does not log, the caller decides the log level (Logger.critical(PackageResolver.error.message) for a required package, nothing for an availability check).
Shared Express packages (index.js)
The Express packages the package depends on are exported, so the projects (Reldens) don't duplicate them in their package.json:
- ExpressSession - the express-session module, used for ExpressSession.Store in the custom session stores.
- ExpressBasicAuth - the express-basic-auth middleware factory, used to protect the Colyseus monitor.
RequestLogger (lib/request-logger.js)
Express middleware for request logging.
- createMiddleware(onRequestSuccess, onRequestError) - create the logging middleware.
Tracks the request timing and invokes the callbacks based on the status code: below 400 it calls onRequestSuccess, 400 or above it calls onRequestError.
The logged ip and hostname are req.ip and req.hostname, so the forwarding headers are only used when they come from a proxy trusted through trustedProxy.
EventDispatcher (lib/event-dispatcher.js)
Static utility for dispatching lifecycle events.
- dispatch(onEventCallback, eventType, instanceName, instance, data) - dispatch an event.
Validates that the callback exists before invoking it with structured event data.
ServerErrorHandler (lib/server-error-handler.js)
Centralized error handling for all the server components.
- handleError(onErrorCallback, instanceName, instance, key, error, context) - handle and delegate errors.
Used by Http2CdnServer, AppServerFactory and ReverseProxyConfigurer. Provides structured error context with the instance details and metadata.
ServerDefaultConfigurations (lib/server-default-configurations.js)
Static class providing default configurations.
- mimeTypes - MIME type mappings for common file extensions.
- cacheConfig - default cache max-age settings (1 year for CSS / JS / fonts, 30 days for images).
ServerFactoryUtils (lib/server-factory-utils.js)
Static utility methods for server operations.
- getCacheConfigForPath(path, cacheConfig) - cache config for a file path.
- validateOrigin(origin, corsOrigins, corsAllowAll) - validate a CORS origin (supports strings and RegExp).
- stripQueryString(url) - remove the query string from a URL.
ServerHeaders (lib/server-headers.js)
Centralized header management: HTTP/2 headers configuration, Express security headers, cache control headers and the proxy forwarding header names (X-Forwarded-For, X-Forwarded-Proto, X-Forwarded-Host, X-Real-IP and X-Client-IP).
- buildCacheControlHeader(maxAge) - build the cache control header string.
Security Configurers
Located in lib/app-server-factory/.
DevelopmentModeDetector (development-mode-detector.js)
Auto-detects the development environment.
- detect(config) - detect if in development mode.
- matchesPattern(domain) - check if a domain matches a development pattern.
Checks NODE_ENV, domain patterns and configured domains. Built-in patterns: localhost, 127.0.0.1, .local, .test, .dev, .staging, etc.
ProtocolEnforcer (protocol-enforcer.js)
Enforces HTTP / HTTPS protocol consistency.
- setup(app, config) - set up the protocol enforcement middleware.
Development mode aware, with automatic redirects when the protocol doesn't match the configuration. The protocol is req.protocol, so X-Forwarded-Proto is only used from a trusted proxy, and the development redirect is only skipped for a request coming from a trusted proxy.
SecurityConfigurer (security-configurer.js)
Helmet integration with CSP management.
- setupHelmet(app, config) - set up the Helmet middleware.
- setupXssProtection(app, config) - set up the XSS protection.
- enableCSP(app, cspOptions) - enable the Content Security Policy.
- addExternalDomainsToCsp(directives, externalDomains) - add external domains to the CSP.
XSS protection with request body sanitization. Development friendly CSP configuration with directive merging or override support.
CorsConfigurer (cors-configurer.js)
Dynamic CORS origin validation.
- setup(app, config) - set up the CORS middleware.
- extractDevelopmentOrigins(domainMapping) - extract the development origins.
- normalizeHost(originOrHost) - normalize a host string.
Development domain support with automatic port variations, and credentials support configuration.
RateLimitConfigurer (rate-limit-configurer.js)
Global and endpoint-specific rate limiting.
- setup(app, config) - set up the global rate limiting when globalRateLimit is on. The limiter counts in globalStore (an express-rate-limit MemoryStore) with the globalLimit maximum.
- isWithinGlobalLimit(clientAddress) - async, counts a request that never reaches the global limiter middleware (proxied requests and WebSocket upgrades) in the same store and with the same key; true when the global limit is off.
- createLimiter(params) - create a limiter for a single route, with windowMs, maxRequests, message, keyGenerator and skipSuccessfulRequests with requestWasSuccessful. Reldens uses it for the administration panel login.
- createHomeLimiter() - create the homepage-specific limiter.
Development mode multiplier for lenient limits, and an IP-based key generation option.
ReverseProxyConfigurer (reverse-proxy-configurer.js)
Domain-based reverse proxy routing.
- setup(app, config) - set up the reverse proxy.
- createProxyMiddleware(rule) - create the proxy middleware for a rule. The http-proxy-middleware ws option is always off, so the middleware never subscribes to every upgrade of the server.
- attachToServer(server) - register the server upgrade listener when a rule has WebSocket enabled; called by AppServerFactory after the server is created.
- proxyRequest(proxyMiddleware, req, res, next) - count the proxied request in the global rate limit (429 over it), replace the forwarding headers and proxy it.
- handleUpgrade(req, socket, head, server) - proxy an upgrade only for a matching WebSocket rule. It answers 403 for an address denied by the IP lists, 429 over the global rate limit, and 404 when no rule matches and no other upgrade listener exists.
- findUpgradeRule(req) - find the WebSocket rule for the upgrade hostname (with virtual hosts) and path prefix.
- matchesPathPrefix(requestPath, pathPrefix) - match the path segments of a rule path prefix.
- handleProxyError(error, req, res) - handle proxy errors with status codes; closes the socket of a failed WebSocket upgrade.
- validateProxyRule(rule) - validate a proxy rule configuration.
- extractHostname(req) - extract the hostname from the Host header, also on the raw upgrade requests.
- resolveForwardedHeaders(req) - build X-Forwarded-For and X-Real-IP with the client address resolved by proxy-addr and the app trust proxy function, and X-Forwarded-Proto and X-Forwarded-Host from a trusted upstream proxy or from the connection.
- applyForwardedHeaders(req) - replace the forwarding headers of a request before it is proxied and remove X-Client-IP.
- applyUpgradeForwardedHeaders(proxyReq, req) - the same replacement on the outgoing request of a WebSocket upgrade, through the proxyReqWs event.
Features:
- WebSocket support: the upgrades are only proxied for the rule hostname and path prefix, and they pass the IP lists from the first upgrade, without a previous HTTP request.
- The proxied requests and upgrades count in the global rate limit (globalRateLimit, maxRequests, windowMs) with the same key as the local requests.
- SSL termination.
- Forwarding headers (X-Forwarded-For, X-Real-IP, X-Forwarded-Proto, X-Forwarded-Host) always set by the proxy on the requests and the WebSocket upgrades. The values sent by a visitor are never forwarded, only the ones of an upstream proxy trusted through trustedProxy, so the client address can not be spoofed.
- A Reldens server behind the proxy must trust it (trustedProxy: 'loopback', RELDENS_EXPRESS_TRUSTED_PROXY) to use the forwarded client address, otherwise every visitor is seen as the proxy address.
- Virtual host integration.
- Error handling:
- 502 Bad Gateway for ECONNREFUSED errors.
- 504 Gateway Timeout for ETIMEDOUT / ESOCKETTIMEDOUT errors.
- 500 Internal Server Error for other proxy errors.
- Custom error callback support via ServerErrorHandler.
IpListsConfigurer (ip-lists-configurer.js)
Mutable allow and deny address lists consulted at request time.
- setLists(params) - replace the lists with {enabled, allow, deny, forbiddenMessage}.
- isAllowed(address) - check an address; a value that is not an IP is denied only when there are allow entries.
- setup(app) - install the Express middleware answering 403 for the denied req.ip.
Entries are addresses or CIDR ranges. A range needs an integer prefix up to 32 (IPv4) or 128 (IPv6), any other entry is ignored.
ClientAddressGuard (client-address-guard.js)
Created by AppServerFactory.attachClientAddressGuard(server) for the requests that never reach the Express middleware.
- normalizeRequest(request) - resolve the address with proxy-addr and the trust proxy function, remove the X-Real-IP, X-Forwarded-For and X-Client-IP headers and set X-Real-IP to the resolved address.
- attachToServer(server) - normalize every upgrade request first and wrap the current server request listeners.
- handleRequest(request, response, requestListeners, server) - normalize the /matchmake/ requests and answer 403 for the denied addresses; every other request reaches the wrapped listeners untouched.
Related Documentation
- @reldens/server-utils Architecture - Design principles and the callback system.
- Storage Architecture - The storage drivers resolved through PackageResolver.
reldens