LifeMate — Personal, Family & Learning Companion

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