@davoodmehraban89 / LifeMate / commits / 0831ee6
Fork 0

LifeMate — Personal, Family & Learning Companion

fix: separate shared-network session and sensitive auth quotas

Quinn White committed Oct 12, 2026 at 03:45 UTC 0831ee6ba81a4811f819e8d8dbfe3f7b24a566ef
7 files changed +226 -4
.env.example
+3
@@ -25,6 +25,9 @@ API_IMAGE=lifeguide-api:local
25 WEB_IMAGE=lifeguide-web:local
26 NODE_ENV=production
27 LOG_REQUESTS=false
28 +# Session refresh/logout are separately bounded; sensitive auth keeps its own limit.
29 +RATE_LIMIT_SESSION_MAX=60
30 +RATE_LIMIT_SESSION_WINDOW_SECONDS=600
31 # Delivery is unavailable until an operator configures an approved provider.
32 EMAIL_FROM=
33 SMTP_HOST=
backend/package-lock.json
+2 -2
@@ -1,12 +1,12 @@
1 {
2 "name": "lifemate-backend",
3 - "version": "0.7.0",
3 + "version": "0.7.1",
4 "lockfileVersion": 3,
5 "requires": true,
6 "packages": {
7 "": {
8 "name": "lifemate-backend",
9 - "version": "0.7.0",
9 + "version": "0.7.1",
10 "dependencies": {
11 "argon2": "^0.44.0",
12 "cors": "^2.8.5",
backend/package.json
+1 -1
@@ -1,7 +1,7 @@
1 {
2 "name": "lifemate-backend",
3 "private": true,
4 - "version": "0.7.0",
4 + "version": "0.7.1",
5 "type": "module",
6 "scripts": {
7 "start": "node src/entrypoint.js",
backend/src/operations.js
+11 -1
@@ -63,7 +63,17 @@ export function configureTrustedProxy(app, value = process.env.TRUSTED_PROXY_CID
63
64 function profileFor(req) {
65 const path = req.path;
66 - if (path.startsWith('/v1/auth/')) {
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),
backend/tests/auth_nat_rate_limit.test.js new
+180
@@ -0,0 +1,180 @@
1 +import test, { after, before } from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import crypto from 'node:crypto';
4 +import { spawn } from 'node:child_process';
5 +import { once } from 'node:events';
6 +import net from 'node:net';
7 +import pg from 'pg';
8 +import argon2 from 'argon2';
9 +import jwt from 'jsonwebtoken';
10 +
11 +const fixtureUrl = process.env.TEST_FIXTURE_DATABASE_URL ?? process.env.DATABASE_URL;
12 +assert.ok(fixtureUrl, 'NAT acceptance requires migrated synthetic PostgreSQL');
13 +const database = new URL(fixtureUrl);
14 +assert.ok(['localhost', '127.0.0.1', '[::1]', '::1'].includes(database.hostname), 'Only loopback PostgreSQL allowed');
15 +assert.ok(['/lifeguide_library_test', '/lifeguide_contentops_test', '/lifemate_ci'].includes(database.pathname) ||
16 + /^\/lifeguide_roles_source_[a-f0-9]{16}$/.test(database.pathname), 'Only synthetic test databases allowed');
17 +const pool = new pg.Pool({ connectionString: fixtureUrl });
18 +const users = [];
19 +const password = `SyntheticNat-${crypto.randomUUID()}!`;
20 +const secret = 'synthetic-nat-rate-limit-signing-secret-32-characters';
21 +let child, base;
22 +
23 +before(async () => {
24 + const hash = await argon2.hash(password, { type: argon2.argon2id });
25 + for (let index = 0; index < 3; index++) {
26 + const id = crypto.randomUUID(), email = `nat-${id}@example.test`;
27 + users.push({ id, email });
28 + await pool.query('insert into app_user(id,identity_subject,email_normalized,email_verified_at) values($1,$2,$3,now())', [id, `nat-fixture:${id}`, email]);
29 + await pool.query("insert into profile(user_id,display_name) values($1,'Synthetic NAT User')", [id]);
30 + await pool.query('insert into auth_credential(user_id,password_hash) values($1,$2)', [id, hash]);
31 + }
32 + // Use real wall time. Starting away from the fixed-window boundary avoids
33 + // a natural reset halfway through this bounded sequence, without a fake clock.
34 + const remaining = 60 - (Math.floor(Date.now() / 1000) % 60);
35 + if (remaining < 15) await new Promise(resolve => setTimeout(resolve, (remaining + 1) * 1000));
36 + const reservation = net.createServer().listen(0, '127.0.0.1');
37 + await once(reservation, 'listening'); const port = reservation.address().port;
38 + await new Promise(resolve => reservation.close(resolve));
39 + base = `http://127.0.0.1:${port}`;
40 + const env = { ...process.env, NODE_ENV: 'production', PORT: String(port), JWT_SECRET: secret,
41 + LOG_REQUESTS: 'false', TRUSTED_PROXY_CIDRS: '', CORS_ORIGINS: '', SMS_PROVIDER: 'disabled',
42 + SMS_PROVIDER_URL: '', SMS_PROVIDER_TOKEN: '', EMAIL_FROM: '', RESEND_API_KEY: '', SMTP_HOST: '',
43 + SMTP_USER: '', SMTP_PASSWORD: '', AI_API_KEY: '', AI_BASE_URL: '', AI_MODEL: '', OPENAI_API_KEY: '',
44 + ENABLE_SENSITIVE_FEATURES: 'false' };
45 + // Prove the shipping defaults even when the parent runner configures quotas.
46 + for (const key of Object.keys(env)) if (key.startsWith('RATE_LIMIT_')) delete env[key];
47 + delete env.TEST_FIXTURE_DATABASE_URL;
48 + child = spawn(process.execPath, ['src/entrypoint.js'], { cwd: new URL('../', import.meta.url), env,
49 + stdio: ['ignore', 'pipe', 'pipe'] });
50 + child.stderr.on('data', () => {});
51 + await new Promise((resolve, reject) => {
52 + let output = '';
53 + const timer = setTimeout(() => reject(new Error('NAT fixture startup timed out')), 10000);
54 + child.stdout.on('data', chunk => {
55 + output += chunk;
56 + if (output.includes('"type":"startup"')) { clearTimeout(timer); resolve(); }
57 + });
58 + child.once('error', () => { clearTimeout(timer); reject(new Error('NAT fixture process failed')); });
59 + child.once('exit', () => {
60 + if (!output.includes('"type":"startup"')) { clearTimeout(timer); reject(new Error('NAT fixture exited before startup')); }
61 + });
62 + });
63 +});
64 +after(async () => {
65 + if (child && child.exitCode === null && child.signalCode === null) {
66 + const closed = once(child, 'close'); child.kill('SIGTERM'); await closed;
67 + }
68 + try { await pool.query('delete from app_user where id=any($1::uuid[])', [users.map(user => user.id)]); }
69 + finally { await pool.end(); }
70 +});
71 +async function request(method, path, body, headers = {}) {
72 + const response = await fetch(base + path, { method,
73 + headers: { 'content-type': 'application/json', ...headers },
74 + ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
75 + const raw = await response.text();
76 + return { status: response.status, headers: response.headers,
77 + body: raw && response.headers.get('content-type')?.includes('application/json') ? JSON.parse(raw) : null };
78 +}
79 +const profile = user => request('GET', '/v1/profile', undefined, { authorization: `Bearer ${user.tokens.accessToken}` });
80 +const digest = value => crypto.createHash('sha256').update(value).digest('hex');
81 +function limited(response, limit, label) {
82 + assert.equal(response.status, 429, label);
83 + assert.equal(response.headers.get('RateLimit-Limit'), String(limit), label);
84 + assert.equal(response.headers.get('RateLimit-Remaining'), '0', label);
85 + const retry = Number(response.headers.get('Retry-After'));
86 + const windowSeconds = limit === 120 ? 60 : 600;
87 + assert.ok(Number.isInteger(retry) && retry > 0 && retry <= windowSeconds, `${label}: bounded real Retry-After`);
88 + const expectedRetry = windowSeconds - (Math.floor(Date.now() / 1000) % windowSeconds);
89 + assert.ok(Math.abs(retry - expectedRetry) <= 1, `${label}: actual default window expiry`);
90 + assert.equal(response.body?.error, 'rate_limited', label);
91 +}
92 +
93 +test('three users on one IP retain default strict login guards while capability discovery and rotating sessions have separate bounded budgets', async () => {
94 + const discoveryLimits = [];
95 + for (let index = 0; index < 12; index++) {
96 + const result = await request('GET', '/v1/auth/capabilities');
97 + assert.equal(result.status, 200, `Capability request ${index + 1} must not exhaust login`);
98 + discoveryLimits.push(result.headers.get('RateLimit-Limit'));
99 + }
100 + assert.ok(discoveryLimits.every(limit => limit === '120'), 'Discovery uses the bounded general quota');
101 + for (let index = 0; index < users.length; index++) {
102 + const user = users[index], login = await request('POST', '/v1/auth/login', { email: user.email, password });
103 + assert.equal(login.status, 200, `Independent user ${index + 1} can log in behind the same IP`);
104 + assert.equal(login.headers.get('RateLimit-Limit'), '10');
105 + user.tokens = login.body; user.initialTokens = login.body;
106 + const identity = jwt.verify(user.tokens.accessToken, secret, { audience: 'lifemate-api', issuer: 'lifemate' });
107 + assert.equal(identity.sub, user.id);
108 + }
109 + for (let index = 0; index < 7; index++) {
110 + const result = await request('POST', '/v1/auth/login', { email: users[index % 3].email, password: 'SyntheticInvalidPassword!' });
111 + assert.equal(result.status, 401); assert.equal(result.headers.get('RateLimit-Limit'), '10');
112 + }
113 + limited(await request('POST', '/v1/auth/login', { email: users[0].email, password }), 10, 'Strict auth request 11');
114 + const nearMatches = [
115 + ['HEAD', '/v1/auth/capabilities'], ['POST', '/v1/auth/capabilities'],
116 + ['GET', '/v1/auth/capabilities/'], ['GET', '/v1/auth/Capabilities'],
117 + ['GET', '/V1/AUTH/capabilities'], ['GET', '/v1/auth/refresh'],
118 + ['POST', '/v1/auth/refresh/'], ['POST', '/v1/auth/refreshing'],
119 + ['POST', '/v1/auth/logout/extra'], ['GET', '/v1/auth'],
120 + ];
121 + for (const [method, path] of nearMatches) {
122 + const result = await request(method, path);
123 + // HEAD deliberately has no response body.
124 + assert.equal(result.status, 429, `${method} ${path} remains strict`);
125 + assert.equal(result.headers.get('RateLimit-Limit'), '10');
126 + assert.ok(Number(result.headers.get('Retry-After')) > 0);
127 + }
128 + for (let index = 0; index < 3; index++) limited(await request('POST', '/v1/auth/login', {}, {
129 + 'x-forwarded-for': `198.51.100.${index + 1}`, 'x-real-ip': `192.0.2.${index + 1}`,
130 + forwarded: `for=203.0.113.${index + 1}`,
131 + }), 10, 'Forged forwarding cannot acquire a new strict bucket');
132 +
133 + let sessionRequests = 0;
134 + async function session(path, body, headers) {
135 + const result = await request('POST', path, body, headers); sessionRequests++;
136 + assert.equal(result.headers.get('RateLimit-Limit'), '60');
137 + assert.equal(result.headers.get('RateLimit-Remaining'), String(Math.max(0, 60 - sessionRequests)));
138 + return result;
139 + }
140 + for (let index = 0; index < 12; index++) {
141 + const user = users[index % 3], previous = user.tokens, result = await session('/v1/auth/refresh', { refreshToken: previous.refreshToken });
142 + assert.equal(result.status, 200, `Refresh ${index + 1} succeeds after strict login bucket is exhausted`);
143 + assert.ok(result.body.refreshToken !== previous.refreshToken, 'Refresh proof must rotate');
144 + const oldIdentity = jwt.verify(previous.accessToken, secret, { audience: 'lifemate-api', issuer: 'lifemate' });
145 + assert.ok((await pool.query('select revoked_at from auth_session where id=$1 and user_id=$2', [oldIdentity.sid, user.id])).rows[0].revoked_at);
146 + user.tokens = result.body;
147 + }
148 + for (const user of users) {
149 + assert.equal((await profile(user)).status, 200);
150 + assert.equal((await request('GET', '/v1/profile', undefined, { authorization: `Bearer ${user.initialTokens.accessToken}` })).status, 401);
151 + const identity = jwt.verify(user.tokens.accessToken, secret, { audience: 'lifemate-api', issuer: 'lifemate' });
152 + const active = (await pool.query('select refresh_digest from auth_session where id=$1 and user_id=$2 and revoked_at is null and expires_at>now()', [identity.sid, user.id])).rows[0];
153 + assert.ok(active && active.refresh_digest === digest(user.tokens.refreshToken), 'Independent PostgreSQL confirms only hashed current refresh proof');
154 + assert.equal((await pool.query('select count(*)::int n from auth_session where user_id=$1 and revoked_at is null', [user.id])).rows[0].n, 1);
155 + }
156 + assert.equal((await session('/v1/auth/refresh', { refreshToken: users[0].initialTokens.refreshToken })).status, 401);
157 + assert.equal((await session('/v1/auth/logout', { refreshToken: users[0].tokens.refreshToken })).status, 204);
158 + assert.equal((await profile(users[0])).status, 401);
159 + for (const user of users.slice(1)) assert.equal((await profile(user)).status, 200, 'Another family account remains independently active');
160 + assert.equal((await session('/v1/auth/logout', {}, { authorization: `Bearer ${users[1].tokens.accessToken}` })).status, 204);
161 + assert.equal((await profile(users[1])).status, 401);
162 + const expiring = jwt.verify(users[2].tokens.accessToken, secret, { audience: 'lifemate-api', issuer: 'lifemate' });
163 + await pool.query("update auth_session set expires_at=statement_timestamp()-interval '1 second' where id=$1 and user_id=$2", [expiring.sid, users[2].id]);
164 + assert.equal((await profile(users[2])).status, 401);
165 + assert.equal((await session('/v1/auth/refresh', { refreshToken: users[2].tokens.refreshToken })).status, 401);
166 + assert.equal((await session('/v1/auth/logout', { refreshToken: users[2].tokens.refreshToken })).status, 204);
167 + while (sessionRequests < 60) assert.equal((await session('/v1/auth/logout', {})).status, 204);
168 + limited(await session('/v1/auth/refresh', { refreshToken: users[0].tokens.refreshToken }), 60, 'Session request 61');
169 + limited(await session('/v1/auth/logout', {}), 60, 'Logout shares the exhausted session bucket');
170 +
171 + let discovery = await request('GET', '/v1/auth/capabilities');
172 + assert.equal(discovery.status, 200, 'Strict and session exhaustion do not block discovery');
173 + const remaining = Number(discovery.headers.get('RateLimit-Remaining'));
174 + assert.ok(Number.isInteger(remaining) && remaining >= 0 && remaining < 120);
175 + for (let index = 0; index < remaining; index++) {
176 + discovery = await request('GET', '/v1/auth/capabilities'); assert.equal(discovery.status, 200);
177 + }
178 + assert.equal(discovery.headers.get('RateLimit-Remaining'), '0');
179 + limited(await request('GET', '/v1/auth/capabilities'), 120, 'Capabilities retain the bounded general budget');
180 +});
docker-compose.yml
+2
@@ -12,6 +12,8 @@ x-api-environment: &api-environment
12 PUBLIC_APP_URL: ${PUBLIC_APP_URL:?Set the operator-approved HTTPS origin}
13 CORS_ORIGINS: ${CORS_ORIGINS:?Set the operator-approved HTTPS origin}
14 LOG_REQUESTS: ${LOG_REQUESTS:-false}
15 + RATE_LIMIT_SESSION_MAX: ${RATE_LIMIT_SESSION_MAX:-60}
16 + RATE_LIMIT_SESSION_WINDOW_SECONDS: ${RATE_LIMIT_SESSION_WINDOW_SECONDS:-600}
17 EMAIL_FROM: ${EMAIL_FROM:-}
18 SMTP_HOST: ${SMTP_HOST:-}
19 SMTP_PORT: ${SMTP_PORT:-587}
docs/superpowers/specs/2026-10-12-auth-nat-rate-limits.md new
+27
@@ -0,0 +1,27 @@
1 +# LifeGuide — authentication limits behind a shared family connection
2 +
3 +The production middleware currently sends every `/v1/auth/` request into the
4 +same IP bucket (10 requests per 600 seconds). Capability discovery, session
5 +refresh and logout therefore consume the budget for login and recovery. Three
6 +independent clients sharing a home/public IP can receive 429 while reopening.
7 +
8 +Only literal `GET /v1/auth/capabilities` uses the existing bounded general
9 +budget (120/60). Only literal `POST /v1/auth/refresh` and
10 +`POST /v1/auth/logout` share a separate IP session budget (60/600), configured
11 +through `RATE_LIMIT_SESSION_MAX` and `RATE_LIMIT_SESSION_WINDOW_SECONDS`.
12 +Other authentication methods/paths retain the strict 10/600 budget, including
13 +case variants and trailing/nested paths that Express may otherwise match.
14 +Authentication/token validation, hashed refresh storage and rotation remain
15 +unchanged. Public health and OPTIONS behavior and the pinned-proxy allowlist
16 +remain unchanged. This does not implement a distributed limiter or per-account
17 +quotas; multiple processes still have their existing independent IP buckets.
18 +
19 +Acceptance uses one uninterrupted real production entrypoint, default limits,
20 +synthetic PostgreSQL and three independent users on the same loopback IP. Twelve
21 +capability GETs precede real login; at least twelve successful refreshes rotate
22 +tokens and invalidate old proofs independently checked in PostgreSQL. Ten strict
23 +requests are accepted by the limiter, and the eleventh is 429 with Retry-After.
24 +Wrong methods/near paths and forged forwarding headers cannot escape that
25 +bucket. Session request 61 is 429; both session paths share the limit. Capabilities
26 +remain bounded by the real general bucket. No bucket reset, fake clock, live
27 +server restart, global quota increase or disabled middleware is used.