LifeMate — Personal, Family & Learning Companion

feat/aparat-learning-library
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 201 lines 14.6 KB
Raw
1 import crypto from 'node:crypto';
2
3 const kinds = new Set(['task', 'event', 'routine', 'goal', 'assignment', 'exam', 'study_session']);
4 const statuses = new Set(['planned', 'in_progress', 'completed', 'cancelled']);
5 const priorities = new Set(['low', 'normal', 'high', 'urgent']);
6 const scopes = new Set(['private', 'selected_members', 'parent_guardian', 'family']);
7 export const validUuid = (x) => typeof x === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(x);
8 export class PlanMutationError extends Error {
9 constructor(status, code, details = {}) { super(code); this.status = status; this.code = code; this.details = details; }
10 }
11 const fail = (status, code, details) => { throw new PlanMutationError(status, code, details); };
12 export function serializePlanItem(item, viewer) {
13 const result = { ...item, version: Number(item.version), activity_version: Number(item.activity_version) };
14 if (item.owner_user_id !== viewer) delete result.notes;
15 return result;
16 }
17 function canonical(value) {
18 if (Array.isArray(value)) return value.map(canonical);
19 if (value && typeof value === 'object') return Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonical(value[key])]));
20 return value;
21 }
22 function date(value, field) {
23 if (value === null) return null;
24 if (typeof value !== 'string' || !/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{1,6})?(?:Z|[+-]\d\d:\d\d)$/.test(value)) fail(400, `invalid_${field}`);
25 const parsed = new Date(value);
26 if (!Number.isFinite(parsed.getTime())) fail(400, `invalid_${field}`);
27 return parsed;
28 }
29 function text(value, field, max, nullable = false) {
30 if (nullable && value === null) return null;
31 if (typeof value !== 'string' || value.length > max || (!nullable && !value.trim())) fail(400, `invalid_${field}`);
32 return nullable ? value : value.trim();
33 }
34 function id(value, field) {
35 if (value === null) return null;
36 if (!validUuid(value)) fail(400, `invalid_${field}`);
37 return value;
38 }
39 function integer(value, field, min, max) {
40 if (value === null) return null;
41 if (!Number.isSafeInteger(value) || value < min || value > max) fail(400, `invalid_${field}`);
42 return value;
43 }
44 function normalize(payload, existing = null) {
45 if (!payload || typeof payload !== 'object' || Array.isArray(payload)) fail(400, 'invalid_plan_item');
46 for (const key of ['ownerUserId', 'owner_user_id', 'version', 'activity_version', 'created_at', 'updated_at', 'completed_at']) if (key in payload) fail(400, 'server_owned_field');
47 const fields = {};
48 const isCreate = !existing;
49 const defaults = { kind: 'task', title: '', priority: 'normal', visibility: 'private', familyId: null, subjectId: null, learningUnitId: null,
50 notes: null, startsAt: null, dueAt: null, durationMinutes: null, plannedDurationSeconds: null,
51 recurrenceRule: null, parentItemId: null };
52 const values = isCreate ? { ...defaults, ...payload } : payload;
53 const pick = (key, column, validation) => { if (values[key] !== undefined) fields[column] = validation(values[key]); };
54 pick('kind', 'kind', (x) => { if (!kinds.has(x)) fail(400, 'invalid_kind'); return x; });
55 pick('title', 'title', (x) => text(x, 'title', 240));
56 pick('notes', 'notes', (x) => text(x, 'notes', 10000, true));
57 pick('priority', 'priority', (x) => { if (!priorities.has(x)) fail(400, 'invalid_priority'); return x; });
58 pick('visibility', 'visibility', (x) => { if (!scopes.has(x)) fail(400, 'invalid_visibility'); return x; });
59 pick('status', 'status', (x) => { if (!statuses.has(x) || (isCreate && x !== 'planned')) fail(400, 'invalid_status'); return x; });
60 pick('familyId', 'family_id', (x) => id(x, 'family_id'));
61 pick('subjectId', 'subject_id', (x) => id(x, 'subject_id'));
62 pick('learningUnitId', 'learning_unit_id', (x) => id(x, 'learning_unit_id'));
63 pick('parentItemId', 'parent_item_id', (x) => id(x, 'parent_item_id'));
64 pick('startsAt', 'starts_at', (x) => date(x, 'starts_at'));
65 pick('dueAt', 'due_at', (x) => date(x, 'due_at'));
66 pick('recurrenceRule', 'recurrence_rule', (x) => text(x, 'recurrence_rule', 1000, true));
67 pick('durationMinutes', 'duration_minutes', (x) => integer(x, 'duration_minutes', 1, 1440));
68 pick('plannedDurationSeconds', 'planned_duration_seconds', (x) => integer(x, 'planned_duration_seconds', 0, 86400));
69 for (const [key, column] of [['gradePoints', 'grade_points'], ['gradeOutOf', 'grade_out_of']]) pick(key, column, (x) => {
70 if (x === null) return null;
71 if (typeof x !== 'number' || !Number.isFinite(x) || x < 0 || x > 999999.99) fail(400, 'invalid_grade');
72 return x;
73 });
74 if (payload.plannedDurationSeconds !== undefined) fields.duration_minutes = payload.plannedDurationSeconds == null || payload.plannedDurationSeconds === 0 ? null : Math.ceil(payload.plannedDurationSeconds / 60);
75 else if (payload.durationMinutes !== undefined) fields.planned_duration_seconds = payload.durationMinutes == null ? null : payload.durationMinutes * 60;
76 const merged = { ...existing, ...fields };
77 if (fields.grade_points !== undefined || fields.grade_out_of !== undefined) {
78 if (!['assignment', 'exam'].includes(merged.kind)) fail(400, 'grade_not_applicable');
79 if (!(merged.grade_points == null && merged.grade_out_of == null)
80 && (merged.grade_points == null || merged.grade_out_of == null || Number(merged.grade_out_of) <= 0 || Number(merged.grade_points) > Number(merged.grade_out_of))) fail(400, 'invalid_grade');
81 }
82 if (merged.starts_at && merged.due_at && new Date(merged.due_at) < new Date(merged.starts_at)) fail(400, 'invalid_date_order');
83 if (['family', 'parent_guardian', 'selected_members'].includes(merged.visibility) && !merged.family_id) fail(400, 'family_required_for_visibility');
84 return { fields, merged };
85 }
86 export async function planOwnerLock(client, userId) {
87 await client.query('select pg_advisory_xact_lock(hashtextextended($1::text,0))', [userId]);
88 }
89 async function authorize(client, userId, item) {
90 if (!(await client.query('select 1 from app_user where id=$1 and disabled_at is null', [userId])).rowCount) fail(401, 'unauthorized');
91 if (item && item.owner_user_id !== userId) fail(403, 'forbidden');
92 if (item?.family_id && !(await client.query('select 1 where is_active_family_member($1,$2)', [item.family_id, userId])).rowCount) fail(403, 'family_membership_required');
93 }
94 async function relations(client, userId, item, payload, existing = null) {
95 await authorize(client, userId, item);
96 if (item.learning_unit_id && !(await client.query('select 1 from learning_unit where id=$1 and active', [item.learning_unit_id])).rowCount) fail(400, 'invalid_learning_unit_id');
97 if (item.subject_id && !(await client.query('select 1 from subject where id=$1 and student_user_id=$2', [item.subject_id, userId])).rowCount) fail(403, 'subject_forbidden');
98 if (item.parent_item_id && !(await client.query('select 1 from plan_item where id=$1 and owner_user_id=$2', [item.parent_item_id, userId])).rowCount) fail(403, 'parent_item_forbidden');
99 if (payload.selectedMemberIds !== undefined && (!Array.isArray(payload.selectedMemberIds) || payload.selectedMemberIds.length > 100)) fail(400, 'invalid_selected_members');
100 const selected = payload.selectedMemberIds === undefined ? null : [...new Set(payload.selectedMemberIds)];
101 if (item.visibility === 'selected_members' && (!existing || existing.visibility !== 'selected_members' || existing.family_id !== item.family_id) && (!selected || !selected.length)) fail(400, 'selected_members_required');
102 if (selected) for (const member of selected) {
103 if (!validUuid(member) || !(await client.query('select 1 where is_active_family_member($1,$2)', [item.family_id, member])).rowCount) fail(400, 'selected_member_not_in_family');
104 }
105 return selected;
106 }
107 async function grants(client, item, selected) {
108 if (selected !== null || item.visibility !== 'selected_members') await client.query("delete from sharing_grant where resource_type='plan_item' and resource_id=$1", [item.id]);
109 if (item.visibility === 'selected_members' && selected) for (const member of selected) await client.query(
110 "insert into sharing_grant(resource_type,resource_id,grantee_user_id,granted_by) values('plan_item',$1,$2,$3)", [item.id, member, item.owner_user_id],
111 );
112 }
113 async function reminders(client, item, payload) {
114 if (payload.reminderMinutesBefore !== undefined) {
115 if (!Array.isArray(payload.reminderMinutesBefore) || payload.reminderMinutesBefore.length > 100 || payload.reminderMinutesBefore.some((x) => !Number.isSafeInteger(x) || x < 0 || x > 10080)) fail(400, 'invalid_reminders');
116 await client.query('delete from reminder where plan_item_id=$1', [item.id]);
117 const base = item.starts_at ?? item.due_at;
118 if (base) for (const minutes of new Set(payload.reminderMinutesBefore)) await client.query(
119 'insert into reminder(plan_item_id,owner_user_id,minutes_before,scheduled_for) values($1,$2,$3,$4::timestamptz-make_interval(mins=>$3))', [item.id, item.owner_user_id, minutes, base],
120 );
121 }
122 if (['completed', 'cancelled'].includes(item.status)) await client.query("update reminder set status='cancelled' where plan_item_id=$1 and status in ('scheduled','claimed')", [item.id]);
123 else await client.query('select recompute_reminder_schedule($1)', [item.id]);
124 }
125 export async function createPlanItem(client, userId, payload, itemId = crypto.randomUUID()) {
126 if (!validUuid(itemId)) fail(400, 'invalid_id');
127 const { fields } = normalize(payload);
128 const selected = await relations(client, userId, { ...fields, owner_user_id: userId }, payload);
129 const columns = ['id', 'owner_user_id', ...Object.keys(fields)];
130 const values = [itemId, userId, ...Object.values(fields)];
131 const row = (await client.query(`insert into plan_item(${columns.join(',')}) values(${values.map((_, i) => `$${i + 1}`).join(',')}) returning *`, values)).rows[0];
132 await grants(client, row, selected);
133 await reminders(client, row, payload);
134 return row;
135 }
136 export async function updatePlanItem(client, userId, itemId, payload, expectedVersion) {
137 if (!validUuid(itemId)) fail(400, 'invalid_id');
138 const current = (await client.query('select * from plan_item where id=$1 for update', [itemId])).rows[0];
139 if (!current) fail(404, 'not_found');
140 await authorize(client, userId, current);
141 if (!Number.isSafeInteger(expectedVersion) || expectedVersion < 0) fail(400, 'expected_version_required');
142 if (expectedVersion !== Number(current.version)) fail(409, 'version_conflict', { serverVersion: Number(current.version) });
143 const { fields, merged } = normalize(payload, current);
144 if (!Object.keys(fields).length && payload.selectedMemberIds === undefined && payload.reminderMinutesBefore === undefined) fail(400, 'no_changes');
145 const selected = await relations(client, userId, merged, payload, current);
146 if (fields.status !== undefined) fields.completed_at = fields.status === 'completed' ? current.completed_at ?? new Date() : null;
147 const values = [itemId, ...Object.values(fields)];
148 const update = [...Object.keys(fields).map((key, i) => `${key}=$${i + 2}`), 'updated_at=now()'];
149 const item = (await client.query(`update plan_item set ${update.join(',')} where id=$1 returning *`, values)).rows[0];
150 await grants(client, item, selected);
151 await reminders(client, item, payload);
152 return item;
153 }
154 export async function planTransaction(pool, userId, execute) {
155 const client = await pool.connect();
156 try { await client.query('begin'); await planOwnerLock(client, userId); const result = await execute(client); await client.query('commit'); return result; }
157 catch (error) { await client.query('rollback').catch(() => {}); if (error.code === '23505') fail(409, 'plan_item_exists'); throw error; }
158 finally { client.release(); }
159 }
160 export async function applyPlanMutation(pool, userId, mutation) {
161 const idValue = mutation?.id;
162 try {
163 if (!validUuid(idValue) || mutation.entityType !== 'plan_item' || !validUuid(mutation.entityId)
164 || !['create', 'update', 'complete', 'reschedule', 'archive'].includes(mutation.operation)
165 || !mutation.payload || typeof mutation.payload !== 'object' || Array.isArray(mutation.payload)) fail(400, 'invalid_mutation');
166 const hash = crypto.createHash('sha256').update(JSON.stringify(canonical({ entityType: mutation.entityType, entityId: mutation.entityId, operation: mutation.operation, expectedVersion: mutation.expectedVersion ?? null, payload: mutation.payload }))).digest('hex');
167 return await planTransaction(pool, userId, async (client) => {
168 const previous = (await client.query('select * from sync_mutation where user_id=$1 and id=$2', [userId, idValue])).rows[0];
169 if (previous) {
170 const current = (await client.query('select * from plan_item where id=$1', [previous.entity_id])).rows[0];
171 if (!current) fail(404, 'not_found');
172 await authorize(client, userId, current);
173 if (previous.request_hash !== hash || !previous.canonical_item) fail(409, 'mutation_id_reused', { serverVersion: Number(current.version) });
174 return { id: idValue, entityId: previous.entity_id, status: 'already_applied', acceptedAt: previous.accepted_at, item: previous.canonical_item };
175 }
176 let item;
177 if (mutation.operation === 'create') {
178 if (mutation.expectedVersion !== undefined && mutation.expectedVersion !== 0) fail(400, 'create_expected_version_zero');
179 if (mutation.payload.id !== undefined && mutation.payload.id !== mutation.entityId) fail(400, 'entity_id_mismatch');
180 item = await createPlanItem(client, userId, mutation.payload, mutation.entityId);
181 } else {
182 const payload = { ...mutation.payload };
183 if (mutation.operation === 'complete') payload.status = 'completed';
184 if (mutation.operation === 'archive') payload.status = 'cancelled';
185 if (mutation.operation === 'reschedule' && payload.dueAt === undefined && payload.startsAt === undefined) fail(400, 'invalid_reschedule');
186 item = await updatePlanItem(client, userId, mutation.entityId, payload, mutation.expectedVersion);
187 }
188 const canonicalItem = serializePlanItem(item, userId);
189 const accepted = (await client.query(
190 `insert into sync_mutation(id,user_id,entity_type,entity_id,operation,client_updated_at,payload,request_hash,canonical_item)
191 values($1,$2,'plan_item',$3,$4,now(),$5::jsonb,$6,$7::jsonb) returning accepted_at`,
192 [idValue, userId, item.id, mutation.operation, JSON.stringify(mutation.payload), hash, JSON.stringify(canonicalItem)],
193 )).rows[0].accepted_at;
194 return { id: idValue, entityId: item.id, status: 'accepted', acceptedAt: accepted, item: canonicalItem };
195 });
196 } catch (error) {
197 if (!(error instanceof PlanMutationError)) throw error;
198 return { id: idValue ?? null, entityId: mutation?.entityId ?? null,
199 status: error.status === 409 ? 'conflict' : 'rejected', error: error.code, httpStatus: error.status, ...error.details };
200 }
201 }