LifeMate — Personal, Family & Learning Companion

test/role-entry-apk
chore/phase1-repository-cleanup deploy/stable-web-apk deployment-static design/mobile-accessibility-v2 design/mobile-navigation-review docs/child-education-access-decision docs/offline-data-rescue-options docs/owner-guide-and-delivery-plan docs/phase1-policy-options docs/public-review-live-2026-10-15 feat/aparat-learning-library feat/child-device-safety feat/child-identity-schema feat/flutter-mobile-navigation feat/learning-content-operations feat/local-signing-preflight feat/online-family-stage0 feat/personal-encrypted-recovery feat/private-planner-series-api feat/public-review-page feat/standalone-weekly-planner feat/weekly-planner-android final-feature-1/iran-family-school fix/auth-abuse-expiry-safety fix/auth-expiry-after-lock fix/backend-request-safety fix/lifeguide-bootstrap-naming-ci fix/lifeguide-pages-qa-base-preflight fix/lifeguide-qa-pages-env-deployment fix/local-task-persistence fix/managed-child-session-boundary fix/personal-jalali-dates fix/personal-notification-controls fix/personal-upgrade-delivery-guard fix/sms-approval-gates fix/study-duration-display infra/cloudflare-neon-migration infra/lifeguide-cloudflare-qa infra/lifeguide-github-pages-qa infra/lifeguide-supabase-qa main phase-1/foundation-completion phase-2/product-foundation-identity phase-3/planner-school-family-core phase-4/ai-learning-wellbeing phase-5/hardening-observability-release test/android-reminder-acceptance test/personal-notification-settings test/personal-recovery-acceptance test/role-entry-apk
js 111 lines 3.77 KB
Raw
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 }