LifeMate — Personal, Family & Learning Companion
fix/personal-notification-controls
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
| 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 | export function rateLimitProfile(req, env = process.env) { |
| 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)) || /^\/v1\/child-devices\/accept\/?$/i.test(path)) { |
| 70 | if (req.method === 'POST' && (path === '/v1/auth/refresh' || path === '/v1/auth/logout')) { |
| 71 | return { |
| 72 | name: 'session', |
| 73 | limit: positiveInt(env.RATE_LIMIT_SESSION_MAX, 60), |
| 74 | windowSeconds: positiveInt(env.RATE_LIMIT_SESSION_WINDOW_SECONDS, 10 * 60), |
| 75 | }; |
| 76 | } |
| 77 | return { |
| 78 | name: 'auth', |
| 79 | limit: positiveInt(env.RATE_LIMIT_AUTH_MAX, 10), |
| 80 | windowSeconds: positiveInt(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(env.RATE_LIMIT_AI_MAX, 30), |
| 87 | windowSeconds: positiveInt(env.RATE_LIMIT_AI_WINDOW_SECONDS, 10 * 60), |
| 88 | }; |
| 89 | } |
| 90 | return { |
| 91 | name: 'general', |
| 92 | limit: positiveInt(env.RATE_LIMIT_GENERAL_MAX, 120), |
| 93 | windowSeconds: positiveInt(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 = rateLimitProfile(req); |
| 102 | if (req.authRateLimitCharged && ['auth', 'session'].includes(profile.name)) return next(); |
| 103 | const now = nowSeconds(); |
| 104 | const windowStart = Math.floor(now / profile.windowSeconds) * profile.windowSeconds; |
| 105 | const key = `${profile.name}:${clientKey(req)}:${windowStart}`; |
| 106 | const count = (buckets.get(key) ?? 0) + 1; |
| 107 | buckets.set(key, count); |
| 108 | |
| 109 | if (buckets.size > 10000) { |
| 110 | for (const storedKey of buckets.keys()) { |
| 111 | const storedWindow = Number(storedKey.split(':').at(-1)); |
| 112 | if (storedWindow + 3600 < now) buckets.delete(storedKey); |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | const remaining = Math.max(0, profile.limit - count); |
| 117 | res.setHeader('RateLimit-Limit', String(profile.limit)); |
| 118 | res.setHeader('RateLimit-Remaining', String(remaining)); |
| 119 | if (count > profile.limit) { |
| 120 | const retryAfter = Math.max(1, windowStart + profile.windowSeconds - now); |
| 121 | res.setHeader('Retry-After', String(retryAfter)); |
| 122 | return res.status(429).json({ error: 'rate_limited' }); |
| 123 | } |
| 124 | next(); |
| 125 | } |
| 126 | |
| 127 | export function operationalErrorHandler(err, req, res, _next) { |
| 128 | const event = { |
| 129 | type: 'http_error', |
| 130 | requestId: req.requestId, |
| 131 | method: req.method, |
| 132 | path: req.route?.path ?? req.path, |
| 133 | errorClass: err?.name || 'Error', |
| 134 | }; |
| 135 | if (process.env.NODE_ENV !== 'test') console.error(JSON.stringify(event)); |
| 136 | if (res.headersSent) { |
| 137 | // Passing the original error to Express would print its raw message/stack. |
| 138 | res.destroy(); |
| 139 | return; |
| 140 | } |
| 141 | if (err?.type === 'entity.parse.failed') { |
| 142 | return res.status(400).json({ error: 'invalid_json', requestId: req.requestId }); |
| 143 | } |
| 144 | if (err?.type === 'entity.too.large') { |
| 145 | return res.status(413).json({ error: 'request_body_too_large', requestId: req.requestId }); |
| 146 | } |
| 147 | if (err?.code === 'CORS_ORIGIN_DENIED') { |
| 148 | return res.status(403).json({ error: 'cors_origin_denied', requestId: req.requestId }); |
| 149 | } |
| 150 | res.status(500).json({ error: 'internal_error', requestId: req.requestId }); |
| 151 | } |