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 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 | const fixtureIpDigest = crypto.createHmac('sha256', secret) |
| 22 | .update('lifeguide:auth-ip:v1\0').update('127.0.0.1').digest('hex'); |
| 23 | let child, base; |
| 24 | |
| 25 | before(async () => { |
| 26 | // This fixture deliberately uses a stable key to assert shipping defaults. |
| 27 | // Remove only its own prior-run quota, never another API/test's buckets. |
| 28 | await pool.query("delete from auth_ip_rate_limit where client_digest=$1 and quota_profile in ('auth','session')", [fixtureIpDigest]); |
| 29 | const hash = await argon2.hash(password, { type: argon2.argon2id }); |
| 30 | for (let index = 0; index < 3; index++) { |
| 31 | const id = crypto.randomUUID(), email = `nat-${id}@example.test`; |
| 32 | users.push({ id, email }); |
| 33 | 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]); |
| 34 | await pool.query("insert into profile(user_id,display_name) values($1,'Synthetic NAT User')", [id]); |
| 35 | await pool.query('insert into auth_credential(user_id,password_hash) values($1,$2)', [id, hash]); |
| 36 | } |
| 37 | // Use real wall time. Starting away from the fixed-window boundary avoids |
| 38 | // a natural reset halfway through this bounded sequence, without a fake clock. |
| 39 | const remaining = 60 - (Math.floor(Date.now() / 1000) % 60); |
| 40 | if (remaining < 15) await new Promise(resolve => setTimeout(resolve, (remaining + 1) * 1000)); |
| 41 | const reservation = net.createServer().listen(0, '127.0.0.1'); |
| 42 | await once(reservation, 'listening'); const port = reservation.address().port; |
| 43 | await new Promise(resolve => reservation.close(resolve)); |
| 44 | base = `http://127.0.0.1:${port}`; |
| 45 | const env = { ...process.env, NODE_ENV: 'production', PORT: String(port), JWT_SECRET: secret, |
| 46 | LOG_REQUESTS: 'false', TRUSTED_PROXY_CIDRS: '', CORS_ORIGINS: '', SMS_PROVIDER: 'disabled', |
| 47 | SMS_PROVIDER_URL: '', SMS_PROVIDER_TOKEN: '', EMAIL_FROM: '', RESEND_API_KEY: '', SMTP_HOST: '', |
| 48 | SMTP_USER: '', SMTP_PASSWORD: '', AI_API_KEY: '', AI_BASE_URL: '', AI_MODEL: '', OPENAI_API_KEY: '', |
| 49 | ENABLE_SENSITIVE_FEATURES: 'false' }; |
| 50 | // Prove the shipping defaults even when the parent runner configures quotas. |
| 51 | for (const key of Object.keys(env)) if (key.startsWith('RATE_LIMIT_')) delete env[key]; |
| 52 | delete env.TEST_FIXTURE_DATABASE_URL; |
| 53 | child = spawn(process.execPath, ['src/entrypoint.js'], { cwd: new URL('../', import.meta.url), env, |
| 54 | stdio: ['ignore', 'pipe', 'pipe'] }); |
| 55 | child.stderr.on('data', () => {}); |
| 56 | await new Promise((resolve, reject) => { |
| 57 | let output = ''; |
| 58 | const timer = setTimeout(() => reject(new Error('NAT fixture startup timed out')), 10000); |
| 59 | child.stdout.on('data', chunk => { |
| 60 | output += chunk; |
| 61 | if (output.includes('"type":"startup"')) { clearTimeout(timer); resolve(); } |
| 62 | }); |
| 63 | child.once('error', () => { clearTimeout(timer); reject(new Error('NAT fixture process failed')); }); |
| 64 | child.once('exit', () => { |
| 65 | if (!output.includes('"type":"startup"')) { clearTimeout(timer); reject(new Error('NAT fixture exited before startup')); } |
| 66 | }); |
| 67 | }); |
| 68 | }); |
| 69 | after(async () => { |
| 70 | if (child && child.exitCode === null && child.signalCode === null) { |
| 71 | const closed = once(child, 'close'); child.kill('SIGTERM'); await closed; |
| 72 | } |
| 73 | try { |
| 74 | await pool.query('delete from app_user where id=any($1::uuid[])', [users.map(user => user.id)]); |
| 75 | await pool.query("delete from auth_ip_rate_limit where client_digest=$1 and quota_profile in ('auth','session')", [fixtureIpDigest]); |
| 76 | } |
| 77 | finally { await pool.end(); } |
| 78 | }); |
| 79 | async function request(method, path, body, headers = {}) { |
| 80 | const response = await fetch(base + path, { method, |
| 81 | headers: { 'content-type': 'application/json', ...headers }, |
| 82 | ...(body === undefined ? {} : { body: JSON.stringify(body) }) }); |
| 83 | const raw = await response.text(); |
| 84 | return { status: response.status, headers: response.headers, |
| 85 | body: raw && response.headers.get('content-type')?.includes('application/json') ? JSON.parse(raw) : null }; |
| 86 | } |
| 87 | const profile = user => request('GET', '/v1/profile', undefined, { authorization: `Bearer ${user.tokens.accessToken}` }); |
| 88 | const digest = value => crypto.createHash('sha256').update(value).digest('hex'); |
| 89 | function limited(response, limit, label) { |
| 90 | assert.equal(response.status, 429, label); |
| 91 | assert.equal(response.headers.get('RateLimit-Limit'), String(limit), label); |
| 92 | assert.equal(response.headers.get('RateLimit-Remaining'), '0', label); |
| 93 | const retry = Number(response.headers.get('Retry-After')); |
| 94 | const windowSeconds = limit === 120 ? 60 : 600; |
| 95 | assert.ok(Number.isInteger(retry) && retry > 0 && retry <= windowSeconds, `${label}: bounded real Retry-After`); |
| 96 | const expectedRetry = windowSeconds - (Math.floor(Date.now() / 1000) % windowSeconds); |
| 97 | assert.ok(Math.abs(retry - expectedRetry) <= 1, `${label}: actual default window expiry`); |
| 98 | assert.equal(response.body?.error, 'rate_limited', label); |
| 99 | } |
| 100 | |
| 101 | test('three users on one IP retain default strict login guards while capability discovery and rotating sessions have separate bounded budgets', async () => { |
| 102 | const discoveryLimits = []; |
| 103 | for (let index = 0; index < 12; index++) { |
| 104 | const result = await request('GET', '/v1/auth/capabilities'); |
| 105 | assert.equal(result.status, 200, `Capability request ${index + 1} must not exhaust login`); |
| 106 | discoveryLimits.push(result.headers.get('RateLimit-Limit')); |
| 107 | } |
| 108 | assert.ok(discoveryLimits.every(limit => limit === '120'), 'Discovery uses the bounded general quota'); |
| 109 | for (let index = 0; index < users.length; index++) { |
| 110 | const user = users[index], login = await request('POST', '/v1/auth/login', { email: user.email, password }); |
| 111 | assert.equal(login.status, 200, `Independent user ${index + 1} can log in behind the same IP`); |
| 112 | assert.equal(login.headers.get('RateLimit-Limit'), '10'); |
| 113 | user.tokens = login.body; user.initialTokens = login.body; |
| 114 | const identity = jwt.verify(user.tokens.accessToken, secret, { audience: 'lifemate-api', issuer: 'lifemate' }); |
| 115 | assert.equal(identity.sub, user.id); |
| 116 | } |
| 117 | for (let index = 0; index < 7; index++) { |
| 118 | const result = await request('POST', '/v1/auth/login', { email: users[index % 3].email, password: 'SyntheticInvalidPassword!' }); |
| 119 | assert.equal(result.status, 401); assert.equal(result.headers.get('RateLimit-Limit'), '10'); |
| 120 | } |
| 121 | limited(await request('POST', '/v1/auth/login', { email: users[0].email, password }), 10, 'Strict auth request 11'); |
| 122 | const nearMatches = [ |
| 123 | ['HEAD', '/v1/auth/capabilities'], ['POST', '/v1/auth/capabilities'], |
| 124 | ['GET', '/v1/auth/capabilities/'], ['GET', '/v1/auth/Capabilities'], |
| 125 | ['GET', '/V1/AUTH/capabilities'], ['GET', '/v1/auth/refresh'], |
| 126 | ['POST', '/v1/auth/refresh/'], ['POST', '/v1/auth/refreshing'], |
| 127 | ['POST', '/v1/auth/logout/extra'], ['GET', '/v1/auth'], |
| 128 | ]; |
| 129 | for (const [method, path] of nearMatches) { |
| 130 | const result = await request(method, path); |
| 131 | // HEAD deliberately has no response body. |
| 132 | assert.equal(result.status, 429, `${method} ${path} remains strict`); |
| 133 | assert.equal(result.headers.get('RateLimit-Limit'), '10'); |
| 134 | assert.ok(Number(result.headers.get('Retry-After')) > 0); |
| 135 | } |
| 136 | for (let index = 0; index < 3; index++) limited(await request('POST', '/v1/auth/login', {}, { |
| 137 | 'x-forwarded-for': `198.51.100.${index + 1}`, 'x-real-ip': `192.0.2.${index + 1}`, |
| 138 | forwarded: `for=203.0.113.${index + 1}`, |
| 139 | }), 10, 'Forged forwarding cannot acquire a new strict bucket'); |
| 140 | |
| 141 | let sessionRequests = 0; |
| 142 | async function session(path, body, headers) { |
| 143 | const result = await request('POST', path, body, headers); sessionRequests++; |
| 144 | assert.equal(result.headers.get('RateLimit-Limit'), '60'); |
| 145 | assert.equal(result.headers.get('RateLimit-Remaining'), String(Math.max(0, 60 - sessionRequests))); |
| 146 | return result; |
| 147 | } |
| 148 | for (let index = 0; index < 12; index++) { |
| 149 | const user = users[index % 3], previous = user.tokens, result = await session('/v1/auth/refresh', { refreshToken: previous.refreshToken }); |
| 150 | assert.equal(result.status, 200, `Refresh ${index + 1} succeeds after strict login bucket is exhausted`); |
| 151 | assert.ok(result.body.refreshToken !== previous.refreshToken, 'Refresh proof must rotate'); |
| 152 | const oldIdentity = jwt.verify(previous.accessToken, secret, { audience: 'lifemate-api', issuer: 'lifemate' }); |
| 153 | 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); |
| 154 | user.tokens = result.body; |
| 155 | } |
| 156 | for (const user of users) { |
| 157 | assert.equal((await profile(user)).status, 200); |
| 158 | assert.equal((await request('GET', '/v1/profile', undefined, { authorization: `Bearer ${user.initialTokens.accessToken}` })).status, 401); |
| 159 | const identity = jwt.verify(user.tokens.accessToken, secret, { audience: 'lifemate-api', issuer: 'lifemate' }); |
| 160 | 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]; |
| 161 | assert.ok(active && active.refresh_digest === digest(user.tokens.refreshToken), 'Independent PostgreSQL confirms only hashed current refresh proof'); |
| 162 | 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); |
| 163 | } |
| 164 | assert.equal((await session('/v1/auth/refresh', { refreshToken: users[0].initialTokens.refreshToken })).status, 401); |
| 165 | assert.equal((await session('/v1/auth/logout', { refreshToken: users[0].tokens.refreshToken })).status, 204); |
| 166 | assert.equal((await profile(users[0])).status, 401); |
| 167 | for (const user of users.slice(1)) assert.equal((await profile(user)).status, 200, 'Another family account remains independently active'); |
| 168 | assert.equal((await session('/v1/auth/logout', {}, { authorization: `Bearer ${users[1].tokens.accessToken}` })).status, 204); |
| 169 | assert.equal((await profile(users[1])).status, 401); |
| 170 | const expiring = jwt.verify(users[2].tokens.accessToken, secret, { audience: 'lifemate-api', issuer: 'lifemate' }); |
| 171 | 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]); |
| 172 | assert.equal((await profile(users[2])).status, 401); |
| 173 | assert.equal((await session('/v1/auth/refresh', { refreshToken: users[2].tokens.refreshToken })).status, 401); |
| 174 | assert.equal((await session('/v1/auth/logout', { refreshToken: users[2].tokens.refreshToken })).status, 204); |
| 175 | while (sessionRequests < 60) assert.equal((await session('/v1/auth/logout', {})).status, 204); |
| 176 | limited(await session('/v1/auth/refresh', { refreshToken: users[0].tokens.refreshToken }), 60, 'Session request 61'); |
| 177 | limited(await session('/v1/auth/logout', {}), 60, 'Logout shares the exhausted session bucket'); |
| 178 | |
| 179 | let discovery = await request('GET', '/v1/auth/capabilities'); |
| 180 | assert.equal(discovery.status, 200, 'Strict and session exhaustion do not block discovery'); |
| 181 | const remaining = Number(discovery.headers.get('RateLimit-Remaining')); |
| 182 | assert.ok(Number.isInteger(remaining) && remaining >= 0 && remaining < 120); |
| 183 | for (let index = 0; index < remaining; index++) { |
| 184 | discovery = await request('GET', '/v1/auth/capabilities'); assert.equal(discovery.status, 200); |
| 185 | } |
| 186 | assert.equal(discovery.headers.get('RateLimit-Remaining'), '0'); |
| 187 | limited(await request('GET', '/v1/auth/capabilities'), 120, 'Capabilities retain the bounded general budget'); |
| 188 | }); |