api-sentinel-express 0.0.0-stage → 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/CHANGELOG.md ADDED
@@ -0,0 +1,19 @@
1
+ # Changelog
2
+
3
+ All notable changes to **`api-sentinel-express`** will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [1.0.0] - 2026-11-18
9
+
10
+ ### Added
11
+ - **Core Express Middleware (`createApiSentinel`)**: Automatic lifecycle tracking for incoming HTTP requests and completed/aborted responses using high-resolution `performance.now()` timing.
12
+ - **Request ID Generation & Correlation**: Cryptographic UUID v4 generation via `node:crypto` (`randomUUID()`), automatic `X-Request-ID` response header injection, and strict validation for optional incoming correlation IDs.
13
+ - **Response-Time & Rolling P95 Analytics**: Fixed-capacity `Float64Array` circular ring buffer (`RollingWindowSampler`) providing $O(1)$ sample insertion and nearest-rank P95 latency calculation both globally and per endpoint.
14
+ - **Slow API Detection**: Configurable `slowRequestThresholdMs` (default `500ms`) with automatic flagging, counter aggregation, and structured `'slow-request'` warning events.
15
+ - **HTTP Status & Error Classification**: Tracks `1xx`, `2xx`, `3xx`, `4xx`, `404`, `5xx`, unmatched routes, and prematurely aborted connections.
16
+ - **Express Error-Handling Middleware (`sentinel.errorHandler`)**: Captures privacy-safe error classification metadata (`errorName`, `errorCode`) and forwards errors via `next(err)` without swallowing exceptions or leaking stack traces.
17
+ - **Route Normalization & Cardinality Protection**: Combines Express `req.baseUrl` + `req.route.path`, strips query strings, normalizes dynamic UUID/ObjectId/numeric path segments into `:id`, groups unmatched 404s under `/__unmatched__`, and enforces `maxRouteEntries` via an overflow bucket (`/__overflow_routes__`).
18
+ - **Privacy-First Structured Logger**: Machine-readable JSON event logging with custom `writer` callback support, strict field whitelisting, and complete failure isolation (`try / catch`).
19
+ - **Dual ESM & CommonJS Build**: Built with `esbuild` producing `dist/index.js` (ESM) and `dist/index.cjs` (CommonJS) with zero runtime dependencies.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Aviral Dwivedi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,431 @@
1
- # Temporary Holding Version
1
+ # API Sentinel (`api-sentinel-express`)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > **Monitor. Diagnose. Optimize.**
4
+ > Lightweight, privacy-first Express.js observability and API monitoring middleware with in-memory latency analytics, rolling P95 tracking, slow-request detection, and structured logging.
5
+
6
+ ---
7
+
8
+ ## 1. Product Overview
9
+
10
+ **API Sentinel** (`api-sentinel-express`) is a zero-dependency, developer-first observability toolkit built for Node.js and Express applications. By adding a single middleware to an Express server, developers gain immediate, real-time visibility into endpoint latency, rolling 95th percentile (P95) response times, slow endpoints, HTTP 4xx/5xx error distributions, and correlated request IDs—without sending data to external third-party servers.
11
+
12
+ ---
13
+
14
+ ## 2. The Problem
15
+
16
+ Modern web backends rely heavily on REST APIs, yet developers building small-to-medium Node.js applications frequently lack immediate operational visibility:
17
+
18
+ - An endpoint silently degrades to 2–3 seconds under load.
19
+ - Certain routes intermittently return HTTP 500 or HTTP 429 responses.
20
+ - Dynamic URLs (`/api/products/101`, `/api/products/102`) make per-endpoint performance hard to aggregate without high-cardinality memory leaks.
21
+ - Correlating an application error with its originating HTTP request requires grepping raw console logs.
22
+ - Naive request loggers accidentally capture passwords, `Authorization` headers, cookies, or database credentials in stack traces.
23
+
24
+ ---
25
+
26
+ ## 3. Our Solution
27
+
28
+ API Sentinel bridges the gap between raw terminal output and heavy enterprise APM agents:
29
+
30
+ - **One-Line Middleware Integration**: Plugs directly into Express 4 and Express 5.
31
+ - **Bounded In-Memory Storage**: Uses fixed-capacity circular ring buffers (`Float64Array` for latency windows) and route cardinality caps so memory usage never grows unbounded.
32
+ - **Privacy-First Defaults**: Never captures request bodies, query parameters, authorization tokens, cookies, or raw stack traces.
33
+ - **Dual Module Compatibility**: Ships both ESM (`dist/index.js`) and CommonJS (`dist/index.cjs`) bundles built from clean, modern JavaScript.
34
+
35
+ ---
36
+
37
+ ## 4. Core Features
38
+
39
+ 1. **Automatic Request & Response Tracking**: Observes every HTTP request from arrival until response completion (`finish`) or premature client disconnect (`close`).
40
+ 2. **High-Resolution Latency Analytics**: Measures duration via `performance.now()` and computes average, minimum, maximum, and rolling-window **P95** response times.
41
+ 3. **Configurable Slow API Detection**: Flags requests exceeding `slowRequestThresholdMs` (default `500ms`), increments slow counters, and emits structured `'slow-request'` warnings.
42
+ 4. **HTTP Status & Error Classification**: Tracks `1xx`, `2xx`, `3xx`, `4xx`, `404`, `5xx`, unmatched routes, and aborted requests.
43
+ 5. **Cryptographic Request ID Correlation**: Generates UUID v4 identifiers via `crypto.randomUUID()`, attaches `X-Request-ID` response headers, and correlates logs and metrics.
44
+ 6. **Intelligent Route Normalization**: Collapses Express route templates (`/api/products/:id`), dynamic UUIDs/ObjectIds/numeric segments, and unmatched 404s (`/__unmatched__`).
45
+ 7. **Structured Machine-Readable Logging**: Emits whitelisted JSON events with configurable filters and complete failure isolation.
46
+ 8. **Express Error-Handler Helper**: `sentinel.errorHandler` captures safe error classification metadata (`errorName`, `errorCode`) and forwards errors via `next(err)`.
47
+
48
+ ---
49
+
50
+ ## 5. Architecture Overview
51
+
52
+ ```mermaid
53
+ flowchart LR
54
+ Req["Incoming HTTP Request"] --> MW["sentinel.middleware"]
55
+ MW --> ID["Generate X-Request-ID"]
56
+ ID --> Timer["Start Monotonic Timer (WeakMap)"]
57
+ Timer --> Route["Express Route Handlers"]
58
+ Route --> Err["sentinel.errorHandler (Optional)"]
59
+ Route --> Finish["res.on('finish' | 'close')"]
60
+ Err --> Finish
61
+ Finish --> Norm["Route Normalizer (:id / /__unmatched__)"]
62
+ Norm --> Coll["Bounded MetricsCollector (Ring Buffers)"]
63
+ Norm --> Log["Privacy-Safe StructuredLogger"]
64
+ ```
65
+
66
+ ---
67
+
68
+ ## 6. Installation & Requirements
69
+
70
+ ```bash
71
+ npm install api-sentinel-express
72
+ ```
73
+
74
+ ### Supported Runtime & Framework Versions
75
+
76
+ - **Node.js**: `>= 20.0.0` (Verified on Node.js 22.x and 24.x)
77
+ - **Express.js**: `^4.18.0 || ^5.0.0` (Peer dependency)
78
+ - **Module Formats**: ES Modules (`import`) and CommonJS (`require`)
79
+
80
+ ---
81
+
82
+ ## 7. Quick-Start Example
83
+
84
+ ```javascript
85
+ import express from 'express';
86
+ import { createApiSentinel } from 'api-sentinel-express';
87
+
88
+ const app = express();
89
+ const sentinel = createApiSentinel({
90
+ slowRequestThresholdMs: 500,
91
+ });
92
+
93
+ app.use(sentinel.middleware);
94
+
95
+ app.get('/api/users', (req, res) => {
96
+ res.json({ users: [{ id: 1, name: 'Aarav' }] });
97
+ });
98
+
99
+ app.get('/internal/metrics', (req, res) => {
100
+ res.json(sentinel.getMetrics());
101
+ });
102
+
103
+ app.listen(3000);
104
+ ```
105
+
106
+ ---
107
+
108
+ ## 8. Complete Express Integration Example (With Error Handler)
109
+
110
+ ```javascript
111
+ import express from 'express';
112
+ import { createApiSentinel } from 'api-sentinel-express';
113
+
114
+ const app = express();
115
+ app.use(express.json());
116
+
117
+ const sentinel = createApiSentinel({
118
+ slowRequestThresholdMs: 350,
119
+ maxRecentRequests: 200,
120
+ maxRouteEntries: 100,
121
+ windowSampleSize: 1000,
122
+ ignorePaths: ['/internal/metrics', '/healthz'],
123
+ logging: {
124
+ enabled: true,
125
+ logSlowRequests: true,
126
+ logServerErrors: true,
127
+ logClientErrors: false,
128
+ logAllRequests: false,
129
+ },
130
+ });
131
+
132
+ // 1. Register request monitoring middleware before routes
133
+ app.use(sentinel.middleware);
134
+
135
+ app.get('/api/products/:id', (req, res) => {
136
+ res.json({ id: req.params.id, status: 'available' });
137
+ });
138
+
139
+ app.get('/api/orders/fail', (req, res, next) => {
140
+ const err = new Error('Database timeout on internal host');
141
+ err.name = 'DatabaseTimeoutError';
142
+ err.code = 'ETIMEDOUT';
143
+ next(err);
144
+ });
145
+
146
+ // Internal observability endpoint (protect in production!)
147
+ app.get('/internal/metrics', (req, res) => {
148
+ res.json({
149
+ metrics: sentinel.getMetrics(),
150
+ recentRequests: sentinel.getRecentRequests(25),
151
+ endpoints: sentinel.getEndpointMetrics(),
152
+ });
153
+ });
154
+
155
+ // 2. Register API Sentinel error handler after routes and before final error responder
156
+ app.use(sentinel.errorHandler);
157
+
158
+ app.use((err, req, res, next) => {
159
+ res.status(500).json({ error: 'Internal Server Error' });
160
+ });
161
+
162
+ app.listen(4000);
163
+ ```
164
+
165
+ ---
166
+
167
+ ## 9. Configuration Reference
168
+
169
+ | Option | Type | Default | Description |
170
+ | :--- | :--- | :--- | :--- |
171
+ | `slowRequestThresholdMs` | `number` | `500` | Latency threshold (ms) above which a request is marked `isSlow: true` (`1`–`3,600,000`). |
172
+ | `maxRecentRequests` | `number` | `200` | Maximum recent request records retained in the circular history buffer (`1`–`50,000`). |
173
+ | `maxRouteEntries` | `number` | `100` | Maximum distinct `(method + normalized route)` keys tracked before overflow bucket aggregation (`2`–`10,000`). |
174
+ | `windowSampleSize` | `number` | `1000` | Capacity of the rolling `Float64Array` window for P95 latency calculations (`10`–`50,000`). |
175
+ | `requestIdHeader` | `string` | `'X-Request-ID'` | Outgoing HTTP response header name for the request correlation ID. |
176
+ | `trustIncomingRequestId` | `boolean` | `false` | When `true`, accepts a client-supplied request ID header if it matches `/^[A-Za-z0-9_-]{8,64}$/`. |
177
+ | `logging` | `boolean \| object` | `true` | `false` to disable logging, or `{ enabled, logSlowRequests, logServerErrors, logClientErrors, logAllRequests, writer }`. |
178
+ | `ignorePaths` | `Array<string\|RegExp> \| Function` | `[]` | Paths, regex patterns, or `(req) => boolean` predicate to exclude from monitoring. |
179
+ | `fallbackRouteLabel` | `string` | `'/__overflow_routes__'` | Synthetic route label for the cardinality overflow bucket. |
180
+ | `unmatchedRouteLabel` | `string` | `'/__unmatched__'` | Synthetic route label for unmatched HTTP 404 responses. |
181
+
182
+ ---
183
+
184
+ ## 10. Public API Reference
185
+
186
+ Calling `const sentinel = createApiSentinel(options)` returns a frozen object with:
187
+
188
+ - **`sentinel.middleware`**: Express middleware `(req, res, next) => void`.
189
+ - **`sentinel.errorHandler`**: Express error middleware `(err, req, res, next) => void`.
190
+ - **`sentinel.getMetrics()`**: Returns a detached, deeply cloned aggregate metrics snapshot.
191
+ - **`sentinel.getRecentRequests(limit?)`**: Returns an array of recent request records ordered from newest to oldest.
192
+ - **`sentinel.getEndpointMetrics()`**: Returns an array of per-endpoint analytics sorted by request volume.
193
+ - **`sentinel.resetMetrics()`**: Clears all in-memory counters, endpoint metrics, latency samples, and recent request records.
194
+ - **`sentinel.getConfig()`**: Returns the resolved, frozen configuration object.
195
+
196
+ ---
197
+
198
+ ## 11. Example Metrics Response (`sentinel.getMetrics()`)
199
+
200
+ ```json
201
+ {
202
+ "generatedAt": "2026-11-18T15:30:12.410Z",
203
+ "startedAt": "2026-11-18T15:25:00.000Z",
204
+ "uptimeSeconds": 312.41,
205
+ "totalRequests": 42,
206
+ "informationalRequests": 0,
207
+ "successfulRequests": 36,
208
+ "redirectRequests": 0,
209
+ "notModifiedRequests": 0,
210
+ "clientErrorRequests": 4,
211
+ "serverErrorRequests": 2,
212
+ "notFoundRequests": 2,
213
+ "unmatchedRouteRequests": 2,
214
+ "slowRequests": 3,
215
+ "abortedRequests": 0,
216
+ "errorRate": 14.29,
217
+ "slowRequestRate": 7.14,
218
+ "latency": {
219
+ "avgMs": 48.62,
220
+ "minMs": 2.14,
221
+ "maxMs": 612.85,
222
+ "p95Ms": 485.2,
223
+ "sampleCount": 42
224
+ },
225
+ "statusDistribution": {
226
+ "1xx": 0,
227
+ "2xx": 36,
228
+ "3xx": 0,
229
+ "4xx": 4,
230
+ "5xx": 2
231
+ },
232
+ "statusCodeCounts": {
233
+ "200": 34,
234
+ "201": 2,
235
+ "400": 2,
236
+ "404": 2,
237
+ "500": 2
238
+ },
239
+ "endpoints": [
240
+ {
241
+ "key": "GET /api/products/:id",
242
+ "method": "GET",
243
+ "route": "/api/products/:id",
244
+ "requestCount": 25,
245
+ "informationalCount": 0,
246
+ "successCount": 25,
247
+ "redirectCount": 0,
248
+ "notModifiedCount": 0,
249
+ "errorCount": 0,
250
+ "clientErrorCount": 0,
251
+ "serverErrorCount": 0,
252
+ "slowRequestCount": 0,
253
+ "avgDurationMs": 14.3,
254
+ "minDurationMs": 8.12,
255
+ "maxDurationMs": 28.4,
256
+ "p95DurationMs": 25.1,
257
+ "lastSeenAt": "2026-11-18T15:30:10.100Z",
258
+ "isOverflowBucket": false
259
+ }
260
+ ],
261
+ "cardinalityOverflowCount": 0,
262
+ "config": {
263
+ "slowRequestThresholdMs": 350,
264
+ "maxRecentRequests": 200,
265
+ "maxRouteEntries": 100,
266
+ "windowSampleSize": 1000,
267
+ "requestIdHeader": "X-Request-ID"
268
+ }
269
+ }
270
+ ```
271
+
272
+ ---
273
+
274
+ ## 12. Structured Logging Output Examples
275
+
276
+ When a request exceeds `slowRequestThresholdMs`:
277
+
278
+ ```json
279
+ {
280
+ "type": "slow-request",
281
+ "requestId": "8f1d4e9a-3c2b-4d7a-9e1f-5b6a7c8d9e0f",
282
+ "method": "GET",
283
+ "route": "/api/demo/slow",
284
+ "statusCode": 200,
285
+ "durationMs": 542.18,
286
+ "timestamp": "2026-11-18T15:30:05.120Z",
287
+ "outcome": "success",
288
+ "isSlow": true,
289
+ "isUnmatchedRoute": false,
290
+ "aborted": false
291
+ }
292
+ ```
293
+
294
+ When an error traverses `sentinel.errorHandler`:
295
+
296
+ ```json
297
+ {
298
+ "type": "error-detected",
299
+ "requestId": "c4a1b2d3-8e9f-4a5b-8c7d-1e2f3a4b5c6d",
300
+ "method": "GET",
301
+ "route": "/api/demo/error",
302
+ "statusCode": 500,
303
+ "durationMs": 16.42,
304
+ "timestamp": "2026-11-18T15:30:09.811Z",
305
+ "outcome": "server_error",
306
+ "isSlow": false,
307
+ "isUnmatchedRoute": false,
308
+ "errorName": "DatabasePoolExhaustedError",
309
+ "errorCode": "ECONNREFUSED"
310
+ }
311
+ ```
312
+
313
+ ---
314
+
315
+ ## 13. Privacy and Security Guarantees
316
+
317
+ - **Zero External Telemetry**: Never phones home or opens network connections.
318
+ - **No Sensitive Payload Capture**: Never inspects `req.body`, `Authorization` headers, cookies, or query parameters (`?token=...` is stripped before normalization).
319
+ - **Safe Error Metadata Only**: Strips `err.message` and `err.stack` so credentials or SQL statements in exception messages cannot leak into metrics.
320
+ - **Untrusted External Request IDs by Default**: Generates fresh UUID v4 identifiers unless `trustIncomingRequestId: true` is configured and passes strict `/^[A-Za-z0-9_-]{8,64}$/` validation.
321
+ - See [SECURITY.md](./SECURITY.md) for the full security policy.
322
+
323
+ ---
324
+
325
+ ## 14. Performance & Actual Benchmark Results
326
+
327
+ Run the reproducible benchmark script with:
328
+
329
+ ```bash
330
+ npm run benchmark
331
+ ```
332
+
333
+ ### Actual Measured Benchmark (`benchmarks/overhead-benchmark.js`)
334
+
335
+ - **Environment**: Apple M4 (`darwin arm64`, 10 logical cores), Node.js `v22.23.0` / `v24.14.0`
336
+ - **Workload**: `1,500` HTTP GET requests (`/api/items/:id`) at concurrency `25` following a `200`-request warmup phase (`logging: false` to measure pure middleware & metrics aggregation overhead).
337
+
338
+ | Scenario | Requests / sec | Avg Latency (ms) | P95 Latency (ms) | Total Time (ms) |
339
+ | :--- | ---: | ---: | ---: | ---: |
340
+ | **Baseline Express (No Middleware)** | `13,024.53` | `1.902 ms` | `2.41 ms` | `115.17 ms` |
341
+ | **Express + API Sentinel Middleware** | `14,952.35` | `1.663 ms` | `2.65 ms` | `100.32 ms` |
342
+
343
+ - **P95 Latency Delta**: `+0.24 ms` (`2.65 ms` vs. `2.41 ms`).
344
+ - **Interpretation**: Per-request recording uses $O(1)$ circular buffers (`Float64Array`) and `WeakMap` lookups, adding sub-millisecond overhead (~`0.24 ms` at P95) that falls within normal V8 JIT execution variance.
345
+
346
+ ---
347
+
348
+ ## 15. Testing & Code Coverage
349
+
350
+ ```bash
351
+ # Run unit and integration test suite
352
+ npm test
353
+
354
+ # Run test suite with V8 coverage
355
+ npm run test:coverage
356
+
357
+ # Run ESLint & Prettier verification
358
+ npm run lint
359
+ npm run format:check
360
+ ```
361
+
362
+ ### Verified Coverage (`34 / 34` tests passing across 3 test files)
363
+
364
+ - **Statements**: `97.35%` (Target: `>= 90%`)
365
+ - **Branches**: `87.67%` (Target: `>= 85%`)
366
+ - **Functions**: `98.11%` (Target: `>= 90%`)
367
+ - **Lines**: `97.35%` (Target: `>= 90%`)
368
+
369
+ ---
370
+
371
+ ## 16. Separate Consumer Demonstration Application (`api-sentinel-demo`)
372
+
373
+ A complete full-stack Express + React (Vite) observability application is located in the sibling directory `../api-sentinel-demo`:
374
+
375
+ ```bash
376
+ # Terminal 1 — Start the Express Demo Backend (Port 4000)
377
+ cd ../api-sentinel-demo/backend
378
+ npm install
379
+ npm start
380
+
381
+ # Terminal 2 — Start the React Observability Dashboard (Port 5173)
382
+ cd ../api-sentinel-demo/frontend
383
+ npm install
384
+ npm run dev
385
+ ```
386
+
387
+ Open `http://localhost:5173` to interactively trigger normal 2xx requests, slow requests (`>350ms`), client errors (`400` / `404`), server errors (`500`), and 15-request bursts.
388
+
389
+ ---
390
+
391
+ ## 17. Troubleshooting
392
+
393
+ - **Routes show dynamic paths instead of `:id` templates**: Ensure `app.use(sentinel.middleware)` is registered **before** your routes so its `res.on('finish')` listener runs after Express populates `req.route.path`.
394
+ - **`errorName` is missing on 500 responses**: Register `app.use(sentinel.errorHandler)` **after** your routes and **before** your final Express error responder.
395
+ - **Metrics reset when server restarts**: API Sentinel uses in-memory storage; metrics are process-local and reset on process restart or `nodemon`/`node --watch` reload.
396
+
397
+ ---
398
+
399
+ ## 18. Limitations & Known Constraints
400
+
401
+ 1. **Process-Local In-Memory Storage**: Metrics are stored in the current Node.js process RAM and are not automatically shared across multiple cluster workers or containers.
402
+ 2. **Rolling Window P95**: P95 latency is calculated over the most recent `windowSampleSize` (default `1,000`) requests rather than lifetime unbounded history.
403
+ 3. **Express-Specific Middleware**: Designed specifically for Express 4 and Express 5 applications.
404
+
405
+ ---
406
+
407
+ ## 19. Documentation Index
408
+
409
+ - [Architecture Guide](./docs/ARCHITECTURE.md)
410
+ - [Complete API Reference](./docs/API_REFERENCE.md)
411
+ - [Engineering Design Decisions](./docs/DESIGN_DECISIONS.md)
412
+ - [Testing & Coverage Report](./docs/TESTING.md)
413
+ - [Security & Privacy Policy](./SECURITY.md)
414
+ - [Future Product Roadmap](./docs/FUTURE_ROADMAP.md)
415
+ - [NPM Publishing Guide](./NPM_PUBLISHING_GUIDE.md)
416
+ - [University Viva Preparation Guide](./VIVA_PREPARATION.md)
417
+ - [University Submission Guide](./SUBMISSION.md)
418
+
419
+ ---
420
+
421
+ ## 20. Repository & Package Links
422
+
423
+ - **GitHub Repository (Package)**: `https://github.com/<YOUR_GITHUB_USERNAME>/api-sentinel-express` *(configure placeholder after pushing)*
424
+ - **NPM Registry Page**: `https://www.npmjs.com/package/api-sentinel-express` *(available upon running `npm publish`)*
425
+ - **GitHub Repository (Consumer Demo Application)**: `https://github.com/<YOUR_GITHUB_USERNAME>/api-sentinel-demo` *(configure placeholder after pushing)*
426
+
427
+ ---
428
+
429
+ ## 21. License
430
+
431
+ Released under the [MIT License](./LICENSE).
package/SECURITY.md ADDED
@@ -0,0 +1,55 @@
1
+ # Security and Privacy Policy — API Sentinel (`api-sentinel-express`)
2
+
3
+ ## 1. Privacy-First Engineering Principles
4
+
5
+ API Sentinel is designed from the ground up with **privacy-by-default** and **zero external telemetry**:
6
+
7
+ 1. **No External Network Transmission**: The package makes zero outbound HTTP requests, opens zero sockets, and never transmits telemetry to third-party servers. All metrics remain strictly in the host Node.js process memory.
8
+ 2. **No Request Body Capture**: `req.body` is never read, inspected, cloned, or stored under any configuration.
9
+ 3. **No Sensitive Header or Cookie Capture**: `Authorization`, `Cookie`, `Set-Cookie`, `X-API-Key`, and all other HTTP request headers are excluded from metrics snapshots, recent request records, and structured logs.
10
+ 4. **Query-String Stripping**: `cleanPathString()` in `src/core/route-normalizer.js` strips all query parameters (`?token=...&password=...`) and URL fragments (`#...`) before recording routes or emitting logs.
11
+ 5. **Dynamic URL Normalization**: Raw dynamic path segments (numeric IDs, UUIDs, MongoDB ObjectIds, long opaque tokens) are collapsed into `:id` or matched against Express `req.route.path` templates so user-specific identifiers in URLs do not leak into endpoint metric keys.
12
+ 6. **Stack Trace & Exception Message Suppression**: `extractSafeErrorMetadata()` in `src/utils/sanitizer.js` records only the sanitized error class name (`errorName`, e.g., `DatabaseError`) and standard error code (`errorCode`, e.g., `ECONNREFUSED`). Raw `err.message` and `err.stack` strings—which frequently contain database connection strings, SQL queries, or PII—are never stored in metrics or emitted by API Sentinel.
13
+ 7. **Untrusted Incoming Request IDs by Default**: By default (`trustIncomingRequestId: false`), API Sentinel ignores client-supplied `X-Request-ID` headers and generates a fresh cryptographic UUID v4 via `crypto.randomUUID()`. When `trustIncomingRequestId: true` is explicitly enabled, incoming IDs are validated against `/^[A-Za-z0-9_-]{8,64}$/` to prevent CRLF header splitting and log injection.
14
+ 8. **Zero Runtime Dependencies**: `api-sentinel-express` has zero runtime `dependencies` in `package.json` (relying only on built-in Node.js modules `node:crypto` and `node:perf_hooks`, plus `express` as a peer dependency), minimizing supply-chain attack surface.
15
+
16
+ ---
17
+
18
+ ## 2. Safe Exposure of Metrics Endpoints
19
+
20
+ API Sentinel provides programmatic methods (`sentinel.getMetrics()`, `sentinel.getRecentRequests()`, `sentinel.getEndpointMetrics()`) and does **not** automatically mount any public HTTP route on your Express application.
21
+
22
+ If you expose a metrics route (such as `GET /internal/metrics` or `GET /api/metrics`), you must protect it in production environments:
23
+
24
+ - Restrict access to internal private networks / VPCs or localhost.
25
+ - Require authentication middleware (e.g., mutual TLS, Bearer JWT, or an internal API token header such as `X-Sentinel-Token`).
26
+ - Do not expose internal endpoint metrics publicly on the open internet without access control.
27
+
28
+ ---
29
+
30
+ ## 3. Bounded Memory & Denial-of-Service (DoS) Protection
31
+
32
+ To protect the host Node.js process from memory exhaustion under high traffic or malicious URL-scanning attacks:
33
+
34
+ - **Unmatched 404 Grouping**: All unmatched 404 requests are automatically grouped under `/__unmatched__`, preventing random bot scanner URLs from creating thousands of metric entries.
35
+ - **Endpoint Cardinality Cap (`maxRouteEntries`)**: Capped at `100` routes by default. Any excess routes are aggregated into a single fallback bucket (`ALL /__overflow_routes__`).
36
+ - **Fixed Circular Ring Buffers**: Recent request history (`maxRecentRequests`, default `200`) and P95 latency windows (`windowSampleSize`, default `1000` using pre-allocated `Float64Array` buffers) overwrite the oldest entries in $O(1)$ time.
37
+
38
+ ---
39
+
40
+ ## 4. Supported Versions
41
+
42
+ | Version | Supported | Node.js Compatibility | Express Compatibility |
43
+ | :--- | :--- | :--- | :--- |
44
+ | `1.0.x` | Yes | Node.js `>= 20.0.0` (Tested on 22 & 24) | Express `^4.18.0 \|\| ^5.0.0` |
45
+
46
+ ---
47
+
48
+ ## 5. Reporting a Vulnerability
49
+
50
+ If you discover a security or privacy vulnerability in `api-sentinel-express`:
51
+
52
+ 1. **Do not open a public GitHub issue.**
53
+ 2. Report the finding privately to the maintainer via email (`your-email@example.com`) or through GitHub Private Vulnerability Reporting on the repository's **Security** tab.
54
+ 3. Include a minimal reproduction script, affected configuration options, and potential impact.
55
+ 4. You will receive an acknowledgment within 48 hours and a remediation timeline once triaged.