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 crypto from 'node:crypto'; |
| 2 | import express from 'express'; |
| 3 | import {createSessionAuth} from './session_auth.js'; |
| 4 | import {validUuid} from './plan_mutations.js'; |
| 5 | |
| 6 | class AssessmentError extends Error { |
| 7 | constructor(status,code){super(code);this.status=status;this.code=code;} |
| 8 | } |
| 9 | const fail=(status,code)=>{throw new AssessmentError(status,code);}; |
| 10 | const text=(x,max=2000)=>typeof x==='string'&&x.trim().length>0&&x.length<=max&&!x.includes('\0'); |
| 11 | const key=x=>typeof x==='string'&&/^[a-zA-Z0-9_-]{1,80}$/.test(x); |
| 12 | function canonical(x){if(Array.isArray(x))return x.map(canonical);if(x&&typeof x==='object')return Object.fromEntries(Object.keys(x).sort().map(k=>[k,canonical(x[k])]));return x;} |
| 13 | const digest=x=>crypto.createHash('sha256').update(JSON.stringify(canonical(x))).digest('hex'); |
| 14 | export const assessmentHash=questions=>digest(questions); |
| 15 | export const assessmentContextHash=row=>digest({bookCode:row.book_code,schoolYear:row.school_year, |
| 16 | bookEvidenceUrl:row.book_evidence_url,unitKey:row.unit_key,titleFa:row.unit_title_fa,unitEvidenceUrl:row.unit_evidence_url}); |
| 17 | const assessmentSelect=`select a.*,t.book_code,t.edition_verification,s.school_year,t.source_evidence_url book_evidence_url, |
| 18 | u.unit_key,u.title_fa unit_title_fa,u.source_evidence_url unit_evidence_url |
| 19 | from learning_assessment a join learning_unit u on u.id=a.unit_id join textbook_catalog t on t.id=u.textbook_id |
| 20 | join curriculum_subject s on s.id=t.curriculum_subject_id`; |
| 21 | |
| 22 | export function validateAssessmentDefinition(questions){ |
| 23 | if(!Array.isArray(questions)||questions.length<1||questions.length>20)fail(400,'invalid_assessment_definition'); |
| 24 | const ids=new Set(); |
| 25 | for(const q of questions){ |
| 26 | if(!q||typeof q!=='object'||!key(q.id)||ids.has(q.id)||!key(q.objectiveId)||!text(q.promptFa)||!text(q.explanationFa)||!text(q.remediationFa)||!Array.isArray(q.choices)||q.choices.length<2||q.choices.length>6)fail(400,'invalid_assessment_definition'); |
| 27 | ids.add(q.id);const choices=new Set(); |
| 28 | for(const c of q.choices){if(!c||!key(c.id)||choices.has(c.id)||!text(c.textFa))fail(400,'invalid_assessment_definition');choices.add(c.id);} |
| 29 | if(!choices.has(q.correctChoiceId))fail(400,'invalid_assessment_definition'); |
| 30 | } |
| 31 | return questions; |
| 32 | } |
| 33 | export function gradeAssessment(questions,answers){ |
| 34 | validateAssessmentDefinition(questions); |
| 35 | if(!Array.isArray(answers)||answers.length!==questions.length)fail(400,'invalid_answers'); |
| 36 | const map=new Map(); |
| 37 | for(const a of answers){if(!a||Object.keys(a).some(k=>!['questionId','choiceId'].includes(k))||!key(a.questionId)||!key(a.choiceId)||map.has(a.questionId))fail(400,'invalid_answers');map.set(a.questionId,a.choiceId);} |
| 38 | const feedback=questions.map(q=>{ |
| 39 | const choice=map.get(q.id); |
| 40 | if(!q.choices.some(c=>c.id===choice))fail(400,'invalid_answers'); |
| 41 | return {questionId:q.id,objectiveId:q.objectiveId,correct:choice===q.correctChoiceId,explanationFa:q.explanationFa,remediationFa:q.remediationFa}; |
| 42 | }); |
| 43 | const correctCount=feedback.filter(f=>f.correct).length; |
| 44 | return {correctCount,total:questions.length,feedback,resultLabel:correctCount===questions.length?'answered_correctly':'needs_practice'}; |
| 45 | } |
| 46 | function reviewed(row){ |
| 47 | try{validateAssessmentDefinition(row.questions);return row.publication_status==='published' |
| 48 | &&row.edition_verification==='verified'&&row.school_year!=='unknown' |
| 49 | &&row.content_hash===assessmentHash(row.questions)&&row.context_hash===assessmentContextHash(row);}catch{return false;} |
| 50 | } |
| 51 | export function createLearningAssessmentRouter({pool,auth}){ |
| 52 | const router=express.Router(),requireAuth=auth??createSessionAuth({pool,jwtSecret:process.env.JWT_SECRET}); |
| 53 | router.get('/education/units/:unitId/assessment',requireAuth,async(req,res)=>{ |
| 54 | if(!validUuid(req.params.unitId))return res.status(400).json({error:'invalid_unit_id'}); |
| 55 | const active=await pool.query('select 1 from learning_unit where id=$1 and active',[req.params.unitId]); |
| 56 | if(!active.rowCount)return res.status(404).json({error:'not_found'}); |
| 57 | const row=(await pool.query(assessmentSelect+" where a.unit_id=$1 and a.publication_status='published' and u.active order by a.version desc,a.created_at desc,a.id limit 1",[req.params.unitId])).rows[0]; |
| 58 | if(!row||!reviewed(row))return res.json({assessment:null,reason:'review_pending'}); |
| 59 | const questions=row.questions.map(q=>({id:q.id,objectiveId:q.objectiveId,promptFa:q.promptFa,choices:q.choices.map(c=>({id:c.id,textFa:c.textFa}))})); |
| 60 | res.json({assessment:{id:row.id,unitId:row.unit_id,version:row.version,questions}}); |
| 61 | }); |
| 62 | router.post('/me/learning-attempts',requireAuth,async(req,res)=>{ |
| 63 | const b=req.body,allowed=['mutationId','assessmentId','assessmentVersion','answers','confidence']; |
| 64 | if(!b||typeof b!=='object'||Array.isArray(b)||Object.keys(b).some(k=>!allowed.includes(k))||!validUuid(b.mutationId)||!validUuid(b.assessmentId)||!Number.isSafeInteger(b.assessmentVersion)||b.assessmentVersion<1||!['unsure','somewhat','confident'].includes(b.confidence)||!Array.isArray(b.answers)||b.answers.length<1||b.answers.length>20)return res.status(400).json({error:'invalid_attempt'}); |
| 65 | const owner=req.identity.sub,requestHash=digest({assessmentId:b.assessmentId,assessmentVersion:b.assessmentVersion,answers:b.answers,confidence:b.confidence}); |
| 66 | const c=await pool.connect();try{ |
| 67 | await c.query('begin');await c.query('select pg_advisory_xact_lock(hashtextextended($1::text,0))',['learning-assessment:'+owner]); |
| 68 | if(!(await c.query('select 1 from app_user where id=$1 and disabled_at is null for share',[owner])).rowCount)fail(401,'unauthorized'); |
| 69 | const prior=(await c.query('select request_hash,acknowledgement from learning_assessment_attempt where owner_user_id=$1 and mutation_id=$2',[owner,b.mutationId])).rows[0]; |
| 70 | if(prior){if(prior.request_hash!==requestHash)fail(409,'mutation_id_reused');await c.query('commit');return res.json(prior.acknowledgement);} |
| 71 | // The runtime role can only read reviewed catalogue tables. This statement |
| 72 | // reads one consistent definition/context; the accepted snapshot is retained |
| 73 | // in the attempt even if a later curator revision withdraws this version. |
| 74 | const a=(await c.query(assessmentSelect+" where a.id=$1 and u.active and a.publication_status='published'",[b.assessmentId])).rows[0]; |
| 75 | if(!a||!reviewed(a))fail(409,'assessment_not_available'); |
| 76 | if(a.version!==b.assessmentVersion)fail(409,'assessment_version_conflict'); |
| 77 | const graded=gradeAssessment(a.questions,b.answers); |
| 78 | const recent=(await c.query("select count(*)::int n from learning_assessment_attempt where owner_user_id=$1 and created_at>now()-interval '1 hour'",[owner])).rows[0].n; |
| 79 | if(recent>=100)fail(429,'assessment_rate_limited'); |
| 80 | const now=(await c.query('select now() at')).rows[0].at; |
| 81 | const id=crypto.randomUUID(),nextReviewAt=new Date(now.getTime()+(graded.correctCount===graded.total?3:1)*86400000).toISOString(); |
| 82 | const ack={mutationId:b.mutationId,attemptId:id,unitId:a.unit_id,assessmentId:a.id,assessmentVersion:a.version,...graded,nextReviewAt,schedulePolicy:'pilot-1-or-3-days',source:'quiz_answers',acceptedAt:now.toISOString()}; |
| 83 | await c.query('insert into learning_assessment_attempt(id,owner_user_id,mutation_id,assessment_id,unit_id,assessment_version,request_hash,answers,confidence,question_snapshot,acknowledgement) values($1,$2,$3,$4,$5,$6,$7,$8::jsonb,$9,$10::jsonb,$11::jsonb)',[id,owner,b.mutationId,a.id,a.unit_id,a.version,requestHash,JSON.stringify(b.answers),b.confidence,JSON.stringify(a.questions),JSON.stringify(ack)]); |
| 84 | await c.query('insert into learning_review_schedule(owner_user_id,unit_id,last_attempt_id,next_review_at) values($1,$2,$3,$4) on conflict(owner_user_id,unit_id) do update set last_attempt_id=excluded.last_attempt_id,next_review_at=excluded.next_review_at',[owner,a.unit_id,id,nextReviewAt]); |
| 85 | await c.query('commit');res.status(201).json(ack); |
| 86 | }catch(e){await c.query('rollback').catch(()=>{});if(e instanceof AssessmentError)return res.status(e.status).json({error:e.code});throw e;}finally{c.release();} |
| 87 | }); |
| 88 | router.get('/me/learning-attempts',requireAuth,async(req,res)=>{ |
| 89 | const unit=req.query.unitId??null; |
| 90 | if(unit!==null&&!validUuid(unit))return res.status(400).json({error:'invalid_unit_id'}); |
| 91 | const r=await pool.query('select acknowledgement,confidence from learning_assessment_attempt where owner_user_id=$1 and ($2::uuid is null or unit_id=$2) order by created_at desc,id desc limit 100',[req.identity.sub,unit]); |
| 92 | res.json({attempts:r.rows.map(row=>({...row.acknowledgement,confidence:row.confidence})),fetchedAt:new Date().toISOString()}); |
| 93 | }); |
| 94 | router.get('/me/learning-reviews',requireAuth,async(req,res)=>{ |
| 95 | const r=await pool.query('select unit_id,next_review_at,schedule_policy from learning_review_schedule where owner_user_id=$1 order by next_review_at,unit_id limit 100',[req.identity.sub]); |
| 96 | res.json({reviews:r.rows.map(row=>({unitId:row.unit_id,nextReviewAt:row.next_review_at,schedulePolicy:row.schedule_policy})),fetchedAt:new Date().toISOString()}); |
| 97 | }); |
| 98 | return router; |
| 99 | } |