npm.io
1.1.0 • Published 2d ago

@shieldpress/tracker

Licence
MIT
Version
1.1.0
Deps
0
Size
931 kB
Vulns
0
Weekly
0

@shieldpress/tracker

Lightweight monitoring, security & tracking SDK for Node.js applications. Collects system metrics, HTTP performance, security threats, dependency vulnerabilities, and runtime health — then reports them to your ShieldPress dashboard.

Features

  • System Metrics — CPU, RAM, heap memory, load average, uptime
  • HTTP Tracking — response times (avg, p50, p95, p99), status codes, top paths, RPS
  • Error Tracking — uncaught exceptions, unhandled rejections, manual captures
  • Security Monitoring — SQL injection, XSS, command injection, path traversal, bot detection, brute-force detection, sensitive data leak detection
  • Dependency Audit — automatic npm audit integration, CVE tracking per package
  • Runtime Performance — event loop lag, GC pauses, V8 heap spaces, active handles
  • Environment Security — Node.js version check, security headers validation, debug mode detection, sensitive env var warnings
  • Heartbeat — uptime monitoring for your Node.js process
  • Express Middleware — drop-in integration for Express apps
  • Next.js Integration — middleware wrapper, API route tracking, instrumentation hook
  • Zero runtime dependencies — only uses Node.js built-in modules
  • Wide compatibility — Node.js 14+, Express 4+, Next.js 13+

Requirements

  • Node.js >= 14.0.0 (recommended: 20 LTS+)
  • Express >= 4.0 (optional)
  • Next.js >= 13.0 (optional)

Installation

npm install @shieldpress/tracker

Quick Start

Basic Node.js
import { ShieldPressTracker } from "@shieldpress/tracker";

const tracker = new ShieldPressTracker({
  apiKey: process.env.SHIELDPRESS_API_KEY,
  siteId: process.env.SHIELDPRESS_SITE_ID,
  appName: "my-api",
  appVersion: "1.2.0",
}).start();
Express
import express from "express";
import { createExpressTracker } from "@shieldpress/tracker/express";

const app = express();

const { middleware, errorHandler, tracker } = createExpressTracker({
  apiKey: process.env.SHIELDPRESS_API_KEY,
  siteId: process.env.SHIELDPRESS_SITE_ID,
  appName: "my-express-app",
});

// Add tracking middleware (before routes)
app.use(middleware);

// ... your routes ...

// Add error handler (after routes)
app.use(errorHandler);

app.listen(3000);
Next.js

1. Initialize in instrumentation.ts:

import { initTracker } from "@shieldpress/tracker/nextjs";

export function register() {
  if (process.env.NEXT_RUNTIME === "nodejs") {
    initTracker({
      apiKey: process.env.SHIELDPRESS_API_KEY!,
      siteId: process.env.SHIELDPRESS_SITE_ID!,
      appName: "my-nextjs-app",
    });
  }
}

2. Track requests in middleware.ts:

import { withShieldPress } from "@shieldpress/tracker/nextjs";
import { NextResponse } from "next/server";

export const middleware = withShieldPress((request) => {
  // your existing middleware logic
  return NextResponse.next();
});

3. Track API routes:

import { withTracking } from "@shieldpress/tracker/nextjs";

export const GET = withTracking(async (request) => {
  return Response.json({ data: "hello" });
});

Configuration

Option Type Default Description
apiKey string required API key from ShieldPress dashboard
siteId string required Site ID registered in ShieldPress
apiUrl string https://api.shieldpress.net ShieldPress API URL
reportInterval number 60 Reporting interval in seconds
systemMetrics boolean true Collect CPU, RAM, disk metrics
httpTracking boolean true Track HTTP requests
errorTracking boolean true Track errors
securityTracking boolean true Security threat detection
depAudit boolean true Dependency vulnerability audit
depAuditInterval number 3600 Dep audit interval in seconds
runtimeMetrics boolean true Event loop lag, GC, heap spaces
envSecurity boolean true Environment security checks
heartbeat boolean true Send uptime heartbeat
appName string "node-app" App name for identification
appVersion string "0.0.0" App version string
environment string NODE_ENV Environment label
tags object {} Custom tags for filtering
ignorePaths string[] health/static paths Paths to exclude from tracking
maxErrorBuffer number 100 Max errors buffered before flush
maxSecurityBuffer number 500 Max security events buffered
debug boolean false Enable console debug logs

Security Monitoring

The tracker automatically detects and reports security threats:

Auto-detected Threats
Threat Severity Description
SQL Injection Critical UNION SELECT, DROP TABLE, sleep/benchmark patterns
XSS Attempt High <script>, javascript:, event handlers, eval()
Command Injection Critical Shell operators, system commands in input
Path Traversal High ../, encoded traversal attempts
Suspicious Paths Medium Admin probing (/wp-admin, .env, .git, /phpMyAdmin)
Bot/Scanner Medium Known scanner user-agents (sqlmap, nikto, nmap, burp, etc.)
Brute Force Critical 50+ security events from same IP in time window
Oversized Payload Medium Request body > 10MB
API Key Exposed Critical API keys/tokens/passwords in URL query strings
Sensitive Data Leak Critical JWT, AWS keys, private keys in response body
Manual Security Events
// Record authentication failure
tracker.recordAuthFailure({
  ip: "1.2.3.4",
  url: "/api/login",
  reason: "Invalid credentials",
});

// Record rate limit hit
tracker.recordRateLimit({
  ip: "1.2.3.4",
  url: "/api/data",
  limit: 100,
});

// Record CORS violation
tracker.recordCorsViolation({
  ip: "1.2.3.4",
  origin: "https://evil.com",
  url: "/api/users",
});

// Record custom security event
tracker.securityCollector.recordCustom(
  "custom",
  "high",
  "Suspicious admin action detected",
  { userId: "user_123", action: "bulk_delete" }
);

Dependency Audit

Automatically runs npm audit and reports vulnerabilities:

{
  "depAudit": {
    "totalDeps": 142,
    "totalVulnerabilities": 3,
    "bySeverity": { "critical": 1, "high": 1, "moderate": 1 },
    "vulnerabilities": [
      {
        "package": "lodash",
        "installedVersion": "4.17.20",
        "severity": "critical",
        "title": "Prototype Pollution",
        "patchedVersions": "4.17.21"
      }
    ]
  }
}

Runtime Performance

Monitors Node.js runtime health:

{
  "runtime": {
    "eventLoopLagMs": 2.5,
    "eventLoopLagP99Ms": 15.3,
    "activeHandles": 12,
    "activeRequests": 3,
    "gcPausesMsTotal": 45.2,
    "gcPausesCount": 8,
    "heapSpaces": [
      { "name": "new_space", "sizeMb": 16, "usedMb": 8.5, "availableMb": 7.5 },
      { "name": "old_space", "sizeMb": 128, "usedMb": 95.2, "availableMb": 32.8 }
    ]
  }
}

Environment Security

Checks your deployment environment:

{
  "envSecurity": {
    "nodeVersion": "v22.5.0",
    "nodeVersionSecure": true,
    "npmVersion": "10.8.2",
    "frameworkName": "next",
    "frameworkVersion": "^15.0.0",
    "securityHeaders": [
      { "header": "strict-transport-security", "present": true, "value": "max-age=31536000" },
      { "header": "content-security-policy", "present": false, "recommendation": "Add CSP header..." }
    ],
    "envVarWarnings": [
      "Sensitive env var 'DATABASE_URL' is set — ensure it's not exposed to client"
    ],
    "debugModeEnabled": false,
    "sourceMapExposed": false
  }
}

Full Report Payload

Each report sent to ShieldPress includes:

{
  "siteId": "site_xxx",
  "appName": "my-api",
  "environment": "production",
  "timestamp": "2025-01-15T10:30:00.000Z",
  "system": {
    "cpuPercent": 23.5,
    "memPercent": 67.2,
    "heapUsedMb": 128,
    "uptimeSeconds": 86400,
    "loadAvg": [1.2, 0.8, 0.6]
  },
  "http": {
    "totalRequests": 1520,
    "totalErrors": 3,
    "avgResponseMs": 45,
    "p95ResponseMs": 120,
    "requestsPerSecond": 25.3,
    "topPaths": [...]
  },
  "errors": [...],
  "security": {
    "totalEvents": 12,
    "bySeverity": { "critical": 1, "high": 3, "medium": 5, "low": 3 },
    "byType": { "sql_injection": 1, "xss_attempt": 3, "suspicious_path": 5, "bot_detected": 3 },
    "topOffendingIps": [{ "ip": "1.2.3.4", "count": 8, "types": ["sql_injection", "xss_attempt"] }],
    "events": [...]
  },
  "depAudit": {
    "totalDeps": 142,
    "totalVulnerabilities": 3,
    "vulnerabilities": [...]
  },
  "runtime": {
    "eventLoopLagMs": 2.5,
    "activeHandles": 12,
    "gcPausesCount": 8,
    "heapSpaces": [...]
  },
  "envSecurity": {
    "nodeVersion": "v22.5.0",
    "nodeVersionSecure": true,
    "securityHeaders": [...],
    "debugModeEnabled": false
  },
  "heartbeat": true
}

Environment Variables

SHIELDPRESS_API_KEY=sp_xxx
SHIELDPRESS_SITE_ID=site_xxx

License

MIT

Keywords