LifeMate — Personal, Family & Learning Companion
docs/child-education-access-decision
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 } from 'node:test'; |
| 2 | import assert from 'node:assert/strict'; |
| 3 | import crypto from 'node:crypto'; |
| 4 | import jwt from 'jsonwebtoken'; |
| 5 | import pg from 'pg'; |
| 6 | import net from 'node:net'; |
| 7 | import {spawn} from 'node:child_process'; |
| 8 | import {once} from 'node:events'; |
| 9 | |
| 10 | assert.ok(process.env.DATABASE_URL && process.env.JWT_SECRET?.length >= 32, |
| 11 | 'Use a migrated synthetic PostgreSQL database and synthetic signing secret'); |
| 12 | const pool=new pg.Pool({connectionString:process.env.DATABASE_URL}); |
| 13 | const users = [], families = []; |
| 14 | let server, base; |
| 15 | async function restart() { |
| 16 | if(server) { const closed=once(server,'close'); server.kill('SIGTERM'); await closed; } |
| 17 | const reservation=net.createServer().listen(0,'127.0.0.1'); |
| 18 | await once(reservation,'listening'); const port=reservation.address().port; |
| 19 | await new Promise(resolve=>reservation.close(resolve)); |
| 20 | base=`http://127.0.0.1:${port}`; |
| 21 | server=spawn(process.execPath,['src/entrypoint.js'],{stdio:['ignore','pipe','pipe'],env:{...process.env, |
| 22 | NODE_ENV:'production',PORT:String(port),SMS_PROVIDER:'disabled',SMS_PROVIDER_URL:'',SMS_PROVIDER_TOKEN:'', |
| 23 | EMAIL_FROM:'',RESEND_API_KEY:'',SMTP_HOST:'',SMTP_PASSWORD:'',ENABLE_SENSITIVE_FEATURES:'false', |
| 24 | CORS_ORIGINS:'',TRUSTED_PROXY_CIDRS:'',RATE_LIMIT_AUTH_MAX:'2000',RATE_LIMIT_GENERAL_MAX:'4000'}}); |
| 25 | await new Promise((resolve,reject)=>{ |
| 26 | let output=''; const timeout=setTimeout(()=>reject(new Error('Goal API process startup timed out')),10000); |
| 27 | server.stdout.on('data',chunk=>{output+=chunk.toString();if(output.includes('"type":"startup"')) {clearTimeout(timeout);resolve();}}); |
| 28 | server.once('error',error=>{clearTimeout(timeout);reject(error);}); |
| 29 | server.once('exit',code=>{clearTimeout(timeout);reject(new Error(`Goal API process stopped before startup (${code})`));}); |
| 30 | }); |
| 31 | } |
| 32 | await restart(); |
| 33 | after(async () => { |
| 34 | if(server && server.exitCode===null && server.signalCode===null) { |
| 35 | const closed=once(server,'close'); server.kill('SIGTERM'); await closed; |
| 36 | } |
| 37 | try { |
| 38 | if (families.length) await pool.query('delete from family_workspace where id=any($1::uuid[])', [families]); |
| 39 | if (users.length) await pool.query('delete from app_user where id=any($1::uuid[])', [users]); |
| 40 | } finally { await pool.end(); } |
| 41 | }); |
| 42 | async function actor() { |
| 43 | const id = crypto.randomUUID(), sid = crypto.randomUUID(); users.push(id); |
| 44 | await pool.query('insert into app_user(id,identity_subject,email_normalized,email_verified_at) values($1,$2,$3,now())', [id, `goal-test:${id}`, `goal-${id}@example.test`]); |
| 45 | await pool.query("insert into profile(user_id,display_name) values($1,'Synthetic Goal')", [id]); |
| 46 | 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.randomUUID()]); |
| 47 | return {id,sid, token: jwt.sign({sub:id,sid,aud:'lifemate-api'},process.env.JWT_SECRET,{issuer:'lifemate',expiresIn:'15m'})}; |
| 48 | } |
| 49 | async function request(actor, method, path, body) { |
| 50 | const response = await fetch(base+'/v1/learning/goals'+path,{method, |
| 51 | headers:{'content-type':'application/json',...(actor?{authorization:`Bearer ${actor.token}`}:{})}, |
| 52 | ...(body===undefined?{}:{body:JSON.stringify(body)})}); |
| 53 | const raw = await response.text(); |
| 54 | return {status:response.status,body:raw?JSON.parse(raw):null}; |
| 55 | } |
| 56 | const create = () => ({id:crypto.randomUUID(),mutationId:crypto.randomUUID(),expectedVersion:0,title:'هدف ساختگی',target:'Private synthetic target'}); |
| 57 | |
| 58 | test('modern goal creates one stable record, retries lost acknowledgement after real API process restart and retains archive tombstone/history',async()=>{ |
| 59 | const owner=await actor(), body=create(); |
| 60 | const first=await request(owner,'POST','',body); |
| 61 | assert.equal(first.status,201); assert.ok(first.body.goal,'Canonical goal acknowledgement is required'); assert.equal(first.body.goal.id,body.id); |
| 62 | assert.equal(first.body.goal.version,1); assert.equal(first.body.acknowledgement.mutationId,body.mutationId); |
| 63 | const firstProcess=server.pid; await restart(); assert.notEqual(server.pid,firstProcess); |
| 64 | const retry=await request(owner,'POST','',body); assert.equal(retry.status,200); |
| 65 | assert.equal(retry.body.acknowledgement.status,'already_applied'); |
| 66 | assert.equal((await pool.query('select count(*)::int n from learning_goal where id=$1',[body.id])).rows[0].n,1); |
| 67 | const checkin=(await pool.query('insert into learning_checkin(owner_user_id,learning_goal_id,confidence,note) values($1,$2,3,$3) returning id',[owner.id,body.id,'PRIVATE-SYNTHETIC-NOTE'])).rows[0]; |
| 68 | const edit={mutationId:crypto.randomUUID(),expectedVersion:1,title:'ویرایش ساختگی',target:null,status:'completed'}; |
| 69 | assert.equal((await request(owner,'PATCH','/'+body.id,edit)).body.goal.version,2); |
| 70 | const archive={mutationId:crypto.randomUUID(),expectedVersion:2}; |
| 71 | const archived=await request(owner,'DELETE','/'+body.id,archive); assert.equal(archived.status,200); assert.equal(archived.body.goal.status,'archived'); |
| 72 | const oldCreate=await request(owner,'POST','',body); assert.equal(oldCreate.body.goal.status,'archived'); |
| 73 | assert.equal(oldCreate.body.goal.version,3); assert.equal(oldCreate.body.acknowledgement.appliedVersion,1); |
| 74 | assert.equal((await request(owner,'DELETE','/'+body.id,archive)).body.goal.version,3); |
| 75 | assert.equal((await request(owner,'GET','')).body.items.length,0); |
| 76 | assert.equal((await request(owner,'GET','/'+body.id)).body.status,'archived'); |
| 77 | const retained=(await pool.query('select learning_goal_id,note from learning_checkin where id=$1',[checkin.id])).rows[0]; |
| 78 | assert.deepEqual(retained,{learning_goal_id:body.id,note:'PRIVATE-SYNTHETIC-NOTE'}); |
| 79 | }); |
| 80 | |
| 81 | test('goal mutation hash and expected version reject reuse, concurrent stale edits and archived revival',async()=>{ |
| 82 | const owner=await actor(),body=create(); await request(owner,'POST','',body); |
| 83 | assert.equal((await request(owner,'POST','',{...body,title:'Changed intent'})).status,409); |
| 84 | const results=await Promise.all(['One','Two'].map(title=>request(owner,'PATCH','/'+body.id,{title,mutationId:crypto.randomUUID(),expectedVersion:1}))); |
| 85 | assert.deepEqual(results.map(x=>x.status).sort(),[200,409]); |
| 86 | await request(owner,'DELETE','/'+body.id,{mutationId:crypto.randomUUID(),expectedVersion:2}); |
| 87 | assert.equal((await request(owner,'PATCH','/'+body.id,{status:'active',mutationId:crypto.randomUUID(),expectedVersion:3})).status,409); |
| 88 | assert.equal((await pool.query('select count(*)::int n from learning_goal_mutation where owner_user_id=$1',[owner.id])).rows[0].n,3); |
| 89 | }); |
| 90 | |
| 91 | test('guardian and other family cannot read or mutate private goals, including request-owner injection',async()=>{ |
| 92 | const owner=await actor(),guardian=await actor(),other=await actor(),family=crypto.randomUUID(); families.push(family); |
| 93 | await pool.query("insert into family_workspace(id,name,created_by) values($1,'Synthetic Goal Family',$2)",[family,guardian.id]); |
| 94 | await pool.query("insert into family_membership(family_id,user_id,role) values($1,$2,'teen_minor'),($1,$3,'parent_guardian')",[family,owner.id,guardian.id]); |
| 95 | await pool.query('insert into guardian_relationship(family_id,guardian_user_id,minor_user_id) values($1,$2,$3)',[family,guardian.id,owner.id]); |
| 96 | const body=create(); await request(owner,'POST','',body); |
| 97 | for(const viewer of [guardian,other]) { |
| 98 | assert.equal((await request(viewer,'GET','/'+body.id)).status,404); |
| 99 | assert.deepEqual((await request(viewer,'GET','')).body.items,[]); |
| 100 | assert.equal((await request(viewer,'PATCH','/'+body.id,{title:'Forbidden',mutationId:crypto.randomUUID(),expectedVersion:1})).status,403); |
| 101 | assert.equal((await request(viewer,'DELETE','/'+body.id,{mutationId:crypto.randomUUID(),expectedVersion:1})).status,403); |
| 102 | } |
| 103 | assert.equal((await request(owner,'POST','',{...create(),ownerUserId:other.id})).status,400); |
| 104 | for(const method of ['GET','POST','PATCH','DELETE']) assert.equal((await request(null,method,method==='POST'?'':'/'+body.id,method==='GET'?undefined:{})).status,401); |
| 105 | }); |
| 106 | |
| 107 | async function schoolSubject(owner, {subjectOwner=owner,activeContext=true,activeYear=true,activeTerm=true,archived=false}={}) { |
| 108 | const context=crypto.randomUUID(),year=crypto.randomUUID(),term=crypto.randomUUID(),subject=crypto.randomUUID(); |
| 109 | await pool.query("insert into life_context(id,user_id,kind,title) values($1,$2,'student','Synthetic Goal Context')",[context,subjectOwner.id]); |
| 110 | await pool.query("insert into academic_year(id,student_user_id,life_context_id,title,starts_on,ends_on) values($1,$2,$3,'Synthetic Year','2026-09-23','2027-06-22')",[year,subjectOwner.id,context]); |
| 111 | await pool.query("insert into academic_term(id,academic_year_id,title,starts_on,ends_on) values($1,$2,'Synthetic Term','2026-09-23','2027-01-22')",[term,year]); |
| 112 | await pool.query("insert into subject(id,student_user_id,academic_term_id,name,archived_at) values($1,$2,$3,'Synthetic Math',case when $4 then now() else null end)",[subject,subjectOwner.id,term,archived]); |
| 113 | if(!activeContext) await pool.query('update life_context set active=false where id=$1',[context]); |
| 114 | if(!activeYear) await pool.query('update academic_year set active=false where id=$1',[year]); |
| 115 | if(!activeTerm) await pool.query('update academic_term set active=false where id=$1',[term]); |
| 116 | return {id:subject,context,year}; |
| 117 | } |
| 118 | |
| 119 | test('legacy and modern goals reject archived, inactive and foreign-owned school ancestry',async()=>{ |
| 120 | const owner=await actor(),other=await actor(); |
| 121 | const cases=[{archived:true},{activeContext:false},{activeYear:false},{activeTerm:false},{subjectOwner:other}]; |
| 122 | for(const scenario of cases) { |
| 123 | const subject=await schoolSubject(owner,scenario); |
| 124 | const legacy=await request(owner,'POST','',{title:'Forbidden ancestry',subjectId:subject.id}); |
| 125 | assert.equal(legacy.status,403,`legacy POST must reject ${Object.keys(scenario)[0]}`); |
| 126 | const modern=await request(owner,'POST','',{...create(),subjectId:subject.id}); |
| 127 | assert.equal(modern.status,403,`modern POST must reject ${Object.keys(scenario)[0]}`); |
| 128 | const goal=await request(owner,'POST','',create()); |
| 129 | assert.equal((await request(owner,'PATCH','/'+goal.body.goal.id,{subjectId:subject.id})).status,403); |
| 130 | assert.equal((await request(owner,'PATCH','/'+goal.body.goal.id,{subjectId:subject.id,mutationId:crypto.randomUUID(),expectedVersion:1})).status,403); |
| 131 | assert.equal((await request(owner,'GET','/'+goal.body.goal.id)).body.version,1); |
| 132 | } |
| 133 | const subject=await schoolSubject(owner); |
| 134 | const linked=await request(owner,'POST','',{...create(),subjectId:subject.id}); |
| 135 | assert.equal(linked.status,201); assert.equal(linked.body.goal.subject_id,subject.id); |
| 136 | // Historical goal text remains editable after its school parent is inactive; |
| 137 | // only a new/reassigned subject link requires the currently active ancestry. |
| 138 | await pool.query('update academic_year set active=false where id=$1',[subject.year]); |
| 139 | const edited=await request(owner,'PATCH','/'+linked.body.goal.id,{mutationId:crypto.randomUUID(),expectedVersion:1,title:'Historical goal correction'}); |
| 140 | assert.equal(edited.status,200); assert.equal(edited.body.goal.subject_id,subject.id); |
| 141 | }); |
| 142 | |
| 143 | test('legacy response shapes retain CRUD while versions and archive timestamps remain consistent',async()=>{ |
| 144 | const owner=await actor(); |
| 145 | const created=await request(owner,'POST','',{title:'Legacy goal',target:'Legacy target'}); |
| 146 | assert.equal(created.status,201); assert.equal(created.body.version,1); assert.ok(created.body.id); assert.equal(created.body.goal,undefined); |
| 147 | const edited=await request(owner,'PATCH','/'+created.body.id,{target:null,status:'completed'}); |
| 148 | assert.equal(edited.status,200); assert.equal(edited.body.version,2); assert.equal(edited.body.target,null); assert.equal(edited.body.archived_at,null); |
| 149 | const archived=await request(owner,'PATCH','/'+created.body.id,{status:'archived'}); |
| 150 | assert.equal(archived.body.version,3); assert.ok(archived.body.archived_at); |
| 151 | assert.equal((await request(owner,'DELETE','/'+created.body.id)).status,204); |
| 152 | assert.equal((await request(owner,'DELETE','/'+created.body.id)).status,204); |
| 153 | const tombstone=await request(owner,'GET','/'+created.body.id); |
| 154 | assert.equal(tombstone.body.version,3); assert.equal(tombstone.body.archived_at,archived.body.archived_at); |
| 155 | assert.equal((await request(owner,'PATCH','/'+created.body.id,{status:'active'})).status,409); |
| 156 | }); |
| 157 | |
| 158 | test('goals validate exact write fields, text types, status and bounded versions without silently applying them',async()=>{ |
| 159 | const owner=await actor(),goal=await request(owner,'POST','',create()),id=goal.body.goal.id; |
| 160 | const invalidCreates=[null,[],{title:{text:'Coercion'}},{title:'Too long',target:'x'.repeat(1001)}, |
| 161 | {title:'Injected owner',ownerUserId:owner.id},{title:'Claimed verification',source:'verified'}, |
| 162 | {title:'Invalid status',status:'verified'},{title:'Nul\u0000byte'}]; |
| 163 | for(const body of invalidCreates) assert.equal((await request(owner,'POST','',body)).status,400); |
| 164 | for(const body of [{},[],{source:'verified'},{ownerUserId:owner.id},{title:'Nul\u0000byte'}, |
| 165 | {status:'verified'},{title:'Valid',mutationId:crypto.randomUUID(),expectedVersion:0}, |
| 166 | {title:'Valid',mutationId:crypto.randomUUID(),expectedVersion:2147483647}, |
| 167 | {title:'Valid',mutationId:crypto.randomUUID(),expectedVersion:2147483648}]) { |
| 168 | assert.equal((await request(owner,'PATCH','/'+id,body)).status,400); |
| 169 | } |
| 170 | assert.equal((await request(owner,'DELETE','/'+id,{source:'verified'})).status,400); |
| 171 | assert.equal((await request(owner,'PATCH','/'+id+'?ownerUserId='+owner.id,{title:'Valid'})).status,400); |
| 172 | assert.equal((await request(owner,'GET','/'+id)).body.version,1); |
| 173 | }); |
| 174 | |
| 175 | async function waitForBlockedRequest(blockerPid) { |
| 176 | for(let tries=0;tries<100;tries++) { |
| 177 | const blocked=await pool.query('select 1 from pg_stat_activity where $1::int=any(pg_blocking_pids(pid))',[blockerPid]); |
| 178 | if(blocked.rowCount) return; |
| 179 | await new Promise(resolve=>setTimeout(resolve,10)); |
| 180 | } |
| 181 | assert.fail('The real HTTP write never reached the PostgreSQL lock wait'); |
| 182 | } |
| 183 | |
| 184 | test('legacy and modern goal writes recheck expired/revoked sessions and JWT after an actual account lock wait',async()=>{ |
| 185 | for(const modern of [false,true]) for(const reason of ['session_expiry','revocation','jwt_expiry']) { |
| 186 | const owner=await actor(),body=modern?create():{title:'Blocked synthetic goal'}; |
| 187 | let expiresAt; |
| 188 | if(reason==='jwt_expiry') { |
| 189 | expiresAt=Math.floor(Date.now()/1000)+2; |
| 190 | owner.token=jwt.sign({sub:owner.id,sid:owner.sid,aud:'lifemate-api',exp:expiresAt},process.env.JWT_SECRET,{issuer:'lifemate'}); |
| 191 | } |
| 192 | const blocker=await pool.connect(); |
| 193 | let pending; |
| 194 | try { |
| 195 | await blocker.query('begin'); |
| 196 | const pid=(await blocker.query('select pg_backend_pid() pid')).rows[0].pid; |
| 197 | await blocker.query('select id from app_user where id=$1 for update',[owner.id]); |
| 198 | pending=request(owner,'POST','',body); |
| 199 | await waitForBlockedRequest(pid); |
| 200 | if(reason==='session_expiry') await pool.query("update auth_session set expires_at=statement_timestamp()-interval '1 second' where id=$1",[owner.sid]); |
| 201 | if(reason==='revocation') await pool.query('update auth_session set revoked_at=statement_timestamp() where id=$1',[owner.sid]); |
| 202 | if(reason==='jwt_expiry') await new Promise(resolve=>setTimeout(resolve,Math.max(0,expiresAt*1000-Date.now()+20))); |
| 203 | await blocker.query('commit'); |
| 204 | const result=await pending; |
| 205 | assert.equal(result.status,401,`${modern?'modern':'legacy'} ${reason} must rollback after waiting`); |
| 206 | assert.equal((await pool.query('select count(*)::int n from learning_goal where owner_user_id=$1',[owner.id])).rows[0].n,0); |
| 207 | } finally { |
| 208 | await blocker.query('rollback'); blocker.release(); |
| 209 | if(pending) await pending; |
| 210 | } |
| 211 | } |
| 212 | }); |
| 213 | |
| 214 | test('goal final authorization rolls back a legacy or modern edit when JWT expires during the goal row wait',async()=>{ |
| 215 | for(const modern of [false,true]) { |
| 216 | const owner=await actor(),created=await request(owner,'POST','',create()); |
| 217 | const id=created.body.goal.id,expiresAt=Math.floor(Date.now()/1000)+2; |
| 218 | owner.token=jwt.sign({sub:owner.id,sid:owner.sid,aud:'lifemate-api',exp:expiresAt},process.env.JWT_SECRET,{issuer:'lifemate'}); |
| 219 | const blocker=await pool.connect(); let pending; |
| 220 | try { |
| 221 | await blocker.query('begin'); |
| 222 | const pid=(await blocker.query('select pg_backend_pid() pid')).rows[0].pid; |
| 223 | await blocker.query('select id from learning_goal where id=$1 for update',[id]); |
| 224 | pending=request(owner,'PATCH','/'+id,{title:'Must roll back',...(modern?{mutationId:crypto.randomUUID(),expectedVersion:1}:{})}); |
| 225 | await waitForBlockedRequest(pid); |
| 226 | await new Promise(resolve=>setTimeout(resolve,Math.max(0,expiresAt*1000-Date.now()+20))); |
| 227 | await blocker.query('commit'); |
| 228 | assert.equal((await pending).status,401); |
| 229 | const stored=(await pool.query('select title,version from learning_goal where id=$1',[id])).rows[0]; |
| 230 | assert.deepEqual(stored,{title:'هدف ساختگی',version:1}); |
| 231 | assert.equal((await pool.query('select count(*)::int n from learning_goal_mutation where owner_user_id=$1',[owner.id])).rows[0].n,1); |
| 232 | } finally { |
| 233 | await blocker.query('rollback'); blocker.release(); |
| 234 | if(pending) await pending; |
| 235 | } |
| 236 | } |
| 237 | }); |
| 238 | |
| 239 | test('two owners concurrently using the same stable goal ID get one create and one denied conflict without a server error',async()=>{ |
| 240 | const first=await actor(),second=await actor(),id=crypto.randomUUID(); |
| 241 | const blocker=await pool.connect(); let pending; |
| 242 | try { |
| 243 | await blocker.query('begin'); await blocker.query('lock table learning_goal in share mode'); |
| 244 | const blockerPid=(await blocker.query('select pg_backend_pid() pid')).rows[0].pid; |
| 245 | pending=Promise.all([first,second].map(owner=>request(owner,'POST','',{...create(),id}))); |
| 246 | // Without entity serialization both creates reach the blocked INSERT after |
| 247 | // independently seeing no row. With serialization the second waits at the |
| 248 | // advisory lock, and observes the first committed row after release. |
| 249 | await waitForBlockedRequest(blockerPid); |
| 250 | await new Promise(resolve=>setTimeout(resolve,50)); |
| 251 | await blocker.query('commit'); |
| 252 | const results=await pending; |
| 253 | assert.deepEqual(results.map(result=>result.status).sort(),[201,403]); |
| 254 | assert.equal((await pool.query('select count(*)::int n from learning_goal where id=$1',[id])).rows[0].n,1); |
| 255 | const journal=await pool.query('select owner_user_id from learning_goal_mutation where goal_id=$1',[id]); |
| 256 | const goal=(await pool.query('select owner_user_id from learning_goal where id=$1',[id])).rows[0]; |
| 257 | assert.deepEqual(journal.rows,[goal]); |
| 258 | const denied=results.find(result=>result.status===403); |
| 259 | assert.deepEqual(denied.body,{error:'goal_forbidden'}); |
| 260 | } finally { |
| 261 | await blocker.query('rollback');blocker.release();if(pending) await pending; |
| 262 | } |
| 263 | }); |