LifeMate — Personal, Family & Learning Companion

fix/lifeguide-bootstrap-naming-ci
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 150 lines 5.66 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 const discovery = req.method === 'GET' && path === '/v1/auth/capabilities';
67 // Express accepts case variants and trailing slashes. Only these literal
68 // method/path pairs receive the session quota; near matches remain strict.
69 if (!discovery && /^\/v1\/auth(?:\/|$)/i.test(path)) {
70 if (req.method === 'POST' && (path === '/v1/auth/refresh' || path === '/v1/auth/logout')) {
71 return {
72 name: 'session',
73 limit: positiveInt(process.env.RATE_LIMIT_SESSION_MAX, 60),
74 windowSeconds: positiveInt(process.env.RATE_LIMIT_SESSION_WINDOW_SECONDS, 10 * 60),
75 };
76 }
77 return {
78 name: 'auth',
79 limit: positiveInt(process.env.RATE_LIMIT_AUTH_MAX, 10),
80 windowSeconds: positiveInt(process.env.RATE_LIMIT_AUTH_WINDOW_SECONDS, 10 * 60),
81 };
82 }
83 if (/^\/v1\/ai\//.test(path) || /\/family-guidance$/.test(path)) {
84 return {
85 name: 'ai',
86 limit: positiveInt(process.env.RATE_LIMIT_AI_MAX, 30),
87 windowSeconds: positiveInt(process.env.RATE_LIMIT_AI_WINDOW_SECONDS, 10 * 60),
88 };
89 }
90 return {
91 name: 'general',
92 limit: positiveInt(process.env.RATE_LIMIT_GENERAL_MAX, 120),
93 windowSeconds: positiveInt(process.env.RATE_LIMIT_GENERAL_WINDOW_SECONDS, 60),
94 };
95 }
96
97 export function rateLimit(req, res, next) {
98 if (process.env.NODE_ENV === 'test' || req.method === 'OPTIONS' || req.path === '/live' || req.path === '/ready' || req.path === '/health') {
99 return next();
100 }
101 const profile = profileFor(req);
102 const now = nowSeconds();
103 const windowStart = Math.floor(now / profile.windowSeconds) * profile.windowSeconds;
104 const key = `${profile.name}:${clientKey(req)}:${windowStart}`;
105 const count = (buckets.get(key) ?? 0) + 1;
106 buckets.set(key, count);
107
108 if (buckets.size > 10000) {
109 for (const storedKey of buckets.keys()) {
110 const storedWindow = Number(storedKey.split(':').at(-1));
111 if (storedWindow + 3600 < now) buckets.delete(storedKey);
112 }
113 }
114
115 const remaining = Math.max(0, profile.limit - count);
116 res.setHeader('RateLimit-Limit', String(profile.limit));
117 res.setHeader('RateLimit-Remaining', String(remaining));
118 if (count > profile.limit) {
119 const retryAfter = Math.max(1, windowStart + profile.windowSeconds - now);
120 res.setHeader('Retry-After', String(retryAfter));
121 return res.status(429).json({ error: 'rate_limited' });
122 }
123 next();
124 }
125
126 export function operationalErrorHandler(err, req, res, _next) {
127 const event = {
128 type: 'http_error',
129 requestId: req.requestId,
130 method: req.method,
131 path: req.route?.path ?? req.path,
132 errorClass: err?.name || 'Error',
133 };
134 if (process.env.NODE_ENV !== 'test') console.error(JSON.stringify(event));
135 if (res.headersSent) {
136 // Passing the original error to Express would print its raw message/stack.
137 res.destroy();
138 return;
139 }
140 if (err?.type === 'entity.parse.failed') {
141 return res.status(400).json({ error: 'invalid_json', requestId: req.requestId });
142 }
143 if (err?.type === 'entity.too.large') {
144 return res.status(413).json({ error: 'request_body_too_large', requestId: req.requestId });
145 }
146 if (err?.code === 'CORS_ORIGIN_DENIED') {
147 return res.status(403).json({ error: 'cors_origin_denied', requestId: req.requestId });
148 }
149 res.status(500).json({ error: 'internal_error', requestId: req.requestId });
150 }