LifeMate — Personal, Family & Learning Companion

feat/learning-content-operations
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 363 lines 20.2 KB
Raw
1 import test, { after, before } from 'node:test';
2 import assert from 'node:assert/strict';
3 import crypto from 'node:crypto';
4 import http from 'node:http';
5 import express from 'express';
6 import jwt from 'jsonwebtoken';
7 import pg from 'pg';
8 import { createPhase4Router } from '../src/phase4.js';
9 import { createPhase6Router } from '../src/phase6.js';
10 import { createSchoolCrudRouter } from '../src/school_crud_router.js';
11 import { createSessionAuth } from '../src/session_auth.js';
12 import { operationalErrorHandler } from '../src/operations.js';
13
14 assert.ok(process.env.DATABASE_URL, 'Configure a separate synthetic PostgreSQL test database');
15 const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
16 const secret = 'synthetic-privacy-test-secret-at-least-32-characters';
17 const users = [];
18 const families = [];
19 const servers = [];
20 let defaultBase;
21 let enabledBase;
22
23 async function serve(options) {
24 const app = express();
25 app.use(express.json({ limit: '64kb' }));
26 const auth = createSessionAuth({ pool, jwtSecret: secret });
27 app.use('/v1', createSchoolCrudRouter({ pool, auth }));
28 app.use('/v1', createPhase4Router({ pool, auth, ...options }));
29 app.use('/v1', createPhase6Router({ pool, auth, ...options }));
30 app.use(operationalErrorHandler);
31 const server = app.listen(0, '127.0.0.1');
32 await new Promise((resolve) => server.once('listening', resolve));
33 servers.push(server);
34 return `http://127.0.0.1:${server.address().port}`;
35 }
36
37 before(async () => {
38 delete process.env.ENABLE_SENSITIVE_FEATURES;
39 defaultBase = await serve({});
40 enabledBase = await serve({ sensitiveFeaturesEnabled: true });
41 });
42
43 after(async () => {
44 for (const server of servers) await new Promise((resolve) => server.close(resolve));
45 try {
46 if (families.length) {
47 await pool.query('delete from access_audit where family_id=any($1::uuid[])', [families]);
48 await pool.query('delete from family_workspace where id=any($1::uuid[])', [families]);
49 }
50 if (users.length) await pool.query('delete from app_user where id=any($1::uuid[])', [users]);
51 } finally {
52 await pool.end();
53 }
54 });
55
56 async function user() {
57 const id = crypto.randomUUID();
58 const sid = crypto.randomUUID();
59 await pool.query(
60 'insert into app_user(id,identity_subject,email_normalized,email_verified_at) values($1,$2,$3,now())',
61 [id, `privacy-test:${id}`, `privacy-test-${id}@example.test`],
62 );
63 users.push(id);
64 await pool.query("insert into profile(user_id,display_name,theme_preference) values($1,'Synthetic Privacy','adult_blue')", [id]);
65 await pool.query(
66 "insert into auth_session(id,user_id,refresh_digest,expires_at) values($1,$2,$3,now()+interval '1 day')",
67 [sid, id, crypto.randomBytes(32).toString('hex')],
68 );
69 return { id, token: jwt.sign({ sub: id, sid, aud: 'lifemate-api' }, secret, { issuer: 'lifemate', expiresIn: '15m' }) };
70 }
71
72 async function fixture() {
73 const [child, parent, selected, outsider] = await Promise.all([user(), user(), user(), user()]);
74 const familyId = crypto.randomUUID();
75 await pool.query('insert into family_workspace(id,name,created_by) values($1,$2,$3)', [familyId, 'Synthetic Privacy Family', parent.id]);
76 families.push(familyId);
77 for (const [member, role] of [[child, 'teen_minor'], [parent, 'parent_guardian'], [selected, 'adult_member']]) {
78 await pool.query('insert into family_membership(family_id,user_id,role) values($1,$2,$3)', [familyId, member.id, role]);
79 }
80 await pool.query('insert into guardian_relationship(family_id,guardian_user_id,minor_user_id) values($1,$2,$3)', [familyId, parent.id, child.id]);
81 return { child, parent, selected, outsider, familyId };
82 }
83
84 async function plan(f, visibility, { kind = 'assignment', status = 'planned', minutes = null } = {}) {
85 const row = await pool.query(
86 `insert into plan_item(owner_user_id,family_id,kind,title,visibility,status,duration_minutes,due_at,completed_at)
87 values($1,$2,$3,'Synthetic private title',$4,$5::plan_item_status,$6,now()-interval '1 day',case when $5::plan_item_status='completed' then now() end) returning id`,
88 [f.child.id, f.familyId, kind, visibility, status, minutes],
89 );
90 return row.rows[0].id;
91 }
92
93 async function grant(f, itemId, viewer = f.selected) {
94 await pool.query("insert into sharing_grant(resource_type,resource_id,grantee_user_id,granted_by) values('plan_item',$1,$2,$3)", [itemId, viewer.id, f.child.id]);
95 }
96
97 async function canView(viewer, itemId) {
98 return (await pool.query('select can_view_plan_item($1,$2) as allowed', [viewer.id, itemId])).rows[0].allowed;
99 }
100
101 async function academic(viewer, student) {
102 return (await pool.query('select can_view_student_academic($1,$2) as allowed', [viewer.id, student.id])).rows[0].allowed;
103 }
104
105 async function request(base, path, { method = 'GET', actor, body } = {}) {
106 const response = await fetch(base + path, {
107 method,
108 headers: { 'content-type': 'application/json', ...(actor ? { authorization: `Bearer ${actor.token}` } : {}) },
109 body: body === undefined ? undefined : JSON.stringify(body),
110 });
111 const text = await response.text();
112 return { status: response.status, body: text ? JSON.parse(text) : null };
113 }
114
115 test('privatizing a selected item revokes its grant and does not resurrect it when selected again', async () => {
116 const f = await fixture();
117 const item = await plan(f, 'selected_members');
118 await grant(f, item);
119 assert.equal(await canView(f.selected, item), true);
120 await pool.query("update plan_item set visibility='private' where id=$1", [item]);
121 assert.equal(await canView(f.selected, item), false);
122 assert.equal((await pool.query('select 1 from sharing_grant where resource_id=$1', [item])).rowCount, 0);
123 await pool.query("update plan_item set visibility='selected_members' where id=$1", [item]);
124 assert.equal(await canView(f.selected, item), false);
125 assert.equal(await canView(f.child, item), true);
126 });
127
128 for (const side of ['owner', 'viewer']) {
129 test(`ending the selected item ${side}'s membership revokes the grant even after rejoining`, async () => {
130 const f = await fixture();
131 const item = await plan(f, 'selected_members');
132 await grant(f, item);
133 const member = side === 'owner' ? f.child : f.selected;
134 await pool.query('update family_membership set ended_at=now() where family_id=$1 and user_id=$2', [f.familyId, member.id]);
135 assert.equal(await canView(f.selected, item), false);
136 assert.equal((await pool.query('select 1 from sharing_grant where resource_id=$1', [item])).rowCount, 0);
137 await pool.query('update family_membership set ended_at=null where family_id=$1 and user_id=$2', [f.familyId, member.id]);
138 assert.equal(await canView(f.selected, item), false);
139 });
140 }
141
142 test('family sharing requires both the item owner and viewer to remain active members', async () => {
143 const f = await fixture();
144 const item = await plan(f, 'family');
145 assert.equal(await canView(f.parent, item), true);
146 await pool.query('update family_membership set ended_at=now() where family_id=$1 and user_id=$2', [f.familyId, f.child.id]);
147 assert.equal(await canView(f.parent, item), false);
148 assert.equal(await canView(f.child, item), true);
149 });
150
151 test('a direct selected grant cannot authorize someone outside the current item family', async () => {
152 const f = await fixture();
153 const item = await plan(f, 'selected_members');
154 await grant(f, item, f.outsider);
155 assert.equal(await canView(f.outsider, item), false);
156 });
157
158 for (const side of ['guardian', 'minor']) {
159 test(`academic authorization ends when the ${side}'s current role changes`, async () => {
160 const f = await fixture();
161 assert.equal(await academic(f.parent, f.child), true);
162 const member = side === 'guardian' ? f.parent : f.child;
163 await pool.query("update family_membership set role='adult_member' where family_id=$1 and user_id=$2", [f.familyId, member.id]);
164 assert.equal(await academic(f.parent, f.child), false);
165 assert.equal(await academic(f.child, f.child), true);
166 });
167 }
168
169 test('private plan items remain owner-only for both guardians and outsiders', async () => {
170 const f = await fixture();
171 const item = await plan(f, 'private');
172 assert.equal(await canView(f.child, item), true);
173 assert.equal(await canView(f.parent, item), false);
174 assert.equal(await canView(f.outsider, item), false);
175 });
176
177 test('sensitive wellbeing and cycle reads and writes are closed by default, including test mode', async () => {
178 const f = await fixture();
179 const paths = [
180 ['GET', '/v1/wellbeing/checkins'],
181 ['POST', '/v1/wellbeing/checkins', { mood: 3, energy: 3, stress: 3 }],
182 ['GET', `/v1/families/${f.familyId}/children/${f.child.id}/wellbeing-summary`],
183 ['POST', `/v1/families/${f.familyId}/children/${f.child.id}/family-guidance`, { question: 'Synthetic support question' }],
184 ['GET', '/v1/me/menstrual-cycles'],
185 ['POST', '/v1/me/menstrual-cycles', { startsOn: '2026-10-01' }],
186 ['DELETE', `/v1/me/menstrual-cycles/${crypto.randomUUID()}`],
187 ['POST', '/v1/ai/sessions', { kind: 'wellbeing' }],
188 ];
189 for (const [method, path, body] of paths) {
190 const result = await request(defaultBase, path, { method, actor: f.parent, body });
191 assert.equal(result.status, 503, `${method} ${path} must stay gated`);
192 assert.equal(result.body.error, 'sensitive_features_disabled');
193 }
194 assert.equal((await pool.query('select 1 from wellbeing_checkin where owner_user_id=$1', [f.parent.id])).rowCount, 0);
195 assert.equal((await pool.query('select 1 from menstrual_cycle_entry where owner_user_id=$1', [f.parent.id])).rowCount, 0);
196 });
197
198 test('every Phase 4/6 read and write requires a verified server session before gate or data access', async () => {
199 const f = await fixture();
200 const routes = [
201 ['GET', '/v1/learning/goals'], ['POST', '/v1/learning/goals'], ['POST', '/v1/learning/checkins'],
202 ['GET', '/v1/wellbeing/checkins'], ['POST', '/v1/wellbeing/checkins'],
203 ['GET', `/v1/families/${f.familyId}/children/${f.child.id}/wellbeing-summary`],
204 ['POST', `/v1/families/${f.familyId}/children/${f.child.id}/family-guidance`],
205 ['POST', '/v1/ai/sessions'], ['POST', `/v1/ai/sessions/${crypto.randomUUID()}/messages`],
206 ['POST', '/v1/ai/proposals'], ['PATCH', `/v1/ai/proposals/${crypto.randomUUID()}`],
207 ['GET', '/v1/me/iran-profile'], ['PATCH', '/v1/me/iran-profile'], ['PUT', '/v1/me/education'],
208 ['GET', '/v1/education/catalog'], ['GET', '/v1/calendar/iran'],
209 ['GET', '/v1/me/notification-preferences'], ['PATCH', '/v1/me/notification-preferences'],
210 ['GET', '/v1/me/menstrual-cycles'], ['POST', '/v1/me/menstrual-cycles'],
211 ['DELETE', `/v1/me/menstrual-cycles/${crypto.randomUUID()}`],
212 ];
213 for (const [method, path] of routes) {
214 assert.equal((await request(defaultBase, path, { method, body: method === 'GET' ? undefined : {} })).status, 401, path);
215 }
216 });
217
218 test('explicit synthetic opt-in preserves owner-only cycle records', async () => {
219 const f = await fixture();
220 const written = await request(enabledBase, '/v1/me/menstrual-cycles', { method: 'POST', actor: f.child, body: { startsOn: '2026-10-01', notes: 'Synthetic private cycle' } });
221 assert.equal(written.status, 201);
222 const item = written.body.id;
223 assert.equal((await request(enabledBase, '/v1/me/menstrual-cycles', { actor: f.parent })).body.entries.length, 0);
224 assert.equal((await request(enabledBase, `/v1/me/menstrual-cycles/${item}`, { method: 'DELETE', actor: f.parent })).status, 204);
225 assert.equal((await pool.query('select 1 from menstrual_cycle_entry where id=$1', [item])).rowCount, 1);
226 assert.equal((await request(enabledBase, '/v1/me/menstrual-cycles', { actor: f.child })).body.entries[0].notes, 'Synthetic private cycle');
227 assert.equal((await request(enabledBase, `/v1/me/menstrual-cycles/${item}`, { method: 'DELETE', actor: f.child })).status, 204);
228 });
229
230 test('Phase 4 guardian summaries reject a stale guardian role after synthetic opt-in', async () => {
231 const f = await fixture();
232 const path = `/v1/families/${f.familyId}/children/${f.child.id}/wellbeing-summary`;
233 assert.equal((await request(enabledBase, path, { actor: f.parent })).status, 200);
234 await pool.query("update family_membership set role='adult_member' where family_id=$1 and user_id=$2", [f.familyId, f.parent.id]);
235 assert.equal((await request(enabledBase, path, { actor: f.parent })).status, 403);
236 });
237
238 test('family guidance academic aggregates include only plan items visible to that guardian', async () => {
239 const f = await fixture();
240 await plan(f, 'private', { kind: 'study_session', status: 'completed', minutes: 90 });
241 await plan(f, 'parent_guardian', { kind: 'study_session', status: 'completed', minutes: 15 });
242 const result = await request(enabledBase, `/v1/families/${f.familyId}/children/${f.child.id}/family-guidance`, { method: 'POST', actor: f.parent, body: { question: 'Synthetic guidance' } });
243 assert.equal(result.status, 200);
244 assert.equal(result.body.summary.academic.completed_last_7_days, 1);
245 assert.equal(result.body.summary.academic.study_minutes_last_7_days, 15);
246 });
247
248 test('configured AI credentials cannot trigger a provider request in this work package', async () => {
249 const f = await fixture();
250 let calls = 0;
251 const provider = http.createServer((_req, res) => {
252 calls += 1;
253 res.setHeader('content-type', 'application/json');
254 res.end(JSON.stringify({ choices: [{ message: { content: 'Synthetic provider reply' } }] }));
255 });
256 provider.listen(0, '127.0.0.1');
257 await new Promise((resolve) => provider.once('listening', resolve));
258 const previous = Object.fromEntries(['AI_API_KEY', 'AI_BASE_URL', 'AI_MODEL'].map((key) => [key, process.env[key]]));
259 Object.assign(process.env, { AI_API_KEY: 'synthetic-disabled-key', AI_BASE_URL: `http://127.0.0.1:${provider.address().port}`, AI_MODEL: 'synthetic-disabled-model' });
260 try {
261 const session = await request(defaultBase, '/v1/ai/sessions', { method: 'POST', actor: f.child, body: { kind: 'study' } });
262 assert.equal(session.status, 201);
263 const reply = await request(defaultBase, `/v1/ai/sessions/${session.body.id}/messages`, { method: 'POST', actor: f.child, body: { message: 'Synthetic math question' } });
264 assert.equal(reply.status, 200);
265 assert.equal(calls, 0);
266 assert.equal(reply.body.providerMode, 'local_fallback');
267 assert.notEqual(reply.body.body, 'Synthetic provider reply');
268 } finally {
269 for (const [key, value] of Object.entries(previous)) {
270 if (value === undefined) delete process.env[key]; else process.env[key] = value;
271 }
272 await new Promise((resolve) => provider.close(resolve));
273 }
274 });
275
276 test('an existing wellbeing guide cannot receive messages while sensitive features are disabled', async () => {
277 const f = await fixture();
278 const session = await request(enabledBase, '/v1/ai/sessions', { method: 'POST', actor: f.child, body: { kind: 'wellbeing' } });
279 assert.equal(session.status, 201);
280 const reply = await request(defaultBase, `/v1/ai/sessions/${session.body.id}/messages`, { method: 'POST', actor: f.child, body: { message: 'Synthetic private reflection' } });
281 assert.equal(reply.status, 503);
282 assert.equal((await pool.query('select 1 from ai_guide_message where session_id=$1', [session.body.id])).rowCount, 0);
283 });
284
285 test('learning checkins cannot reference another owner\'s goal', async () => {
286 const f = await fixture();
287 const goal = await request(defaultBase, '/v1/learning/goals', { method: 'POST', actor: f.child, body: { title: 'Synthetic goal' } });
288 assert.equal(goal.status, 201);
289 assert.equal((await request(defaultBase, '/v1/learning/checkins', { method: 'POST', actor: f.outsider, body: { learningGoalId: goal.body.id, confidence: 3, difficulty: 3 } })).status, 403);
290 });
291
292 test('AI proposals cannot reference another owner\'s guide session', async () => {
293 const f = await fixture();
294 const session = await request(defaultBase, '/v1/ai/sessions', { method: 'POST', actor: f.child, body: { kind: 'study' } });
295 assert.equal(session.status, 201);
296 assert.equal((await request(defaultBase, '/v1/ai/proposals', { method: 'POST', actor: f.outsider, body: { sessionId: session.body.id, title: 'Synthetic proposal', proposal: { steps: [] } } })).status, 403);
297 });
298
299 test('changing a selected item to another family revokes the previous grants', async () => {
300 const f = await fixture();
301 const other = await fixture();
302 const item = await plan(f, 'selected_members');
303 await grant(f, item);
304 await pool.query('update plan_item set family_id=$2 where id=$1', [item, other.familyId]);
305 assert.equal(await canView(f.selected, item), false);
306 assert.equal((await pool.query('select 1 from sharing_grant where resource_id=$1', [item])).rowCount, 0);
307 });
308
309 test('production with no sensitive flag remains closed', async () => {
310 const f = await fixture();
311 const previous = process.env.NODE_ENV;
312 process.env.NODE_ENV = 'production';
313 try {
314 const base = await serve({});
315 const result = await request(base, '/v1/me/menstrual-cycles', { actor: f.child });
316 assert.equal(result.status, 503);
317 assert.equal(result.body.error, 'sensitive_features_disabled');
318 } finally {
319 if (previous === undefined) delete process.env.NODE_ENV; else process.env.NODE_ENV = previous;
320 }
321 });
322
323 test('deleting and recreating a selected member cannot revive a previous grant', async () => {
324 const f = await fixture();
325 const item = await plan(f, 'selected_members');
326 await grant(f, item);
327 await pool.query('delete from family_membership where family_id=$1 and user_id=$2', [f.familyId, f.selected.id]);
328 assert.equal(await canView(f.selected, item), false);
329 await pool.query("insert into family_membership(family_id,user_id,role) values($1,$2,'adult_member')", [f.familyId, f.selected.id]);
330 assert.equal(await canView(f.selected, item), false);
331 });
332
333 test('learning goals cannot reference another student\'s subject', async () => {
334 const f = await fixture();
335 const context = await pool.query("insert into life_context(user_id,kind,title) values($1,'student','Synthetic class') returning id", [f.child.id]);
336 const year = await pool.query("insert into academic_year(student_user_id,life_context_id,title,starts_on,ends_on) values($1,$2,'Synthetic year','2026-09-01','2027-06-01') returning id", [f.child.id, context.rows[0].id]);
337 const term = await pool.query("insert into academic_term(academic_year_id,title,starts_on,ends_on) values($1,'Synthetic term','2026-09-01','2026-12-01') returning id", [year.rows[0].id]);
338 const subject = await pool.query("insert into subject(student_user_id,academic_term_id,name) values($1,$2,'Synthetic math') returning id", [f.child.id, term.rows[0].id]);
339 const result = await request(defaultBase, '/v1/learning/goals', { method: 'POST', actor: f.outsider, body: { title: 'Synthetic foreign goal', subjectId: subject.rows[0].id } });
340 assert.equal(result.status, 403);
341 assert.equal((await pool.query('select 1 from learning_goal where owner_user_id=$1', [f.outsider.id])).rowCount, 0);
342 });
343
344 test('wellbeing-linked proposals cannot be created or accepted while sensitive features are disabled', async () => {
345 const f = await fixture();
346 const session = await request(enabledBase, '/v1/ai/sessions', { method: 'POST', actor: f.child, body: { kind: 'wellbeing' } });
347 const body = { sessionId: session.body.id, title: 'Synthetic reflection proposal', proposal: { steps: [] } };
348 assert.equal((await request(defaultBase, '/v1/ai/proposals', { method: 'POST', actor: f.child, body })).status, 503);
349 const proposal = await request(enabledBase, '/v1/ai/proposals', { method: 'POST', actor: f.child, body });
350 assert.equal(proposal.status, 201);
351 assert.equal((await request(defaultBase, `/v1/ai/proposals/${proposal.body.id}`, { method: 'PATCH', actor: f.child, body: { status: 'accepted' } })).status, 503);
352 assert.equal((await pool.query('select status from ai_plan_proposal where id=$1', [proposal.body.id])).rows[0].status, 'proposed');
353 });
354
355 test('study guidance does not create sensitive wellbeing events while the feature is disabled', async () => {
356 const f = await fixture();
357 const session = await request(defaultBase, '/v1/ai/sessions', { method: 'POST', actor: f.child, body: { kind: 'study' } });
358 assert.equal(session.status, 201);
359 const reply = await request(defaultBase, `/v1/ai/sessions/${session.body.id}/messages`, { method: 'POST', actor: f.child, body: { message: 'Synthetic safety regression: self-harm' } });
360 assert.equal(reply.status, 200);
361 assert.match(reply.body.body, /کمک فوری/);
362 assert.equal((await pool.query('select 1 from wellbeing_safety_event where owner_user_id=$1', [f.child.id])).rowCount, 0);
363 });