LifeMate — Personal, Family & Learning Companion
design/mobile-accessibility-v2
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 | // Operator-only local tooling. This module is never mounted on an HTTP router. |
| 2 | import crypto from 'node:crypto'; |
| 3 | import {assessmentHash,assessmentContextHash,validateAssessmentDefinition} from './learning_assessment.js'; |
| 4 | |
| 5 | const uuid=value=>typeof value==='string'&&/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(value); |
| 6 | const hash=value=>typeof value==='string'&&/^[a-f0-9]{64}$/.test(value); |
| 7 | const exact=(value,fields)=>value&&typeof value==='object'&&!Array.isArray(value)&&Object.keys(value).every(field=>fields.includes(field)); |
| 8 | const text=(value,max=12000)=>typeof value==='string'&&value.trim().length>0&&value.length<=max&&!value.includes('\u0000'); |
| 9 | function canonical(value){if(Array.isArray(value))return value.map(canonical);if(value&&typeof value==='object')return Object.fromEntries(Object.keys(value).sort().map(key=>[key,canonical(value[key])]));return value;} |
| 10 | const digest=value=>crypto.createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex'); |
| 11 | export class ContentPublicationError extends Error {constructor(code){super(code);this.code=code;}} |
| 12 | const fail=code=>{throw new ContentPublicationError(code);}; |
| 13 | |
| 14 | export function localContentReviewConnection(env) { |
| 15 | if(env.CONTENT_REVIEW_SYNTHETIC_ONLY!=='true'||!env.CONTENT_REVIEW_DATABASE_URL) fail('synthetic_configuration_required'); |
| 16 | let url;try{url=new URL(env.CONTENT_REVIEW_DATABASE_URL);}catch{fail('invalid_operator_configuration');} |
| 17 | // pg connection-string query parameters can override host/database/user or |
| 18 | // load TLS files. The checked URL is the only accepted connection source. |
| 19 | if(url.search||url.hash||!['postgres:','postgresql:'].includes(url.protocol)||!['localhost','127.0.0.1','[::1]'].includes(url.hostname)|| |
| 20 | !/^\/(?:lifeguide_[a-z0-9_]*test(?:_[a-z0-9]+)*|lifemate_ci|lifeguide_roles_(?:source|target)_[a-f0-9]{16})$/.test(url.pathname)) fail('local_test_database_required'); |
| 21 | return url.toString(); |
| 22 | } |
| 23 | |
| 24 | const videoReviewFields=['evidenceScope','reviewerName','reviewedAt','bookCode','schoolYear','unitKey','bookEvidenceUrl','unitEvidenceUrl','materialHash', |
| 25 | 'watchedEntireVideo','editionAligned','accuracyApproved','suitabilityApproved','embedRightsApproved','questionCoverageReviewed', |
| 26 | 'alignmentNotes','accuracyNotes','suitabilityNotes','embedRightsEvidence','questionCoverageNotes']; |
| 27 | const assessmentReviewFields=['evidenceScope','reviewerName','reviewedAt','bookCode','schoolYear','unitKey','contentHash','contextHash', |
| 28 | 'accuracyApproved','suitabilityApproved','editionAligned','objectiveCoverageApproved','reviewNotes']; |
| 29 | |
| 30 | export function normalizePublicationOperation(body) { |
| 31 | const assessment=body?.entityType==='assessment',draft=body?.operation==='draft_assessment'; |
| 32 | const fields=['schemaVersion','mutationId','entityType','entityId','operation','expectedStatus','expectedContentHash','expectedContextHash', |
| 33 | ...(assessment?['expectedVersion']:[]),...(draft?['unitId','questions']:[]),...(body?.operation==='publish'?['review']:[])]; |
| 34 | if(!exact(body,fields)||body.schemaVersion!==1||!uuid(body.mutationId)||!uuid(body.entityId)||!['video','assessment'].includes(body.entityType)|| |
| 35 | !['publish','withdraw','draft_assessment'].includes(body.operation)||(!assessment&&draft)|| |
| 36 | !['absent','draft','published','withdrawn'].includes(body.expectedStatus)||!hash(body.expectedContextHash)|| |
| 37 | (body.expectedStatus==='absent'?(!draft||body.expectedContentHash!==null):!hash(body.expectedContentHash))|| |
| 38 | (assessment&&(!Number.isSafeInteger(body.expectedVersion)||body.expectedVersion<0||body.expectedVersion>=2147483647|| |
| 39 | (body.expectedStatus==='absent'?body.expectedVersion!==0:body.expectedVersion===0)))) fail('invalid_publication_operation'); |
| 40 | if(draft) { |
| 41 | if(!uuid(body.unitId)) fail('invalid_publication_operation'); |
| 42 | try { |
| 43 | validateAssessmentDefinition(body.questions); |
| 44 | for(const question of body.questions) { |
| 45 | if(!exact(question,['id','objectiveId','promptFa','choices','correctChoiceId','explanationFa','remediationFa'])|| |
| 46 | question.choices.some(choice=>!exact(choice,['id','textFa']))) fail('invalid_assessment_definition'); |
| 47 | } |
| 48 | } catch { fail('invalid_assessment_definition'); } |
| 49 | } |
| 50 | if(body.operation==='publish'&&!exact(body.review,assessment?assessmentReviewFields:videoReviewFields)) fail('invalid_review_record'); |
| 51 | return canonical({...body,mutationId:body.mutationId.toLowerCase(),entityId:body.entityId.toLowerCase(),...(draft?{unitId:body.unitId.toLowerCase()}:{} )}); |
| 52 | } |
| 53 | |
| 54 | // Same metadata fingerprint as the existing catalogue importer. This is not a |
| 55 | // cryptographic fingerprint of provider-hosted video bytes or proof of viewing. |
| 56 | export function videoMaterialHash(row) { |
| 57 | return crypto.createHash('sha256').update(JSON.stringify({bookKey:row.stable_book_key,bookTitle:row.book_title_fa, |
| 58 | editionVerification:row.edition_verification,bookEvidence:row.book_evidence_url,unitKey:row.unit_key,unitTitle:row.unit_title_fa, |
| 59 | indexKind:row.index_kind,orderIndex:row.order_index,unitEvidence:row.unit_evidence_url,aparatId:row.aparat_id, |
| 60 | canonicalAparatId:row.canonical_aparat_id??null,title:row.title_fa,creatorName:row.creator_name,creatorUrl:row.creator_url, |
| 61 | sourceEvidence:row.source_evidence_url,verification:row.verification_status,durationSeconds:row.duration_seconds, |
| 62 | freeAccess:row.free_access,qualityNotes:row.quality_notes_fa})).digest('hex'); |
| 63 | } |
| 64 | export function videoContextHash(row) { |
| 65 | return digest({bookKey:row.stable_book_key,bookTitle:row.book_title_fa,bookCode:row.book_code,schoolYear:row.school_year, |
| 66 | bookEvidenceUrl:row.book_evidence_url,editionVerification:row.edition_verification,grade:row.national_grade,tracks:row.track_codes, |
| 67 | variant:row.variant,unitKey:row.unit_key,titleFa:row.unit_title_fa,indexKind:row.index_kind,orderIndex:row.order_index, |
| 68 | unitEvidenceUrl:row.unit_evidence_url,active:row.active}); |
| 69 | } |
| 70 | |
| 71 | async function operator(client,env,apply=false) { |
| 72 | const url=new URL(localContentReviewConnection(env)); |
| 73 | const row=(await client.query(`select current_database() database,current_user role, |
| 74 | has_table_privilege(current_user,'learning_video_resource','UPDATE') video_write, |
| 75 | (has_table_privilege(current_user,'learning_assessment','INSERT') and |
| 76 | has_table_privilege(current_user,'learning_assessment','UPDATE')) assessment_write, |
| 77 | has_table_privilege(current_user,'content_publication_audit','INSERT') audit_write`)).rows[0]; |
| 78 | if(row.database!==decodeURIComponent(url.pathname.slice(1))) fail('operator_database_mismatch'); |
| 79 | if(['lifeguide_api','lifeguide_backup'].includes(row.role)||(apply&&(!row.video_write||!row.assessment_write||!row.audit_write))) fail('separate_operator_required'); |
| 80 | return row.role; |
| 81 | } |
| 82 | const contextSelect=`select u.id unit_id,u.unit_key,u.title_fa unit_title_fa,u.order_index,u.index_kind,u.source_evidence_url unit_evidence_url,u.active, |
| 83 | t.id book_id,t.stable_book_key,t.title_fa book_title_fa,t.book_code,t.track_codes,t.variant,t.edition_verification,t.source_evidence_url book_evidence_url, |
| 84 | s.school_year,s.national_grade from learning_unit u join textbook_catalog t on t.id=u.textbook_id join curriculum_subject s on s.id=t.curriculum_subject_id`; |
| 85 | async function load(client,type,id,{apply=false,unitId=null}={}) { |
| 86 | const table=type==='video'?'learning_video_resource':'learning_assessment'; |
| 87 | const raw=(await client.query(`select * from ${table} where id=$1`,[id])).rows[0]; |
| 88 | if(raw&&unitId&&raw.unit_id!==unitId) fail('assessment_unit_immutable'); |
| 89 | const unit=raw?.unit_id??unitId;if(!unit) fail('material_not_found'); |
| 90 | const context=(await client.query(contextSelect+' where u.id=$1'+(apply?' for share of u,t,s':''),[unit])).rows[0]; |
| 91 | if(!context) fail('unit_not_found'); |
| 92 | // The import lock serializes importer and operator; row locks additionally |
| 93 | // serialize direct catalogue corrections against approval snapshots. |
| 94 | const locked=apply?(await client.query(`select * from ${table} where id=$1 for update`,[id])).rows[0]:raw; |
| 95 | if(locked&&locked.unit_id!==unit) fail('assessment_unit_immutable'); |
| 96 | return {...context,...locked,id,exists:Boolean(locked)}; |
| 97 | } |
| 98 | function current(row,type) { |
| 99 | const contentHash=row.exists?(type==='video'?row.material_hash:row.content_hash):null; |
| 100 | const computedContentHash=row.exists?(type==='video'?videoMaterialHash(row):assessmentHash(row.questions)):null; |
| 101 | const contextHash=type==='video'?videoContextHash(row):assessmentContextHash(row); |
| 102 | let eligible=false; |
| 103 | try { if(row.publication_status==='published') { validateReview(row,type,row.review_record,false);eligible=contentHash===computedContentHash&&(type==='video'||row.context_hash===contextHash); } } catch {} |
| 104 | return {entityType:type,entityId:row.id,unitId:row.unit_id,publicationStatus:row.exists?row.publication_status:'absent', |
| 105 | version:type==='assessment'?(row.version??0):null,contentHash,computedContentHash,contextHash, |
| 106 | contextVerified:row.active&&row.edition_verification==='verified'&&row.school_year!=='unknown',eligibleForLearners:eligible}; |
| 107 | } |
| 108 | function reviewTimestamp(value) { |
| 109 | if(typeof value!=='string'||!/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{3})?Z$/.test(value)) return false; |
| 110 | const date=new Date(value);return Number.isFinite(date.getTime())&&date.toISOString().slice(0,19)===value.slice(0,19)&&date.getTime()<=Date.now(); |
| 111 | } |
| 112 | function validateReview(row,type,review,synthetic) { |
| 113 | if(!row.active||row.edition_verification!=='verified'||row.school_year==='unknown') fail('verified_edition_required'); |
| 114 | if(synthetic&&(review?.evidenceScope!=='SYNTHETIC_TEST_ONLY'||!review?.reviewerName?.startsWith('SYNTHETIC'))) fail('synthetic_receipt_required'); |
| 115 | if(!text(review?.reviewerName,240)||!reviewTimestamp(review?.reviewedAt)||review.bookCode!==row.book_code|| |
| 116 | review.schoolYear!==row.school_year||review.unitKey!==row.unit_key) fail('review_context_mismatch'); |
| 117 | if(type==='video') { |
| 118 | const flags=['watchedEntireVideo','editionAligned','accuracyApproved','suitabilityApproved','embedRightsApproved','questionCoverageReviewed']; |
| 119 | const notes=['alignmentNotes','accuracyNotes','suitabilityNotes','embedRightsEvidence','questionCoverageNotes']; |
| 120 | if(flags.some(field=>review[field]!==true)||notes.some(field=>!text(review[field]))||row.free_access!==true|| |
| 121 | !['metadata_verified','embed_verified'].includes(row.verification_status)) fail('incomplete_video_review'); |
| 122 | if(review.materialHash!==row.material_hash||review.bookEvidenceUrl!==row.book_evidence_url||review.unitEvidenceUrl!==row.unit_evidence_url) fail('review_context_mismatch'); |
| 123 | if(videoMaterialHash(row)!==row.material_hash) fail('material_hash_mismatch'); |
| 124 | } else { |
| 125 | if(['accuracyApproved','suitabilityApproved','editionAligned','objectiveCoverageApproved'].some(field=>review[field]!==true)||!text(review.reviewNotes)) fail('incomplete_assessment_review'); |
| 126 | validateAssessmentDefinition(row.questions); |
| 127 | if(review.contentHash!==row.content_hash||review.contextHash!==row.context_hash||row.content_hash!==assessmentHash(row.questions)|| |
| 128 | row.context_hash!==assessmentContextHash(row)) fail('assessment_hash_mismatch'); |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | export async function inspectLearningContent(client,type,id,{env=process.env}={}) { |
| 133 | if(!['video','assessment'].includes(type)||!uuid(id)) fail('invalid_inspection'); |
| 134 | await operator(client,env); |
| 135 | await client.query('begin isolation level repeatable read read only'); |
| 136 | try {const state=current(await load(client,type,id),type);await client.query('rollback');return state;} |
| 137 | catch(error){await client.query('rollback').catch(()=>{});throw error;} |
| 138 | } |
| 139 | |
| 140 | export async function reviewLearningContent(client,raw,{env=process.env,apply=false}={}) { |
| 141 | const body=normalizePublicationOperation(raw),requestHash=digest(body); |
| 142 | const role=await operator(client,env,apply); |
| 143 | await client.query(apply?'begin':'begin isolation level repeatable read read only'); |
| 144 | try { |
| 145 | if(apply) await client.query("select pg_advisory_xact_lock(hashtextextended('learning_catalog_import',0))"); |
| 146 | const previous=(await client.query('select * from content_publication_audit where mutation_id=$1',[body.mutationId])).rows[0]; |
| 147 | if(previous&&previous.request_hash!==requestHash) fail('mutation_id_reused'); |
| 148 | let row=await load(client,body.entityType,body.entityId,{apply,unitId:body.unitId}); |
| 149 | if(apply&&!row.stable_book_key?.startsWith('synthetic-publication:')) fail('synthetic_material_required'); |
| 150 | if(previous) { |
| 151 | const result={mode:apply?'synthetic-apply':'dry-run',current:current(row,body.entityType),acknowledgement:{mutationId:body.mutationId, |
| 152 | entityId:body.entityId,status:'already_applied',appliedStatus:previous.applied_status,appliedVersion:previous.applied_version,acceptedAt:previous.accepted_at}}; |
| 153 | await client.query(apply?'commit':'rollback');return result; |
| 154 | } |
| 155 | const state=current(row,body.entityType); |
| 156 | if(state.publicationStatus!==body.expectedStatus) fail('publication_status_conflict'); |
| 157 | if(state.contentHash!==body.expectedContentHash) fail('content_conflict'); |
| 158 | if(state.contextHash!==body.expectedContextHash) fail('context_conflict'); |
| 159 | if(body.entityType==='assessment'&&state.version!==body.expectedVersion) fail('assessment_version_conflict'); |
| 160 | if(body.operation==='draft_assessment') { |
| 161 | if(row.publication_status==='published') fail('published_definition_immutable'); |
| 162 | if(!row.active) fail('unit_inactive'); |
| 163 | if(row.exists&&assessmentHash(body.questions)===row.content_hash&&assessmentContextHash(row)===row.context_hash) fail('definition_change_not_required'); |
| 164 | } else { |
| 165 | if(!row.exists) fail('material_not_found'); |
| 166 | if(body.operation==='publish') { |
| 167 | if(row.publication_status==='published') fail('publication_change_not_required'); |
| 168 | validateReview(row,body.entityType,body.review,apply); |
| 169 | } |
| 170 | } |
| 171 | const proposedStatus=body.operation==='publish'?'published':body.operation==='withdraw'?'withdrawn':'draft'; |
| 172 | if(!apply) {await client.query('rollback');return {mode:'dry-run',current:state,proposedStatus,proposedVersion:body.operation==='draft_assessment'?body.expectedVersion+1:state.version};} |
| 173 | if(body.operation==='draft_assessment') { |
| 174 | const values=[body.entityId,row.unit_id,body.expectedVersion+1,JSON.stringify(body.questions),assessmentHash(body.questions),assessmentContextHash(row)]; |
| 175 | if(row.exists) await client.query("update learning_assessment set version=$3,questions=$4,content_hash=$5,context_hash=$6,publication_status='draft',review_record=null where id=$1 and unit_id=$2",values); |
| 176 | else await client.query('insert into learning_assessment(id,unit_id,version,questions,content_hash,context_hash) values($1,$2,$3,$4,$5,$6)',values); |
| 177 | } else { |
| 178 | const table=body.entityType==='video'?'learning_video_resource':'learning_assessment'; |
| 179 | if(body.operation==='publish') await client.query(`update ${table} set publication_status='published',review_record=$2${body.entityType==='video'?",pedagogical_review='full_reviewed'":''} where id=$1`,[body.entityId,JSON.stringify(body.review)]); |
| 180 | else await client.query(`update ${table} set publication_status='withdrawn' where id=$1`,[body.entityId]); |
| 181 | } |
| 182 | row=await load(client,body.entityType,body.entityId,{apply}); |
| 183 | const updated=current(row,body.entityType); |
| 184 | const receipt=(await client.query(`insert into content_publication_audit(mutation_id,entity_type,entity_id,operation,request_hash, |
| 185 | applied_content_hash,applied_context_hash,applied_version,applied_status,operator_role) values($1,$2,$3,$4,$5,$6,$7,$8,$9,$10) returning accepted_at`, |
| 186 | [body.mutationId,body.entityType,body.entityId,body.operation,requestHash,updated.contentHash,updated.contextHash,updated.version,updated.publicationStatus,role])).rows[0]; |
| 187 | await client.query('commit');return {mode:'synthetic-apply',current:updated,acknowledgement:{mutationId:body.mutationId,entityId:body.entityId, |
| 188 | status:'accepted',appliedStatus:updated.publicationStatus,appliedVersion:updated.version,acceptedAt:receipt.accepted_at}}; |
| 189 | } catch(error) {await client.query('rollback').catch(()=>{});throw error;} |
| 190 | } |