LifeMate — Personal, Family & Learning Companion

feat/standalone-weekly-planner
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 83 lines 4.55 KB
Raw
1 import crypto from 'node:crypto';
2 import { isIP } from 'node:net';
3 import { rateLimitProfile } from './operations.js';
4
5 const digestDomain = 'lifeguide:auth-ip:v1\0';
6
7 function canonicalIp(value) {
8 const address = String(value ?? '');
9 if (isIP(address) === 4) return address;
10 if (isIP(address) !== 6) throw new Error('Invalid client address');
11 const canonical = new URL(`http://[${address}]`).hostname.slice(1, -1);
12 // Socket addresses can represent the same IPv4 client as mapped IPv6.
13 const mapped = /^::ffff:([a-f0-9]{1,4}):([a-f0-9]{1,4})$/.exec(canonical);
14 if (!mapped) return canonical;
15 const upper = Number.parseInt(mapped[1], 16), lower = Number.parseInt(mapped[2], 16);
16 return `${upper >> 8}.${upper & 255}.${lower >> 8}.${lower & 255}`;
17 }
18
19 /** Shared fixed-window budgets for auth and session routes. Forwarded headers
20 * are deliberately never read here: Express req.ip reflects the separately
21 * validated, operator-pinned trusted-proxy configuration.
22 */
23 export function createAuthIpRateLimit({ pool, jwtSecret, env = process.env }) {
24 if (typeof jwtSecret !== 'string' || jwtSecret.length < 32) throw new Error('Invalid auth limiter signing secret');
25 return async function authIpRateLimit(req, res, next) {
26 if (env.NODE_ENV === 'test' || req.method === 'OPTIONS') return next();
27 const profile = rateLimitProfile(req, env);
28 if (!['auth', 'session'].includes(profile.name)) return next();
29 let client;
30 try {
31 const digest = crypto.createHmac('sha256', jwtSecret).update(digestDomain)
32 .update(canonicalIp(req.ip || req.socket?.remoteAddress)).digest('hex');
33 client = await pool.connect();
34 await client.query("begin; set local lock_timeout='2s'; set local statement_timeout='3s'");
35 // Lock the stable digest/profile, not a precomputed window. A waiting
36 // request samples the PostgreSQL clock only after acquiring this lock.
37 await client.query("select pg_advisory_xact_lock(hashtextextended('lifeguide:auth-ip:' || $1 || ':' || $2,0))", [profile.name, digest]);
38 const result = await client.query(`
39 with clock as (select statement_timestamp() as instant),
40 quota_window as (select to_timestamp(floor(extract(epoch from instant)/$3::integer)*$3::integer) as start from clock)
41 insert into auth_ip_rate_limit(quota_profile,client_digest,window_start,window_end,request_count)
42 select $1,$2,start,start+make_interval(secs=>$3::integer),1 from quota_window
43 on conflict(quota_profile,client_digest,window_start) do update
44 set request_count=auth_ip_rate_limit.request_count+1
45 returning request_count,
46 greatest(1,ceil(extract(epoch from window_end-statement_timestamp())))::integer as retry_after`,
47 [profile.name, digest, profile.windowSeconds]);
48 await client.query('commit');
49 const row = result.rows[0];
50 const count = Number(row.request_count);
51 // The in-memory middleware must not charge these routes a second time.
52 req.authRateLimitCharged = true;
53 res.setHeader('RateLimit-Limit', String(profile.limit));
54 res.setHeader('RateLimit-Remaining', String(Math.max(0, profile.limit - count)));
55 if (count > profile.limit) {
56 res.setHeader('Retry-After', String(row.retry_after));
57 return res.status(429).json({ error: 'rate_limited' });
58 }
59 return next();
60 } catch {
61 if (client) await client.query('rollback').catch(() => {});
62 // Database/key/address failures never fall back to a per-process quota.
63 // Do not expose or log connection strings, raw IPs, or PostgreSQL errors.
64 res.setHeader('Retry-After', '5');
65 return res.status(503).json({ error: 'temporarily_unavailable' });
66 } finally { client?.release(); }
67 };
68 }
69
70 /** Explicit local/operator housekeeping hook; no timer, worker or external
71 * scheduler is started. Each call deletes at most 500 expired metadata rows.
72 * Current windows are retained, so housekeeping cannot reopen an active quota.
73 */
74 export async function pruneExpiredAuthRateLimits(pool, batchSize = 500) {
75 if (!Number.isInteger(batchSize) || batchSize < 1 || batchSize > 500) throw new Error('Invalid auth limiter cleanup batch');
76 const result = await pool.query(`with expired as (
77 select quota_profile,client_digest,window_start from auth_ip_rate_limit
78 where window_end<=statement_timestamp() order by window_end
79 limit $1 for update skip locked
80 ) delete from auth_ip_rate_limit b using expired e
81 where b.quota_profile=e.quota_profile and b.client_digest=e.client_digest and b.window_start=e.window_start`, [batchSize]);
82 return result.rowCount;
83 }