ReviewOS

also looking at this

loghqorg/loghq

Deploy: uniform auth session model (main → production)

#7
Merged glennmichael123 wants to merge main into production
282 files +3028 -64856
app/Actions/Auth/VerifyTwoFactorLoginAction.tsadded+72-0
Changes to app/Actions/Auth/VerifyTwoFactorLoginAction.ts
@@ -0,0 +1,72 @@
1import type { RequestInstance } from '@stacksjs/types'
2import { Action } from '@stacksjs/actions'
3import { Auth, consumeTwoFactorChallenge, verifyTwoFactorLoginCode } from '@stacksjs/auth'
4import { response } from '@stacksjs/router'
5import { schema } from '@stacksjs/validation'
6import { buildAuthCookie, sessionExpiryMinutes } from './authCookie'
7
8/**
9 * Exchange a LoginAction 2FA challenge + TOTP code for a real session,
10 * registered at POST /api/auth/verify-two-factor-login (routes/auth.ts).
11 *
12 * Dormant in loghq (there is no enrolment UI), but wired end to end so a
13 * 2FA-enabled account completing step two is signed in exactly like the
14 * single-step path: the same HttpOnly `auth-token` cookie, the same
15 * remember-me tier. See LoginAction / authCookie.ts.
16 */
17export default new Action({
18 name: 'VerifyTwoFactorLoginAction',
19 description: 'Exchange a LoginAction 2FA challenge + TOTP code for a real token pack',
20 method: 'POST',
21
22 validations: {
23 challenge_token: {
24 rule: schema.string().min(1),
25 message: 'A challenge token is required.',
26 },
27 code: {
28 rule: schema.string().min(6).max(6),
29 message: 'Code must be a 6-digit TOTP code.',
30 },
31 },
32
33 async handle(request: RequestInstance) {
34 const challengeToken = request.get('challenge_token')
35 const code = request.get('code')
36
37 // Single-use: a second attempt with the same challenge token (right code or
38 // wrong) must start over from LoginAction, not retry.
39 const userId = await consumeTwoFactorChallenge(challengeToken)
40 if (!userId)
41 return response.unauthorized('This login attempt has expired - please sign in again.')
42
43 const valid = await verifyTwoFactorLoginCode(userId, code)
44 if (!valid)
45 return response.unauthorized('Invalid code - please sign in again.')
46
47 // Carry the "remember me" tier chosen on step one through to the session
48 // issued here, so a 2FA account is not silently downgraded to the baseline
49 // week. The login page re-sends the checkbox with the TOTP code.
50 const expiresInMinutes = sessionExpiryMinutes(request.get('remember'))
51 const result = await Auth.loginUsingId(userId, { expiresInMinutes })
52 if (!result)
53 return response.unauthorized('Invalid code - please sign in again.')
54
55 const user = result.user
56
57 return response.json(
58 {
59 access_token: result.token,
60 token_type: 'Bearer',
61 expires_in: result.expiresIn,
62 token: result.token,
63 user: {
64 id: user?.id,
65 email: user?.email,
66 name: user?.name,
67 },
68 },
69 { status: 200, headers: { 'Set-Cookie': buildAuthCookie(result.token, result.expiresIn) } },
70 )
71 },
72})