@davoodmehraban89 / LifeMate / commits / 72c0c0d
Fork 0

LifeMate — Personal, Family & Learning Companion

feat: add operational hardening middleware

davoodmehraban89 committed Oct 5, 2026 at 17:10 UTC 72c0c0de6597f678c7da7d3a5ea15f5f6a4a66c7
1 file changed +111
backend/src/operations.js new
+111
@@ -0,0 +1,111 @@
1 +import crypto from 'node:crypto';
2 +
3 +const buckets = new Map();
4 +const nowSeconds = () => Math.floor(Date.now() / 1000);
5 +const positiveInt = (value, fallback) => {
6 + const n = Number(value);
7 + return Number.isInteger(n) && n > 0 ? n : fallback;
8 +};
9 +
10 +export function requestContext(req, res, next) {
11 + const incoming = String(req.headers['x-request-id'] ?? '');
12 + const requestId = /^[A-Za-z0-9._:-]{8,128}$/.test(incoming)
13 + ? incoming
14 + : crypto.randomUUID();
15 + req.requestId = requestId;
16 + req.requestStartedAt = process.hrtime.bigint();
17 + res.setHeader('X-Request-Id', requestId);
18 + res.setHeader('X-Content-Type-Options', 'nosniff');
19 + res.setHeader('X-Frame-Options', 'DENY');
20 + res.setHeader('Referrer-Policy', 'no-referrer');
21 + res.setHeader('Permissions-Policy', 'camera=(), microphone=(), geolocation=()');
22 + res.setHeader('Cross-Origin-Resource-Policy', 'same-site');
23 + next();
24 +}
25 +
26 +export function requestTelemetry(req, res, next) {
27 + res.on('finish', () => {
28 + if (process.env.NODE_ENV === 'test' || process.env.LOG_REQUESTS === 'false') return;
29 + const start = req.requestStartedAt ?? process.hrtime.bigint();
30 + const durationMs = Number(process.hrtime.bigint() - start) / 1e6;
31 + const event = {
32 + type: 'http_request',
33 + requestId: req.requestId,
34 + method: req.method,
35 + path: req.route?.path ?? req.path,
36 + status: res.statusCode,
37 + durationMs: Math.round(durationMs * 10) / 10,
38 + };
39 + console.log(JSON.stringify(event));
40 + });
41 + next();
42 +}
43 +
44 +function clientKey(req) {
45 + return req.socket?.remoteAddress || 'unknown';
46 +}
47 +
48 +function profileFor(req) {
49 + const path = req.path;
50 + if (path.startsWith('/v1/auth/')) {
51 + return {
52 + name: 'auth',
53 + limit: positiveInt(process.env.RATE_LIMIT_AUTH_MAX, 10),
54 + windowSeconds: positiveInt(process.env.RATE_LIMIT_AUTH_WINDOW_SECONDS, 10 * 60),
55 + };
56 + }
57 + if (/^\/v1\/ai\//.test(path) || /\/family-guidance$/.test(path)) {
58 + return {
59 + name: 'ai',
60 + limit: positiveInt(process.env.RATE_LIMIT_AI_MAX, 30),
61 + windowSeconds: positiveInt(process.env.RATE_LIMIT_AI_WINDOW_SECONDS, 10 * 60),
62 + };
63 + }
64 + return {
65 + name: 'general',
66 + limit: positiveInt(process.env.RATE_LIMIT_GENERAL_MAX, 120),
67 + windowSeconds: positiveInt(process.env.RATE_LIMIT_GENERAL_WINDOW_SECONDS, 60),
68 + };
69 +}
70 +
71 +export function rateLimit(req, res, next) {
72 + if (process.env.NODE_ENV === 'test' || req.method === 'OPTIONS' || req.path === '/live' || req.path === '/ready' || req.path === '/health') {
73 + return next();
74 + }
75 + const profile = profileFor(req);
76 + const now = nowSeconds();
77 + const windowStart = Math.floor(now / profile.windowSeconds) * profile.windowSeconds;
78 + const key = `${profile.name}:${clientKey(req)}:${windowStart}`;
79 + const count = (buckets.get(key) ?? 0) + 1;
80 + buckets.set(key, count);
81 +
82 + if (buckets.size > 10000) {
83 + for (const storedKey of buckets.keys()) {
84 + const storedWindow = Number(storedKey.split(':').at(-1));
85 + if (storedWindow + 3600 < now) buckets.delete(storedKey);
86 + }
87 + }
88 +
89 + const remaining = Math.max(0, profile.limit - count);
90 + res.setHeader('RateLimit-Limit', String(profile.limit));
91 + res.setHeader('RateLimit-Remaining', String(remaining));
92 + if (count > profile.limit) {
93 + const retryAfter = Math.max(1, windowStart + profile.windowSeconds - now);
94 + res.setHeader('Retry-After', String(retryAfter));
95 + return res.status(429).json({ error: 'rate_limited' });
96 + }
97 + next();
98 +}
99 +
100 +export function operationalErrorHandler(err, req, res, _next) {
101 + const event = {
102 + type: 'http_error',
103 + requestId: req.requestId,
104 + method: req.method,
105 + path: req.route?.path ?? req.path,
106 + errorClass: err?.name || 'Error',
107 + };
108 + if (process.env.NODE_ENV !== 'test') console.error(JSON.stringify(event));
109 + if (res.headersSent) return;
110 + res.status(500).json({ error: 'internal_error', requestId: req.requestId });
111 +}