LifeMate — Personal, Family & Learning Companion

feat/local-signing-preflight
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 240 lines 18.6 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
10 if (!process.env.DATABASE_URL) throw new Error('planner sync tests require synthetic PostgreSQL');
11 const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
12 const secret = 'synthetic-planner-sync-secret-32-characters';
13 const app = express();
14 app.use(express.json({ limit: '64kb' }));
15 app.use('/v1', createPhase3Router({ pool, auth: createSessionAuth({ pool, jwtSecret: secret }) }));
16 app.use((error, _req, res, _next) => { console.error(error); res.status(500).json({ error: 'internal_error' }); });
17 let server = app.listen(0);
18 let base = `http://127.0.0.1:${server.address().port}`;
19 after(async () => { await new Promise((resolve) => server.close(resolve)); await pool.end(); });
20 const uuid = () => crypto.randomUUID();
21 async function user() {
22 const id = uuid(), sid = uuid();
23 await pool.query('insert into app_user(id,identity_subject,email_normalized,email_verified_at) values($1,$2,$3,now())', [id, `planner-test:${id}`, `${id}@example.test`]);
24 await pool.query("insert into profile(user_id,display_name,theme_preference) values($1,'Synthetic Planner','adult_blue')", [id]);
25 await pool.query("insert into auth_session(id,user_id,refresh_digest,expires_at) values($1,$2,$3,now()+interval '1 day')", [sid, id, uuid()]);
26 return { id, token: jwt.sign({ sub: id, sid, aud: 'lifemate-api' }, secret, { issuer: 'lifemate', expiresIn: '15m' }) };
27 }
28 async function fixture() {
29 const child = await user(), parent = await user(), outsider = await user(), familyId = uuid();
30 await pool.query("insert into family_workspace(id,name,created_by) values($1,'Synthetic Planner Family',$2)", [familyId, parent.id]);
31 await pool.query("insert into family_membership(family_id,user_id,role) values($1,$2,'teen_minor'),($1,$3,'parent_guardian')", [familyId, child.id, parent.id]);
32 await pool.query('insert into guardian_relationship(family_id,guardian_user_id,minor_user_id) values($1,$2,$3)', [familyId, parent.id, child.id]);
33 return { child, parent, outsider, familyId };
34 }
35 async function request(path, actor, { method = 'GET', body } = {}) {
36 const response = await fetch(base + path, { method, headers: { 'content-type': 'application/json', ...(actor ? { authorization: `Bearer ${actor.token}` } : {}) }, body: body === undefined ? undefined : JSON.stringify(body) });
37 const text = await response.text();
38 return { status: response.status, body: response.headers.get('content-type')?.includes('application/json') ? JSON.parse(text) : text };
39 }
40 async function sync(actor, mutations) { return request('/v1/sync/mutations', actor, { method: 'POST', body: { mutations } }); }
41 const create = (f, payload = {}) => ({ id: uuid(), entityType: 'plan_item', entityId: uuid(), operation: 'create', expectedVersion: 0,
42 payload: { kind: 'assignment', title: 'تکلیف ریاضی آزمایشی', familyId: f.familyId, visibility: 'parent_guardian', dueAt: new Date(Date.now() + 3600000).toISOString(), plannedDurationSeconds: 1500, ...payload } });
43
44 test('offline stable create/retry/update/complete/archive have canonical acknowledgements and PostgreSQL survives HTTP restart', async () => {
45 const f = await fixture();
46 const mutation = create(f);
47 const created = await sync(f.child, [mutation]);
48 assert.equal(created.status, 200);
49 const a = created.body.results[0];
50 assert.equal(a.status, 'accepted');
51 assert.equal(a.item.id, mutation.entityId);
52 assert.equal(Number(a.item.version), 1);
53 assert.equal(a.item.planned_duration_seconds, 1500);
54 assert.ok(Number.isFinite(Date.parse(a.acceptedAt)));
55 const duplicate = await sync(f.child, [mutation]);
56 assert.equal(duplicate.body.results[0].status, 'already_applied');
57 assert.deepEqual(duplicate.body.results[0].item, a.item);
58 assert.equal((await pool.query('select count(*)::int n from plan_item where id=$1', [mutation.entityId])).rows[0].n, 1);
59 const update = { id: uuid(), entityType: 'plan_item', entityId: mutation.entityId, operation: 'update', expectedVersion: 1, payload: { title: 'ویرایش تکلیف', plannedDurationSeconds: 600 } };
60 const updated = await sync(f.child, [update]);
61 assert.equal(updated.body.results[0].status, 'accepted');
62 assert.equal(Number(updated.body.results[0].item.version), 2);
63 const complete = await sync(f.child, [{ ...update, id: uuid(), operation: 'complete', expectedVersion: 2, payload: {} }]);
64 assert.equal(complete.body.results[0].item.status, 'completed');
65 assert.equal(Number(complete.body.results[0].item.version), 3);
66 const event = (await pool.query('select state,source from activity_state_event where plan_item_id=$1 order by version desc limit 1', [mutation.entityId])).rows[0];
67 assert.deepEqual(event, { state: 'completed', source: 'self_reported' });
68 await new Promise((resolve) => server.close(resolve)); server = app.listen(0); base = `http://127.0.0.1:${server.address().port}`;
69 const read = await request(`/v1/plan-items/${mutation.entityId}`, f.child);
70 assert.equal(read.status, 200);
71 assert.equal(read.body.title, 'ویرایش تکلیف');
72 const archive = await sync(f.child, [{ ...update, id: uuid(), operation: 'archive', expectedVersion: 3, payload: {} }]);
73 assert.equal(archive.body.results[0].item.status, 'cancelled');
74 assert.equal((await pool.query('select status from plan_item where id=$1', [mutation.entityId])).rows[0].status, 'cancelled');
75 });
76
77 test('server versions defeat future client clocks; concurrent updates and changed mutation reuse are explicit conflicts', async () => {
78 const f = await fixture(), mutation = create(f);
79 assert.equal((await sync(f.child, [mutation])).body.results[0].status, 'accepted');
80 const reused = await sync(f.child, [{ ...mutation, payload: { ...mutation.payload, title: 'Changed duplicate' } }]);
81 assert.equal(reused.body.results[0].status, 'conflict');
82 assert.equal(reused.body.results[0].error, 'mutation_id_reused');
83 assert.equal(reused.body.results[0].httpStatus, 409);
84 const stale = { id: uuid(), entityType: 'plan_item', entityId: mutation.entityId, operation: 'update', expectedVersion: 0, clientUpdatedAt: '2999-01-01T00:00:00Z', payload: { title: 'Wrong stale update' } };
85 assert.equal((await sync(f.child, [stale])).body.results[0].error, 'version_conflict');
86 const [a, b] = await Promise.all([sync(f.child, [{ ...stale, id: uuid(), expectedVersion: 1 }]), sync(f.child, [{ ...stale, id: uuid(), expectedVersion: 1, payload: { title: 'Other writer' } }])]);
87 assert.deepEqual([a.body.results[0].status, b.body.results[0].status].sort(), ['accepted', 'conflict']);
88 assert.equal((await pool.query('select version from plan_item where id=$1', [mutation.entityId])).rows[0].version, '2');
89 });
90
91 test('direct planner writes require expectedVersion, reject malformed data and return compatible version-one creates', async () => {
92 const f = await fixture();
93 const created = await request('/v1/plan-items', f.child, { method: 'POST', body: create(f).payload });
94 assert.equal(created.status, 201); assert.equal(Number(created.body.version), 1);
95 assert.equal((await request(`/v1/plan-items/${created.body.id}`, f.child, { method: 'PATCH', body: { title: 'No version' } })).status, 400);
96 assert.equal((await request(`/v1/plan-items/${created.body.id}`, f.child, { method: 'PATCH', body: { expectedVersion: 0, title: 'Stale' } })).status, 409);
97 assert.equal((await request(`/v1/plan-items/${created.body.id}`, f.child, { method: 'PATCH', body: { expectedVersion: 1, plannedDurationSeconds: 86401 } })).status, 400);
98 assert.equal((await request(`/v1/plan-items/${created.body.id}`, f.child, { method: 'PATCH', body: { expectedVersion: 1, dueAt: 'not-a-date' } })).status, 400);
99 const updated = await request(`/v1/plan-items/${created.body.id}`, f.child, { method: 'PATCH', body: { expectedVersion: 1, plannedDurationSeconds: 0 } });
100 assert.equal(updated.status, 200); assert.equal(updated.body.planned_duration_seconds, 0);
101 assert.equal((await request(`/v1/plan-items/${created.body.id}`, f.parent, { method: 'PATCH', body: { expectedVersion: 2, title: 'Parent overwrite' } })).status, 403);
102 });
103
104 test('duplicate sync mutation rechecks ownership and current family membership; archived families close all helpers and reads', async () => {
105 const f = await fixture(), mutation = create(f);
106 assert.equal((await sync(f.child, [mutation])).body.results[0].status, 'accepted');
107 const forged = await sync(f.outsider, [{ ...mutation, id: uuid(), operation: 'update', expectedVersion: 1, payload: { title: 'Forbidden' } }]);
108 assert.equal(forged.body.results[0].status, 'rejected');
109 await pool.query('update family_membership set ended_at=now() where family_id=$1 and user_id=$2', [f.familyId, f.child.id]);
110 assert.equal((await sync(f.child, [mutation])).body.results[0].status, 'rejected');
111 await pool.query('update family_membership set ended_at=null where family_id=$1 and user_id=$2', [f.familyId, f.child.id]);
112 await pool.query('update family_workspace set archived_at=now() where id=$1', [f.familyId]);
113 assert.equal((await request(`/v1/families/${f.familyId}/calendar`, f.parent)).status, 403);
114 assert.equal((await request(`/v1/school/${f.child.id}/overview`, f.parent)).status, 403);
115 assert.deepEqual((await pool.query('select is_active_family_member($1,$2) member,is_active_guardian($1,$3,$2) guardian', [f.familyId, f.child.id, f.parent.id])).rows[0], { member: false, guardian: false });
116 });
117
118 test('every parent planner read strips owner notes and every school/support aggregate excludes private plans', async () => {
119 const f = await fixture();
120 const publicPlan = await request('/v1/plan-items', f.child, { method: 'POST', body: create(f, { notes: 'PRIVATE-NOTES-SECRET' }).payload });
121 const privatePlan = await request('/v1/plan-items', f.child, { method: 'POST', body: create(f, { visibility: 'private', title: 'PRIVATE-TITLE-SECRET', notes: 'PRIVATE-NOTES-SECRET' }).payload });
122 await pool.query('update plan_item set grade_points=18,grade_out_of=20 where id=$1', [publicPlan.body.id]);
123 await pool.query("update plan_item set status='completed',completed_at=now(),grade_points=100,grade_out_of=100 where id=$1", [privatePlan.body.id]);
124 for (const path of ['/v1/today', '/v1/plan-items', `/v1/plan-items/${publicPlan.body.id}`, `/v1/families/${f.familyId}/calendar`, `/v1/school/${f.child.id}/overview`, `/v1/families/${f.familyId}/children/${f.child.id}/support-summary`]) {
125 const result = await request(path, f.parent);
126 assert.equal(result.status, 200, path);
127 assert.ok(!JSON.stringify(result.body).includes('PRIVATE-NOTES-SECRET'), path);
128 assert.ok(!JSON.stringify(result.body).includes('PRIVATE-TITLE-SECRET'), path);
129 }
130 const owner = await request(`/v1/plan-items/${publicPlan.body.id}`, f.child);
131 assert.equal(owner.body.notes, 'PRIVATE-NOTES-SECRET');
132 const support = await request(`/v1/families/${f.familyId}/children/${f.child.id}/support-summary`, f.parent);
133 assert.equal(support.body.metrics.gradePercent, 90);
134 assert.equal(support.body.metrics.completedLast7Days, 0);
135 const overview = await request(`/v1/school/${f.child.id}/overview`, f.parent);
136 assert.equal(overview.body.grades.length, 1);
137 });
138
139 test('mutation IDs are scoped to accounts and a malformed/unauthorized mutation never aborts accepted siblings', async () => {
140 const a = await fixture(), b = await fixture(), first = create(a), second = { ...create(b), id: first.id };
141 assert.equal((await sync(a.child, [first])).body.results[0].status, 'accepted');
142 assert.equal((await sync(b.child, [second])).body.results[0].status, 'accepted');
143 const bad = { ...create(a), entityId: 'not-a-uuid' }, valid = create(a);
144 const batch = await sync(a.child, [bad, valid]);
145 assert.equal(batch.status, 200);
146 assert.deepEqual(batch.body.results.map((x) => x.status), ['rejected', 'accepted']);
147 assert.equal((await pool.query('select count(*)::int n from sync_mutation where id=$1', [first.id])).rows[0].n, 2);
148 });
149
150 test('reschedule, selected-member grants and private-note edits share validation without publishing notes', async () => {
151 const f = await fixture(), mutation = create(f, { visibility: 'selected_members', selectedMemberIds: [f.parent.id], notes: 'OWN-NOTE-SECRET' });
152 const created = await sync(f.child, [mutation]);
153 assert.equal(created.body.results[0].status, 'accepted');
154 assert.equal((await request(`/v1/plan-items/${mutation.entityId}`, f.parent)).status, 200);
155 const reschedule = { id: uuid(), entityType: 'plan_item', entityId: mutation.entityId, operation: 'reschedule', expectedVersion: 1, payload: { dueAt: new Date(Date.now() + 7200000).toISOString() } };
156 assert.equal((await sync(f.child, [reschedule])).body.results[0].status, 'accepted');
157 const madePrivate = await sync(f.child, [{ ...reschedule, id: uuid(), operation: 'update', expectedVersion: 2, payload: { visibility: 'private', notes: 'EDITED-OWN-NOTE-SECRET' } }]);
158 assert.equal(madePrivate.body.results[0].status, 'accepted');
159 assert.equal((await request(`/v1/plan-items/${mutation.entityId}`, f.parent)).status, 404);
160 const owner = await request(`/v1/plan-items/${mutation.entityId}`, f.child);
161 assert.equal(owner.body.notes, 'EDITED-OWN-NOTE-SECRET');
162 assert.equal((await pool.query("select count(*)::int n from sharing_grant where resource_type='plan_item' and resource_id=$1", [mutation.entityId])).rows[0].n, 0);
163 });
164
165 test('grade updates require the latest owner version and support time counts only visible recorded intervals', async () => {
166 const f = await fixture(), a = create(f), b = create(f, { visibility: 'private' });
167 const created = await sync(f.child, [a, b]);
168 assert.ok(created.body.results.every((x) => x.status === 'accepted'));
169 const path = `/v1/school/plan-items/${a.entityId}/grade`;
170 assert.equal((await request(path, f.child, { method: 'PATCH', body: { points: 18, outOf: 20 } })).status, 400);
171 const grade = await request(path, f.child, { method: 'PATCH', body: { points: 18, outOf: 20, expectedVersion: 1 } });
172 assert.equal(grade.status, 200);
173 assert.equal(Number(grade.body.version), 2);
174 assert.equal((await request(path, f.child, { method: 'PATCH', body: { points: 19, outOf: 20, expectedVersion: 1 } })).status, 409);
175 const t = Date.now() - 3600000;
176 for (const [planId, offset, seconds] of [[a.entityId, 0, 300], [b.entityId, 600000, 600]]) {
177 const sessionId = uuid(), start = new Date(t + offset), end = new Date(t + offset + seconds * 1000);
178 await pool.query("insert into study_session(id,child_user_id,plan_item_id,source,status,started_at,ended_at,last_event_at,recorded_duration_seconds) values($1,$2,$3,'self_reported','completed',$4,$5,$5,$6)", [sessionId, f.child.id, planId, start, end, seconds]);
179 await pool.query('insert into study_interval(session_id,starts_at,ends_at) values($1,$2,$3)', [sessionId, start, end]);
180 }
181 const report = await request(`/v1/families/${f.familyId}/children/${f.child.id}/support-summary`, f.parent);
182 assert.equal(report.status, 200);
183 assert.equal(report.body.metrics.recordedStudySecondsLast7Days, 300);
184 assert.equal(report.body.metrics.studyMinutesLast7Days, 5);
185 assert.equal(report.body.metrics.recordedTimeIsProofOfStudy, false);
186 });
187
188 test('sync create/update/retry preserve real reminder schedules without duplicates; reschedule, complete and archive retain cancellation semantics', async () => {
189 const f = await fixture();
190 const dueAt = new Date(Date.now() + 3600000).toISOString();
191 const mutation = create(f, { dueAt, reminderMinutesBefore: [30, 10, 10] });
192 const reminderRows = async (planId = mutation.entityId) => (await pool.query(
193 'select id,minutes_before,status,scheduled_for from reminder where plan_item_id=$1 order by minutes_before', [planId],
194 )).rows;
195 const assertSchedule = (rows, base, leads) => {
196 assert.deepEqual(rows.map((row) => row.minutes_before), leads);
197 for (const row of rows) {
198 assert.equal(row.status, 'scheduled');
199 assert.equal(row.scheduled_for.toISOString(), new Date(Date.parse(base) - row.minutes_before * 60000).toISOString());
200 }
201 };
202 const created = await sync(f.child, [mutation]);
203 assert.equal(created.body.results[0].status, 'accepted');
204 const original = await reminderRows();
205 assertSchedule(original, dueAt, [10, 30]);
206 assert.equal((await sync(f.child, [mutation])).body.results[0].status, 'already_applied');
207 assert.deepEqual(await reminderRows(), original);
208
209 const updatedDueAt = new Date(Date.now() + 7200000).toISOString();
210 const update = { id: uuid(), entityType: 'plan_item', entityId: mutation.entityId, operation: 'update', expectedVersion: 1,
211 payload: { dueAt: updatedDueAt, reminderMinutesBefore: [15, 0, 15] } };
212 const updated = await sync(f.child, [update]);
213 assert.equal(updated.body.results[0].status, 'accepted');
214 const replacement = await reminderRows();
215 assertSchedule(replacement, updatedDueAt, [0, 15]);
216 assert.equal((await pool.query('select count(*)::int n from reminder where id=any($1::uuid[])', [original.map((row) => row.id)])).rows[0].n, 0);
217 const retry = await sync(f.child, [update]);
218 assert.equal(retry.body.results[0].status, 'already_applied');
219 assert.deepEqual(retry.body.results[0].item, updated.body.results[0].item);
220 assert.deepEqual(await reminderRows(), replacement);
221
222 const movedDueAt = new Date(Date.now() + 10800000).toISOString();
223 const reschedule = { id: uuid(), entityType: 'plan_item', entityId: mutation.entityId, operation: 'reschedule', expectedVersion: 2, payload: { dueAt: movedDueAt } };
224 assert.equal((await sync(f.child, [reschedule])).body.results[0].status, 'accepted');
225 const moved = await reminderRows();
226 assertSchedule(moved, movedDueAt, [0, 15]);
227 assert.deepEqual(moved.map((row) => row.id), replacement.map((row) => row.id));
228 assert.equal((await sync(f.child, [reschedule])).body.results[0].status, 'already_applied');
229 assert.deepEqual(await reminderRows(), moved);
230 const complete = { id: uuid(), entityType: 'plan_item', entityId: mutation.entityId, operation: 'complete', expectedVersion: 3, payload: {} };
231 assert.equal((await sync(f.child, [complete])).body.results[0].status, 'accepted');
232 assert.ok((await reminderRows()).every((row) => row.status === 'cancelled'));
233
234 const archiveItem = create(f, { dueAt, reminderMinutesBefore: [5] });
235 assert.equal((await sync(f.child, [archiveItem])).body.results[0].status, 'accepted');
236 assertSchedule(await reminderRows(archiveItem.entityId), dueAt, [5]);
237 const archive = { id: uuid(), entityType: 'plan_item', entityId: archiveItem.entityId, operation: 'archive', expectedVersion: 1, payload: {} };
238 assert.equal((await sync(f.child, [archive])).body.results[0].status, 'accepted');
239 assert.equal((await reminderRows(archiveItem.entityId))[0].status, 'cancelled');
240 });