LifeMate — Personal, Family & Learning Companion

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