@shieldpress/tracker 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,322 @@
1
+ # @shieldpress/tracker
2
+
3
+ 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](https://shieldpress.net) dashboard.
4
+
5
+ ## Features
6
+
7
+ - **System Metrics** — CPU, RAM, heap memory, load average, uptime
8
+ - **HTTP Tracking** — response times (avg, p50, p95, p99), status codes, top paths, RPS
9
+ - **Error Tracking** — uncaught exceptions, unhandled rejections, manual captures
10
+ - **Security Monitoring** — SQL injection, XSS, command injection, path traversal, bot detection, brute-force detection, sensitive data leak detection
11
+ - **Dependency Audit** — automatic `npm audit` integration, CVE tracking per package
12
+ - **Runtime Performance** — event loop lag, GC pauses, V8 heap spaces, active handles
13
+ - **Environment Security** — Node.js version check, security headers validation, debug mode detection, sensitive env var warnings
14
+ - **Heartbeat** — uptime monitoring for your Node.js process
15
+ - **Express Middleware** — drop-in integration for Express apps
16
+ - **Next.js Integration** — middleware wrapper, API route tracking, instrumentation hook
17
+ - **Zero runtime dependencies** — only uses Node.js built-in modules
18
+ - **Wide compatibility** — Node.js 14+, Express 4+, Next.js 13+
19
+
20
+ ## Requirements
21
+
22
+ - Node.js >= 14.0.0 (recommended: 20 LTS+)
23
+ - Express >= 4.0 (optional)
24
+ - Next.js >= 13.0 (optional)
25
+
26
+ ## Installation
27
+
28
+ ```bash
29
+ npm install @shieldpress/tracker
30
+ ```
31
+
32
+ ## Quick Start
33
+
34
+ ### Basic Node.js
35
+
36
+ ```ts
37
+ import { ShieldPressTracker } from "@shieldpress/tracker";
38
+
39
+ const tracker = new ShieldPressTracker({
40
+ apiKey: process.env.SHIELDPRESS_API_KEY,
41
+ siteId: process.env.SHIELDPRESS_SITE_ID,
42
+ appName: "my-api",
43
+ appVersion: "1.2.0",
44
+ }).start();
45
+ ```
46
+
47
+ ### Express
48
+
49
+ ```ts
50
+ import express from "express";
51
+ import { createExpressTracker } from "@shieldpress/tracker/express";
52
+
53
+ const app = express();
54
+
55
+ const { middleware, errorHandler, tracker } = createExpressTracker({
56
+ apiKey: process.env.SHIELDPRESS_API_KEY,
57
+ siteId: process.env.SHIELDPRESS_SITE_ID,
58
+ appName: "my-express-app",
59
+ });
60
+
61
+ // Add tracking middleware (before routes)
62
+ app.use(middleware);
63
+
64
+ // ... your routes ...
65
+
66
+ // Add error handler (after routes)
67
+ app.use(errorHandler);
68
+
69
+ app.listen(3000);
70
+ ```
71
+
72
+ ### Next.js
73
+
74
+ **1. Initialize in `instrumentation.ts`:**
75
+
76
+ ```ts
77
+ import { initTracker } from "@shieldpress/tracker/nextjs";
78
+
79
+ export function register() {
80
+ if (process.env.NEXT_RUNTIME === "nodejs") {
81
+ initTracker({
82
+ apiKey: process.env.SHIELDPRESS_API_KEY!,
83
+ siteId: process.env.SHIELDPRESS_SITE_ID!,
84
+ appName: "my-nextjs-app",
85
+ });
86
+ }
87
+ }
88
+ ```
89
+
90
+ **2. Track requests in `middleware.ts`:**
91
+
92
+ ```ts
93
+ import { withShieldPress } from "@shieldpress/tracker/nextjs";
94
+ import { NextResponse } from "next/server";
95
+
96
+ export const middleware = withShieldPress((request) => {
97
+ // your existing middleware logic
98
+ return NextResponse.next();
99
+ });
100
+ ```
101
+
102
+ **3. Track API routes:**
103
+
104
+ ```ts
105
+ import { withTracking } from "@shieldpress/tracker/nextjs";
106
+
107
+ export const GET = withTracking(async (request) => {
108
+ return Response.json({ data: "hello" });
109
+ });
110
+ ```
111
+
112
+ ## Configuration
113
+
114
+ | Option | Type | Default | Description |
115
+ |--------|------|---------|-------------|
116
+ | `apiKey` | `string` | *required* | API key from ShieldPress dashboard |
117
+ | `siteId` | `string` | *required* | Site ID registered in ShieldPress |
118
+ | `apiUrl` | `string` | `https://api.shieldpress.net` | ShieldPress API URL |
119
+ | `reportInterval` | `number` | `60` | Reporting interval in seconds |
120
+ | `systemMetrics` | `boolean` | `true` | Collect CPU, RAM, disk metrics |
121
+ | `httpTracking` | `boolean` | `true` | Track HTTP requests |
122
+ | `errorTracking` | `boolean` | `true` | Track errors |
123
+ | `securityTracking` | `boolean` | `true` | Security threat detection |
124
+ | `depAudit` | `boolean` | `true` | Dependency vulnerability audit |
125
+ | `depAuditInterval` | `number` | `3600` | Dep audit interval in seconds |
126
+ | `runtimeMetrics` | `boolean` | `true` | Event loop lag, GC, heap spaces |
127
+ | `envSecurity` | `boolean` | `true` | Environment security checks |
128
+ | `heartbeat` | `boolean` | `true` | Send uptime heartbeat |
129
+ | `appName` | `string` | `"node-app"` | App name for identification |
130
+ | `appVersion` | `string` | `"0.0.0"` | App version string |
131
+ | `environment` | `string` | `NODE_ENV` | Environment label |
132
+ | `tags` | `object` | `{}` | Custom tags for filtering |
133
+ | `ignorePaths` | `string[]` | health/static paths | Paths to exclude from tracking |
134
+ | `maxErrorBuffer` | `number` | `100` | Max errors buffered before flush |
135
+ | `maxSecurityBuffer` | `number` | `500` | Max security events buffered |
136
+ | `debug` | `boolean` | `false` | Enable console debug logs |
137
+
138
+ ## Security Monitoring
139
+
140
+ The tracker automatically detects and reports security threats:
141
+
142
+ ### Auto-detected Threats
143
+
144
+ | Threat | Severity | Description |
145
+ |--------|----------|-------------|
146
+ | SQL Injection | Critical | `UNION SELECT`, `DROP TABLE`, sleep/benchmark patterns |
147
+ | XSS Attempt | High | `<script>`, `javascript:`, event handlers, `eval()` |
148
+ | Command Injection | Critical | Shell operators, system commands in input |
149
+ | Path Traversal | High | `../`, encoded traversal attempts |
150
+ | Suspicious Paths | Medium | Admin probing (`/wp-admin`, `.env`, `.git`, `/phpMyAdmin`) |
151
+ | Bot/Scanner | Medium | Known scanner user-agents (sqlmap, nikto, nmap, burp, etc.) |
152
+ | Brute Force | Critical | 50+ security events from same IP in time window |
153
+ | Oversized Payload | Medium | Request body > 10MB |
154
+ | API Key Exposed | Critical | API keys/tokens/passwords in URL query strings |
155
+ | Sensitive Data Leak | Critical | JWT, AWS keys, private keys in response body |
156
+
157
+ ### Manual Security Events
158
+
159
+ ```ts
160
+ // Record authentication failure
161
+ tracker.recordAuthFailure({
162
+ ip: "1.2.3.4",
163
+ url: "/api/login",
164
+ reason: "Invalid credentials",
165
+ });
166
+
167
+ // Record rate limit hit
168
+ tracker.recordRateLimit({
169
+ ip: "1.2.3.4",
170
+ url: "/api/data",
171
+ limit: 100,
172
+ });
173
+
174
+ // Record CORS violation
175
+ tracker.recordCorsViolation({
176
+ ip: "1.2.3.4",
177
+ origin: "https://evil.com",
178
+ url: "/api/users",
179
+ });
180
+
181
+ // Record custom security event
182
+ tracker.securityCollector.recordCustom(
183
+ "custom",
184
+ "high",
185
+ "Suspicious admin action detected",
186
+ { userId: "user_123", action: "bulk_delete" }
187
+ );
188
+ ```
189
+
190
+ ## Dependency Audit
191
+
192
+ Automatically runs `npm audit` and reports vulnerabilities:
193
+
194
+ ```json
195
+ {
196
+ "depAudit": {
197
+ "totalDeps": 142,
198
+ "totalVulnerabilities": 3,
199
+ "bySeverity": { "critical": 1, "high": 1, "moderate": 1 },
200
+ "vulnerabilities": [
201
+ {
202
+ "package": "lodash",
203
+ "installedVersion": "4.17.20",
204
+ "severity": "critical",
205
+ "title": "Prototype Pollution",
206
+ "patchedVersions": "4.17.21"
207
+ }
208
+ ]
209
+ }
210
+ }
211
+ ```
212
+
213
+ ## Runtime Performance
214
+
215
+ Monitors Node.js runtime health:
216
+
217
+ ```json
218
+ {
219
+ "runtime": {
220
+ "eventLoopLagMs": 2.5,
221
+ "eventLoopLagP99Ms": 15.3,
222
+ "activeHandles": 12,
223
+ "activeRequests": 3,
224
+ "gcPausesMsTotal": 45.2,
225
+ "gcPausesCount": 8,
226
+ "heapSpaces": [
227
+ { "name": "new_space", "sizeMb": 16, "usedMb": 8.5, "availableMb": 7.5 },
228
+ { "name": "old_space", "sizeMb": 128, "usedMb": 95.2, "availableMb": 32.8 }
229
+ ]
230
+ }
231
+ }
232
+ ```
233
+
234
+ ## Environment Security
235
+
236
+ Checks your deployment environment:
237
+
238
+ ```json
239
+ {
240
+ "envSecurity": {
241
+ "nodeVersion": "v22.5.0",
242
+ "nodeVersionSecure": true,
243
+ "npmVersion": "10.8.2",
244
+ "frameworkName": "next",
245
+ "frameworkVersion": "^15.0.0",
246
+ "securityHeaders": [
247
+ { "header": "strict-transport-security", "present": true, "value": "max-age=31536000" },
248
+ { "header": "content-security-policy", "present": false, "recommendation": "Add CSP header..." }
249
+ ],
250
+ "envVarWarnings": [
251
+ "Sensitive env var 'DATABASE_URL' is set — ensure it's not exposed to client"
252
+ ],
253
+ "debugModeEnabled": false,
254
+ "sourceMapExposed": false
255
+ }
256
+ }
257
+ ```
258
+
259
+ ## Full Report Payload
260
+
261
+ Each report sent to ShieldPress includes:
262
+
263
+ ```json
264
+ {
265
+ "siteId": "site_xxx",
266
+ "appName": "my-api",
267
+ "environment": "production",
268
+ "timestamp": "2025-01-15T10:30:00.000Z",
269
+ "system": {
270
+ "cpuPercent": 23.5,
271
+ "memPercent": 67.2,
272
+ "heapUsedMb": 128,
273
+ "uptimeSeconds": 86400,
274
+ "loadAvg": [1.2, 0.8, 0.6]
275
+ },
276
+ "http": {
277
+ "totalRequests": 1520,
278
+ "totalErrors": 3,
279
+ "avgResponseMs": 45,
280
+ "p95ResponseMs": 120,
281
+ "requestsPerSecond": 25.3,
282
+ "topPaths": [...]
283
+ },
284
+ "errors": [...],
285
+ "security": {
286
+ "totalEvents": 12,
287
+ "bySeverity": { "critical": 1, "high": 3, "medium": 5, "low": 3 },
288
+ "byType": { "sql_injection": 1, "xss_attempt": 3, "suspicious_path": 5, "bot_detected": 3 },
289
+ "topOffendingIps": [{ "ip": "1.2.3.4", "count": 8, "types": ["sql_injection", "xss_attempt"] }],
290
+ "events": [...]
291
+ },
292
+ "depAudit": {
293
+ "totalDeps": 142,
294
+ "totalVulnerabilities": 3,
295
+ "vulnerabilities": [...]
296
+ },
297
+ "runtime": {
298
+ "eventLoopLagMs": 2.5,
299
+ "activeHandles": 12,
300
+ "gcPausesCount": 8,
301
+ "heapSpaces": [...]
302
+ },
303
+ "envSecurity": {
304
+ "nodeVersion": "v22.5.0",
305
+ "nodeVersionSecure": true,
306
+ "securityHeaders": [...],
307
+ "debugModeEnabled": false
308
+ },
309
+ "heartbeat": true
310
+ }
311
+ ```
312
+
313
+ ## Environment Variables
314
+
315
+ ```env
316
+ SHIELDPRESS_API_KEY=sp_xxx
317
+ SHIELDPRESS_SITE_ID=site_xxx
318
+ ```
319
+
320
+ ## License
321
+
322
+ MIT
@@ -0,0 +1,27 @@
1
+ import { Request, Response, NextFunction } from 'express';
2
+ import { T as TrackerConfig, S as ShieldPressTracker } from './tracker-BJBniOSu.mjs';
3
+
4
+ /**
5
+ * Express middleware that tracks HTTP requests, errors, and security threats.
6
+ *
7
+ * Usage:
8
+ * ```ts
9
+ * import { createExpressTracker } from "@shieldpress/tracker/express";
10
+ *
11
+ * const { middleware, tracker, errorHandler } = createExpressTracker({
12
+ * apiKey: "sp_xxx",
13
+ * siteId: "site_xxx",
14
+ * });
15
+ *
16
+ * app.use(middleware);
17
+ * // ... routes ...
18
+ * app.use(errorHandler);
19
+ * ```
20
+ */
21
+ declare function createExpressTracker(config: TrackerConfig): {
22
+ middleware: (req: Request, res: Response, next: NextFunction) => void;
23
+ errorHandler: (err: Error, req: Request, res: Response, next: NextFunction) => void;
24
+ tracker: ShieldPressTracker;
25
+ };
26
+
27
+ export { ShieldPressTracker, TrackerConfig, createExpressTracker };
@@ -0,0 +1,27 @@
1
+ import { Request, Response, NextFunction } from 'express';
2
+ import { T as TrackerConfig, S as ShieldPressTracker } from './tracker-BJBniOSu.js';
3
+
4
+ /**
5
+ * Express middleware that tracks HTTP requests, errors, and security threats.
6
+ *
7
+ * Usage:
8
+ * ```ts
9
+ * import { createExpressTracker } from "@shieldpress/tracker/express";
10
+ *
11
+ * const { middleware, tracker, errorHandler } = createExpressTracker({
12
+ * apiKey: "sp_xxx",
13
+ * siteId: "site_xxx",
14
+ * });
15
+ *
16
+ * app.use(middleware);
17
+ * // ... routes ...
18
+ * app.use(errorHandler);
19
+ * ```
20
+ */
21
+ declare function createExpressTracker(config: TrackerConfig): {
22
+ middleware: (req: Request, res: Response, next: NextFunction) => void;
23
+ errorHandler: (err: Error, req: Request, res: Response, next: NextFunction) => void;
24
+ tracker: ShieldPressTracker;
25
+ };
26
+
27
+ export { ShieldPressTracker, TrackerConfig, createExpressTracker };