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
| 1 | import express from 'express'; |
| 2 | |
| 3 | const clampText = (value, max = 4000) => |
| 4 | String(value ?? '').trim().slice(0, max); |
| 5 | const isUuid = (value) => typeof value === 'string' && /^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(value); |
| 6 | |
| 7 | function safetyClass(text) { |
| 8 | const value = text.toLowerCase(); |
| 9 | if (/(خودکشی|خودم را بکشم|آسیب به خود|self[- ]?harm|suicide|kill myself)/i.test(value)) { |
| 10 | return 'urgent_review'; |
| 11 | } |
| 12 | if (/(غمگین|اضطراب|استرس|نگران|sad|anxious|stress|worried)/i.test(value)) { |
| 13 | return 'supportive'; |
| 14 | } |
| 15 | return 'ordinary'; |
| 16 | } |
| 17 | |
| 18 | function localGuide(kind, text, klass) { |
| 19 | if (klass === 'urgent_review') { |
| 20 | return 'من جای کمک فوری یا متخصص را نمیگیرم. اگر خطر فوری وجود دارد، همین حالا با یک فرد قابل اعتماد در نزدیکی خود یا خدمات اضطراری محلی تماس بگیر. میتوانیم فقط روی قدم امن بعدی تمرکز کنیم.'; |
| 21 | } |
| 22 | if (kind === 'study') { |
| 23 | return `پیشنهاد مطالعه: هدف را به یک بخش ۲۵ دقیقهای کوچک تبدیل کن، بعد ۵ دقیقه استراحت و در پایان سه نکته را بدون نگاهکردن مرور کن. موضوع فعلی: ${text.slice(0, 180)}`; |
| 24 | } |
| 25 | if (kind === 'planner') { |
| 26 | return 'پیشنهاد برنامهریزی: فقط سه اولویت امروز را انتخاب کن؛ کار سختتر را به کوچکترین اقدام قابل شروع بشکن و برای استراحت زمان واقعی نگه دار.'; |
| 27 | } |
| 28 | return 'میتوانم برای خودبازتابی، ارتباط سالم و عادتهای حمایتی کمک کنم، نه تشخیص پزشکی. احساس را نامگذاری کن، شدت آن را بسنج و یک اقدام کوچک مثل آب، استراحت، حرکت کوتاه یا صحبت با فرد قابل اعتماد انتخاب کن.'; |
| 29 | } |
| 30 | |
| 31 | async function providerGuide(kind, text, klass) { |
| 32 | // External AI/voice is not authorized in this package, even if keys exist. |
| 33 | return localGuide(kind, text, klass); |
| 34 | } |
| 35 | |
| 36 | async function guardianRelationship(pool, familyId, guardianUserId, minorUserId) { |
| 37 | const result = await pool.query( |
| 38 | 'select is_active_guardian($1,$2,$3) as allowed', |
| 39 | [familyId, guardianUserId, minorUserId], |
| 40 | ); |
| 41 | return result.rows[0]?.allowed === true; |
| 42 | } |
| 43 | |
| 44 | export function createPhase4Router({ pool, auth, sensitiveFeaturesEnabled = process.env.ENABLE_SENSITIVE_FEATURES === 'true' }) { |
| 45 | const router = express.Router(); |
| 46 | const sensitiveEnabled = sensitiveFeaturesEnabled === true; |
| 47 | const requireSensitive = (_req, res, next) => { |
| 48 | if (!sensitiveEnabled) return res.status(503).json({ error: 'sensitive_features_disabled' }); |
| 49 | return next(); |
| 50 | }; |
| 51 | router.use(auth); |
| 52 | |
| 53 | router.post('/learning/goals', async (req, res) => { |
| 54 | const title = clampText(req.body.title, 240); |
| 55 | if (!title) return res.status(400).json({ error: 'invalid_input' }); |
| 56 | if (req.body.subjectId != null && !isUuid(req.body.subjectId)) return res.status(400).json({ error: 'invalid_subject_id' }); |
| 57 | if (req.body.subjectId) { |
| 58 | const subject = await pool.query( |
| 59 | 'select 1 from subject where id=$1 and student_user_id=$2', |
| 60 | [req.body.subjectId, req.identity.sub], |
| 61 | ); |
| 62 | if (!subject.rowCount) return res.status(403).json({ error: 'subject_forbidden' }); |
| 63 | } |
| 64 | const result = await pool.query( |
| 65 | 'insert into learning_goal(owner_user_id,subject_id,title,target) values($1,$2,$3,$4) returning *', |
| 66 | [ |
| 67 | req.identity.sub, |
| 68 | req.body.subjectId || null, |
| 69 | title, |
| 70 | clampText(req.body.target, 1000) || null, |
| 71 | ], |
| 72 | ); |
| 73 | res.status(201).json(result.rows[0]); |
| 74 | }); |
| 75 | |
| 76 | router.get('/learning/goals', async (req, res) => { |
| 77 | const result = await pool.query( |
| 78 | "select * from learning_goal where owner_user_id=$1 and status<>'archived' order by created_at desc", |
| 79 | [req.identity.sub], |
| 80 | ); |
| 81 | res.json({ items: result.rows }); |
| 82 | }); |
| 83 | |
| 84 | router.get('/learning/goals/:id', async (req, res) => { |
| 85 | if (!isUuid(req.params.id)) return res.status(400).json({ error: 'invalid_goal_id' }); |
| 86 | const result = await pool.query('select * from learning_goal where id=$1 and owner_user_id=$2', [req.params.id, req.identity.sub]); |
| 87 | if (!result.rowCount) return res.status(404).json({ error: 'goal_not_found' }); |
| 88 | res.json(result.rows[0]); |
| 89 | }); |
| 90 | |
| 91 | router.patch('/learning/goals/:id', async (req, res) => { |
| 92 | if (!isUuid(req.params.id)) return res.status(400).json({ error: 'invalid_goal_id' }); |
| 93 | const body = req.body ?? {}; |
| 94 | const has = (field) => Object.hasOwn(body, field); |
| 95 | if (has('title') && (typeof body.title !== 'string' || !body.title.trim() || body.title.trim().length > 240)) return res.status(400).json({ error: 'invalid_input' }); |
| 96 | if (has('target') && body.target != null && (typeof body.target !== 'string' || body.target.trim().length > 1000)) return res.status(400).json({ error: 'invalid_input' }); |
| 97 | if (has('subjectId') && body.subjectId != null && !isUuid(body.subjectId)) return res.status(400).json({ error: 'invalid_subject_id' }); |
| 98 | if (has('status') && !['active', 'completed', 'archived'].includes(body.status)) return res.status(400).json({ error: 'invalid_status' }); |
| 99 | const client = await pool.connect(); |
| 100 | try { |
| 101 | await client.query('begin'); |
| 102 | const goal = await client.query('select status from learning_goal where id=$1 and owner_user_id=$2 for update', [req.params.id, req.identity.sub]); |
| 103 | if (!goal.rowCount || goal.rows[0].status === 'archived') { |
| 104 | await client.query('rollback'); |
| 105 | return res.status(goal.rowCount ? 409 : 404).json({ error: goal.rowCount ? 'goal_archived' : 'goal_not_found' }); |
| 106 | } |
| 107 | if (body.subjectId != null) { |
| 108 | const subject = await client.query('select 1 from subject where id=$1 and student_user_id=$2', [body.subjectId, req.identity.sub]); |
| 109 | if (!subject.rowCount) { |
| 110 | await client.query('rollback'); |
| 111 | return res.status(403).json({ error: 'subject_forbidden' }); |
| 112 | } |
| 113 | } |
| 114 | const result = await client.query( |
| 115 | `update learning_goal set title=case when $3 then $4 else title end, |
| 116 | target=case when $5 then $6 else target end, |
| 117 | subject_id=case when $7 then $8::uuid else subject_id end, |
| 118 | status=coalesce($9,status),updated_at=now() |
| 119 | where id=$1 and owner_user_id=$2 returning *`, |
| 120 | [req.params.id, req.identity.sub, has('title'), has('title') ? body.title.trim() : null, |
| 121 | has('target'), body.target?.trim() || null, has('subjectId'), body.subjectId ?? null, body.status ?? null], |
| 122 | ); |
| 123 | await client.query('commit'); |
| 124 | res.json(result.rows[0]); |
| 125 | } catch (error) { |
| 126 | await client.query('rollback').catch(() => {}); |
| 127 | throw error; |
| 128 | } finally { client.release(); } |
| 129 | }); |
| 130 | |
| 131 | router.delete('/learning/goals/:id', async (req, res) => { |
| 132 | if (!isUuid(req.params.id)) return res.status(400).json({ error: 'invalid_goal_id' }); |
| 133 | const result = await pool.query( |
| 134 | `update learning_goal set status='archived', |
| 135 | updated_at=case when status='archived' then updated_at else now() end |
| 136 | where id=$1 and owner_user_id=$2 returning id`, |
| 137 | [req.params.id, req.identity.sub], |
| 138 | ); |
| 139 | if (!result.rowCount) return res.status(404).json({ error: 'goal_not_found' }); |
| 140 | res.status(204).end(); |
| 141 | }); |
| 142 | |
| 143 | router.post('/wellbeing/checkins', requireSensitive, async (req, res) => { |
| 144 | const mood = Number(req.body.mood); |
| 145 | const energy = Number(req.body.energy); |
| 146 | const stress = Number(req.body.stress); |
| 147 | if (![mood, energy, stress].every((x) => Number.isInteger(x) && x >= 1 && x <= 5)) { |
| 148 | return res.status(400).json({ error: 'invalid_input' }); |
| 149 | } |
| 150 | const visibility = |
| 151 | req.body.visibility === 'guardian_summary' ? 'guardian_summary' : 'private'; |
| 152 | const result = await pool.query( |
| 153 | 'insert into wellbeing_checkin(owner_user_id,mood,energy,stress,note,visibility) values($1,$2,$3,$4,$5,$6) returning id,mood,energy,stress,visibility,created_at', |
| 154 | [ |
| 155 | req.identity.sub, |
| 156 | mood, |
| 157 | energy, |
| 158 | stress, |
| 159 | clampText(req.body.note, 2000) || null, |
| 160 | visibility, |
| 161 | ], |
| 162 | ); |
| 163 | res.status(201).json(result.rows[0]); |
| 164 | }); |
| 165 | |
| 166 | router.get('/wellbeing/checkins', requireSensitive, async (req, res) => { |
| 167 | const result = await pool.query( |
| 168 | 'select id,mood,energy,stress,visibility,created_at from wellbeing_checkin where owner_user_id=$1 order by created_at desc limit 30', |
| 169 | [req.identity.sub], |
| 170 | ); |
| 171 | res.json({ items: result.rows }); |
| 172 | }); |
| 173 | |
| 174 | router.get('/families/:familyId/children/:minorUserId/wellbeing-summary', requireSensitive, async (req, res) => { |
| 175 | const allowed = await guardianRelationship( |
| 176 | pool, |
| 177 | req.params.familyId, |
| 178 | req.identity.sub, |
| 179 | req.params.minorUserId, |
| 180 | ); |
| 181 | if (!allowed) return res.status(403).json({ error: 'forbidden' }); |
| 182 | |
| 183 | const summary = await pool.query( |
| 184 | `select |
| 185 | count(*)::int as checkin_count, |
| 186 | round(avg(mood)::numeric,2) as mood_average, |
| 187 | round(avg(energy)::numeric,2) as energy_average, |
| 188 | round(avg(stress)::numeric,2) as stress_average, |
| 189 | min(created_at) as window_start, |
| 190 | max(created_at) as window_end |
| 191 | from wellbeing_checkin |
| 192 | where owner_user_id=$1 |
| 193 | and visibility='guardian_summary' |
| 194 | and created_at >= now()-interval '14 days'`, |
| 195 | [req.params.minorUserId], |
| 196 | ); |
| 197 | const safety = await pool.query( |
| 198 | `select count(*)::int as open_urgent_count,max(created_at) as latest_urgent_at |
| 199 | from wellbeing_safety_event |
| 200 | where owner_user_id=$1 and status='open'`, |
| 201 | [req.params.minorUserId], |
| 202 | ); |
| 203 | res.json({ |
| 204 | summary: summary.rows[0], |
| 205 | safety: safety.rows[0], |
| 206 | rawNotesIncluded: false, |
| 207 | rawConversationIncluded: false, |
| 208 | medicalDiagnosis: false, |
| 209 | }); |
| 210 | }); |
| 211 | |
| 212 | router.post('/families/:familyId/children/:minorUserId/family-guidance', requireSensitive, async (req, res) => { |
| 213 | const allowed = await guardianRelationship( |
| 214 | pool, |
| 215 | req.params.familyId, |
| 216 | req.identity.sub, |
| 217 | req.params.minorUserId, |
| 218 | ); |
| 219 | if (!allowed) return res.status(403).json({ error: 'forbidden' }); |
| 220 | |
| 221 | const question = clampText(req.body.question, 2000); |
| 222 | if (!question) return res.status(400).json({ error: 'invalid_input' }); |
| 223 | |
| 224 | const [academic, wellbeing, safety] = await Promise.all([ |
| 225 | pool.query( |
| 226 | `select |
| 227 | count(*) filter ( |
| 228 | where kind in ('assignment','study_session') |
| 229 | and status not in ('completed','cancelled') |
| 230 | and due_at < now() |
| 231 | )::int as overdue, |
| 232 | count(*) filter ( |
| 233 | where kind in ('assignment','study_session') |
| 234 | and status='completed' |
| 235 | and completed_at >= now()-interval '7 days' |
| 236 | )::int as completed_last_7_days, |
| 237 | coalesce(sum(duration_minutes) filter ( |
| 238 | where kind='study_session' |
| 239 | and status='completed' |
| 240 | and completed_at >= now()-interval '7 days' |
| 241 | ),0)::int as study_minutes_last_7_days, |
| 242 | case when sum(grade_out_of) filter ( |
| 243 | where grade_points is not null and grade_out_of is not null |
| 244 | ) > 0 then |
| 245 | round( |
| 246 | sum(grade_points) filter (where grade_points is not null and grade_out_of is not null) |
| 247 | / |
| 248 | sum(grade_out_of) filter (where grade_points is not null and grade_out_of is not null) |
| 249 | * 100, |
| 250 | 1 |
| 251 | ) |
| 252 | end as grade_percent |
| 253 | from plan_item |
| 254 | where owner_user_id=$1 and can_view_plan_item($2,id)`, |
| 255 | [req.params.minorUserId, req.identity.sub], |
| 256 | ), |
| 257 | pool.query( |
| 258 | `select |
| 259 | count(*)::int as checkin_count, |
| 260 | round(avg(mood)::numeric,2) as mood_average, |
| 261 | round(avg(energy)::numeric,2) as energy_average, |
| 262 | round(avg(stress)::numeric,2) as stress_average |
| 263 | from wellbeing_checkin |
| 264 | where owner_user_id=$1 |
| 265 | and visibility='guardian_summary' |
| 266 | and created_at >= now()-interval '14 days'`, |
| 267 | [req.params.minorUserId], |
| 268 | ), |
| 269 | pool.query( |
| 270 | `select count(*)::int as open_urgent_count |
| 271 | from wellbeing_safety_event |
| 272 | where owner_user_id=$1 and status='open'`, |
| 273 | [req.params.minorUserId], |
| 274 | ), |
| 275 | ]); |
| 276 | |
| 277 | const context = { |
| 278 | academic: academic.rows[0], |
| 279 | wellbeing: wellbeing.rows[0], |
| 280 | safety: safety.rows[0], |
| 281 | privacy: { |
| 282 | rawNotesIncluded: false, |
| 283 | rawConversationIncluded: false, |
| 284 | }, |
| 285 | }; |
| 286 | const prompt = [ |
| 287 | 'You are advising a parent/guardian using only authorized aggregate data.', |
| 288 | 'Do not diagnose the child and do not infer hidden mental state.', |
| 289 | 'Give concrete, low-pressure family support ideas and questions the parent can ask.', |
| 290 | 'If safety.open_urgent_count is above zero, prioritize immediate trusted-human support and local emergency resources.', |
| 291 | `Authorized summary: ${JSON.stringify(context)}`, |
| 292 | `Parent question: ${question}`, |
| 293 | ].join('\n'); |
| 294 | |
| 295 | const klass = |
| 296 | Number(context.safety.open_urgent_count ?? 0) > 0 |
| 297 | ? 'urgent_review' |
| 298 | : safetyClass(question); |
| 299 | const advice = await providerGuide('wellbeing', prompt, klass); |
| 300 | |
| 301 | await pool.query( |
| 302 | `insert into access_audit(actor_user_id,family_id,action,target_type,target_id,metadata) |
| 303 | values($1,$2,'parent.family_guidance.request','student',$3,$4::jsonb)`, |
| 304 | [ |
| 305 | req.identity.sub, |
| 306 | req.params.familyId, |
| 307 | req.params.minorUserId, |
| 308 | JSON.stringify({ rawNotesIncluded: false, rawConversationIncluded: false }), |
| 309 | ], |
| 310 | ); |
| 311 | |
| 312 | res.json({ |
| 313 | advice, |
| 314 | summary: context, |
| 315 | advisory: true, |
| 316 | medicalDiagnosis: false, |
| 317 | rawNotesIncluded: false, |
| 318 | rawConversationIncluded: false, |
| 319 | }); |
| 320 | }); |
| 321 | |
| 322 | router.post('/ai/sessions', async (req, res) => { |
| 323 | const kind = ['study', 'planner', 'wellbeing'].includes(req.body.kind) |
| 324 | ? req.body.kind |
| 325 | : null; |
| 326 | if (!kind) return res.status(400).json({ error: 'invalid_kind' }); |
| 327 | if (kind === 'wellbeing' && !sensitiveEnabled) return res.status(503).json({ error: 'sensitive_features_disabled' }); |
| 328 | const result = await pool.query( |
| 329 | 'insert into ai_guide_session(owner_user_id,guide_kind) values($1,$2) returning *', |
| 330 | [req.identity.sub, kind], |
| 331 | ); |
| 332 | res.status(201).json(result.rows[0]); |
| 333 | }); |
| 334 | |
| 335 | router.post('/ai/sessions/:id/messages', async (req, res) => { |
| 336 | const text = clampText(req.body.message); |
| 337 | if (!text) return res.status(400).json({ error: 'invalid_input' }); |
| 338 | const session = await pool.query( |
| 339 | "select * from ai_guide_session where id=$1 and owner_user_id=$2 and status='active'", |
| 340 | [req.params.id, req.identity.sub], |
| 341 | ); |
| 342 | if (!session.rowCount) return res.status(404).json({ error: 'session_not_found' }); |
| 343 | if (session.rows[0].guide_kind === 'wellbeing' && !sensitiveEnabled) return res.status(503).json({ error: 'sensitive_features_disabled' }); |
| 344 | |
| 345 | const klass = safetyClass(text); |
| 346 | await pool.query( |
| 347 | "insert into ai_guide_message(session_id,author,body,safety_class) values($1,'user',$2,$3)", |
| 348 | [req.params.id, text, klass], |
| 349 | ); |
| 350 | if (klass === 'urgent_review' && sensitiveEnabled) { |
| 351 | await pool.query( |
| 352 | "insert into wellbeing_safety_event(owner_user_id,source_session_id,severity) values($1,$2,'urgent_review')", |
| 353 | [req.identity.sub, req.params.id], |
| 354 | ); |
| 355 | } |
| 356 | |
| 357 | const reply = await providerGuide(session.rows[0].guide_kind, text, klass); |
| 358 | const result = await pool.query( |
| 359 | "insert into ai_guide_message(session_id,author,body,safety_class) values($1,'assistant',$2,$3) returning id,body,safety_class,created_at", |
| 360 | [req.params.id, reply, klass], |
| 361 | ); |
| 362 | res.json({ |
| 363 | ...result.rows[0], |
| 364 | advisory: true, |
| 365 | medicalDiagnosis: false, |
| 366 | automaticAction: false, |
| 367 | providerMode: 'local_fallback', |
| 368 | }); |
| 369 | }); |
| 370 | |
| 371 | router.post('/ai/proposals', async (req, res) => { |
| 372 | const title = clampText(req.body.title, 240); |
| 373 | if (!title || !req.body.proposal || typeof req.body.proposal !== 'object') { |
| 374 | return res.status(400).json({ error: 'invalid_input' }); |
| 375 | } |
| 376 | if (req.body.sessionId) { |
| 377 | const session = await pool.query('select guide_kind from ai_guide_session where id=$1 and owner_user_id=$2', [req.body.sessionId, req.identity.sub]); |
| 378 | if (!session.rowCount) return res.status(403).json({ error: 'session_forbidden' }); |
| 379 | if (session.rows[0].guide_kind === 'wellbeing' && !sensitiveEnabled) return res.status(503).json({ error: 'sensitive_features_disabled' }); |
| 380 | } |
| 381 | const result = await pool.query( |
| 382 | 'insert into ai_plan_proposal(owner_user_id,session_id,title,proposal) values($1,$2,$3,$4) returning *', |
| 383 | [req.identity.sub, req.body.sessionId || null, title, req.body.proposal], |
| 384 | ); |
| 385 | res.status(201).json(result.rows[0]); |
| 386 | }); |
| 387 | |
| 388 | router.patch('/ai/proposals/:id', async (req, res) => { |
| 389 | const status = ['accepted', 'rejected'].includes(req.body.status) |
| 390 | ? req.body.status |
| 391 | : null; |
| 392 | if (!status) return res.status(400).json({ error: 'invalid_status' }); |
| 393 | const proposal = await pool.query( |
| 394 | `select s.guide_kind from ai_plan_proposal p |
| 395 | left join ai_guide_session s on s.id=p.session_id |
| 396 | where p.id=$1 and p.owner_user_id=$2 and p.status='proposed'`, |
| 397 | [req.params.id, req.identity.sub], |
| 398 | ); |
| 399 | if (!proposal.rowCount) return res.status(404).json({ error: 'proposal_not_found' }); |
| 400 | if (proposal.rows[0].guide_kind === 'wellbeing' && !sensitiveEnabled) return res.status(503).json({ error: 'sensitive_features_disabled' }); |
| 401 | const result = await pool.query( |
| 402 | "update ai_plan_proposal set status=$3,decided_at=now() where id=$1 and owner_user_id=$2 and status='proposed' returning *", |
| 403 | [req.params.id, req.identity.sub, status], |
| 404 | ); |
| 405 | if (!result.rowCount) return res.status(404).json({ error: 'proposal_not_found' }); |
| 406 | res.json(result.rows[0]); |
| 407 | }); |
| 408 | |
| 409 | return router; |
| 410 | } |