@davoodmehraban89 / LifeMate / commits / 51d9684
Fork 0

LifeMate — Personal, Family & Learning Companion

feat: complete identity and family API foundation

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