LifeMate — Personal, Family & Learning Companion
feat/learning-content-operations
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, { before, after } from 'node:test'; |
| 2 | import assert from 'node:assert/strict'; |
| 3 | import crypto from 'node:crypto'; |
| 4 | import net from 'node:net'; |
| 5 | import { spawn } from 'node:child_process'; |
| 6 | import { once } from 'node:events'; |
| 7 | import pg from 'pg'; |
| 8 | import jwt from 'jsonwebtoken'; |
| 9 | |
| 10 | // Real HTTP/SQL against a local synthetic test DB; no teaching approval. |
| 11 | const fixtureUrl = process.env.TEST_FIXTURE_DATABASE_URL ?? process.env.DATABASE_URL; |
| 12 | assert.ok(fixtureUrl, 'Locator tests require a migrated synthetic PostgreSQL fixture'); |
| 13 | const location = new URL(fixtureUrl); |
| 14 | assert.ok(['127.0.0.1', 'localhost', '[::1]', '::1'].includes(location.hostname)); |
| 15 | assert.ok(location.pathname.includes('test') || location.pathname === '/lifemate_ci' || |
| 16 | /^\/lifeguide_roles_source_[a-f0-9]{16}$/.test(location.pathname), 'Synthetic test database required'); |
| 17 | const pool = new pg.Pool({ connectionString: fixtureUrl }); |
| 18 | const secret = 'synthetic-unit-locator-secret-at-least-32-characters'; |
| 19 | const ids = { subject: crypto.randomUUID(), course: crypto.randomUUID(), unit: crypto.randomUUID() }; |
| 20 | const actors = []; |
| 21 | let child, base; |
| 22 | |
| 23 | before(async () => { |
| 24 | const reservation = net.createServer(); |
| 25 | reservation.listen(0, '127.0.0.1'); await once(reservation, 'listening'); |
| 26 | const port = reservation.address().port; |
| 27 | await new Promise(resolve => reservation.close(resolve)); |
| 28 | const env = { ...process.env, PORT: String(port), JWT_SECRET: secret, NODE_ENV: 'production', |
| 29 | SMS_PROVIDER: 'disabled', EMAIL_PROVIDER: 'disabled', ENABLE_SENSITIVE_FEATURES: 'false' }; |
| 30 | delete env.TEST_FIXTURE_DATABASE_URL; |
| 31 | for (const key of ['SMS_PROVIDER_URL', 'SMS_PROVIDER_TOKEN', 'EMAIL_FROM', 'RESEND_API_KEY', |
| 32 | 'SMTP_HOST', 'SMTP_USER', 'SMTP_PASSWORD', 'AI_API_KEY', 'AI_BASE_URL', 'AI_MODEL', 'OPENAI_API_KEY']) env[key] = ''; |
| 33 | child = spawn(process.execPath, ['src/entrypoint.js'], { |
| 34 | cwd: new URL('../', import.meta.url), env, stdio: ['ignore', 'pipe', 'pipe'], |
| 35 | }); |
| 36 | let ready = false; |
| 37 | child.stdout.on('data', chunk => { if (chunk.toString().includes('"type":"startup"')) ready = true; }); |
| 38 | child.stderr.on('data', () => {}); |
| 39 | for (let retry = 0; retry < 200 && !ready; retry++) await new Promise(resolve => setTimeout(resolve, 25)); |
| 40 | assert.ok(ready, 'Synthetic API must start'); base = `http://127.0.0.1:${port}`; |
| 41 | await pool.query(`insert into curriculum_subject(id,school_year,national_grade,code,name_fa) |
| 42 | values($1,'1405-1406',5,$2,'Synthetic locator subject')`, [ids.subject, `locator-${ids.subject}`]); |
| 43 | await pool.query(`insert into textbook_catalog(id,curriculum_subject_id,title_fa,source_url,stable_book_key) |
| 44 | values($1,$2,'Synthetic locator course','https://chap.sch.ir/',$3)`, [ids.course, ids.subject, `locator:${ids.course}`]); |
| 45 | await pool.query(`insert into learning_unit(id,textbook_id,unit_key,title_fa,order_index,index_kind,source_evidence_url) |
| 46 | values($1,$2,'locator-unit','درس صرفاً آزمایشی',1,'lesson','https://chap.sch.ir/')`, [ids.unit, ids.course]); |
| 47 | for (let index = 0; index < 2; index++) { |
| 48 | const id = crypto.randomUUID(), sid = crypto.randomUUID(); actors.push({ id, sid }); |
| 49 | await pool.query(`insert into app_user(id,identity_subject,email_normalized,email_verified_at) |
| 50 | values($1,$2,$3,now())`, [id, `locator:${id}`, `${id}@example.test`]); |
| 51 | await pool.query(`insert into profile(user_id,display_name,theme_preference) |
| 52 | values($1,'Synthetic locator learner','adult_blue')`, [id]); |
| 53 | await pool.query(`insert into auth_session(id,user_id,refresh_digest,expires_at) |
| 54 | values($1,$2,$3,now()+interval '1 day')`, [sid, id, crypto.randomUUID()]); |
| 55 | actors[index].token = jwt.sign({ sub: id, sid, aud: 'lifemate-api' }, secret, |
| 56 | { issuer: 'lifemate', expiresIn: '15m' }); |
| 57 | } |
| 58 | await pool.query(`insert into learning_progress(owner_user_id,unit_id,status,source,version) |
| 59 | values($1,$2,'in_progress','self_reported',1)`, [actors[0].id, ids.unit]); |
| 60 | }); |
| 61 | |
| 62 | after(async () => { |
| 63 | if (child && child.exitCode === null) { const closed = once(child, 'close'); child.kill('SIGTERM'); await closed; } |
| 64 | try { |
| 65 | await pool.query('delete from app_user where id=any($1::uuid[])', [actors.map(actor => actor.id)]); |
| 66 | await pool.query('delete from learning_unit where id=$1', [ids.unit]); |
| 67 | await pool.query('delete from textbook_catalog where id=$1', [ids.course]); |
| 68 | await pool.query('delete from curriculum_subject where id=$1', [ids.subject]); |
| 69 | } finally { await pool.end(); } |
| 70 | }); |
| 71 | |
| 72 | async function get(unit, actor, query = '') { |
| 73 | const response = await fetch(`${base}/v1/education/units/${unit}${query}`, { |
| 74 | headers: actor ? { authorization: `Bearer ${actor.token}` } : {}, |
| 75 | }); |
| 76 | return { status: response.status, body: response.headers.get('content-type')?.includes('application/json') |
| 77 | ? await response.json() : null }; |
| 78 | } |
| 79 | |
| 80 | test('locator gives authenticated catalogue navigation without owner or progress data', async () => { |
| 81 | const expected = { id: ids.unit, titleFa: 'درس صرفاً آزمایشی', courseId: ids.course }; |
| 82 | for (const actor of actors) { |
| 83 | const result = await get(ids.unit, actor, `?ownerUserId=${actors[0].id}`); |
| 84 | assert.equal(result.status, 200); assert.deepEqual(result.body.unit, expected); |
| 85 | assert.deepEqual(Object.keys(result.body).sort(), ['fetchedAt', 'unit']); |
| 86 | assert.ok(Number.isFinite(Date.parse(result.body.fetchedAt))); |
| 87 | assert.equal(JSON.stringify(result.body).includes(actors[0].id), false); |
| 88 | assert.equal(JSON.stringify(result.body).includes('in_progress'), false); |
| 89 | } |
| 90 | }); |
| 91 | |
| 92 | test('locator requires current session and bounds UUID and absent catalogue items', async () => { |
| 93 | assert.equal((await get(ids.unit)).status, 401); |
| 94 | assert.equal((await get('not-a-uuid', actors[0])).status, 400); |
| 95 | assert.equal((await get(crypto.randomUUID(), actors[0])).status, 404); |
| 96 | }); |
| 97 | |
| 98 | test('inactive units and non-library legacy books cannot be located', async () => { |
| 99 | await pool.query('update learning_unit set active=false where id=$1', [ids.unit]); |
| 100 | try { assert.equal((await get(ids.unit, actors[0])).status, 404); } |
| 101 | finally { await pool.query('update learning_unit set active=true where id=$1', [ids.unit]); } |
| 102 | await pool.query('update textbook_catalog set stable_book_key=null where id=$1', [ids.course]); |
| 103 | try { assert.equal((await get(ids.unit, actors[0])).status, 404); } |
| 104 | finally { await pool.query('update textbook_catalog set stable_book_key=$2 where id=$1', [ids.course, `locator:${ids.course}`]); } |
| 105 | }); |
| 106 | |
| 107 | test('locator reflects current public title but neither private progress nor injected owner context', async () => { |
| 108 | const original = await get(ids.unit, actors[1]); |
| 109 | await pool.query("update learning_progress set status='completed',version=version+1,updated_at=now() where owner_user_id=$1 and unit_id=$2", [actors[0].id, ids.unit]); |
| 110 | const afterProgress = await get(ids.unit, actors[1], `?ownerUserId=${actors[0].id}&childId=${actors[0].id}&role=parent_guardian`); |
| 111 | assert.equal(afterProgress.status, 200); assert.deepEqual(afterProgress.body.unit, original.body.unit); |
| 112 | assert.deepEqual(Object.keys(afterProgress.body).sort(), ['fetchedAt', 'unit']); |
| 113 | assert.equal(JSON.stringify(afterProgress.body).includes('completed'), false); |
| 114 | assert.equal(JSON.stringify(afterProgress.body).includes(actors[0].id), false); |
| 115 | await pool.query('update learning_unit set title_fa=$2 where id=$1', [ids.unit, 'عنوان عمومی اصلاحشده']); |
| 116 | try { |
| 117 | const changed = await get(ids.unit, actors[1]); |
| 118 | assert.equal(changed.status, 200); |
| 119 | assert.deepEqual(changed.body.unit, { ...original.body.unit, titleFa: 'عنوان عمومی اصلاحشده' }); |
| 120 | } finally { await pool.query('update learning_unit set title_fa=$2 where id=$1', [ids.unit, original.body.unit.titleFa]); } |
| 121 | }); |
| 122 | |
| 123 | test('locator rechecks token expiry, session expiry and disabled account state on each read', async () => { |
| 124 | const actor = actors[0]; |
| 125 | const expired = { ...actor, token: jwt.sign({ sub: actor.id, sid: actor.sid, aud: 'lifemate-api' }, secret, { issuer: 'lifemate', expiresIn: -1 }) }; |
| 126 | const expiredResult = await get(ids.unit, expired); |
| 127 | assert.equal(expiredResult.status, 401); assert.deepEqual(Object.keys(expiredResult.body), ['error']); |
| 128 | await pool.query("update auth_session set expires_at=now()-interval '1 second' where id=$1", [actor.sid]); |
| 129 | try { assert.equal((await get(ids.unit, actor)).status, 401); } |
| 130 | finally { await pool.query("update auth_session set expires_at=now()+interval '1 day' where id=$1", [actor.sid]); } |
| 131 | await pool.query('update app_user set disabled_at=now() where id=$1', [actor.id]); |
| 132 | try { |
| 133 | const disabled = await get(ids.unit, actor); |
| 134 | assert.equal(disabled.status, 401); assert.deepEqual(Object.keys(disabled.body), ['error']); |
| 135 | } finally { await pool.query('update app_user set disabled_at=null where id=$1', [actor.id]); } |
| 136 | assert.equal((await get(ids.unit, actor)).status, 200); |
| 137 | }); |
| 138 | |
| 139 | test('revoked session cannot resolve lesson metadata', async () => { |
| 140 | await pool.query('update auth_session set revoked_at=now() where id=$1', [actors[1].sid]); |
| 141 | assert.equal((await get(ids.unit, actors[1])).status, 401); |
| 142 | }); |