LifeMate — Personal, Family & Learning Companion

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