LifeMate — Personal, Family & Learning Companion

feat/flutter-mobile-navigation
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 266 lines 21.7 KB
Raw
1 // Synthetic accounts on loopback PostgreSQL only; never invokes SMS, email or AI.
2 import test, { after } from 'node:test';
3 import assert from 'node:assert/strict';
4 import crypto from 'node:crypto';
5 import express from 'express';
6 import jwt from 'jsonwebtoken';
7 import pg from 'pg';
8 import { createSessionAuth } from '../src/session_auth.js';
9 import { createChildIdentityRouter } from '../src/child_identity.js';
10
11 const location = new URL(process.env.TEST_FIXTURE_DATABASE_URL ?? process.env.DATABASE_URL);
12 assert.ok(['127.0.0.1', 'localhost', '[::1]'].includes(location.hostname));
13 assert.match(location.pathname, /^\/(?:lifeguide_roles_source_[a-f0-9]{16}|lifemate_ci|lifeguide_\w*test\w*)$/);
14 const marker = 'child-sandbox-' + crypto.randomUUID();
15 const pool = new pg.Pool({ connectionString: location.href, application_name: marker });
16 const secret = 'synthetic-child-sandbox-signing-fixture-not-a-live-key';
17 const users = [], families = [], servers = [];
18 const consentVersion = 'sandbox-child-consent-v1-not-legal';
19 async function start(env = { NODE_ENV: 'test', ENABLE_CHILD_IDENTITY_SANDBOX: 'true' }) {
20 const app = express(); app.use(express.json());
21 app.use('/v1', createChildIdentityRouter({ pool, jwtSecret: secret,
22 auth: createSessionAuth({ pool, jwtSecret: secret, env }), env }));
23 app.use((_req, res) => res.status(404).json({ error: 'not_found' }));
24 app.use((_error, _req, res, _next) => res.status(500).json({ error: 'test_unexpected_server_error' }));
25 const server = app.listen(0, '127.0.0.1'); servers.push(server);
26 await new Promise(resolve => server.once('listening', resolve));
27 return 'http://127.0.0.1:' + server.address().port + '/v1';
28 }
29 const base = await start();
30 after(async () => {
31 await Promise.all(servers.map(server => new Promise(resolve => server.close(resolve))));
32 try {
33 await pool.query('delete from access_audit where family_id=any($1::uuid[]) or actor_user_id=any($2::uuid[])', [families, users]);
34 await pool.query('delete from family_workspace where id=any($1::uuid[])', [families]);
35 await pool.query('delete from auth_session where user_id=any($1::uuid[])', [users]);
36 await pool.query('delete from app_user where id=any($1::uuid[])', [users]);
37 } finally { await pool.end(); }
38 });
39 async function actor({ birthDate = '1985-01-01' } = {}) {
40 const id = crypto.randomUUID(), sid = crypto.randomUUID(); users.push(id);
41 await pool.query('insert into app_user(id,identity_subject,email_normalized) values($1,$2,$3)',
42 [id, marker + ':' + id, 'sandbox-' + id + '@example.test']);
43 await pool.query("insert into profile(user_id,display_name,birth_date) values($1,'Synthetic Adult',$2)", [id, birthDate]);
44 await pool.query("insert into auth_session(id,user_id,refresh_digest,expires_at) values($1,$2,$3,clock_timestamp()+interval '1 day')", [sid, id, crypto.randomUUID()]);
45 return { id, sid, token: jwt.sign({ sub: id, sid, aud: 'lifemate-api' }, secret, { issuer: 'lifemate', expiresIn: '15m' }) };
46 }
47 async function family(owner, members = []) {
48 const id = crypto.randomUUID(); families.push(id);
49 await pool.query("insert into family_workspace(id,name,created_by) values($1,'Synthetic child sandbox',$2)", [id, owner.id]);
50 await pool.query("insert into family_membership(family_id,user_id,role,is_admin) values($1,$2,'parent_guardian',true)", [id, owner.id]);
51 for (const member of members) await pool.query('insert into family_membership(family_id,user_id,role,is_admin) values($1,$2,$3,$4)',
52 [id, member.user.id, member.role ?? 'parent_guardian', member.admin ?? false]);
53 return id;
54 }
55 async function request(who, method, path, body, origin = base) {
56 const response = await fetch(origin + path, { method, headers: { 'content-type': 'application/json',
57 ...(who ? { authorization: 'Bearer ' + who.token } : {}) }, body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(10000) });
58 return { status: response.status, body: await response.json(), cache: response.headers.get('cache-control') };
59 }
60 const createBody = () => ({ displayName: 'Synthetic Child', birthDate: '2015-03-12', profileCategory: 'girl_minor',
61 consentVersion, consentAccepted: true, synthetic: true });
62 async function child(owner, familyId) {
63 const result = await request(owner, 'POST', `/families/${familyId}/children`, createBody());
64 assert.equal(result.status, 201); users.push(result.body.child.userId); return result.body.child;
65 }
66 const issueDevice = (owner, familyId, childId) => request(owner, 'POST', `/families/${familyId}/children/${childId}/device-invitations`, { synthetic: true });
67 const acceptDevice = token => request(null, 'POST', '/child-devices/accept', { token });
68 const issueGuardian = (owner, familyId, childId, recipient) => request(owner, 'POST', `/families/${familyId}/children/${childId}/guardian-invitations`, { guardianUserId: recipient.id });
69 const acceptGuardian = (recipient, token) => request(recipient, 'POST', '/guardian-invitations/accept', { token });
70 async function observedWait() {
71 for (let i = 0; i < 300; i++) {
72 if ((await pool.query("select 1 from pg_stat_activity where application_name=$1 and wait_event_type='Lock'", [marker])).rowCount) return;
73 await new Promise(resolve => setTimeout(resolve, 10));
74 }
75 assert.fail('Expected real PostgreSQL lock wait');
76 }
77 async function blockFamily(familyId, operation, mutation) {
78 const blocker = await pool.connect();
79 try {
80 await blocker.query('begin'); await blocker.query('select id from family_workspace where id=$1 for update', [familyId]);
81 const pending = operation(); await observedWait(); await mutation(blocker); await blocker.query('commit'); return await pending;
82 } finally { await blocker.query('rollback'); blocker.release(); }
83 }
84
85 test('sandbox is disabled unless explicitly enabled in test/development; production cannot opt in', async () => {
86 for (const env of [{ NODE_ENV: 'production', ENABLE_CHILD_IDENTITY_SANDBOX: 'true' }, { NODE_ENV: 'test' },
87 { NODE_ENV: 'staging', ENABLE_CHILD_IDENTITY_SANDBOX: 'true' }]) {
88 const origin = await start(env);
89 const result = await request(null, 'POST', '/child-devices/accept', { token: 'synthetic' }, origin);
90 assert.equal(result.status, 503); assert.equal(result.body.error, 'child_identity_sandbox_disabled');
91 }
92 });
93
94 test('adult parent admin creates contactless child, initial guardian and versioned synthetic consent atomically', async () => {
95 const owner = await actor(), id = await family(owner), created = await child(owner, id);
96 const row = (await pool.query(`select u.email_normalized,u.phone_normalized,u.is_managed_child,p.birth_date::text,p.profile_category,
97 m.role,m.is_admin,g.active,c.text_version,c.text_digest,mc.creator_user_id,
98 exists(select 1 from auth_credential where user_id=u.id) has_credential
99 from app_user u join profile p on p.user_id=u.id join family_membership m on m.user_id=u.id
100 join managed_child mc on mc.user_id=u.id join child_consent c on c.child_user_id=u.id
101 join guardian_relationship g on g.minor_user_id=u.id where u.id=$1`, [created.userId])).rows[0];
102 assert.equal(row.email_normalized, null); assert.equal(row.phone_normalized, null); assert.equal(row.is_managed_child, true);
103 assert.equal(row.birth_date, '2015-03-12'); assert.equal(row.profile_category, 'girl_minor'); assert.equal(row.role, 'teen_minor');
104 assert.equal(row.is_admin, false); assert.equal(row.active, true); assert.equal(row.has_credential, false);
105 assert.equal(row.creator_user_id, owner.id); assert.equal(row.text_version, consentVersion); assert.match(row.text_digest, /^[a-f0-9]{64}$/);
106 assert.equal((await pool.query('select count(*)::int n from auth_session where user_id=$1', [created.userId])).rows[0].n, 0);
107 });
108
109 test('creation rejects malformed DOB/category/consent and unauthorized or age-unknown parent without rows', async () => {
110 const owner = await actor(), unknown = await actor({ birthDate: null }), minor = await actor({ birthDate: '2015-01-01' }), outsider = await actor();
111 const id = await family(owner, [{ user: unknown, admin: true }, { user: minor, admin: true }]);
112 for (const patch of [{ birthDate: '2015-02-30' }, { birthDate: '2999-01-01' }, { birthDate: '1980-01-01' },
113 { birthDate: null }, { profileCategory: 'adult' }, { consentAccepted: false }, { consentVersion: 'unapproved' }, { synthetic: false },
114 { phone: '+000' }, { birthDate: ['2015-03-12'] }, { displayName: '\u0000' }]) {
115 assert.equal((await request(owner, 'POST', `/families/${id}/children`, { ...createBody(), ...patch })).status, 400);
116 }
117 for (const candidate of [unknown, minor, outsider]) assert.equal((await request(candidate, 'POST', `/families/${id}/children`, createBody())).status, 403);
118 assert.equal((await pool.query('select count(*)::int n from managed_child where family_id=$1', [id])).rows[0].n, 0);
119 });
120
121 test('device redemption stores only digest, is single-use under concurrency and mints education scope', async () => {
122 const owner = await actor(), id = await family(owner), created = await child(owner, id), invitation = await issueDevice(owner, id, created.userId);
123 assert.equal(invitation.status, 201); assert.equal(invitation.cache, 'no-store');
124 assert.match(invitation.body.token, /^[A-Za-z0-9_-]{43}$/);
125 const stored = (await pool.query('select token_digest from child_device_invitation where child_user_id=$1', [created.userId])).rows[0];
126 assert.equal(stored.token_digest, crypto.createHash('sha256').update(invitation.body.token).digest('hex'));
127 const responses = await Promise.all([acceptDevice(invitation.body.token), acceptDevice(invitation.body.token)]);
128 assert.deepEqual(responses.map(r => r.status).sort(), [200, 400]);
129 const accepted = responses.find(r => r.status === 200); assert.equal(accepted.cache, 'no-store');
130 const claims = jwt.verify(accepted.body.accessToken, secret, { issuer: 'lifemate', audience: 'lifemate-api' });
131 assert.equal(claims.sub, created.userId); assert.equal(claims.scope, 'child_education');
132 const session = (await pool.query('select access_scope from auth_session where id=$1', [claims.sid])).rows[0];
133 assert.equal(session.access_scope, 'child_education');
134 const visibility = await request({ token: accepted.body.accessToken }, 'GET', '/child-visibility');
135 assert.equal(visibility.status, 200); assert.equal(visibility.body.guardians[0].userId, owner.id);
136 assert.equal(visibility.body.privateScopeGrantedByThisFlow, false);
137 assert.equal((await request(owner, 'GET', '/child-visibility')).status, 403);
138 });
139
140 test('recovery issuance revokes all child sessions and old invitations before new code is returned', async () => {
141 const owner = await actor(), id = await family(owner), created = await child(owner, id), first = await issueDevice(owner, id, created.userId);
142 const accepted = await acceptDevice(first.body.token); assert.equal(accepted.status, 200);
143 const pending = await issueDevice(owner, id, created.userId); assert.equal(pending.status, 201);
144 assert.equal((await request({ token: accepted.body.accessToken }, 'GET', '/child-visibility')).status, 401);
145 const last = await issueDevice(owner, id, created.userId); assert.equal((await acceptDevice(pending.body.token)).status, 400);
146 const restored = await acceptDevice(last.body.token); assert.equal(restored.status, 200);
147 assert.equal(jwt.decode(restored.body.accessToken).scope, 'child_education');
148 assert.equal((await pool.query('select count(*)::int n from auth_session where user_id=$1 and revoked_at is null', [created.userId])).rows[0].n, 1);
149 });
150
151 test('creator confirmation plus recipient acceptance is required for second guardian; other admin cannot assign', async () => {
152 const owner = await actor(), recipient = await actor(), admin = await actor(), outsider = await actor();
153 const id = await family(owner, [{ user: recipient }, { user: admin, admin: true }]), created = await child(owner, id);
154 assert.equal((await issueGuardian(admin, id, created.userId, recipient)).status, 403);
155 assert.equal((await issueGuardian(owner, id, created.userId, outsider)).status, 403);
156 const invitation = await issueGuardian(owner, id, created.userId, recipient); assert.equal(invitation.status, 201);
157 assert.equal((await pool.query('select count(*)::int n from guardian_relationship where family_id=$1 and minor_user_id=$2', [id, created.userId])).rows[0].n, 1);
158 assert.equal((await acceptGuardian(admin, invitation.body.token)).status, 400);
159 assert.equal((await acceptGuardian(recipient, invitation.body.token)).status, 200);
160 assert.equal((await acceptGuardian(recipient, invitation.body.token)).status, 400);
161 assert.equal((await pool.query('select count(*)::int n from guardian_relationship where family_id=$1 and minor_user_id=$2 and active', [id, created.userId])).rows[0].n, 2);
162 assert.equal((await issueDevice(recipient, id, created.userId)).status, 201);
163 });
164
165 test('consent revocation is creator-only and revokes sessions, relationships and every outstanding invitation', async () => {
166 const owner = await actor(), recipient = await actor(), id = await family(owner, [{ user: recipient }]), created = await child(owner, id);
167 const code = await issueDevice(owner, id, created.userId), accepted = await acceptDevice(code.body.token);
168 const device = await issueDevice(owner, id, created.userId), guardian = await issueGuardian(owner, id, created.userId, recipient);
169 assert.equal((await request(recipient, 'DELETE', `/families/${id}/children/${created.userId}/consent`)).status, 403);
170 assert.equal((await request(owner, 'DELETE', `/families/${id}/children/${created.userId}/consent`)).status, 200);
171 assert.equal((await acceptDevice(device.body.token)).status, 400); assert.equal((await acceptGuardian(recipient, guardian.body.token)).status, 400);
172 assert.equal((await request({ token: accepted.body.accessToken }, 'GET', '/child-visibility')).status, 401);
173 assert.equal((await issueDevice(owner, id, created.userId)).status, 403);
174 assert.equal((await pool.query('select count(*)::int n from guardian_relationship where family_id=$1 and minor_user_id=$2 and active', [id, created.userId])).rows[0].n, 0);
175 });
176
177 test('device expiry and guardian revocation after actual lock waits prevent redemption without consuming tokens', async () => {
178 const owner = await actor(), recipient = await actor(), id = await family(owner, [{ user: recipient }]), created = await child(owner, id);
179 const device = await issueDevice(owner, id, created.userId);
180 const expired = await blockFamily(id, () => acceptDevice(device.body.token), blocker => blocker.query('update child_device_invitation set expires_at=clock_timestamp() where child_user_id=$1', [created.userId]));
181 assert.equal(expired.status, 400);
182 assert.equal((await pool.query('select used_at from child_device_invitation where token_digest=$1', [crypto.createHash('sha256').update(device.body.token).digest('hex')])).rows[0].used_at, null);
183 const guardian = await issueGuardian(owner, id, created.userId, recipient);
184 const revoked = await blockFamily(id, () => acceptGuardian(recipient, guardian.body.token), blocker => blocker.query('update guardian_relationship set active=false where family_id=$1 and guardian_user_id=$2', [id, owner.id]));
185 assert.equal(revoked.status, 400);
186 });
187
188 test('parent session expiry or authority change during family wait rolls back child creation', async () => {
189 for (const invalidation of ['session', 'membership', 'birth_date']) {
190 const owner = await actor(), id = await family(owner);
191 const result = await blockFamily(id, () => request(owner, 'POST', `/families/${id}/children`, createBody()), blocker =>
192 invalidation === 'session' ? blocker.query('update auth_session set expires_at=clock_timestamp() where id=$1', [owner.sid]) :
193 invalidation === 'membership' ? blocker.query('update family_membership set is_admin=false where family_id=$1 and user_id=$2', [id, owner.id]) :
194 blocker.query("update profile set birth_date='2015-01-01' where user_id=$1", [owner.id]));
195 assert.equal(result.status, invalidation === 'session' ? 401 : 403);
196 assert.equal((await pool.query('select count(*)::int n from managed_child where family_id=$1', [id])).rows[0].n, 0);
197 }
198 });
199
200 test('strict route identifiers and token bodies return 400 without PostgreSQL cast errors', async () => {
201 const owner = await actor(), id = await family(owner), created = await child(owner, id);
202 assert.equal((await request(owner, 'POST', '/families/not-a-uuid/children', createBody())).status, 400);
203 assert.equal((await request(owner, 'POST', `/families/${id}/children/not-a-uuid/device-invitations`, { synthetic: true })).status, 400);
204 assert.equal((await request(owner, 'POST', `/families/${id}/children/${created.userId}/guardian-invitations`, { guardianUserId: ['invalid'] })).status, 400);
205 for (const body of [{ token: null }, { token: [] }, { token: 'unknown' }, { token: 'a'.repeat(43), extra: true }]) {
206 assert.equal((await request(null, 'POST', '/child-devices/accept', body)).status, 400);
207 }
208 assert.equal((await acceptDevice('a'.repeat(43))).body.error, 'invalid_or_expired_invitation');
209 });
210
211 test('cross-family child and inactive guardian cannot issue or redeem an existing device invitation', async () => {
212 const owner = await actor(), outsider = await actor(), first = await family(owner), second = await family(outsider), created = await child(owner, first);
213 assert.equal((await issueDevice(outsider, second, created.userId)).status, 403);
214 assert.equal((await issueDevice(outsider, first, created.userId)).status, 403);
215 const invitation = await issueDevice(owner, first, created.userId);
216 await pool.query('update family_membership set ended_at=clock_timestamp() where family_id=$1 and user_id=$2', [first, owner.id]);
217 assert.equal((await acceptDevice(invitation.body.token)).status, 400);
218 assert.equal((await pool.query('select count(*)::int n from auth_session where user_id=$1', [created.userId])).rows[0].n, 0);
219 });
220
221 test('final parent session-row wait rechecks expiry and rolls back earlier creation writes and audit', async () => {
222 const owner = await actor(), id = await family(owner), blocker = await pool.connect();
223 try {
224 await blocker.query('begin'); await blocker.query('select id from auth_session where id=$1 for update', [owner.sid]);
225 const pending = request(owner, 'POST', `/families/${id}/children`, createBody()); await observedWait();
226 await blocker.query('update auth_session set expires_at=clock_timestamp() where id=$1', [owner.sid]);
227 await blocker.query('commit'); assert.equal((await pending).status, 401);
228 assert.equal((await pool.query('select count(*)::int n from managed_child where family_id=$1', [id])).rows[0].n, 0);
229 assert.equal((await pool.query('select count(*)::int n from access_audit where family_id=$1', [id])).rows[0].n, 0);
230 } finally { await blocker.query('rollback'); blocker.release(); }
231 });
232
233 test('guardian token expiration during final recipient session-row wait is rechecked before consumption', async () => {
234 const owner = await actor(), recipient = await actor(), id = await family(owner, [{ user: recipient }]), created = await child(owner, id);
235 const invitation = await issueGuardian(owner, id, created.userId, recipient), blocker = await pool.connect();
236 const tokenDigest = crypto.createHash('sha256').update(invitation.body.token).digest('hex');
237 const deadline = (await pool.query("update guardian_invitation set expires_at=clock_timestamp()+interval '2 seconds' where token_digest=$1 returning expires_at", [tokenDigest])).rows[0].expires_at;
238 try {
239 await blocker.query('begin'); await blocker.query('select id from auth_session where id=$1 for update', [recipient.sid]);
240 const pending = acceptGuardian(recipient, invitation.body.token); await observedWait();
241 // Invitation row is held by the request. Observe the real DB wall clock
242 // passing its deadline without trying to mutate the locked invitation.
243 while (!(await blocker.query('select clock_timestamp()>=$1::timestamptz expired', [deadline])).rows[0].expired)
244 await new Promise(resolve => setTimeout(resolve, 10));
245 await blocker.query('commit'); assert.equal((await pending).status, 400);
246 assert.equal((await pool.query('select used_at from guardian_invitation where token_digest=$1', [tokenDigest])).rows[0].used_at, null);
247 } finally { await blocker.query('rollback'); blocker.release(); }
248 });
249
250 test('creator can revoke accepted second guardian and its issued devices; another admin cannot', async () => {
251 const owner = await actor(), recipient = await actor(), admin = await actor(), id = await family(owner, [{ user: recipient }, { user: admin, admin: true }]);
252 const created = await child(owner, id), invitation = await issueGuardian(owner, id, created.userId, recipient);
253 assert.equal((await acceptGuardian(recipient, invitation.body.token)).status, 200);
254 const device = await issueDevice(recipient, id, created.userId), accepted = await acceptDevice(device.body.token);
255 assert.equal(accepted.status, 200);
256 const pending = await issueDevice(recipient, id, created.userId);
257 const revoke = who => request(who, 'DELETE', `/families/${id}/children/${created.userId}/guardians/${recipient.id}`);
258 assert.equal((await revoke(admin)).status, 403);
259 assert.equal((await request(owner, 'DELETE', `/families/${id}/children/${created.userId}/guardians/${owner.id}`)).status, 409);
260 assert.equal((await revoke(owner)).status, 200);
261 assert.equal((await pool.query('select active from guardian_relationship where family_id=$1 and guardian_user_id=$2 and minor_user_id=$3', [id, recipient.id, created.userId])).rows[0].active, false);
262 assert.ok((await pool.query('select revoked_at from guardian_invitation where token_digest=$1', [crypto.createHash('sha256').update(invitation.body.token).digest('hex')])).rows[0].revoked_at);
263 assert.equal((await acceptDevice(pending.body.token)).status, 400);
264 assert.equal((await request({ token: accepted.body.accessToken }, 'GET', '/child-visibility')).status, 401);
265 assert.equal((await issueDevice(recipient, id, created.userId)).status, 403);
266 });