LifeMate — Personal, Family & Learning Companion

feat/child-identity-schema
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 348 lines 21.9 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 { normalizeEmail, normalizePhone, isEmail, validPassword } from './auth_contacts.js';
6 import { createEmailProvider, createSmsProvider, safelyDeliver } from './auth_delivery.js';
7
8 const sha256 = (value) => crypto.createHash('sha256').update(value).digest('hex');
9 const randomToken = () => crypto.randomBytes(32).toString('base64url');
10 const uuid = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;
11
12 async function transaction(pool, operation) {
13 const client = await pool.connect();
14 try {
15 await client.query('begin');
16 const result = await operation(client);
17 await client.query('commit');
18 return result;
19 } catch (error) {
20 await client.query('rollback').catch(() => {});
21 throw error;
22 } finally { client.release(); }
23 }
24
25 export function createAuthRouter({ pool, jwtSecret, auth, env = process.env,
26 emailProvider = createEmailProvider({ env }), smsProvider = createSmsProvider() }) {
27 const router = express.Router();
28 const testMode = env.NODE_ENV === 'test';
29 const publicApp = env.PUBLIC_APP_URL ?? 'https://app.lifeguide.invalid';
30 const dummyHash = argon2.hash(randomToken(), { type: argon2.argon2id });
31 const digest = (value) => crypto.createHmac('sha256', jwtSecret).update(value).digest('hex');
32
33 async function oneTimeToken(client, userId, kind, minutes) {
34 const raw = randomToken();
35 await client.query(
36 "insert into auth_token(user_id,kind,token_digest,expires_at) values($1,$2,$3,now()+($4 || ' minutes')::interval)",
37 [userId, kind, sha256(raw), String(minutes)],
38 );
39 return raw;
40 }
41
42 async function usableToken(client, raw, kind) {
43 const tokenDigest = sha256(raw);
44 const owner = await client.query('select user_id from auth_token where token_digest=$1 and kind=$2', [tokenDigest, kind]);
45 if (!owner.rowCount) return null;
46 const active = await client.query('select 1 from app_user where id=$1 and disabled_at is null for update', [owner.rows[0].user_id]);
47 if (!active.rowCount) return null;
48 const token = await client.query('select user_id from auth_token where token_digest=$1 and kind=$2 and used_at is null for update', [tokenDigest, kind]);
49 if (!token.rowCount) return null;
50 // now() is the transaction start, and predicates in FOR UPDATE can be
51 // evaluated before a row-lock wait. Check wall time in a NEW statement
52 // after both account and token locks have actually been acquired.
53 const fresh = await client.query('select 1 from auth_token where token_digest=$1 and kind=$2 and used_at is null and expires_at>clock_timestamp()', [tokenDigest, kind]);
54 return fresh.rowCount ? token.rows[0] : null;
55 }
56
57 async function session(client, userId) {
58 const refreshToken = randomToken();
59 const result = await client.query(
60 "insert into auth_session(user_id,refresh_digest,expires_at) values($1,$2,now()+interval '30 days') returning id",
61 [userId, sha256(refreshToken)],
62 );
63 return {
64 accessToken: jwt.sign({ sub: userId, sid: result.rows[0].id, aud: 'lifemate-api' }, jwtSecret, { expiresIn: '15m', issuer: 'lifemate' }),
65 refreshToken,
66 };
67 }
68
69 async function claimDelivery(client, recipient, purpose, userId = null) {
70 // The same limit is claimed before account lookup for known and unknown contacts.
71 const recipientDigest = digest(`delivery:${recipient}`);
72 await client.query('select pg_advisory_xact_lock(hashtextextended($1,0))', [recipientDigest + ':' + purpose]);
73 const recent = await client.query(
74 `select count(*)::int as n,
75 ceil(extract(epoch from (max(requested_at)+interval '60 seconds'-statement_timestamp()))) as cooldown,
76 ceil(extract(epoch from (min(requested_at)+interval '1 hour'-statement_timestamp()))) as window_wait
77 from auth_delivery_attempt where recipient_digest=$1 and purpose=$2
78 and requested_at>statement_timestamp()-interval '1 hour'`, [recipientDigest, purpose],
79 );
80 const row = recent.rows[0];
81 const wait = row.n >= 3 ? Number(row.window_wait) : Number(row.cooldown);
82 if (wait > 0) return { retryAfter: Math.max(1, wait) };
83 const inserted = await client.query(
84 'insert into auth_delivery_attempt(recipient_digest,purpose,user_id,requested_at) values($1,$2,$3,clock_timestamp()) returning id',
85 [recipientDigest, purpose, userId],
86 );
87 return { attemptId: inserted.rows[0].id };
88 }
89
90 function limited(res, result) {
91 if (!result.retryAfter) return false;
92 res.setHeader('Retry-After', String(result.retryAfter));
93 res.status(429).json({ error: 'rate_limited' });
94 return true;
95 }
96
97 async function emailDelivery(userEmail, raw, kind, attemptId) {
98 const verify = kind === 'email_verification';
99 return safelyDeliver(emailProvider, {
100 to: userEmail,
101 subject: verify ? 'تأیید حساب لایف‌گاید' : 'بازیابی رمز عبور لایف‌گاید',
102 text: `${verify ? 'برای تأیید حساب LifeGuide / لایف‌گاید' : 'برای ساخت رمز جدید لایف‌گاید'} این لینک را باز کن: ${publicApp}/${verify ? 'verify-email' : 'reset-password'}?token=${encodeURIComponent(raw)}\nاین لینک ${verify ? '۲۴ ساعت' : '۳۰ دقیقه'} اعتبار دارد. اگر این درخواست را نداده‌ای، پیام را نادیده بگیر.`,
103 }, { pool, attemptId, env });
104 }
105
106 router.get('/capabilities', (_req, res) => res.json({
107 emailDeliveryAvailable: Boolean(emailProvider.configured),
108 emailStatus: emailProvider.status ?? 'UNVERIFIED',
109 smsAvailable: Boolean(smsProvider.configured),
110 smsStatus: smsProvider.status ?? 'UNVERIFIED',
111 }));
112
113 router.post('/register', async (req, res) => {
114 const email = normalizeEmail(req.body?.email);
115 const phone = req.body?.phone == null ? null : normalizePhone(req.body.phone);
116 const name = String(req.body?.displayName ?? '').trim();
117 if (!name || name.length > 100 || !validPassword(req.body?.password) ||
118 (email && phone) || (!email && !phone) || (email && !isEmail(email)) ||
119 (req.body?.phone != null && !phone)) return res.status(400).json({ error: 'invalid_input' });
120 if (phone && !smsProvider.configured) return res.status(503).json({ error: 'sms_unavailable' });
121 // Always hash valid registration input, including duplicates; never replace credentials.
122 const hash = await argon2.hash(req.body.password, { type: argon2.argon2id });
123 const result = await transaction(pool, async (client) => {
124 const rate = email ? await claimDelivery(client, email, 'email_verification') : {};
125 const inserted = await client.query(
126 'insert into app_user(identity_subject,email_normalized,phone_normalized) values($1,$2,$3) on conflict do nothing returning id',
127 [`local:${crypto.randomUUID()}`, email || null, phone],
128 );
129 if (!inserted.rowCount) return { ...rate };
130 const userId = inserted.rows[0].id;
131 await client.query("insert into profile(user_id,display_name,theme_preference) values($1,$2,'adult_blue')", [userId, name]);
132 await client.query('insert into auth_credential(user_id,password_hash) values($1,$2)', [userId, hash]);
133 let verificationToken;
134 if (email) verificationToken = await oneTimeToken(client, userId, 'email_verification', 1440);
135 if (rate.attemptId) await client.query('update auth_delivery_attempt set user_id=$2 where id=$1', [rate.attemptId, userId]);
136 return { ...rate, userId, verificationToken };
137 });
138 // The response is sent before provider I/O, which cannot change a committed account response.
139 res.status(testMode ? 201 : 202).json(testMode
140 ? { accepted: true, userId: result.userId, verificationToken: result.verificationToken }
141 : { accepted: true });
142 if (result.verificationToken && result.attemptId) await emailDelivery(email, result.verificationToken, 'email_verification', result.attemptId);
143 else if (result.attemptId) await pool.query("update auth_delivery_attempt set status='not_needed' where id=$1", [result.attemptId]).catch(() => {});
144 });
145
146 router.post('/resend-verification', async (req, res) => {
147 const email = normalizeEmail(req.body?.email);
148 if (!isEmail(email)) return res.status(400).json({ error: 'invalid_input' });
149 const result = await transaction(pool, async (client) => {
150 const rate = await claimDelivery(client, email, 'email_verification');
151 if (rate.retryAfter) return rate;
152 const user = await client.query('select id from app_user where email_normalized=$1 and email_verified_at is null and disabled_at is null for update', [email]);
153 if (!user.rowCount) return rate;
154 const token = await oneTimeToken(client, user.rows[0].id, 'email_verification', 1440);
155 await client.query('update auth_delivery_attempt set user_id=$2 where id=$1', [rate.attemptId, user.rows[0].id]);
156 return { ...rate, token };
157 });
158 if (limited(res, result)) return;
159 res.status(202).json({ accepted: true });
160 if (result.token) await emailDelivery(email, result.token, 'email_verification', result.attemptId);
161 else await pool.query("update auth_delivery_attempt set status='not_needed' where id=$1", [result.attemptId]).catch(() => {});
162 });
163
164 router.post('/verify-email', async (req, res) => {
165 if (!validPassword(req.body?.newPassword)) return res.status(400).json({ error: 'invalid_password' });
166 const ok = await transaction(pool, async (client) => {
167 const token = await usableToken(client, String(req.body?.token ?? ''), 'email_verification');
168 if (!token) return false;
169 const hash = await argon2.hash(req.body.newPassword, { type: argon2.argon2id });
170 await client.query('update auth_credential set password_hash=$2,password_changed_at=now() where user_id=$1', [token.user_id, hash]);
171 await client.query('update auth_session set revoked_at=now() where user_id=$1 and revoked_at is null', [token.user_id]);
172 await client.query("update auth_token set used_at=now() where user_id=$1 and kind='email_verification' and used_at is null", [token.user_id]);
173 await client.query('update app_user set email_verified_at=coalesce(email_verified_at,now()) where id=$1', [token.user_id]);
174 return true;
175 });
176 if (!ok) return res.status(400).json({ error: 'invalid_or_expired_token' });
177 res.status(204).end();
178 });
179
180 router.post('/login', async (req, res) => {
181 const identifier = String(req.body?.identifier ?? req.body?.email ?? req.body?.phone ?? '').trim();
182 const email = identifier.includes('@') ? normalizeEmail(identifier) : null;
183 const phone = email ? null : normalizePhone(identifier);
184 const result = await pool.query(
185 `select u.id,u.email_verified_at,u.phone_verified_at,c.password_hash from app_user u
186 join auth_credential c on c.user_id=u.id where u.disabled_at is null
187 and (($1::text is not null and u.email_normalized=$1) or ($2::text is not null and u.phone_normalized=$2))`, [email, phone],
188 );
189 const password = String(req.body?.password ?? '');
190 const matched = await argon2.verify(result.rows[0]?.password_hash ?? await dummyHash, password.slice(0, 200));
191 if (!result.rowCount || password.length > 200 || !matched) return res.status(401).json({ error: 'invalid_credentials' });
192 if (email ? !result.rows[0].email_verified_at : !result.rows[0].phone_verified_at) {
193 return res.status(403).json({ error: email ? 'email_not_verified' : 'phone_not_verified' });
194 }
195 const tokens = await transaction(pool, async (client) => {
196 const active = await client.query('select 1 from app_user where id=$1 and disabled_at is null for update', [result.rows[0].id]);
197 if (!active.rowCount) return null;
198 const current = await client.query('select c.password_hash,u.email_verified_at,u.phone_verified_at from auth_credential c join app_user u on u.id=c.user_id where c.user_id=$1', [result.rows[0].id]);
199 // Recovery may have committed while this request verified a previously read hash.
200 if (!current.rowCount || current.rows[0].password_hash !== result.rows[0].password_hash ||
201 (email ? !current.rows[0].email_verified_at : !current.rows[0].phone_verified_at)) return null;
202 return session(client, result.rows[0].id);
203 });
204 if (!tokens) return res.status(401).json({ error: 'invalid_credentials' });
205 res.json(tokens);
206 });
207
208 router.post('/refresh', async (req, res) => {
209 const tokens = await transaction(pool, async (client) => {
210 const preliminary = await client.query('select user_id from auth_session where refresh_digest=$1', [sha256(String(req.body?.refreshToken ?? ''))]);
211 if (!preliminary.rowCount) return null;
212 // Account-first locking is shared with password/OTP recovery.
213 const active = await client.query('select 1 from app_user where id=$1 and disabled_at is null for update', [preliminary.rows[0].user_id]);
214 if (!active.rowCount) return null;
215 const current = await client.query('select id,user_id from auth_session where refresh_digest=$1 and revoked_at is null for update', [sha256(String(req.body?.refreshToken ?? ''))]);
216 if (!current.rowCount) return null;
217 const fresh = await client.query('select 1 from auth_session where id=$1 and revoked_at is null and expires_at>clock_timestamp()', [current.rows[0].id]);
218 if (!fresh.rowCount) return null;
219 await client.query('update auth_session set revoked_at=now() where id=$1', [current.rows[0].id]);
220 return session(client, current.rows[0].user_id);
221 });
222 if (!tokens) return res.status(401).json({ error: 'invalid_refresh_token' });
223 res.json(tokens);
224 });
225
226 router.post('/forgot-password', async (req, res) => {
227 const email = normalizeEmail(req.body?.email);
228 if (!isEmail(email)) return res.json({ accepted: true });
229 const result = await transaction(pool, async (client) => {
230 const rate = await claimDelivery(client, email, 'password_reset');
231 if (rate.retryAfter) return rate;
232 const user = await client.query('select id from app_user where email_normalized=$1 and disabled_at is null for update', [email]);
233 if (!user.rowCount) return rate;
234 const token = await oneTimeToken(client, user.rows[0].id, 'password_reset', 30);
235 await client.query('update auth_delivery_attempt set user_id=$2 where id=$1', [rate.attemptId, user.rows[0].id]);
236 return { ...rate, token };
237 });
238 if (limited(res, result)) return;
239 res.json(testMode ? { accepted: true, resetToken: result.token } : { accepted: true });
240 if (result.token) await emailDelivery(email, result.token, 'password_reset', result.attemptId);
241 else await pool.query("update auth_delivery_attempt set status='not_needed' where id=$1", [result.attemptId]).catch(() => {});
242 });
243
244 router.post('/reset-password', async (req, res) => {
245 if (!validPassword(req.body?.newPassword)) return res.status(400).json({ error: 'invalid_password' });
246 const ok = await transaction(pool, async (client) => {
247 const token = await usableToken(client, String(req.body?.token ?? ''), 'password_reset');
248 if (!token) return false;
249 const hash = await argon2.hash(req.body.newPassword, { type: argon2.argon2id });
250 await client.query('update auth_credential set password_hash=$2,password_changed_at=now() where user_id=$1', [token.user_id, hash]);
251 await client.query("update auth_token set used_at=now() where user_id=$1 and kind='password_reset' and used_at is null", [token.user_id]);
252 await client.query('update auth_session set revoked_at=now() where user_id=$1 and revoked_at is null', [token.user_id]);
253 return true;
254 });
255 if (!ok) return res.status(400).json({ error: 'invalid_or_expired_token' });
256 res.status(204).end();
257 });
258
259 router.post('/change-password', auth, async (req, res) => {
260 if (!validPassword(req.body?.newPassword)) return res.status(400).json({ error: 'invalid_password' });
261 const ok = await transaction(pool, async (client) => {
262 const active = await client.query('select 1 from app_user where id=$1 and disabled_at is null for update', [req.identity.sub]);
263 if (!active.rowCount) return false;
264 const credential = await client.query('select password_hash from auth_credential where user_id=$1 for update', [req.identity.sub]);
265 if (!credential.rowCount || !(await argon2.verify(credential.rows[0].password_hash, String(req.body?.currentPassword ?? '')))) return false;
266 const hash = await argon2.hash(req.body.newPassword, { type: argon2.argon2id });
267 await client.query('update auth_credential set password_hash=$2,password_changed_at=now() where user_id=$1', [req.identity.sub, hash]);
268 await client.query('update auth_session set revoked_at=now() where user_id=$1 and id<>$2 and revoked_at is null', [req.identity.sub, req.identity.sid]);
269 return true;
270 });
271 if (!ok) return res.status(403).json({ error: 'invalid_current_password' });
272 res.status(204).end();
273 });
274
275 router.post('/logout', async (req, res) => {
276 const refresh = req.body?.refreshToken;
277 if (typeof refresh === 'string') {
278 await pool.query('update auth_session set revoked_at=coalesce(revoked_at,now()) where refresh_digest=$1', [sha256(refresh)]);
279 } else {
280 let identity;
281 try {
282 identity = jwt.verify(req.headers.authorization?.replace(/^Bearer\s+/i, ''), jwtSecret, { audience: 'lifemate-api', issuer: 'lifemate' });
283 } catch { /* Uniform logout also accepts expired, missing or revoked proof. */ }
284 if (identity?.sid && identity?.sub) await pool.query('update auth_session set revoked_at=coalesce(revoked_at,now()) where id=$1 and user_id=$2', [identity.sid, identity.sub]);
285 }
286 res.status(204).end();
287 });
288
289 router.post('/phone/request-otp', async (req, res) => {
290 if (!smsProvider.configured) return res.status(503).json({ error: 'sms_unavailable' });
291 const phone = normalizePhone(req.body?.phone);
292 const purpose = req.body?.purpose ?? 'login';
293 if (!phone || !['verify', 'login', 'recovery'].includes(purpose)) return res.status(400).json({ error: 'invalid_input' });
294 const result = await transaction(pool, async (client) => {
295 const rate = await claimDelivery(client, phone, 'phone_otp');
296 if (rate.retryAfter) return rate;
297 const user = await client.query('select id from app_user where phone_normalized=$1 and disabled_at is null', [phone]);
298 const challengeId = crypto.randomUUID();
299 const code = String(crypto.randomInt(0, 1000000)).padStart(6, '0');
300 await client.query("insert into auth_phone_challenge(id,user_id,purpose,code_digest,expires_at) values($1,$2,$3,$4,now()+interval '5 minutes')", [challengeId, user.rows[0]?.id ?? null, purpose, digest(`otp:${challengeId}:${code}`)]);
301 if (user.rowCount) await client.query('update auth_delivery_attempt set user_id=$2 where id=$1', [rate.attemptId, user.rows[0].id]);
302 return { ...rate, challengeId, code, known: Boolean(user.rowCount) };
303 });
304 if (limited(res, result)) return;
305 res.status(202).json({ accepted: true, challengeId: result.challengeId, expiresIn: 300 });
306 if (result.known) await safelyDeliver({ configured: true, send: (message) => smsProvider.sendOtp(message) }, { phone, code: result.code, expiresIn: 300 }, { pool, attemptId: result.attemptId, env });
307 else await pool.query("update auth_delivery_attempt set status='not_needed' where id=$1", [result.attemptId]).catch(() => {});
308 });
309
310 router.post('/phone/verify-otp', async (req, res) => {
311 if (!smsProvider.configured) return res.status(503).json({ error: 'sms_unavailable' });
312 const challengeId = String(req.body?.challengeId ?? '');
313 const code = String(req.body?.code ?? '');
314 if (!uuid.test(challengeId) || !/^\d{6}$/.test(code)) return res.status(401).json({ error: 'invalid_or_expired_otp' });
315 const result = await transaction(pool, async (client) => {
316 const owner = await client.query('select user_id from auth_phone_challenge where id=$1', [challengeId]);
317 // Account-first locking also serializes two different challenges for one account.
318 let user;
319 if (owner.rows[0]?.user_id) {
320 user = await client.query('select phone_verified_at from app_user where id=$1 and disabled_at is null for update', [owner.rows[0].user_id]);
321 if (!user.rowCount) return null;
322 }
323 const challenge = await client.query('select * from auth_phone_challenge where id=$1 and used_at is null and attempts<5 for update', [challengeId]);
324 if (!challenge.rowCount) return null;
325 const fresh = await client.query('select 1 from auth_phone_challenge where id=$1 and used_at is null and attempts<5 and expires_at>clock_timestamp()', [challengeId]);
326 if (!fresh.rowCount) return null;
327 const row = challenge.rows[0];
328 await client.query('update auth_phone_challenge set attempts=attempts+1 where id=$1', [challengeId]);
329 const provided = Buffer.from(digest(`otp:${challengeId}:${code}`), 'hex');
330 if (!crypto.timingSafeEqual(provided, Buffer.from(row.code_digest, 'hex')) || !row.user_id) return null;
331 if (!user?.rowCount || (row.purpose === 'login' && !user.rows[0].phone_verified_at)) return null;
332 if (row.purpose !== 'login') {
333 if (!validPassword(req.body?.newPassword)) return { passwordRequired: true };
334 const hash = await argon2.hash(req.body.newPassword, { type: argon2.argon2id });
335 await client.query('update auth_credential set password_hash=$2,password_changed_at=now() where user_id=$1', [row.user_id, hash]);
336 await client.query('update app_user set phone_verified_at=coalesce(phone_verified_at,now()) where id=$1', [row.user_id]);
337 await client.query('update auth_session set revoked_at=now() where user_id=$1 and revoked_at is null', [row.user_id]);
338 }
339 await client.query('update auth_phone_challenge set used_at=now() where user_id=$1 and used_at is null', [row.user_id]);
340 return session(client, row.user_id);
341 });
342 if (result?.passwordRequired) return res.status(400).json({ error: 'invalid_password' });
343 if (!result) return res.status(401).json({ error: 'invalid_or_expired_otp' });
344 res.json(result);
345 });
346
347 return router;
348 }