DEV Community

Pavel Kostromin
Pavel Kostromin

Posted on

Securing a Node.js Modpack Control Plane Across Docker, WebSockets, SQLite, and Host Filesystems

Anatomy of a Single-Process Control Plane: Express, Dockerode, WebSockets, and SQLite

A modpack control plane for friends and family rarely fails from a million-user surge. It fails when a heavy JVM garbage collection pause collides with a log stream, a SQLite write lock stalls an event watcher, or a coding agent like Claude Code wires an HTTP handler straight into the Docker socket without a boundary in between. Running the entire control plane as a single plain-JavaScript Node.js process—pairing Express, dockerode, ws, and built-in node:sqlite—strips away framework indirection and native build fragility while keeping every failure mode visible in one memory space.

Because Claude Code wrote most of the code while I owned the architecture, feature scope, manual review, and live server testing, single-process simplicity had to carry real structural weight. Without a compilation step rewriting line numbers or an ORM hiding SQL queries behind lazy proxies, runtime behavior stays readable—provided the process enforces hard boundaries around state, sockets, and the host filesystem.

Unidirectional Layering and Zero-Build JSDoc Type Checking

When AI generates endpoints quickly, the fastest way to rot a codebase is letting route handlers talk directly to dockerode or SQLite. If an Express route parses a body, queries a container, and writes a row in one function, testing a server start or crash state requires a live Docker daemon and a populated database—so developers skip writing tests, and subtle regressions slip into production.

Enforcing a strict one-way dependency chain—routes (parse and zod-validate only, zero business logic) to services (feature workflows) to docker, db, and storage adapters—isolates state transitions mechanically. Calling a service function in node:test against an in-memory or temporary SQLite database and a stubbed Docker client exercises actual branching logic without spawning containers. If a route handler imports a low-level adapter directly, test isolation collapses and every unit test turns into an integration hazard.

Pairing plain JavaScript with JSDoc annotations and tsc --checkJs in CI catches property typos, wrong return shapes, and nullability mismatches before runtime, while keeping stack traces pointed straight at the source file you wrote. A TypeScript build step introduces a source-map translation layer that can shift line numbers or mask runtime inspection; tsc --checkJs gives static type checking without rewriting the files executed by Node.js. However, JSDoc checking stops at type boundaries—if a zod schema accepts a wider string set than an internal enum assumes, type-checking passes while runtime logic hits an unexpected branch.

Built-In node:sqlite Versus Native Drivers on ARM64

Persisting server metadata, schedules, and crash history in SQLite avoids running a separate database daemon alongside game servers, yet native SQLite bindings frequently break on arm64 hosts when prebuilt binaries are missing and node-gyp attempts a C++ compilation against mismatched headers or toolchains. That build failure halts container image builds or deployment scripts before the application ever starts.

Using Node 24's built-in node:sqlite in synchronous mode with Write-Ahead Logging (WAL) eliminates external native add-on compilation completely. In WAL mode, readers append to or read from the WAL file while writers commit frames sequentially without blocking concurrent reads, and caching prepared statements by SQL text avoids re-parsing and re-planning identical statements on every call. If a single module owns the database connection and statement cache, connection lifecycle leaks and scattered pragma tweaks cannot happen across files.

Persistence Option Failure Mechanism Operational Verdict
Native C++ SQLite add-on Missing arm64 prebuilt binary triggers node-gyp build failure or ABI mismatch, aborting startup. Suboptimal for portable self-hosted control planes; avoid when built-in runtime support exists.
Built-in node:sqlite (synchronous + WAL + statement cache) Single-process synchronous writes can stall the event loop if large transactions or unindexed scans run during active log/WebSocket traffic. Optimal for low-to-moderate write concurrency on single-host Node 24 deployments.
External client-server DB (e.g., Postgres) Extra memory footprint and network/socket hops compete with JVM modpack heaps on constrained hosts. Excessive overhead for a personal modpack manager; use only if multi-node control plane scaling is required.

Synchronous node:sqlite stops working well when write volume or transaction duration grows large enough to block the Node.js event loop—for instance, writing thousands of high-frequency log lines per second into SQLite inside the request/event path will delay HTTP responses and WebSocket heartbeats. A common choice error is treating synchronous SQLite as free of I/O latency just because there is no network socket; large unbatched writes still flush pages and hold the event loop until complete. Decision rule: if state updates are discrete control-plane events on a single host using Node 24+, use built-in node:sqlite with WAL and prepared-statement caching; if high-volume telemetry ingestion or multi-writer concurrency saturates the event loop, move high-frequency streams out of synchronous SQLite writes into ring buffers or append-only log files.

Dockerode Event Watchers and Brokered WebSocket Log Streams

Shelling out to the docker CLI spawns child processes, allocates pipes, and parses text output that can change formatting across CLI versions—introducing subprocess overhead and fragile string parsing. Calling the Docker Engine API through dockerode keeps communication over a persistent socket or HTTP transport, returning structured objects for container inspection, stats, image pulls, and daemon events.

A background watcher subscribed to Docker events translates container state changes (such as non-zero exits or OOM kills) into persisted history and crash detection. Yet tying a watcher to a single process introduces a subtle coupling risk: if the control plane restarts while a modpack container is running or exiting, missed transient events can leave database state stale unless startup performs a reconciliation pass against dockerode container inspection.

Live console streaming exposes the sharpest throughput trap in a browser-based server panel. If every open browser tab opens its own upstream docker logs --follow stream for the same modpack container, opening ten tabs multiplies daemon log serialization, socket reads, and string decoding by ten—driving CPU and memory usage up even though the underlying container output is identical. Brokering WebSockets solves this mechanically: one upstream follow stream per container feeds an in-memory fan-out hub that pushes chunks to subscribed client sockets, while checking Origin headers and session cookies during the HTTP upgrade handshake blocks cross-site WebSocket hijacking before a socket is attached.

Brokering stops working cleanly if slow or stalled browser clients back up the fan-out path without flow control. When a client's TCP receive window fills and its WebSocket send buffer grows unbounded, retaining references to slow chunks increases Node.js heap memory until garbage collection thrashes or the process hits its memory limit. A typical choice error is broadcasting every raw log chunk unconditionally to every connected socket without checking buffered amounts or capping queue depth. Decision rule: if multiple clients can tail the same container log stream, broker a single upstream stream per container with per-client backpressure checks and bounded buffers; if a client's buffered output exceeds threshold or disconnects, drop/throttle that slow subscriber rather than stalling the upstream reader or inflating process heap.

Server-Rendered Views, CSP Nonces, and Path Canonicalization

Rendering pages with Express and Handlebars alongside a small esbuild bundle for interactive controls avoids heavy client-side framework overhead while keeping server-side control clear. Generating a fresh per-response Content Security Policy (CSP) nonce and attaching it to inline/bootstrapped script tags—without unsafe-inline—ensures that even if a modpack name, player message, or config value ever reaches HTML in a malformed way, an injected script tag lacking that request's random nonce is blocked by the browser's script-execution guard.

Host filesystem access carries the highest blast radius in a modpack manager because server directories hold world saves, configs, and potentially mounted secrets or adjacent host paths. If a file endpoint concatenates user-supplied relative paths onto a base data directory without canonicalization, sequences like ../ can walk outside the data root, and a symlink placed inside a modpack folder can point to a sensitive host file even when the lexical path looks contained. Resolving paths to their real filesystem target and verifying that the canonical path stays strictly inside the canonical data root prevents both lexical traversal and symlink escapes—provided the guard runs on every file operation (read, write, delete, rename, archive extract) rather than only on initial route entry.

  • Canonicalization before every I/O call: Resolve symlinks and relative segments first, then assert the resolved target sits inside the canonical data directory boundary; skipping re-verification across multi-step operations like renames or archive extractions allows escape windows.
  • Live verification alongside unit tests: Passing node:test suites without Docker proves service logic, while a live QA sweep against a running panel catches real socket upgrades, cookie/Origin rejections, CSP headers, and Docker API interactions that mocks cannot simulate.

Five Failure Scenarios in Production: Privilege Escalation, Log Backpressure, and Modpack Chaos

When you build a self-hosted control plane with an AI coding agent like Claude Code, code appears fast—sometimes faster than your threat model. In a plain-JavaScript Node.js panel using Express, dockerode, ws, and built-in node:sqlite, the happy path works on day one: a container boots, console lines stream into a browser tab, and server properties save cleanly. Real load is where assumptions get stress-tested. During live runs of heavy Minecraft modpacks for friends and family, five failure modes surfaced that expose what happens when architectural boundaries are loose or treated as optional.

1. Docker Socket Exposure and Privilege Escalation

Mounting /var/run/docker.sock into a Node.js control plane effectively hands root-equivalent control of the host to whatever code executes inside that process. If an unauthenticated or poorly scoped route accepts arbitrary container creation parameters—such as host bind mounts (/etc, /root, or /), privileged flags, or custom entrypoints—the causal chain is direct: an untrusted request reaches the Docker Engine API via dockerode, the daemon allocates a container with a host filesystem bind mount or elevated capabilities, and the attacker reads host secrets or spawns a root shell outside the container boundary. Even if the web panel itself runs as a non-root user inside its own container, access to the raw Docker socket bypasses container isolation because the daemon acts on behalf of the host.

Relying on dockerode over persistent socket/HTTP transports is still better than shelling out to the docker CLI, which spawns child processes, allocates extra pipes, and forces brittle string parsing on stdout/stderr. However, API ergonomics do not enforce authorization by themselves. Strict route-to-service layering helps keep raw dockerode calls out of HTTP handlers, while services enforce explicit allowlists on images, volumes, capabilities, and WebSocket upgrade origins and session cookies.

A common choice error is assuming that running the Node.js process as a non-root user protects the host when the Docker socket is mounted. Socket permissions only govern local Unix socket access; once opened, the daemon executes privileged lifecycle operations on the host. When a control plane cannot strictly constrain container parameters and socket access—or must expose multi-tenant self-service—use a dedicated container runtime proxy or separate daemon isolation rather than a raw host Docker socket. If you are testing this architecture and want to save your notes or come back to these failure modes later, signing in to a Google Account lets you keep your chat history in one place.

2. Path Traversal and Symlink Escapes During Modpack Extraction

Modpacks ship as sprawling zip archives containing nested configs, scripts, datapacks, and overrides. If extraction joins archive entry names onto a server data directory using naive string concatenation or regex checks for .., an entry like ../../../../etc/cron.d/pwn or a pre-existing symlink inside an extracted directory redirects file writes outside the intended data root. Physically, the file descriptor opens an inode outside the sandbox boundary, overwrites or exposes host files, and leaves stray files on the host filesystem even after the container stops.

Checking lexical paths before resolving symlinks fails because a symlink inside the target tree can point to an external directory while its lexical path still looks nested. Enforcing a path guard on every file operation—canonicalizing targets against the real filesystem path and verifying containment inside the canonical data root before reads, writes, deletes, renames, or archive extractions—closes that gap. Static type checking via JSDoc and tsc --checkJs catches wrong argument shapes at compile time, but it cannot prevent a string from resolving to a dangerous inode at runtime; runtime canonicalization has to do that work.

The typical mistake here is sanitizing only the incoming request path or only checking .. substrings. That stops sloppy inputs and fails on symlinked directories or multi-step archive entries. Canonicalize every target path to its real filesystem location and reject anything outside the canonical data root; if you need cross-directory sharing or host-level backups, move that into a controlled service step with explicit allowlists rather than weakening the path guard.

3. WebSocket Log Flooding and Backpressure

A modded game server under world generation, chunk loading, or tick lag can emit thousands of log lines per second. If every open browser tab opens its own upstream follow stream against the Docker daemon, each client multiplies socket reads, UTF-8 decoding, and string allocation across the single Node.js event loop. Worse, if a slow client connection stalls while chunks arrive faster than the TCP send buffer drains, unbounded per-client queues retain buffer references in the V8 heap. Heap usage climbs, garbage collection works harder to scan live references, and the Node.js process either slows to a crawl or gets OOM-killed.

Brokering one upstream follow stream per container into an in-memory fan-out hub solves the read multiplication problem: the daemon serializes and streams the log once per container, and the Node.js hub distributes frames to active subscribers. To protect memory under slow consumers, check subscriber buffered state and enforce bounded per-client queues—dropping or throttling lagging subscribers rather than letting queues grow without limit or blocking upstream reads.

A frequent choice error is treating WebSocket broadcast as "just ws.send(chunk) in a loop" without inspecting backpressure or connection health. A single brokered stream per server is optimal for personal and small-group panels on one host; if you ever need multi-node fan-out, durable log replay, or heavy search across gigabytes of logs, offload log persistence to rotating files or an external log pipeline instead of stuffing history into Node.js memory.

Failure Mode Underlying Mechanism Control Plane Mitigation
Docker socket privilege escape Unrestricted container config reaches Docker daemon via socket Strict service allowlists, origin/cookie upgrade checks, minimal mounts
Modpack archive traversal Unresolved symlinks or traversal paths escape data directory Real-path canonicalization and root containment check on every op
WebSocket log backpressure Per-tab streams + unbounded queues bloat V8 heap on slow clients One upstream stream per container, fan-out hub, bounded queues
SQLite write contention Synchronous writes or heavy loops block single-threaded event loop Built-in node:sqlite in WAL mode + cached statements + small writes
Crash-loop state drift JVM heap exhaustion or OOM kills collide with missed events Event watcher plus startup reconciliation against live container state

4. SQLite Write Contention on a Single-Threaded Event Loop

Using Node's built-in node:sqlite in synchronous mode with Write-Ahead Logging (WAL) avoids native node-gyp C++ compilation failures and ABI mismatches on arm64 hosts, and centralizing connection ownership with a prepared-statement cache keyed on SQL text avoids repeated SQL parsing and planning. Still, synchronous SQLite calls execute on the Node.js main thread. If code runs large multi-row transactions, unindexed scans, or high-frequency log inserts inside SQLite, disk page flushes and lock contention stall the event loop—delaying HTTP routes, health checks, and WebSocket heartbeats simultaneously.

WAL mode lets readers proceed concurrently with a writer, which helps read-heavy panel views, but single-writer serialization and synchronous I/O remain real constraints under bursty writes. Keep SQLite strictly for discrete control-plane state (servers, users, settings, audit/crash events), keep transactions compact, and never stream high-volume console logs into SQLite.

The classic mistake is reaching for a heavy external database like PostgreSQL on a small host where JVM heap memory is already tight, or conversely dumping high-frequency telemetry into synchronous SQLite. Use built-in node:sqlite with WAL and cached prepared statements for single-host control-plane state; move to an external database only when you actually have multiple control-plane nodes or concurrent writers that exceed single-host SQLite throughput.

5. Crash-Loop Recovery and Modpack Chaos

Modpacks are notoriously unstable: an oversized JVM heap allocation, a buggy mod tick loop, or an out-of-memory kill can crash a server container repeatedly right after boot. If your control plane relies solely on a live Docker event stream to record exits and crashes, a restart of the control plane itself can miss transient events, leaving the database claiming a server is starting or running when the container actually exited with code 137.

Pairing a background Docker event watcher with startup state reconciliation—inspecting live containers via dockerode when the panel boots and aligning persisted state—prevents stale UI states after restarts. Testing service logic with node:test against stubbed Docker clients and temporary/in-memory SQLite databases, backed by a live QA sweep script against a running panel, catches state-transition bugs before a bad modpack update hits real players.

A common choice error is trusting either the database row or the in-memory event listener as the single source of truth after a restart. Always reconcile persisted control-plane state against live Docker container inspection on startup; if a server enters rapid crash loops, surface exit codes and OOM status clearly and apply backoff or manual intervention rather than masking the failure with silent retries.

Filesystem Mediation, Modpack Pipelines, and Licensing Landmines

A modpack control plane looks benign right up until someone drops a 400 MB CurseForge or Modrinth archive into an upload field or edits a server's world directory through a web file manager. Behind a friendly browser UI, that single action hands an untrusted byte stream to a Node.js process that shares host storage with live JVM containers. When Claude Code scaffolds an archive extractor or a file route quickly, it almost always trusts path strings and stream lengths unless you force hard boundaries at the filesystem and licensing layers.

Path Canonicalization vs. Lexical Filtering: Why ../ Checks Fail

The most common bug in hand-rolled or AI-generated file services is filtering .. substrings or calling path.join(root, userInput) before opening a file descriptor. Lexical string normalization only inspects characters; it never touches inodes or directory entries on the underlying filesystem (ext4, XFS, or APFS).

Here is how a traversal or symlink escape actually executes:

  • Raw segment traversal: An attacker or malformed archive entry supplies ../../../../etc/cron.d/panel-job. Naive string concatenation resolves the target path outside the server data directory, allowing the kernel's openat syscall to create or overwrite a file on a completely different subtree once permissions allow.
  • Symlink indirection: Even if you strip .. from the requested path, a previously extracted or host-planted symbolic link inside mods/ or config/ may point to /etc or another server's world/playerdata. When the kernel traverses that symlink dentry during a read, write, rename, or archive extract, it redirects inode resolution to the external target.
  • TOCTOU races during extraction: If a check runs on a path before creating subdirectories or writing files, a concurrent request or nested archive entry can swap a directory for a symlink in the window between validation and the syscall, shifting where bytes land on disk.

Decision rule: If you expose any read, write, delete, rename, or zip/tar extraction against a server data folder, resolve the target against the canonicalized real path (fs.realpathSync) of the root directory on every operation and verify prefix containment with a trailing path separator—never rely on lexical checks or JSDoc types alone. Canonicalization is optimal for single-host Node.js file mediation because it enforces kernel-resolved boundary containment with zero external daemons. It stops working when untrusted users can race directory creation concurrently or when the control plane needs cross-volume bind mounts outside the data root; in those cases, move extraction into an unprivileged, disposable container with read-only host mounts rather than relaxing path guards in Node.

Archive Bombs, Disk Exhaustion, and World File Contention

Modpacks are notoriously uneven in shape: a lightweight client/server pack might be 18 MB of compressed JARs, while a heavy pack with bundled shader configs, custom dimensions, or pre-generated chunks can unpack to gigabytes of small files. A naive unzip loop that pipes an archive entry straight to disk without accounting for byte counts, entry counts, or live JVM writes creates physical and I/O failure modes.

During an archive bomb (a small compressed payload expanding into tens of gigabytes or millions of tiny files), compressed blocks feed the decompressor faster than disk write queues drain. Inode tables fill up or free filesystem blocks vanish; on a shared host where both the Node.js panel and Minecraft JVMs write to the same disk, block exhaustion stalls journal commits and forces JVM garbage-collection pauses or container eviction when host storage hits 100%.

World files introduce a second physical hazard: concurrent mutation. While a Minecraft server is running, chunks, region files (.mca), and level metadata are actively read and written by the JVM. Overwriting world/ or deleting dimension folders during a live tick loop corrupts chunk state or causes region file truncation and missing chunks on reload. Even when the server is stopped, copying or zipping a multi-gigabyte world directory synchronously or without byte/entry caps saturates disk read bandwidth and spikes memory buffers.

Approach Failure Mechanism Verdict
Unbounded stream extract to host disk Decompressed bytes or entry count exhaust disk blocks/inodes, starving host and JVM I/O Unacceptable; cap both total bytes and file count while streaming
Hot world overwrite/archive while container runs Concurrent JVM region/chunk writes collide with file mutations, corrupting world state Reject destructive world writes/restores unless container is cleanly stopped
Canonicalized guarded service + lifecycle gate Enforces byte/entry ceilings, real-path containment, and stopped-state checks before touching disk Optimal for self-hosted single-node panels

A typical AI choice error is treating "zip extraction" as a one-liner helper around a third-party archive library without tracking cumulative uncompressed bytes per archive or blocking world overwrites on running containers. Enforce hard byte budgets, maximum entry counts, and container-state preconditions inside the storage/modpack service layer—never inside Express route handlers.

Third-Party Mod Distribution and Licensing Landmines

Automated modpack ingestion crosses from systems engineering into legal liability the moment your tool fetches, caches, or redistributes third-party mods. Mod authors license their code and assets under varied terms—some use permissive open licenses, many use ARR (All Rights Reserved), and numerous platforms or individual authors explicitly set flags or terms prohibiting third-party distribution or automated scraping.

The mechanical risk is straightforward: if a control plane automatically downloads restricted mod JARs into a shared cache, bundles them into exportable server packs, or exposes cached mod binaries over a network endpoint without respecting distribution restrictions and platform APIs, the operator becomes the party distributing copyrighted binaries without authorization. Even for a private friends-and-family server, automated fetching that bypasses rate limits, API terms, or author distribution opt-outs turns a convenience feature into a compliance exposure.

Decision rule: If a modpack manifest or source marks a mod as restricted from third-party distribution or lacks permission for automated redistribution, fetch only via official APIs/workflows permitted by the source or require the operator to supply the local file manually—never silently mirror or re-host restricted binaries in a shared panel cache. Explicit manual drop-in for restricted mods is more tedious than full automation, and it stops scaling once dozens of users manage dozens of packs independently, at which point you should integrate official pack manifest resolvers and enforce strict per-pack isolation rather than building a public mod mirror.

Hardening the Control Plane: Guardrails, Isolation, and Operational Trade-offs

A plain-JavaScript control plane built around express, dockerode, ws, and node:sqlite—even when drafted rapidly with Claude Code and type-checked with tsc --checkJs—inherits root-equivalent blast radii the moment it touches /var/run/docker.sock, streams game-server console output, mutates modpack archives, and writes state to disk. Speed of generation does not remove physical bottlenecks; it compresses how quickly subtle race conditions, memory retention, and path escapes reach production.

Hardening a single-host control plane is not about bolting on heavy enterprise machinery. It is about placing explicit mechanical boundaries where data crosses trust zones, where byte streams hit storage or V8 heaps, and where container lifecycle state diverges from database rows.

Docker Daemon Exposure and Socket Proxying

Mounting /var/run/docker.sock into a Node.js process hands any reachable code path effective root control over the host daemon. If an HTTP route or WebSocket upgrade handler accepts arbitrary container configurations, bind mounts, privileged flags, or device passthroughs, an authenticated session—or a cross-origin browser tab—can instruct the daemon to mount the host root filesystem into a new container and read sensitive credentials or modify host binaries.

Routing calls through dockerode and enforcing strict service-layer allowlists prevents arbitrary image or mount specifications from reaching the daemon API, while validating Origin headers and session cookies on WebSocket upgrades blocks unauthorized browser-initiated connections. Still, a single application process holding raw daemon socket access remains one logic bug away from privileged container creation.

  • Direct daemon socket + permissive service specs: Fast to wire up, but any parameter leak in container creation or exec/attach paths lets an attacker escalate to host root via bind mounts or privileged flags.
  • Service-gated dockerode client on a single host: Optimal for a personal or small-group modpack panel because it eliminates shelling out to the docker CLI, keeps lifecycle transitions typed and testable, and restricts actions to predefined server records.
  • Socket proxy or isolated daemon: Necessary when multiple untrusted operators share a host or when the control plane itself should never hold raw daemon write authority; it adds network/proxy hop latency and operational complexity that a single-admin friends-and-family deployment usually does not need.

Decision rule: If you run a single-host panel for a trusted small group with strict service-layer allowlists and WebSocket origin/cookie checks, use a gated dockerode client; if untrusted users or multi-tenant boundaries exist, place a filtering Docker socket proxy or isolated daemon in front of the control plane.

Path Canonicalization vs. Lexical Filtering

Modpack management constantly moves files across mods/, config/, and world/ directories. Filtering .. substrings or calling path.join(root, userInput) fails because string manipulation never inspects kernel dentries, inodes, or directory entries on ext4, XFS, or APFS. A lexical check sees a clean string while the kernel resolves filesystem links underneath it.

The causal chain works in three distinct ways:

  • Raw traversal segments: A relative path like ../../../../etc/cron.d/panel-job escapes the server data directory, allowing openat to create or overwrite files outside the intended tree whenever process permissions permit.
  • Symlink indirection: Even when .. is blocked, a symlink sitting inside mods/ or config/ and pointing to /etc or another server's world/playerdata causes the kernel to follow the link during read, write, rename, or archive extraction syscalls, exposing or mutating out-of-bounds files.
  • Time-of-check to time-of-use (TOCTOU) races: Checking a path before creating directories or writing files leaves a window where a concurrent request or nested archive entry swaps a directory for a symlink between validation and the write syscall, redirecting the write to the symlink target.

On every read, write, delete, rename, or archive extract inside a server data folder, canonicalize both the data root and the resolved target with fs.realpathSync and verify prefix containment with a trailing path separator so /srv/data/server-10 cannot match /srv/data/server-1. That check is optimal for single-host Node.js file mediation, but it breaks down under heavy concurrent directory mutation or cross-volume bind mounts outside the canonical root. When extraction faces untrusted archives or concurrent races that lexical/realpath checks alone cannot serialize safely, move extraction into an unprivileged, disposable container with tight mounts rather than weakening path guards.

Archive Bombs, Disk Exhaustion, and Live World Mutation

Modpack archives behave erratically. A lightweight server pack might be an 18 MB bundle of JARs, while a heavy pack with shader presets, custom dimensions, or pre-generated chunks can expand to several gigabytes and tens of thousands of small files.

When an extraction stream decompresses faster than the underlying block device and filesystem journal can commit writes, dirty page buffers accumulate, disk queue depth saturates, and available blocks or inodes run out. On a host running both the Node.js control plane and heavy Minecraft JVMs on the same storage volume, 100% disk I/O saturation stalls journal flushes and storage writes—triggering severe JVM garbage-collection pauses, tick stalls, or container eviction.

Mutating a live world directory creates a different kind of damage. A running Minecraft server actively reads and writes region files (.mca), chunk data, and level state. Overwriting world/ or deleting dimension folders while the JVM tick loop is active collides with open file handles and ongoing writes, resulting in corrupted chunks, truncated regions, or missing terrain on reload. Reading or archiving a multi-gigabyte stopped world without size or throughput limits can likewise saturate disk read bandwidth and inflate memory buffers.

Decision rule: If an operation extracts an archive, enforce hard uncompressed byte and entry ceilings inside the storage service while streaming; if an operation overwrites, restores, or mutates world/ data, require the target container to be cleanly stopped first.

Brokered WebSocket Log Streams and Heap Backpressure

Minecraft servers emit dense console output during boot, world generation, and mod errors. Opening a separate upstream docker logs --follow stream for every browser tab wastes daemon connections and duplicates work, while a naive loop calling ws.send(chunk) on every log chunk ignores TCP and WebSocket backpressure.

When a client tab has a slow network connection or stalls while rendering DOM updates, its outbound socket buffer fills. Without per-client queue bounds and buffer monitoring, chunks accumulate in per-client arrays in the V8 heap. That retained memory increases garbage-collection pressure, stretches event-loop turn times, and can push the Node.js process into an out-of-memory (OOM) kill—or, if upstream reads block on a slow consumer, stall log delivery for healthy tabs.

Maintaining one brokered upstream follow stream per container into a fan-out hub with bounded per-client queues is optimal for a single-host control plane serving a small group of players: lagging subscribers get dropped or throttled rather than expanding V8 heap buffers or stalling upstream reads. It stops working well once you need multi-node fan-out, durable historical log search, or long scrollback replay, where external log storage is far better suited than in-memory Node.js queues.

SQLite WAL Contention and Crash-Loop State Drift

Node's built-in node:sqlite in synchronous mode with Write-Ahead Logging (WAL) avoids native node-gyp compilation headaches on arm64 hosts, and caching prepared statements by SQL string avoids repeated SQL parsing and query planning. WAL also lets readers proceed concurrently with a single writer, which fits a read-heavy control panel well on memory-constrained hosts where running PostgreSQL alongside large Minecraft JVMs wastes scarce RAM.

The catch is that synchronous SQLite calls execute on the main event-loop thread. Large multi-row transactions, unindexed scans, or high-frequency log inserts force disk flushes and write serialization that block incoming HTTP requests, health checks, and WebSocket heartbeats. Keep SQLite strictly for compact control-plane state—servers, users, configuration metadata, and discrete audit or crash events—and never turn it into a high-volume log sink.

State drift compounds these timing issues during crash loops. A modpack server hitting JVM heap limits, a runaway mod tick loop, or a kernel OOM kill (exit code 137) can restart repeatedly. If the control plane restarts mid-loop and relies only on a live Docker event listener, it misses prior exit events and can show stale database rows claiming a container is still starting or running. Relying solely on database rows misses live container state changes. The reliable pattern combines background Docker event watching with startup reconciliation via live container inspection in dockerode, surfacing exit codes and OOM signals with backoff or manual intervention instead of blind retry loops—verified through node:test unit suites with stubbed Docker clients and temporary SQLite databases alongside a live QA sweep against a running instance.

Failure Mode Underlying Mechanism Primary Guardrail Where It Breaks Down
Docker socket privilege escape Unrestricted container specs or unauthenticated/cross-origin upgrades over mounted socket Service-layer allowlists, origin/cookie checks, and socket proxy when untrusted Multi-tenant or untrusted operators sharing one daemon without a filtering proxy
Modpack path & archive escape Lexical filtering misses realpath symlinks, TOCTOU races, or archive bombs fs.realpathSync prefix check + stream byte/entry limits + stopped world gate Untrusted concurrent directory races or cross-volume bind mounts outside root
Log stream heap bloat Per-tab streams and unbounded per-client buffers retain chunks in V8 heap One upstream follow stream per container + bounded client queues with drop/throttle Multi-node deployments, durable log retention, or large log search
SQLite event-loop stalls Synchronous writes, large transactions, or log inserts block main thread WAL mode + SQL-keyed prepared statement cache + compact control-plane data only High-frequency telemetry/log writes or multi-writer concurrency
Crash-loop state drift Missed exit/OOM events during control-plane restarts leave stale status rows Docker event stream + startup live inspection + exit/OOM surfacing and backoff Ignoring exit codes (such as 137) or masking repeated failures with instant retries

Top comments (0)