@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.
  • ipLists - allow and deny address lists ({enabled, allow, deny}).
  • 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.
  • 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, staticPath) - serve static files.
  • 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.
  • 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.
  • 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.

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 proxy forwarding headers.

  • 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.

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.
  • 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.
  • handleProxyError(err, req, res) - handle proxy errors with status codes.
  • validateProxyRule(rule) - validate a proxy rule configuration.
  • extractHostname(req) - extract the hostname from the request.

Features:

  • WebSocket support.
  • SSL termination.
  • Header preservation (X-Forwarded-For, X-Forwarded-Proto, X-Forwarded-Host).
  • 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

Go Up