forked from Talenttrust/Talenttrust-Backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
95 lines (87 loc) · 3.21 KB
/
Copy pathmiddleware.ts
File metadata and controls
95 lines (87 loc) · 3.21 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/**
* @module audit/middleware
* @description Express middleware for automatic audit logging of HTTP requests.
*
* Attaches a per-request audit helper to `res.locals.audit` so route handlers
* can emit structured audit events without importing the service directly.
*
* When `AUDIT_ENABLED=false` the middleware attaches a no-op helper so that
* callers compiled against `res.locals.audit.log(...)` continue to work
* without error — they simply produce no stored entry.
*
* Security notes:
* - IP addresses are extracted from X-Forwarded-For only when the app is
* behind a trusted proxy. Set `app.set('trust proxy', true)` accordingly.
* - Correlation IDs from X-Correlation-ID headers are passed through as-is;
* validate/sanitise them if they are user-controlled.
*/
import type { Request, Response, NextFunction } from 'express';
import { auditService } from './service';
import type { AuditEntry, CreateAuditEntryInput } from './types';
import { validateEnv } from '../config/env.schema';
/** Helper attached to res.locals for route-level audit logging. */
export interface RequestAuditHelper {
/**
* Emits an audit event scoped to the current HTTP request.
* Automatically injects ipAddress and correlationId from the request.
* When AUDIT_ENABLED=false this is a no-op and returns a stub entry.
*/
log(input: Omit<CreateAuditEntryInput, 'ipAddress' | 'correlationId'>): AuditEntry;
}
declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace Express {
interface Locals {
audit: RequestAuditHelper;
}
}
}
/**
* Attaches `res.locals.audit` to every request.
* Mount this before your route handlers.
*
* When `AUDIT_ENABLED=false` (runtime env), the attached helper is a no-op:
* it returns a stub `AuditEntry` without writing anything to the store.
*
* @example
* ```ts
* app.use(auditMiddleware);
* app.post('/api/v1/contracts', (req, res) => {
* res.locals.audit.log({ action: 'CONTRACT_CREATED', ... });
* res.json({ ... });
* });
* ```
*/
export function auditMiddleware(req: Request, res: Response, next: NextFunction): void {
const env = validateEnv();
if (!env.AUDIT_ENABLED) {
// Feature flag off — attach a no-op helper so route code compiles and
// runs without branching on the flag themselves.
res.locals.audit = {
log(_input: Omit<CreateAuditEntryInput, 'ipAddress' | 'correlationId'>): AuditEntry {
return {
id: '',
timestamp: new Date().toISOString(),
hash: '',
previousHash: '',
action: _input.action,
severity: _input.severity,
actor: _input.actor,
resource: _input.resource,
resourceId: _input.resourceId,
metadata: _input.metadata,
};
},
} satisfies RequestAuditHelper;
next();
return;
}
const ipAddress = (req.ip ?? req.socket?.remoteAddress) as string | undefined;
const correlationId = req.headers['x-correlation-id'] as string | undefined;
res.locals.audit = {
log(input: Omit<CreateAuditEntryInput, 'ipAddress' | 'correlationId'>): AuditEntry {
return auditService.log({ ...input, ipAddress, correlationId });
},
} satisfies RequestAuditHelper;
next();
}