LifeMate — Personal, Family & Learning Companion
feat/flutter-mobile-navigation
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 jwt from 'jsonwebtoken'; |
| 9 | import fs from 'node:fs/promises'; |
| 10 | import { assertSchoolSession } from '../src/school_lifecycle.js'; |
| 11 | |
| 12 | assert.ok(process.env.DATABASE_URL, 'School lifecycle tests require migrated synthetic PostgreSQL'); |
| 13 | assert.ok(process.env.JWT_SECRET?.length >= 32, 'School lifecycle tests require a synthetic JWT secret'); |
| 14 | const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL }); |
| 15 | const users = [], families = []; |
| 16 | let child, base, output = '', errors = ''; |
| 17 | |
| 18 | async function start() { |
| 19 | const reservation = net.createServer().listen(0, '127.0.0.1'); |
| 20 | await once(reservation, 'listening'); |
| 21 | const port = reservation.address().port; |
| 22 | await new Promise((resolve) => reservation.close(resolve)); |
| 23 | base = `http://127.0.0.1:${port}`; |
| 24 | let startup = ''; |
| 25 | child = spawn(process.execPath, ['src/entrypoint.js'], { |
| 26 | env: { ...process.env, NODE_ENV: 'production', PORT: String(port), |
| 27 | SMS_PROVIDER: 'disabled', SMS_PROVIDER_URL: '', SMS_PROVIDER_TOKEN: '', EMAIL_FROM: '', RESEND_API_KEY: '', SMTP_HOST: '', |
| 28 | CORS_ORIGINS: '', TRUSTED_PROXY_CIDRS: '', ENABLE_SENSITIVE_FEATURES: 'false', |
| 29 | RATE_LIMIT_AUTH_MAX: '2000', RATE_LIMIT_GENERAL_MAX: '4000', RATE_LIMIT_AI_MAX: '2000' }, |
| 30 | stdio: ['ignore', 'pipe', 'pipe'], |
| 31 | }); |
| 32 | child.stdout.on('data', (chunk) => { output += chunk.toString(); startup += chunk.toString(); }); |
| 33 | child.stderr.on('data', (chunk) => { errors += chunk.toString(); }); |
| 34 | await new Promise((resolve, reject) => { |
| 35 | const timer = setTimeout(() => reject(new Error('School lifecycle fixture startup timed out')), 10000); |
| 36 | const onData = () => { |
| 37 | if (!startup.includes('"type":"startup"')) return; |
| 38 | clearTimeout(timer); child.stdout.off('data', onData); resolve(); |
| 39 | }; |
| 40 | child.stdout.on('data', onData); |
| 41 | child.once('error', (error) => { clearTimeout(timer); reject(error); }); |
| 42 | }); |
| 43 | } |
| 44 | async function stop() { |
| 45 | if (child && child.exitCode === null && child.signalCode === null) { |
| 46 | const closed = once(child, 'close'); child.kill('SIGTERM'); await closed; |
| 47 | } |
| 48 | } |
| 49 | before(start); |
| 50 | after(async () => { |
| 51 | await stop(); |
| 52 | try { |
| 53 | await pool.query('delete from access_audit where family_id=any($1::uuid[]) or actor_user_id=any($2::uuid[])', [families, users]); |
| 54 | await pool.query('delete from family_workspace where id=any($1::uuid[])', [families]); |
| 55 | await pool.query('delete from app_user where id=any($1::uuid[])', [users]); |
| 56 | } finally { await pool.end(); } |
| 57 | }); |
| 58 | async function user() { |
| 59 | const id = crypto.randomUUID(), sid = crypto.randomUUID(); |
| 60 | users.push(id); |
| 61 | await pool.query('insert into app_user(id,identity_subject,email_normalized,email_verified_at) values($1,$2,$3,now())', [id, `school-fixture:${id}`, `school-${id}@example.test`]); |
| 62 | await pool.query("insert into profile(user_id,display_name,theme_preference) values($1,'Synthetic School User','adult_blue')", [id]); |
| 63 | await pool.query("insert into auth_session(id,user_id,refresh_digest,expires_at) values($1,$2,$3,now()+interval '1 day')", [sid, id, crypto.randomBytes(32).toString('hex')]); |
| 64 | return { id, token: jwt.sign({ sub: id, sid, aud: 'lifemate-api' }, process.env.JWT_SECRET, { issuer: 'lifemate', expiresIn: '15m' }) }; |
| 65 | } |
| 66 | async function request(path, { method = 'GET', actor, body } = {}) { |
| 67 | const response = await fetch(base + path, { method, headers: { 'content-type': 'application/json', ...(actor ? { authorization: `Bearer ${actor.token}` } : {}) }, body: body === undefined ? undefined : JSON.stringify(body) }); |
| 68 | const text = await response.text(); |
| 69 | return { status: response.status, body: text && response.headers.get('content-type')?.includes('application/json') ? JSON.parse(text) : text || null }; |
| 70 | } |
| 71 | |
| 72 | async function observedBlock(blocker) { |
| 73 | const pid = (await blocker.query('select pg_backend_pid() as pid')).rows[0].pid; |
| 74 | const deadline = Date.now() + 3000; |
| 75 | while (Date.now() < deadline) { |
| 76 | const waiting = await pool.query('select 1 from pg_stat_activity where $1=any(pg_blocking_pids(pid))', [pid]); |
| 77 | if (waiting.rowCount) return; |
| 78 | await new Promise((resolve) => setTimeout(resolve, 15)); |
| 79 | } |
| 80 | throw new Error('Request never reached the observed PostgreSQL row-lock wait'); |
| 81 | } |
| 82 | |
| 83 | async function expireAfterObservedWait(blocker, expiresAt) { |
| 84 | await observedBlock(blocker); |
| 85 | while (Date.now() <= expiresAt + 25) await new Promise((resolve) => setTimeout(resolve, Math.min(25, expiresAt + 26 - Date.now()))); |
| 86 | await blocker.query('commit'); |
| 87 | } |
| 88 | |
| 89 | |
| 90 | test('owner lifecycle list starts empty and rejects anonymous access', async () => { |
| 91 | const actor = await user(); |
| 92 | assert.equal((await request('/v1/school/lifecycle')).status, 401); |
| 93 | const result = await request('/v1/school/lifecycle', { actor }); |
| 94 | assert.equal(result.status, 200); |
| 95 | assert.deepEqual(result.body.contexts, []); |
| 96 | assert.deepEqual(result.body.years, []); |
| 97 | assert.deepEqual(result.body.terms, []); |
| 98 | assert.ok(Date.parse(result.body.fetchedAt)); |
| 99 | }); |
| 100 | |
| 101 | function intent(operation = 'create', data = {}, entityId = crypto.randomUUID(), expectedVersion = operation === 'create' ? 0 : 1) { |
| 102 | return { mutationId: crypto.randomUUID(), entityId, operation, expectedVersion, data }; |
| 103 | } |
| 104 | const mutate = (actor, type, body) => request(`/v1/school/lifecycle/${type}/mutations`, { method: 'POST', actor, body }); |
| 105 | async function lifecycle(actor = undefined) { |
| 106 | actor ??= await user(); |
| 107 | const contextIntent = intent('create', { kind: 'student', title: 'مدرسه آزمایشی' }); |
| 108 | const context = await mutate(actor, 'contexts', contextIntent); assert.equal(context.status, 201); |
| 109 | const yearIntent = intent('create', { lifeContextId: context.body.entity.id, title: 'سال انتخابی', startsOn: '2026-08-12', endsOn: '2027-07-05' }); |
| 110 | const year = await mutate(actor, 'years', yearIntent); assert.equal(year.status, 201); |
| 111 | const termIntent = intent('create', { academicYearId: year.body.entity.id, title: 'دوره انتخابی', startsOn: '2026-08-15', endsOn: '2027-02-10' }); |
| 112 | const term = await mutate(actor, 'terms', termIntent); assert.equal(term.status, 201); |
| 113 | return { actor, context: context.body.entity, year: year.body.entity, term: term.body.entity, contextIntent, yearIntent, termIntent }; |
| 114 | } |
| 115 | |
| 116 | test('stable school creates survive lost ACK, process restart and old retry returns current version', async () => { |
| 117 | const f = await lifecycle(); |
| 118 | await stop(); await start(); |
| 119 | const retry = await mutate(f.actor, 'years', f.yearIntent); |
| 120 | assert.equal(retry.status, 200); assert.equal(retry.body.acknowledgement.status, 'already_applied'); |
| 121 | assert.equal(retry.body.acknowledgement.appliedVersion, 1); |
| 122 | const edited = await mutate(f.actor, 'years', intent('update', { title: 'سال ویرایششده' }, f.year.id, 1)); |
| 123 | assert.equal(edited.status, 200); assert.equal(edited.body.entity.version, 2); |
| 124 | const oldRetry = await mutate(f.actor, 'years', f.yearIntent); |
| 125 | assert.equal(oldRetry.body.entity.title, 'سال ویرایششده'); assert.equal(oldRetry.body.entity.version, 2); |
| 126 | assert.equal(oldRetry.body.acknowledgement.appliedVersion, 1); |
| 127 | assert.equal((await pool.query('select count(*)::int as n from academic_year where student_user_id=$1', [f.actor.id])).rows[0].n, 1); |
| 128 | assert.equal((await mutate(f.actor, 'years', { ...f.yearIntent, data: { ...f.yearIntent.data, title: 'UUID reused with changed content' } })).status, 409); |
| 129 | const reopened = await request('/v1/school/lifecycle', { actor: f.actor }); |
| 130 | assert.equal(reopened.body.years[0].starts_on, '2026-08-12'); |
| 131 | assert.equal(reopened.body.terms[0].starts_on, '2026-08-15'); |
| 132 | }); |
| 133 | |
| 134 | test('school version conflicts reject stale edits and archive preserves linked tasks and history', async () => { |
| 135 | const f = await lifecycle(); |
| 136 | const subject = await request(`/v1/school/terms/${f.term.id}/subjects`, { method: 'POST', actor: f.actor, body: { name: 'فیزیک انتخابی' } }); |
| 137 | assert.equal(subject.status, 201); |
| 138 | const homework = await request('/v1/plan-items', { method: 'POST', actor: f.actor, body: { kind: 'assignment', title: 'تکلیف تاریخی', subjectId: subject.body.id, visibility: 'private' } }); |
| 139 | assert.equal(homework.status, 201); |
| 140 | const edit = await mutate(f.actor, 'contexts', intent('update', { title: 'نام تازه' }, f.context.id)); |
| 141 | assert.equal(edit.status, 200); |
| 142 | assert.equal((await mutate(f.actor, 'contexts', intent('update', { title: 'stale' }, f.context.id))).status, 409); |
| 143 | const archivedIntent = intent('archive', {}, f.context.id, 2); |
| 144 | const archived = await mutate(f.actor, 'contexts', archivedIntent); |
| 145 | assert.equal(archived.status, 200); assert.equal(archived.body.entity.active, false); |
| 146 | await stop(); await start(); |
| 147 | assert.equal((await mutate(f.actor, 'contexts', archivedIntent)).body.acknowledgement.status, 'already_applied'); |
| 148 | const list = await request('/v1/school/lifecycle', { actor: f.actor }); |
| 149 | assert.equal(list.body.contexts[0].active, false); |
| 150 | assert.equal(list.body.years[0].id, f.year.id); |
| 151 | assert.equal(list.body.terms[0].id, f.term.id); |
| 152 | const retained = (await pool.query('select p.subject_id,s.name from plan_item p join subject s on s.id=p.subject_id where p.id=$1', [homework.body.id])).rows[0]; |
| 153 | assert.equal(retained.subject_id, subject.body.id); assert.equal(retained.name, 'فیزیک انتخابی'); |
| 154 | const overview = await request(`/v1/school/${f.actor.id}/overview`, { actor: f.actor }); |
| 155 | assert.deepEqual(overview.body.years, []); assert.deepEqual(overview.body.subjects, []); |
| 156 | assert.ok(overview.body.workload.some((row) => row.id === homework.body.id)); |
| 157 | assert.equal((await mutate(f.actor, 'terms', intent('update', { title: 'Cannot edit archived ancestor' }, f.term.id))).status, 409); |
| 158 | assert.equal((await mutate(f.actor, 'contexts', intent('update', { title: 'Cannot unarchive' }, f.context.id, 3))).status, 409); |
| 159 | }); |
| 160 | |
| 161 | test('guardian and other-family actors cannot read or write another owner lifecycle', async () => { |
| 162 | const f = await lifecycle(), parent = await user(), outsider = await user(); |
| 163 | const familyId = crypto.randomUUID(); families.push(familyId); |
| 164 | await pool.query("insert into family_workspace(id,name,created_by) values($1,'Lifecycle Synthetic Family',$2)", [familyId, parent.id]); |
| 165 | await pool.query("insert into family_membership(family_id,user_id,role) values($1,$2,'teen_minor'),($1,$3,'parent_guardian')", [familyId, f.actor.id, parent.id]); |
| 166 | await pool.query('insert into guardian_relationship(family_id,guardian_user_id,minor_user_id) values($1,$2,$3)', [familyId, parent.id, f.actor.id]); |
| 167 | for (const actor of [parent, outsider]) { |
| 168 | const list = await request('/v1/school/lifecycle', { actor }); |
| 169 | assert.deepEqual(list.body.contexts, []); assert.deepEqual(list.body.years, []); assert.deepEqual(list.body.terms, []); |
| 170 | for (const [type, entity] of [['contexts', f.context], ['years', f.year], ['terms', f.term]]) { |
| 171 | assert.equal((await mutate(actor, type, intent('update', { title: 'forged' }, entity.id))).status, 404); |
| 172 | assert.equal((await mutate(actor, type, intent('archive', {}, entity.id))).status, 404); |
| 173 | } |
| 174 | assert.equal((await mutate(actor, 'years', intent('create', { lifeContextId: f.context.id, title: 'forged', startsOn: '2026-09-01', endsOn: '2027-01-01' }))).status, 403); |
| 175 | assert.equal((await mutate(actor, 'terms', intent('create', { academicYearId: f.year.id, title: 'forged', startsOn: '2026-09-01', endsOn: '2027-01-01' }))).status, 403); |
| 176 | } |
| 177 | }); |
| 178 | |
| 179 | test('date nesting and historical class recurrence prevent invalid parent date edits', async () => { |
| 180 | const f = await lifecycle(); |
| 181 | for (const date of ['2026-02-30', '0000-01-01', '2026-8-01', '۱۴۰۵-۰۶-۰۱']) { |
| 182 | assert.equal((await mutate(f.actor, 'years', intent('create', { lifeContextId: f.context.id, title: 'invalid', startsOn: date, endsOn: '2027-01-01' }))).status, 400); |
| 183 | } |
| 184 | assert.equal((await mutate(f.actor, 'terms', intent('create', { academicYearId: f.year.id, title: 'outside', startsOn: '2026-08-11', endsOn: '2027-01-01' }))).status, 400); |
| 185 | assert.equal((await mutate(f.actor, 'years', intent('update', { startsOn: '2026-09-01' }, f.year.id))).status, 409); |
| 186 | const subject = await request(`/v1/school/terms/${f.term.id}/subjects`, { method: 'POST', actor: f.actor, body: { name: 'درس' } }); |
| 187 | const lesson = await request(`/v1/school/subjects/${subject.body.id}/classes`, { method: 'POST', actor: f.actor, body: { weekday: 1, startsAt: '09:00', endsAt: '10:00', recurrenceUntil: '2027-02-10' } }); |
| 188 | assert.equal(lesson.status, 201); |
| 189 | assert.equal((await mutate(f.actor, 'terms', intent('update', { endsOn: '2027-02-09' }, f.term.id))).status, 409); |
| 190 | await request(`/v1/school/classes/${lesson.body.id}`, { method: 'DELETE', actor: f.actor }); |
| 191 | assert.equal((await mutate(f.actor, 'terms', intent('update', { endsOn: '2027-02-09' }, f.term.id))).status, 409); |
| 192 | assert.equal((await mutate(f.actor, 'contexts', intent('update', { kind: 'work' }, f.context.id))).status, 409); |
| 193 | }); |
| 194 | |
| 195 | test('term archive blocks both new and legacy child writes and hides active timetable', async () => { |
| 196 | const f = await lifecycle(); |
| 197 | const subject = await request(`/v1/school/terms/${f.term.id}/subjects`, { method: 'POST', actor: f.actor, body: { name: 'درس تاریخی' } }); |
| 198 | const lesson = await request(`/v1/school/subjects/${subject.body.id}/classes`, { method: 'POST', actor: f.actor, body: { weekday: 2, startsAt: '12:00', endsAt: '13:00' } }); |
| 199 | assert.equal(lesson.status, 201); |
| 200 | assert.equal((await mutate(f.actor, 'terms', intent('archive', {}, f.term.id))).status, 200); |
| 201 | assert.equal((await request(`/v1/school/terms/${f.term.id}/subjects`, { method: 'POST', actor: f.actor, body: { name: 'Must not create' } })).status, 404); |
| 202 | assert.equal((await request(`/v1/school/subjects/${subject.body.id}`, { method: 'PATCH', actor: f.actor, body: { name: 'Must not edit' } })).status, 409); |
| 203 | assert.equal((await request(`/v1/school/subjects/${subject.body.id}/classes`, { method: 'POST', actor: f.actor, body: { weekday: 2, startsAt: '14:00', endsAt: '15:00' } })).status, 409); |
| 204 | assert.equal((await request(`/v1/school/classes/${lesson.body.id}`, { method: 'PATCH', actor: f.actor, body: { location: 'Must not edit' } })).status, 409); |
| 205 | assert.deepEqual((await request(`/v1/school/${f.actor.id}/timetable`, { actor: f.actor })).body.classes, []); |
| 206 | assert.equal((await request(`/v1/school/subjects/${subject.body.id}`, { method: 'DELETE', actor: f.actor })).status, 204); |
| 207 | assert.equal((await request(`/v1/school/classes/${lesson.body.id}`, { method: 'DELETE', actor: f.actor })).status, 204); |
| 208 | }); |
| 209 | |
| 210 | test('legacy inserts waiting behind ancestor archival recheck current state without a 500 or duplicate', async () => { |
| 211 | const f = await lifecycle(); |
| 212 | const locking = await pool.connect(); |
| 213 | try { |
| 214 | await locking.query('begin'); |
| 215 | await locking.query('select 1 from app_user where id=$1 for update', [f.actor.id]); |
| 216 | await locking.query('update life_context set active=false where id=$1', [f.context.id]); |
| 217 | const pending = request('/v1/school/years', { method: 'POST', actor: f.actor, body: { lifeContextId: f.context.id, title: 'Racing legacy insert', startsOn: '2028-01-01', endsOn: '2028-12-31' } }); |
| 218 | await new Promise((resolve) => setTimeout(resolve, 100)); |
| 219 | await locking.query('commit'); |
| 220 | const result = await pending; |
| 221 | assert.equal(result.status, 400); |
| 222 | assert.equal(result.body.error, 'invalid_academic_year'); |
| 223 | assert.equal((await pool.query('select count(*)::int as n from academic_year where student_user_id=$1', [f.actor.id])).rows[0].n, 1); |
| 224 | } finally { await locking.query('rollback').catch(() => {}); locking.release(); } |
| 225 | }); |
| 226 | |
| 227 | test('lifecycle input rejects excess fields, invalid versions and malformed IDs', async () => { |
| 228 | const actor = await user(); |
| 229 | const good = intent('create', { kind: 'student', title: 'school' }); |
| 230 | for (const raw of [{ ...good, extra: 'ignored' }, { ...good, expectedVersion: 1 }, { ...good, entityId: 'not-uuid' }, { ...good, data: { ...good.data, active: false } }, { ...good, data: { ...good.data, title: 'x'.repeat(121) } }]) { |
| 231 | assert.equal((await mutate(actor, 'contexts', raw)).status, 400); |
| 232 | } |
| 233 | assert.equal((await mutate(actor, 'unknown', good)).status, 404); |
| 234 | }); |
| 235 | |
| 236 | |
| 237 | test('revoked session after an owner lock wait cannot commit a lifecycle or legacy write', async () => { |
| 238 | for (const legacy of [false, true]) { |
| 239 | const actor = await user(), locking = await pool.connect(); |
| 240 | const claims = jwt.decode(actor.token); |
| 241 | try { |
| 242 | await locking.query('begin'); |
| 243 | await locking.query('select 1 from app_user where id=$1 for update', [actor.id]); |
| 244 | const body = legacy ? { kind: 'student', title: 'Revoked legacy create' } : intent('create', { kind: 'student', title: 'Revoked lifecycle create' }); |
| 245 | const pending = legacy ? request('/v1/life-contexts', { method: 'POST', actor, body }) : mutate(actor, 'contexts', body); |
| 246 | await new Promise((resolve) => setTimeout(resolve, 100)); |
| 247 | await locking.query('update auth_session set revoked_at=clock_timestamp() where id=$1', [claims.sid]); |
| 248 | await locking.query('commit'); |
| 249 | assert.equal((await pending).status, 401); |
| 250 | assert.equal((await pool.query('select count(*)::int as n from life_context where user_id=$1', [actor.id])).rows[0].n, 0); |
| 251 | } finally { await locking.query('rollback').catch(() => {}); locking.release(); } |
| 252 | } |
| 253 | }); |
| 254 | |
| 255 | test('session expiry after a read lock wait returns 401 rather than private lifecycle data', async () => { |
| 256 | const f = await lifecycle(), locking = await pool.connect(), claims = jwt.decode(f.actor.token); |
| 257 | try { |
| 258 | await locking.query('begin'); |
| 259 | await locking.query('select 1 from app_user where id=$1 for update', [f.actor.id]); |
| 260 | const pending = request('/v1/school/lifecycle', { actor: f.actor }); |
| 261 | await new Promise((resolve) => setTimeout(resolve, 100)); |
| 262 | await locking.query("update auth_session set expires_at=clock_timestamp()-interval '1 second' where id=$1", [claims.sid]); |
| 263 | await locking.query('commit'); |
| 264 | const result = await pending; |
| 265 | assert.equal(result.status, 401); assert.equal(result.body.contexts, undefined); |
| 266 | } finally { await locking.query('rollback').catch(() => {}); locking.release(); } |
| 267 | }); |
| 268 | |
| 269 | test('private check-in create, edit and archive roll back JWT expiry after observed record waits', async () => { |
| 270 | const actor = await user(); |
| 271 | const goal = await request('/v1/learning/goals', { method: 'POST', actor, body: { title: 'SYNTHETIC wait goal' } }); |
| 272 | assert.equal(goal.status, 201); |
| 273 | const checkin = await request('/v1/learning/checkins', { method: 'POST', actor, body: { learningGoalId: goal.body.id, confidence: 2, difficulty: 3, note: 'SYNTHETIC private original' } }); |
| 274 | assert.equal(checkin.status, 201); |
| 275 | const claims = jwt.decode(actor.token); |
| 276 | for (const method of ['POST', 'PATCH', 'DELETE']) { |
| 277 | const token = jwt.sign({ sub: actor.id, sid: claims.sid, aud: 'lifemate-api' }, process.env.JWT_SECRET, { issuer: 'lifemate', expiresIn: 2 }); |
| 278 | const exp = jwt.decode(token).exp * 1000; |
| 279 | const locking = await pool.connect(); |
| 280 | try { |
| 281 | await locking.query('begin'); |
| 282 | await locking.query(method === 'POST' ? 'select 1 from learning_goal where id=$1 for update' : 'select 1 from learning_checkin where id=$1 for update', [method === 'POST' ? goal.body.id : checkin.body.id]); |
| 283 | const pending = request(method === 'POST' ? '/v1/learning/checkins' : `/v1/learning/checkins/${checkin.body.id}`, { |
| 284 | method, actor: { ...actor, token }, body: method === 'POST' ? { learningGoalId: goal.body.id, confidence: 1, difficulty: 1 } : method === 'PATCH' ? { note: 'SYNTHETIC must roll back' } : undefined, |
| 285 | }); |
| 286 | await expireAfterObservedWait(locking, exp); |
| 287 | const result = await pending; |
| 288 | assert.equal(result.status, 401, method + ' cannot commit an expired bearer'); |
| 289 | const stored = (await pool.query('select note,archived_at from learning_checkin where id=$1', [checkin.body.id])).rows[0]; |
| 290 | assert.equal(stored.note, 'SYNTHETIC private original'); assert.equal(stored.archived_at, null); |
| 291 | assert.equal((await pool.query('select count(*)::int n from learning_checkin where owner_user_id=$1', [actor.id])).rows[0].n, 1); |
| 292 | } finally { await locking.query('rollback').catch(() => {}); locking.release(); } |
| 293 | } |
| 294 | }); |
| 295 | |
| 296 | test('private check-in edit and read reject database session expiry after an observed row wait', async () => { |
| 297 | const actor = await user(), claims = jwt.decode(actor.token); |
| 298 | const created = await request('/v1/learning/checkins', { method: 'POST', actor, body: { confidence: 2, difficulty: 3, note: 'SYNTHETIC private original' } }); |
| 299 | assert.equal(created.status, 201); |
| 300 | for (const method of ['PATCH', 'GET']) { |
| 301 | const expiresAt = Date.now() + 1700; |
| 302 | await pool.query('update auth_session set expires_at=$2 where id=$1', [claims.sid, new Date(expiresAt)]); |
| 303 | const locking = await pool.connect(); |
| 304 | try { |
| 305 | await locking.query('begin'); |
| 306 | // UPDATE waits on the private row; GET must serialize with account state. |
| 307 | await locking.query(method === 'PATCH' ? 'select 1 from learning_checkin where id=$1 for update' : 'select 1 from app_user where id=$1 for update', [method === 'PATCH' ? created.body.id : actor.id]); |
| 308 | const pending = request(`/v1/learning/checkins/${created.body.id}`, { method, actor, body: method === 'PATCH' ? { note: 'SYNTHETIC must roll back' } : undefined }); |
| 309 | await expireAfterObservedWait(locking, expiresAt); |
| 310 | const result = await pending; |
| 311 | assert.equal(result.status, 401); assert.equal(result.body.note, undefined); |
| 312 | assert.equal((await pool.query('select note from learning_checkin where id=$1', [created.body.id])).rows[0].note, 'SYNTHETIC private original'); |
| 313 | } finally { await locking.query('rollback').catch(() => {}); locking.release(); } |
| 314 | } |
| 315 | }); |
| 316 | |
| 317 | test('school session validation samples fresh database time after the observed session-row lock wait', async () => { |
| 318 | const actor = await user(), claims = jwt.decode(actor.token), locking = await pool.connect(); |
| 319 | const expiresAt = Date.now() + 1700; |
| 320 | await pool.query('update auth_session set expires_at=$2 where id=$1', [claims.sid, new Date(expiresAt)]); |
| 321 | try { |
| 322 | await locking.query('begin'); |
| 323 | await locking.query('select 1 from auth_session where id=$1 for update', [claims.sid]); |
| 324 | const pending = request('/v1/school/lifecycle', { actor }); |
| 325 | await expireAfterObservedWait(locking, expiresAt); |
| 326 | const result = await pending; |
| 327 | assert.equal(result.status, 401); assert.equal(result.body.contexts, undefined); |
| 328 | } finally { await locking.query('rollback').catch(() => {}); locking.release(); } |
| 329 | }); |
| 330 | |
| 331 | test('school session guard itself rejects elapsed expiry after its locking statement began', async () => { |
| 332 | const actor = await user(), claims = jwt.decode(actor.token), locking = await pool.connect(), validating = await pool.connect(); |
| 333 | const expiresAt = Date.now() + 1700; |
| 334 | await pool.query('update auth_session set expires_at=$2 where id=$1', [claims.sid, new Date(expiresAt)]); |
| 335 | try { |
| 336 | await locking.query('begin'); await validating.query('begin'); |
| 337 | await locking.query('select 1 from auth_session where id=$1 for update', [claims.sid]); |
| 338 | const pending = assertSchoolSession(validating, claims).then(() => ({ accepted: true }), (error) => ({ error })); |
| 339 | await expireAfterObservedWait(locking, expiresAt); |
| 340 | const result = await pending; |
| 341 | assert.equal(result.error?.code, 'session_invalid'); |
| 342 | } finally { |
| 343 | await locking.query('rollback').catch(() => {}); locking.release(); |
| 344 | await validating.query('rollback').catch(() => {}); validating.release(); |
| 345 | } |
| 346 | }); |
| 347 | |
| 348 | test('legacy academic reads reject session expiry at observed account waits', async () => { |
| 349 | const f = await lifecycle(), claims = jwt.decode(f.actor.token), locking = await pool.connect(); |
| 350 | const expiresAt = Date.now() + 1700; |
| 351 | await pool.query('update auth_session set expires_at=$2 where id=$1', [claims.sid, new Date(expiresAt)]); |
| 352 | try { |
| 353 | await locking.query('begin'); |
| 354 | await locking.query('select 1 from app_user where id=$1 for update', [f.actor.id]); |
| 355 | const pending = Promise.all(['/v1/life-contexts', `/v1/school/${f.actor.id}/overview`, `/v1/school/${f.actor.id}/timetable`] |
| 356 | .map((path) => request(path, { actor: f.actor }))); |
| 357 | await expireAfterObservedWait(locking, expiresAt); |
| 358 | for (const result of await pending) { |
| 359 | assert.equal(result.status, 401); assert.equal(result.body.contexts, undefined); |
| 360 | assert.equal(result.body.subjects, undefined); assert.equal(result.body.classes, undefined); |
| 361 | } |
| 362 | } finally { await locking.query('rollback').catch(() => {}); locking.release(); } |
| 363 | }); |