LifeMate — Personal, Family & Learning Companion

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