LifeMate — Personal, Family & Learning Companion

infra/lifeguide-supabase-qa
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
js 143 lines 12.1 KB
Raw
1 import crypto from 'node:crypto';
2 import express from 'express';
3
4 const UUID = /^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i;
5 const TYPES = { contexts: 'life_context', years: 'academic_year', terms: 'academic_term' };
6 class InputError extends Error { constructor(status, code) { super(code); this.status = status; this.code = code; } }
7 const fail = (status, code) => { throw new InputError(status, code); };
8 const owns = (raw, key) => Object.hasOwn(raw, key);
9 const uuid = (raw) => { if (typeof raw !== 'string' || !UUID.test(raw)) fail(400, 'invalid_school_id'); return raw.toLowerCase(); };
10 const title = (raw) => { if (typeof raw !== 'string' || !raw.trim() || raw.trim().length > 120) fail(400, 'invalid_school_title'); return raw.trim(); };
11 function date(raw) {
12 if (typeof raw !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(raw) || raw.startsWith('0000-')) fail(400, 'invalid_school_date');
13 const parsed = new Date(`${raw}T00:00:00Z`);
14 if (!Number.isFinite(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== raw) fail(400, 'invalid_school_date');
15 return raw;
16 }
17 export const schoolLifecycleError = (error) => {
18 if (error instanceof InputError) return error;
19 if (error.code === '23505') return new InputError(409, 'school_entity_conflict');
20 if (error.code === '23514' && error.message.startsWith('school_')) {
21 const code = error.message.split('\n')[0];
22 return new InputError(code.includes('forbidden') ? 403 : code.includes('inactive') || code.includes('in_use') || code.includes('immutable') ? 409 : 400, code);
23 }
24 return error;
25 };
26 const route = (handler) => async (req, res, next) => {
27 try { await handler(req, res); }
28 catch (raw) { const error = schoolLifecycleError(raw); if (error instanceof InputError) return res.status(error.status).json({error: error.code}); next(error); }
29 };
30 export async function assertSchoolSession(client, identity) {
31 const session = await client.query(`select 1 from auth_session s join app_user u on u.id=s.user_id
32 where s.id=$1 and s.user_id=$2 and s.revoked_at is null
33 and s.expires_at>statement_timestamp() and u.disabled_at is null for share of s`, [identity.sid, identity.sub]);
34 // statement_timestamp() in the locking SELECT was sampled before any wait.
35 // Sample again after the lock is acquired rather than accepting stale time.
36 const current = session.rowCount && await client.query(`select 1 from auth_session s join app_user u on u.id=s.user_id
37 where s.id=$1 and s.user_id=$2 and s.revoked_at is null
38 and s.expires_at>statement_timestamp() and u.disabled_at is null`, [identity.sid, identity.sub]);
39 if (!current?.rowCount || (identity.exp != null && identity.exp * 1000 <= Date.now())) fail(401, 'session_invalid');
40 }
41 async function transaction(pool, operation, identity, write = false) {
42 const client = await pool.connect();
43 try {
44 await client.query('begin');
45 const account = await client.query(`select 1 from app_user where id=$1 and disabled_at is null for ${write ? 'update' : 'share'}`, [identity.sub]);
46 if (!account.rowCount) fail(401, 'session_invalid');
47 await assertSchoolSession(client, identity);
48 const result = await operation(client);
49 await assertSchoolSession(client, identity);
50 await client.query('commit'); return result;
51 }
52 catch (error) { await client.query('rollback').catch(() => {}); throw error; }
53 finally { client.release(); }
54 }
55 function mutation(raw, type) {
56 if (!raw || typeof raw !== 'object' || Array.isArray(raw) || Object.keys(raw).some((key) => !['mutationId','entityId','operation','expectedVersion','data'].includes(key))) fail(400, 'invalid_school_mutation');
57 const result = { mutationId: uuid(raw.mutationId), entityId: uuid(raw.entityId), operation: raw.operation, expectedVersion: raw.expectedVersion, data: {} };
58 if (!['create','update','archive'].includes(result.operation) || !Number.isInteger(result.expectedVersion) || result.expectedVersion < 0 || result.expectedVersion > 2147483646 || (result.operation === 'create' ? result.expectedVersion !== 0 : result.expectedVersion < 1)) fail(400, 'invalid_school_mutation');
59 const data = raw.data ?? {};
60 if (!data || typeof data !== 'object' || Array.isArray(data)) fail(400, 'invalid_school_data');
61 const allowed = result.operation === 'archive' ? [] : type === 'contexts' ? ['title','kind'] : ['title','startsOn','endsOn', ...(result.operation === 'create' ? [type === 'years' ? 'lifeContextId' : 'academicYearId'] : [])];
62 if (Object.keys(data).some((key) => !allowed.includes(key))) fail(400, 'invalid_school_data');
63 for (const key of allowed) if (owns(data, key)) {
64 result.data[key] = key === 'title' ? title(data[key]) : key.endsWith('On') ? date(data[key]) : key.endsWith('Id') ? uuid(data[key]) : data[key];
65 }
66 if (owns(data, 'kind') && !['student','work','personal'].includes(data.kind)) fail(400, 'invalid_school_kind');
67 if (result.operation === 'create' && allowed.some((key) => !owns(data, key))) fail(400, 'invalid_school_data');
68 if (result.operation === 'update' && !Object.keys(data).length) fail(400, 'invalid_school_data');
69 if (result.data.startsOn && result.data.endsOn && result.data.endsOn < result.data.startsOn) fail(400, 'invalid_school_date_range');
70 return result;
71 }
72 const projection = (type, alias = 'e') => type === 'contexts' ? `${alias}.*` : `${alias}.*,${alias}.starts_on::text as starts_on,${alias}.ends_on::text as ends_on`;
73 async function owned(client, type, id, ownerId, lock = false) {
74 const sql = type === 'contexts' ? `select ${projection(type)} from life_context e where e.id=$1 and e.user_id=$2` : type === 'years' ? `select ${projection(type)} from academic_year e where e.id=$1 and e.student_user_id=$2` : `select ${projection(type)} from academic_term e join academic_year y on y.id=e.academic_year_id join life_context l on l.id=y.life_context_id where e.id=$1 and y.student_user_id=$2 and l.user_id=$2`;
75 return (await client.query(sql + (lock ? ' for update of e' : ''), [id, ownerId])).rows[0];
76 }
77 async function parent(client, type, data, ownerId) {
78 if (type === 'contexts') return;
79 const raw = await owned(client, type === 'years' ? 'contexts' : 'years', type === 'years' ? data.lifeContextId : data.academicYearId, ownerId);
80 if (!raw) fail(403, 'school_parent_forbidden');
81 if (!raw.active || (type === 'years' && raw.kind !== 'student')) fail(409, 'school_parent_inactive');
82 if (type === 'terms') {
83 const context = await owned(client, 'contexts', raw.life_context_id, ownerId);
84 if (!context?.active || context.kind !== 'student') fail(409, 'school_parent_inactive');
85 if (data.startsOn < raw.starts_on || data.endsOn > raw.ends_on) fail(400, 'school_dates_outside_parent');
86 }
87 }
88 export function createSchoolLifecycleRouter({ pool, auth }) {
89 const router = express.Router();
90 router.get('/school/lifecycle', auth, route(async (req, res) => {
91 const result = await transaction(pool, async (client) => {
92 const contexts = (await client.query('select * from life_context where user_id=$1 order by created_at,id limit 501', [req.identity.sub])).rows;
93 const years = (await client.query(`select ${projection('years')} from academic_year e join life_context l on l.id=e.life_context_id where e.student_user_id=$1 and l.user_id=$1 order by e.starts_on desc,e.id limit 501`, [req.identity.sub])).rows;
94 const terms = (await client.query(`select ${projection('terms')} from academic_term e join academic_year y on y.id=e.academic_year_id join life_context l on l.id=y.life_context_id where y.student_user_id=$1 and l.user_id=$1 order by e.starts_on desc,e.id limit 501`, [req.identity.sub])).rows;
95 if ([contexts, years, terms].some((rows) => rows.length > 500)) fail(422, 'school_list_limit_exceeded');
96 const fetchedAt = (await client.query('select clock_timestamp() as now')).rows[0].now.toISOString();
97 return { contexts, years, terms, fetchedAt };
98 }, req.identity);
99 res.json(result);
100 }));
101 router.post('/school/lifecycle/:type/mutations', auth, route(async (req, res) => {
102 const type = req.params.type;
103 if (!owns(TYPES, type)) fail(404, 'school_entity_type_not_found');
104 const body = mutation(req.body, type);
105 const requestHash = crypto.createHash('sha256').update(JSON.stringify({ type, ...body })).digest('hex');
106 const result = await transaction(pool, async (client) => {
107 const ledger = (await client.query('select * from school_lifecycle_mutation where owner_user_id=$1 and mutation_id=$2', [req.identity.sub, body.mutationId])).rows[0];
108 if (ledger) {
109 if (ledger.request_hash !== requestHash) fail(409, 'school_mutation_reused');
110 const entity = await owned(client, type, body.entityId, req.identity.sub);
111 if (!entity) fail(404, 'school_entity_not_found');
112 return { entity, acknowledgement: { mutationId: body.mutationId, entityId: body.entityId, entityType: type, operation: body.operation, status: 'already_applied', appliedVersion: ledger.applied_version, acceptedAt: ledger.accepted_at.toISOString() } };
113 }
114 let entity;
115 if (body.operation === 'create') {
116 const counts = type === 'contexts' ? 'select count(*)::int as n from life_context where user_id=$1' : type === 'years' ? 'select count(*)::int as n from academic_year where student_user_id=$1' : 'select count(*)::int as n from academic_term t join academic_year y on y.id=t.academic_year_id where y.student_user_id=$1';
117 if ((await client.query(counts, [req.identity.sub])).rows[0].n >= 500) fail(422, 'school_list_limit_exceeded');
118 await parent(client, type, body.data, req.identity.sub);
119 if (type === 'contexts') await client.query('insert into life_context(id,user_id,kind,title) values($1,$2,$3,$4)', [body.entityId, req.identity.sub, body.data.kind, body.data.title]);
120 else if (type === 'years') await client.query('insert into academic_year(id,student_user_id,life_context_id,title,starts_on,ends_on) values($1,$2,$3,$4,$5,$6)', [body.entityId, req.identity.sub, body.data.lifeContextId, body.data.title, body.data.startsOn, body.data.endsOn]);
121 else await client.query('insert into academic_term(id,academic_year_id,title,starts_on,ends_on) values($1,$2,$3,$4,$5)', [body.entityId, body.data.academicYearId, body.data.title, body.data.startsOn, body.data.endsOn]);
122 } else {
123 const current = await owned(client, type, body.entityId, req.identity.sub, true);
124 if (!current) fail(404, 'school_entity_not_found');
125 if (current.version !== body.expectedVersion) fail(409, 'school_version_conflict');
126 if (!current.active) fail(409, 'school_entity_archived');
127 if (body.operation === 'archive') await client.query(`update ${TYPES[type]} set active=false where id=$1`, [body.entityId]);
128 else {
129 const data = { title: current.title, ...(type === 'contexts' ? { kind: current.kind } : { startsOn: current.starts_on, endsOn: current.ends_on, ...(type === 'years' ? { lifeContextId: current.life_context_id } : { academicYearId: current.academic_year_id }) }), ...body.data };
130 if (type !== 'contexts' && data.endsOn < data.startsOn) fail(400, 'invalid_school_date_range');
131 await parent(client, type, data, req.identity.sub);
132 if (type === 'contexts') await client.query('update life_context set title=$2,kind=$3 where id=$1', [body.entityId, data.title, data.kind]);
133 else await client.query(`update ${TYPES[type]} set title=$2,starts_on=$3,ends_on=$4 where id=$1`, [body.entityId, data.title, data.startsOn, data.endsOn]);
134 }
135 }
136 entity = await owned(client, type, body.entityId, req.identity.sub);
137 const inserted = (await client.query('insert into school_lifecycle_mutation(owner_user_id,mutation_id,entity_type,entity_id,operation,request_hash,applied_version) values($1,$2,$3,$4,$5,$6,$7) returning accepted_at', [req.identity.sub, body.mutationId, type, body.entityId, body.operation, requestHash, entity.version])).rows[0];
138 return { entity, acknowledgement: { mutationId: body.mutationId, entityId: body.entityId, entityType: type, operation: body.operation, status: 'accepted', appliedVersion: entity.version, acceptedAt: inserted.accepted_at.toISOString() } };
139 }, req.identity, true);
140 res.status(result.acknowledgement.status === 'accepted' && body.operation === 'create' ? 201 : 200).json(result);
141 }));
142 return router;
143 }