LifeMate — Personal, Family & Learning Companion
design/mobile-accessibility-v2
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 | // Real app/HTTP/PostgreSQL integration; only invented identities on loopback. |
| 2 | import test, { after } from 'node:test'; |
| 3 | import assert from 'node:assert/strict'; |
| 4 | import crypto from 'node:crypto'; |
| 5 | import jwt from 'jsonwebtoken'; |
| 6 | import pg from 'pg'; |
| 7 | import { rateLimitProfile } from '../src/operations.js'; |
| 8 | |
| 9 | const location = new URL(process.env.TEST_FIXTURE_DATABASE_URL ?? process.env.DATABASE_URL); |
| 10 | assert.ok(['127.0.0.1', 'localhost', '[::1]'].includes(location.hostname), 'Loopback database only'); |
| 11 | assert.match(location.pathname, /^\/(?:lifeguide_roles_source_[a-f0-9]{16}|lifemate_ci|lifeguide_\w*test\w*)$/); |
| 12 | const marker = 'managed-child-http-' + crypto.randomUUID(); |
| 13 | const secret = 'synthetic-managed-child-http-fixture-not-a-live-signing-key'; |
| 14 | process.env.DATABASE_URL = location.href; |
| 15 | process.env.JWT_SECRET = secret; |
| 16 | process.env.PGAPPNAME = marker; |
| 17 | process.env.NODE_ENV = 'test'; |
| 18 | process.env.ENABLE_CHILD_IDENTITY_SANDBOX = 'true'; |
| 19 | process.env.ENABLE_SENSITIVE_FEATURES = 'false'; |
| 20 | process.env.SMS_PROVIDER = 'disabled'; |
| 21 | for (const name of ['SMS_PROVIDER_URL', 'SMS_PROVIDER_TOKEN', 'KAVENEGAR_API_KEY', 'EMAIL_FROM', 'RESEND_API_KEY', |
| 22 | 'SMTP_HOST', 'SMTP_USER', 'SMTP_PASSWORD', 'AI_API_KEY', 'AI_BASE_URL', 'AI_MODEL', 'OPENAI_API_KEY']) process.env[name] = ''; |
| 23 | const { app, pool } = await import('../src/server.js'); |
| 24 | const observer = new pg.Pool({ connectionString: location.href, application_name: marker + '-observer' }); |
| 25 | const server = app.listen(0, '127.0.0.1'); |
| 26 | await new Promise(resolve => server.once('listening', resolve)); |
| 27 | const base = 'http://127.0.0.1:' + server.address().port + '/v1'; |
| 28 | const users = [], families = []; |
| 29 | const hash = raw => crypto.createHash('sha256').update(raw).digest('hex'); |
| 30 | const claims = (id, sid, extra = {}) => jwt.sign({ ...extra, sub: id, sid, aud: 'lifemate-api' }, secret, { issuer: 'lifemate', expiresIn: '15m' }); |
| 31 | after(async () => { |
| 32 | await new Promise(resolve => server.close(resolve)); |
| 33 | try { |
| 34 | await pool.query('delete from access_audit where family_id=any($1::uuid[]) or actor_user_id=any($2::uuid[])', [families, users]); |
| 35 | await pool.query('delete from family_workspace where id=any($1::uuid[])', [families]); |
| 36 | await pool.query('delete from auth_session where user_id=any($1::uuid[])', [users]); |
| 37 | await pool.query('delete from app_user where id=any($1::uuid[])', [users]); |
| 38 | } finally { await pool.end(); await observer.end(); } |
| 39 | }); |
| 40 | async function request(who, method, path, body) { |
| 41 | const response = await fetch(base + path, { method, headers: { 'content-type': 'application/json', |
| 42 | ...(who ? { authorization: 'Bearer ' + who.accessToken } : {}) }, |
| 43 | body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(10000) }); |
| 44 | const text = await response.text(); |
| 45 | return { status: response.status, body: text ? JSON.parse(text) : null, cache: response.headers.get('cache-control') }; |
| 46 | } |
| 47 | async function adult() { |
| 48 | const id = crypto.randomUUID(), sid = crypto.randomUUID(); users.push(id); |
| 49 | await pool.query('insert into app_user(id,identity_subject,email_normalized,email_verified_at) values($1,$2,$3,clock_timestamp())', |
| 50 | [id, marker + ':' + id, 'synthetic-' + id + '@example.test']); |
| 51 | await pool.query("insert into profile(user_id,display_name,birth_date) values($1,'Synthetic Adult','1985-01-01')", [id]); |
| 52 | await pool.query("insert into auth_session(id,user_id,refresh_digest,expires_at) values($1,$2,$3,clock_timestamp()+interval '1 day')", [sid, id, crypto.randomUUID()]); |
| 53 | return { id, sid, accessToken: claims(id, sid) }; |
| 54 | } |
| 55 | async function fixture() { |
| 56 | const owner = await adult(), other = await adult(), familyId = crypto.randomUUID(); families.push(familyId); |
| 57 | await pool.query("insert into family_workspace(id,name,created_by) values($1,'Synthetic server fixture',$2)", [familyId, owner.id]); |
| 58 | for (const member of [owner, other]) await pool.query("insert into family_membership(family_id,user_id,role,is_admin) values($1,$2,'parent_guardian',true)", [familyId, member.id]); |
| 59 | const result = await request(owner, 'POST', `/families/${familyId}/children`, { |
| 60 | displayName: 'Synthetic Child', birthDate: '2015-03-12', profileCategory: 'girl_minor', |
| 61 | consentVersion: 'sandbox-child-consent-v1-not-legal', consentAccepted: true, synthetic: true }); |
| 62 | assert.equal(result.status, 201, 'Real app child creation'); |
| 63 | const childId = result.body.child.userId; users.push(childId); |
| 64 | const issued = await request(owner, 'POST', `/families/${familyId}/children/${childId}/device-invitations`, { synthetic: true }); |
| 65 | assert.equal(issued.status, 201); |
| 66 | const accepted = await request(null, 'POST', '/child-devices/accept', { token: issued.body.token }); |
| 67 | assert.equal(accepted.status, 200); |
| 68 | return { owner, other, familyId, childId, child: accepted.body }; |
| 69 | } |
| 70 | const refresh = child => request(null, 'POST', '/auth/refresh', { refreshToken: child.refreshToken }); |
| 71 | async function privateDenied(child, planId) { |
| 72 | for (const [method, path, body] of [ |
| 73 | ['GET', '/today'], ['GET', '/plan-items'], ['GET', '/plan-items/' + planId], ['GET', '/study/sessions'], |
| 74 | ['GET', '/me/learning-attempts'], ['GET', '/me/iran-profile'], ['GET', '/me/menstrual-cycles'], |
| 75 | ['POST', '/ai/sessions', {}], ['POST', '/plan-items', { title: 'Synthetic', kind: 'task' }], |
| 76 | ]) { |
| 77 | const result = await request(child, method, path, body); |
| 78 | assert.equal(result.status, 403, 'Managed device denied ' + method + ' ' + path); |
| 79 | assert.equal(result.body.error, 'child_session_scope_denied'); |
| 80 | assert.equal(result.cache, 'no-store'); |
| 81 | } |
| 82 | } |
| 83 | async function privatePlan(f) { |
| 84 | return (await pool.query(`insert into plan_item(owner_user_id,family_id,kind,title,notes,visibility) |
| 85 | values($1,$2,'task','Synthetic private task','SYNTHETIC-PRIVATE-MARKER','private') returning id`, [f.childId, f.familyId])).rows[0].id; |
| 86 | } |
| 87 | |
| 88 | test('real app child device reads only minimal profile/families; legacy privileges and private APIs remain denied', async () => { |
| 89 | const f = await fixture(), planId = await privatePlan(f); |
| 90 | const profile = await request(f.child, 'GET', '/profile'); assert.equal(profile.status, 200); assert.equal(profile.cache, 'no-store'); |
| 91 | assert.deepEqual(Object.keys(profile.body).sort(), ['accessScope', 'display_name', 'profile_category', 'theme_preference', 'user_id'].sort()); |
| 92 | assert.equal(profile.body.user_id, f.childId); |
| 93 | const familiesResult = await request(f.child, 'GET', '/families'); assert.equal(familiesResult.status, 200); assert.equal(familiesResult.cache, 'no-store'); |
| 94 | await privateDenied(f.child, planId); |
| 95 | for (const who of [f.owner, f.other]) for (const method of ['POST', 'DELETE']) |
| 96 | assert.equal((await request(who, method, `/families/${f.familyId}/guardians`, { guardianUserId: f.other.id, minorUserId: f.childId })).status, 403); |
| 97 | assert.equal((await request(f.owner, 'PATCH', `/families/${f.familyId}/members/${f.childId}/role`, { |
| 98 | mutationId: crypto.randomUUID(), expectedVersion: 1, role: 'adult_member' })).status, 403); |
| 99 | assert.equal((await request(f.owner, 'POST', `/families/${f.familyId}/admin-transfer`, { |
| 100 | mutationId: crypto.randomUUID(), targetUserId: f.childId, expectedVersion: 1, expectedActorVersion: 1 })).status, 403); |
| 101 | for (const path of ['/profile', '/me/iran-profile']) assert.equal((await request(f.child, 'PATCH', path, { birthDate: '1980-01-01', profileCategory: 'adult' })).status, 403); |
| 102 | const unchanged = (await pool.query('select birth_date::text,profile_category from profile where user_id=$1', [f.childId])).rows[0]; |
| 103 | assert.deepEqual(unchanged, { birth_date: '2015-03-12', profile_category: 'girl_minor' }); |
| 104 | const identity = jwt.decode(f.child.accessToken); |
| 105 | await privateDenied({ accessToken: claims(f.childId, identity.sid, { scope: 'standard', accessScope: 'standard', managedChild: false }) }, planId); |
| 106 | }); |
| 107 | |
| 108 | test('real refresh rotates once under concurrency, retains DB scope/issuer and rejects standard managed-child sessions', async () => { |
| 109 | const f = await fixture(), planId = await privatePlan(f); |
| 110 | const results = await Promise.all([refresh(f.child), refresh(f.child)]); |
| 111 | assert.deepEqual(results.map(r => r.status).sort(), [200, 401]); |
| 112 | for (const result of results) assert.equal(result.cache, 'no-store'); |
| 113 | const replacement = results.find(r => r.status === 200).body; |
| 114 | const sid = jwt.decode(replacement.accessToken).sid; |
| 115 | const row = (await pool.query('select access_scope,child_issuer_user_id from auth_session where id=$1', [sid])).rows[0]; |
| 116 | assert.deepEqual(row, { access_scope: 'child_education', child_issuer_user_id: f.owner.id }); |
| 117 | assert.equal((await refresh(f.child)).status, 401); await privateDenied(replacement, planId); |
| 118 | const injectedSid = crypto.randomUUID(), raw = crypto.randomBytes(32).toString('base64url'); |
| 119 | await pool.query("insert into auth_session(id,user_id,refresh_digest,expires_at,access_scope) values($1,$2,$3,clock_timestamp()+interval '1 day','standard')", [injectedSid, f.childId, hash(raw)]); |
| 120 | assert.equal((await request({ accessToken: claims(f.childId, injectedSid, { scope: 'standard' }) }, 'GET', '/profile')).status, 401); |
| 121 | assert.equal((await refresh({ refreshToken: raw })).status, 401); |
| 122 | }); |
| 123 | |
| 124 | test('forged guardian relationship without creator invitation acceptance cannot read summary or issue child devices', async () => { |
| 125 | const f = await fixture(); |
| 126 | await pool.query('insert into guardian_relationship(family_id,guardian_user_id,minor_user_id) values($1,$2,$3)', [f.familyId, f.other.id, f.childId]); |
| 127 | assert.equal((await pool.query('select is_active_guardian($1,$2,$3) active', [f.familyId, f.other.id, f.childId])).rows[0].active, false); |
| 128 | assert.equal((await request(f.other, 'GET', `/families/${f.familyId}/children/${f.childId}/support-summary`)).status, 403); |
| 129 | assert.equal((await request(f.other, 'POST', `/families/${f.familyId}/children/${f.childId}/device-invitations`, { synthetic: true })).status, 403); |
| 130 | const visibility = await request(f.child, 'GET', '/child-visibility'); assert.equal(visibility.status, 200); |
| 131 | assert.deepEqual(visibility.body.guardians.map(g => g.userId), [f.owner.id]); |
| 132 | }); |
| 133 | |
| 134 | test('issuer role/relation removal, tampered consent digest and archived family invalidate next access and refresh', async () => { |
| 135 | for (const change of ['role', 'relationship', 'consent_digest', 'archive']) { |
| 136 | const f = await fixture(); |
| 137 | if (change === 'role') await pool.query("update family_membership set role='adult_member' where family_id=$1 and user_id=$2", [f.familyId, f.owner.id]); |
| 138 | if (change === 'relationship') await pool.query('update guardian_relationship set active=false where family_id=$1 and guardian_user_id=$2', [f.familyId, f.owner.id]); |
| 139 | if (change === 'consent_digest') await pool.query('update child_consent set text_digest=$2 where child_user_id=$1', [f.childId, '0'.repeat(64)]); |
| 140 | if (change === 'archive') await pool.query('update family_workspace set archived_at=clock_timestamp() where id=$1', [f.familyId]); |
| 141 | assert.equal((await request(f.child, 'GET', '/profile')).status, 401, change + ' invalidates access'); |
| 142 | assert.equal((await refresh(f.child)).status, 401, change + ' invalidates refresh'); |
| 143 | assert.equal((await pool.query('select count(*)::int n from auth_session where user_id=$1', [f.childId])).rows[0].n, 1); |
| 144 | } |
| 145 | }); |
| 146 | |
| 147 | async function observedLock() { |
| 148 | for (let i = 0; i < 300; i++) { |
| 149 | if ((await observer.query("select 1 from pg_stat_activity where application_name=$1 and wait_event_type='Lock'", [marker])).rowCount) return; |
| 150 | await new Promise(resolve => setTimeout(resolve, 10)); |
| 151 | } |
| 152 | assert.fail('Expected actual refresh PostgreSQL lock wait'); |
| 153 | } |
| 154 | test('refresh waiting on family lock rechecks guardian/session revocation and cannot mint a replacement', async () => { |
| 155 | for (const change of ['relationship', 'session']) { |
| 156 | const f = await fixture(), blocker = await observer.connect(); |
| 157 | try { |
| 158 | await blocker.query('begin'); await blocker.query('select id from family_workspace where id=$1 for update', [f.familyId]); |
| 159 | const pending = refresh(f.child); await observedLock(); |
| 160 | if (change === 'relationship') await blocker.query('update guardian_relationship set active=false where family_id=$1 and guardian_user_id=$2', [f.familyId, f.owner.id]); |
| 161 | else await blocker.query('update auth_session set revoked_at=clock_timestamp() where id=$1', [jwt.decode(f.child.accessToken).sid]); |
| 162 | await blocker.query('commit'); assert.equal((await pending).status, 401); |
| 163 | assert.equal((await pool.query('select count(*)::int n from auth_session where user_id=$1', [f.childId])).rows[0].n, 1); |
| 164 | } finally { await blocker.query('rollback'); blocker.release(); } |
| 165 | } |
| 166 | }); |
| 167 | |
| 168 | test('creator revokes second guardian through real app; its child device and refresh immediately stop working', async () => { |
| 169 | const f = await fixture(); |
| 170 | const invitation = await request(f.owner, 'POST', `/families/${f.familyId}/children/${f.childId}/guardian-invitations`, { guardianUserId: f.other.id }); |
| 171 | assert.equal(invitation.status, 201); |
| 172 | assert.equal((await request(f.other, 'POST', '/guardian-invitations/accept', { token: invitation.body.token })).status, 200); |
| 173 | const code = await request(f.other, 'POST', `/families/${f.familyId}/children/${f.childId}/device-invitations`, { synthetic: true }); |
| 174 | const accepted = await request(null, 'POST', '/child-devices/accept', { token: code.body.token }); assert.equal(accepted.status, 200); |
| 175 | assert.equal((await request(f.owner, 'DELETE', `/families/${f.familyId}/children/${f.childId}/guardians/${f.other.id}`)).status, 200); |
| 176 | assert.equal((await request(accepted.body, 'GET', '/profile')).status, 401); assert.equal((await refresh(accepted.body)).status, 401); |
| 177 | }); |
| 178 | |
| 179 | test('device acceptance exact and Express case/slash variants retain strict authentication quota profile', () => { |
| 180 | for (const path of ['/v1/child-devices/accept', '/V1/CHILD-DEVICES/ACCEPT', '/v1/child-devices/accept/', '/V1/child-devices/Accept/']) { |
| 181 | for (const method of ['POST', 'GET', 'PUT']) assert.equal(rateLimitProfile({ path, method }, {}).name, 'auth'); |
| 182 | } |
| 183 | }); |