LifeMate — Personal, Family & Learning Companion
test/personal-notification-settings
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 | |
| 4 | const uuid=value=>typeof value==='string'&&/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(value); |
| 5 | const statuses=new Set(['received','triaged','planned','declined','released']); |
| 6 | const reviewStatuses=new Set(['triaged','planned','declined']); |
| 7 | const transitions={received:new Set(['triaged','declined']),triaged:new Set(['planned','declined']), |
| 8 | planned:new Set(['triaged','declined']),declined:new Set(['triaged'])}; |
| 9 | const exact=(value,keys)=>value&&typeof value==='object'&&!Array.isArray(value)&& |
| 10 | Object.keys(value).every(key=>keys.includes(key)); |
| 11 | const version=value=>Number.isSafeInteger(value)&&value>0&&value<=2147483647; |
| 12 | const error=(status,name)=>({status,body:{error:name}}); |
| 13 | const digest=value=>crypto.createHash('sha256').update(JSON.stringify(value)).digest('hex'); |
| 14 | const feedbackFields=`id,unit_id,category,summary,status,version,created_at,updated_at`; |
| 15 | const visible=`withdrawn_at is null and share_with_content_team=true and summary is not null`; |
| 16 | |
| 17 | export function normalizeReviewMutation(body) { |
| 18 | if(!exact(body,['mutationId','expectedVersion','status'])||!uuid(body.mutationId)|| |
| 19 | !version(body.expectedVersion)||!reviewStatuses.has(body.status)) return null; |
| 20 | return {mutationId:body.mutationId.toLowerCase(),expectedVersion:body.expectedVersion,status:body.status}; |
| 21 | } |
| 22 | export function normalizeBriefRequest(body) { |
| 23 | if(!exact(body,['mutationId','feedback'])||!uuid(body.mutationId)||!Array.isArray(body.feedback)|| |
| 24 | body.feedback.length<1||body.feedback.length>20||body.feedback.some(source=> |
| 25 | !exact(source,['id','expectedVersion'])||!uuid(source.id)||!version(source.expectedVersion))) return null; |
| 26 | const feedback=body.feedback.map(source=>({id:source.id.toLowerCase(),expectedVersion:source.expectedVersion})); |
| 27 | if(new Set(feedback.map(source=>source.id)).size!==feedback.length) return null; |
| 28 | feedback.sort((a,b)=>a.id.localeCompare(b.id)); |
| 29 | return {mutationId:body.mutationId.toLowerCase(),feedback}; |
| 30 | } |
| 31 | |
| 32 | function feedbackBody(row) { |
| 33 | return {id:row.id,unitId:row.unit_id,category:row.category,summary:row.summary,status:row.status, |
| 34 | version:row.version,createdAt:row.created_at,updatedAt:row.updated_at}; |
| 35 | } |
| 36 | async function transaction(pool,operation,authorization) { |
| 37 | const client=await pool.connect(); |
| 38 | try { |
| 39 | await client.query('begin'); |
| 40 | const result=await operation(client); |
| 41 | // A capability/session may expire while waiting for a source row lock. |
| 42 | // Refuse the response and rollback writes if it is no longer current. |
| 43 | if(authorization) { |
| 44 | const current=await permissions(client,authorization.identity,authorization.required); |
| 45 | if(current.status) { await client.query('rollback'); return current; } |
| 46 | if(Array.isArray(result.body?.permissions)) result.body.permissions=current.permissions; |
| 47 | } |
| 48 | await client.query('commit'); |
| 49 | return result; |
| 50 | } catch(exception) { await client.query('rollback').catch(()=>{}); throw exception; } |
| 51 | finally { client.release(); } |
| 52 | } |
| 53 | function send(res,result) { res.status(result.status).json(result.body); } |
| 54 | |
| 55 | async function permissions(client,identity,required=[]) { |
| 56 | if(identity.exp!=null&&identity.exp*1000<=Date.now()) return error(401,'session_invalid'); |
| 57 | // The offline operator uses this same account lock before grant/revoke. Runtime |
| 58 | // needs SELECT only on capability tables; no role claims or parent shortcuts. |
| 59 | const user=await client.query('select id from app_user where id=$1 and disabled_at is null for update',[identity.sub]); |
| 60 | const session=await client.query(`select 1 from auth_session where id=$1 and user_id=$2 |
| 61 | and revoked_at is null and expires_at>statement_timestamp() for share`,[identity.sid,identity.sub]); |
| 62 | if(!user.rowCount||!session.rowCount) return error(401,'session_invalid'); |
| 63 | const rows=await client.query(`select permission from content_capability_grant where user_id=$1 |
| 64 | and revoked_at is null and expires_at>statement_timestamp() order by permission`,[identity.sub]); |
| 65 | const allowed=rows.rows.map(row=>row.permission); |
| 66 | if(required.some(permission=>!allowed.includes(permission))) return error(403,'content_permission_required'); |
| 67 | return {permissions:allowed}; |
| 68 | } |
| 69 | async function mutation(client,actor,id) { |
| 70 | return (await client.query(`select operation,request_hash,feedback_id,brief_id |
| 71 | from content_review_mutation where actor_user_id=$1 and mutation_id=$2`,[actor,id])).rows[0]; |
| 72 | } |
| 73 | async function lockFeedback(client,id) { |
| 74 | return (await client.query(`select ${feedbackFields} from learning_content_feedback |
| 75 | where id=$1 and ${visible} for update`,[id])).rows[0]; |
| 76 | } |
| 77 | |
| 78 | const tasks=Object.freeze([ |
| 79 | 'نسخه رسمی کتاب و هدف یادگیری این درس را بررسی کنید.', |
| 80 | 'محتوای پیشنهادی و سؤالهای تمرینی را بهطور کامل بازبینی کنید.', |
| 81 | 'برای تغییر پیشنهادی معیار پذیرش، آزمون و PR مستقل تهیه کنید.', |
| 82 | 'انتشار محتوا و استقرار فقط پس از بازبینی و مجوز جداگانه انجام شود.' |
| 83 | ]); |
| 84 | async function briefBody(client,id) { |
| 85 | const brief=(await client.query('select id,created_at,source_count from content_review_brief where id=$1',[id])).rows[0]; |
| 86 | if(!brief) return error(404,'brief_not_found'); |
| 87 | // Sorted row locks share the same serialization boundary as owner withdrawal |
| 88 | // and review updates. No summaries are stored/copied in this brief. |
| 89 | const sources=(await client.query(`select f.id,f.version,f.status,f.withdrawn_at, |
| 90 | f.share_with_content_team,f.category,f.unit_id,s.feedback_version |
| 91 | from content_review_brief_source s join learning_content_feedback f on f.id=s.feedback_id |
| 92 | where s.brief_id=$1 order by f.id for update of f`,[id])).rows; |
| 93 | if(sources.length!==brief.source_count||sources.some(source=>source.withdrawn_at||!source.share_with_content_team|| |
| 94 | source.status!=='planned'||source.version!==source.feedback_version)) return error(409,'brief_invalidated'); |
| 95 | const categories=new Map(); |
| 96 | for(const source of sources) categories.set(source.category,(categories.get(source.category)??0)+1); |
| 97 | const unitIds=[...new Set(sources.map(source=>source.unit_id).filter(Boolean))]; |
| 98 | const units=(await client.query(`select u.id,u.title_fa,t.book_code,t.title_fa book_title, |
| 99 | t.track_codes,t.edition_verification,s.school_year,s.national_grade |
| 100 | from learning_unit u join textbook_catalog t on t.id=u.textbook_id |
| 101 | join curriculum_subject s on s.id=t.curriculum_subject_id where u.id=any($1::uuid[]) order by u.id`,[unitIds])).rows; |
| 102 | return {status:200,body:{brief:{id:brief.id,title:'پیشنهاد بررسی و توسعه محتوای آموزشی',createdAt:brief.created_at, |
| 103 | sourceCount:sources.length,categories:[...categories].sort(([a],[b])=>a.localeCompare(b)).map(([category,count])=>({category,count})), |
| 104 | units:units.map(unit=>({id:unit.id,title:unit.title_fa,bookCode:unit.book_code,bookTitle:unit.book_title, |
| 105 | gradeLevel:unit.national_grade,trackCode:unit.track_codes,editionYear:unit.school_year==='unknown'?null:unit.school_year, |
| 106 | editionStatus:unit.edition_verification})),tasks:[...tasks], |
| 107 | notice:'این پیشنهاد ساختاری فاقد متن بازخورد و اطلاعات خصوصی است؛ تأیید محتوا یا دستور انتشار نیست.'}}}; |
| 108 | } |
| 109 | |
| 110 | export function createContentReviewRouter({pool,auth}) { |
| 111 | const router=express.Router(); |
| 112 | router.get('/me/content-capabilities',auth,async(req,res)=>{ |
| 113 | if(Object.keys(req.query).length) return send(res,error(400,'invalid_content_query')); |
| 114 | send(res,await transaction(pool,async client=>{ |
| 115 | const grant=await permissions(client,req.identity); |
| 116 | return grant.status?grant:{status:200,body:grant}; |
| 117 | },{identity:req.identity,required:[]})); |
| 118 | }); |
| 119 | router.get('/content-review/feedback',auth,async(req,res)=>{ |
| 120 | const cursor=req.query.cursor??null,status=req.query.status??null; |
| 121 | const limit=req.query.limit===undefined?50:Number(req.query.limit); |
| 122 | if(Object.keys(req.query).some(key=>!['cursor','status','limit'].includes(key))|| |
| 123 | (cursor!==null&&!uuid(cursor))||(status!==null&&!statuses.has(status))|| |
| 124 | (req.query.limit!==undefined&&(typeof req.query.limit!=='string'||!/^\d+$/.test(req.query.limit)))|| |
| 125 | !Number.isInteger(limit)||limit<1||limit>100) return send(res,error(400,'invalid_content_query')); |
| 126 | send(res,await transaction(pool,async client=>{ |
| 127 | const grant=await permissions(client,req.identity,['feedback.read']); if(grant.status) return grant; |
| 128 | // Lock the consenting set once. Paging and count derive from the same |
| 129 | // statement snapshot; microseconds remain in PostgreSQL cursor comparisons. |
| 130 | const result=await client.query(`with consenting as materialized ( |
| 131 | select ${feedbackFields} from learning_content_feedback where ${visible} |
| 132 | and ($2::text is null or status=$2) order by id for share |
| 133 | ), page as ( |
| 134 | select * from consenting where $1::uuid is null or (created_at,id)< |
| 135 | (select created_at,id from consenting where id=$1) |
| 136 | order by created_at desc,id desc limit $3 |
| 137 | ) select (select count(*)::int from consenting) total, |
| 138 | exists(select 1 from consenting where id=$1) cursor_exists, |
| 139 | coalesce((select jsonb_agg(to_jsonb(page) order by created_at desc,id desc) from page),'[]'::jsonb) rows`, |
| 140 | [cursor,status,limit+1]); |
| 141 | const row=result.rows[0]; |
| 142 | if(cursor&&!row.cursor_exists) return error(404,'feedback_not_found'); |
| 143 | return {status:200,body:{feedback:row.rows.slice(0,limit).map(feedbackBody), |
| 144 | nextCursor:row.rows.length>limit?row.rows[limit-1].id:null,total:row.total}}; |
| 145 | },{identity:req.identity,required:['feedback.read']})); |
| 146 | }); |
| 147 | router.patch('/content-review/feedback/:id',auth,async(req,res)=>{ |
| 148 | const body=normalizeReviewMutation(req.body); |
| 149 | if(!uuid(req.params.id)||!body||Object.keys(req.query).length) return send(res,error(400,'invalid_review_mutation')); |
| 150 | const hash=digest({feedbackId:req.params.id.toLowerCase(),...body}); |
| 151 | send(res,await transaction(pool,async client=>{ |
| 152 | const grant=await permissions(client,req.identity,['feedback.read','feedback.review']); if(grant.status) return grant; |
| 153 | const previous=await mutation(client,req.identity.sub,body.mutationId); |
| 154 | if(previous&&(previous.operation!=='review'||previous.request_hash!==hash)) return error(409,'mutation_id_reused'); |
| 155 | const row=await lockFeedback(client,req.params.id); if(!row) return error(404,'feedback_not_found'); |
| 156 | if(previous) return {status:200,body:{feedback:feedbackBody(row),acknowledgement:{mutationId:body.mutationId, |
| 157 | feedbackId:row.id,status:'already_applied'}}}; |
| 158 | if(row.version!==body.expectedVersion) return error(409,'feedback_version_conflict'); |
| 159 | if(!transitions[row.status]?.has(body.status)) return error(409,'feedback_transition_invalid'); |
| 160 | const updated=(await client.query(`update learning_content_feedback set status=$2,version=version+1, |
| 161 | updated_at=statement_timestamp() where id=$1 returning ${feedbackFields}`,[row.id,body.status])).rows[0]; |
| 162 | await client.query(`insert into content_review_audit(actor_user_id,feedback_id,before_status,after_status,before_version,after_version) |
| 163 | values($1,$2,$3,$4,$5,$6)`,[req.identity.sub,row.id,row.status,updated.status,row.version,updated.version]); |
| 164 | await client.query(`insert into content_review_mutation(actor_user_id,mutation_id,operation,request_hash,feedback_id) |
| 165 | values($1,$2,'review',$3,$4)`,[req.identity.sub,body.mutationId,hash,row.id]); |
| 166 | return {status:200,body:{feedback:feedbackBody(updated),acknowledgement:{mutationId:body.mutationId, |
| 167 | feedbackId:row.id,status:'accepted'}}}; |
| 168 | },{identity:req.identity,required:['feedback.read','feedback.review']})); |
| 169 | }); |
| 170 | router.post('/content-review/briefs',auth,async(req,res)=>{ |
| 171 | const body=normalizeBriefRequest(req.body); |
| 172 | if(!body||Object.keys(req.query).length) return send(res,error(400,'invalid_brief_request')); |
| 173 | const hash=digest(body); |
| 174 | send(res,await transaction(pool,async client=>{ |
| 175 | const grant=await permissions(client,req.identity,['feedback.read','brief.prepare']); if(grant.status) return grant; |
| 176 | const previous=await mutation(client,req.identity.sub,body.mutationId); |
| 177 | if(previous&&(previous.operation!=='brief'||previous.request_hash!==hash)) return error(409,'mutation_id_reused'); |
| 178 | if(previous) { |
| 179 | const existing=await briefBody(client,previous.brief_id); |
| 180 | if(existing.status!==200) return existing; |
| 181 | existing.body.acknowledgement={mutationId:body.mutationId,briefId:previous.brief_id,status:'already_applied'}; |
| 182 | return existing; |
| 183 | } |
| 184 | for(const source of body.feedback) { |
| 185 | const row=await lockFeedback(client,source.id); if(!row) return error(404,'feedback_not_found'); |
| 186 | if(row.status!=='planned'||row.version!==source.expectedVersion) return error(409,'brief_source_conflict'); |
| 187 | } |
| 188 | const brief=(await client.query('insert into content_review_brief(actor_user_id,source_count) values($1,$2) returning id', |
| 189 | [req.identity.sub,body.feedback.length])).rows[0]; |
| 190 | for(const source of body.feedback) await client.query(`insert into content_review_brief_source(brief_id,feedback_id,feedback_version) |
| 191 | values($1,$2,$3)`,[brief.id,source.id,source.expectedVersion]); |
| 192 | await client.query(`insert into content_review_mutation(actor_user_id,mutation_id,operation,request_hash,brief_id) |
| 193 | values($1,$2,'brief',$3,$4)`,[req.identity.sub,body.mutationId,hash,brief.id]); |
| 194 | const result=await briefBody(client,brief.id); |
| 195 | result.status=201; |
| 196 | result.body.acknowledgement={mutationId:body.mutationId,briefId:brief.id,status:'accepted'}; |
| 197 | return result; |
| 198 | },{identity:req.identity,required:['feedback.read','brief.prepare']})); |
| 199 | }); |
| 200 | router.get('/content-review/briefs/:id',auth,async(req,res)=>{ |
| 201 | if(!uuid(req.params.id)||Object.keys(req.query).length) return send(res,error(400,'invalid_brief_query')); |
| 202 | send(res,await transaction(pool,async client=>{ |
| 203 | const grant=await permissions(client,req.identity,['feedback.read','brief.prepare']); if(grant.status) return grant; |
| 204 | return briefBody(client,req.params.id); |
| 205 | },{identity:req.identity,required:['feedback.read','brief.prepare']})); |
| 206 | }); |
| 207 | return router; |
| 208 | } |