@payez/next-mvp 4.8.0 → 4.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (301) hide show
  1. package/POST-INSTALL.md +408 -408
  2. package/README.md +859 -859
  3. package/dist/components/account/MobileNavDrawer.js +18 -18
  4. package/dist/components/account/UserAvatarMenu.js +1 -1
  5. package/dist/components/admin/AlertSettingsTab.js +40 -40
  6. package/dist/components/admin/LoggingSettingsTab.js +28 -28
  7. package/dist/lib/session-store.js +21 -21
  8. package/dist/lib/startup-init.js +19 -19
  9. package/dist/middleware/create-middleware.js +6 -5
  10. package/dist/pages/login/page.js +28 -28
  11. package/dist/pages/settings/EnhancedSettingsPage.js +17 -17
  12. package/dist/vibe/sessions.js +28 -3
  13. package/package.json +2 -2
  14. package/scripts/check-publish-eol.mjs +33 -15
  15. package/src/api/auth-handler.ts +550 -550
  16. package/src/api/index.ts +17 -17
  17. package/src/api-handlers/account/change-password.ts +170 -170
  18. package/src/api-handlers/account/masked-info.ts +46 -46
  19. package/src/api-handlers/account/profile.ts +99 -99
  20. package/src/api-handlers/account/recovery/forward.ts +117 -117
  21. package/src/api-handlers/account/recovery/initiate.ts +59 -59
  22. package/src/api-handlers/account/recovery/send-code.ts +21 -21
  23. package/src/api-handlers/account/recovery/verify-code.ts +20 -20
  24. package/src/api-handlers/account/reset-password.ts +87 -87
  25. package/src/api-handlers/account/send-code.ts +70 -70
  26. package/src/api-handlers/account/update-phone.ts +84 -84
  27. package/src/api-handlers/account/validate-password.ts +139 -139
  28. package/src/api-handlers/account/verify-email.ts +134 -134
  29. package/src/api-handlers/account/verify-sms.ts +134 -134
  30. package/src/api-handlers/admin/analytics.ts +452 -452
  31. package/src/api-handlers/admin/audit.ts +232 -232
  32. package/src/api-handlers/admin/index.ts +63 -63
  33. package/src/api-handlers/admin/redis-sessions.ts +259 -259
  34. package/src/api-handlers/admin/sessions.ts +327 -327
  35. package/src/api-handlers/admin/site-logs.ts +388 -388
  36. package/src/api-handlers/admin/stats.ts +260 -260
  37. package/src/api-handlers/admin/users.ts +251 -251
  38. package/src/api-handlers/admin/vibe-data.ts +333 -333
  39. package/src/api-handlers/anon/preferences.ts +123 -123
  40. package/src/api-handlers/auth/credential-login-email-code.ts +92 -92
  41. package/src/api-handlers/auth/credential-login.ts +948 -948
  42. package/src/api-handlers/auth/jwks.ts +31 -31
  43. package/src/api-handlers/auth/login.ts +252 -252
  44. package/src/api-handlers/auth/passkey-signin.ts +116 -116
  45. package/src/api-handlers/auth/refresh.ts +829 -829
  46. package/src/api-handlers/auth/signout.ts +201 -201
  47. package/src/api-handlers/auth/status.ts +23 -23
  48. package/src/api-handlers/auth/update-session.ts +144 -144
  49. package/src/api-handlers/auth/validate.ts +45 -45
  50. package/src/api-handlers/auth/verify-code.ts +116 -116
  51. package/src/api-handlers/mfa/backup-code-verify.ts +170 -170
  52. package/src/api-handlers/mfa/backup-codes.ts +42 -42
  53. package/src/api-handlers/mfa/methods.ts +47 -47
  54. package/src/api-handlers/mfa/totp-confirm.ts +43 -43
  55. package/src/api-handlers/mfa/totp-enroll.ts +43 -43
  56. package/src/api-handlers/mfa/totp-verify.ts +172 -172
  57. package/src/api-handlers/oauth/resume.ts +182 -182
  58. package/src/api-handlers/onboarding/send-email-code.ts +18 -18
  59. package/src/api-handlers/onboarding/set-password.ts +21 -21
  60. package/src/api-handlers/onboarding/verify-code.ts +20 -20
  61. package/src/api-handlers/onboarding/verify-welcome-email.ts +17 -17
  62. package/src/api-handlers/passkeys/list.ts +32 -32
  63. package/src/api-handlers/passkeys/manage.ts +55 -55
  64. package/src/api-handlers/passkeys/register-options.ts +43 -43
  65. package/src/api-handlers/passkeys/register-verify.ts +42 -42
  66. package/src/api-handlers/session/refresh-viability.ts +56 -56
  67. package/src/api-handlers/session/viability.ts +238 -238
  68. package/src/api-handlers/test/force-expire.ts +167 -167
  69. package/src/auth/auth-decision.ts +292 -292
  70. package/src/auth/better-auth.ts +1688 -1688
  71. package/src/auth/idp-oauth.ts +310 -310
  72. package/src/auth/password-reset-bridge.ts +98 -98
  73. package/src/auth/route-config.ts +236 -236
  74. package/src/auth/safe-callback.ts +199 -199
  75. package/src/auth/session-cookie-clear.ts +30 -30
  76. package/src/auth/session-reset-link.ts +159 -159
  77. package/src/auth/session-response-sanitizer.ts +151 -151
  78. package/src/auth/types/auth-types.ts +555 -555
  79. package/src/auth/types/index.ts +7 -7
  80. package/src/auth/unauthenticated-routes.ts +2 -2
  81. package/src/auth/utils/idp-client.ts +364 -364
  82. package/src/auth/utils/index.ts +6 -6
  83. package/src/auth/utils/token-utils.ts +243 -243
  84. package/src/client/AuthContext.tsx +192 -192
  85. package/src/client/better-auth-client.ts +70 -70
  86. package/src/client/fetch-with-auth.ts +47 -47
  87. package/src/client/fetchWithSession.ts +21 -21
  88. package/src/client/index.ts +13 -13
  89. package/src/client/useAnonSession.ts +131 -131
  90. package/src/components/SessionSync.tsx +138 -138
  91. package/src/components/SignalRHealthCheck.tsx +131 -131
  92. package/src/components/account/MobileNavDrawer.tsx +305 -305
  93. package/src/components/account/UserAvatarMenu.tsx +277 -277
  94. package/src/components/account/index.ts +13 -13
  95. package/src/components/admin/AlertSettingsTab.tsx +728 -728
  96. package/src/components/admin/AnalyticsTab.tsx +703 -703
  97. package/src/components/admin/DataBrowserTab.tsx +508 -508
  98. package/src/components/admin/LoggingSettingsTab.tsx +665 -665
  99. package/src/components/admin/SessionsTab.tsx +421 -421
  100. package/src/components/admin/StatsTab.tsx +379 -379
  101. package/src/components/admin/VibeAdminContext.tsx +87 -87
  102. package/src/components/admin/VibeAdminLayout.tsx +187 -187
  103. package/src/components/admin/index.ts +59 -59
  104. package/src/components/auth/CredentialSignInForm.tsx +240 -240
  105. package/src/components/auth/FederatedAuthSection.tsx +129 -129
  106. package/src/components/auth/ModeAwareLoginPage.tsx +146 -146
  107. package/src/components/auth/ModeAwareSignupPage.tsx +200 -200
  108. package/src/components/auth/PasswordResetBridge.tsx +30 -30
  109. package/src/components/auth/TraditionalAuthSection.tsx +103 -103
  110. package/src/components/recovery/CompleteStep.tsx +36 -36
  111. package/src/components/recovery/InitiateRecoveryStep.tsx +68 -68
  112. package/src/components/recovery/RequestedStep.tsx +30 -30
  113. package/src/components/recovery/SelectMethodStep.tsx +73 -73
  114. package/src/components/recovery/SetPasswordStep.tsx +118 -118
  115. package/src/components/recovery/VerifyCodeStep.tsx +90 -90
  116. package/src/components/reserved/ReservedRecoveryWarning.tsx +160 -160
  117. package/src/components/reserved/ReservedStatusBox.tsx +118 -118
  118. package/src/components/ui/BetaBadge.tsx +58 -58
  119. package/src/components/ui/Footer.tsx +93 -93
  120. package/src/config/env.ts +55 -55
  121. package/src/config/logger.ts +62 -62
  122. package/src/config/logging-config.ts +82 -82
  123. package/src/config/unauthenticated-routes.ts +19 -19
  124. package/src/config/vibe-log-transport.ts +264 -264
  125. package/src/edge/internal-api-url.ts +65 -65
  126. package/src/edge/middleware.ts +42 -42
  127. package/src/hooks/useAuth.ts +117 -117
  128. package/src/hooks/useAuthSettings.ts +109 -109
  129. package/src/hooks/useAvailableProviders.ts +143 -143
  130. package/src/hooks/usePasswordValidation.ts +127 -127
  131. package/src/hooks/useProfile.ts +82 -82
  132. package/src/hooks/usePublicAuthSettings.ts +171 -171
  133. package/src/hooks/useSessionExpiration.ts +101 -101
  134. package/src/hooks/useViabilitySession.ts +337 -337
  135. package/src/index.ts +64 -64
  136. package/src/lib/anon-session.ts +213 -213
  137. package/src/lib/api-handler.ts +643 -643
  138. package/src/lib/app-slug.ts +228 -228
  139. package/src/lib/authorize-resume.ts +172 -172
  140. package/src/lib/bearer-fetch.ts +31 -31
  141. package/src/lib/client-key.ts +88 -88
  142. package/src/lib/code-step-copy.ts +83 -83
  143. package/src/lib/credential-sign-in-client.ts +101 -101
  144. package/src/lib/demo-mode.ts +18 -18
  145. package/src/lib/device-id.ts +67 -67
  146. package/src/lib/ensure-fresh-access-token.ts +509 -509
  147. package/src/lib/geolocation.ts +265 -265
  148. package/src/lib/idp-client-config.ts +1005 -1005
  149. package/src/lib/idp-fetch.ts +169 -169
  150. package/src/lib/idp-url-guard.ts +37 -37
  151. package/src/lib/internal-api.ts +171 -171
  152. package/src/lib/jwt-decode-client.ts +45 -45
  153. package/src/lib/jwt-decode.ts +82 -82
  154. package/src/lib/lock-window.ts +49 -49
  155. package/src/lib/login-error-message.ts +41 -41
  156. package/src/lib/never-in-response.ts +64 -64
  157. package/src/lib/nextauth-secret.ts +168 -168
  158. package/src/lib/onboarding-proxy.ts +57 -57
  159. package/src/lib/password-rules.ts +50 -50
  160. package/src/lib/rate-limit-service.ts +9 -9
  161. package/src/lib/redis.ts +105 -105
  162. package/src/lib/refresh-token-validator.ts +64 -64
  163. package/src/lib/roles.ts +177 -177
  164. package/src/lib/safe-error-response.ts +149 -149
  165. package/src/lib/secret-validation.ts +8 -8
  166. package/src/lib/session-cookie-shape.ts +185 -185
  167. package/src/lib/session-store.ts +1092 -1092
  168. package/src/lib/session.ts +34 -34
  169. package/src/lib/single-flight.ts +64 -64
  170. package/src/lib/site-logger.ts +245 -245
  171. package/src/lib/standardized-client-api.ts +901 -901
  172. package/src/lib/startup-init.ts +276 -276
  173. package/src/lib/test-aware-get-token.ts +41 -41
  174. package/src/lib/token-expiry.ts +40 -40
  175. package/src/lib/token-lifecycle.ts +546 -546
  176. package/src/lib/token-log-id.ts +69 -69
  177. package/src/lib/twofa-rejection.ts +91 -91
  178. package/src/lib/types/api-responses.ts +336 -336
  179. package/src/lib/user-agent-parser.ts +252 -252
  180. package/src/logging/api/admin-analytics.ts +51 -51
  181. package/src/logging/api/audit-log.ts +53 -53
  182. package/src/logging/components/AdminAnalyticsLayout.tsx +49 -49
  183. package/src/logging/components/AuditLogViewer.tsx +125 -125
  184. package/src/logging/components/ErrorMetricsCard.tsx +98 -98
  185. package/src/logging/components/HealthMetricsCard.tsx +70 -70
  186. package/src/logging/hooks/useAdminAnalytics.ts +22 -22
  187. package/src/logging/hooks/useAuditLog.ts +24 -24
  188. package/src/logging/hooks/useErrorMetrics.ts +40 -40
  189. package/src/logging/hooks/useHealthMetrics.ts +44 -44
  190. package/src/logging/index.ts +18 -18
  191. package/src/logging/types/analytics.ts +81 -81
  192. package/src/logging/types/audit.ts +31 -31
  193. package/src/logging/types/index.ts +3 -3
  194. package/src/middleware/create-middleware.ts +1139 -1138
  195. package/src/middleware/rbac-check.ts +279 -279
  196. package/src/middleware/twofa-presets.ts +224 -224
  197. package/src/models/DecodedAccessToken.ts +16 -16
  198. package/src/models/SessionModel.ts +331 -331
  199. package/src/pages/admin-login/page.tsx +111 -111
  200. package/src/pages/admin-page-permissions/PagePermissionsAdminPage.tsx +527 -527
  201. package/src/pages/admin-page-permissions/index.ts +7 -7
  202. package/src/pages/admin-roles/RolesAdminPage.tsx +533 -533
  203. package/src/pages/admin-roles/index.ts +9 -9
  204. package/src/pages/admin-roles/modals.tsx +469 -469
  205. package/src/pages/client-admin/ClientSiteAdminPage.tsx +382 -382
  206. package/src/pages/client-admin/index.ts +33 -33
  207. package/src/pages/coming-soon/page.tsx +83 -83
  208. package/src/pages/login/page.tsx +338 -338
  209. package/src/pages/onboarding/index.ts +11 -11
  210. package/src/pages/onboarding/page.tsx +212 -212
  211. package/src/pages/profile/EnhancedProfilePage.tsx +514 -514
  212. package/src/pages/profile/index.ts +9 -9
  213. package/src/pages/profile/page.tsx +166 -166
  214. package/src/pages/recovery/page.tsx +267 -267
  215. package/src/pages/roles/MyRolesPage.tsx +211 -211
  216. package/src/pages/roles/components.tsx +294 -294
  217. package/src/pages/roles/index.ts +17 -17
  218. package/src/pages/security/EnhancedSecurityPage.tsx +660 -660
  219. package/src/pages/security/index.ts +12 -12
  220. package/src/pages/security/page.tsx +507 -507
  221. package/src/pages/settings/EnhancedSettingsPage.tsx +642 -642
  222. package/src/pages/settings/index.ts +9 -9
  223. package/src/pages/settings/page.tsx +47 -47
  224. package/src/pages/showcase/ShowcasePage.tsx +532 -532
  225. package/src/pages/showcase/index.ts +13 -13
  226. package/src/pages/test-env/EmergencyLogoutPage.tsx +192 -192
  227. package/src/pages/test-env/JwtInspectPage.tsx +449 -449
  228. package/src/pages/test-env/RefreshTokenPage.tsx +178 -178
  229. package/src/pages/test-env/TestEnvPage.tsx +130 -130
  230. package/src/pages/test-env/guarded.tsx +81 -81
  231. package/src/pages/test-env/index.ts +77 -77
  232. package/src/pages/test-env/redact-credentials.ts +96 -96
  233. package/src/pages/verify-code/page.tsx +746 -746
  234. package/src/routes/account/index.ts +31 -31
  235. package/src/routes/account/masked-info.ts +36 -36
  236. package/src/routes/account/send-code.ts +39 -39
  237. package/src/routes/account/update-phone.ts +13 -13
  238. package/src/routes/account/verify-email.ts +40 -40
  239. package/src/routes/account/verify-sms.ts +40 -40
  240. package/src/routes/auth/credential-login-email-code.ts +6 -6
  241. package/src/routes/auth/credential-login.ts +6 -6
  242. package/src/routes/auth/index.ts +22 -22
  243. package/src/routes/auth/logout.ts +111 -111
  244. package/src/routes/auth/nextauth.ts +45 -45
  245. package/src/routes/auth/passkey-signin.ts +13 -13
  246. package/src/routes/auth/refresh.ts +77 -77
  247. package/src/routes/auth/session-reset.ts +37 -37
  248. package/src/routes/auth/session.ts +261 -261
  249. package/src/routes/auth/settings.ts +181 -181
  250. package/src/routes/auth/viability.ts +519 -519
  251. package/src/routes/index.ts +17 -17
  252. package/src/routes/mfa/backup-code-verify.ts +1 -1
  253. package/src/routes/mfa/backup-codes.ts +10 -10
  254. package/src/routes/mfa/methods.ts +22 -22
  255. package/src/routes/mfa/totp-confirm.ts +10 -10
  256. package/src/routes/mfa/totp-enroll.ts +10 -10
  257. package/src/routes/mfa/totp-verify.ts +14 -14
  258. package/src/routes/onboarding/index.ts +15 -15
  259. package/src/routes/onboarding/send-email-code.ts +2 -2
  260. package/src/routes/onboarding/set-password.ts +2 -2
  261. package/src/routes/onboarding/verify-code.ts +2 -2
  262. package/src/routes/onboarding/verify-welcome-email.ts +2 -2
  263. package/src/routes/passkeys/list.ts +10 -10
  264. package/src/routes/passkeys/manage.ts +23 -23
  265. package/src/routes/passkeys/register-options.ts +10 -10
  266. package/src/routes/passkeys/register-verify.ts +10 -10
  267. package/src/routes/session/index.ts +7 -7
  268. package/src/routes/session/refresh-viability.ts +17 -17
  269. package/src/server/auth-guard.ts +203 -203
  270. package/src/server/auth.ts +486 -486
  271. package/src/server/decode-session.ts +309 -309
  272. package/src/server/slim-middleware.ts +117 -117
  273. package/src/server/verified-session-token.ts +103 -103
  274. package/src/server/with-auth.ts +93 -93
  275. package/src/services/signalrActivityService.ts +258 -258
  276. package/src/stores/authStore.ts +1900 -1900
  277. package/src/templates/instrumentation.ts +60 -60
  278. package/src/theme/ThemeProvider.tsx +39 -39
  279. package/src/theme/default.ts +33 -33
  280. package/src/theme/index.ts +31 -31
  281. package/src/theme/types.ts +69 -69
  282. package/src/theme/useTheme.ts +57 -57
  283. package/src/theme/utils.ts +40 -40
  284. package/src/types/api.ts +12 -12
  285. package/src/types/auth.d.ts +23 -23
  286. package/src/types/auth.ts +48 -48
  287. package/src/types/logging.ts +11 -11
  288. package/src/types/recovery.ts +54 -54
  289. package/src/utils/api.ts +401 -401
  290. package/src/utils/circuitBreaker.ts +40 -40
  291. package/src/utils/error-message.ts +108 -108
  292. package/src/utils/layout/reservedSpace.ts +124 -124
  293. package/src/utils/logout.ts +30 -30
  294. package/src/vibe/client.ts +877 -877
  295. package/src/vibe/enterprise-auth.ts +208 -208
  296. package/src/vibe/errors.ts +209 -209
  297. package/src/vibe/generic.ts +339 -339
  298. package/src/vibe/hooks/index.ts +367 -367
  299. package/src/vibe/index.ts +133 -133
  300. package/src/vibe/sessions.ts +925 -899
  301. package/src/vibe/types.ts +577 -577
@@ -1,746 +1,746 @@
1
- /**
2
- * Themed 2FA Verification Page for @payez/next-mvp
3
- *
4
- * PLAIN STYLING, FULL FUNCTIONALITY
5
- * - Clean, professional appearance
6
- * - All functional patterns from website-membership
7
- * - Themeable via ThemeProvider
8
- *
9
- * DEPENDENCIES: Only React, Next.js, next-auth, and Tailwind CSS
10
- * NO shadcn/ui or other UI library required!
11
- *
12
- * FEATURES:
13
- * ✅ Progressive disclosure: method selection → code input
14
- * ✅ Method locking after selection (prevents accidental multi-send)
15
- * ✅ Masked contact info display (informational only)
16
- * ✅ Auto-submit when code reaches 6 digits
17
- * ✅ Cooldown timers (30s) on resend buttons
18
- * ✅ Stale session detection (401 → redirect to login)
19
- * ✅ JWT-specific error detection and messaging
20
- * ✅ Session viability polling (every 30s) to detect expiration early
21
- * ✅ Duplicate submission prevention
22
- * ✅ Success/error states with atomic management
23
- * ✅ "Change method" action
24
- * ✅ Session cleanup on success/expiry
25
- *
26
- * USAGE:
27
- * 1. Import from @payez/next-mvp/pages/verify-code
28
- * 2. Wrap your app with ThemeProvider to customize branding
29
- */
30
-
31
- 'use client';
32
-
33
- import React, { useState, useEffect, useRef } from 'react';
34
- import { useRouter, useSearchParams } from 'next/navigation';
35
- import { authClient } from '../../client/better-auth-client';
36
- import { Suspense } from 'react';
37
- import { useColors } from '../../theme/useTheme';
38
- import { safeCallbackPath } from '../../auth/safe-callback';
39
-
40
- /**
41
- * Session storage key to track that user intentionally navigated to verify-code.
42
- * Prevents auto-redirect back to dashboard when session refreshes in background.
43
- */
44
- const VERIFY_IN_PROGRESS_KEY = 'idealvibe_2fa_verify_in_progress';
45
-
46
- // Masked info structure from IDP
47
- interface MaskedInfo {
48
- masked_email?: string;
49
- masked_phone_number?: string;
50
- has_authenticator?: boolean;
51
- }
52
-
53
- function VerifyCodeForm({ enrollHref }: { enrollHref: string }) {
54
- const router = useRouter();
55
- const searchParams = useSearchParams();
56
- /**
57
- * 375936 - ORIGIN-GUARDED AT THE READ, NOT AT THE SINK.
58
- *
59
- * This value ends up in `window.location.href` after a SUCCESSFUL 2FA
60
- * ceremony (see the setTimeout further down). That is a full navigation, so
61
- * an absolute URL here is a cross-origin redirect - the user completes a
62
- * genuine login and is then dropped on an attacker-controlled page at the
63
- * exact moment they are most primed to trust what they see.
64
- *
65
- * This used to be a raw `searchParams?.get('callbackUrl') || '/dashboard'`.
66
- * The middleware does NOT protect this page: create-middleware's
67
- * `needsTwoFactorRedirect` returns false for VERIFY_CODE_PAGE, so a direct
68
- * request arrives here with its query string untouched.
69
- *
70
- * Do NOT "simplify" this back to a `startsWith('/account-auth/')` test. The
71
- * three such tests below are LOOP prevention, not ORIGIN prevention -
72
- * `https://evil.example` passes every one of them. safeCallbackPath asks the
73
- * URL parser instead, so protocol-relative (`//host`), backslash (`/\host`)
74
- * and TAB/LF/CR spellings all fail one origin comparison rather than needing
75
- * their own blacklist entry.
76
- *
77
- * Guarding at the READ rather than at the sink means every later use of
78
- * `callbackUrl` on this page inherits the guarantee.
79
- */
80
- const callbackUrl = safeCallbackPath(searchParams?.get('callbackUrl'), '/dashboard');
81
-
82
- const { data: sessionData, isPending } = authClient.useSession();
83
- const session = sessionData;
84
- const status = isPending ? 'loading' : session ? 'authenticated' : 'unauthenticated';
85
- // TODO: Better Auth session refresh
86
- const updateSession = async () => { return session; };
87
- const colors = useColors();
88
-
89
- // Method selection
90
- type Method = 'email' | 'sms' | null;
91
- const [method, setMethod] = useState<Method>(null);
92
- const [methodLocked, setMethodLocked] = useState(false);
93
-
94
- // Form state
95
- const [code, setCode] = useState('');
96
- const [maskedInfo, setMaskedInfo] = useState<MaskedInfo | null>(null);
97
- const [loadingMasked, setLoadingMasked] = useState(true);
98
-
99
- // Atomic state - only one active at a time
100
- const [sending, setSending] = useState(false);
101
- const [verifying, setVerifying] = useState(false);
102
- const [success, setSuccess] = useState(false);
103
- const [error, setError] = useState<string | null>(null);
104
-
105
- // Cooldown timers
106
- const [emailCooldown, setEmailCooldown] = useState(0);
107
- const [smsCooldown, setSmsCooldown] = useState(0);
108
-
109
- // Toast notifications
110
- const [toast, setToast] = useState<{ type: 'success' | 'error'; message: string } | null>(null);
111
-
112
- // Refs
113
- const codeInputRef = useRef<HTMLInputElement>(null);
114
- const lastSubmittedCode = useRef<string>('');
115
-
116
- // Track that user is intentionally on this page
117
- const [verifyInProgress, setVerifyInProgress] = useState(false);
118
-
119
- // ==========================================================================
120
- // CRITICAL FIX: Mark that user is intentionally on verify page
121
- // This prevents auto-redirect when background token refresh updates session
122
- // ==========================================================================
123
- useEffect(() => {
124
- // On mount, mark that verification is in progress
125
- if (typeof window !== 'undefined') {
126
- const wasInProgress = sessionStorage.getItem(VERIFY_IN_PROGRESS_KEY) === 'true';
127
- if (!wasInProgress) {
128
- console.log('[2FA] User navigated to verify-code page, marking verify in progress');
129
- sessionStorage.setItem(VERIFY_IN_PROGRESS_KEY, 'true');
130
- }
131
- setVerifyInProgress(true);
132
- }
133
- }, []);
134
-
135
- // Auto-dismiss toast
136
- useEffect(() => {
137
- if (toast) {
138
- const timer = setTimeout(() => setToast(null), 2500);
139
- return () => clearTimeout(timer);
140
- }
141
- }, [toast]);
142
-
143
- // Cooldown countdown
144
- useEffect(() => {
145
- if (emailCooldown > 0) {
146
- const timer = setTimeout(() => setEmailCooldown(emailCooldown - 1), 1000);
147
- return () => clearTimeout(timer);
148
- }
149
- }, [emailCooldown]);
150
-
151
- useEffect(() => {
152
- if (smsCooldown > 0) {
153
- const timer = setTimeout(() => setSmsCooldown(smsCooldown - 1), 1000);
154
- return () => clearTimeout(timer);
155
- }
156
- }, [smsCooldown]);
157
-
158
- // Fetch masked info on mount
159
- useEffect(() => {
160
- const fetchMaskedInfo = async () => {
161
- // BUGFIX: Always set loadingMasked=false, even if not authenticated
162
- // Otherwise page stays stuck in loading spinner
163
- if (status !== 'authenticated' || !session) {
164
- setLoadingMasked(false);
165
- return;
166
- }
167
-
168
- try {
169
- const res = await fetch('/api/account/masked-info', {
170
- method: 'POST',
171
- credentials: 'include',
172
- });
173
-
174
- if (res.status === 401) {
175
- // Session expired - redirect to login
176
- setError('Your session has expired. Redirecting to login...');
177
- setTimeout(async () => {
178
- await authClient.signOut();
179
- const safeCallback = callbackUrl.startsWith('/account-auth/') ? '/dashboard' : callbackUrl;
180
- router.push(`/account-auth/login?callbackUrl=${encodeURIComponent(safeCallback)}`);
181
- }, 1200);
182
- return;
183
- }
184
-
185
- if (!res.ok) {
186
- throw new Error('Failed to load contact information');
187
- }
188
-
189
- const data = await res.json();
190
- setMaskedInfo(data);
191
- } catch (err) {
192
- console.error('[2FA] Error fetching masked info:', err);
193
- setError('Could not load your contact information. Please try again.');
194
- } finally {
195
- setLoadingMasked(false);
196
- }
197
- };
198
-
199
- fetchMaskedInfo();
200
- }, [status, session, callbackUrl, router]);
201
-
202
- // Auto-submit when code is 6 digits
203
- useEffect(() => {
204
- if (code.length === 6 && method && !verifying) {
205
- handleVerifyCode();
206
- }
207
- }, [code, method, verifying]);
208
-
209
- // ==========================================================================
210
- // Session viability check - detect expiration early and warn user
211
- // ==========================================================================
212
- useEffect(() => {
213
- if (status !== 'authenticated') return;
214
-
215
- // Check session viability every 30 seconds
216
- const checkSession = async () => {
217
- try {
218
- const res = await fetch('/api/session/viability', {
219
- credentials: 'include',
220
- });
221
-
222
- // ====================================================================
223
- // THE ENROLMENT DEAD END (cards 170045 / 170047, was 141688 / 141741)
224
- // ====================================================================
225
- // A first-time social user arrives here with ZERO usable methods and is
226
- // asked for a code from an authenticator that does not exist. There was
227
- // no way out: not a missing feature, AN UNASKED QUESTION.
228
- //
229
- // The IDP already decides this and says so. The package already relays
230
- // it — from BOTH viability exports, deliberately, so an app mounting
231
- // either is not left blind. The graft already mounts the route. THIS
232
- // PAGE ALREADY CALLS IT, four lines above. It simply never read the
233
- // answer: the only branch was `res.status === 401`, so on a perfectly
234
- // valid session the response was fetched and thrown away.
235
- //
236
- // 'enroll_mfa' no USABLE method — the user CANNOT complete a
237
- // challenge, so keeping them on a code prompt is a trap
238
- // 'mfa_verify' a usable method exists — the prompt is correct
239
- // null nothing due
240
- //
241
- // Every link in that chain was built against these very cards. The
242
- // last consumer just never asked.
243
- if (res.ok) {
244
- const data = await res.json().catch(() => ({}));
245
- if (data?.nextStep === 'enroll_mfa') {
246
- router.replace(enrollHref);
247
- return;
248
- }
249
- }
250
-
251
- if (res.status === 401) {
252
- const data = await res.json().catch(() => ({}));
253
-
254
- // Session is no longer valid - warn user and redirect
255
- if (data.valid === false || data.mfaExpired === true) {
256
- setError('Your session has expired. Redirecting to login...');
257
- setTimeout(async () => {
258
- await authClient.signOut();
259
- if (typeof window !== 'undefined') {
260
- sessionStorage.removeItem(VERIFY_IN_PROGRESS_KEY);
261
- }
262
- router.push(`/account-auth/login?error=SessionExpired`);
263
- }, 2000);
264
- }
265
- }
266
- } catch (err) {
267
- // Silent fail - let the next actual API call handle the error
268
- console.log('[2FA] Session viability check failed:', err);
269
- }
270
- };
271
-
272
- // Initial check after 5 seconds, then every 30 seconds
273
- const initialTimeout = setTimeout(checkSession, 5000);
274
- const interval = setInterval(checkSession, 30000);
275
-
276
- return () => {
277
- clearTimeout(initialTimeout);
278
- clearInterval(interval);
279
- };
280
- }, [status, router, enrollHref]);
281
-
282
- // ==========================================================================
283
- // Enrolment dead-end check — IMMEDIATE, and deliberately separate
284
- // ==========================================================================
285
- // The poller above first fires after 5 SECONDS. For expiry that is fine. For
286
- // a user who can never complete this challenge it is five seconds of staring
287
- // at an unanswerable prompt, which is the whole complaint in card 170045.
288
- //
289
- // This runs at once — but it is a SEPARATE effect rather than removing the
290
- // 5s delay, because that delay guards the 401 path against racing session
291
- // establishment immediately after sign-in. Firing the expiry logic instantly
292
- // could sign a user out for having a session that is merely still settling.
293
- // So: this reads ONLY the 200 body and ONLY routes on 'enroll_mfa'. It never
294
- // signs anyone out, so it is safe to run with no delay.
295
- useEffect(() => {
296
- if (status !== 'authenticated') return;
297
- let cancelled = false;
298
- (async () => {
299
- try {
300
- const res = await fetch('/api/session/viability', { credentials: 'include' });
301
- if (!res.ok || cancelled) return;
302
- const data = await res.json().catch(() => ({}));
303
- if (data?.nextStep === 'enroll_mfa') router.replace(enrollHref);
304
- } catch {
305
- // Silent: the poller and the next real API call both still cover this.
306
- // A failed check must leave the user on the prompt, never redirect them.
307
- }
308
- })();
309
- return () => { cancelled = true; };
310
- }, [status, router, enrollHref]);
311
-
312
- const handleSendCode = async (selectedMethod: 'email' | 'sms') => {
313
- setSending(true);
314
- setError(null);
315
-
316
- try {
317
- const res = await fetch('/api/account/send-code', {
318
- method: 'POST',
319
- headers: { 'Content-Type': 'application/json' },
320
- body: JSON.stringify({ method: selectedMethod }),
321
- credentials: 'include',
322
- });
323
-
324
- if (res.status === 401) {
325
- const errorData = await res.json().catch(() => ({}));
326
- const isJwtExpired = errorData?.error?.includes('JWT') || errorData?.message?.includes('JWT') || errorData?.error?.includes('expired');
327
-
328
- setError(isJwtExpired
329
- ? 'Your 2FA session has expired. Please sign in again.'
330
- : 'Your session has expired. Redirecting to login...'
331
- );
332
-
333
- setTimeout(async () => {
334
- await authClient.signOut();
335
- if (typeof window !== 'undefined') {
336
- sessionStorage.removeItem(VERIFY_IN_PROGRESS_KEY);
337
- }
338
- const safeCallback = callbackUrl.startsWith('/account-auth/') ? '/dashboard' : callbackUrl;
339
- // PAY-884: an expired JWT here is the provisional pre-2FA token - say so on the login page.
340
- const errorParam = isJwtExpired ? '&error=TwoFactorTimeout' : '';
341
- router.push(`/account-auth/login?callbackUrl=${encodeURIComponent(safeCallback)}${errorParam}`);
342
- }, 1500);
343
- return;
344
- }
345
-
346
- if (!res.ok) {
347
- const data = await res.json();
348
- throw new Error(data.message || data.error || 'Failed to send code');
349
- }
350
-
351
- // Lock method and set cooldown
352
- setMethod(selectedMethod);
353
- setMethodLocked(true);
354
-
355
- if (selectedMethod === 'email') {
356
- setEmailCooldown(30);
357
- } else {
358
- setSmsCooldown(30);
359
- }
360
-
361
- setToast({
362
- type: 'success',
363
- message: `Verification code sent to your ${selectedMethod === 'email' ? 'email' : 'phone'}`,
364
- });
365
-
366
- // Focus code input
367
- setTimeout(() => codeInputRef.current?.focus(), 100);
368
- } catch (err) {
369
- setError(err instanceof Error ? err.message : 'Failed to send verification code');
370
- } finally {
371
- setSending(false);
372
- }
373
- };
374
-
375
- const handleVerifyCode = async () => {
376
- if (!code || !method || code.length !== 6) {
377
- return;
378
- }
379
-
380
- // Prevent duplicate submissions
381
- if (lastSubmittedCode.current === code) {
382
- console.log('[2FA] Duplicate submission prevented');
383
- return;
384
- }
385
- lastSubmittedCode.current = code;
386
-
387
- setVerifying(true);
388
- setError(null);
389
-
390
- try {
391
- const endpoint = method === 'sms' ? '/api/account/verify-sms' : '/api/account/verify-email';
392
-
393
- const res = await fetch(endpoint, {
394
- method: 'POST',
395
- headers: { 'Content-Type': 'application/json' },
396
- body: JSON.stringify({ verificationCode: code }),
397
- credentials: 'include',
398
- });
399
-
400
- if (res.status === 401) {
401
- const errorData = await res.json().catch(() => ({}));
402
- const isJwtExpired = errorData?.error?.includes('JWT') || errorData?.message?.includes('JWT') || errorData?.error?.includes('expired');
403
-
404
- setError(isJwtExpired
405
- ? 'Your 2FA session has expired. Please sign in again.'
406
- : 'Your session has expired. Redirecting to login...'
407
- );
408
-
409
- setTimeout(async () => {
410
- await authClient.signOut();
411
- if (typeof window !== 'undefined') {
412
- sessionStorage.removeItem(VERIFY_IN_PROGRESS_KEY);
413
- }
414
- const safeCallback = callbackUrl.startsWith('/account-auth/') ? '/dashboard' : callbackUrl;
415
- // PAY-884: an expired JWT here is the provisional pre-2FA token - say so on the login page.
416
- const errorParam = isJwtExpired ? '&error=TwoFactorTimeout' : '';
417
- router.push(`/account-auth/login?callbackUrl=${encodeURIComponent(safeCallback)}${errorParam}`);
418
- }, 1500);
419
- return;
420
- }
421
-
422
- if (!res.ok) {
423
- const data = await res.json();
424
- throw new Error(data.error || data.message || 'Verification failed');
425
- }
426
-
427
- const result = await res.json();
428
-
429
- // Normalize response: support both enveloped and unwrapped payloads
430
- const payload = (result && typeof result === 'object' && 'data' in result)
431
- ? (result as any).data
432
- : result;
433
-
434
- // Check if verification was successful
435
- const verified =
436
- payload?.verificationSuccessful === true ||
437
- payload?.twoFactorSessionVerified === true ||
438
- payload?.success === true ||
439
- // Accept token-based success (unwrapped raw tokens from backend)
440
- (!!payload?.access_token && !!payload?.refresh_token);
441
-
442
- if (!verified) {
443
- throw new Error('Verification failed. Please try again.');
444
- }
445
-
446
- // CRITICAL: If tokens are included (unwrapped response), persist them in server session
447
- if (payload?.access_token && payload?.refresh_token) {
448
- try {
449
- console.log('[2FA] Updating session with new MFA tokens...');
450
- const updateRes = await fetch('/api/auth/update-session', {
451
- method: 'POST',
452
- headers: { 'Content-Type': 'application/json' },
453
- credentials: 'include',
454
- body: JSON.stringify({
455
- access_token: payload.access_token,
456
- refresh_token: payload.refresh_token
457
- })
458
- });
459
-
460
- if (!updateRes.ok) {
461
- console.warn('[2FA] update-session returned non-OK status:', updateRes.status);
462
- const errorData = await updateRes.json();
463
- // PAY-1427: the request carried access_token/refresh_token; log the error envelope's shape, never its contents.
464
- console.warn('[2FA] update-session error:', { keys: errorData && typeof errorData === 'object' ? Object.keys(errorData) : typeof errorData, code: errorData?.error?.code ?? errorData?.code });
465
- } else {
466
- console.log('[2FA] Session updated successfully with MFA tokens');
467
- }
468
- } catch (e) {
469
- console.warn('[2FA] Failed to call update-session:', e);
470
- }
471
- }
472
-
473
- // Show success state
474
- setSuccess(true);
475
- setError(null);
476
-
477
- // CRITICAL: Force NextAuth to refetch session from server
478
- // This ensures useSession() gets the updated twoFactorComplete: true
479
- console.log('[2FA] Forcing session refresh after verification...');
480
- try {
481
- await updateSession(); // This triggers /api/auth/session and updates useSession() state
482
- console.log('[2FA] Session refresh completed');
483
- } catch (e) {
484
- console.warn('[2FA] updateSession failed:', e);
485
- }
486
-
487
- // Clear verify-in-progress flag before redirect
488
- if (typeof window !== 'undefined') {
489
- sessionStorage.removeItem(VERIFY_IN_PROGRESS_KEY);
490
- }
491
-
492
- // Redirect after showing success state
493
- setTimeout(() => {
494
- window.location.href = callbackUrl;
495
- }, 1500);
496
- } catch (err) {
497
- setError(err instanceof Error ? err.message : 'Failed to verify code');
498
- lastSubmittedCode.current = ''; // Allow retry
499
- } finally {
500
- setVerifying(false);
501
- }
502
- };
503
-
504
- const handleResetMethod = () => {
505
- setMethod(null);
506
- setMethodLocked(false);
507
- setCode('');
508
- setError(null);
509
- setEmailCooldown(0);
510
- setSmsCooldown(0);
511
- lastSubmittedCode.current = '';
512
- };
513
-
514
- const handleCodeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
515
- const value = e.target.value.replace(/[^0-9]/g, '').slice(0, 6);
516
- setCode(value);
517
- };
518
-
519
- // Loading state
520
- if (status === 'loading' || loadingMasked) {
521
- return (
522
- <div className="flex flex-col items-center justify-center py-8" style={{ background: 'hsl(var(--background))' }}>
523
- <svg className="animate-spin h-10 w-10" style={{ color: 'hsl(var(--primary))' }} viewBox="0 0 24 24" fill="none">
524
- <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
525
- <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z" />
526
- </svg>
527
- <p className="mt-4 text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>Loading...</p>
528
- </div>
529
- );
530
- }
531
-
532
- return (
533
- <div className="flex items-center justify-center px-4 py-8" style={{ background: 'hsl(var(--background))' }}>
534
- <div className="max-w-md w-full">
535
- {/* Toast Notification */}
536
- {toast && (
537
- <div
538
- className={`fixed top-4 right-4 p-4 rounded border transition-all duration-300 ${
539
- toast.type === 'success' ? 'bg-green-50 text-green-800 border-green-200' : 'bg-red-50 text-red-800 border-red-200'
540
- }`}
541
- >
542
- {toast.message}
543
- </div>
544
- )}
545
-
546
- {/* Card */}
547
- <div className="rounded-2xl border p-8" style={{ background: 'hsl(var(--card))', borderColor: 'hsl(var(--border))' }}>
548
- {/* Header */}
549
- <div className="mb-6">
550
- <h1 className="text-2xl font-semibold mb-2" style={{ color: 'hsl(var(--foreground))' }}>Verify Your Identity</h1>
551
- <p className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>Choose how you'd like to receive your verification code</p>
552
- </div>
553
-
554
- {/* Masked Info Display */}
555
- {maskedInfo && (
556
- <div className="mb-6 p-3 rounded border text-sm" style={{ background: 'hsl(var(--muted) / 0.1)', borderColor: 'hsl(var(--border))', color: 'hsl(var(--foreground))' }}>
557
- {maskedInfo.masked_email && (
558
- <div className="mb-1">
559
- Email: <span className="font-mono">{maskedInfo.masked_email}</span>
560
- </div>
561
- )}
562
- {maskedInfo.masked_phone_number && (
563
- <div>
564
- Phone: <span className="font-mono">{maskedInfo.masked_phone_number}</span>
565
- </div>
566
- )}
567
- </div>
568
- )}
569
-
570
- {/* Method Selection or Code Input */}
571
- {!method ? (
572
- /* Method Selection */
573
- <div className="space-y-3">
574
- <button
575
- type="button"
576
- onClick={() => handleSendCode('email')}
577
- disabled={sending || !maskedInfo?.masked_email}
578
- className="w-full flex items-center justify-between p-3 border rounded disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
579
- style={{
580
- background: 'hsl(var(--card))',
581
- borderColor: 'hsl(var(--border))',
582
- color: 'hsl(var(--foreground))'
583
- }}
584
- >
585
- <div className="text-left">
586
- <p className="font-medium" style={{ color: 'hsl(var(--foreground))' }}>Email</p>
587
- <p className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>{maskedInfo?.masked_email || 'Not available'}</p>
588
- </div>
589
- <span style={{ color: 'hsl(var(--muted-foreground))' }}>→</span>
590
- </button>
591
-
592
- <button
593
- type="button"
594
- onClick={() => handleSendCode('sms')}
595
- disabled={sending || !maskedInfo?.masked_phone_number}
596
- className="w-full flex items-center justify-between p-3 border rounded disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
597
- style={{
598
- background: 'hsl(var(--card))',
599
- borderColor: 'hsl(var(--border))',
600
- color: 'hsl(var(--foreground))'
601
- }}
602
- >
603
- <div className="text-left">
604
- <p className="font-medium" style={{ color: 'hsl(var(--foreground))' }}>SMS</p>
605
- <p className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>{maskedInfo?.masked_phone_number || 'Not available'}</p>
606
- </div>
607
- <span style={{ color: 'hsl(var(--muted-foreground))' }}>→</span>
608
- </button>
609
- </div>
610
- ) : (
611
- /* Code Input */
612
- <div className="space-y-4">
613
- {/* Method indicator */}
614
- <div className="flex items-center justify-between p-3 rounded border" style={{ background: 'hsl(var(--muted) / 0.1)', borderColor: 'hsl(var(--border))' }}>
615
- <span className="text-sm" style={{ color: 'hsl(var(--foreground))' }}>
616
- Code sent to your {method === 'email' ? 'email' : 'phone'}
617
- </span>
618
- <button type="button" onClick={handleResetMethod} className="text-sm hover:underline font-medium" style={{ color: 'hsl(var(--primary))' }}>
619
- Change method
620
- </button>
621
- </div>
622
-
623
- {/* Code input */}
624
- <div>
625
- <label htmlFor="code" className="block text-sm font-medium mb-2" style={{ color: 'hsl(var(--foreground))' }}>
626
- Verification Code
627
- </label>
628
- <input
629
- ref={codeInputRef}
630
- id="code"
631
- type="text"
632
- inputMode="numeric"
633
- pattern="[0-9]*"
634
- maxLength={6}
635
- value={code}
636
- onChange={handleCodeChange}
637
- className="w-full px-4 py-3 text-center text-2xl font-mono border rounded focus:ring-2 tracking-widest"
638
- style={{
639
- background: 'hsl(var(--input))',
640
- borderColor: 'hsl(var(--border))',
641
- color: 'hsl(var(--foreground))',
642
- caretColor: 'hsl(var(--foreground))'
643
- }}
644
- placeholder="000000"
645
- disabled={verifying || success}
646
- autoComplete="one-time-code"
647
- autoFocus
648
- />
649
- <p className="mt-2 text-sm text-center" style={{ color: 'hsl(var(--muted-foreground))' }}>Enter the 6-digit code</p>
650
- </div>
651
-
652
- {/* Status Display - Pre-sized container to prevent layout shift */}
653
- <div className="min-h-[3.5rem] flex items-center">
654
- {verifying ? (
655
- <div className="w-full flex items-start space-x-2 p-3 rounded border" style={{ background: 'hsl(var(--muted) / 0.1)', borderColor: 'hsl(var(--border))' }}>
656
- <svg className="animate-spin w-4 h-4 mt-0.5" style={{ color: 'hsl(var(--primary))' }} fill="none" viewBox="0 0 24 24">
657
- <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
658
- <path
659
- className="opacity-75"
660
- fill="currentColor"
661
- d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
662
- />
663
- </svg>
664
- <span className="text-sm" style={{ color: 'hsl(var(--foreground))' }}>Verifying code...</span>
665
- </div>
666
- ) : error ? (
667
- <div className="w-full flex items-start space-x-2 p-3 rounded bg-red-50 border border-red-200">
668
- <span className="text-red-700 text-sm font-medium">✗</span>
669
- <span className="text-red-700 text-sm">{error}</span>
670
- </div>
671
- ) : success ? (
672
- <div className="w-full flex items-start space-x-2 p-2.5 rounded bg-green-50 border border-green-200">
673
- <span className="text-green-700 text-xs font-medium">✓</span>
674
- <span className="text-green-700 text-xs">Verification successful! Redirecting...</span>
675
- </div>
676
- ) : null}
677
- </div>
678
-
679
- {/* Resend button */}
680
- {methodLocked && (
681
- <button
682
- type="button"
683
- onClick={() => handleSendCode(method)}
684
- disabled={sending || (method === 'email' ? emailCooldown > 0 : smsCooldown > 0)}
685
- className="w-full text-sm hover:underline font-medium disabled:no-underline disabled:cursor-not-allowed disabled:opacity-50"
686
- style={{ color: 'hsl(var(--primary))' }}
687
- >
688
- {sending
689
- ? 'Sending...'
690
- : method === 'email'
691
- ? emailCooldown > 0
692
- ? `Resend code in ${emailCooldown}s`
693
- : 'Resend code'
694
- : smsCooldown > 0
695
- ? `Resend code in ${smsCooldown}s`
696
- : 'Resend code'}
697
- </button>
698
- )}
699
- </div>
700
- )}
701
- </div>
702
-
703
- {/* Back to login */}
704
- <p className="mt-4 text-center text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>
705
- <a href="/account-auth/login" className="hover:underline font-medium" style={{ color: 'hsl(var(--primary))' }}>
706
- Back to login
707
- </a>
708
- </p>
709
- </div>
710
- </div>
711
- );
712
- }
713
-
714
- function VerifyCodePageFallback() {
715
- const colors = useColors();
716
- return (
717
- <div className="flex items-center justify-center py-8" style={{ background: 'hsl(var(--background))' }}>
718
- <div className="text-center">
719
- <svg className="animate-spin h-10 w-10 mx-auto" style={{ color: 'hsl(var(--primary))' }} xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
720
- <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
721
- <path
722
- className="opacity-75"
723
- fill="currentColor"
724
- d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
725
- />
726
- </svg>
727
- <p className="mt-4" style={{ color: 'hsl(var(--muted-foreground))' }}>Loading...</p>
728
- </div>
729
- </div>
730
- );
731
- }
732
-
733
- /**
734
- * @param enrollHref where a user with NO usable 2FA method is sent to enrol.
735
- * Defaults to `/account/security`, which is where the enrolment surface
736
- * lives in the admin graft. It is a PROP rather than a constant because the
737
- * mount path is the consumer's choice — the package must not assume another
738
- * app's routing table.
739
- */
740
- export default function VerifyCodePage({ enrollHref = '/account/security' }: { enrollHref?: string } = {}) {
741
- return (
742
- <Suspense fallback={<VerifyCodePageFallback />}>
743
- <VerifyCodeForm enrollHref={enrollHref} />
744
- </Suspense>
745
- );
746
- }
1
+ /**
2
+ * Themed 2FA Verification Page for @payez/next-mvp
3
+ *
4
+ * PLAIN STYLING, FULL FUNCTIONALITY
5
+ * - Clean, professional appearance
6
+ * - All functional patterns from website-membership
7
+ * - Themeable via ThemeProvider
8
+ *
9
+ * DEPENDENCIES: Only React, Next.js, next-auth, and Tailwind CSS
10
+ * NO shadcn/ui or other UI library required!
11
+ *
12
+ * FEATURES:
13
+ * ✅ Progressive disclosure: method selection → code input
14
+ * ✅ Method locking after selection (prevents accidental multi-send)
15
+ * ✅ Masked contact info display (informational only)
16
+ * ✅ Auto-submit when code reaches 6 digits
17
+ * ✅ Cooldown timers (30s) on resend buttons
18
+ * ✅ Stale session detection (401 → redirect to login)
19
+ * ✅ JWT-specific error detection and messaging
20
+ * ✅ Session viability polling (every 30s) to detect expiration early
21
+ * ✅ Duplicate submission prevention
22
+ * ✅ Success/error states with atomic management
23
+ * ✅ "Change method" action
24
+ * ✅ Session cleanup on success/expiry
25
+ *
26
+ * USAGE:
27
+ * 1. Import from @payez/next-mvp/pages/verify-code
28
+ * 2. Wrap your app with ThemeProvider to customize branding
29
+ */
30
+
31
+ 'use client';
32
+
33
+ import React, { useState, useEffect, useRef } from 'react';
34
+ import { useRouter, useSearchParams } from 'next/navigation';
35
+ import { authClient } from '../../client/better-auth-client';
36
+ import { Suspense } from 'react';
37
+ import { useColors } from '../../theme/useTheme';
38
+ import { safeCallbackPath } from '../../auth/safe-callback';
39
+
40
+ /**
41
+ * Session storage key to track that user intentionally navigated to verify-code.
42
+ * Prevents auto-redirect back to dashboard when session refreshes in background.
43
+ */
44
+ const VERIFY_IN_PROGRESS_KEY = 'idealvibe_2fa_verify_in_progress';
45
+
46
+ // Masked info structure from IDP
47
+ interface MaskedInfo {
48
+ masked_email?: string;
49
+ masked_phone_number?: string;
50
+ has_authenticator?: boolean;
51
+ }
52
+
53
+ function VerifyCodeForm({ enrollHref }: { enrollHref: string }) {
54
+ const router = useRouter();
55
+ const searchParams = useSearchParams();
56
+ /**
57
+ * 375936 - ORIGIN-GUARDED AT THE READ, NOT AT THE SINK.
58
+ *
59
+ * This value ends up in `window.location.href` after a SUCCESSFUL 2FA
60
+ * ceremony (see the setTimeout further down). That is a full navigation, so
61
+ * an absolute URL here is a cross-origin redirect - the user completes a
62
+ * genuine login and is then dropped on an attacker-controlled page at the
63
+ * exact moment they are most primed to trust what they see.
64
+ *
65
+ * This used to be a raw `searchParams?.get('callbackUrl') || '/dashboard'`.
66
+ * The middleware does NOT protect this page: create-middleware's
67
+ * `needsTwoFactorRedirect` returns false for VERIFY_CODE_PAGE, so a direct
68
+ * request arrives here with its query string untouched.
69
+ *
70
+ * Do NOT "simplify" this back to a `startsWith('/account-auth/')` test. The
71
+ * three such tests below are LOOP prevention, not ORIGIN prevention -
72
+ * `https://evil.example` passes every one of them. safeCallbackPath asks the
73
+ * URL parser instead, so protocol-relative (`//host`), backslash (`/\host`)
74
+ * and TAB/LF/CR spellings all fail one origin comparison rather than needing
75
+ * their own blacklist entry.
76
+ *
77
+ * Guarding at the READ rather than at the sink means every later use of
78
+ * `callbackUrl` on this page inherits the guarantee.
79
+ */
80
+ const callbackUrl = safeCallbackPath(searchParams?.get('callbackUrl'), '/dashboard');
81
+
82
+ const { data: sessionData, isPending } = authClient.useSession();
83
+ const session = sessionData;
84
+ const status = isPending ? 'loading' : session ? 'authenticated' : 'unauthenticated';
85
+ // TODO: Better Auth session refresh
86
+ const updateSession = async () => { return session; };
87
+ const colors = useColors();
88
+
89
+ // Method selection
90
+ type Method = 'email' | 'sms' | null;
91
+ const [method, setMethod] = useState<Method>(null);
92
+ const [methodLocked, setMethodLocked] = useState(false);
93
+
94
+ // Form state
95
+ const [code, setCode] = useState('');
96
+ const [maskedInfo, setMaskedInfo] = useState<MaskedInfo | null>(null);
97
+ const [loadingMasked, setLoadingMasked] = useState(true);
98
+
99
+ // Atomic state - only one active at a time
100
+ const [sending, setSending] = useState(false);
101
+ const [verifying, setVerifying] = useState(false);
102
+ const [success, setSuccess] = useState(false);
103
+ const [error, setError] = useState<string | null>(null);
104
+
105
+ // Cooldown timers
106
+ const [emailCooldown, setEmailCooldown] = useState(0);
107
+ const [smsCooldown, setSmsCooldown] = useState(0);
108
+
109
+ // Toast notifications
110
+ const [toast, setToast] = useState<{ type: 'success' | 'error'; message: string } | null>(null);
111
+
112
+ // Refs
113
+ const codeInputRef = useRef<HTMLInputElement>(null);
114
+ const lastSubmittedCode = useRef<string>('');
115
+
116
+ // Track that user is intentionally on this page
117
+ const [verifyInProgress, setVerifyInProgress] = useState(false);
118
+
119
+ // ==========================================================================
120
+ // CRITICAL FIX: Mark that user is intentionally on verify page
121
+ // This prevents auto-redirect when background token refresh updates session
122
+ // ==========================================================================
123
+ useEffect(() => {
124
+ // On mount, mark that verification is in progress
125
+ if (typeof window !== 'undefined') {
126
+ const wasInProgress = sessionStorage.getItem(VERIFY_IN_PROGRESS_KEY) === 'true';
127
+ if (!wasInProgress) {
128
+ console.log('[2FA] User navigated to verify-code page, marking verify in progress');
129
+ sessionStorage.setItem(VERIFY_IN_PROGRESS_KEY, 'true');
130
+ }
131
+ setVerifyInProgress(true);
132
+ }
133
+ }, []);
134
+
135
+ // Auto-dismiss toast
136
+ useEffect(() => {
137
+ if (toast) {
138
+ const timer = setTimeout(() => setToast(null), 2500);
139
+ return () => clearTimeout(timer);
140
+ }
141
+ }, [toast]);
142
+
143
+ // Cooldown countdown
144
+ useEffect(() => {
145
+ if (emailCooldown > 0) {
146
+ const timer = setTimeout(() => setEmailCooldown(emailCooldown - 1), 1000);
147
+ return () => clearTimeout(timer);
148
+ }
149
+ }, [emailCooldown]);
150
+
151
+ useEffect(() => {
152
+ if (smsCooldown > 0) {
153
+ const timer = setTimeout(() => setSmsCooldown(smsCooldown - 1), 1000);
154
+ return () => clearTimeout(timer);
155
+ }
156
+ }, [smsCooldown]);
157
+
158
+ // Fetch masked info on mount
159
+ useEffect(() => {
160
+ const fetchMaskedInfo = async () => {
161
+ // BUGFIX: Always set loadingMasked=false, even if not authenticated
162
+ // Otherwise page stays stuck in loading spinner
163
+ if (status !== 'authenticated' || !session) {
164
+ setLoadingMasked(false);
165
+ return;
166
+ }
167
+
168
+ try {
169
+ const res = await fetch('/api/account/masked-info', {
170
+ method: 'POST',
171
+ credentials: 'include',
172
+ });
173
+
174
+ if (res.status === 401) {
175
+ // Session expired - redirect to login
176
+ setError('Your session has expired. Redirecting to login...');
177
+ setTimeout(async () => {
178
+ await authClient.signOut();
179
+ const safeCallback = callbackUrl.startsWith('/account-auth/') ? '/dashboard' : callbackUrl;
180
+ router.push(`/account-auth/login?callbackUrl=${encodeURIComponent(safeCallback)}`);
181
+ }, 1200);
182
+ return;
183
+ }
184
+
185
+ if (!res.ok) {
186
+ throw new Error('Failed to load contact information');
187
+ }
188
+
189
+ const data = await res.json();
190
+ setMaskedInfo(data);
191
+ } catch (err) {
192
+ console.error('[2FA] Error fetching masked info:', err);
193
+ setError('Could not load your contact information. Please try again.');
194
+ } finally {
195
+ setLoadingMasked(false);
196
+ }
197
+ };
198
+
199
+ fetchMaskedInfo();
200
+ }, [status, session, callbackUrl, router]);
201
+
202
+ // Auto-submit when code is 6 digits
203
+ useEffect(() => {
204
+ if (code.length === 6 && method && !verifying) {
205
+ handleVerifyCode();
206
+ }
207
+ }, [code, method, verifying]);
208
+
209
+ // ==========================================================================
210
+ // Session viability check - detect expiration early and warn user
211
+ // ==========================================================================
212
+ useEffect(() => {
213
+ if (status !== 'authenticated') return;
214
+
215
+ // Check session viability every 30 seconds
216
+ const checkSession = async () => {
217
+ try {
218
+ const res = await fetch('/api/session/viability', {
219
+ credentials: 'include',
220
+ });
221
+
222
+ // ====================================================================
223
+ // THE ENROLMENT DEAD END (cards 170045 / 170047, was 141688 / 141741)
224
+ // ====================================================================
225
+ // A first-time social user arrives here with ZERO usable methods and is
226
+ // asked for a code from an authenticator that does not exist. There was
227
+ // no way out: not a missing feature, AN UNASKED QUESTION.
228
+ //
229
+ // The IDP already decides this and says so. The package already relays
230
+ // it — from BOTH viability exports, deliberately, so an app mounting
231
+ // either is not left blind. The graft already mounts the route. THIS
232
+ // PAGE ALREADY CALLS IT, four lines above. It simply never read the
233
+ // answer: the only branch was `res.status === 401`, so on a perfectly
234
+ // valid session the response was fetched and thrown away.
235
+ //
236
+ // 'enroll_mfa' no USABLE method — the user CANNOT complete a
237
+ // challenge, so keeping them on a code prompt is a trap
238
+ // 'mfa_verify' a usable method exists — the prompt is correct
239
+ // null nothing due
240
+ //
241
+ // Every link in that chain was built against these very cards. The
242
+ // last consumer just never asked.
243
+ if (res.ok) {
244
+ const data = await res.json().catch(() => ({}));
245
+ if (data?.nextStep === 'enroll_mfa') {
246
+ router.replace(enrollHref);
247
+ return;
248
+ }
249
+ }
250
+
251
+ if (res.status === 401) {
252
+ const data = await res.json().catch(() => ({}));
253
+
254
+ // Session is no longer valid - warn user and redirect
255
+ if (data.valid === false || data.mfaExpired === true) {
256
+ setError('Your session has expired. Redirecting to login...');
257
+ setTimeout(async () => {
258
+ await authClient.signOut();
259
+ if (typeof window !== 'undefined') {
260
+ sessionStorage.removeItem(VERIFY_IN_PROGRESS_KEY);
261
+ }
262
+ router.push(`/account-auth/login?error=SessionExpired`);
263
+ }, 2000);
264
+ }
265
+ }
266
+ } catch (err) {
267
+ // Silent fail - let the next actual API call handle the error
268
+ console.log('[2FA] Session viability check failed:', err);
269
+ }
270
+ };
271
+
272
+ // Initial check after 5 seconds, then every 30 seconds
273
+ const initialTimeout = setTimeout(checkSession, 5000);
274
+ const interval = setInterval(checkSession, 30000);
275
+
276
+ return () => {
277
+ clearTimeout(initialTimeout);
278
+ clearInterval(interval);
279
+ };
280
+ }, [status, router, enrollHref]);
281
+
282
+ // ==========================================================================
283
+ // Enrolment dead-end check — IMMEDIATE, and deliberately separate
284
+ // ==========================================================================
285
+ // The poller above first fires after 5 SECONDS. For expiry that is fine. For
286
+ // a user who can never complete this challenge it is five seconds of staring
287
+ // at an unanswerable prompt, which is the whole complaint in card 170045.
288
+ //
289
+ // This runs at once — but it is a SEPARATE effect rather than removing the
290
+ // 5s delay, because that delay guards the 401 path against racing session
291
+ // establishment immediately after sign-in. Firing the expiry logic instantly
292
+ // could sign a user out for having a session that is merely still settling.
293
+ // So: this reads ONLY the 200 body and ONLY routes on 'enroll_mfa'. It never
294
+ // signs anyone out, so it is safe to run with no delay.
295
+ useEffect(() => {
296
+ if (status !== 'authenticated') return;
297
+ let cancelled = false;
298
+ (async () => {
299
+ try {
300
+ const res = await fetch('/api/session/viability', { credentials: 'include' });
301
+ if (!res.ok || cancelled) return;
302
+ const data = await res.json().catch(() => ({}));
303
+ if (data?.nextStep === 'enroll_mfa') router.replace(enrollHref);
304
+ } catch {
305
+ // Silent: the poller and the next real API call both still cover this.
306
+ // A failed check must leave the user on the prompt, never redirect them.
307
+ }
308
+ })();
309
+ return () => { cancelled = true; };
310
+ }, [status, router, enrollHref]);
311
+
312
+ const handleSendCode = async (selectedMethod: 'email' | 'sms') => {
313
+ setSending(true);
314
+ setError(null);
315
+
316
+ try {
317
+ const res = await fetch('/api/account/send-code', {
318
+ method: 'POST',
319
+ headers: { 'Content-Type': 'application/json' },
320
+ body: JSON.stringify({ method: selectedMethod }),
321
+ credentials: 'include',
322
+ });
323
+
324
+ if (res.status === 401) {
325
+ const errorData = await res.json().catch(() => ({}));
326
+ const isJwtExpired = errorData?.error?.includes('JWT') || errorData?.message?.includes('JWT') || errorData?.error?.includes('expired');
327
+
328
+ setError(isJwtExpired
329
+ ? 'Your 2FA session has expired. Please sign in again.'
330
+ : 'Your session has expired. Redirecting to login...'
331
+ );
332
+
333
+ setTimeout(async () => {
334
+ await authClient.signOut();
335
+ if (typeof window !== 'undefined') {
336
+ sessionStorage.removeItem(VERIFY_IN_PROGRESS_KEY);
337
+ }
338
+ const safeCallback = callbackUrl.startsWith('/account-auth/') ? '/dashboard' : callbackUrl;
339
+ // PAY-884: an expired JWT here is the provisional pre-2FA token - say so on the login page.
340
+ const errorParam = isJwtExpired ? '&error=TwoFactorTimeout' : '';
341
+ router.push(`/account-auth/login?callbackUrl=${encodeURIComponent(safeCallback)}${errorParam}`);
342
+ }, 1500);
343
+ return;
344
+ }
345
+
346
+ if (!res.ok) {
347
+ const data = await res.json();
348
+ throw new Error(data.message || data.error || 'Failed to send code');
349
+ }
350
+
351
+ // Lock method and set cooldown
352
+ setMethod(selectedMethod);
353
+ setMethodLocked(true);
354
+
355
+ if (selectedMethod === 'email') {
356
+ setEmailCooldown(30);
357
+ } else {
358
+ setSmsCooldown(30);
359
+ }
360
+
361
+ setToast({
362
+ type: 'success',
363
+ message: `Verification code sent to your ${selectedMethod === 'email' ? 'email' : 'phone'}`,
364
+ });
365
+
366
+ // Focus code input
367
+ setTimeout(() => codeInputRef.current?.focus(), 100);
368
+ } catch (err) {
369
+ setError(err instanceof Error ? err.message : 'Failed to send verification code');
370
+ } finally {
371
+ setSending(false);
372
+ }
373
+ };
374
+
375
+ const handleVerifyCode = async () => {
376
+ if (!code || !method || code.length !== 6) {
377
+ return;
378
+ }
379
+
380
+ // Prevent duplicate submissions
381
+ if (lastSubmittedCode.current === code) {
382
+ console.log('[2FA] Duplicate submission prevented');
383
+ return;
384
+ }
385
+ lastSubmittedCode.current = code;
386
+
387
+ setVerifying(true);
388
+ setError(null);
389
+
390
+ try {
391
+ const endpoint = method === 'sms' ? '/api/account/verify-sms' : '/api/account/verify-email';
392
+
393
+ const res = await fetch(endpoint, {
394
+ method: 'POST',
395
+ headers: { 'Content-Type': 'application/json' },
396
+ body: JSON.stringify({ verificationCode: code }),
397
+ credentials: 'include',
398
+ });
399
+
400
+ if (res.status === 401) {
401
+ const errorData = await res.json().catch(() => ({}));
402
+ const isJwtExpired = errorData?.error?.includes('JWT') || errorData?.message?.includes('JWT') || errorData?.error?.includes('expired');
403
+
404
+ setError(isJwtExpired
405
+ ? 'Your 2FA session has expired. Please sign in again.'
406
+ : 'Your session has expired. Redirecting to login...'
407
+ );
408
+
409
+ setTimeout(async () => {
410
+ await authClient.signOut();
411
+ if (typeof window !== 'undefined') {
412
+ sessionStorage.removeItem(VERIFY_IN_PROGRESS_KEY);
413
+ }
414
+ const safeCallback = callbackUrl.startsWith('/account-auth/') ? '/dashboard' : callbackUrl;
415
+ // PAY-884: an expired JWT here is the provisional pre-2FA token - say so on the login page.
416
+ const errorParam = isJwtExpired ? '&error=TwoFactorTimeout' : '';
417
+ router.push(`/account-auth/login?callbackUrl=${encodeURIComponent(safeCallback)}${errorParam}`);
418
+ }, 1500);
419
+ return;
420
+ }
421
+
422
+ if (!res.ok) {
423
+ const data = await res.json();
424
+ throw new Error(data.error || data.message || 'Verification failed');
425
+ }
426
+
427
+ const result = await res.json();
428
+
429
+ // Normalize response: support both enveloped and unwrapped payloads
430
+ const payload = (result && typeof result === 'object' && 'data' in result)
431
+ ? (result as any).data
432
+ : result;
433
+
434
+ // Check if verification was successful
435
+ const verified =
436
+ payload?.verificationSuccessful === true ||
437
+ payload?.twoFactorSessionVerified === true ||
438
+ payload?.success === true ||
439
+ // Accept token-based success (unwrapped raw tokens from backend)
440
+ (!!payload?.access_token && !!payload?.refresh_token);
441
+
442
+ if (!verified) {
443
+ throw new Error('Verification failed. Please try again.');
444
+ }
445
+
446
+ // CRITICAL: If tokens are included (unwrapped response), persist them in server session
447
+ if (payload?.access_token && payload?.refresh_token) {
448
+ try {
449
+ console.log('[2FA] Updating session with new MFA tokens...');
450
+ const updateRes = await fetch('/api/auth/update-session', {
451
+ method: 'POST',
452
+ headers: { 'Content-Type': 'application/json' },
453
+ credentials: 'include',
454
+ body: JSON.stringify({
455
+ access_token: payload.access_token,
456
+ refresh_token: payload.refresh_token
457
+ })
458
+ });
459
+
460
+ if (!updateRes.ok) {
461
+ console.warn('[2FA] update-session returned non-OK status:', updateRes.status);
462
+ const errorData = await updateRes.json();
463
+ // PAY-1427: the request carried access_token/refresh_token; log the error envelope's shape, never its contents.
464
+ console.warn('[2FA] update-session error:', { keys: errorData && typeof errorData === 'object' ? Object.keys(errorData) : typeof errorData, code: errorData?.error?.code ?? errorData?.code });
465
+ } else {
466
+ console.log('[2FA] Session updated successfully with MFA tokens');
467
+ }
468
+ } catch (e) {
469
+ console.warn('[2FA] Failed to call update-session:', e);
470
+ }
471
+ }
472
+
473
+ // Show success state
474
+ setSuccess(true);
475
+ setError(null);
476
+
477
+ // CRITICAL: Force NextAuth to refetch session from server
478
+ // This ensures useSession() gets the updated twoFactorComplete: true
479
+ console.log('[2FA] Forcing session refresh after verification...');
480
+ try {
481
+ await updateSession(); // This triggers /api/auth/session and updates useSession() state
482
+ console.log('[2FA] Session refresh completed');
483
+ } catch (e) {
484
+ console.warn('[2FA] updateSession failed:', e);
485
+ }
486
+
487
+ // Clear verify-in-progress flag before redirect
488
+ if (typeof window !== 'undefined') {
489
+ sessionStorage.removeItem(VERIFY_IN_PROGRESS_KEY);
490
+ }
491
+
492
+ // Redirect after showing success state
493
+ setTimeout(() => {
494
+ window.location.href = callbackUrl;
495
+ }, 1500);
496
+ } catch (err) {
497
+ setError(err instanceof Error ? err.message : 'Failed to verify code');
498
+ lastSubmittedCode.current = ''; // Allow retry
499
+ } finally {
500
+ setVerifying(false);
501
+ }
502
+ };
503
+
504
+ const handleResetMethod = () => {
505
+ setMethod(null);
506
+ setMethodLocked(false);
507
+ setCode('');
508
+ setError(null);
509
+ setEmailCooldown(0);
510
+ setSmsCooldown(0);
511
+ lastSubmittedCode.current = '';
512
+ };
513
+
514
+ const handleCodeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
515
+ const value = e.target.value.replace(/[^0-9]/g, '').slice(0, 6);
516
+ setCode(value);
517
+ };
518
+
519
+ // Loading state
520
+ if (status === 'loading' || loadingMasked) {
521
+ return (
522
+ <div className="flex flex-col items-center justify-center py-8" style={{ background: 'hsl(var(--background))' }}>
523
+ <svg className="animate-spin h-10 w-10" style={{ color: 'hsl(var(--primary))' }} viewBox="0 0 24 24" fill="none">
524
+ <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
525
+ <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z" />
526
+ </svg>
527
+ <p className="mt-4 text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>Loading...</p>
528
+ </div>
529
+ );
530
+ }
531
+
532
+ return (
533
+ <div className="flex items-center justify-center px-4 py-8" style={{ background: 'hsl(var(--background))' }}>
534
+ <div className="max-w-md w-full">
535
+ {/* Toast Notification */}
536
+ {toast && (
537
+ <div
538
+ className={`fixed top-4 right-4 p-4 rounded border transition-all duration-300 ${
539
+ toast.type === 'success' ? 'bg-green-50 text-green-800 border-green-200' : 'bg-red-50 text-red-800 border-red-200'
540
+ }`}
541
+ >
542
+ {toast.message}
543
+ </div>
544
+ )}
545
+
546
+ {/* Card */}
547
+ <div className="rounded-2xl border p-8" style={{ background: 'hsl(var(--card))', borderColor: 'hsl(var(--border))' }}>
548
+ {/* Header */}
549
+ <div className="mb-6">
550
+ <h1 className="text-2xl font-semibold mb-2" style={{ color: 'hsl(var(--foreground))' }}>Verify Your Identity</h1>
551
+ <p className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>Choose how you'd like to receive your verification code</p>
552
+ </div>
553
+
554
+ {/* Masked Info Display */}
555
+ {maskedInfo && (
556
+ <div className="mb-6 p-3 rounded border text-sm" style={{ background: 'hsl(var(--muted) / 0.1)', borderColor: 'hsl(var(--border))', color: 'hsl(var(--foreground))' }}>
557
+ {maskedInfo.masked_email && (
558
+ <div className="mb-1">
559
+ Email: <span className="font-mono">{maskedInfo.masked_email}</span>
560
+ </div>
561
+ )}
562
+ {maskedInfo.masked_phone_number && (
563
+ <div>
564
+ Phone: <span className="font-mono">{maskedInfo.masked_phone_number}</span>
565
+ </div>
566
+ )}
567
+ </div>
568
+ )}
569
+
570
+ {/* Method Selection or Code Input */}
571
+ {!method ? (
572
+ /* Method Selection */
573
+ <div className="space-y-3">
574
+ <button
575
+ type="button"
576
+ onClick={() => handleSendCode('email')}
577
+ disabled={sending || !maskedInfo?.masked_email}
578
+ className="w-full flex items-center justify-between p-3 border rounded disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
579
+ style={{
580
+ background: 'hsl(var(--card))',
581
+ borderColor: 'hsl(var(--border))',
582
+ color: 'hsl(var(--foreground))'
583
+ }}
584
+ >
585
+ <div className="text-left">
586
+ <p className="font-medium" style={{ color: 'hsl(var(--foreground))' }}>Email</p>
587
+ <p className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>{maskedInfo?.masked_email || 'Not available'}</p>
588
+ </div>
589
+ <span style={{ color: 'hsl(var(--muted-foreground))' }}>→</span>
590
+ </button>
591
+
592
+ <button
593
+ type="button"
594
+ onClick={() => handleSendCode('sms')}
595
+ disabled={sending || !maskedInfo?.masked_phone_number}
596
+ className="w-full flex items-center justify-between p-3 border rounded disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
597
+ style={{
598
+ background: 'hsl(var(--card))',
599
+ borderColor: 'hsl(var(--border))',
600
+ color: 'hsl(var(--foreground))'
601
+ }}
602
+ >
603
+ <div className="text-left">
604
+ <p className="font-medium" style={{ color: 'hsl(var(--foreground))' }}>SMS</p>
605
+ <p className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>{maskedInfo?.masked_phone_number || 'Not available'}</p>
606
+ </div>
607
+ <span style={{ color: 'hsl(var(--muted-foreground))' }}>→</span>
608
+ </button>
609
+ </div>
610
+ ) : (
611
+ /* Code Input */
612
+ <div className="space-y-4">
613
+ {/* Method indicator */}
614
+ <div className="flex items-center justify-between p-3 rounded border" style={{ background: 'hsl(var(--muted) / 0.1)', borderColor: 'hsl(var(--border))' }}>
615
+ <span className="text-sm" style={{ color: 'hsl(var(--foreground))' }}>
616
+ Code sent to your {method === 'email' ? 'email' : 'phone'}
617
+ </span>
618
+ <button type="button" onClick={handleResetMethod} className="text-sm hover:underline font-medium" style={{ color: 'hsl(var(--primary))' }}>
619
+ Change method
620
+ </button>
621
+ </div>
622
+
623
+ {/* Code input */}
624
+ <div>
625
+ <label htmlFor="code" className="block text-sm font-medium mb-2" style={{ color: 'hsl(var(--foreground))' }}>
626
+ Verification Code
627
+ </label>
628
+ <input
629
+ ref={codeInputRef}
630
+ id="code"
631
+ type="text"
632
+ inputMode="numeric"
633
+ pattern="[0-9]*"
634
+ maxLength={6}
635
+ value={code}
636
+ onChange={handleCodeChange}
637
+ className="w-full px-4 py-3 text-center text-2xl font-mono border rounded focus:ring-2 tracking-widest"
638
+ style={{
639
+ background: 'hsl(var(--input))',
640
+ borderColor: 'hsl(var(--border))',
641
+ color: 'hsl(var(--foreground))',
642
+ caretColor: 'hsl(var(--foreground))'
643
+ }}
644
+ placeholder="000000"
645
+ disabled={verifying || success}
646
+ autoComplete="one-time-code"
647
+ autoFocus
648
+ />
649
+ <p className="mt-2 text-sm text-center" style={{ color: 'hsl(var(--muted-foreground))' }}>Enter the 6-digit code</p>
650
+ </div>
651
+
652
+ {/* Status Display - Pre-sized container to prevent layout shift */}
653
+ <div className="min-h-[3.5rem] flex items-center">
654
+ {verifying ? (
655
+ <div className="w-full flex items-start space-x-2 p-3 rounded border" style={{ background: 'hsl(var(--muted) / 0.1)', borderColor: 'hsl(var(--border))' }}>
656
+ <svg className="animate-spin w-4 h-4 mt-0.5" style={{ color: 'hsl(var(--primary))' }} fill="none" viewBox="0 0 24 24">
657
+ <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
658
+ <path
659
+ className="opacity-75"
660
+ fill="currentColor"
661
+ d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
662
+ />
663
+ </svg>
664
+ <span className="text-sm" style={{ color: 'hsl(var(--foreground))' }}>Verifying code...</span>
665
+ </div>
666
+ ) : error ? (
667
+ <div className="w-full flex items-start space-x-2 p-3 rounded bg-red-50 border border-red-200">
668
+ <span className="text-red-700 text-sm font-medium">✗</span>
669
+ <span className="text-red-700 text-sm">{error}</span>
670
+ </div>
671
+ ) : success ? (
672
+ <div className="w-full flex items-start space-x-2 p-2.5 rounded bg-green-50 border border-green-200">
673
+ <span className="text-green-700 text-xs font-medium">✓</span>
674
+ <span className="text-green-700 text-xs">Verification successful! Redirecting...</span>
675
+ </div>
676
+ ) : null}
677
+ </div>
678
+
679
+ {/* Resend button */}
680
+ {methodLocked && (
681
+ <button
682
+ type="button"
683
+ onClick={() => handleSendCode(method)}
684
+ disabled={sending || (method === 'email' ? emailCooldown > 0 : smsCooldown > 0)}
685
+ className="w-full text-sm hover:underline font-medium disabled:no-underline disabled:cursor-not-allowed disabled:opacity-50"
686
+ style={{ color: 'hsl(var(--primary))' }}
687
+ >
688
+ {sending
689
+ ? 'Sending...'
690
+ : method === 'email'
691
+ ? emailCooldown > 0
692
+ ? `Resend code in ${emailCooldown}s`
693
+ : 'Resend code'
694
+ : smsCooldown > 0
695
+ ? `Resend code in ${smsCooldown}s`
696
+ : 'Resend code'}
697
+ </button>
698
+ )}
699
+ </div>
700
+ )}
701
+ </div>
702
+
703
+ {/* Back to login */}
704
+ <p className="mt-4 text-center text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>
705
+ <a href="/account-auth/login" className="hover:underline font-medium" style={{ color: 'hsl(var(--primary))' }}>
706
+ Back to login
707
+ </a>
708
+ </p>
709
+ </div>
710
+ </div>
711
+ );
712
+ }
713
+
714
+ function VerifyCodePageFallback() {
715
+ const colors = useColors();
716
+ return (
717
+ <div className="flex items-center justify-center py-8" style={{ background: 'hsl(var(--background))' }}>
718
+ <div className="text-center">
719
+ <svg className="animate-spin h-10 w-10 mx-auto" style={{ color: 'hsl(var(--primary))' }} xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
720
+ <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
721
+ <path
722
+ className="opacity-75"
723
+ fill="currentColor"
724
+ d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
725
+ />
726
+ </svg>
727
+ <p className="mt-4" style={{ color: 'hsl(var(--muted-foreground))' }}>Loading...</p>
728
+ </div>
729
+ </div>
730
+ );
731
+ }
732
+
733
+ /**
734
+ * @param enrollHref where a user with NO usable 2FA method is sent to enrol.
735
+ * Defaults to `/account/security`, which is where the enrolment surface
736
+ * lives in the admin graft. It is a PROP rather than a constant because the
737
+ * mount path is the consumer's choice — the package must not assume another
738
+ * app's routing table.
739
+ */
740
+ export default function VerifyCodePage({ enrollHref = '/account/security' }: { enrollHref?: string } = {}) {
741
+ return (
742
+ <Suspense fallback={<VerifyCodePageFallback />}>
743
+ <VerifyCodeForm enrollHref={enrollHref} />
744
+ </Suspense>
745
+ );
746
+ }