@davoodmehraban89 / LifeMate / commits / c72621f
Fork 0

LifeMate — Personal, Family & Learning Companion

fix(auth): confine managed child sessions and preserve recovery scope

Quinn White committed Oct 16, 2026 at 06:51 UTC c72621fade774576ab9038f27e61670f5ba73335
9 files changed +149 -16
backend/src/auth_router.js
+31 -11
@@ -4,6 +4,7 @@ import argon2 from 'argon2';
4 import jwt from 'jsonwebtoken';
5 import { normalizeEmail, normalizePhone, isEmail, validPassword } from './auth_contacts.js';
6 import { createEmailProvider, createSmsProvider, safelyDeliver } from './auth_delivery.js';
7 +import { managedChildAccessActive } from './child_session_policy.js';
8
9 const sha256 = (value) => crypto.createHash('sha256').update(value).digest('hex');
10 const randomToken = () => crypto.randomBytes(32).toString('base64url');
@@ -25,6 +26,7 @@ async function transaction(pool, operation) {
26 export function createAuthRouter({ pool, jwtSecret, auth, env = process.env,
27 emailProvider = createEmailProvider({ env }), smsProvider = createSmsProvider() }) {
28 const router = express.Router();
29 + router.use((_req, res, next) => { res.setHeader('Cache-Control', 'no-store'); next(); });
30 const testMode = env.NODE_ENV === 'test';
31 const publicApp = env.PUBLIC_APP_URL ?? 'https://app.lifeguide.invalid';
32 const dummyHash = argon2.hash(randomToken(), { type: argon2.argon2id });
@@ -43,7 +45,7 @@ export function createAuthRouter({ pool, jwtSecret, auth, env = process.env,
45 const tokenDigest = sha256(raw);
46 const owner = await client.query('select user_id from auth_token where token_digest=$1 and kind=$2', [tokenDigest, kind]);
47 if (!owner.rowCount) return null;
46 - const active = await client.query('select 1 from app_user where id=$1 and disabled_at is null for update', [owner.rows[0].user_id]);
48 + const active = await client.query('select 1 from app_user where id=$1 and disabled_at is null and not is_managed_child for update', [owner.rows[0].user_id]);
49 if (!active.rowCount) return null;
50 const token = await client.query('select user_id from auth_token where token_digest=$1 and kind=$2 and used_at is null for update', [tokenDigest, kind]);
51 if (!token.rowCount) return null;
@@ -54,15 +56,24 @@ export function createAuthRouter({ pool, jwtSecret, auth, env = process.env,
56 return fresh.rowCount ? token.rows[0] : null;
57 }
58
57 - async function session(client, userId) {
59 + async function session(client, userId, { priorScope = 'standard', issuerId = null } = {}) {
60 + const account = await client.query('select is_managed_child from app_user where id=$1 and disabled_at is null', [userId]);
61 + if (!account.rowCount) return null;
62 + let scope = 'standard';
63 + if (account.rows[0].is_managed_child) {
64 + if (priorScope !== 'child_education' || !await managedChildAccessActive(client, userId, issuerId, env)) return null;
65 + scope = 'child_education';
66 + } else if (priorScope !== 'standard') return null;
67 const refreshToken = randomToken();
68 const result = await client.query(
60 - "insert into auth_session(user_id,refresh_digest,expires_at) values($1,$2,now()+interval '30 days') returning id",
61 - [userId, sha256(refreshToken)],
69 + "insert into auth_session(user_id,refresh_digest,expires_at,access_scope,child_issuer_user_id) values($1,$2,clock_timestamp()+interval '30 days',$3,$4) returning id",
70 + [userId, sha256(refreshToken), scope, scope === 'child_education' ? issuerId : null],
71 );
72 return {
64 - accessToken: jwt.sign({ sub: userId, sid: result.rows[0].id, aud: 'lifemate-api' }, jwtSecret, { expiresIn: '15m', issuer: 'lifemate' }),
73 + accessToken: jwt.sign({ sub: userId, sid: result.rows[0].id, aud: 'lifemate-api',
74 + ...(scope === 'child_education' ? { scope } : {}) }, jwtSecret, { expiresIn: '15m', issuer: 'lifemate' }),
75 refreshToken,
76 + ...(scope === 'child_education' ? { accessScope: scope } : {}),
77 };
78 }
79
@@ -183,7 +194,7 @@ export function createAuthRouter({ pool, jwtSecret, auth, env = process.env,
194 const phone = email ? null : normalizePhone(identifier);
195 const result = await pool.query(
196 `select u.id,u.email_verified_at,u.phone_verified_at,c.password_hash from app_user u
186 - join auth_credential c on c.user_id=u.id where u.disabled_at is null
197 + join auth_credential c on c.user_id=u.id where u.disabled_at is null and not u.is_managed_child
198 and (($1::text is not null and u.email_normalized=$1) or ($2::text is not null and u.phone_normalized=$2))`, [email, phone],
199 );
200 const password = String(req.body?.password ?? '');
@@ -207,17 +218,26 @@ export function createAuthRouter({ pool, jwtSecret, auth, env = process.env,
218
219 router.post('/refresh', async (req, res) => {
220 const tokens = await transaction(pool, async (client) => {
210 - const preliminary = await client.query('select user_id from auth_session where refresh_digest=$1', [sha256(String(req.body?.refreshToken ?? ''))]);
221 + const preliminary = await client.query(`select s.user_id,u.is_managed_child,mc.family_id
222 + from auth_session s join app_user u on u.id=s.user_id
223 + left join managed_child mc on mc.user_id=s.user_id where s.refresh_digest=$1`, [sha256(String(req.body?.refreshToken ?? ''))]);
224 if (!preliminary.rowCount) return null;
225 + // Child recovery/consent operations lock family before accounts. Match
226 + // that order rather than deadlocking with a concurrent device recovery.
227 + if (preliminary.rows[0].is_managed_child) {
228 + if (!(await client.query('select id from family_workspace where id=$1 and archived_at is null for update',
229 + [preliminary.rows[0].family_id])).rowCount) return null;
230 + }
231 // Account-first locking is shared with password/OTP recovery.
232 const active = await client.query('select 1 from app_user where id=$1 and disabled_at is null for update', [preliminary.rows[0].user_id]);
233 if (!active.rowCount) return null;
215 - const current = await client.query('select id,user_id from auth_session where refresh_digest=$1 and revoked_at is null for update', [sha256(String(req.body?.refreshToken ?? ''))]);
234 + const current = await client.query('select id,user_id,access_scope,child_issuer_user_id from auth_session where refresh_digest=$1 and revoked_at is null for update', [sha256(String(req.body?.refreshToken ?? ''))]);
235 if (!current.rowCount) return null;
236 const fresh = await client.query('select 1 from auth_session where id=$1 and revoked_at is null and expires_at>clock_timestamp()', [current.rows[0].id]);
237 if (!fresh.rowCount) return null;
238 await client.query('update auth_session set revoked_at=now() where id=$1', [current.rows[0].id]);
220 - return session(client, current.rows[0].user_id);
239 + return session(client, current.rows[0].user_id, { priorScope: current.rows[0].access_scope,
240 + issuerId: current.rows[0].child_issuer_user_id });
241 });
242 if (!tokens) return res.status(401).json({ error: 'invalid_refresh_token' });
243 res.json(tokens);
@@ -294,7 +314,7 @@ export function createAuthRouter({ pool, jwtSecret, auth, env = process.env,
314 const result = await transaction(pool, async (client) => {
315 const rate = await claimDelivery(client, phone, 'phone_otp');
316 if (rate.retryAfter) return rate;
297 - const user = await client.query('select id from app_user where phone_normalized=$1 and disabled_at is null', [phone]);
317 + const user = await client.query('select id from app_user where phone_normalized=$1 and disabled_at is null and not is_managed_child', [phone]);
318 const challengeId = crypto.randomUUID();
319 const code = String(crypto.randomInt(0, 1000000)).padStart(6, '0');
320 await client.query("insert into auth_phone_challenge(id,user_id,purpose,code_digest,expires_at) values($1,$2,$3,$4,now()+interval '5 minutes')", [challengeId, user.rows[0]?.id ?? null, purpose, digest(`otp:${challengeId}:${code}`)]);
@@ -317,7 +337,7 @@ export function createAuthRouter({ pool, jwtSecret, auth, env = process.env,
337 // Account-first locking also serializes two different challenges for one account.
338 let user;
339 if (owner.rows[0]?.user_id) {
320 - user = await client.query('select phone_verified_at from app_user where id=$1 and disabled_at is null for update', [owner.rows[0].user_id]);
340 + user = await client.query('select phone_verified_at from app_user where id=$1 and disabled_at is null and not is_managed_child for update', [owner.rows[0].user_id]);
341 if (!user.rowCount) return null;
342 }
343 const challenge = await client.query('select * from auth_phone_challenge where id=$1 and used_at is null and attempts<5 for update', [challengeId]);
backend/src/child_session_policy.js new
+26
@@ -0,0 +1,26 @@
1 +// Experimental identity work is deliberately unavailable in production.
2 +// This switch is not a consent policy or permission to use real child data.
3 +export const childSandboxEnabled = env => ['test', 'development'].includes(env.NODE_ENV)
4 + && env.ENABLE_CHILD_IDENTITY_SANDBOX === 'true';
5 +
6 +export async function managedChildAccessActive(client, userId, issuerId, env) {
7 + if (!childSandboxEnabled(env) || !issuerId) return false;
8 + return (await client.query(`select 1 from managed_child mc
9 + join child_consent cc on cc.child_user_id=mc.user_id and cc.revoked_at is null
10 + join app_user u on u.id=mc.user_id and u.disabled_at is null and u.is_managed_child
11 + join family_workspace f on f.id=mc.family_id and f.archived_at is null
12 + join family_membership m on m.family_id=mc.family_id and m.user_id=mc.user_id
13 + and m.ended_at is null and m.role='teen_minor' and not m.is_admin
14 + where mc.user_id=$1 and is_active_guardian(mc.family_id,$2,mc.user_id)`, [userId, issuerId])).rowCount > 0;
15 +}
16 +
17 +export function childSessionRouteAllowed(req) {
18 + if (req.method !== 'GET') return false;
19 + // Compare literal original paths: encoded/case/slash variants never expand
20 + // these permissions. Avoid router-relative req.path and prefix wildcards.
21 + const path = (req.originalUrl ?? req.url ?? '').split('?')[0];
22 + return ['/v1/profile', '/v1/families', '/v1/child-visibility',
23 + '/v1/education/catalog', '/v1/calendar/iran'].includes(path)
24 + || /^\/v1\/education\/units\/[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}(?:\/assessment)?$/i.test(path)
25 + && path.startsWith('/v1/education/units/');
26 +}
backend/src/family_lifecycle.js
+2
@@ -150,6 +150,7 @@ export function createFamilyLifecycleRouter({pool,auth}){
150 if(previous&&previous.request_hash!==digest)return error(409,'mutation_id_reused');
151 if(!previous&&!admin(actor))return error(403,'forbidden');
152 const target=await targetMember(client,familyId,id);if(!target)return error(404,'membership_not_found');
153 + if((await client.query('select 1 from managed_child where user_id=$1',[id])).rowCount)return error(403,'managed_child_membership_locked');
154 if(previous)return {status:200,body:{members:[memberBody(target)],acknowledgement:acknowledgement(body,familyId,id,'role',true)}};
155 if(target.ended_at||target.disabled_at)return error(409,'member_not_active');
156 if(target.version!==body.expectedVersion)return error(409,'membership_version_conflict');
@@ -174,6 +175,7 @@ export function createFamilyLifecycleRouter({pool,auth}){
175 if(previous&&previous.request_hash!==digest)return error(409,'mutation_id_reused');
176 if(!previous&&!admin(actor))return error(403,'forbidden');
177 const target=await targetMember(client,familyId,body.targetUserId);if(!target)return error(404,'membership_not_found');
178 + if((await client.query('select 1 from managed_child where user_id=$1',[body.targetUserId])).rowCount)return error(403,'managed_child_membership_locked');
179 if(previous)return {status:200,body:{members:[memberBody(actor),memberBody(target)],
180 acknowledgement:acknowledgement(body,familyId,body.targetUserId,'admin_transfer',true)}};
181 if(target.user_id===actor.user_id)return error(409,'admin_target_invalid');
backend/src/operations.js
+1 -1
@@ -66,7 +66,7 @@ export function rateLimitProfile(req, env = process.env) {
66 const discovery = req.method === 'GET' && path === '/v1/auth/capabilities';
67 // Express accepts case variants and trailing slashes. Only these literal
68 // method/path pairs receive the session quota; near matches remain strict.
69 - if (!discovery && /^\/v1\/auth(?:\/|$)/i.test(path)) {
69 + if ((!discovery && /^\/v1\/auth(?:\/|$)/i.test(path)) || /^\/v1\/child-devices\/accept\/?$/i.test(path)) {
70 if (req.method === 'POST' && (path === '/v1/auth/refresh' || path === '/v1/auth/logout')) {
71 return {
72 name: 'session',
backend/src/phase6.js
+5 -1
@@ -13,7 +13,11 @@ export function createPhase6Router({pool,auth,sensitiveFeaturesEnabled=process.e
13 const router=express.Router(); const requireAuth=auth??createSessionAuth({pool,jwtSecret:process.env.JWT_SECRET});
14 const requireSensitive=(_req,res,next)=>sensitiveFeaturesEnabled===true?next():res.status(503).json({error:'sensitive_features_disabled'});
15 router.get('/me/iran-profile',requireAuth,async(req,res)=>{ const r=await pool.query(`select p.user_id,p.display_name,p.birth_date,p.household_persona,p.sex,e.stage,e.national_grade,e.local_year,e.school_name,e.school_year,e.track_code from profile p left join education_profile e on e.user_id=p.user_id where p.user_id=$1`,[req.identity.sub]); res.json(r.rows[0]??{}); });
16 - router.patch('/me/iran-profile',requireAuth,async(req,res)=>{ const persona=req.body.householdPersona,sex=req.body.sex,birthDate=req.body.birthDate; if(persona!=null&&!validPersona(persona))return res.status(400).json({error:'invalid_persona'}); if(sex!=null&&!['female','male','unspecified'].includes(sex))return res.status(400).json({error:'invalid_sex'}); if(birthDate!=null&&!validBirthDate(birthDate))return res.status(400).json({error:'invalid_birth_date'}); await pool.query(`update profile set household_persona=coalesce($2,household_persona),sex=coalesce($3,sex),birth_date=coalesce($4::date,birth_date),updated_at=now() where user_id=$1`,[req.identity.sub,persona??null,sex??null,birthDate??null]); res.status(204).end(); });
16 + router.patch('/me/iran-profile',requireAuth,async(req,res)=>{
17 + if(Object.hasOwn(req.body??{},'birthDate')&&(await pool.query('select 1 from managed_child where user_id=$1',[req.identity.sub])).rowCount)
18 + return res.status(403).json({error:'managed_child_age_locked'});
19 + const persona=req.body.householdPersona,sex=req.body.sex,birthDate=req.body.birthDate; if(persona!=null&&!validPersona(persona))return res.status(400).json({error:'invalid_persona'}); if(sex!=null&&!['female','male','unspecified'].includes(sex))return res.status(400).json({error:'invalid_sex'}); if(birthDate!=null&&!validBirthDate(birthDate))return res.status(400).json({error:'invalid_birth_date'}); await pool.query(`update profile set household_persona=coalesce($2,household_persona),sex=coalesce($3,sex),birth_date=coalesce($4::date,birth_date),updated_at=now() where user_id=$1`,[req.identity.sub,persona??null,sex??null,birthDate??null]); res.status(204).end();
20 + });
21 router.put('/me/education',requireAuth,async(req,res)=>{
22 const mapped=educationForGrade(req.body.nationalGrade);if(!Number.isInteger(req.body.nationalGrade)||!mapped||(req.body.stage&&req.body.stage!==mapped.stage))return res.status(400).json({error:'invalid_grade_stage'});
23 const schoolYear=req.body.schoolYear??'1405-1406',schoolName=req.body.schoolName??null;
backend/src/profile_router.js
+10
@@ -21,6 +21,13 @@ export function createProfileRouter({ pool, auth }) {
21 [req.identity.sub],
22 );
23 if (!result.rowCount) return res.status(404).json({ error: 'profile_not_found' });
24 + if (req.identity.managedChild) {
25 + res.setHeader('Cache-Control', 'no-store');
26 + const row = result.rows[0];
27 + return res.json({ user_id: row.user_id, display_name: row.display_name,
28 + profile_category: row.profile_category, theme_preference: row.theme_preference,
29 + accessScope: 'child_education' });
30 + }
31 res.json(result.rows[0]);
32 });
33
@@ -30,6 +37,9 @@ export function createProfileRouter({ pool, auth }) {
37 const theme = body.themePreference == null ? null : String(body.themePreference);
38 const category = body.profileCategory;
39 const birthDate = body.birthDate;
40 + if (Object.hasOwn(body, 'birthDate') && (await pool.query('select 1 from managed_child where user_id=$1', [req.identity.sub])).rowCount) {
41 + return res.status(403).json({ error: 'managed_child_age_locked' });
42 + }
43 if (name != null && (!name || name.length > 100)) return res.status(400).json({ error: 'invalid_display_name' });
44 if (theme != null && !themes.has(theme)) return res.status(400).json({ error: 'invalid_theme' });
45 if (Object.hasOwn(body, 'profileCategory') && !categories.has(category)) return res.status(400).json({ error: 'invalid_profile_category' });
backend/src/session_auth.js
+15 -2
@@ -1,7 +1,8 @@
1 import jwt from 'jsonwebtoken';
2 +import { childSandboxEnabled, childSessionRouteAllowed, managedChildAccessActive } from './child_session_policy.js';
3
4 // Every API router must check both the session and the current account state.
4 -export function createSessionAuth({ pool, jwtSecret }) {
5 +export function createSessionAuth({ pool, jwtSecret, env = process.env }) {
6 return async (req, res, next) => {
7 const raw = req.headers.authorization?.replace(/^Bearer\s+/i, '');
8 try {
@@ -10,12 +11,24 @@ export function createSessionAuth({ pool, jwtSecret }) {
11 issuer: 'lifemate',
12 });
13 const session = await pool.query(
13 - `select 1 from auth_session s join app_user u on u.id=s.user_id
14 + `select s.access_scope,s.child_issuer_user_id,u.is_managed_child
15 + from auth_session s join app_user u on u.id=s.user_id
16 where s.id=$1 and s.user_id=$2 and s.revoked_at is null
17 and s.expires_at>now() and u.disabled_at is null`,
18 [identity.sid, identity.sub],
19 );
20 if (!session.rowCount) return res.status(401).json({ error: 'session_invalid' });
21 + const row = session.rows[0];
22 + if (row.is_managed_child || row.access_scope === 'child_education') {
23 + res.setHeader('Cache-Control', 'no-store');
24 + if (!childSandboxEnabled(env)) return res.status(503).json({ error: 'child_identity_sandbox_disabled' });
25 + if (!row.is_managed_child || row.access_scope !== 'child_education') return res.status(401).json({ error: 'session_invalid' });
26 + if (!await managedChildAccessActive(pool, identity.sub, row.child_issuer_user_id, env)) return res.status(401).json({ error: 'session_invalid' });
27 + if (!childSessionRouteAllowed(req)) return res.status(403).json({ error: 'child_session_scope_denied' });
28 + }
29 + // Claims supplied in a JWT cannot override the database scope/marker.
30 + identity.accessScope = row.access_scope;
31 + identity.managedChild = row.is_managed_child === true;
32 req.identity = identity;
33 next();
34 } catch {
backend/tests/auth_delivery.test.js
+3 -1
@@ -470,7 +470,9 @@ test('login cannot issue a session using a stale password after concurrent recov
470 await barrier.query('begin');
471 await barrier.query('select id from app_user where id=$1 for update', [account.id]);
472 const blocked = async (count) => (await pool.query(
473 - "select count(*)::int as n from pg_stat_activity where application_name=$1 and wait_event_type='Lock' and query='select 1 from app_user where id=$1 and disabled_at is null for update'", [applicationName],
473 + // Recovery now also excludes managed children. Still observe actual
474 + // account-row waits for this fixture, without freezing optional filters.
475 + "select count(*)::int as n from pg_stat_activity where application_name=$1 and wait_event_type='Lock' and query like 'select 1 from app_user where id=$1 and disabled_at is null%for update'", [applicationName],
476 )).rows[0].n >= count;
477 // Queue real recovery first, then let real login verify the old hash before it blocks.
478 recovery = providerRequest('/v1/auth/reset-password', { token: reset, newPassword: replacement });
backend/tests/managed_child_scope.test.js new
+56
@@ -0,0 +1,56 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import express from 'express';
4 +import jwt from 'jsonwebtoken';
5 +import { createSessionAuth } from '../src/session_auth.js';
6 +
7 +// Unit boundary tests: the pool is a stub. PostgreSQL integration is separate.
8 +const secret = 'synthetic-managed-scope-unit-fixture-not-live';
9 +async function probe({ path = '/v1/today', method = 'GET', scope = 'child_education', managed = true,
10 + active = true, env = { NODE_ENV: 'test', ENABLE_CHILD_IDENTITY_SANDBOX: 'true' } } = {}) {
11 + const app = express();
12 + const pool = { async query() { return { rowCount: active ? 1 : 0,
13 + rows: active ? [{ access_scope: scope, is_managed_child: managed, child_issuer_user_id: '00000000-0000-4000-8000-000000000004' }] : [] }; } };
14 + app.use(createSessionAuth({ pool, jwtSecret: secret, env }));
15 + app.use((_req, res) => res.json({ reached: true }));
16 + const server = app.listen(0, '127.0.0.1');
17 + await new Promise(resolve => server.once('listening', resolve));
18 + const token = jwt.sign({ sub: '00000000-0000-4000-8000-000000000001', sid: '00000000-0000-4000-8000-000000000002' },
19 + secret, { issuer: 'lifemate', audience: 'lifemate-api', expiresIn: '1h' });
20 + try {
21 + const response = await fetch('http://127.0.0.1:' + server.address().port + path,
22 + { method, headers: { authorization: 'Bearer ' + token } });
23 + return { status: response.status, body: await response.json() };
24 + } finally { await new Promise(resolve => server.close(resolve)); }
25 +}
26 +
27 +test('managed child is fail-closed in production and without the sandbox flag', async () => {
28 + assert.equal((await probe({ env: { NODE_ENV: 'production', ENABLE_CHILD_IDENTITY_SANDBOX: 'true' } })).status, 503);
29 + assert.equal((await probe({ env: { NODE_ENV: 'test' } })).status, 503);
30 +});
31 +test('managed marker and stored restricted scope must agree', async () => {
32 + assert.equal((await probe({ scope: 'standard' })).status, 401);
33 + assert.equal((await probe({ managed: false })).status, 401);
34 +});
35 +test('restricted device cannot read legacy private records or change identity or membership', async () => {
36 + for (const path of ['/v1/today', '/v1/plan-items', '/v1/study/sessions', '/v1/me/learning-attempts',
37 + '/v1/education/library', '/v1/education/courses/00000000-0000-4000-8000-000000000003',
38 + '/v1/learning/goals', '/v1/learning/checkins', '/v1/me/iran-profile', '/v1/me/menstrual-cycles',
39 + '/v1/ai/sessions', '/v1/content-review', '/v1/profile/', '/V1/profile', '/v1/%70rofile']) {
40 + assert.equal((await probe({ path })).status, 403, path);
41 + }
42 + for (const path of ['/v1/profile', '/v1/families', '/v1/sync/mutations', '/v1/auth/change-password']) {
43 + assert.equal((await probe({ path, method: 'POST' })).status, 403, path);
44 + }
45 +});
46 +test('restricted device only reaches exact safe catalogue and projected identity reads', async () => {
47 + for (const path of ['/v1/profile', '/v1/families', '/v1/child-visibility', '/v1/education/catalog',
48 + '/v1/calendar/iran', '/v1/education/units/00000000-0000-4000-8000-000000000003',
49 + '/v1/education/units/00000000-0000-4000-8000-000000000003/assessment']) {
50 + assert.equal((await probe({ path })).status, 200, path);
51 + }
52 +});
53 +test('ordinary account retains legacy routes; stale managed access is rejected', async () => {
54 + assert.equal((await probe({ managed: false, scope: 'standard' })).status, 200);
55 + assert.equal((await probe({ active: false })).status, 401);
56 +});