LifeMate — Personal, Family & Learning Companion

fix/study-duration-display
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 555 lines 44.2 KB
Raw
1 import test, { after, before, describe } from 'node:test';
2 import assert from 'node:assert/strict';
3 import crypto from 'node:crypto';
4 import { spawn } from 'node:child_process';
5 import { once } from 'node:events';
6 import net from 'node:net';
7 import pg from 'pg';
8 import jwt from 'jsonwebtoken';
9
10 const uuid = () => crypto.randomUUID();
11
12 describe('family lifecycle real entrypoint and synthetic PostgreSQL', { concurrency: false }, () => {
13 let pool, child, base;
14 const users = [], families = [];
15 const applicationName = `family-lifecycle-fixture-${uuid()}`;
16 const secret = 'synthetic-family-lifecycle-signing-secret-not-for-production';
17
18 async function start() {
19 const listener = net.createServer().listen(0, '127.0.0.1');
20 await once(listener, 'listening');
21 const port = listener.address().port;
22 await new Promise(resolve => listener.close(resolve));
23 base = `http://127.0.0.1:${port}`;
24 const env = { ...process.env, JWT_SECRET: secret, NODE_ENV: 'production', PORT: String(port), PGAPPNAME: applicationName,
25 SMS_PROVIDER: 'disabled', SMS_PROVIDER_URL: '', SMS_PROVIDER_TOKEN: '', EMAIL_FROM: '', RESEND_API_KEY: '',
26 SMTP_HOST: '', SMTP_USER: '', SMTP_PASSWORD: '', AI_API_KEY: '', AI_BASE_URL: '', AI_MODEL: '', OPENAI_API_KEY: '',
27 CORS_ORIGINS: '', TRUSTED_PROXY_CIDRS: '', ENABLE_SENSITIVE_FEATURES: 'false',
28 RATE_LIMIT_AUTH_MAX: '2000', RATE_LIMIT_GENERAL_MAX: '8000' };
29 delete env.TEST_FIXTURE_DATABASE_URL;
30 child = spawn(process.execPath, ['src/entrypoint.js'], { cwd: new URL('../', import.meta.url), env,
31 stdio: ['ignore', 'pipe', 'pipe'] });
32 let startup = '';
33 // Do not print fixture HTTP telemetry, JWTs or database connection strings.
34 child.stderr.on('data', () => {});
35 await new Promise((resolve, reject) => {
36 const timeout = setTimeout(() => reject(new Error('Family fixture startup timed out')), 10000);
37 const ready = chunk => {
38 startup += chunk;
39 if (startup.includes('"type":"startup"')) {
40 clearTimeout(timeout); child.stdout.off('data', ready); child.stdout.on('data', () => {}); resolve();
41 }
42 };
43 child.stdout.on('data', ready);
44 child.once('error', () => { clearTimeout(timeout); reject(new Error('Family fixture start failed')); });
45 child.once('exit', () => {
46 if (!startup.includes('"type":"startup"')) { clearTimeout(timeout); reject(new Error('Family fixture exited early')); }
47 });
48 });
49 }
50 async function stop() {
51 if (child && child.exitCode === null && child.signalCode === null) {
52 const ended = once(child, 'close'); child.kill('SIGTERM'); await ended;
53 }
54 }
55 before(async () => {
56 assert.ok(process.env.DATABASE_URL, 'Migrated synthetic PostgreSQL fixture required');
57 const location = new URL(process.env.TEST_FIXTURE_DATABASE_URL ?? process.env.DATABASE_URL);
58 assert.ok(['localhost', '127.0.0.1', '[::1]', '::1'].includes(location.hostname), 'Only loopback test PostgreSQL allowed');
59 assert.ok(location.pathname.includes('test') || location.pathname === '/lifemate_ci' ||
60 /^\/lifeguide_roles_source_[a-f0-9]{16}$/.test(location.pathname), 'Explicit synthetic database required');
61 pool = new pg.Pool({ connectionString: process.env.TEST_FIXTURE_DATABASE_URL ?? process.env.DATABASE_URL });
62 await start();
63 });
64 after(async () => {
65 await stop(); if (!pool) return;
66 try {
67 await pool.query('delete from access_audit where family_id=any($1::uuid[]) or actor_user_id=any($2::uuid[])', [families, users]);
68 await pool.query('delete from family_workspace where id=any($1::uuid[])', [families]);
69 await pool.query('delete from app_user where id=any($1::uuid[])', [users]);
70 } finally { await pool.end(); }
71 });
72 async function actor({ birthDate = null, category = 'adult', claims = {} } = {}) {
73 const id = uuid(), sid = uuid(), email = `family-${id}@example.test`; users.push(id);
74 await pool.query('insert into app_user(id,identity_subject,email_normalized,email_verified_at) values($1,$2,$3,now())',
75 [id, `family-lifecycle:${id}`, email]);
76 await pool.query("insert into profile(user_id,display_name,birth_date,profile_category,theme_preference) values($1,'Synthetic Family',$2,$3,'adult_blue')", [id, birthDate, category]);
77 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()]);
78 return { id, sid, email, token: jwt.sign({ ...claims, sub: id, sid, aud: 'lifemate-api' }, secret,
79 { issuer: 'lifemate', expiresIn: '15m' }) };
80 }
81 async function family(admin, members = []) {
82 const id = uuid(); families.push(id);
83 await pool.query("insert into family_workspace(id,name,created_by) values($1,'Synthetic Lifecycle Family',$2)", [id, admin.id]);
84 await pool.query("insert into family_membership(family_id,user_id,role,is_admin) values($1,$2,'parent_guardian',true)", [id, admin.id]);
85 for (const member of members) await pool.query('insert into family_membership(family_id,user_id,role,is_admin) values($1,$2,$3,$4)',
86 [id, member.user.id, member.role ?? 'adult_member', member.admin ?? false]);
87 return id;
88 }
89 async function request(user, method, path, body) {
90 const response = await fetch(base + '/v1' + path, { method, headers: { 'content-type': 'application/json',
91 ...(user ? { authorization: `Bearer ${user.token}` } : {}) }, body: body === undefined ? undefined : JSON.stringify(body) });
92 const raw = await response.text();
93 return { status: response.status, body: raw && response.headers.get('content-type')?.includes('application/json') ? JSON.parse(raw) : raw || null };
94 }
95 const members = (user, id) => request(user, 'GET', `/families/${id}/members`);
96 const role = (user, id, target, body) => request(user, 'PATCH', `/families/${id}/members/${target.id}/role`, body);
97 const transfer = (user, id, body) => request(user, 'POST', `/families/${id}/admin-transfer`, body);
98 const invitations = (user, id, query = '') => request(user, 'GET', `/families/${id}/invitations${query}`);
99 const revoke = (user, id, invitationId, body) => request(user, 'PATCH', `/families/${id}/invitations/${invitationId}`, body);
100 const accept = (user, token) => request(user, 'POST', '/invitations/accept', { token });
101 async function member(id, user) {
102 return (await pool.query('select user_id,role,is_admin,version,ended_at from family_membership where family_id=$1 and user_id=$2', [id, user.id])).rows[0];
103 }
104 async function invite(admin, id, recipient, intendedRole = 'adult_member') {
105 const result = await request(admin, 'POST', `/families/${id}/invitations`, { email: recipient.email, role: intendedRole });
106 assert.equal(result.status, 201, JSON.stringify(result.body)); return result.body;
107 }
108 async function blockedOn(client, minimum = 1) {
109 const pid = (await client.query('select pg_backend_pid() pid')).rows[0].pid, deadline = Date.now() + 5000;
110 while (Date.now() < deadline) {
111 const result = await pool.query(`with recursive waits as (
112 select pid from pg_stat_activity where $2=any(pg_blocking_pids(pid))
113 union select a.pid from pg_stat_activity a join waits w on w.pid=any(pg_blocking_pids(a.pid))
114 ) select count(*)::int n from pg_stat_activity a join waits w on w.pid=a.pid
115 where a.application_name=$1`, [applicationName, pid]);
116 if (result.rows[0].n >= minimum) return;
117 await new Promise(resolve => setTimeout(resolve, 15));
118 }
119 assert.fail('API did not reach the observed PostgreSQL lock wait');
120 }
121 async function withFamilyBlocked(id, action) {
122 const blocker = await pool.connect();
123 try {
124 await blocker.query('begin'); await blocker.query('select id from family_workspace where id=$1 for update', [id]);
125 await action(blocker);
126 } finally { await blocker.query('rollback').catch(() => {}); blocker.release(); }
127 }
128
129 test('current explicit administrator, not family role, profile type or JWT claims, controls every lifecycle route', async () => {
130 const owner = await actor(), parent = await actor({ claims: { is_admin: true, role: 'admin' } }),
131 child = await actor({ category: 'adult' }), outsider = await actor();
132 const id = await family(owner, [{ user: parent, role: 'parent_guardian' }, { user: child, role: 'teen_minor' }]);
133 const foreign = await family(outsider), recipient = await actor(), invitation = await invite(owner, id, recipient);
134 for (const unauthorized of [parent, child, outsider, null]) {
135 const expected = unauthorized ? 403 : 401;
136 assert.equal((await invitations(unauthorized, id)).status, expected);
137 assert.equal((await role(unauthorized, id, parent, { mutationId: uuid(), expectedVersion: 1, role: 'adult_member' })).status, expected);
138 assert.equal((await transfer(unauthorized, id, { mutationId: uuid(), targetUserId: parent.id, expectedVersion: 1, expectedActorVersion: 1 })).status, expected);
139 assert.equal((await revoke(unauthorized, id, invitation.id, { mutationId: uuid(), expectedVersion: 1, action: 'revoke' })).status, expected);
140 }
141 assert.equal((await invitations(owner, foreign)).status, 403);
142 for (const path of [`/families/${id}/invitations?limit=0`, `/families/${id}/invitations?limit=1.5`,
143 `/families/${id}/invitations?limit=1&limit=2`, `/families/${id}/invitations?cursor=bad`, `/families/${id}/invitations?email=x`])
144 assert.equal((await request(owner, 'GET', path)).status, 400);
145 assert.equal((await role(owner, id, parent, { mutationId: uuid(), expectedVersion: 1, role: 'adult_member', isAdmin: true })).status, 400);
146 assert.equal((await transfer(owner, id, { mutationId: uuid(), targetUserId: parent.id, expectedVersion: 1, expectedActorVersion: 1, ownerUserId: outsider.id })).status, 400);
147 assert.equal((await revoke(owner, id, invitation.id, { mutationId: uuid(), expectedVersion: 1, action: 'accept' })).status, 400);
148 });
149
150 test('administrator invitation pagination masks contact and never leaks bearer token or digest', async () => {
151 const owner = await actor(), id = await family(owner), recipients = await Promise.all([actor(), actor(), actor()]);
152 const rows = [];
153 for (const recipient of recipients) rows.push(await invite(owner, id, recipient));
154 const listed = await invitations(owner, id, '?limit=2'); assert.equal(listed.status, 200);
155 assert.equal(listed.body.total, 3); assert.equal(listed.body.invitations.length, 2); assert.ok(listed.body.nextCursor);
156 const serialized = JSON.stringify(listed.body);
157 for (const recipient of recipients) assert.ok(!serialized.includes(recipient.email));
158 for (const row of rows) {
159 assert.ok(!serialized.includes(row.invitationToken));
160 assert.ok(!serialized.includes(crypto.createHash('sha256').update(row.invitationToken).digest('hex')));
161 }
162 const next = await invitations(owner, id, `?limit=2&cursor=${listed.body.nextCursor}`);
163 assert.equal(next.body.invitations.length, 1); assert.equal(next.body.nextCursor, null);
164 assert.equal(new Set([...listed.body.invitations, ...next.body.invitations].map(row => row.id)).size, 3);
165 assert.ok(listed.body.invitations.every(row => row.version === 1 && row.recipientHint === '***@example.test'));
166 assert.equal((await invitations(owner, id, `?cursor=${uuid()}`)).status, 404);
167 });
168
169 test('role CAS increments one version, stable receipt survives API restart and rejects changed intent', async () => {
170 const owner = await actor(), target = await actor(), id = await family(owner, [{ user: target, role: 'parent_guardian' }]);
171 assert.equal((await members(owner, id)).body.members.find(row => row.user_id === target.id).version, 1);
172 const mutation = { mutationId: uuid(), expectedVersion: 1, role: 'adult_member' };
173 const first = await role(owner, id, target, mutation);
174 assert.equal(first.status, 200); assert.equal(first.body.members[0].version, 2); assert.equal(first.body.members[0].role, 'adult_member');
175 assert.equal(first.body.acknowledgement.status, 'accepted');
176 await stop(); await start();
177 const replay = await role(owner, id, target, mutation); assert.equal(replay.status, 200);
178 assert.equal(replay.body.acknowledgement.status, 'already_applied'); assert.equal(replay.body.members[0].version, 2);
179 assert.equal((await role(owner, id, target, { ...mutation, role: 'teen_minor' })).status, 409);
180 assert.equal((await role(owner, id, target, { mutationId: uuid(), expectedVersion: 1, role: 'parent_guardian' })).body.error, 'membership_version_conflict');
181 const second = { mutationId: uuid(), expectedVersion: 2, role: 'parent_guardian' };
182 assert.equal((await role(owner, id, target, second)).body.members[0].version, 3);
183 assert.equal((await role(owner, id, target, mutation)).body.members[0].version, 3, 'Retry returns current state, not obsolete role');
184 assert.equal((await member(id, target)).role, 'parent_guardian');
185 assert.equal((await pool.query('select count(*)::int n from family_lifecycle_mutation where actor_user_id=$1 and family_id=$2', [owner.id, id])).rows[0].n, 2);
186 assert.equal((await pool.query("select count(*)::int n from access_audit where actor_user_id=$1 and action='family.lifecycle.role'", [owner.id])).rows[0].n, 2);
187 });
188
189 test('known minors cannot take adult roles or administration; unknown legacy adult can receive explicit transfer', async () => {
190 const owner = await actor(), teen = await actor({ category: 'adult' }),
191 minorAdult = await actor({ birthDate: '2020-01-01', category: 'adult' }), adultTeen = await actor({ birthDate: '1990-01-01', category: 'girl_minor' }),
192 legacyAdult = await actor({ category: 'boy_minor' });
193 const id = await family(owner, [{ user: teen, role: 'teen_minor' }, { user: minorAdult },
194 { user: adultTeen, role: 'teen_minor' }, { user: legacyAdult }]);
195 assert.equal((await role(owner, id, teen, { mutationId: uuid(), expectedVersion: 1, role: 'adult_member' })).body.error, 'age_confirmation_required');
196 assert.equal((await role(owner, id, minorAdult, { mutationId: uuid(), expectedVersion: 1, role: 'parent_guardian' })).body.error, 'minor_role_upgrade_forbidden');
197 for (const target of [teen, minorAdult]) assert.equal((await transfer(owner, id, {
198 mutationId: uuid(), targetUserId: target.id, expectedVersion: 1, expectedActorVersion: 1 })).body.error, 'minor_cannot_admin');
199 assert.equal((await role(owner, id, adultTeen, { mutationId: uuid(), expectedVersion: 1, role: 'adult_member' })).status, 200);
200 assert.equal((await role(owner, id, owner, { mutationId: uuid(), expectedVersion: 1, role: 'teen_minor' })).body.error, 'minor_cannot_admin');
201 assert.equal((await transfer(owner, id, { mutationId: uuid(), targetUserId: legacyAdult.id, expectedVersion: 1, expectedActorVersion: 1 })).status, 200);
202 assert.equal((await member(id, legacyAdult)).is_admin, true);
203 assert.equal((await pool.query('select profile_category from profile where user_id=$1', [legacyAdult.id])).rows[0].profile_category, 'boy_minor', 'Profile category is not silently rewritten by family authority');
204 });
205
206 test('family creation denies known minors while profile category itself does not infer administrative age', async () => {
207 const knownMinor = await actor({ birthDate: '2020-01-01', category: 'adult' });
208 const rejected = await request(knownMinor, 'POST', '/families', { name: 'Synthetic denied family', role: 'parent_guardian' });
209 assert.equal(rejected.status, 403); assert.equal(rejected.body.error, 'minor_cannot_admin');
210 assert.equal((await pool.query('select count(*)::int n from family_workspace where created_by=$1', [knownMinor.id])).rows[0].n, 0);
211 for (const options of [{ birthDate: '1990-01-01', category: 'girl_minor' }, { category: 'boy_minor' }]) {
212 const creator = await actor(options), created = await request(creator, 'POST', '/families', { name: 'Synthetic allowed family', role: 'adult_member' });
213 if (created.status === 201) families.push(created.body.id);
214 assert.equal(created.status, 201, 'Explicit adult date or legacy unknown adult is not rejected by a UI profile category');
215 assert.equal((await member(created.body.id, creator)).is_admin, true);
216 }
217 });
218
219 test('new family creation cannot bypass unknown-age teen membership through an adult-looking profile', async () => {
220 const owner = await actor(), teen = await actor({ category: 'adult' });
221 await family(owner, [{ user: teen, role: 'teen_minor' }]);
222 const rejected = await request(teen, 'POST', '/families', { name: 'Synthetic age bypass attempt', role: 'adult_member' });
223 if (rejected.status === 201) families.push(rejected.body.id);
224 assert.equal(rejected.status, 403); assert.equal(rejected.body.error, 'age_confirmation_required');
225 assert.equal((await pool.query('select count(*)::int n from family_workspace where created_by=$1', [teen.id])).rows[0].n, 0);
226 });
227
228 test('new family admin age derives from locked fresh profile after account-row wait', async () => {
229 const creator = await actor({ birthDate: '1990-01-01' }), blocker = await pool.connect(); let pending;
230 try {
231 await blocker.query('begin'); await blocker.query('select id from app_user where id=$1 for update', [creator.id]);
232 await blocker.query('select user_id from profile where user_id=$1 for update', [creator.id]);
233 pending = request(creator, 'POST', '/families', { name: 'Synthetic age correction race' });
234 await blockedOn(blocker);
235 await blocker.query("update profile set birth_date='2020-01-01' where user_id=$1", [creator.id]);
236 await blocker.query('commit'); const response = await pending;
237 if (response.status === 201) families.push(response.body.id);
238 assert.equal(response.status, 403); assert.equal(response.body.error, 'minor_cannot_admin');
239 } finally { await blocker.query('rollback').catch(() => {}); blocker.release(); if (pending) await pending.catch(() => {}); }
240 assert.equal((await pool.query('select count(*)::int n from family_workspace where created_by=$1', [creator.id])).rows[0].n, 0);
241 });
242
243 test('invitation acceptance cannot assign known minors adult or guardian roles and leaves the invitation recoverable', async () => {
244 const owner = await actor(), id = await family(owner);
245 for (const intendedRole of ['adult_member', 'parent_guardian']) {
246 const recipient = await actor({ birthDate: '2020-01-01', category: 'adult' }), invitation = await invite(owner, id, recipient, intendedRole);
247 const rejected = await accept(recipient, invitation.invitationToken);
248 assert.equal(rejected.status, 403); assert.equal(rejected.body.error, 'minor_role_upgrade_forbidden');
249 assert.equal(await member(id, recipient), undefined);
250 assert.equal((await pool.query('select status,accepted_by,version from family_invitation where id=$1', [invitation.id])).rows[0].status, 'pending');
251 assert.equal((await pool.query("select count(*)::int n from access_audit where actor_user_id=$1 and action='invitation.accept'", [recipient.id])).rows[0].n, 0);
252 assert.equal((await pool.query('select profile_category,theme_preference from profile where user_id=$1', [recipient.id])).rows[0].profile_category, 'adult');
253 const correction = await invite(owner, id, recipient, 'teen_minor');
254 assert.equal((await accept(recipient, correction.invitationToken)).status, 204);
255 assert.equal((await member(id, recipient)).role, 'teen_minor');
256 const activeConflict = await accept(recipient, invitation.invitationToken);
257 assert.equal(activeConflict.status, 409); assert.equal(activeConflict.body.error, 'member_already_active');
258 assert.equal((await member(id, recipient)).role, 'teen_minor');
259 assert.equal((await pool.query('select status from family_invitation where id=$1', [invitation.id])).rows[0].status, 'pending');
260 }
261 });
262
263 test('invitation adult role requires age confirmation for an active unknown-age teen in another family', async () => {
264 const owner = await actor(), teen = await actor({ category: 'adult' }), existing = await family(owner, [{ user: teen, role: 'teen_minor' }]);
265 const newOwner = await actor(), target = await family(newOwner);
266 for (const intendedRole of ['adult_member', 'parent_guardian']) {
267 const invitation = await invite(newOwner, target, teen, intendedRole), rejected = await accept(teen, invitation.invitationToken);
268 assert.equal(rejected.status, 403); assert.equal(rejected.body.error, 'age_confirmation_required');
269 assert.equal(await member(target, teen), undefined); assert.equal((await member(existing, teen)).role, 'teen_minor');
270 assert.equal((await pool.query('select status from family_invitation where id=$1', [invitation.id])).rows[0].status, 'pending');
271 }
272 const correction = await invite(newOwner, target, teen, 'teen_minor');
273 assert.equal((await accept(teen, correction.invitationToken)).status, 204);
274 assert.equal((await member(target, teen)).role, 'teen_minor');
275 });
276
277 test('invitation age checks use birth date and current teen membership rather than profile category', async () => {
278 const owner = await actor(), id = await family(owner);
279 for (const options of [{ birthDate: '1990-01-01', category: 'girl_minor' }, { category: 'boy_minor' }]) {
280 const recipient = await actor(options), invitation = await invite(owner, id, recipient, 'parent_guardian');
281 assert.equal((await accept(recipient, invitation.invitationToken)).status, 204);
282 assert.equal((await member(id, recipient)).role, 'parent_guardian');
283 assert.equal((await pool.query('select profile_category from profile where user_id=$1', [recipient.id])).rows[0].profile_category, options.category);
284 }
285 const adultFormerTeen = await actor({ birthDate: '1990-01-01', category: 'girl_minor' });
286 await family(owner, [{ user: adultFormerTeen, role: 'teen_minor' }]);
287 const invitation = await invite(owner, id, adultFormerTeen, 'adult_member');
288 assert.equal((await accept(adultFormerTeen, invitation.invitationToken)).status, 204);
289 assert.equal((await member(id, adultFormerTeen)).role, 'adult_member');
290 });
291
292 test('invitation acceptance waits for editable birth date and rejects a newly known minor before membership', async () => {
293 const owner = await actor(), recipient = await actor({ birthDate: '1990-01-01' }), id = await family(owner),
294 invitation = await invite(owner, id, recipient, 'parent_guardian'), blocker = await pool.connect(); let pending;
295 try {
296 await blocker.query('begin'); await blocker.query('select user_id from profile where user_id=$1 for update', [recipient.id]);
297 pending = accept(recipient, invitation.invitationToken); await blockedOn(blocker);
298 await blocker.query("update profile set birth_date='2020-01-01' where user_id=$1", [recipient.id]);
299 await blocker.query('commit'); const rejected = await pending;
300 assert.equal(rejected.status, 403); assert.equal(rejected.body.error, 'minor_role_upgrade_forbidden');
301 } finally { await blocker.query('rollback').catch(() => {}); blocker.release(); if (pending) await pending.catch(() => {}); }
302 assert.equal(await member(id, recipient), undefined);
303 assert.equal((await pool.query('select status from family_invitation where id=$1', [invitation.id])).rows[0].status, 'pending');
304 });
305
306 test('atomic transfer preserves administrator, revokes old pending invitations and only exact old retry bypasses new-admin check', async () => {
307 const owner = await actor(), target = await actor(), recipient = await actor(), id = await family(owner, [{ user: target }]);
308 const invitation = await invite(owner, id, recipient), mutation = { mutationId: uuid(), targetUserId: target.id, expectedVersion: 1, expectedActorVersion: 1 };
309 const first = await transfer(owner, id, mutation); assert.equal(first.status, 200);
310 assert.deepEqual(first.body.members.map(row => [row.userId, row.isAdmin, row.version]), [[owner.id, false, 2], [target.id, true, 2]]);
311 assert.equal((await pool.query('select status,version from family_invitation where id=$1', [invitation.id])).rows[0].status, 'revoked');
312 assert.equal((await accept(recipient, invitation.invitationToken)).status, 400);
313 assert.equal((await invitations(owner, id)).status, 403);
314 assert.equal((await role(owner, id, target, { mutationId: uuid(), expectedVersion: 2, role: 'parent_guardian' })).status, 403);
315 const replay = await transfer(owner, id, mutation); assert.equal(replay.status, 200); assert.equal(replay.body.acknowledgement.status, 'already_applied');
316 assert.equal((await transfer(owner, id, { ...mutation, expectedVersion: 2 })).body.error, 'mutation_id_reused');
317 assert.equal((await transfer(target, id, { mutationId: uuid(), targetUserId: owner.id, expectedVersion: 2, expectedActorVersion: 2 })).status, 200);
318 assert.equal((await accept(recipient, invitation.invitationToken)).status, 400, 'Transfer back must not revive old invitation');
319 assert.equal((await transfer(owner, id, mutation)).body.members.find(row => row.userId === target.id).isAdmin, false, 'Exact old retry reports current authority');
320 assert.equal((await request(owner, 'DELETE', `/families/${id}/members/${owner.id}`)).body.error, 'last_admin_required');
321 });
322
323 test('concurrent transfer/role CAS keeps one administrator and one accepted version', async () => {
324 const owner = await actor(), first = await actor(), second = await actor(), id = await family(owner, [{ user: first }, { user: second }]);
325 const results = await Promise.all([first, second].map(target => transfer(owner, id, {
326 mutationId: uuid(), targetUserId: target.id, expectedVersion: 1, expectedActorVersion: 1 })));
327 assert.deepEqual(results.map(result => result.status).sort(), [200, 403]);
328 const active = (await pool.query('select user_id from family_membership where family_id=$1 and ended_at is null and is_admin', [id])).rows;
329 assert.equal(active.length, 1); assert.notEqual(active[0].user_id, owner.id);
330 const newAdmin = active[0].user_id === first.id ? first : second, target = newAdmin === first ? second : first;
331 const writes = await Promise.all(['parent_guardian', 'teen_minor'].map(newRole => role(newAdmin, id, target, {
332 mutationId: uuid(), expectedVersion: 1, role: newRole })));
333 assert.deepEqual(writes.map(result => result.status).sort(), [200, 409]);
334 assert.equal((await member(id, target)).version, 2);
335 });
336
337 test('role changes revoke affected guardian/selected sharing; reversal or removal/rejoin never resurrects access', async () => {
338 const owner = await actor(), parent = await actor(), child = await actor({ birthDate: '1990-01-01', category: 'girl_minor' });
339 const id = await family(owner, [{ user: parent, role: 'parent_guardian' }, { user: child, role: 'teen_minor' }]);
340 await pool.query('insert into guardian_relationship(family_id,guardian_user_id,minor_user_id) values($1,$2,$3)', [id, parent.id, child.id]);
341 const task = await request(child, 'POST', '/plan-items', { title: 'Synthetic selected task', kind: 'assignment', familyId: id,
342 visibility: 'selected_members', selectedMemberIds: [parent.id], notes: 'SYNTHETIC-PRIVATE-NOTE' });
343 assert.equal(task.status, 201, JSON.stringify(task.body));
344 // Verify a real grant independently; some legacy clients omit the grant list.
345 await pool.query("insert into sharing_grant(resource_type,resource_id,grantee_user_id,granted_by) values('plan_item',$1,$2,$3) on conflict do nothing", [task.body.id, parent.id, child.id]);
346 assert.equal((await request(parent, 'GET', `/plan-items/${task.body.id}`)).status, 200);
347 assert.equal((await role(owner, id, parent, { mutationId: uuid(), expectedVersion: 1, role: 'adult_member' })).status, 200);
348 assert.equal((await pool.query('select active from guardian_relationship where family_id=$1 and guardian_user_id=$2', [id, parent.id])).rows[0].active, false);
349 assert.equal((await pool.query('select count(*)::int n from sharing_grant where resource_id=$1', [task.body.id])).rows[0].n, 0);
350 assert.equal((await role(owner, id, parent, { mutationId: uuid(), expectedVersion: 2, role: 'parent_guardian' })).status, 200);
351 assert.equal((await request(parent, 'GET', `/plan-items/${task.body.id}`)).status, 404);
352 await pool.query("insert into sharing_grant(resource_type,resource_id,grantee_user_id,granted_by) values('plan_item',$1,$2,$3)", [task.body.id, parent.id, child.id]);
353 assert.equal((await request(owner, 'DELETE', `/families/${id}/members/${parent.id}`)).status, 204);
354 const invitation = await invite(owner, id, parent, 'parent_guardian'); assert.equal((await accept(parent, invitation.invitationToken)).status, 204);
355 assert.equal((await member(id, parent)).version, 5, 'Legacy end and rejoin revisions are tracked');
356 assert.equal((await request(parent, 'GET', `/plan-items/${task.body.id}`)).status, 404);
357 assert.equal((await pool.query('select active from guardian_relationship where family_id=$1 and guardian_user_id=$2', [id, parent.id])).rows[0].active, false);
358 const progress = (await pool.query('select profile_category from profile where user_id=$1', [child.id])).rows[0];
359 assert.equal(progress.profile_category, 'girl_minor');
360 });
361
362 test('inactive target, disabled target and archived family reject new mutations; removal prevents historical retry', async () => {
363 const owner = await actor(), target = await actor(), id = await family(owner, [{ user: target }]);
364 const mutation = { mutationId: uuid(), expectedVersion: 1, role: 'parent_guardian' };
365 await pool.query('update app_user set disabled_at=now() where id=$1', [target.id]);
366 assert.equal((await role(owner, id, target, mutation)).body.error, 'member_not_active');
367 assert.equal((await transfer(owner, id, { mutationId: uuid(), targetUserId: target.id, expectedVersion: 1, expectedActorVersion: 1 })).body.error, 'member_not_active');
368 await pool.query('update app_user set disabled_at=null where id=$1', [target.id]);
369 assert.equal((await role(owner, id, target, mutation)).status, 200);
370 assert.equal((await request(owner, 'DELETE', `/families/${id}/members/${target.id}`)).status, 204);
371 assert.equal((await role(owner, id, target, { mutationId: uuid(), expectedVersion: 3, role: 'adult_member' })).body.error, 'member_not_active');
372 assert.equal((await request(owner, 'DELETE', `/families/${id}`)).status, 204);
373 assert.equal((await role(owner, id, target, mutation)).status, 403);
374 assert.equal((await invitations(owner, id)).status, 403);
375 });
376
377 test('invitation revoke receipt persists, returns current state and rejects concurrent accept without contact/token disclosure', async () => {
378 const owner = await actor(), recipient = await actor(), id = await family(owner), invitation = await invite(owner, id, recipient);
379 const mutation = { mutationId: uuid(), expectedVersion: 1, action: 'revoke' };
380 const result = await revoke(owner, id, invitation.id, mutation); assert.equal(result.status, 200);
381 assert.equal(result.body.invitation.status, 'revoked'); assert.equal(result.body.invitation.version, 2);
382 assert.ok(!JSON.stringify(result.body).includes(recipient.email)); assert.ok(!JSON.stringify(result.body).includes(invitation.invitationToken));
383 assert.equal((await accept(recipient, invitation.invitationToken)).status, 400);
384 await stop(); await start();
385 const replay = await revoke(owner, id, invitation.id, mutation); assert.equal(replay.status, 200);
386 assert.equal(replay.body.acknowledgement.status, 'already_applied'); assert.equal(replay.body.invitation.version, 2);
387 assert.equal((await revoke(owner, id, invitation.id, { ...mutation, expectedVersion: 2 })).body.error, 'mutation_id_reused');
388 assert.equal((await revoke(owner, id, invitation.id, { mutationId: uuid(), expectedVersion: 2, action: 'revoke' })).body.error, 'invitation_not_pending');
389 assert.equal((await invitations(owner, id)).body.total, 0);
390 });
391
392 test('invitation expiry is rechecked after an observed family-row wait, not frozen transaction time', async () => {
393 const owner = await actor(), recipient = await actor(), id = await family(owner), invitation = await invite(owner, id, recipient);
394 await pool.query("update family_invitation set created_at=now()-interval '1 minute' where id=$1", [invitation.id]);
395 await withFamilyBlocked(id, async blocker => {
396 const pending = accept(recipient, invitation.invitationToken); await blockedOn(blocker);
397 await blocker.query("update family_invitation set expires_at=statement_timestamp()-interval '1 millisecond' where id=$1", [invitation.id]);
398 await blocker.query('commit');
399 assert.equal((await pending).status, 400, 'Expired invitation must not commit membership after lock wait');
400 });
401 assert.equal((await pool.query('select count(*)::int n from family_membership where family_id=$1 and user_id=$2', [id, recipient.id])).rows[0].n, 0);
402 assert.equal((await invitations(owner, id)).body.invitations[0].status, 'expired');
403 });
404
405 test('acceptance waiting behind revoke sees committed revocation and creates no membership', async () => {
406 const owner = await actor(), recipient = await actor(), id = await family(owner), invitation = await invite(owner, id, recipient);
407 await withFamilyBlocked(id, async blocker => {
408 const pending = accept(recipient, invitation.invitationToken); await blockedOn(blocker);
409 await blocker.query("update family_invitation set status='revoked' where id=$1", [invitation.id]);
410 await blocker.query('commit'); assert.equal((await pending).status, 400);
411 });
412 assert.equal((await pool.query('select count(*)::int n from family_membership where family_id=$1 and user_id=$2', [id, recipient.id])).rows[0].n, 0);
413 });
414
415 test('role/transfer/revoke reject session expiry or revocation that occurs during an observed family lock wait', async () => {
416 for (const operation of ['role', 'transfer', 'revoke']) {
417 for (const invalidation of ['expiry', 'revocation']) {
418 const owner = await actor(), target = await actor(), id = await family(owner, [{ user: target }]),
419 invitation = operation === 'revoke' ? await invite(owner, id, await actor()) : null;
420 await withFamilyBlocked(id, async blocker => {
421 const pending = operation === 'role' ? role(owner, id, target, { mutationId: uuid(), expectedVersion: 1, role: 'parent_guardian' }) :
422 operation === 'transfer' ? transfer(owner, id, { mutationId: uuid(), targetUserId: target.id, expectedVersion: 1, expectedActorVersion: 1 }) :
423 revoke(owner, id, invitation.id, { mutationId: uuid(), expectedVersion: 1, action: 'revoke' });
424 await blockedOn(blocker);
425 await blocker.query(invalidation === 'expiry' ? "update auth_session set expires_at=statement_timestamp()-interval '1 millisecond' where id=$1" :
426 'update auth_session set revoked_at=statement_timestamp() where id=$1', [owner.sid]);
427 await blocker.query('commit'); assert.equal((await pending).status, 401, `${operation}/${invalidation}`);
428 });
429 assert.equal((await member(id, target)).version, 1);
430 assert.equal((await pool.query('select count(*)::int n from family_lifecycle_mutation where actor_user_id=$1', [owner.id])).rows[0].n, 0);
431 if (invitation) assert.equal((await pool.query('select status from family_invitation where id=$1', [invitation.id])).rows[0].status, 'pending');
432 }
433 }
434 });
435
436 test('legacy invitation acceptance and membership removal roll back session expiry during observed lock wait', async () => {
437 for (const operation of ['accept', 'remove']) {
438 const owner = await actor(), recipient = await actor(), id = await family(owner, operation === 'remove' ? [{ user: recipient }] : []);
439 const invitation = operation === 'accept' ? await invite(owner, id, recipient) : null, acting = operation === 'accept' ? recipient : owner;
440 await withFamilyBlocked(id, async blocker => {
441 const pending = operation === 'accept' ? accept(recipient, invitation.invitationToken) : request(owner, 'DELETE', `/families/${id}/members/${recipient.id}`);
442 await blockedOn(blocker);
443 await blocker.query("update auth_session set expires_at=statement_timestamp()-interval '1 millisecond' where id=$1", [acting.sid]);
444 await blocker.query('commit'); assert.equal((await pending).status, 401, `${operation}: expired session must not commit`);
445 });
446 const record = await member(id, recipient);
447 assert.ok(operation === 'accept' ? !record : record.ended_at === null);
448 }
449 });
450
451 test('JWT expiry during an observed family-row wait rolls back an otherwise active session', async () => {
452 const owner = await actor(), target = await actor(), id = await family(owner, [{ user: target }]);
453 const expiration = Math.floor(Date.now() / 1000) + 2;
454 owner.token = jwt.sign({ sub: owner.id, sid: owner.sid, aud: 'lifemate-api', exp: expiration }, secret, { issuer: 'lifemate' });
455 await withFamilyBlocked(id, async blocker => {
456 const pending = role(owner, id, target, { mutationId: uuid(), expectedVersion: 1, role: 'parent_guardian' });
457 await blockedOn(blocker);
458 const deadline = Date.now() + 4000;
459 while (Date.now() < deadline) {
460 if ((await blocker.query('select statement_timestamp()>=to_timestamp($1) expired', [expiration])).rows[0].expired) break;
461 await new Promise(resolve => setTimeout(resolve, 15));
462 }
463 assert.equal((await blocker.query('select statement_timestamp()>=to_timestamp($1) expired', [expiration])).rows[0].expired, true);
464 await blocker.query('commit'); assert.equal((await pending).status, 401);
465 });
466 assert.equal((await member(id, target)).version, 1);
467 });
468
469 test('final session-row lock serializes logout and uses fresh time after a session-row wait', async () => {
470 for (const invalidation of ['expiry', 'revocation']) {
471 const owner = await actor(), target = await actor(), id = await family(owner, [{ user: target }]), blocker = await pool.connect();
472 try {
473 await blocker.query('begin'); await blocker.query('select id from auth_session where id=$1 for update', [owner.sid]);
474 const pending = role(owner, id, target, { mutationId: uuid(), expectedVersion: 1, role: 'parent_guardian' });
475 await blockedOn(blocker);
476 await blocker.query(invalidation === 'expiry' ? "update auth_session set expires_at=statement_timestamp()-interval '1 millisecond' where id=$1" :
477 'update auth_session set revoked_at=statement_timestamp() where id=$1', [owner.sid]);
478 await blocker.query('commit'); assert.equal((await pending).status, 401);
479 } finally { await blocker.query('rollback').catch(() => {}); blocker.release(); }
480 assert.equal((await member(id, target)).version, 1, 'Even earlier writes must roll back at the final session gate');
481 assert.equal((await pool.query('select count(*)::int n from family_lifecycle_mutation where actor_user_id=$1', [owner.id])).rows[0].n, 0);
482 }
483 });
484
485 test('legacy family helper, invitation acceptance and family creation reject expiry after their final session-row wait', async () => {
486 for (const operation of ['rename', 'accept', 'create']) {
487 const owner = await actor(), recipient = await actor(), id = operation === 'create' ? null : await family(owner),
488 invitation = operation === 'accept' ? await invite(owner, id, recipient) : null,
489 acting = operation === 'accept' ? recipient : owner, blocker = await pool.connect();
490 try {
491 await blocker.query('begin'); await blocker.query('select id from auth_session where id=$1 for update', [acting.sid]);
492 const pending = operation === 'rename' ? request(owner, 'PATCH', `/families/${id}`, { name: 'Expired mutation' }) :
493 operation === 'accept' ? accept(recipient, invitation.invitationToken) : request(owner, 'POST', '/families', { name: 'Expired new family' });
494 await blockedOn(blocker);
495 await blocker.query("update auth_session set expires_at=statement_timestamp()-interval '1 millisecond' where id=$1", [acting.sid]);
496 await blocker.query('commit'); const response = await pending;
497 if (operation === 'create' && response.status === 201) families.push(response.body.id);
498 assert.equal(response.status, 401, `${operation}: initial valid session must not authorize a write after final row wait expiry`);
499 } finally { await blocker.query('rollback').catch(() => {}); blocker.release(); }
500 if (operation === 'rename') assert.equal((await pool.query('select name from family_workspace where id=$1', [id])).rows[0].name, 'Synthetic Lifecycle Family');
501 if (operation === 'accept') {
502 assert.equal(await member(id, recipient), undefined);
503 assert.equal((await pool.query('select status from family_invitation where id=$1', [invitation.id])).rows[0].status, 'pending');
504 }
505 if (operation === 'create') assert.equal((await pool.query('select count(*)::int n from family_workspace where created_by=$1', [owner.id])).rows[0].n, 0);
506 }
507 });
508
509 test('admin transfer waits for concurrent editable birth date and denies newly known minor context', async () => {
510 const owner = await actor(), target = await actor({ birthDate: '1990-01-01' }), id = await family(owner, [{ user: target }]), blocker = await pool.connect();
511 try {
512 await blocker.query('begin'); await blocker.query('select user_id from profile where user_id=$1 for update', [target.id]);
513 const pending = transfer(owner, id, { mutationId: uuid(), targetUserId: target.id, expectedVersion: 1, expectedActorVersion: 1 });
514 await blockedOn(blocker);
515 await blocker.query("update profile set birth_date='2020-01-01' where user_id=$1", [target.id]);
516 await blocker.query('commit'); assert.equal((await pending).body.error, 'minor_cannot_admin');
517 } finally { await blocker.query('rollback').catch(() => {}); blocker.release(); }
518 assert.equal((await member(id, owner)).is_admin, true); assert.equal((await member(id, target)).version, 1);
519 });
520
521 test('active admin authority is rechecked after an observed lock wait, and transfer/removal cannot remove the last admin', async () => {
522 const owner = await actor(), successor = await actor(), target = await actor(), id = await family(owner, [{ user: successor, admin: true }, { user: target }]);
523 await withFamilyBlocked(id, async blocker => {
524 const pending = role(owner, id, target, { mutationId: uuid(), expectedVersion: 1, role: 'parent_guardian' }); await blockedOn(blocker);
525 await blocker.query('update family_membership set is_admin=false where family_id=$1 and user_id=$2', [id, owner.id]);
526 await blocker.query('commit'); assert.equal((await pending).status, 403);
527 });
528 const results = await Promise.all([
529 transfer(successor, id, { mutationId: uuid(), targetUserId: target.id, expectedVersion: 1, expectedActorVersion: 1 }),
530 request(successor, 'DELETE', `/families/${id}/members/${successor.id}`),
531 ]);
532 assert.equal(results[0].status, 200);
533 assert.ok([403, 409].includes(results[1].status));
534 assert.equal((await pool.query('select count(*)::int n from family_membership m join app_user u on u.id=m.user_id where m.family_id=$1 and m.is_admin and m.ended_at is null and u.disabled_at is null', [id])).rows[0].n, 1);
535 });
536
537 test('cross-family reciprocal writes lock participating accounts in a stable order without deadlock', async () => {
538 const pair = (await Promise.all([actor(), actor()])).sort((a, b) => a.id.localeCompare(b.id));
539 const [low, high] = pair;
540 const first = await family(high, [{ user: low, role: 'parent_guardian', admin: true }]);
541 const second = await family(low, [{ user: high, role: 'parent_guardian', admin: true }]);
542 const blocker = await pool.connect(); let writes = [];
543 try {
544 await blocker.query('begin'); await blocker.query('select id from app_user where id=$1 for update', [low.id]);
545 await blocker.query('savepoint high_lock'); await blocker.query('select id from app_user where id=$1 for update', [high.id]);
546 writes = [role(high, first, low, { mutationId: uuid(), expectedVersion: 1, role: 'adult_member' }),
547 role(low, second, high, { mutationId: uuid(), expectedVersion: 1, role: 'adult_member' })];
548 await blockedOn(blocker, 2); await blocker.query('rollback to savepoint high_lock');
549 await blockedOn(blocker, 2); // Both must now wait for low, without retaining a higher account lock.
550 await blocker.query('commit');
551 const result = await Promise.all(writes); assert.deepEqual(result.map(row => row.status), [200, 200]);
552 assert.equal((await member(first, low)).version, 2); assert.equal((await member(second, high)).version, 2);
553 } finally { await blocker.query('rollback').catch(() => {}); blocker.release(); await Promise.allSettled(writes); }
554 });
555 });