LifeMate — Personal, Family & Learning Companion

docs/offline-data-rescue-options
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 277 lines 20.1 KB
Raw
1 import test, { after } from 'node:test';
2 import assert from 'node:assert/strict';
3 import crypto from 'node:crypto';
4 import express from 'express';
5 import jwt from 'jsonwebtoken';
6 import pg from 'pg';
7 import { createSessionAuth } from '../src/session_auth.js';
8 import { createPhase3Router } from '../src/phase3.js';
9 import { createStudySessionsRouter } from '../src/study_sessions.js';
10
11 assert.ok(process.env.DATABASE_URL, 'Report-period tests require synthetic PostgreSQL');
12 const database = new URL(process.env.DATABASE_URL);
13 assert.ok(['localhost', '127.0.0.1', '::1'].includes(database.hostname), 'Report tests refuse a nonlocal database');
14 assert.match(database.pathname, /^\/(?:lifeguide_[a-z_]*test[a-z_]*|lifemate_ci|lifeguide_roles_source_[a-f0-9]{16})$/);
15 const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
16 const secret = 'synthetic-report-period-secret-32-characters';
17 const auth = createSessionAuth({ pool, jwtSecret: secret });
18 const app = express();
19 app.use(express.json());
20 app.use('/v1', createPhase3Router({ pool, auth }));
21 app.use('/v1', createStudySessionsRouter({ pool, auth }));
22 app.use((error, _req, res, _next) => { console.error(error); res.status(500).json({ error: 'internal_error' }); });
23 const server = app.listen(0, '127.0.0.1');
24 await new Promise((resolve) => server.on('listening', resolve));
25 const base = `http://127.0.0.1:${server.address().port}`;
26 const users = [], families = [];
27 after(async () => {
28 await new Promise((resolve) => server.close(resolve));
29 try {
30 await pool.query('delete from access_audit where family_id=any($1::uuid[]) or actor_user_id=any($2::uuid[])', [families, users]);
31 await pool.query('delete from family_workspace where id=any($1::uuid[])', [families]);
32 await pool.query('delete from app_user where id=any($1::uuid[])', [users]);
33 } finally { await pool.end(); }
34 });
35 const iso = (ms) => new Date(ms).toISOString();
36 const day = 86400000;
37 function range() {
38 const local = new Date(Date.now() + 210 * 60000);
39 const to = Date.UTC(local.getUTCFullYear(), local.getUTCMonth(), local.getUTCDate()) - 210 * 60000;
40 return { from: to - 7 * day, to };
41 }
42 async function user() {
43 const id = crypto.randomUUID(), sid = crypto.randomUUID(); users.push(id);
44 await pool.query('insert into app_user(id,identity_subject,email_normalized,email_verified_at) values($1,$2,$3,now())', [id, `report-period:${id}`, `report-period-${id}@example.test`]);
45 await pool.query("insert into profile(user_id,display_name,theme_preference) values($1,'Synthetic report account','adult_blue')", [id]);
46 await pool.query("insert into auth_session(id,user_id,refresh_digest,expires_at) values($1,$2,$3,now()+interval '1 day')", [sid, id, crypto.randomUUID()]);
47 return { id, sid, token: jwt.sign({ sub: id, sid, aud: 'lifemate-api' }, secret, { issuer: 'lifemate', expiresIn: '15m' }) };
48 }
49 async function fixture() {
50 const child = await user(), mother = await user(), father = await user(), outsider = await user();
51 const familyId = crypto.randomUUID(); families.push(familyId);
52 await pool.query("insert into family_workspace(id,name,created_by) values($1,'Synthetic report family',$2)", [familyId, mother.id]);
53 for (const [actor, role] of [[child, 'teen_minor'], [mother, 'parent_guardian'], [father, 'parent_guardian']]) {
54 await pool.query('insert into family_membership(family_id,user_id,role,is_admin) values($1,$2,$3,$4)', [familyId, actor.id, role, actor === mother]);
55 }
56 for (const actor of [mother, father]) await pool.query('insert into guardian_relationship(family_id,guardian_user_id,minor_user_id) values($1,$2,$3)', [familyId, actor.id, child.id]);
57 return { child, mother, father, outsider, familyId };
58 }
59 async function request(path, actor, method = 'GET', body) {
60 const response = await fetch(base + path, { method, headers: { 'content-type': 'application/json', ...(actor ? { authorization: `Bearer ${actor.token}` } : {}) }, body: body === undefined ? undefined : JSON.stringify(body) });
61 return { status: response.status, body: await response.json() };
62 }
63 async function task(f, fields = {}) {
64 const { status, ...createFields } = fields;
65 const response = await request('/v1/plan-items', f.child, 'POST', { kind: 'assignment', title: 'Synthetic period assignment', familyId: f.familyId, visibility: 'parent_guardian', plannedDurationSeconds: 600, notes: 'PRIVATE-REPORT-DETAIL', ...createFields });
66 assert.equal(response.status, 201, JSON.stringify(response.body));
67 if (status === 'completed') {
68 const completed = await request(`/v1/plan-items/${response.body.id}/activity-state`, f.child, 'POST', { mutationId: crypto.randomUUID(), expectedVersion: 0, state: 'completed', source: 'self_reported', occurredAt: iso(Date.now() - 1000) });
69 assert.equal(completed.status, 200, JSON.stringify(completed.body));
70 }
71 return response.body;
72 }
73 async function report(f, actor = f.mother, window = range()) {
74 return request(`/v1/families/${f.familyId}/children/${f.child.id}/learning-report?from=${encodeURIComponent(iso(window.from))}&to=${encodeURIComponent(iso(window.to))}`, actor);
75 }
76 async function subject(f, name = 'Same-named subject') {
77 const context = await request('/v1/life-contexts', f.child, 'POST', { kind: 'student', title: 'Synthetic report school' });
78 assert.equal(context.status, 201);
79 const year = await request('/v1/school/years', f.child, 'POST', { lifeContextId: context.body.id, title: 'Synthetic year', startsOn: '2026-01-01', endsOn: '2026-12-31' });
80 assert.equal(year.status, 201);
81 const term = await request(`/v1/school/years/${year.body.id}/terms`, f.child, 'POST', { title: 'Synthetic term', startsOn: '2026-01-01', endsOn: '2026-12-31' });
82 assert.equal(term.status, 201);
83 const result = await request(`/v1/school/terms/${term.body.id}/subjects`, f.child, 'POST', { name });
84 assert.equal(result.status, 201); return result.body.id;
85 }
86 async function recorded(f, taskId, start, end) {
87 const result = await request('/v1/study/sessions', f.child, 'POST', { id: crypto.randomUUID(), mutationId: crypto.randomUUID(), planItemId: taskId, source: 'self_reported', startedAt: iso(start), endedAt: iso(end) });
88 assert.equal(result.status, 201, JSON.stringify(result.body));
89 return result.body.session;
90 }
91
92 test('period task cohort uses inclusive due/start boundaries, excludes undated and keeps explicit historical totals', async () => {
93 const f = await fixture(), window = range();
94 const atStart = await task(f, { dueAt: iso(window.from), status: 'completed', plannedDurationSeconds: 120 });
95 const startOnly = await task(f, { startsAt: iso(window.from + day), plannedDurationSeconds: 180 });
96 const old = await task(f, { dueAt: iso(window.from - 1), status: 'completed', plannedDurationSeconds: 900 });
97 const atEnd = await task(f, { dueAt: iso(window.to), plannedDurationSeconds: 300 });
98 const differentDates = await task(f, { startsAt: iso(window.from + day), dueAt: iso(window.to + day), plannedDurationSeconds: 360 });
99 const undated = await task(f, { plannedDurationSeconds: 420 });
100 const result = await report(f, f.mother, window);
101 assert.equal(result.status, 200);
102 assert.deepEqual(result.body.periodMetrics, {
103 totalTasks: 2, completedTasks: 1, completionPercent: 50, overdueTasks: 0,
104 plannedDurationSeconds: 300, recordedDurationSeconds: 0,
105 examCount: 0, gradedExamCount: 0, gradePercent: null,
106 });
107 assert.equal(result.body.allTimeTaskMetrics.totalTasks, 6);
108 assert.equal(result.body.allTimeTaskMetrics.completedTasks, 2);
109 assert.equal(result.body.metrics.totalTasks, 6, 'legacy field remains historical');
110 assert.equal(result.body.metrics.plannedInRangeDurationSeconds, 300);
111 assert.equal(result.body.taskDatePolicy, 'due_at_then_starts_at');
112 assert.equal(result.body.rangeConvention, 'inclusive_from_exclusive_to');
113 assert.equal(result.body.completionBasis, 'current_status_of_period_tasks');
114 assert.equal(result.body.timezone, 'Asia/Tehran');
115 assert.ok(Number.isFinite(Date.parse(result.body.asOf)));
116 const included = result.body.items.filter((row) => row.taskInRange).map((row) => row.id).sort();
117 assert.deepEqual(included, [atStart.id, startOnly.id].sort());
118 assert.ok([old, atEnd, differentDates, undated].every((row) => !result.body.items.find((item) => item.id === row.id).taskInRange));
119 assert.equal(JSON.stringify(result.body).includes('PRIVATE-REPORT-DETAIL'), false);
120 });
121
122 test('period time clips Tehran midnight even for older tasks and subject/exam aggregates only include authorized items once', async () => {
123 const f = await fixture(), window = range();
124 const firstSubject = await subject(f), secondSubject = await subject(f);
125 const firstExam = await task(f, { kind: 'exam', title: 'Allowed exam one', subjectId: firstSubject, dueAt: iso(window.from + day), gradePoints: 15, gradeOutOf: 20 });
126 const secondExam = await task(f, { kind: 'exam', title: 'Allowed exam two', subjectId: secondSubject, dueAt: iso(window.from + 2 * day), gradePoints: 30, gradeOutOf: 40 });
127 const older = await task(f, { subjectId: firstSubject, dueAt: iso(window.from - day) });
128 const privateExam = await task(f, { kind: 'exam', title: 'PRIVATE-EXAM-NOT-SHARED', subjectId: firstSubject, dueAt: iso(window.from + day), gradePoints: 0, gradeOutOf: 100, visibility: 'private' });
129 const selected = await task(f, { kind: 'exam', title: 'Mother-only exam', subjectId: firstSubject, dueAt: iso(window.from + 2 * day), gradePoints: 10, gradeOutOf: 10, visibility: 'selected_members', selectedMemberIds: [f.mother.id] });
130 await recorded(f, older.id, window.from - 5 * 60000, window.from + 10 * 60000);
131 await recorded(f, firstExam.id, window.from + 2 * day - 5 * 60000, window.from + 2 * day + 5 * 60000);
132 await recorded(f, secondExam.id, window.to - 5 * 60000, window.to + 5 * 60000);
133 await recorded(f, privateExam.id, window.from + 3 * day, window.from + 3 * day + 20 * 60000);
134 const mother = await report(f, f.mother, window);
135 assert.equal(mother.status, 200);
136 assert.equal(mother.body.periodMetrics.totalTasks, 3);
137 assert.equal(mother.body.periodMetrics.recordedDurationSeconds, 1500);
138 assert.equal(mother.body.periodMetrics.examCount, 3);
139 assert.equal(mother.body.periodMetrics.gradedExamCount, 3);
140 assert.equal(mother.body.periodMetrics.gradePercent, 78.57);
141 assert.deepEqual(mother.body.periodExams.map((row) => row.id).sort(), [firstExam.id, secondExam.id, selected.id].sort());
142 assert.equal(mother.body.periodSubjects.length, 2, 'same labels do not merge distinct subjects');
143 const first = mother.body.periodSubjects.find((row) => row.subjectId === firstSubject);
144 const second = mother.body.periodSubjects.find((row) => row.subjectId === secondSubject);
145 assert.equal(first.totalTasks, 2); assert.equal(first.recordedDurationSeconds, 1200); assert.equal(first.gradePercent, 83.33);
146 assert.equal(second.totalTasks, 1); assert.equal(second.recordedDurationSeconds, 300); assert.equal(second.gradePercent, 75);
147 assert.equal(mother.body.daily.reduce((sum, row) => sum + row.recordedDurationSeconds, 0), 1500);
148 assert.equal(mother.body.isEvidenceOfStudy, false);
149 assert.equal(mother.body.recordingDisclaimerKey, 'recorded_time_is_not_proof_of_study');
150 const father = await report(f, f.father, window);
151 assert.equal(father.body.periodMetrics.totalTasks, 2); assert.equal(father.body.periodMetrics.gradePercent, 75);
152 assert.equal(father.body.periodExams.length, 2);
153 assert.equal(JSON.stringify(mother.body).includes('PRIVATE-EXAM-NOT-SHARED'), false);
154 assert.equal(JSON.stringify(mother.body).includes('PRIVATE-REPORT-DETAIL'), false);
155 assert.equal(JSON.stringify(father.body).includes('Mother-only exam'), false);
156 assert.equal((await report(f, f.outsider, window)).status, 403);
157 });
158
159 test('period fields recheck current membership, guardian relationship, family state and sharing on every read', async () => {
160 const f = await fixture(), window = range();
161 const otherFamily = await fixture();
162 assert.equal((await report(f, otherFamily.mother, window)).status, 403, 'a guardian of another family cannot read this child');
163 const shared = await task(f, { dueAt: iso(window.from + day) });
164 assert.equal((await report(f, f.mother, window)).body.periodMetrics.totalTasks, 1);
165 await pool.query("update plan_item set visibility='private' where id=$1", [shared.id]);
166 const hidden = await report(f, f.mother, window);
167 assert.equal(hidden.body.periodMetrics.totalTasks, 0);
168 assert.deepEqual(hidden.body.periodExams, []); assert.deepEqual(hidden.body.periodSubjects, []);
169 await pool.query("update plan_item set visibility='parent_guardian' where id=$1", [shared.id]);
170 await pool.query('update guardian_relationship set active=false where family_id=$1 and guardian_user_id=$2', [f.familyId, f.mother.id]);
171 assert.equal((await report(f, f.mother, window)).status, 403);
172 await pool.query('update guardian_relationship set active=true where family_id=$1 and guardian_user_id=$2', [f.familyId, f.mother.id]);
173 await pool.query('update family_membership set ended_at=now() where family_id=$1 and user_id=$2', [f.familyId, f.child.id]);
174 assert.equal((await report(f, f.mother, window)).status, 403);
175 await pool.query('update family_membership set ended_at=null where family_id=$1 and user_id=$2', [f.familyId, f.child.id]);
176 await pool.query('update family_workspace set archived_at=now() where id=$1', [f.familyId]);
177 assert.equal((await report(f, f.mother, window)).status, 403);
178 });
179
180 test('report version reflects the period and authorized subject label rather than only task timestamps', async () => {
181 const f = await fixture(), window = range();
182 const subjectId = await subject(f, 'Original report label');
183 await task(f, { subjectId, dueAt: iso(window.from + day) });
184 const original = await report(f, f.mother, window);
185 const changedRange = await report(f, f.mother, { ...window, from: window.from + 2 * day });
186 assert.notEqual(original.body.sourceVersion, changedRange.body.sourceVersion);
187 await pool.query('update subject set name=$2 where id=$1', [subjectId, 'Renamed report label']);
188 const renamed = await report(f, f.mother, window);
189 assert.equal(renamed.body.periodSubjects[0].subjectName, 'Renamed report label');
190 assert.notEqual(original.body.sourceVersion, renamed.body.sourceVersion);
191 });
192
193 test('period reports reject expired credentials, database sessions and disabled accounts before returning data', async () => {
194 const f = await fixture(), window = range();
195 await task(f, { title: 'SESSION-PRIVATE-REPORT-TITLE', dueAt: iso(window.from + day) });
196 const expired = { ...f.mother, token: jwt.sign({ sub: f.mother.id, sid: f.mother.sid, aud: 'lifemate-api' }, secret, { issuer: 'lifemate', expiresIn: -1 }) };
197 for (const actor of [null, expired]) {
198 const result = await report(f, actor, window);
199 assert.equal(result.status, 401); assert.deepEqual(Object.keys(result.body), ['error']);
200 }
201 await pool.query("update auth_session set expires_at=now()-interval '1 second' where id=$1", [f.mother.sid]);
202 assert.equal((await report(f, f.mother, window)).status, 401);
203 await pool.query("update auth_session set expires_at=now()+interval '1 day',revoked_at=now() where id=$1", [f.mother.sid]);
204 assert.equal((await report(f, f.mother, window)).status, 401);
205 await pool.query('update auth_session set revoked_at=null where id=$1', [f.mother.sid]);
206 await pool.query('update app_user set disabled_at=now() where id=$1', [f.mother.id]);
207 const disabled = await report(f, f.mother, window);
208 assert.equal(disabled.status, 401); assert.deepEqual(Object.keys(disabled.body), ['error']);
209 assert.equal(JSON.stringify(disabled.body).includes('SESSION-PRIVATE-REPORT-TITLE'), false);
210 });
211
212 test('report requests validate UTC ranges, duration bounds, defaults and repeated parameters', async () => {
213 const f = await fixture(), window = range();
214 const path = `/v1/families/${f.familyId}/children/${f.child.id}/learning-report`;
215 const query = (from, to) => `${path}?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`;
216 for (const [from, to] of [
217 ['broken', iso(window.to)], [iso(window.from), 'broken'],
218 [iso(window.from), iso(window.from)], [iso(window.to), iso(window.from)],
219 [iso(window.to - 367 * day), iso(window.to)],
220 ['2026-02-30T00:00:00Z', '2026-03-01T00:00:00Z'],
221 ['2026-01-01T00:00:00+03:30', '2026-01-02T00:00:00Z'],
222 ]) {
223 const invalid = await request(query(from, to), f.mother);
224 assert.equal(invalid.status, 400, `${from} → ${to}`);
225 assert.deepEqual(invalid.body, { error: 'invalid_report_range' });
226 }
227 const duplicate = await request(`${query(iso(window.from), iso(window.to))}&from=${encodeURIComponent(iso(window.from))}`, f.mother);
228 assert.equal(duplicate.status, 400);
229 const maximum = await request(query(iso(window.to - 366 * day), iso(window.to)), f.mother);
230 assert.equal(maximum.status, 200); assert.equal(Date.parse(maximum.body.to) - Date.parse(maximum.body.from), 366 * day);
231 const onlyTo = await request(`${path}?to=${encodeURIComponent(iso(window.to))}`, f.mother);
232 assert.equal(onlyTo.status, 200); assert.equal(Date.parse(onlyTo.body.to) - Date.parse(onlyTo.body.from), 30 * day);
233 const before = Date.now(), defaults = await request(path, f.mother), after = Date.now();
234 assert.equal(defaults.status, 200);
235 assert.equal(Date.parse(defaults.body.to) - Date.parse(defaults.body.from), 30 * day);
236 assert.ok(Date.parse(defaults.body.to) >= before && Date.parse(defaults.body.to) <= after);
237 });
238
239 test('report fingerprints change only for current visible source data and preserve no private mutation signal', async () => {
240 const f = await fixture(), window = range();
241 const shared = await task(f, { title: 'Visible source', dueAt: iso(window.from + day) });
242 const hidden = await task(f, { title: 'PRIVATE-HIDDEN-SOURCE', visibility: 'private', dueAt: iso(window.from + day) });
243 const original = await report(f, f.mother, window), repeated = await report(f, f.mother, window);
244 assert.match(original.body.sourceVersion, /^[a-f0-9]{64}$/);
245 assert.equal(repeated.body.sourceVersion, original.body.sourceVersion);
246 await pool.query('update plan_item set title=$2,version=version+1,updated_at=now() where id=$1', [hidden.id, 'PRIVATE-HIDDEN-CHANGED']);
247 const hiddenChanged = await report(f, f.mother, window);
248 assert.equal(hiddenChanged.body.sourceVersion, original.body.sourceVersion);
249 assert.equal(hiddenChanged.body.lastSyncAt, original.body.lastSyncAt);
250 assert.equal(JSON.stringify(hiddenChanged.body).includes('PRIVATE-HIDDEN-CHANGED'), false);
251 await pool.query('update plan_item set title=$2,version=version+1,updated_at=now() where id=$1', [shared.id, 'Visible source changed']);
252 const visibleChanged = await report(f, f.mother, window);
253 assert.notEqual(visibleChanged.body.sourceVersion, original.body.sourceVersion);
254 await pool.query("update plan_item set visibility='private' where id=$1", [shared.id]);
255 const revoked = await report(f, f.mother, window);
256 assert.equal(revoked.body.periodMetrics.totalTasks, 0); assert.deepEqual(revoked.body.items, []);
257 assert.notEqual(revoked.body.sourceVersion, visibleChanged.body.sourceVersion);
258 assert.equal(revoked.body.lastSyncAt, null);
259 await pool.query("update family_membership set role='adult_member' where family_id=$1 and user_id=$2", [f.familyId, f.mother.id]);
260 assert.equal((await report(f, f.mother, window)).status, 403, 'family administration is not guardian authority');
261 });
262
263 test('report fingerprint is stable when only fixture interval physical row order changes', async () => {
264 const f = await fixture(), window = range();
265 const shared = await task(f, { dueAt: iso(window.from + day) });
266 const first = await recorded(f, shared.id, window.from + day, window.from + day + 5 * 60000);
267 await recorded(f, shared.id, window.from + 2 * day, window.from + 2 * day + 7 * 60000);
268 const original = await report(f, f.mother, window);
269 // A no-op SQL update changes the physical heap position without changing
270 // any logical report input. Only this randomized fixture's row is touched.
271 await pool.query('update study_interval set starts_at=starts_at where session_id=$1', [first.id]);
272 const reordered = await report(f, f.mother, window);
273 assert.deepEqual(reordered.body.items, original.body.items);
274 assert.deepEqual(reordered.body.periodMetrics, original.body.periodMetrics);
275 assert.deepEqual(reordered.body.daily, original.body.daily);
276 assert.equal(reordered.body.sourceVersion, original.body.sourceVersion);
277 });