LifeMate — Personal, Family & Learning Companion

feat/aparat-learning-library
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 408 lines 20 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 { configureTrustedProxy, operationalErrorHandler } from './operations.js';
13 import { createSessionAuth } from './session_auth.js';
14 import { createAuthRouter } from './auth_router.js';
15 import { createStudySessionsRouter } from './study_sessions.js';
16 import { createProfileRouter } from './profile_router.js';
17 import { createSchoolCrudRouter } from './school_crud_router.js';
18 import { normalizeEmail, normalizePhone, isEmail } from './auth_contacts.js';
19 import { createEmailProvider, safelyDeliver } from './auth_delivery.js';
20
21 const { Pool } = pg;
22 const app = express();
23 configureTrustedProxy(app);
24 const allowedOrigins = (process.env.CORS_ORIGINS ?? '')
25 .split(',')
26 .map((value) => value.trim())
27 .filter(Boolean);
28 app.use(
29 cors({
30 origin(origin, callback) {
31 if (!origin || testMode || allowedOrigins.includes(origin)) {
32 return callback(null, true);
33 }
34 const error = new Error('cors_origin_denied');
35 error.code = 'CORS_ORIGIN_DENIED';
36 return callback(error);
37 },
38 methods: ['GET', 'POST', 'PATCH', 'PUT', 'DELETE', 'OPTIONS'],
39 allowedHeaders: ['Content-Type', 'Authorization'],
40 maxAge: 86400,
41 }),
42 );
43 app.use(express.json({ limit: '64kb' }));
44
45 const pool = new Pool({ connectionString: process.env.DATABASE_URL });
46 const jwtSecret = process.env.JWT_SECRET;
47 if (!jwtSecret || jwtSecret.length < 32) throw new Error('JWT_SECRET must be at least 32 characters');
48
49 const sha256 = (value) => crypto.createHash('sha256').update(value).digest('hex');
50 const randomToken = () => crypto.randomBytes(32).toString('base64url');
51 const testMode = process.env.NODE_ENV === 'test';
52 const emailProvider = createEmailProvider();
53 const auth = createSessionAuth({ pool, jwtSecret });
54 const uuid = (value) => typeof value === 'string' && /^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(value);
55
56 async function familyAccess(familyId, userId, { roles = [], admin = false } = {}) {
57 if (!uuid(familyId)) return false;
58 const r = await pool.query(
59 `select m.role,m.is_admin from family_membership m
60 join family_workspace f on f.id=m.family_id
61 where m.family_id=$1 and m.user_id=$2 and m.ended_at is null and f.archived_at is null`,
62 [familyId, userId],
63 );
64 if (!r.rowCount) return false;
65 return (admin && r.rows[0].is_admin) || roles.includes(r.rows[0].role);
66 }
67
68 async function familyAdminTransaction(familyId, userId, operation) {
69 if (!uuid(familyId)) return { status: 403, body: { error: 'forbidden' } };
70 const client = await pool.connect();
71 try {
72 await client.query('begin');
73 const family = await client.query('select id from family_workspace where id=$1 and archived_at is null for update', [familyId]);
74 const membership = family.rowCount ? await client.query(
75 `select 1 from family_membership m join app_user u on u.id=m.user_id
76 where m.family_id=$1 and m.user_id=$2 and m.ended_at is null
77 and m.is_admin and u.disabled_at is null for update of m,u`, [familyId, userId],
78 ) : { rowCount: 0 };
79 const result = membership.rowCount ? await operation(client) : { status: 403, body: { error: 'forbidden' } };
80 await client.query('commit');
81 return result;
82 } catch (error) {
83 await client.query('rollback').catch(() => {});
84 throw error;
85 } finally { client.release(); }
86 }
87 function familyResponse(res, result) {
88 return result.body === undefined ? res.status(result.status).end() : res.status(result.status).json(result.body);
89 }
90 async function familyAudit(client, familyId, userId, action, targetType, targetId) {
91 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]);
92 }
93
94 app.get('/health', async (_req, res) => {
95 const r = await pool.query('select 1 as ok');
96 res.json({
97 status: r.rows[0].ok === 1 ? 'ok' : 'degraded',
98 emailProviderConfigured: emailProvider.configured,
99 });
100 });
101
102 app.use('/v1/auth', createAuthRouter({ pool, jwtSecret, auth, emailProvider }));
103
104 app.use('/v1/profile', createProfileRouter({ pool, auth }));
105
106 app.get('/v1/families', auth, async (req, res) => {
107 const r = await pool.query(
108 `select f.id,f.name,m.role,m.is_admin
109 from family_membership m
110 join family_workspace f on f.id=m.family_id
111 where m.user_id=$1 and m.ended_at is null and f.archived_at is null
112 order by f.created_at`,
113 [req.identity.sub],
114 );
115 res.json({ families: r.rows });
116 });
117
118 app.post('/v1/families', auth, async (req, res) => {
119 const name = String(req.body.name ?? '').trim();
120 if (!name || name.length > 120) return res.status(400).json({ error: 'invalid_name' });
121
122 const creatorRole = ['parent_guardian', 'adult_member'].includes(req.body.role)
123 ? req.body.role
124 : 'adult_member';
125 const c = await pool.connect();
126 try {
127 await c.query('begin');
128 const f = await c.query(
129 'insert into family_workspace(name,created_by) values($1,$2) returning id,name',
130 [name, req.identity.sub],
131 );
132 await c.query(
133 'insert into family_membership(family_id,user_id,role,is_admin) values($1,$2,$3,true)',
134 [f.rows[0].id, req.identity.sub, creatorRole],
135 );
136 await c.query(
137 "insert into access_audit(actor_user_id,family_id,action,target_type,target_id) values($1,$2,'family.create','family',$3)",
138 [req.identity.sub, f.rows[0].id, String(f.rows[0].id)],
139 );
140 await c.query('commit');
141 res.status(201).json(f.rows[0]);
142 } catch (e) {
143 await c.query('rollback');
144 throw e;
145 } finally {
146 c.release();
147 }
148 });
149
150 app.get('/v1/families/:familyId', auth, async (req, res) => {
151 if (!await familyAccess(req.params.familyId, req.identity.sub, { roles: ['parent_guardian', 'teen_minor', 'adult_member'] })) return res.status(403).json({ error: 'forbidden' });
152 const result = await pool.query(`select f.id,f.name,m.role,m.is_admin from family_workspace f
153 join family_membership m on m.family_id=f.id where f.id=$1 and f.archived_at is null
154 and m.user_id=$2 and m.ended_at is null`, [req.params.familyId, req.identity.sub]);
155 if (!result.rowCount) return res.status(403).json({ error: 'forbidden' });
156 res.json(result.rows[0]);
157 });
158
159 app.patch('/v1/families/:familyId', auth, async (req, res) => {
160 const name = String(req.body?.name ?? '').trim();
161 if (!name || name.length > 120) return res.status(400).json({ error: 'invalid_name' });
162 const result = await familyAdminTransaction(req.params.familyId, req.identity.sub, async (client) => {
163 const updated = await client.query('update family_workspace set name=$2 where id=$1 returning id,name', [req.params.familyId, name]);
164 await familyAudit(client, req.params.familyId, req.identity.sub, 'family.rename', 'family', req.params.familyId);
165 return { status: 200, body: updated.rows[0] };
166 });
167 familyResponse(res, result);
168 });
169
170 app.delete('/v1/families/:familyId', auth, async (req, res) => {
171 const result = await familyAdminTransaction(req.params.familyId, req.identity.sub, async (client) => {
172 await client.query('update family_workspace set archived_at=now() where id=$1', [req.params.familyId]);
173 await client.query("update family_invitation set status='revoked' where family_id=$1 and status='pending'", [req.params.familyId]);
174 await client.query('update guardian_relationship set active=false where family_id=$1', [req.params.familyId]);
175 await familyAudit(client, req.params.familyId, req.identity.sub, 'family.archive', 'family', req.params.familyId);
176 return { status: 204 };
177 });
178 familyResponse(res, result);
179 });
180
181 app.delete('/v1/families/:familyId/members/:userId', auth, async (req, res) => {
182 if (!uuid(req.params.userId)) return res.status(400).json({ error: 'invalid_member' });
183 const result = await familyAdminTransaction(req.params.familyId, req.identity.sub, async (client) => {
184 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]);
185 if (!target.rowCount) return { status: 204 };
186 if (target.rows[0].is_admin && !target.rows[0].disabled_at) {
187 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]);
188 if (count.rows[0].n <= 1) return { status: 409, body: { error: 'last_admin_required' } };
189 }
190 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]);
191 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]);
192 await client.query(`update family_invitation i set status='revoked' from app_user u where u.id=$2
193 and i.family_id=$1 and i.status='pending' and (i.invited_by=u.id
194 or i.invited_email_normalized=u.email_normalized or i.invited_phone_normalized=u.phone_normalized)`, [req.params.familyId, req.params.userId]);
195 await familyAudit(client, req.params.familyId, req.identity.sub, 'membership.end', 'membership', req.params.userId);
196 return { status: 204 };
197 });
198 familyResponse(res, result);
199 });
200
201 app.get('/v1/families/:familyId/members', auth, async (req, res) => {
202 const allowed = await familyAccess(req.params.familyId, req.identity.sub, {
203 roles: ['parent_guardian', 'teen_minor', 'adult_member'],
204 });
205 if (!allowed) return res.status(403).json({ error: 'forbidden' });
206
207 const r = await pool.query(
208 `select m.user_id,m.role,m.is_admin,p.display_name,p.theme_preference
209 from family_membership m
210 join profile p on p.user_id=m.user_id
211 join family_workspace f on f.id=m.family_id
212 where m.family_id=$1 and m.ended_at is null and f.archived_at is null
213 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)
214 order by m.joined_at`,
215 [req.params.familyId, req.identity.sub],
216 );
217 res.json({ members: r.rows });
218 });
219
220 app.post('/v1/families/:familyId/invitations', auth, async (req, res) => {
221 const allowed = await familyAccess(req.params.familyId, req.identity.sub, {
222 admin: true,
223 });
224 if (!allowed) return res.status(403).json({ error: 'forbidden' });
225
226 const email = normalizeEmail(req.body.email);
227 const phone = req.body.phone == null ? null : normalizePhone(req.body.phone);
228 const role = String(req.body.role ?? '');
229 const themePreference = String(req.body.themePreference ?? '');
230 const allowedRoles = ['parent_guardian', 'teen_minor', 'adult_member'];
231 const allowedThemes = ['girl_pink', 'boy_blue', 'adult_blue', 'custom'];
232 const resolvedTheme = allowedThemes.includes(themePreference)
233 ? themePreference
234 : role === 'teen_minor'
235 ? 'girl_pink'
236 : 'adult_blue';
237 if ((email && phone) || (!email && !phone) || (email && !isEmail(email)) ||
238 (req.body.phone != null && !phone) || !allowedRoles.includes(role)) {
239 return res.status(400).json({ error: 'invalid_invitation' });
240 }
241
242 const token = randomToken();
243 const result = await familyAdminTransaction(req.params.familyId, req.identity.sub, async (client) => {
244 const activeMember = await client.query(
245 `select 1
246 from family_membership m
247 join app_user u on u.id=m.user_id
248 where m.family_id=$1
249 and m.ended_at is null
250 and ((u.email_normalized=$2 and $2::text is not null)
251 or (u.phone_normalized=$3 and $3::text is not null))`,
252 [req.params.familyId, email || null, phone],
253 );
254 if (activeMember.rowCount) {
255 return { status: 409, body: { error: 'member_already_active' } };
256 }
257
258 const r = await client.query(
259 "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",
260 [req.params.familyId, email || null, phone, role, resolvedTheme, sha256(token), req.identity.sub],
261 );
262 await familyAudit(client, req.params.familyId, req.identity.sub, 'invitation.create', 'invitation', r.rows[0].id);
263 return { status: 201, body: r.rows[0] };
264 });
265 if (result.status !== 201) return familyResponse(res, result);
266
267 const baseUrl = process.env.PUBLIC_APP_URL ?? 'https://app.lifeguide.invalid';
268 const invitationLink = `${baseUrl}/accept-invitation?token=${encodeURIComponent(token)}`;
269 // The authenticated family administrator can copy the link even without a provider.
270 res.status(201).json({
271 ...result.body,
272 invitationToken: token,
273 invitationLink,
274 });
275 if (email) await safelyDeliver(emailProvider, {
276 to: email,
277 subject: 'دعوت به خانواده در لایف‌گاید',
278 text: `برای پیوستن به خانواده در LifeGuide / لایف‌گاید این لینک را باز کن: ${invitationLink}\nاین لینک ۷ روز اعتبار دارد.`,
279 }, { attemptId: result.body.id });
280 });
281
282 app.post('/v1/invitations/accept', auth, async (req, res) => {
283 const digest = sha256(String(req.body.token ?? ''));
284 const client = await pool.connect();
285 try {
286 await client.query('begin');
287 const preliminary = await client.query('select family_id,invited_by from family_invitation where token_digest=$1', [digest]);
288 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 };
289 const inviter = family.rowCount ? await client.query(`select 1 from family_membership m
290 join app_user u on u.id=m.user_id where m.family_id=$1 and m.user_id=$2
291 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 };
292 if (!inviter.rowCount) {
293 await client.query('rollback');
294 return res.status(400).json({ error: 'invalid_or_expired_invitation' });
295 }
296 await client.query('select id from app_user where id=$1 for update', [req.identity.sub]);
297 const invitation = await client.query(
298 `select i.id,i.family_id,i.intended_role,i.intended_theme,
299 i.invited_email_normalized,i.invited_phone_normalized,
300 u.email_normalized,u.email_verified_at,u.phone_normalized,u.phone_verified_at
301 from family_invitation i
302 join app_user u on u.id=$2
303 where i.token_digest=$1
304 and i.status='pending'
305 and i.expires_at>now()
306 and u.disabled_at is null
307 for update of i`,
308 [digest, req.identity.sub],
309 );
310 if (!invitation.rowCount) {
311 await client.query('rollback');
312 return res.status(400).json({ error: 'invalid_or_expired_invitation' });
313 }
314 const row = invitation.rows[0];
315 const matchesEmail = row.invited_email_normalized && row.email_verified_at &&
316 row.invited_email_normalized === row.email_normalized;
317 const matchesPhone = row.invited_phone_normalized && row.phone_verified_at &&
318 row.invited_phone_normalized === row.phone_normalized;
319 if (!matchesEmail && !matchesPhone) {
320 await client.query('rollback');
321 return res.status(403).json({ error: 'invitation_contact_mismatch' });
322 }
323
324 const membership = await client.query(
325 `insert into family_membership(family_id,user_id,role)
326 values($1,$2,$3)
327 on conflict(family_id,user_id)
328 do update set role=excluded.role,ended_at=null,is_admin=false,joined_at=now()
329 where family_membership.ended_at is not null returning user_id`,
330 [row.family_id, req.identity.sub, row.intended_role],
331 );
332 if (!membership.rowCount) {
333 await client.query('rollback');
334 return res.status(409).json({ error: 'member_already_active' });
335 }
336 await client.query(
337 "update family_invitation set status='accepted',accepted_by=$2,accepted_at=now() where id=$1",
338 [row.id, req.identity.sub],
339 );
340 if (row.intended_theme) {
341 await client.query(
342 'update profile set theme_preference=$2,updated_at=now() where user_id=$1',
343 [req.identity.sub, row.intended_theme],
344 );
345 }
346 await client.query(
347 "insert into access_audit(actor_user_id,family_id,action,target_type,target_id) values($1,$2,'invitation.accept','membership',$3)",
348 [req.identity.sub, row.family_id, String(req.identity.sub)],
349 );
350 await client.query('commit');
351 res.status(204).end();
352 } catch (error) {
353 await client.query('rollback').catch(() => {});
354 throw error;
355 } finally {
356 client.release();
357 }
358 });
359
360 app.post('/v1/families/:familyId/guardians', auth, async (req, res) => {
361 const guardianUserId = String(req.body?.guardianUserId ?? '');
362 const minorUserId = String(req.body?.minorUserId ?? '');
363 if (!uuid(guardianUserId) || !uuid(minorUserId)) return res.status(400).json({ error: 'invalid_guardian_relationship' });
364 const result = await familyAdminTransaction(req.params.familyId, req.identity.sub, async (client) => {
365 const roles = await client.query(`select m.user_id,m.role from family_membership m
366 join app_user u on u.id=m.user_id where m.family_id=$1 and m.user_id in ($2,$3)
367 and m.ended_at is null and u.disabled_at is null for update of m`, [req.params.familyId, guardianUserId, minorUserId]);
368 const map = new Map(roles.rows.map((row) => [row.user_id, row.role]));
369 if (map.get(guardianUserId) !== 'parent_guardian' || map.get(minorUserId) !== 'teen_minor') return { status: 400, body: { error: 'invalid_guardian_relationship' } };
370 await client.query(`insert into guardian_relationship(family_id,guardian_user_id,minor_user_id,active)
371 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]);
372 await familyAudit(client, req.params.familyId, req.identity.sub, 'guardian.activate', 'guardian_relationship', guardianUserId);
373 return { status: 204 };
374 });
375 familyResponse(res, result);
376 });
377
378 app.delete('/v1/families/:familyId/guardians', auth, async (req, res) => {
379 const guardianUserId = String(req.body?.guardianUserId ?? '');
380 const minorUserId = String(req.body?.minorUserId ?? '');
381 if (!uuid(guardianUserId) || !uuid(minorUserId)) return res.status(400).json({ error: 'invalid_guardian_relationship' });
382 const result = await familyAdminTransaction(req.params.familyId, req.identity.sub, async (client) => {
383 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]);
384 await familyAudit(client, req.params.familyId, req.identity.sub, 'guardian.deactivate', 'guardian_relationship', guardianUserId);
385 return { status: 204 };
386 });
387 familyResponse(res, result);
388 });
389
390 app.use('/v1', createSchoolCrudRouter({ pool, auth }));
391 app.use('/v1', createPhase3Router({ pool, auth }));
392 app.use('/v1', createPhase4Router({ pool, auth }));
393 app.use('/v1', createPhase6Router({ pool, auth }));
394 app.use('/v1', createLearningLibraryRouter({ pool, auth }));
395 app.use('/v1', createLearningFeedbackRouter({ pool, auth }));
396 app.use('/v1', createLearningAssessmentRouter({ pool, auth }));
397 app.use('/v1', createStudySessionsRouter({ pool, auth }));
398
399 app.use(operationalErrorHandler);
400
401 const port = Number(process.env.PORT ?? 8080);
402 const invokedDirectly = process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href;
403 if (!testMode && invokedDirectly) {
404 app.listen(port, () => console.log(`LifeGuide API listening on ${port}`));
405 }
406
407 export { app, pool };
408 export default app;