LifeMate — Personal, Family & Learning Companion

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