LifeMate — Personal, Family & Learning Companion

feat/personal-encrypted-recovery
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 512 lines 26.6 KB
Raw
1 import crypto from 'node:crypto';
2 import { pathToFileURL } from 'node:url';
3 import express from 'express';
4 import pg from 'pg';
5 import cors from 'cors';
6 import { createPhase3Router } from './phase3.js';
7 import { createPhase4Router } from './phase4.js';
8 import { createPhase6Router } from './phase6.js';
9 import { createLearningLibraryRouter } from './learning_library.js';
10 import { createLearningFeedbackRouter } from './learning_feedback.js';
11 import { createLearningAssessmentRouter } from './learning_assessment.js';
12 import { createContentReviewRouter } from './content_review.js';
13 import { createFamilyLifecycleRouter } from './family_lifecycle.js';
14 import { configureTrustedProxy, operationalErrorHandler } from './operations.js';
15 import { createSessionAuth } from './session_auth.js';
16 import { createAuthRouter } from './auth_router.js';
17 import { createStudySessionsRouter } from './study_sessions.js';
18 import { createProfileRouter } from './profile_router.js';
19 import { createSchoolCrudRouter } from './school_crud_router.js';
20 import { createSchoolLifecycleRouter } from './school_lifecycle.js';
21 import { normalizeEmail, normalizePhone, isEmail } from './auth_contacts.js';
22 import { createEmailProvider, safelyDeliver } from './auth_delivery.js';
23 import { createChildIdentityRouter } from './child_identity.js';
24
25 const { Pool } = pg;
26 const app = express();
27 configureTrustedProxy(app);
28 const allowedOrigins = (process.env.CORS_ORIGINS ?? '')
29 .split(',')
30 .map((value) => value.trim())
31 .filter(Boolean);
32 app.use(
33 cors({
34 origin(origin, callback) {
35 if (!origin || testMode || allowedOrigins.includes(origin)) {
36 return callback(null, true);
37 }
38 const error = new Error('cors_origin_denied');
39 error.code = 'CORS_ORIGIN_DENIED';
40 return callback(error);
41 },
42 methods: ['GET', 'POST', 'PATCH', 'PUT', 'DELETE', 'OPTIONS'],
43 allowedHeaders: ['Content-Type', 'Authorization'],
44 maxAge: 86400,
45 }),
46 );
47 app.use(express.json({ limit: '64kb' }));
48
49 const pool = new Pool({ connectionString: process.env.DATABASE_URL });
50 const jwtSecret = process.env.JWT_SECRET;
51 if (!jwtSecret || jwtSecret.length < 32) throw new Error('JWT_SECRET must be at least 32 characters');
52
53 const sha256 = (value) => crypto.createHash('sha256').update(value).digest('hex');
54 const randomToken = () => crypto.randomBytes(32).toString('base64url');
55 const testMode = process.env.NODE_ENV === 'test';
56 const emailProvider = createEmailProvider();
57 const auth = createSessionAuth({ pool, jwtSecret });
58 const uuid = (value) => typeof value === 'string' && /^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(value);
59
60 async function familyAccess(familyId, userId, { roles = [], admin = false } = {}) {
61 if (!uuid(familyId)) return false;
62 const r = await pool.query(
63 `select m.role,m.is_admin from family_membership m
64 join family_workspace f on f.id=m.family_id
65 where m.family_id=$1 and m.user_id=$2 and m.ended_at is null and f.archived_at is null`,
66 [familyId, userId],
67 );
68 if (!r.rowCount) return false;
69 return (admin && r.rows[0].is_admin) || roles.includes(r.rows[0].role);
70 }
71
72 async function familyAdminTransaction(familyId, identity, operation) {
73 const userId = identity.sub;
74 if (!uuid(familyId)) return { status: 403, body: { error: 'forbidden' } };
75 const client = await pool.connect();
76 try {
77 await client.query('begin');
78 const family = await client.query('select id from family_workspace where id=$1 and archived_at is null for update', [familyId]);
79 const membership = family.rowCount ? await client.query(
80 `select 1 from family_membership m join app_user u on u.id=m.user_id
81 where m.family_id=$1 and m.user_id=$2 and m.ended_at is null
82 and m.is_admin and u.disabled_at is null for update of m,u`, [familyId, userId],
83 ) : { rowCount: 0 };
84 const result = membership.rowCount ? await operation(client) : { status: 403, body: { error: 'forbidden' } };
85 const session = await client.query(`select 1 from auth_session s join app_user u on u.id=s.user_id
86 where s.id=$1 and s.user_id=$2 and s.revoked_at is null
87 and s.expires_at>statement_timestamp() and u.disabled_at is null for share of s`, [identity.sid, userId]);
88 const freshSession = session.rowCount ? await client.query(`select 1 from auth_session
89 where id=$1 and user_id=$2 and revoked_at is null and expires_at>statement_timestamp()`, [identity.sid,userId]) : {rowCount:0};
90 if (!freshSession.rowCount || (identity.exp != null && identity.exp * 1000 <= Date.now())) {
91 await client.query('rollback');
92 return { status: 401, body: { error: 'session_invalid' } };
93 }
94 await client.query('commit');
95 return result;
96 } catch (error) {
97 await client.query('rollback').catch(() => {});
98 throw error;
99 } finally { client.release(); }
100 }
101 function familyResponse(res, result) {
102 return result.body === undefined ? res.status(result.status).end() : res.status(result.status).json(result.body);
103 }
104 async function familyAudit(client, familyId, userId, action, targetType, targetId) {
105 await client.query('insert into access_audit(actor_user_id,family_id,action,target_type,target_id) values($1,$2,$3,$4,$5)', [userId, familyId, action, targetType, targetId]);
106 }
107
108 app.get('/health', async (_req, res) => {
109 const r = await pool.query('select 1 as ok');
110 res.json({
111 status: r.rows[0].ok === 1 ? 'ok' : 'degraded',
112 emailProviderConfigured: emailProvider.configured,
113 });
114 });
115
116 app.use('/v1/auth', createAuthRouter({ pool, jwtSecret, auth, emailProvider }));
117
118 app.use('/v1/profile', createProfileRouter({ pool, auth }));
119 app.use('/v1', createChildIdentityRouter({ pool, auth, jwtSecret }));
120
121 app.get('/v1/families', auth, async (req, res) => {
122 const r = await pool.query(
123 `select f.id,f.name,m.role,m.is_admin
124 from family_membership m
125 join family_workspace f on f.id=m.family_id
126 where m.user_id=$1 and m.ended_at is null and f.archived_at is null
127 order by f.created_at`,
128 [req.identity.sub],
129 );
130 res.json({ families: r.rows });
131 });
132
133 app.post('/v1/families', auth, async (req, res) => {
134 const name = String(req.body.name ?? '').trim();
135 if (!name || name.length > 120) return res.status(400).json({ error: 'invalid_name' });
136
137 const creatorRole = ['parent_guardian', 'adult_member'].includes(req.body.role)
138 ? req.body.role
139 : 'adult_member';
140 const c = await pool.connect();
141 try {
142 await c.query('begin');
143 const creator = await c.query('select id from app_user where id=$1 and disabled_at is null for update', [req.identity.sub]);
144 if (!creator.rowCount) {
145 await c.query('rollback');
146 return res.status(401).json({ error: 'session_invalid' });
147 }
148 // Profiles can be edited without an app_user lock. Acquire that row in a
149 // separate statement after the account lock, so a pre-wait join snapshot
150 // cannot confer administration using an obsolete birth date.
151 const profile = (await c.query(`select birth_date,
152 (birth_date is not null and birth_date>(current_date-interval '18 years')::date) known_minor
153 from profile where user_id=$1 for update`, [req.identity.sub])).rows[0];
154 if (profile?.known_minor) {
155 await c.query('rollback');
156 return res.status(403).json({ error: 'minor_cannot_admin' });
157 }
158 if (!profile?.birth_date && (await c.query(`select 1 from family_membership m
159 join family_workspace f on f.id=m.family_id where m.user_id=$1 and m.ended_at is null
160 and m.role='teen_minor' and f.archived_at is null limit 1`, [req.identity.sub])).rowCount) {
161 await c.query('rollback');
162 return res.status(403).json({ error: 'age_confirmation_required' });
163 }
164 const f = await c.query(
165 'insert into family_workspace(name,created_by) values($1,$2) returning id,name',
166 [name, req.identity.sub],
167 );
168 await c.query(
169 'insert into family_membership(family_id,user_id,role,is_admin) values($1,$2,$3,true)',
170 [f.rows[0].id, req.identity.sub, creatorRole],
171 );
172 await c.query(
173 "insert into access_audit(actor_user_id,family_id,action,target_type,target_id) values($1,$2,'family.create','family',$3)",
174 [req.identity.sub, f.rows[0].id, String(f.rows[0].id)],
175 );
176 const session = await c.query(`select 1 from auth_session where id=$1 and user_id=$2
177 and revoked_at is null and expires_at>statement_timestamp() for share`, [req.identity.sid,req.identity.sub]);
178 const freshSession = session.rowCount ? await c.query(`select 1 from auth_session
179 where id=$1 and user_id=$2 and revoked_at is null and expires_at>statement_timestamp()`, [req.identity.sid,req.identity.sub]) : {rowCount:0};
180 if (!freshSession.rowCount || (req.identity.exp != null && req.identity.exp * 1000 <= Date.now())) {
181 await c.query('rollback');
182 return res.status(401).json({ error: 'session_invalid' });
183 }
184 await c.query('commit');
185 res.status(201).json(f.rows[0]);
186 } catch (e) {
187 await c.query('rollback');
188 throw e;
189 } finally {
190 c.release();
191 }
192 });
193
194 app.get('/v1/families/:familyId', auth, async (req, res) => {
195 if (!await familyAccess(req.params.familyId, req.identity.sub, { roles: ['parent_guardian', 'teen_minor', 'adult_member'] })) return res.status(403).json({ error: 'forbidden' });
196 const result = await pool.query(`select f.id,f.name,m.role,m.is_admin from family_workspace f
197 join family_membership m on m.family_id=f.id where f.id=$1 and f.archived_at is null
198 and m.user_id=$2 and m.ended_at is null`, [req.params.familyId, req.identity.sub]);
199 if (!result.rowCount) return res.status(403).json({ error: 'forbidden' });
200 res.json(result.rows[0]);
201 });
202
203 app.patch('/v1/families/:familyId', auth, async (req, res) => {
204 const name = String(req.body?.name ?? '').trim();
205 if (!name || name.length > 120) return res.status(400).json({ error: 'invalid_name' });
206 const result = await familyAdminTransaction(req.params.familyId, req.identity, async (client) => {
207 const updated = await client.query('update family_workspace set name=$2 where id=$1 returning id,name', [req.params.familyId, name]);
208 await familyAudit(client, req.params.familyId, req.identity.sub, 'family.rename', 'family', req.params.familyId);
209 return { status: 200, body: updated.rows[0] };
210 });
211 familyResponse(res, result);
212 });
213
214 app.delete('/v1/families/:familyId', auth, async (req, res) => {
215 const result = await familyAdminTransaction(req.params.familyId, req.identity, async (client) => {
216 await client.query('update family_workspace set archived_at=now() where id=$1', [req.params.familyId]);
217 await client.query("update family_invitation set status='revoked' where family_id=$1 and status='pending'", [req.params.familyId]);
218 await client.query('update guardian_relationship set active=false where family_id=$1', [req.params.familyId]);
219 await familyAudit(client, req.params.familyId, req.identity.sub, 'family.archive', 'family', req.params.familyId);
220 return { status: 204 };
221 });
222 familyResponse(res, result);
223 });
224
225 app.delete('/v1/families/:familyId/members/:userId', auth, async (req, res) => {
226 if (!uuid(req.params.userId)) return res.status(400).json({ error: 'invalid_member' });
227 const result = await familyAdminTransaction(req.params.familyId, req.identity, async (client) => {
228 const target = await client.query('select m.is_admin,u.disabled_at from family_membership m join app_user u on u.id=m.user_id where m.family_id=$1 and m.user_id=$2 and m.ended_at is null for update of m', [req.params.familyId, req.params.userId]);
229 if (!target.rowCount) return { status: 204 };
230 if (target.rows[0].is_admin && !target.rows[0].disabled_at) {
231 const count = await client.query('select count(*)::int as n from family_membership m join app_user u on u.id=m.user_id where m.family_id=$1 and m.ended_at is null and m.is_admin and u.disabled_at is null', [req.params.familyId]);
232 if (count.rows[0].n <= 1) return { status: 409, body: { error: 'last_admin_required' } };
233 }
234 await client.query('update family_membership set ended_at=now(),is_admin=false where family_id=$1 and user_id=$2', [req.params.familyId, req.params.userId]);
235 await client.query('update guardian_relationship set active=false where family_id=$1 and (guardian_user_id=$2 or minor_user_id=$2)', [req.params.familyId, req.params.userId]);
236 await client.query(`update family_invitation i set status='revoked' from app_user u where u.id=$2
237 and i.family_id=$1 and i.status='pending' and (i.invited_by=u.id
238 or i.invited_email_normalized=u.email_normalized or i.invited_phone_normalized=u.phone_normalized)`, [req.params.familyId, req.params.userId]);
239 await familyAudit(client, req.params.familyId, req.identity.sub, 'membership.end', 'membership', req.params.userId);
240 return { status: 204 };
241 });
242 familyResponse(res, result);
243 });
244
245 app.get('/v1/families/:familyId/members', auth, async (req, res) => {
246 const allowed = await familyAccess(req.params.familyId, req.identity.sub, {
247 roles: ['parent_guardian', 'teen_minor', 'adult_member'],
248 });
249 if (!allowed) return res.status(403).json({ error: 'forbidden' });
250
251 const r = await pool.query(
252 `select m.user_id,m.role,m.is_admin,m.version,m.updated_at,
253 (u.disabled_at is not null) as account_disabled,p.display_name,p.theme_preference
254 from family_membership m
255 join app_user u on u.id=m.user_id
256 join profile p on p.user_id=m.user_id
257 join family_workspace f on f.id=m.family_id
258 where m.family_id=$1 and m.ended_at is null and f.archived_at is null
259 and exists(select 1 from family_membership viewer where viewer.family_id=m.family_id and viewer.user_id=$2 and viewer.ended_at is null)
260 order by m.joined_at`,
261 [req.params.familyId, req.identity.sub],
262 );
263 res.json({ members: r.rows });
264 });
265
266 app.post('/v1/families/:familyId/invitations', auth, async (req, res) => {
267 const allowed = await familyAccess(req.params.familyId, req.identity.sub, {
268 admin: true,
269 });
270 if (!allowed) return res.status(403).json({ error: 'forbidden' });
271
272 const email = normalizeEmail(req.body.email);
273 const phone = req.body.phone == null ? null : normalizePhone(req.body.phone);
274 const role = String(req.body.role ?? '');
275 const themePreference = String(req.body.themePreference ?? '');
276 const allowedRoles = ['parent_guardian', 'teen_minor', 'adult_member'];
277 const allowedThemes = ['girl_pink', 'boy_blue', 'adult_blue', 'custom'];
278 const resolvedTheme = allowedThemes.includes(themePreference)
279 ? themePreference
280 : role === 'teen_minor'
281 ? 'girl_pink'
282 : 'adult_blue';
283 if ((email && phone) || (!email && !phone) || (email && !isEmail(email)) ||
284 (req.body.phone != null && !phone) || !allowedRoles.includes(role)) {
285 return res.status(400).json({ error: 'invalid_invitation' });
286 }
287
288 const token = randomToken();
289 const result = await familyAdminTransaction(req.params.familyId, req.identity, async (client) => {
290 const activeMember = await client.query(
291 `select 1
292 from family_membership m
293 join app_user u on u.id=m.user_id
294 where m.family_id=$1
295 and m.ended_at is null
296 and ((u.email_normalized=$2 and $2::text is not null)
297 or (u.phone_normalized=$3 and $3::text is not null))`,
298 [req.params.familyId, email || null, phone],
299 );
300 if (activeMember.rowCount) {
301 return { status: 409, body: { error: 'member_already_active' } };
302 }
303
304 const r = await client.query(
305 "insert into family_invitation(family_id,invited_email_normalized,invited_phone_normalized,intended_role,intended_theme,token_digest,invited_by,expires_at) values($1,$2,$3,$4,$5,$6,$7,now()+interval '7 days') returning id,expires_at",
306 [req.params.familyId, email || null, phone, role, resolvedTheme, sha256(token), req.identity.sub],
307 );
308 await familyAudit(client, req.params.familyId, req.identity.sub, 'invitation.create', 'invitation', r.rows[0].id);
309 return { status: 201, body: r.rows[0] };
310 });
311 if (result.status !== 201) return familyResponse(res, result);
312
313 const baseUrl = process.env.PUBLIC_APP_URL ?? 'https://app.lifeguide.invalid';
314 const invitationLink = `${baseUrl}/accept-invitation?token=${encodeURIComponent(token)}`;
315 // The authenticated family administrator can copy the link even without a provider.
316 res.status(201).json({
317 ...result.body,
318 invitationToken: token,
319 invitationLink,
320 });
321 if (email) await safelyDeliver(emailProvider, {
322 to: email,
323 subject: 'دعوت به خانواده در لایف‌گاید',
324 text: `برای پیوستن به خانواده در LifeGuide / لایف‌گاید این لینک را باز کن: ${invitationLink}\nاین لینک ۷ روز اعتبار دارد.`,
325 }, { attemptId: result.body.id });
326 });
327
328 app.post('/v1/invitations/accept', auth, async (req, res) => {
329 const digest = sha256(String(req.body.token ?? ''));
330 const client = await pool.connect();
331 try {
332 await client.query('begin');
333 const preliminary = await client.query('select family_id,invited_by from family_invitation where token_digest=$1', [digest]);
334 const family = preliminary.rowCount ? await client.query('select 1 from family_workspace where id=$1 and archived_at is null for update', [preliminary.rows[0].family_id]) : { rowCount: 0 };
335 const inviter = family.rowCount ? await client.query(`select 1 from family_membership m
336 join app_user u on u.id=m.user_id where m.family_id=$1 and m.user_id=$2
337 and m.ended_at is null and m.is_admin and u.disabled_at is null for update of m`, [preliminary.rows[0].family_id, preliminary.rows[0].invited_by]) : { rowCount: 0 };
338 if (!inviter.rowCount) {
339 await client.query('rollback');
340 return res.status(400).json({ error: 'invalid_or_expired_invitation' });
341 }
342 await client.query('select id from app_user where id=$1 for update', [req.identity.sub]);
343 if ((await client.query('select 1 from managed_child where user_id=$1', [req.identity.sub])).rowCount) {
344 await client.query('rollback');
345 return res.status(403).json({ error: 'managed_child_membership_locked' });
346 }
347 const invitation = await client.query(
348 `select i.id,i.family_id,i.intended_role,i.intended_theme,
349 i.invited_email_normalized,i.invited_phone_normalized,
350 u.email_normalized,u.email_verified_at,u.phone_normalized,u.phone_verified_at
351 from family_invitation i
352 join app_user u on u.id=$2
353 where i.token_digest=$1
354 and i.status='pending'
355 and i.expires_at>statement_timestamp()
356 and u.disabled_at is null
357 for update of i`,
358 [digest, req.identity.sub],
359 );
360 if (!invitation.rowCount) {
361 await client.query('rollback');
362 return res.status(400).json({ error: 'invalid_or_expired_invitation' });
363 }
364 const row = invitation.rows[0];
365 const matchesEmail = row.invited_email_normalized && row.email_verified_at &&
366 row.invited_email_normalized === row.email_normalized;
367 const matchesPhone = row.invited_phone_normalized && row.phone_verified_at &&
368 row.invited_phone_normalized === row.phone_normalized;
369 if (!matchesEmail && !matchesPhone) {
370 await client.query('rollback');
371 return res.status(403).json({ error: 'invitation_contact_mismatch' });
372 }
373
374 // Preserve the existing active-member conflict before validating any new
375 // role. All membership changes for this family share the family row lock;
376 // an older invitation cannot replace an already active membership.
377 const activeMembership = await client.query(`select 1 from family_membership
378 where family_id=$1 and user_id=$2 and ended_at is null`, [row.family_id, req.identity.sub]);
379 if (activeMembership.rowCount) {
380 await client.query('rollback');
381 return res.status(409).json({ error: 'member_already_active' });
382 }
383
384 // The family/invitation locks above serialize acceptance with transfer and
385 // revocation. The recipient account is already locked; lock the editable
386 // profile separately so a waiting statement cannot use an obsolete age.
387 // Profile category and theme never grant adult family permissions.
388 const profile = (await client.query(`select birth_date,
389 (birth_date is not null and birth_date>(current_date-interval '18 years')::date) known_minor
390 from profile where user_id=$1 for update`, [req.identity.sub])).rows[0];
391 if (row.intended_role !== 'teen_minor') {
392 if (profile?.known_minor) {
393 await client.query('rollback');
394 return res.status(403).json({ error: 'minor_role_upgrade_forbidden' });
395 }
396 if (!profile?.birth_date && (await client.query(`select 1 from family_membership m
397 join family_workspace f on f.id=m.family_id where m.user_id=$1 and m.ended_at is null
398 and m.role='teen_minor' and f.archived_at is null limit 1`, [req.identity.sub])).rowCount) {
399 await client.query('rollback');
400 return res.status(403).json({ error: 'age_confirmation_required' });
401 }
402 }
403
404 const membership = await client.query(
405 `insert into family_membership(family_id,user_id,role)
406 values($1,$2,$3)
407 on conflict(family_id,user_id)
408 do update set role=excluded.role,ended_at=null,is_admin=false,joined_at=now()
409 where family_membership.ended_at is not null returning user_id`,
410 [row.family_id, req.identity.sub, row.intended_role],
411 );
412 if (!membership.rowCount) {
413 await client.query('rollback');
414 return res.status(409).json({ error: 'member_already_active' });
415 }
416 await client.query(
417 "update family_invitation set status='accepted',accepted_by=$2,accepted_at=now() where id=$1",
418 [row.id, req.identity.sub],
419 );
420 if (row.intended_theme) {
421 await client.query(
422 'update profile set theme_preference=$2,updated_at=now() where user_id=$1',
423 [req.identity.sub, row.intended_theme],
424 );
425 }
426 await client.query(
427 "insert into access_audit(actor_user_id,family_id,action,target_type,target_id) values($1,$2,'invitation.accept','membership',$3)",
428 [req.identity.sub, row.family_id, String(req.identity.sub)],
429 );
430 const session = await client.query(`select 1 from app_user u join auth_session s on s.user_id=u.id
431 where u.id=$1 and u.disabled_at is null and s.id=$2 and s.revoked_at is null
432 and s.expires_at>statement_timestamp() for share of s`, [req.identity.sub, req.identity.sid]);
433 const freshSession = session.rowCount ? await client.query(`select 1 from auth_session
434 where id=$1 and user_id=$2 and revoked_at is null and expires_at>statement_timestamp()`, [req.identity.sid,req.identity.sub]) : {rowCount:0};
435 if (!freshSession.rowCount || (req.identity.exp != null && req.identity.exp * 1000 <= Date.now())) {
436 await client.query('rollback');
437 return res.status(401).json({ error: 'session_invalid' });
438 }
439 const unexpired = await client.query('select 1 from family_invitation where id=$1 and expires_at>statement_timestamp()', [row.id]);
440 if (!unexpired.rowCount) {
441 await client.query('rollback');
442 return res.status(400).json({ error: 'invalid_or_expired_invitation' });
443 }
444 await client.query('commit');
445 res.status(204).end();
446 } catch (error) {
447 await client.query('rollback').catch(() => {});
448 throw error;
449 } finally {
450 client.release();
451 }
452 });
453
454 app.post('/v1/families/:familyId/guardians', auth, async (req, res) => {
455 const guardianUserId = String(req.body?.guardianUserId ?? '');
456 const minorUserId = String(req.body?.minorUserId ?? '');
457 if (!uuid(guardianUserId) || !uuid(minorUserId)) return res.status(400).json({ error: 'invalid_guardian_relationship' });
458 const result = await familyAdminTransaction(req.params.familyId, req.identity, async (client) => {
459 if ((await client.query('select 1 from managed_child where user_id=$1', [minorUserId])).rowCount) {
460 return { status: 403, body: { error: 'managed_guardian_invitation_required' } };
461 }
462 const roles = await client.query(`select m.user_id,m.role from family_membership m
463 join app_user u on u.id=m.user_id where m.family_id=$1 and m.user_id in ($2,$3)
464 and m.ended_at is null and u.disabled_at is null for update of m`, [req.params.familyId, guardianUserId, minorUserId]);
465 const map = new Map(roles.rows.map((row) => [row.user_id, row.role]));
466 if (map.get(guardianUserId) !== 'parent_guardian' || map.get(minorUserId) !== 'teen_minor') return { status: 400, body: { error: 'invalid_guardian_relationship' } };
467 await client.query(`insert into guardian_relationship(family_id,guardian_user_id,minor_user_id,active)
468 values($1,$2,$3,true) on conflict(family_id,guardian_user_id,minor_user_id) do update set active=true`, [req.params.familyId, guardianUserId, minorUserId]);
469 await familyAudit(client, req.params.familyId, req.identity.sub, 'guardian.activate', 'guardian_relationship', guardianUserId);
470 return { status: 204 };
471 });
472 familyResponse(res, result);
473 });
474
475 app.delete('/v1/families/:familyId/guardians', auth, async (req, res) => {
476 const guardianUserId = String(req.body?.guardianUserId ?? '');
477 const minorUserId = String(req.body?.minorUserId ?? '');
478 if (!uuid(guardianUserId) || !uuid(minorUserId)) return res.status(400).json({ error: 'invalid_guardian_relationship' });
479 const result = await familyAdminTransaction(req.params.familyId, req.identity, async (client) => {
480 if ((await client.query('select 1 from managed_child where user_id=$1', [minorUserId])).rowCount) {
481 return { status: 403, body: { error: 'managed_guardian_flow_required' } };
482 }
483 await client.query('update guardian_relationship set active=false where family_id=$1 and guardian_user_id=$2 and minor_user_id=$3', [req.params.familyId, guardianUserId, minorUserId]);
484 await familyAudit(client, req.params.familyId, req.identity.sub, 'guardian.deactivate', 'guardian_relationship', guardianUserId);
485 return { status: 204 };
486 });
487 familyResponse(res, result);
488 });
489
490 app.use('/v1', createSchoolCrudRouter({ pool, auth }));
491 app.use('/v1', createSchoolLifecycleRouter({ pool, auth }));
492 app.use('/v1', createPhase3Router({ pool, auth }));
493 app.use('/v1', createPhase4Router({ pool, auth }));
494 app.use('/v1', createPhase6Router({ pool, auth }));
495 app.use('/v1', createLearningLibraryRouter({ pool, auth }));
496 app.use('/v1', createLearningFeedbackRouter({ pool, auth }));
497 app.use('/v1', createLearningAssessmentRouter({ pool, auth }));
498 app.use('/v1', createContentReviewRouter({ pool, auth }));
499 app.use('/v1', createFamilyLifecycleRouter({ pool, auth }));
500 app.use('/v1', createStudySessionsRouter({ pool, auth }));
501
502 app.use(operationalErrorHandler);
503
504 const invokedDirectly = process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href;
505 if (!testMode && invokedDirectly) {
506 // Production must include the shared request/security/IP-quota middleware.
507 // Tests may import app; a second production listener would bypass those guards.
508 throw new Error('production_entrypoint_required: use npm start (src/entrypoint.js)');
509 }
510
511 export { app, pool };
512 export default app;