LifeMate — Personal, Family & Learning Companion

feat/aparat-learning-library
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 140 lines 5.11 KB
Raw
1 import crypto from 'node:crypto';
2 import { isIP } from 'node:net';
3
4 const buckets = new Map();
5 const nowSeconds = () => Math.floor(Date.now() / 1000);
6 const positiveInt = (value, fallback) => {
7 const n = Number(value);
8 return Number.isInteger(n) && n > 0 ? n : fallback;
9 };
10
11 export function requestContext(req, res, next) {
12 const incoming = String(req.headers['x-request-id'] ?? '');
13 const requestId = /^[A-Za-z0-9._:-]{8,128}$/.test(incoming)
14 ? incoming
15 : crypto.randomUUID();
16 req.requestId = requestId;
17 req.requestStartedAt = process.hrtime.bigint();
18 res.setHeader('X-Request-Id', requestId);
19 res.setHeader('X-Content-Type-Options', 'nosniff');
20 res.setHeader('X-Frame-Options', 'DENY');
21 res.setHeader('Referrer-Policy', 'no-referrer');
22 res.setHeader('Permissions-Policy', 'camera=(), microphone=(), geolocation=()');
23 res.setHeader('Cross-Origin-Resource-Policy', 'same-site');
24 next();
25 }
26
27 export function requestTelemetry(req, res, next) {
28 res.on('finish', () => {
29 if (process.env.NODE_ENV === 'test' || process.env.LOG_REQUESTS === 'false') return;
30 const start = req.requestStartedAt ?? process.hrtime.bigint();
31 const durationMs = Number(process.hrtime.bigint() - start) / 1e6;
32 const event = {
33 type: 'http_request',
34 requestId: req.requestId,
35 method: req.method,
36 path: req.route?.path ?? req.path,
37 status: res.statusCode,
38 durationMs: Math.round(durationMs * 10) / 10,
39 };
40 console.log(JSON.stringify(event));
41 });
42 next();
43 }
44
45 function clientKey(req) {
46 return req.ip || req.socket?.remoteAddress || 'unknown';
47 }
48
49 // Only an operator-pinned internal gateway may supply forwarding information.
50 // Standalone API defaults to ignoring all forwarded headers.
51 export function configureTrustedProxy(app, value = process.env.TRUSTED_PROXY_CIDRS ?? '') {
52 const entries = value.split(',').map(x => x.trim()).filter(Boolean);
53 if (entries.length > 8) throw new Error('Invalid trusted proxy allowlist');
54 for (const entry of entries) {
55 const [address, prefix, ...extra] = entry.split('/');
56 const bits = isIP(address) === 4 ? 32 : isIP(address) === 6 ? 128 : 0;
57 if (!bits || extra.length || (prefix !== undefined && (!/^\d+$/.test(prefix) || Number(prefix) < 1 || Number(prefix) > bits))) {
58 throw new Error('Invalid trusted proxy address');
59 }
60 }
61 app.set('trust proxy', entries.length ? entries : false);
62 }
63
64 function profileFor(req) {
65 const path = req.path;
66 if (path.startsWith('/v1/auth/')) {
67 return {
68 name: 'auth',
69 limit: positiveInt(process.env.RATE_LIMIT_AUTH_MAX, 10),
70 windowSeconds: positiveInt(process.env.RATE_LIMIT_AUTH_WINDOW_SECONDS, 10 * 60),
71 };
72 }
73 if (/^\/v1\/ai\//.test(path) || /\/family-guidance$/.test(path)) {
74 return {
75 name: 'ai',
76 limit: positiveInt(process.env.RATE_LIMIT_AI_MAX, 30),
77 windowSeconds: positiveInt(process.env.RATE_LIMIT_AI_WINDOW_SECONDS, 10 * 60),
78 };
79 }
80 return {
81 name: 'general',
82 limit: positiveInt(process.env.RATE_LIMIT_GENERAL_MAX, 120),
83 windowSeconds: positiveInt(process.env.RATE_LIMIT_GENERAL_WINDOW_SECONDS, 60),
84 };
85 }
86
87 export function rateLimit(req, res, next) {
88 if (process.env.NODE_ENV === 'test' || req.method === 'OPTIONS' || req.path === '/live' || req.path === '/ready' || req.path === '/health') {
89 return next();
90 }
91 const profile = profileFor(req);
92 const now = nowSeconds();
93 const windowStart = Math.floor(now / profile.windowSeconds) * profile.windowSeconds;
94 const key = `${profile.name}:${clientKey(req)}:${windowStart}`;
95 const count = (buckets.get(key) ?? 0) + 1;
96 buckets.set(key, count);
97
98 if (buckets.size > 10000) {
99 for (const storedKey of buckets.keys()) {
100 const storedWindow = Number(storedKey.split(':').at(-1));
101 if (storedWindow + 3600 < now) buckets.delete(storedKey);
102 }
103 }
104
105 const remaining = Math.max(0, profile.limit - count);
106 res.setHeader('RateLimit-Limit', String(profile.limit));
107 res.setHeader('RateLimit-Remaining', String(remaining));
108 if (count > profile.limit) {
109 const retryAfter = Math.max(1, windowStart + profile.windowSeconds - now);
110 res.setHeader('Retry-After', String(retryAfter));
111 return res.status(429).json({ error: 'rate_limited' });
112 }
113 next();
114 }
115
116 export function operationalErrorHandler(err, req, res, _next) {
117 const event = {
118 type: 'http_error',
119 requestId: req.requestId,
120 method: req.method,
121 path: req.route?.path ?? req.path,
122 errorClass: err?.name || 'Error',
123 };
124 if (process.env.NODE_ENV !== 'test') console.error(JSON.stringify(event));
125 if (res.headersSent) {
126 // Passing the original error to Express would print its raw message/stack.
127 res.destroy();
128 return;
129 }
130 if (err?.type === 'entity.parse.failed') {
131 return res.status(400).json({ error: 'invalid_json', requestId: req.requestId });
132 }
133 if (err?.type === 'entity.too.large') {
134 return res.status(413).json({ error: 'request_body_too_large', requestId: req.requestId });
135 }
136 if (err?.code === 'CORS_ORIGIN_DENIED') {
137 return res.status(403).json({ error: 'cors_origin_denied', requestId: req.requestId });
138 }
139 res.status(500).json({ error: 'internal_error', requestId: req.requestId });
140 }