-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaudit.middleware.ts
More file actions
43 lines (37 loc) · 1.41 KB
/
Copy pathaudit.middleware.ts
File metadata and controls
43 lines (37 loc) · 1.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import { Injectable, Logger, NestMiddleware } from '@nestjs/common';
import { NextFunction, Request, Response } from 'express';
const MUTATING_METHODS = new Set(['POST', 'PATCH', 'PUT', 'DELETE']);
/**
* Audits every mutating request. Implemented as middleware (not an
* interceptor) on purpose: middleware runs *before* guards, so by hooking
* `res.on('finish')` we capture the FINAL response status of every request —
* including ones rejected by the API-key guard (401), which an interceptor
* would miss because guards short-circuit before interceptors run.
*
* One structured line per request: method, path, status, latency, user agent.
*/
@Injectable()
export class AuditMiddleware implements NestMiddleware {
private readonly logger = new Logger('Audit');
use(req: Request, res: Response, next: NextFunction): void {
if (!MUTATING_METHODS.has(req.method)) {
return next();
}
const startedAt = process.hrtime.bigint();
res.on('finish', () => {
const durationMs =
Number(process.hrtime.bigint() - startedAt) / 1_000_000;
this.logger.log(
JSON.stringify({
timestamp: new Date().toISOString(),
method: req.method,
path: req.originalUrl,
status: res.statusCode,
durationMs: Math.round(durationMs * 100) / 100,
userAgent: req.headers['user-agent'] ?? 'unknown',
}),
);
});
next();
}
}