LifeMate — Personal, Family & Learning Companion
test/android-reminder-acceptance
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'&&/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(value); |
| 5 | const version=value=>Number.isInteger(value)&&value>0&&value<2147483647; |
| 6 | const roles=new Set(['parent_guardian','teen_minor','adult_member']); |
| 7 | const exact=(body,fields)=>body&&typeof body==='object'&&!Array.isArray(body)&&Object.keys(body).every(key=>fields.includes(key)); |
| 8 | const error=(status,name)=>({status,body:{error:name}}); |
| 9 | const hash=body=>crypto.createHash('sha256').update(JSON.stringify(body)).digest('hex'); |
| 10 | const memberColumns='m.user_id,m.role,m.is_admin,m.version,m.updated_at,m.ended_at'; |
| 11 | const send=(res,result)=>res.status(result.status).json(result.body); |
| 12 | |
| 13 | export function normalizeRoleMutation(body){ |
| 14 | if(!exact(body,['mutationId','expectedVersion','role'])||!uuid(body.mutationId)||!version(body.expectedVersion)||!roles.has(body.role))return null; |
| 15 | return {mutationId:body.mutationId.toLowerCase(),expectedVersion:body.expectedVersion,role:body.role}; |
| 16 | } |
| 17 | export function normalizeAdminTransfer(body){ |
| 18 | if(!exact(body,['mutationId','targetUserId','expectedVersion','expectedActorVersion'])||!uuid(body.mutationId)||!uuid(body.targetUserId)|| |
| 19 | !version(body.expectedVersion)||!version(body.expectedActorVersion))return null; |
| 20 | return {mutationId:body.mutationId.toLowerCase(),targetUserId:body.targetUserId.toLowerCase(), |
| 21 | expectedVersion:body.expectedVersion,expectedActorVersion:body.expectedActorVersion}; |
| 22 | } |
| 23 | export function normalizeInvitationRevoke(body){ |
| 24 | if(!exact(body,['mutationId','expectedVersion','action'])||!uuid(body.mutationId)||!version(body.expectedVersion)||body.action!=='revoke')return null; |
| 25 | return {mutationId:body.mutationId.toLowerCase(),expectedVersion:body.expectedVersion,action:'revoke'}; |
| 26 | } |
| 27 | const memberBody=row=>({userId:row.user_id,role:row.role,isAdmin:row.is_admin,version:row.version,updatedAt:row.updated_at,endedAt:row.ended_at}); |
| 28 | const invitationBody=row=>({id:row.id,status:row.status,version:row.version,createdAt:row.created_at,expiresAt:row.expires_at}); |
| 29 | function hint(row){return row.invited_phone_normalized?`***${row.invited_phone_normalized.slice(-4)}`: |
| 30 | row.invited_email_normalized?`***@${row.invited_email_normalized.split('@').at(-1)}`:null;} |
| 31 | |
| 32 | async function sessionCurrent(client,identity,{lock=false}={}){ |
| 33 | // Logout does not lock app_user. Hold the session row only at the final gate, |
| 34 | // then check fresh statement time after any session-row lock wait as well. |
| 35 | if(lock)await client.query('select id from auth_session where id=$1 and user_id=$2 for share',[identity.sid,identity.sub]); |
| 36 | return (await client.query(`select 1 from app_user u join auth_session s on s.user_id=u.id |
| 37 | where u.id=$1 and u.disabled_at is null and s.id=$2 and s.revoked_at is null |
| 38 | and s.expires_at>statement_timestamp() |
| 39 | and ($3::double precision is null or to_timestamp($3)>statement_timestamp())`,[identity.sub,identity.sid,identity.exp??null])).rowCount>0; |
| 40 | } |
| 41 | async function transaction(pool,identity,operation){ |
| 42 | const client=await pool.connect(); |
| 43 | try{ |
| 44 | await client.query('begin');const result=await operation(client); |
| 45 | if(!await sessionCurrent(client,identity,{lock:true})){await client.query('rollback');return error(401,'session_invalid');} |
| 46 | await client.query('commit');return result; |
| 47 | }catch(exception){await client.query('rollback').catch(()=>{});throw exception;} |
| 48 | finally{client.release();} |
| 49 | } |
| 50 | async function familyMember(client,familyId,identity,targetId=null){ |
| 51 | const family=await client.query('select id from family_workspace where id=$1 and archived_at is null for update',[familyId]); |
| 52 | if(!family.rowCount)return error(403,'forbidden'); |
| 53 | const participants=[...new Set([identity.sub,...(targetId?[targetId]:[])])].sort(); |
| 54 | // Multiple families may share these accounts. Lock all participating users in |
| 55 | // UUID order before individual memberships, rather than actor then target. |
| 56 | await client.query('select id from app_user where id=any($1::uuid[]) order by id for update',[participants]); |
| 57 | // Birth dates are editable independently of the account row. Freeze the age |
| 58 | // context until this explicit family change commits. |
| 59 | await client.query('select user_id from profile where user_id=any($1::uuid[]) order by user_id for update',[participants]); |
| 60 | await client.query('select user_id from family_membership where family_id=$1 and user_id=any($2::uuid[]) order by user_id for update',[familyId,participants]); |
| 61 | const member=(await client.query(`select ${memberColumns} from family_membership m join app_user u on u.id=m.user_id |
| 62 | where m.family_id=$1 and m.user_id=$2 and m.ended_at is null and u.disabled_at is null`,[familyId,identity.sub])).rows[0]; |
| 63 | if(!member)return error(403,'forbidden'); |
| 64 | if(!await sessionCurrent(client,identity))return error(401,'session_invalid'); |
| 65 | return member; |
| 66 | } |
| 67 | const admin=member=>member.is_admin&&member.role!=='teen_minor'; |
| 68 | async function targetMember(client,familyId,id){ |
| 69 | return (await client.query(`select ${memberColumns},u.disabled_at,p.birth_date, |
| 70 | (p.birth_date is not null and p.birth_date>(current_date-interval '18 years')::date) known_minor |
| 71 | from family_membership m join app_user u on u.id=m.user_id left join profile p on p.user_id=m.user_id |
| 72 | where m.family_id=$1 and m.user_id=$2`,[familyId,id])).rows[0]; |
| 73 | } |
| 74 | async function receipt(client,identity,mutationId){ |
| 75 | return (await client.query('select * from family_lifecycle_mutation where actor_user_id=$1 and mutation_id=$2',[identity.sub,mutationId])).rows[0]; |
| 76 | } |
| 77 | async function saveReceipt(client,identity,body,familyId,operation,targetId,digest){ |
| 78 | await client.query(`insert into family_lifecycle_mutation(actor_user_id,mutation_id,family_id,operation,target_id,request_hash) |
| 79 | values($1,$2,$3,$4,$5,$6)`,[identity.sub,body.mutationId,familyId,operation,targetId,digest]); |
| 80 | } |
| 81 | function acknowledgement(body,familyId,targetId,operation,applied){return {mutationId:body.mutationId,familyId,targetId,operation, |
| 82 | status:applied?'already_applied':'accepted'};} |
| 83 | async function audit(client,identity,familyId,operation,targetId){ |
| 84 | await client.query(`insert into access_audit(actor_user_id,family_id,action,target_type,target_id) |
| 85 | values($1,$2,$3,$4,$5)`,[identity.sub,familyId,`family.lifecycle.${operation}`, |
| 86 | operation==='invitation_revoke'?'invitation':'membership',targetId]); |
| 87 | } |
| 88 | async function invalidateRoleSharing(client,familyId,targetId){ |
| 89 | await client.query(`update guardian_relationship g set active=false |
| 90 | where g.family_id=$1 and g.active and (g.guardian_user_id=$2 or g.minor_user_id=$2) |
| 91 | and not exists(select 1 from family_membership gm join family_membership mm on mm.family_id=gm.family_id |
| 92 | where gm.family_id=g.family_id and gm.user_id=g.guardian_user_id and gm.ended_at is null and gm.role='parent_guardian' |
| 93 | and mm.user_id=g.minor_user_id and mm.ended_at is null and mm.role='teen_minor')`,[familyId,targetId]); |
| 94 | // A role change is a new sharing context. Explicit selections must be chosen |
| 95 | // again; reversing a role never silently restores previous selections. |
| 96 | await client.query(`delete from sharing_grant sg using plan_item p where sg.resource_type='plan_item' |
| 97 | and sg.resource_id=p.id and p.family_id=$1 and (p.owner_user_id=$2 or sg.grantee_user_id=$2)`,[familyId,targetId]); |
| 98 | } |
| 99 | |
| 100 | export function createFamilyLifecycleRouter({pool,auth}){ |
| 101 | const router=express.Router(); |
| 102 | router.get('/families/:familyId/invitations',auth,async(req,res)=>{ |
| 103 | const cursor=req.query.cursor??null,limit=req.query.limit===undefined?100:Number(req.query.limit); |
| 104 | if(!uuid(req.params.familyId)||Object.keys(req.query).some(key=>!['limit','cursor'].includes(key))|| |
| 105 | (cursor!==null&&!uuid(cursor))||!Number.isInteger(limit)||limit<1||limit>100|| |
| 106 | (req.query.limit!==undefined&&(typeof req.query.limit!=='string'||!/^\d+$/.test(req.query.limit))))return send(res,error(400,'invalid_invitation_query')); |
| 107 | send(res,await transaction(pool,req.identity,async client=>{ |
| 108 | const actor=await familyMember(client,req.params.familyId,req.identity);if(actor.status)return actor; |
| 109 | if(!admin(actor))return error(403,'forbidden'); |
| 110 | const result=(await client.query(`with pending as materialized ( |
| 111 | select id,intended_role,case when expires_at<=statement_timestamp() then 'expired' else 'pending' end status, |
| 112 | invited_email_normalized,invited_phone_normalized,version,created_at,expires_at |
| 113 | from family_invitation where family_id=$1 and status='pending' |
| 114 | ),page as (select * from pending where $2::uuid is null or (created_at,id)<(select created_at,id from pending where id=$2) |
| 115 | order by created_at desc,id desc limit $3) |
| 116 | select (select count(*)::int from pending) total,exists(select 1 from pending where id=$2) cursor_exists, |
| 117 | coalesce((select jsonb_agg(to_jsonb(page) order by created_at desc,id desc) from page),'[]'::jsonb) rows`, |
| 118 | [req.params.familyId,cursor,limit+1])).rows[0]; |
| 119 | if(cursor&&!result.cursor_exists)return error(404,'invitation_not_found'); |
| 120 | return {status:200,body:{invitations:result.rows.slice(0,limit).map(row=>({...invitationBody(row), |
| 121 | intendedRole:row.intended_role,recipientHint:hint(row)})),nextCursor:result.rows.length>limit?result.rows[limit-1].id:null,total:result.total}}; |
| 122 | })); |
| 123 | }); |
| 124 | router.patch('/families/:familyId/invitations/:id',auth,async(req,res)=>{ |
| 125 | const body=normalizeInvitationRevoke(req.body),familyId=req.params.familyId,id=req.params.id; |
| 126 | if(!uuid(familyId)||!uuid(id)||!body||Object.keys(req.query).length)return send(res,error(400,'invalid_invitation_mutation')); |
| 127 | const digest=hash({familyId:familyId.toLowerCase(),id:id.toLowerCase(),operation:'invitation_revoke',...body}); |
| 128 | send(res,await transaction(pool,req.identity,async client=>{ |
| 129 | const actor=await familyMember(client,familyId,req.identity);if(actor.status)return actor; |
| 130 | const previous=await receipt(client,req.identity,body.mutationId); |
| 131 | if(previous&&previous.request_hash!==digest)return error(409,'mutation_id_reused'); |
| 132 | if(!previous&&!admin(actor))return error(403,'forbidden'); |
| 133 | const row=(await client.query('select id,status,version,created_at,expires_at from family_invitation where family_id=$1 and id=$2 for update',[familyId,id])).rows[0]; |
| 134 | if(!row)return error(404,'invitation_not_found'); |
| 135 | if(previous)return {status:200,body:{invitation:invitationBody(row),acknowledgement:acknowledgement(body,familyId,id,'invitation_revoke',true)}}; |
| 136 | if(row.version!==body.expectedVersion)return error(409,'invitation_version_conflict'); |
| 137 | if(row.status!=='pending')return error(409,'invitation_not_pending'); |
| 138 | const updated=(await client.query("update family_invitation set status='revoked' where id=$1 returning id,status,version,created_at,expires_at",[id])).rows[0]; |
| 139 | await saveReceipt(client,req.identity,body,familyId,'invitation_revoke',id,digest);await audit(client,req.identity,familyId,'invitation_revoke',id); |
| 140 | return {status:200,body:{invitation:invitationBody(updated),acknowledgement:acknowledgement(body,familyId,id,'invitation_revoke',false)}}; |
| 141 | })); |
| 142 | }); |
| 143 | router.patch('/families/:familyId/members/:userId/role',auth,async(req,res)=>{ |
| 144 | const body=normalizeRoleMutation(req.body),familyId=req.params.familyId,id=req.params.userId; |
| 145 | if(!uuid(familyId)||!uuid(id)||!body||Object.keys(req.query).length)return send(res,error(400,'invalid_membership_mutation')); |
| 146 | const digest=hash({familyId:familyId.toLowerCase(),id:id.toLowerCase(),operation:'role',...body}); |
| 147 | send(res,await transaction(pool,req.identity,async client=>{ |
| 148 | const actor=await familyMember(client,familyId,req.identity,id);if(actor.status)return actor; |
| 149 | const previous=await receipt(client,req.identity,body.mutationId); |
| 150 | if(previous&&previous.request_hash!==digest)return error(409,'mutation_id_reused'); |
| 151 | if(!previous&&!admin(actor))return error(403,'forbidden'); |
| 152 | const target=await targetMember(client,familyId,id);if(!target)return error(404,'membership_not_found'); |
| 153 | if((await client.query('select 1 from managed_child where user_id=$1',[id])).rowCount)return error(403,'managed_child_membership_locked'); |
| 154 | if(previous)return {status:200,body:{members:[memberBody(target)],acknowledgement:acknowledgement(body,familyId,id,'role',true)}}; |
| 155 | if(target.ended_at||target.disabled_at)return error(409,'member_not_active'); |
| 156 | if(target.version!==body.expectedVersion)return error(409,'membership_version_conflict'); |
| 157 | if(target.role===body.role)return error(409,'membership_change_not_required'); |
| 158 | if(body.role==='teen_minor'&&target.is_admin)return error(409,'minor_cannot_admin'); |
| 159 | if(body.role!=='teen_minor'&&target.known_minor)return error(409,'minor_role_upgrade_forbidden'); |
| 160 | if(target.role==='teen_minor'&&body.role!=='teen_minor'&&!target.birth_date)return error(409,'age_confirmation_required'); |
| 161 | const updated=(await client.query(`update family_membership m set role=$3 |
| 162 | where family_id=$1 and user_id=$2 returning ${memberColumns}`,[familyId,id,body.role])).rows[0]; |
| 163 | await invalidateRoleSharing(client,familyId,id); |
| 164 | await saveReceipt(client,req.identity,body,familyId,'role',id,digest);await audit(client,req.identity,familyId,'role',id); |
| 165 | return {status:200,body:{members:[memberBody(updated)],acknowledgement:acknowledgement(body,familyId,id,'role',false)}}; |
| 166 | })); |
| 167 | }); |
| 168 | router.post('/families/:familyId/admin-transfer',auth,async(req,res)=>{ |
| 169 | const body=normalizeAdminTransfer(req.body),familyId=req.params.familyId; |
| 170 | if(!uuid(familyId)||!body||Object.keys(req.query).length)return send(res,error(400,'invalid_admin_transfer')); |
| 171 | const digest=hash({familyId:familyId.toLowerCase(),operation:'admin_transfer',...body}); |
| 172 | send(res,await transaction(pool,req.identity,async client=>{ |
| 173 | const actor=await familyMember(client,familyId,req.identity,body.targetUserId);if(actor.status)return actor; |
| 174 | const previous=await receipt(client,req.identity,body.mutationId); |
| 175 | if(previous&&previous.request_hash!==digest)return error(409,'mutation_id_reused'); |
| 176 | if(!previous&&!admin(actor))return error(403,'forbidden'); |
| 177 | const target=await targetMember(client,familyId,body.targetUserId);if(!target)return error(404,'membership_not_found'); |
| 178 | if((await client.query('select 1 from managed_child where user_id=$1',[body.targetUserId])).rowCount)return error(403,'managed_child_membership_locked'); |
| 179 | if(previous)return {status:200,body:{members:[memberBody(actor),memberBody(target)], |
| 180 | acknowledgement:acknowledgement(body,familyId,body.targetUserId,'admin_transfer',true)}}; |
| 181 | if(target.user_id===actor.user_id)return error(409,'admin_target_invalid'); |
| 182 | if(target.ended_at||target.disabled_at)return error(409,'member_not_active'); |
| 183 | if(target.role==='teen_minor'||target.known_minor)return error(409,'minor_cannot_admin'); |
| 184 | if(actor.version!==body.expectedActorVersion||target.version!==body.expectedVersion)return error(409,'membership_version_conflict'); |
| 185 | if(target.is_admin)return error(409,'admin_target_already_admin'); |
| 186 | const promoted=(await client.query(`update family_membership m set is_admin=true where family_id=$1 and user_id=$2 returning ${memberColumns}`, |
| 187 | [familyId,body.targetUserId])).rows[0]; |
| 188 | const demoted=(await client.query(`update family_membership m set is_admin=false where family_id=$1 and user_id=$2 returning ${memberColumns}`, |
| 189 | [familyId,req.identity.sub])).rows[0]; |
| 190 | // Existing invitations require a currently active inviter-admin. Revoke |
| 191 | // them on transfer; transferring back never revives an old bearer token. |
| 192 | await client.query("update family_invitation set status='revoked' where family_id=$1 and invited_by=$2 and status='pending'",[familyId,req.identity.sub]); |
| 193 | await saveReceipt(client,req.identity,body,familyId,'admin_transfer',body.targetUserId,digest);await audit(client,req.identity,familyId,'admin_transfer',body.targetUserId); |
| 194 | return {status:200,body:{members:[memberBody(demoted),memberBody(promoted)], |
| 195 | acknowledgement:acknowledgement(body,familyId,body.targetUserId,'admin_transfer',false)}}; |
| 196 | })); |
| 197 | }); |
| 198 | return router; |
| 199 | } |