LifeMate — Personal, Family & Learning Companion

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