LifeMate — Personal, Family & Learning Companion
fix/backend-request-safety
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
| 1 | import crypto from 'node:crypto'; |
| 2 | import { pathToFileURL } from 'node:url'; |
| 3 | import express from 'express'; |
| 4 | import argon2 from 'argon2'; |
| 5 | import jwt from 'jsonwebtoken'; |
| 6 | import pg from 'pg'; |
| 7 | import nodemailer from 'nodemailer'; |
| 8 | import cors from 'cors'; |
| 9 | import { createPhase3Router } from './phase3.js'; |
| 10 | import { createPhase4Router } from './phase4.js'; |
| 11 | import { createPhase6Router } from './phase6.js'; |
| 12 | import { operationalErrorHandler } from './operations.js'; |
| 13 | import { createSessionAuth } from './session_auth.js'; |
| 14 | |
| 15 | const { Pool } = pg; |
| 16 | const app = express(); |
| 17 | const allowedOrigins = (process.env.CORS_ORIGINS ?? '') |
| 18 | .split(',') |
| 19 | .map((value) => value.trim()) |
| 20 | .filter(Boolean); |
| 21 | app.use( |
| 22 | cors({ |
| 23 | origin(origin, callback) { |
| 24 | if (!origin || testMode || allowedOrigins.includes(origin)) { |
| 25 | return callback(null, true); |
| 26 | } |
| 27 | const error = new Error('cors_origin_denied'); |
| 28 | error.code = 'CORS_ORIGIN_DENIED'; |
| 29 | return callback(error); |
| 30 | }, |
| 31 | methods: ['GET', 'POST', 'PATCH', 'PUT', 'DELETE', 'OPTIONS'], |
| 32 | allowedHeaders: ['Content-Type', 'Authorization'], |
| 33 | maxAge: 86400, |
| 34 | }), |
| 35 | ); |
| 36 | app.use(express.json({ limit: '64kb' })); |
| 37 | |
| 38 | const pool = new Pool({ connectionString: process.env.DATABASE_URL }); |
| 39 | const jwtSecret = process.env.JWT_SECRET; |
| 40 | if (!jwtSecret || jwtSecret.length < 32) throw new Error('JWT_SECRET must be at least 32 characters'); |
| 41 | |
| 42 | const sha256 = (value) => crypto.createHash('sha256').update(value).digest('hex'); |
| 43 | const randomToken = () => crypto.randomBytes(32).toString('base64url'); |
| 44 | const normalizeEmail = (email) => String(email ?? '').trim().toLowerCase(); |
| 45 | const validPassword = (p) => typeof p === 'string' && p.length >= 10 && p.length <= 200; |
| 46 | const isEmail = (value) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value); |
| 47 | const testMode = process.env.NODE_ENV === 'test'; |
| 48 | |
| 49 | async function sendTransactionalEmail({ to, subject, text }) { |
| 50 | if (testMode) return { delivered: false, testMode: true }; |
| 51 | |
| 52 | const from = process.env.EMAIL_FROM; |
| 53 | if (!from) return { delivered: false, reason: 'provider_not_configured' }; |
| 54 | |
| 55 | const apiKey = process.env.RESEND_API_KEY; |
| 56 | if (apiKey) { |
| 57 | const response = await fetch('https://api.resend.com/emails', { |
| 58 | method: 'POST', |
| 59 | headers: { |
| 60 | Authorization: `Bearer ${apiKey}`, |
| 61 | 'Content-Type': 'application/json', |
| 62 | }, |
| 63 | body: JSON.stringify({ from, to: [to], subject, text }), |
| 64 | }); |
| 65 | if (!response.ok) throw new Error(`email_delivery_failed:${response.status}`); |
| 66 | return { delivered: true, provider: 'resend' }; |
| 67 | } |
| 68 | |
| 69 | const smtpHost = process.env.SMTP_HOST; |
| 70 | const smtpPort = Number(process.env.SMTP_PORT ?? 0); |
| 71 | if (smtpHost && smtpPort > 0) { |
| 72 | const transporter = nodemailer.createTransport({ |
| 73 | host: smtpHost, |
| 74 | port: smtpPort, |
| 75 | secure: process.env.SMTP_SECURE === 'true', |
| 76 | auth: process.env.SMTP_USER |
| 77 | ? { |
| 78 | user: process.env.SMTP_USER, |
| 79 | pass: process.env.SMTP_PASSWORD, |
| 80 | } |
| 81 | : undefined, |
| 82 | }); |
| 83 | await transporter.sendMail({ from, to, subject, text }); |
| 84 | return { delivered: true, provider: 'smtp' }; |
| 85 | } |
| 86 | |
| 87 | return { delivered: false, reason: 'provider_not_configured' }; |
| 88 | } |
| 89 | |
| 90 | const issueAccess = (userId, sessionId) => |
| 91 | jwt.sign( |
| 92 | { sub: userId, sid: sessionId, aud: 'lifemate-api' }, |
| 93 | jwtSecret, |
| 94 | { expiresIn: '15m', issuer: 'lifemate' }, |
| 95 | ); |
| 96 | |
| 97 | const auth = createSessionAuth({ pool, jwtSecret }); |
| 98 | |
| 99 | async function createOneTimeToken(client, userId, kind, minutes) { |
| 100 | const raw = randomToken(); |
| 101 | await client.query( |
| 102 | "insert into auth_token(user_id,kind,token_digest,expires_at) values($1,$2,$3,now()+($4 || ' minutes')::interval)", |
| 103 | [userId, kind, sha256(raw), String(minutes)], |
| 104 | ); |
| 105 | return raw; |
| 106 | } |
| 107 | |
| 108 | async function createSession(client, userId) { |
| 109 | const refreshToken = randomToken(); |
| 110 | const r = await client.query( |
| 111 | "insert into auth_session(user_id,refresh_digest,expires_at) values($1,$2,now()+interval '30 days') returning id", |
| 112 | [userId, sha256(refreshToken)], |
| 113 | ); |
| 114 | return { |
| 115 | accessToken: issueAccess(userId, r.rows[0].id), |
| 116 | refreshToken, |
| 117 | }; |
| 118 | } |
| 119 | |
| 120 | async function familyAccess(familyId, userId, { roles = [], admin = false } = {}) { |
| 121 | const r = await pool.query( |
| 122 | 'select role,is_admin from family_membership where family_id=$1 and user_id=$2 and ended_at is null', |
| 123 | [familyId, userId], |
| 124 | ); |
| 125 | if (!r.rowCount) return false; |
| 126 | return (admin && r.rows[0].is_admin) || roles.includes(r.rows[0].role); |
| 127 | } |
| 128 | |
| 129 | app.get('/health', async (_req, res) => { |
| 130 | const r = await pool.query('select 1 as ok'); |
| 131 | res.json({ |
| 132 | status: r.rows[0].ok === 1 ? 'ok' : 'degraded', |
| 133 | emailProviderConfigured: Boolean(process.env.EMAIL_FROM && (process.env.RESEND_API_KEY || (process.env.SMTP_HOST && process.env.SMTP_PORT))), |
| 134 | }); |
| 135 | }); |
| 136 | |
| 137 | app.post('/v1/auth/register', async (req, res) => { |
| 138 | const email = normalizeEmail(req.body.email); |
| 139 | const password = req.body.password; |
| 140 | const name = String(req.body.displayName ?? '').trim(); |
| 141 | if (!isEmail(email) || !validPassword(password) || !name) { |
| 142 | return res.status(400).json({ error: 'invalid_input' }); |
| 143 | } |
| 144 | |
| 145 | const client = await pool.connect(); |
| 146 | try { |
| 147 | await client.query('begin'); |
| 148 | const hash = await argon2.hash(password, { type: argon2.argon2id }); |
| 149 | const u = await client.query( |
| 150 | 'insert into app_user(identity_subject,email_normalized) values($1,$2) returning id', |
| 151 | [`local:${crypto.randomUUID()}`, email], |
| 152 | ); |
| 153 | await client.query( |
| 154 | "insert into profile(user_id,display_name,theme_preference) values($1,$2,'adult_blue')", |
| 155 | [u.rows[0].id, name], |
| 156 | ); |
| 157 | await client.query( |
| 158 | 'insert into auth_credential(user_id,password_hash) values($1,$2)', |
| 159 | [u.rows[0].id, hash], |
| 160 | ); |
| 161 | const verificationToken = await createOneTimeToken( |
| 162 | client, |
| 163 | u.rows[0].id, |
| 164 | 'email_verification', |
| 165 | 60 * 24, |
| 166 | ); |
| 167 | await client.query('commit'); |
| 168 | |
| 169 | const baseUrl = process.env.PUBLIC_APP_URL ?? 'https://app.lifemate.invalid'; |
| 170 | const delivery = await sendTransactionalEmail({ |
| 171 | to: email, |
| 172 | subject: 'تأیید حساب LifeMate', |
| 173 | text: `برای تأیید حساب LifeMate این لینک را باز کنید: ${baseUrl}/verify-email?token=${encodeURIComponent(verificationToken)}`, |
| 174 | }); |
| 175 | |
| 176 | res.status(201).json({ |
| 177 | userId: u.rows[0].id, |
| 178 | verificationToken: testMode ? verificationToken : undefined, |
| 179 | emailDelivery: delivery.delivered ? 'sent' : 'pending_configuration', |
| 180 | }); |
| 181 | } catch (e) { |
| 182 | await client.query('rollback').catch(() => {}); |
| 183 | if (e.code === '23505') return res.status(409).json({ error: 'account_exists' }); |
| 184 | throw e; |
| 185 | } finally { |
| 186 | client.release(); |
| 187 | } |
| 188 | }); |
| 189 | |
| 190 | app.post('/v1/auth/verify-email', async (req, res) => { |
| 191 | const digest = sha256(String(req.body.token ?? '')); |
| 192 | const client = await pool.connect(); |
| 193 | try { |
| 194 | await client.query('begin'); |
| 195 | const r = await client.query( |
| 196 | "select user_id from auth_token where kind='email_verification' and token_digest=$1 and used_at is null and expires_at>now() for update", |
| 197 | [digest], |
| 198 | ); |
| 199 | if (!r.rowCount) { |
| 200 | await client.query('rollback'); |
| 201 | return res.status(400).json({ error: 'invalid_or_expired_token' }); |
| 202 | } |
| 203 | await client.query('update auth_token set used_at=now() where token_digest=$1', [digest]); |
| 204 | await client.query( |
| 205 | 'update app_user set email_verified_at=coalesce(email_verified_at,now()) where id=$1', |
| 206 | [r.rows[0].user_id], |
| 207 | ); |
| 208 | await client.query('commit'); |
| 209 | res.status(204).end(); |
| 210 | } finally { |
| 211 | client.release(); |
| 212 | } |
| 213 | }); |
| 214 | |
| 215 | app.post('/v1/auth/login', async (req, res) => { |
| 216 | const email = normalizeEmail(req.body.email); |
| 217 | const password = String(req.body.password ?? ''); |
| 218 | const r = await pool.query( |
| 219 | 'select u.id,u.email_verified_at,c.password_hash from app_user u join auth_credential c on c.user_id=u.id where u.email_normalized=$1 and u.disabled_at is null', |
| 220 | [email], |
| 221 | ); |
| 222 | if (!r.rowCount || !(await argon2.verify(r.rows[0].password_hash, password))) { |
| 223 | return res.status(401).json({ error: 'invalid_credentials' }); |
| 224 | } |
| 225 | if (!r.rows[0].email_verified_at) { |
| 226 | return res.status(403).json({ error: 'email_not_verified' }); |
| 227 | } |
| 228 | |
| 229 | const client = await pool.connect(); |
| 230 | try { |
| 231 | const tokens = await createSession(client, r.rows[0].id); |
| 232 | res.json(tokens); |
| 233 | } finally { |
| 234 | client.release(); |
| 235 | } |
| 236 | }); |
| 237 | |
| 238 | app.post('/v1/auth/refresh', async (req, res) => { |
| 239 | const digest = sha256(String(req.body.refreshToken ?? '')); |
| 240 | const client = await pool.connect(); |
| 241 | try { |
| 242 | await client.query('begin'); |
| 243 | const r = await client.query( |
| 244 | `select s.id,s.user_id from auth_session s join app_user u on u.id=s.user_id |
| 245 | where s.refresh_digest=$1 and s.revoked_at is null and s.expires_at>now() |
| 246 | and u.disabled_at is null for update of s,u`, |
| 247 | [digest], |
| 248 | ); |
| 249 | if (!r.rowCount) { |
| 250 | await client.query('rollback'); |
| 251 | return res.status(401).json({ error: 'invalid_refresh_token' }); |
| 252 | } |
| 253 | |
| 254 | await client.query('update auth_session set revoked_at=now() where id=$1', [r.rows[0].id]); |
| 255 | const tokens = await createSession(client, r.rows[0].user_id); |
| 256 | await client.query('commit'); |
| 257 | res.json(tokens); |
| 258 | } finally { |
| 259 | client.release(); |
| 260 | } |
| 261 | }); |
| 262 | |
| 263 | app.post('/v1/auth/forgot-password', async (req, res) => { |
| 264 | const email = normalizeEmail(req.body.email); |
| 265 | const r = await pool.query( |
| 266 | 'select id from app_user where email_normalized=$1 and disabled_at is null', |
| 267 | [email], |
| 268 | ); |
| 269 | |
| 270 | let resetToken; |
| 271 | if (r.rowCount) { |
| 272 | const c = await pool.connect(); |
| 273 | try { |
| 274 | resetToken = await createOneTimeToken(c, r.rows[0].id, 'password_reset', 30); |
| 275 | } finally { |
| 276 | c.release(); |
| 277 | } |
| 278 | const baseUrl = process.env.PUBLIC_APP_URL ?? 'https://app.lifemate.invalid'; |
| 279 | await sendTransactionalEmail({ |
| 280 | to: email, |
| 281 | subject: 'بازیابی رمز عبور LifeMate', |
| 282 | text: `برای ساخت رمز جدید این لینک را باز کنید: ${baseUrl}/reset-password?token=${encodeURIComponent(resetToken)}`, |
| 283 | }); |
| 284 | } |
| 285 | |
| 286 | res.json({ |
| 287 | accepted: true, |
| 288 | resetToken: testMode ? resetToken : undefined, |
| 289 | }); |
| 290 | }); |
| 291 | |
| 292 | app.post('/v1/auth/reset-password', async (req, res) => { |
| 293 | if (!validPassword(req.body.newPassword)) { |
| 294 | return res.status(400).json({ error: 'invalid_password' }); |
| 295 | } |
| 296 | |
| 297 | const digest = sha256(String(req.body.token ?? '')); |
| 298 | const client = await pool.connect(); |
| 299 | try { |
| 300 | await client.query('begin'); |
| 301 | const r = await client.query( |
| 302 | "select user_id from auth_token where kind='password_reset' and token_digest=$1 and used_at is null and expires_at>now() for update", |
| 303 | [digest], |
| 304 | ); |
| 305 | if (!r.rowCount) { |
| 306 | await client.query('rollback'); |
| 307 | return res.status(400).json({ error: 'invalid_or_expired_token' }); |
| 308 | } |
| 309 | |
| 310 | await client.query('update auth_token set used_at=now() where token_digest=$1', [digest]); |
| 311 | const hash = await argon2.hash(req.body.newPassword, { type: argon2.argon2id }); |
| 312 | await client.query( |
| 313 | 'update auth_credential set password_hash=$1,password_changed_at=now() where user_id=$2', |
| 314 | [hash, r.rows[0].user_id], |
| 315 | ); |
| 316 | await client.query( |
| 317 | 'update auth_session set revoked_at=now() where user_id=$1 and revoked_at is null', |
| 318 | [r.rows[0].user_id], |
| 319 | ); |
| 320 | await client.query('commit'); |
| 321 | res.status(204).end(); |
| 322 | } finally { |
| 323 | client.release(); |
| 324 | } |
| 325 | }); |
| 326 | |
| 327 | app.post('/v1/auth/change-password', auth, async (req, res) => { |
| 328 | if (!validPassword(req.body.newPassword)) { |
| 329 | return res.status(400).json({ error: 'invalid_password' }); |
| 330 | } |
| 331 | |
| 332 | const r = await pool.query( |
| 333 | 'select password_hash from auth_credential where user_id=$1', |
| 334 | [req.identity.sub], |
| 335 | ); |
| 336 | if ( |
| 337 | !r.rowCount || |
| 338 | !(await argon2.verify(r.rows[0].password_hash, String(req.body.currentPassword ?? ''))) |
| 339 | ) { |
| 340 | return res.status(403).json({ error: 'invalid_current_password' }); |
| 341 | } |
| 342 | |
| 343 | const hash = await argon2.hash(req.body.newPassword, { type: argon2.argon2id }); |
| 344 | const client = await pool.connect(); |
| 345 | try { |
| 346 | await client.query('begin'); |
| 347 | await client.query( |
| 348 | 'update auth_credential set password_hash=$1,password_changed_at=now() where user_id=$2', |
| 349 | [hash, req.identity.sub], |
| 350 | ); |
| 351 | await client.query( |
| 352 | 'update auth_session set revoked_at=now() where user_id=$1 and id<>$2 and revoked_at is null', |
| 353 | [req.identity.sub, req.identity.sid], |
| 354 | ); |
| 355 | await client.query('commit'); |
| 356 | res.status(204).end(); |
| 357 | } finally { |
| 358 | client.release(); |
| 359 | } |
| 360 | }); |
| 361 | |
| 362 | app.post('/v1/auth/logout', auth, async (req, res) => { |
| 363 | await pool.query('update auth_session set revoked_at=now() where id=$1', [req.identity.sid]); |
| 364 | res.status(204).end(); |
| 365 | }); |
| 366 | |
| 367 | app.get('/v1/profile', auth, async (req, res) => { |
| 368 | const r = await pool.query( |
| 369 | 'select u.id as user_id,p.display_name,p.birth_date,p.theme_preference,u.email_normalized,u.email_verified_at from profile p join app_user u on u.id=p.user_id where p.user_id=$1', |
| 370 | [req.identity.sub], |
| 371 | ); |
| 372 | if (!r.rowCount) return res.status(404).json({ error: 'profile_not_found' }); |
| 373 | res.json(r.rows[0]); |
| 374 | }); |
| 375 | |
| 376 | app.patch('/v1/profile', auth, async (req, res) => { |
| 377 | const name = req.body.displayName == null ? null : String(req.body.displayName).trim(); |
| 378 | const theme = req.body.themePreference == null ? null : String(req.body.themePreference); |
| 379 | const allowedThemes = ['girl_pink', 'boy_blue', 'adult_blue', 'custom']; |
| 380 | if (name != null && (!name || name.length > 100)) { |
| 381 | return res.status(400).json({ error: 'invalid_display_name' }); |
| 382 | } |
| 383 | if (theme != null && !allowedThemes.includes(theme)) { |
| 384 | return res.status(400).json({ error: 'invalid_theme' }); |
| 385 | } |
| 386 | |
| 387 | const r = await pool.query( |
| 388 | `update profile |
| 389 | set display_name=coalesce($2,display_name), |
| 390 | birth_date=coalesce($3::date,birth_date), |
| 391 | theme_preference=coalesce($4,theme_preference), |
| 392 | updated_at=now() |
| 393 | where user_id=$1 |
| 394 | returning display_name,birth_date,theme_preference`, |
| 395 | [req.identity.sub, name, req.body.birthDate ?? null, theme], |
| 396 | ); |
| 397 | res.json(r.rows[0]); |
| 398 | }); |
| 399 | |
| 400 | app.get('/v1/families', auth, async (req, res) => { |
| 401 | const r = await pool.query( |
| 402 | `select f.id,f.name,m.role,m.is_admin |
| 403 | from family_membership m |
| 404 | join family_workspace f on f.id=m.family_id |
| 405 | where m.user_id=$1 and m.ended_at is null and f.archived_at is null |
| 406 | order by f.created_at`, |
| 407 | [req.identity.sub], |
| 408 | ); |
| 409 | res.json({ families: r.rows }); |
| 410 | }); |
| 411 | |
| 412 | app.post('/v1/families', auth, async (req, res) => { |
| 413 | const name = String(req.body.name ?? '').trim(); |
| 414 | if (!name) return res.status(400).json({ error: 'invalid_name' }); |
| 415 | |
| 416 | const creatorRole = ['parent_guardian', 'adult_member'].includes(req.body.role) |
| 417 | ? req.body.role |
| 418 | : 'adult_member'; |
| 419 | const c = await pool.connect(); |
| 420 | try { |
| 421 | await c.query('begin'); |
| 422 | const f = await c.query( |
| 423 | 'insert into family_workspace(name,created_by) values($1,$2) returning id,name', |
| 424 | [name, req.identity.sub], |
| 425 | ); |
| 426 | await c.query( |
| 427 | 'insert into family_membership(family_id,user_id,role,is_admin) values($1,$2,$3,true)', |
| 428 | [f.rows[0].id, req.identity.sub, creatorRole], |
| 429 | ); |
| 430 | await c.query( |
| 431 | "insert into access_audit(actor_user_id,family_id,action,target_type,target_id) values($1,$2,'family.create','family',$3)", |
| 432 | [req.identity.sub, f.rows[0].id, String(f.rows[0].id)], |
| 433 | ); |
| 434 | await c.query('commit'); |
| 435 | res.status(201).json(f.rows[0]); |
| 436 | } catch (e) { |
| 437 | await c.query('rollback'); |
| 438 | throw e; |
| 439 | } finally { |
| 440 | c.release(); |
| 441 | } |
| 442 | }); |
| 443 | |
| 444 | app.get('/v1/families/:familyId/members', auth, async (req, res) => { |
| 445 | const allowed = await familyAccess(req.params.familyId, req.identity.sub, { |
| 446 | roles: ['parent_guardian', 'teen_minor', 'adult_member'], |
| 447 | }); |
| 448 | if (!allowed) return res.status(403).json({ error: 'forbidden' }); |
| 449 | |
| 450 | const r = await pool.query( |
| 451 | `select m.user_id,m.role,m.is_admin,p.display_name,p.theme_preference |
| 452 | from family_membership m |
| 453 | join profile p on p.user_id=m.user_id |
| 454 | where m.family_id=$1 and m.ended_at is null |
| 455 | order by m.joined_at`, |
| 456 | [req.params.familyId], |
| 457 | ); |
| 458 | res.json({ members: r.rows }); |
| 459 | }); |
| 460 | |
| 461 | app.post('/v1/families/:familyId/invitations', auth, async (req, res) => { |
| 462 | const allowed = await familyAccess(req.params.familyId, req.identity.sub, { |
| 463 | admin: true, |
| 464 | }); |
| 465 | if (!allowed) return res.status(403).json({ error: 'forbidden' }); |
| 466 | |
| 467 | const email = normalizeEmail(req.body.email); |
| 468 | const role = String(req.body.role ?? ''); |
| 469 | const themePreference = String(req.body.themePreference ?? ''); |
| 470 | const allowedRoles = ['parent_guardian', 'teen_minor', 'adult_member']; |
| 471 | const allowedThemes = ['girl_pink', 'boy_blue', 'adult_blue', 'custom']; |
| 472 | const resolvedTheme = allowedThemes.includes(themePreference) |
| 473 | ? themePreference |
| 474 | : role === 'teen_minor' |
| 475 | ? 'girl_pink' |
| 476 | : 'adult_blue'; |
| 477 | if (!isEmail(email) || !allowedRoles.includes(role)) { |
| 478 | return res.status(400).json({ error: 'invalid_invitation' }); |
| 479 | } |
| 480 | |
| 481 | const activeMember = await pool.query( |
| 482 | `select 1 |
| 483 | from family_membership m |
| 484 | join app_user u on u.id=m.user_id |
| 485 | where m.family_id=$1 |
| 486 | and m.ended_at is null |
| 487 | and u.email_normalized=$2`, |
| 488 | [req.params.familyId, email], |
| 489 | ); |
| 490 | if (activeMember.rowCount) { |
| 491 | return res.status(409).json({ error: 'member_already_active' }); |
| 492 | } |
| 493 | |
| 494 | const token = randomToken(); |
| 495 | const r = await pool.query( |
| 496 | "insert into family_invitation(family_id,invited_email_normalized,intended_role,intended_theme,token_digest,invited_by,expires_at) values($1,$2,$3,$4,$5,$6,now()+interval '7 days') returning id,expires_at", |
| 497 | [req.params.familyId, email, role, resolvedTheme, sha256(token), req.identity.sub], |
| 498 | ); |
| 499 | |
| 500 | const baseUrl = process.env.PUBLIC_APP_URL ?? 'https://app.lifemate.invalid'; |
| 501 | await sendTransactionalEmail({ |
| 502 | to: email, |
| 503 | subject: 'دعوت به خانواده در LifeMate', |
| 504 | text: `برای پیوستن به خانواده این لینک را باز کنید: ${baseUrl}/accept-invitation?token=${encodeURIComponent(token)}`, |
| 505 | }); |
| 506 | |
| 507 | res.status(201).json({ |
| 508 | ...r.rows[0], |
| 509 | invitationToken: testMode ? token : undefined, |
| 510 | }); |
| 511 | }); |
| 512 | |
| 513 | app.post('/v1/invitations/accept', auth, async (req, res) => { |
| 514 | const digest = sha256(String(req.body.token ?? '')); |
| 515 | const client = await pool.connect(); |
| 516 | try { |
| 517 | await client.query('begin'); |
| 518 | const invitation = await client.query( |
| 519 | `select i.id,i.family_id,i.intended_role,i.intended_theme,i.invited_email_normalized,u.email_normalized |
| 520 | from family_invitation i |
| 521 | join app_user u on u.id=$2 |
| 522 | where i.token_digest=$1 |
| 523 | and i.status='pending' |
| 524 | and i.expires_at>now() |
| 525 | for update`, |
| 526 | [digest, req.identity.sub], |
| 527 | ); |
| 528 | if (!invitation.rowCount) { |
| 529 | await client.query('rollback'); |
| 530 | return res.status(400).json({ error: 'invalid_or_expired_invitation' }); |
| 531 | } |
| 532 | const row = invitation.rows[0]; |
| 533 | if (row.invited_email_normalized !== row.email_normalized) { |
| 534 | await client.query('rollback'); |
| 535 | return res.status(403).json({ error: 'invitation_email_mismatch' }); |
| 536 | } |
| 537 | |
| 538 | await client.query( |
| 539 | `insert into family_membership(family_id,user_id,role) |
| 540 | values($1,$2,$3) |
| 541 | on conflict(family_id,user_id) |
| 542 | do update set role=excluded.role,ended_at=null`, |
| 543 | [row.family_id, req.identity.sub, row.intended_role], |
| 544 | ); |
| 545 | await client.query( |
| 546 | "update family_invitation set status='accepted',accepted_by=$2,accepted_at=now() where id=$1", |
| 547 | [row.id, req.identity.sub], |
| 548 | ); |
| 549 | if (row.intended_theme) { |
| 550 | await client.query( |
| 551 | 'update profile set theme_preference=$2,updated_at=now() where user_id=$1', |
| 552 | [req.identity.sub, row.intended_theme], |
| 553 | ); |
| 554 | } |
| 555 | await client.query( |
| 556 | "insert into access_audit(actor_user_id,family_id,action,target_type,target_id) values($1,$2,'invitation.accept','membership',$3)", |
| 557 | [req.identity.sub, row.family_id, String(req.identity.sub)], |
| 558 | ); |
| 559 | await client.query('commit'); |
| 560 | res.status(204).end(); |
| 561 | } finally { |
| 562 | client.release(); |
| 563 | } |
| 564 | }); |
| 565 | |
| 566 | app.post('/v1/families/:familyId/guardians', auth, async (req, res) => { |
| 567 | const allowed = await familyAccess(req.params.familyId, req.identity.sub, { |
| 568 | admin: true, |
| 569 | }); |
| 570 | if (!allowed) return res.status(403).json({ error: 'forbidden' }); |
| 571 | |
| 572 | const guardianUserId = String(req.body.guardianUserId ?? ''); |
| 573 | const minorUserId = String(req.body.minorUserId ?? ''); |
| 574 | |
| 575 | const roles = await pool.query( |
| 576 | 'select user_id,role from family_membership where family_id=$1 and user_id in ($2,$3) and ended_at is null', |
| 577 | [req.params.familyId, guardianUserId, minorUserId], |
| 578 | ); |
| 579 | const map = new Map(roles.rows.map((row) => [row.user_id, row.role])); |
| 580 | if (map.get(guardianUserId) !== 'parent_guardian' || map.get(minorUserId) !== 'teen_minor') { |
| 581 | return res.status(400).json({ error: 'invalid_guardian_relationship' }); |
| 582 | } |
| 583 | |
| 584 | await pool.query( |
| 585 | `insert into guardian_relationship(family_id,guardian_user_id,minor_user_id,active) |
| 586 | values($1,$2,$3,true) |
| 587 | on conflict(family_id,guardian_user_id,minor_user_id) |
| 588 | do update set active=true`, |
| 589 | [req.params.familyId, guardianUserId, minorUserId], |
| 590 | ); |
| 591 | await pool.query( |
| 592 | "insert into access_audit(actor_user_id,family_id,action,target_type,target_id,metadata) values($1,$2,'guardian.activate','guardian_relationship',$3,jsonb_build_object('minorUserId',$4::text))", |
| 593 | [req.identity.sub, req.params.familyId, guardianUserId, minorUserId], |
| 594 | ); |
| 595 | res.status(204).end(); |
| 596 | }); |
| 597 | |
| 598 | app.use('/v1', createPhase3Router({ pool, auth })); |
| 599 | app.use('/v1', createPhase4Router({ pool, auth })); |
| 600 | app.use('/v1', createPhase6Router({ pool, auth })); |
| 601 | |
| 602 | app.use(operationalErrorHandler); |
| 603 | |
| 604 | const port = Number(process.env.PORT ?? 8080); |
| 605 | const invokedDirectly = process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href; |
| 606 | if (!testMode && invokedDirectly) { |
| 607 | app.listen(port, () => console.log(`LifeMate API listening on ${port}`)); |
| 608 | } |
| 609 | |
| 610 | export { app, pool }; |
| 611 | export default app; |