LifeMate — Personal, Family & Learning Companion

feat/weekly-planner-android
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 187 lines 13.5 KB
Raw
1 import test, { after } from 'node:test';
2 import assert from 'node:assert/strict';
3 import crypto from 'node:crypto';
4 import fs from 'node:fs/promises';
5 import jwt from 'jsonwebtoken';
6 import pg from 'pg';
7
8 assert.ok(process.env.DATABASE_URL, 'Use a migrated synthetic PostgreSQL database');
9 assert.ok(process.env.JWT_SECRET?.length >= 32, 'Use a synthetic JWT secret');
10 const { app, pool } = await import('../src/server.js');
11 const users = [];
12 const families = [];
13 let server = app.listen(0, '127.0.0.1');
14 await new Promise((resolve) => server.once('listening', resolve));
15 let base = `http://127.0.0.1:${server.address().port}`;
16
17 after(async () => {
18 await new Promise((resolve) => server.close(resolve));
19 try {
20 if (families.length) {
21 await pool.query('delete from access_audit where family_id=any($1::uuid[])', [families]);
22 await pool.query('delete from family_workspace where id=any($1::uuid[])', [families]);
23 }
24 if (users.length) await pool.query('delete from app_user where id=any($1::uuid[])', [users]);
25 } finally { await pool.end(); }
26 });
27
28 async function user() {
29 const id = crypto.randomUUID(), sid = crypto.randomUUID();
30 await pool.query('insert into app_user(id,identity_subject,email_normalized,email_verified_at) values($1,$2,$3,now())', [id, `profile-test:${id}`, `profile-${id}@example.test`]);
31 users.push(id);
32 await pool.query("insert into profile(user_id,display_name,theme_preference) values($1,'Synthetic Profile','adult_blue')", [id]);
33 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.randomBytes(32).toString('hex')]);
34 return { id, token: jwt.sign({ sub: id, sid, aud: 'lifemate-api' }, process.env.JWT_SECRET, { issuer: 'lifemate', expiresIn: '15m' }) };
35 }
36
37 async function fixture() {
38 const [child, parent, outsider] = await Promise.all([user(), user(), user()]);
39 const familyId = crypto.randomUUID();
40 await pool.query("insert into family_workspace(id,name,created_by) values($1,'Synthetic Profile Family',$2)", [familyId, parent.id]);
41 families.push(familyId);
42 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]);
43 await pool.query('insert into guardian_relationship(family_id,guardian_user_id,minor_user_id) values($1,$2,$3)', [familyId, parent.id, child.id]);
44 return { child, parent, outsider, familyId };
45 }
46
47 async function request(path, { method = 'GET', actor, body } = {}) {
48 const response = await fetch(base + path, { method, headers: { 'content-type': 'application/json', ...(actor ? { authorization: `Bearer ${actor.token}` } : {}) }, body: body === undefined ? undefined : JSON.stringify(body) });
49 const text = await response.text();
50 return { status: response.status, body: text && response.headers.get('content-type')?.includes('application/json') ? JSON.parse(text) : text };
51 }
52
53 test('profile category has an explicit adult default and edits never change family roles or theme', async () => {
54 const f = await fixture();
55 const initial = await request('/v1/profile', { actor: f.child });
56 assert.equal(initial.status, 200);
57 assert.equal(initial.body.profile_category, 'adult');
58 const updated = await request('/v1/profile', { method: 'PATCH', actor: f.parent, body: { displayName: 'ویرایش ساختگی', profileCategory: 'girl_minor' } });
59 assert.equal(updated.status, 200);
60 assert.equal(updated.body.profile_category, 'girl_minor');
61 assert.equal(updated.body.theme_preference, 'adult_blue');
62 assert.equal((await pool.query('select role from family_membership where family_id=$1 and user_id=$2', [f.familyId, f.parent.id])).rows[0].role, 'parent_guardian');
63 const changedTheme = await request('/v1/profile', { method: 'PATCH', actor: f.parent, body: { themePreference: 'boy_blue' } });
64 assert.equal(changedTheme.body.profile_category, 'girl_minor');
65 assert.equal(changedTheme.body.display_name, 'ویرایش ساختگی');
66 await pool.query("update family_membership set role='adult_member',ended_at=now() where family_id=$1 and user_id=$2", [f.familyId, f.parent.id]);
67 const read = await request('/v1/profile', { actor: f.parent });
68 assert.equal(read.body.profile_category, 'girl_minor');
69 assert.equal(read.body.theme_preference, 'boy_blue');
70 });
71
72 test('profile validation returns 400 for invalid real calendar dates and categories without partial writes', async () => {
73 const actor = await user();
74 for (const birthDate of ['not-a-date', '2026-02-30', '2026-13-01', '2008-02-29T00:00:00Z', 20080229]) {
75 const bad = await request('/v1/profile', { method: 'PATCH', actor, body: { displayName: 'Must Not Save', birthDate } });
76 assert.equal(bad.status, 400, String(birthDate));
77 assert.equal(bad.body.error, 'invalid_birth_date');
78 }
79 assert.equal((await request('/v1/profile', { method: 'PATCH', actor, body: { profileCategory: 'parent_guardian' } })).status, 400);
80 assert.equal((await request('/v1/profile', { method: 'PATCH', actor, body: { displayName: '' } })).status, 400);
81 assert.equal((await request('/v1/profile', { method: 'PATCH', actor, body: { themePreference: 'unknown' } })).status, 400);
82 assert.equal((await request('/v1/profile', { actor })).body.display_name, 'Synthetic Profile');
83 const valid = await request('/v1/profile', { method: 'PATCH', actor, body: { birthDate: '2008-02-29', profileCategory: 'boy_minor', themePreference: 'custom' } });
84 assert.equal(valid.status, 200);
85 const saved = (await pool.query('select birth_date::text,profile_category,theme_preference from profile where user_id=$1', [actor.id])).rows[0];
86 assert.deepEqual(saved, { birth_date: '2008-02-29', profile_category: 'boy_minor', theme_preference: 'custom' });
87 });
88
89 test('both profile date aliases reject invalid dates and retain the previous calendar day', async () => {
90 const actor = await user();
91 await pool.query("update profile set birth_date='2008-02-29' where user_id=$1", [actor.id]);
92 for (const path of ['/v1/profile', '/v1/me/iran-profile']) {
93 for (const birthDate of ['2026-02-30', 'invalid-private-birthday', '2026-13-01']) {
94 const result = await request(path, { method: 'PATCH', actor, body: { birthDate } });
95 assert.equal(result.status, 400, path);
96 assert.equal(result.body.error, 'invalid_birth_date');
97 }
98 }
99 assert.equal((await pool.query('select birth_date::text from profile where user_id=$1', [actor.id])).rows[0].birth_date, '2008-02-29');
100 });
101
102 test('profile and learning CRUD reject missing sessions and cannot target another profile', async () => {
103 const f = await fixture();
104 const id = crypto.randomUUID();
105 for (const [method, path] of [['GET', '/v1/profile'], ['PATCH', '/v1/profile'], ['GET', '/v1/learning/goals'], ['POST', '/v1/learning/goals'], ['GET', `/v1/learning/goals/${id}`], ['PATCH', `/v1/learning/goals/${id}`], ['DELETE', `/v1/learning/goals/${id}`]]) {
106 assert.equal((await request(path, { method, body: method === 'GET' ? undefined : {} })).status, 401, path);
107 }
108 const forged = await request('/v1/profile', { method: 'PATCH', actor: f.child, body: { userId: f.parent.id, displayName: 'Owned Change', profileCategory: 'boy_minor' } });
109 assert.equal(forged.status, 200);
110 assert.equal((await request('/v1/profile', { actor: f.parent })).body.display_name, 'Synthetic Profile');
111 assert.equal((await request('/v1/profile', { actor: f.child })).body.display_name, 'Owned Change');
112 });
113
114 test('learning goals create, read, edit and safely archive under the same owner and stable ID', async () => {
115 const f = await fixture();
116 const created = await request('/v1/learning/goals', { method: 'POST', actor: f.child, body: { title: 'هدف ساختگی', target: 'Private synthetic target' } });
117 assert.equal(created.status, 201);
118 const path = `/v1/learning/goals/${created.body.id}`;
119 const read = await request(path, { actor: f.child });
120 assert.equal(read.status, 200);
121 assert.equal(read.body.target, 'Private synthetic target');
122 for (const viewer of [f.parent, f.outsider]) {
123 assert.equal((await request(path, { actor: viewer })).status, 404);
124 assert.equal((await request(path, { method: 'PATCH', actor: viewer, body: { title: 'Forbidden' } })).status, 404);
125 assert.equal((await request(path, { method: 'DELETE', actor: viewer })).status, 404);
126 assert.equal((await request('/v1/learning/goals', { actor: viewer })).body.items.length, 0);
127 }
128 const checkin = await request('/v1/learning/checkins', { method: 'POST', actor: f.child, body: { learningGoalId: created.body.id, confidence: 3, difficulty: 3, note: 'Private synthetic note' } });
129 assert.equal(checkin.status, 201);
130 const edited = await request(path, { method: 'PATCH', actor: f.child, body: { title: 'ویرایش هدف', target: null, status: 'completed' } });
131 assert.equal(edited.status, 200);
132 assert.equal(edited.body.id, created.body.id);
133 assert.equal(edited.body.title, 'ویرایش هدف');
134 assert.equal(edited.body.target, null);
135 await new Promise((resolve) => server.close(resolve));
136 server = app.listen(0, '127.0.0.1');
137 await new Promise((resolve) => server.once('listening', resolve));
138 base = `http://127.0.0.1:${server.address().port}`;
139 assert.equal((await request(path, { actor: f.child })).body.status, 'completed');
140 for (let attempt = 0; attempt < 2; attempt++) assert.equal((await request(path, { method: 'DELETE', actor: f.child })).status, 204);
141 assert.equal((await request('/v1/learning/goals', { actor: f.child })).body.items.length, 0);
142 assert.equal((await request(path, { actor: f.child })).body.status, 'archived');
143 assert.equal((await request(path, { method: 'PATCH', actor: f.child, body: { status: 'active' } })).status, 409);
144 const retained = (await pool.query('select learning_goal_id,note from learning_checkin where id=$1', [checkin.body.id])).rows[0];
145 assert.deepEqual(retained, { learning_goal_id: created.body.id, note: 'Private synthetic note' });
146 });
147
148 test('learning goal edits validate ownership of subjects, IDs and allowed statuses', async () => {
149 const f = await fixture();
150 const invalidCreate = await request('/v1/learning/goals', { method: 'POST', actor: f.child, body: { title: 'Synthetic goal', subjectId: 'not-a-uuid' } });
151 assert.equal(invalidCreate.status, 400);
152 assert.equal(invalidCreate.body.error, 'invalid_subject_id');
153 const created = await request('/v1/learning/goals', { method: 'POST', actor: f.child, body: { title: 'Synthetic goal' } });
154 const path = `/v1/learning/goals/${created.body.id}`;
155 const context = await pool.query("insert into life_context(user_id,kind,title) values($1,'student','Synthetic class') returning id", [f.outsider.id]);
156 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.outsider.id, context.rows[0].id]);
157 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]);
158 const subject = await pool.query("insert into subject(student_user_id,academic_term_id,name) values($1,$2,'Synthetic math') returning id", [f.outsider.id, term.rows[0].id]);
159 assert.equal((await request(path, { method: 'PATCH', actor: f.child, body: { subjectId: subject.rows[0].id } })).status, 403);
160 assert.equal((await request(path, { method: 'PATCH', actor: f.child, body: { status: 'achieved' } })).status, 400);
161 assert.equal((await request(path, { method: 'PATCH', actor: f.child, body: { title: '' } })).status, 400);
162 assert.equal((await request('/v1/learning/goals/not-a-uuid', { method: 'PATCH', actor: f.child, body: { title: 'Valid' } })).status, 400);
163 assert.equal((await request(path, { actor: f.child })).body.title, 'Synthetic goal');
164 });
165
166 test('profile migration derives legacy categories from themes only and new records default to adult', async () => {
167 // A real PostgreSQL session with a temporary legacy table exercises the exact
168 // migration without changing the already-migrated shared test schema.
169 const client = new pg.Client({ connectionString: process.env.DATABASE_URL });
170 await client.connect();
171 try {
172 await client.query('create temporary table profile(user_id uuid primary key,theme_preference text)');
173 await client.query('create temporary table family_membership(user_id uuid,role text)');
174 const legacy = [['girl_pink', 'girl_minor', 'adult_member'], ['boy_blue', 'boy_minor', 'parent_guardian'], ['adult_blue', 'adult', 'teen_minor'], ['custom', 'adult', 'teen_minor'], [null, 'adult', 'parent_guardian']];
175 for (const [theme, , role] of legacy) {
176 const id = crypto.randomUUID();
177 await client.query('insert into profile(user_id,theme_preference) values($1,$2)', [id, theme]);
178 await client.query('insert into family_membership(user_id,role) values($1,$2)', [id, role]);
179 }
180 await client.query(await fs.readFile(new URL('../migrations/0011_profile_category.sql', import.meta.url), 'utf8'));
181 const rows = await client.query('select theme_preference,profile_category from profile');
182 for (const [theme, expected] of legacy) assert.equal(rows.rows.find((row) => row.theme_preference === theme).profile_category, expected);
183 const created = await client.query("insert into profile(user_id,theme_preference) values($1,'girl_pink') returning profile_category", [crypto.randomUUID()]);
184 assert.equal(created.rows[0].profile_category, 'adult');
185 await assert.rejects(client.query("insert into profile(user_id,profile_category) values($1,'parent_guardian')", [crypto.randomUUID()]), (error) => error.code === '23514');
186 } finally { await client.end(); }
187 });