LifeMate — Personal, Family & Learning Companion

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