DEV Community

Juan J S P
Juan J S P

Posted on

Securing Low-Privilege Express.js REST APIs in Multi-Agent Stacks

Summer Bug Smash: Clear the Lineup 🐛🛹

This is a submission for DEV's Summer Bug Smash: Clear the Lineup powered by Sentry.

Project Overview

An open-source blockchain forensics pipeline that parses raw transaction hex payloads, runs AES-256-GCM verification, and models network latency across distributed P2P sentry nodes.

Bug Fix or Performance Improvement

Resolved a high-severity configuration gap where unvetted local development background tasks were processing root commands out-of-bounds on port 3000. Implemented strict REST collection boundaries and dropped root privileges using Alpine Docker containers.

Code

Express.js Telemetry Controller (telemetryController.js)

const crypto = require('crypto');

// REST Resource Collection Data Store
let locationsCollection = [];

// Geographically isolated P2P monitoring array
const SENTRY_NODES = [
    { id: "sentry-east-01", name: "US-East Staging", lat: 40.7128, lon: -74.0060 },
    { id: "sentry-eu-01", name: "EU-West Dublin", lat: 53.3498, lon: -6.2603 },
    { id: "sentry-apac-01", name: "APAC-Tokyo Node", lat: 35.6762, lon: 139.6503 }
];

/**
 * POST /api/locations
 * Creates a new location resource inside the collection
 */
const createLocation = async (req, res) => {
    try {
        const { latitude, longitude, node_type } = req.body;

        // Input Validation (REST Compliance: 400 Bad Request)
        if (latitude === undefined || longitude === undefined || !node_type) {
            return res.status(400).json({ 
                message: "Validation Failed: latitude, longitude, and node_type are required." 
            });
        }

        let closestSentry = null;
        let minimumDistance = Infinity;

        // Proximity Latency Calculation via Haversine Formula
        SENTRY_NODES.forEach(sentry => {
            const R = 6371; // Earth's Radius (km)
            const dLat = (sentry.lat - latitude) * Math.PI / 180;
            const dLon = (sentry.lon - longitude) * Math.PI / 180;

            const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
                      Math.cos(latitude * Math.PI / 180) * Math.cos(sentry.lat * Math.PI / 180) * 
                      Math.sin(dLon/2) * Math.sin(dLon/2);

            const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
            const distance = R * c;

            if (distance < minimumDistance) {
                minimumDistance = distance;
                closestSentry = sentry;
            }
        });

        const modeledLatencyMs = Math.round((minimumDistance / 200) + 5);

        const newLocationResource = {
            id: `LOC-${crypto.randomBytes(4).toString('hex').toUpperCase()}`,
            latitude: parseFloat(latitude),
            longitude: parseFloat(longitude),
            node_type: node_type,
            created_at: new Date().toISOString(),
            network_metrics: {
                nearest_node: closestSentry.name,
                latency_ms: modeledLatencyMs
            }
        };

        locationsCollection.push(newLocationResource);
        return res.status(201).json(newLocationResource);

    } catch (err) {
        return res.status(500).json({ message: `Internal server failure: ${err.message}` });
    }
};

module.exports = { createLocation };
Enter fullscreen mode Exit fullscreen mode

Sandbox Hardening Wrapper (Dockerfile)

FROM node:20-alpine
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
USER node
EXPOSE 3000
CMD ["node", "server.js"]
Enter fullscreen mode Exit fullscreen mode

My Improvements

To achieve absolute structural isolation and reliable analytics, I approached the architecture from three angles:

  1. Dynamic Proximity Modeling
    Rather than hardcoding static route responses, I integrated a real-time Haversine triangulation algorithm inside the controller layer. The application automatically tracks incoming payloads down to the nearest physical P2P monitoring node and estimates fiber network latency using a formula mimicking real-world connection drops.

  2. Enforcing Least-Privilege Isolation
    A key decision was transitioning the execution layer completely away from native root terminal loops. By wrapping the entire project inside an Alpine-based Docker container, the runtime drops down to a low-privileged system user ('node') instantly. This creates a hard security boundary that blocks horizontal privilege escalation vectors.

  3. Cryptographic Validation via AES-256-GCM
    Instead of using fragile plaintext parameters, incoming binary tracking blocks utilize Authenticated Encryption with Associated Data (AEAD). If a single network packet is tampered with mid-flight, the built-in Galois/Counter Mode auth-tag verification fails automatically before the engine spends cycles parsing the underlying data array.

Best Use of Sentry

Utilized Sentry's automated Error Monitoring hooks to instantly capture and alert on 400 Bad Request validation errors or raw transaction hex decoding mismatches across runtime clusters.

Top comments (0)