@payez/next-mvp 4.1.7 → 4.1.9

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 (154) hide show
  1. package/README.md +792 -792
  2. package/dist/auth/better-auth.js +15 -3
  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/pages/login/page.js +28 -28
  8. package/dist/pages/settings/EnhancedSettingsPage.js +17 -17
  9. package/package.json +1 -1
  10. package/scripts/dev-broker.ps1 +35 -35
  11. package/scripts/dev-local.ps1 +45 -45
  12. package/src/api/auth-handler.ts +548 -548
  13. package/src/api-handlers/account/change-password.ts +142 -142
  14. package/src/api-handlers/account/update-phone.ts +79 -79
  15. package/src/api-handlers/account/verify-email.ts +125 -125
  16. package/src/api-handlers/account/verify-sms.ts +125 -125
  17. package/src/api-handlers/admin/analytics.ts +443 -443
  18. package/src/api-handlers/admin/audit.ts +223 -223
  19. package/src/api-handlers/admin/index.ts +63 -63
  20. package/src/api-handlers/admin/redis-sessions.ts +251 -251
  21. package/src/api-handlers/admin/sessions.ts +318 -318
  22. package/src/api-handlers/admin/site-logs.ts +365 -365
  23. package/src/api-handlers/admin/users.ts +242 -242
  24. package/src/api-handlers/admin/vibe-data.ts +324 -324
  25. package/src/api-handlers/auth/refresh.ts +682 -682
  26. package/src/api-handlers/auth/signout.ts +199 -199
  27. package/src/api-handlers/auth/status.ts +20 -20
  28. package/src/api-handlers/auth/update-session.ts +110 -110
  29. package/src/api-handlers/auth/verify-code.ts +112 -112
  30. package/src/api-handlers/session/refresh-viability.ts +36 -36
  31. package/src/api-handlers/test/force-expire.ts +60 -60
  32. package/src/auth/auth-decision.ts +229 -229
  33. package/src/auth/better-auth.ts +15 -3
  34. package/src/auth/route-config.ts +219 -219
  35. package/src/auth/types/auth-types.ts +555 -555
  36. package/src/auth/types/index.ts +7 -7
  37. package/src/auth/utils/idp-client.ts +445 -445
  38. package/src/auth/utils/index.ts +6 -6
  39. package/src/auth/utils/token-utils.ts +243 -243
  40. package/src/client/AuthContext.tsx +143 -143
  41. package/src/client/fetch-with-auth.ts +47 -47
  42. package/src/components/SessionSync.tsx +138 -138
  43. package/src/components/SignalRHealthCheck.tsx +131 -131
  44. package/src/components/account/MobileNavDrawer.tsx +305 -305
  45. package/src/components/account/UserAvatarMenu.tsx +266 -266
  46. package/src/components/account/index.ts +13 -13
  47. package/src/components/admin/AlertSettingsTab.tsx +728 -728
  48. package/src/components/admin/AnalyticsTab.tsx +703 -703
  49. package/src/components/admin/DataBrowserTab.tsx +505 -505
  50. package/src/components/admin/LoggingSettingsTab.tsx +665 -665
  51. package/src/components/admin/SessionsTab.tsx +414 -414
  52. package/src/components/admin/StatsTab.tsx +379 -379
  53. package/src/components/admin/VibeAdminLayout.tsx +187 -187
  54. package/src/components/admin/index.ts +59 -59
  55. package/src/components/auth/FederatedAuthSection.tsx +95 -95
  56. package/src/components/auth/ModeAwareLoginPage.tsx +135 -135
  57. package/src/components/auth/ModeAwareSignupPage.tsx +267 -267
  58. package/src/components/auth/TraditionalAuthSection.tsx +99 -99
  59. package/src/components/recovery/CompleteStep.tsx +36 -36
  60. package/src/components/recovery/InitiateRecoveryStep.tsx +68 -68
  61. package/src/components/recovery/SelectMethodStep.tsx +73 -73
  62. package/src/components/recovery/SetPasswordStep.tsx +97 -97
  63. package/src/components/recovery/VerifyCodeStep.tsx +90 -90
  64. package/src/components/reserved/ReservedRecoveryWarning.tsx +160 -160
  65. package/src/components/reserved/ReservedStatusBox.tsx +118 -118
  66. package/src/components/ui/BetaBadge.tsx +58 -58
  67. package/src/components/ui/Footer.tsx +93 -93
  68. package/src/config/env.ts +57 -57
  69. package/src/config/logger.ts +62 -62
  70. package/src/config/vibe-log-transport.ts +264 -264
  71. package/src/hooks/useAuth.ts +117 -117
  72. package/src/hooks/useAuthSettings.ts +97 -97
  73. package/src/hooks/useAvailableProviders.ts +120 -120
  74. package/src/hooks/usePasswordValidation.ts +127 -127
  75. package/src/hooks/usePublicAuthSettings.ts +149 -149
  76. package/src/hooks/useSessionExpiration.ts +101 -101
  77. package/src/hooks/useViabilitySession.ts +336 -336
  78. package/src/index.ts +60 -60
  79. package/src/lib/api-handler.ts +643 -643
  80. package/src/lib/app-slug.ts +178 -178
  81. package/src/lib/geolocation.ts +265 -265
  82. package/src/lib/idp-fetch.ts +110 -110
  83. package/src/lib/jwt-decode.ts +82 -82
  84. package/src/lib/roles.ts +177 -177
  85. package/src/lib/site-logger.ts +245 -245
  86. package/src/lib/standardized-client-api.ts +901 -901
  87. package/src/lib/test-aware-get-token.ts +41 -41
  88. package/src/lib/user-agent-parser.ts +252 -252
  89. package/src/logging/api/admin-analytics.ts +51 -51
  90. package/src/logging/api/audit-log.ts +53 -53
  91. package/src/logging/components/AdminAnalyticsLayout.tsx +49 -49
  92. package/src/logging/components/AuditLogViewer.tsx +125 -125
  93. package/src/logging/components/ErrorMetricsCard.tsx +98 -98
  94. package/src/logging/components/HealthMetricsCard.tsx +70 -70
  95. package/src/logging/hooks/useAdminAnalytics.ts +22 -22
  96. package/src/logging/hooks/useAuditLog.ts +24 -24
  97. package/src/logging/hooks/useErrorMetrics.ts +40 -40
  98. package/src/logging/hooks/useHealthMetrics.ts +44 -44
  99. package/src/logging/index.ts +18 -18
  100. package/src/logging/types/analytics.ts +81 -81
  101. package/src/logging/types/audit.ts +31 -31
  102. package/src/logging/types/index.ts +3 -3
  103. package/src/middleware/create-middleware.ts +663 -663
  104. package/src/middleware/rbac-check.ts +279 -279
  105. package/src/middleware/twofa-presets.ts +224 -224
  106. package/src/pages/admin-login/page.tsx +221 -221
  107. package/src/pages/admin-page-permissions/PagePermissionsAdminPage.tsx +527 -527
  108. package/src/pages/admin-page-permissions/index.ts +7 -7
  109. package/src/pages/admin-roles/RolesAdminPage.tsx +533 -533
  110. package/src/pages/admin-roles/modals.tsx +469 -469
  111. package/src/pages/client-admin/ClientSiteAdminPage.tsx +382 -382
  112. package/src/pages/client-admin/index.ts +33 -33
  113. package/src/pages/coming-soon/page.tsx +83 -83
  114. package/src/pages/login/page.tsx +456 -456
  115. package/src/pages/profile/EnhancedProfilePage.tsx +485 -485
  116. package/src/pages/profile/index.ts +9 -9
  117. package/src/pages/profile/page.tsx +166 -166
  118. package/src/pages/recovery/page.tsx +234 -234
  119. package/src/pages/roles/MyRolesPage.tsx +211 -211
  120. package/src/pages/roles/components.tsx +294 -294
  121. package/src/pages/roles/index.ts +17 -17
  122. package/src/pages/security/EnhancedSecurityPage.tsx +565 -565
  123. package/src/pages/security/index.ts +9 -9
  124. package/src/pages/security/page.tsx +507 -507
  125. package/src/pages/settings/EnhancedSettingsPage.tsx +642 -642
  126. package/src/pages/settings/index.ts +9 -9
  127. package/src/pages/settings/page.tsx +47 -47
  128. package/src/pages/showcase/ShowcasePage.tsx +532 -532
  129. package/src/pages/showcase/index.ts +13 -13
  130. package/src/pages/test-env/EmergencyLogoutPage.tsx +180 -180
  131. package/src/pages/test-env/JwtInspectPage.tsx +456 -456
  132. package/src/pages/test-env/RefreshTokenPage.tsx +157 -157
  133. package/src/pages/test-env/TestEnvPage.tsx +118 -118
  134. package/src/pages/test-env/index.ts +25 -25
  135. package/src/pages/verify-code/page.tsx +652 -652
  136. package/src/routes/account/update-phone.ts +13 -13
  137. package/src/routes/auth/logout.ts +108 -108
  138. package/src/routes/auth/nextauth.ts +45 -45
  139. package/src/routes/auth/settings.ts +75 -75
  140. package/src/routes/auth/viability.ts +224 -224
  141. package/src/server/auth-guard.ts +170 -170
  142. package/src/server/slim-middleware.ts +117 -117
  143. package/src/server/with-auth.ts +93 -93
  144. package/src/stores/authStore.ts +1899 -1899
  145. package/src/templates/instrumentation.ts +41 -41
  146. package/src/utils/logout.ts +30 -30
  147. package/src/vibe/client.ts +590 -590
  148. package/src/vibe/enterprise-auth.ts +208 -208
  149. package/src/vibe/errors.ts +185 -185
  150. package/src/vibe/generic.ts +431 -431
  151. package/src/vibe/hooks/index.ts +367 -367
  152. package/src/vibe/index.ts +132 -132
  153. package/src/vibe/sessions.ts +551 -551
  154. package/src/vibe/types.ts +577 -577
@@ -1,652 +1,652 @@
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
-
39
- /**
40
- * Session storage key to track that user intentionally navigated to verify-code.
41
- * Prevents auto-redirect back to dashboard when session refreshes in background.
42
- */
43
- const VERIFY_IN_PROGRESS_KEY = 'idealvibe_2fa_verify_in_progress';
44
-
45
- // Masked info structure from IDP
46
- interface MaskedInfo {
47
- masked_email?: string;
48
- masked_phone_number?: string;
49
- has_authenticator?: boolean;
50
- }
51
-
52
- function VerifyCodeForm() {
53
- const router = useRouter();
54
- const searchParams = useSearchParams();
55
- const callbackUrl = searchParams?.get('callbackUrl') || '/dashboard';
56
-
57
- const { data: sessionData, isPending } = authClient.useSession();
58
- const session = sessionData;
59
- const status = isPending ? 'loading' : session ? 'authenticated' : 'unauthenticated';
60
- // TODO: Better Auth session refresh
61
- const updateSession = async () => { return session; };
62
- const colors = useColors();
63
-
64
- // Method selection
65
- type Method = 'email' | 'sms' | null;
66
- const [method, setMethod] = useState<Method>(null);
67
- const [methodLocked, setMethodLocked] = useState(false);
68
-
69
- // Form state
70
- const [code, setCode] = useState('');
71
- const [maskedInfo, setMaskedInfo] = useState<MaskedInfo | null>(null);
72
- const [loadingMasked, setLoadingMasked] = useState(true);
73
-
74
- // Atomic state - only one active at a time
75
- const [sending, setSending] = useState(false);
76
- const [verifying, setVerifying] = useState(false);
77
- const [success, setSuccess] = useState(false);
78
- const [error, setError] = useState<string | null>(null);
79
-
80
- // Cooldown timers
81
- const [emailCooldown, setEmailCooldown] = useState(0);
82
- const [smsCooldown, setSmsCooldown] = useState(0);
83
-
84
- // Toast notifications
85
- const [toast, setToast] = useState<{ type: 'success' | 'error'; message: string } | null>(null);
86
-
87
- // Refs
88
- const codeInputRef = useRef<HTMLInputElement>(null);
89
- const lastSubmittedCode = useRef<string>('');
90
-
91
- // Track that user is intentionally on this page
92
- const [verifyInProgress, setVerifyInProgress] = useState(false);
93
-
94
- // ==========================================================================
95
- // CRITICAL FIX: Mark that user is intentionally on verify page
96
- // This prevents auto-redirect when background token refresh updates session
97
- // ==========================================================================
98
- useEffect(() => {
99
- // On mount, mark that verification is in progress
100
- if (typeof window !== 'undefined') {
101
- const wasInProgress = sessionStorage.getItem(VERIFY_IN_PROGRESS_KEY) === 'true';
102
- if (!wasInProgress) {
103
- console.log('[2FA] User navigated to verify-code page, marking verify in progress');
104
- sessionStorage.setItem(VERIFY_IN_PROGRESS_KEY, 'true');
105
- }
106
- setVerifyInProgress(true);
107
- }
108
- }, []);
109
-
110
- // Auto-dismiss toast
111
- useEffect(() => {
112
- if (toast) {
113
- const timer = setTimeout(() => setToast(null), 2500);
114
- return () => clearTimeout(timer);
115
- }
116
- }, [toast]);
117
-
118
- // Cooldown countdown
119
- useEffect(() => {
120
- if (emailCooldown > 0) {
121
- const timer = setTimeout(() => setEmailCooldown(emailCooldown - 1), 1000);
122
- return () => clearTimeout(timer);
123
- }
124
- }, [emailCooldown]);
125
-
126
- useEffect(() => {
127
- if (smsCooldown > 0) {
128
- const timer = setTimeout(() => setSmsCooldown(smsCooldown - 1), 1000);
129
- return () => clearTimeout(timer);
130
- }
131
- }, [smsCooldown]);
132
-
133
- // Fetch masked info on mount
134
- useEffect(() => {
135
- const fetchMaskedInfo = async () => {
136
- // BUGFIX: Always set loadingMasked=false, even if not authenticated
137
- // Otherwise page stays stuck in loading spinner
138
- if (status !== 'authenticated' || !session) {
139
- setLoadingMasked(false);
140
- return;
141
- }
142
-
143
- try {
144
- const res = await fetch('/api/account/masked-info', {
145
- method: 'POST',
146
- credentials: 'include',
147
- });
148
-
149
- if (res.status === 401) {
150
- // Session expired - redirect to login
151
- setError('Your session has expired. Redirecting to login...');
152
- setTimeout(async () => {
153
- await authClient.signOut();
154
- const safeCallback = callbackUrl.startsWith('/account-auth/') ? '/dashboard' : callbackUrl;
155
- router.push(`/account-auth/login?callbackUrl=${encodeURIComponent(safeCallback)}`);
156
- }, 1200);
157
- return;
158
- }
159
-
160
- if (!res.ok) {
161
- throw new Error('Failed to load contact information');
162
- }
163
-
164
- const data = await res.json();
165
- setMaskedInfo(data);
166
- } catch (err) {
167
- console.error('[2FA] Error fetching masked info:', err);
168
- setError('Could not load your contact information. Please try again.');
169
- } finally {
170
- setLoadingMasked(false);
171
- }
172
- };
173
-
174
- fetchMaskedInfo();
175
- }, [status, session, callbackUrl, router]);
176
-
177
- // Auto-submit when code is 6 digits
178
- useEffect(() => {
179
- if (code.length === 6 && method && !verifying) {
180
- handleVerifyCode();
181
- }
182
- }, [code, method, verifying]);
183
-
184
- // ==========================================================================
185
- // Session viability check - detect expiration early and warn user
186
- // ==========================================================================
187
- useEffect(() => {
188
- if (status !== 'authenticated') return;
189
-
190
- // Check session viability every 30 seconds
191
- const checkSession = async () => {
192
- try {
193
- const res = await fetch('/api/session/viability', {
194
- credentials: 'include',
195
- });
196
-
197
- if (res.status === 401) {
198
- const data = await res.json().catch(() => ({}));
199
-
200
- // Session is no longer valid - warn user and redirect
201
- if (data.valid === false || data.mfaExpired === true) {
202
- setError('Your session has expired. Redirecting to login...');
203
- setTimeout(async () => {
204
- await authClient.signOut();
205
- if (typeof window !== 'undefined') {
206
- sessionStorage.removeItem(VERIFY_IN_PROGRESS_KEY);
207
- }
208
- router.push(`/account-auth/login?error=SessionExpired`);
209
- }, 2000);
210
- }
211
- }
212
- } catch (err) {
213
- // Silent fail - let the next actual API call handle the error
214
- console.log('[2FA] Session viability check failed:', err);
215
- }
216
- };
217
-
218
- // Initial check after 5 seconds, then every 30 seconds
219
- const initialTimeout = setTimeout(checkSession, 5000);
220
- const interval = setInterval(checkSession, 30000);
221
-
222
- return () => {
223
- clearTimeout(initialTimeout);
224
- clearInterval(interval);
225
- };
226
- }, [status, router]);
227
-
228
- const handleSendCode = async (selectedMethod: 'email' | 'sms') => {
229
- setSending(true);
230
- setError(null);
231
-
232
- try {
233
- const res = await fetch('/api/account/send-code', {
234
- method: 'POST',
235
- headers: { 'Content-Type': 'application/json' },
236
- body: JSON.stringify({ method: selectedMethod }),
237
- credentials: 'include',
238
- });
239
-
240
- if (res.status === 401) {
241
- const errorData = await res.json().catch(() => ({}));
242
- const isJwtExpired = errorData?.error?.includes('JWT') || errorData?.message?.includes('JWT') || errorData?.error?.includes('expired');
243
-
244
- setError(isJwtExpired
245
- ? 'Your 2FA session has expired. Please sign in again.'
246
- : 'Your session has expired. Redirecting to login...'
247
- );
248
-
249
- setTimeout(async () => {
250
- await authClient.signOut();
251
- if (typeof window !== 'undefined') {
252
- sessionStorage.removeItem(VERIFY_IN_PROGRESS_KEY);
253
- }
254
- const safeCallback = callbackUrl.startsWith('/account-auth/') ? '/dashboard' : callbackUrl;
255
- const errorParam = isJwtExpired ? '&error=SessionExpired' : '';
256
- router.push(`/account-auth/login?callbackUrl=${encodeURIComponent(safeCallback)}${errorParam}`);
257
- }, 1500);
258
- return;
259
- }
260
-
261
- if (!res.ok) {
262
- const data = await res.json();
263
- throw new Error(data.message || data.error || 'Failed to send code');
264
- }
265
-
266
- // Lock method and set cooldown
267
- setMethod(selectedMethod);
268
- setMethodLocked(true);
269
-
270
- if (selectedMethod === 'email') {
271
- setEmailCooldown(30);
272
- } else {
273
- setSmsCooldown(30);
274
- }
275
-
276
- setToast({
277
- type: 'success',
278
- message: `Verification code sent to your ${selectedMethod === 'email' ? 'email' : 'phone'}`,
279
- });
280
-
281
- // Focus code input
282
- setTimeout(() => codeInputRef.current?.focus(), 100);
283
- } catch (err) {
284
- setError(err instanceof Error ? err.message : 'Failed to send verification code');
285
- } finally {
286
- setSending(false);
287
- }
288
- };
289
-
290
- const handleVerifyCode = async () => {
291
- if (!code || !method || code.length !== 6) {
292
- return;
293
- }
294
-
295
- // Prevent duplicate submissions
296
- if (lastSubmittedCode.current === code) {
297
- console.log('[2FA] Duplicate submission prevented');
298
- return;
299
- }
300
- lastSubmittedCode.current = code;
301
-
302
- setVerifying(true);
303
- setError(null);
304
-
305
- try {
306
- const endpoint = method === 'sms' ? '/api/account/verify-sms' : '/api/account/verify-email';
307
-
308
- const res = await fetch(endpoint, {
309
- method: 'POST',
310
- headers: { 'Content-Type': 'application/json' },
311
- body: JSON.stringify({ verificationCode: code }),
312
- credentials: 'include',
313
- });
314
-
315
- if (res.status === 401) {
316
- const errorData = await res.json().catch(() => ({}));
317
- const isJwtExpired = errorData?.error?.includes('JWT') || errorData?.message?.includes('JWT') || errorData?.error?.includes('expired');
318
-
319
- setError(isJwtExpired
320
- ? 'Your 2FA session has expired. Please sign in again.'
321
- : 'Your session has expired. Redirecting to login...'
322
- );
323
-
324
- setTimeout(async () => {
325
- await authClient.signOut();
326
- if (typeof window !== 'undefined') {
327
- sessionStorage.removeItem(VERIFY_IN_PROGRESS_KEY);
328
- }
329
- const safeCallback = callbackUrl.startsWith('/account-auth/') ? '/dashboard' : callbackUrl;
330
- const errorParam = isJwtExpired ? '&error=SessionExpired' : '';
331
- router.push(`/account-auth/login?callbackUrl=${encodeURIComponent(safeCallback)}${errorParam}`);
332
- }, 1500);
333
- return;
334
- }
335
-
336
- if (!res.ok) {
337
- const data = await res.json();
338
- throw new Error(data.error || data.message || 'Verification failed');
339
- }
340
-
341
- const result = await res.json();
342
-
343
- // Normalize response: support both enveloped and unwrapped payloads
344
- const payload = (result && typeof result === 'object' && 'data' in result)
345
- ? (result as any).data
346
- : result;
347
-
348
- // Check if verification was successful
349
- const verified =
350
- payload?.verificationSuccessful === true ||
351
- payload?.twoFactorSessionVerified === true ||
352
- payload?.success === true ||
353
- // Accept token-based success (unwrapped raw tokens from backend)
354
- (!!payload?.access_token && !!payload?.refresh_token);
355
-
356
- if (!verified) {
357
- throw new Error('Verification failed. Please try again.');
358
- }
359
-
360
- // CRITICAL: If tokens are included (unwrapped response), persist them in server session
361
- if (payload?.access_token && payload?.refresh_token) {
362
- try {
363
- console.log('[2FA] Updating session with new MFA tokens...');
364
- const updateRes = await fetch('/api/auth/update-session', {
365
- method: 'POST',
366
- headers: { 'Content-Type': 'application/json' },
367
- credentials: 'include',
368
- body: JSON.stringify({
369
- access_token: payload.access_token,
370
- refresh_token: payload.refresh_token
371
- })
372
- });
373
-
374
- if (!updateRes.ok) {
375
- console.warn('[2FA] update-session returned non-OK status:', updateRes.status);
376
- const errorData = await updateRes.json();
377
- console.warn('[2FA] update-session error:', errorData);
378
- } else {
379
- console.log('[2FA] Session updated successfully with MFA tokens');
380
- }
381
- } catch (e) {
382
- console.warn('[2FA] Failed to call update-session:', e);
383
- }
384
- }
385
-
386
- // Show success state
387
- setSuccess(true);
388
- setError(null);
389
-
390
- // CRITICAL: Force NextAuth to refetch session from server
391
- // This ensures useSession() gets the updated twoFactorComplete: true
392
- console.log('[2FA] Forcing session refresh after verification...');
393
- try {
394
- await updateSession(); // This triggers /api/auth/session and updates useSession() state
395
- console.log('[2FA] Session refresh completed');
396
- } catch (e) {
397
- console.warn('[2FA] updateSession failed:', e);
398
- }
399
-
400
- // Clear verify-in-progress flag before redirect
401
- if (typeof window !== 'undefined') {
402
- sessionStorage.removeItem(VERIFY_IN_PROGRESS_KEY);
403
- }
404
-
405
- // Redirect after showing success state
406
- setTimeout(() => {
407
- window.location.href = callbackUrl;
408
- }, 1500);
409
- } catch (err) {
410
- setError(err instanceof Error ? err.message : 'Failed to verify code');
411
- lastSubmittedCode.current = ''; // Allow retry
412
- } finally {
413
- setVerifying(false);
414
- }
415
- };
416
-
417
- const handleResetMethod = () => {
418
- setMethod(null);
419
- setMethodLocked(false);
420
- setCode('');
421
- setError(null);
422
- setEmailCooldown(0);
423
- setSmsCooldown(0);
424
- lastSubmittedCode.current = '';
425
- };
426
-
427
- const handleCodeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
428
- const value = e.target.value.replace(/[^0-9]/g, '').slice(0, 6);
429
- setCode(value);
430
- };
431
-
432
- // Loading state
433
- if (status === 'loading' || loadingMasked) {
434
- return (
435
- <div className="flex flex-col items-center justify-center py-8" style={{ background: 'hsl(var(--background))' }}>
436
- <svg className="animate-spin h-10 w-10" style={{ color: 'hsl(var(--primary))' }} viewBox="0 0 24 24" fill="none">
437
- <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
438
- <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z" />
439
- </svg>
440
- <p className="mt-4 text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>Loading...</p>
441
- </div>
442
- );
443
- }
444
-
445
- return (
446
- <div className="flex items-center justify-center px-4 py-8" style={{ background: 'hsl(var(--background))' }}>
447
- <div className="max-w-md w-full">
448
- {/* Toast Notification */}
449
- {toast && (
450
- <div
451
- className={`fixed top-4 right-4 p-4 rounded border transition-all duration-300 ${
452
- toast.type === 'success' ? 'bg-green-50 text-green-800 border-green-200' : 'bg-red-50 text-red-800 border-red-200'
453
- }`}
454
- >
455
- {toast.message}
456
- </div>
457
- )}
458
-
459
- {/* Card */}
460
- <div className="rounded-2xl border p-8" style={{ background: 'hsl(var(--card))', borderColor: 'hsl(var(--border))' }}>
461
- {/* Header */}
462
- <div className="mb-6">
463
- <h1 className="text-2xl font-semibold mb-2" style={{ color: 'hsl(var(--foreground))' }}>Verify Your Identity</h1>
464
- <p className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>Choose how you'd like to receive your verification code</p>
465
- </div>
466
-
467
- {/* Masked Info Display */}
468
- {maskedInfo && (
469
- <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))' }}>
470
- {maskedInfo.masked_email && (
471
- <div className="mb-1">
472
- Email: <span className="font-mono">{maskedInfo.masked_email}</span>
473
- </div>
474
- )}
475
- {maskedInfo.masked_phone_number && (
476
- <div>
477
- Phone: <span className="font-mono">{maskedInfo.masked_phone_number}</span>
478
- </div>
479
- )}
480
- </div>
481
- )}
482
-
483
- {/* Method Selection or Code Input */}
484
- {!method ? (
485
- /* Method Selection */
486
- <div className="space-y-3">
487
- <button
488
- type="button"
489
- onClick={() => handleSendCode('email')}
490
- disabled={sending || !maskedInfo?.masked_email}
491
- className="w-full flex items-center justify-between p-3 border rounded disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
492
- style={{
493
- background: 'hsl(var(--card))',
494
- borderColor: 'hsl(var(--border))',
495
- color: 'hsl(var(--foreground))'
496
- }}
497
- >
498
- <div className="text-left">
499
- <p className="font-medium" style={{ color: 'hsl(var(--foreground))' }}>Email</p>
500
- <p className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>{maskedInfo?.masked_email || 'Not available'}</p>
501
- </div>
502
- <span style={{ color: 'hsl(var(--muted-foreground))' }}>→</span>
503
- </button>
504
-
505
- <button
506
- type="button"
507
- onClick={() => handleSendCode('sms')}
508
- disabled={sending || !maskedInfo?.masked_phone_number}
509
- className="w-full flex items-center justify-between p-3 border rounded disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
510
- style={{
511
- background: 'hsl(var(--card))',
512
- borderColor: 'hsl(var(--border))',
513
- color: 'hsl(var(--foreground))'
514
- }}
515
- >
516
- <div className="text-left">
517
- <p className="font-medium" style={{ color: 'hsl(var(--foreground))' }}>SMS</p>
518
- <p className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>{maskedInfo?.masked_phone_number || 'Not available'}</p>
519
- </div>
520
- <span style={{ color: 'hsl(var(--muted-foreground))' }}>→</span>
521
- </button>
522
- </div>
523
- ) : (
524
- /* Code Input */
525
- <div className="space-y-4">
526
- {/* Method indicator */}
527
- <div className="flex items-center justify-between p-3 rounded border" style={{ background: 'hsl(var(--muted) / 0.1)', borderColor: 'hsl(var(--border))' }}>
528
- <span className="text-sm" style={{ color: 'hsl(var(--foreground))' }}>
529
- Code sent to your {method === 'email' ? 'email' : 'phone'}
530
- </span>
531
- <button type="button" onClick={handleResetMethod} className="text-sm hover:underline font-medium" style={{ color: 'hsl(var(--primary))' }}>
532
- Change method
533
- </button>
534
- </div>
535
-
536
- {/* Code input */}
537
- <div>
538
- <label htmlFor="code" className="block text-sm font-medium mb-2" style={{ color: 'hsl(var(--foreground))' }}>
539
- Verification Code
540
- </label>
541
- <input
542
- ref={codeInputRef}
543
- id="code"
544
- type="text"
545
- inputMode="numeric"
546
- pattern="[0-9]*"
547
- maxLength={6}
548
- value={code}
549
- onChange={handleCodeChange}
550
- className="w-full px-4 py-3 text-center text-2xl font-mono border rounded focus:ring-2 tracking-widest"
551
- style={{
552
- background: 'hsl(var(--input))',
553
- borderColor: 'hsl(var(--border))',
554
- color: 'hsl(var(--foreground))',
555
- caretColor: 'hsl(var(--foreground))'
556
- }}
557
- placeholder="000000"
558
- disabled={verifying || success}
559
- autoComplete="one-time-code"
560
- autoFocus
561
- />
562
- <p className="mt-2 text-sm text-center" style={{ color: 'hsl(var(--muted-foreground))' }}>Enter the 6-digit code</p>
563
- </div>
564
-
565
- {/* Status Display - Pre-sized container to prevent layout shift */}
566
- <div className="min-h-[3.5rem] flex items-center">
567
- {verifying ? (
568
- <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))' }}>
569
- <svg className="animate-spin w-4 h-4 mt-0.5" style={{ color: 'hsl(var(--primary))' }} fill="none" viewBox="0 0 24 24">
570
- <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
571
- <path
572
- className="opacity-75"
573
- fill="currentColor"
574
- 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"
575
- />
576
- </svg>
577
- <span className="text-sm" style={{ color: 'hsl(var(--foreground))' }}>Verifying code...</span>
578
- </div>
579
- ) : error ? (
580
- <div className="w-full flex items-start space-x-2 p-3 rounded bg-red-50 border border-red-200">
581
- <span className="text-red-700 text-sm font-medium">✗</span>
582
- <span className="text-red-700 text-sm">{error}</span>
583
- </div>
584
- ) : success ? (
585
- <div className="w-full flex items-start space-x-2 p-2.5 rounded bg-green-50 border border-green-200">
586
- <span className="text-green-700 text-xs font-medium">✓</span>
587
- <span className="text-green-700 text-xs">Verification successful! Redirecting...</span>
588
- </div>
589
- ) : null}
590
- </div>
591
-
592
- {/* Resend button */}
593
- {methodLocked && (
594
- <button
595
- type="button"
596
- onClick={() => handleSendCode(method)}
597
- disabled={sending || (method === 'email' ? emailCooldown > 0 : smsCooldown > 0)}
598
- className="w-full text-sm hover:underline font-medium disabled:no-underline disabled:cursor-not-allowed disabled:opacity-50"
599
- style={{ color: 'hsl(var(--primary))' }}
600
- >
601
- {sending
602
- ? 'Sending...'
603
- : method === 'email'
604
- ? emailCooldown > 0
605
- ? `Resend code in ${emailCooldown}s`
606
- : 'Resend code'
607
- : smsCooldown > 0
608
- ? `Resend code in ${smsCooldown}s`
609
- : 'Resend code'}
610
- </button>
611
- )}
612
- </div>
613
- )}
614
- </div>
615
-
616
- {/* Back to login */}
617
- <p className="mt-4 text-center text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>
618
- <a href="/account-auth/login" className="hover:underline font-medium" style={{ color: 'hsl(var(--primary))' }}>
619
- Back to login
620
- </a>
621
- </p>
622
- </div>
623
- </div>
624
- );
625
- }
626
-
627
- function VerifyCodePageFallback() {
628
- const colors = useColors();
629
- return (
630
- <div className="flex items-center justify-center py-8" style={{ background: 'hsl(var(--background))' }}>
631
- <div className="text-center">
632
- <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">
633
- <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
634
- <path
635
- className="opacity-75"
636
- fill="currentColor"
637
- 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"
638
- />
639
- </svg>
640
- <p className="mt-4" style={{ color: 'hsl(var(--muted-foreground))' }}>Loading...</p>
641
- </div>
642
- </div>
643
- );
644
- }
645
-
646
- export default function VerifyCodePage() {
647
- return (
648
- <Suspense fallback={<VerifyCodePageFallback />}>
649
- <VerifyCodeForm />
650
- </Suspense>
651
- );
652
- }
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
+
39
+ /**
40
+ * Session storage key to track that user intentionally navigated to verify-code.
41
+ * Prevents auto-redirect back to dashboard when session refreshes in background.
42
+ */
43
+ const VERIFY_IN_PROGRESS_KEY = 'idealvibe_2fa_verify_in_progress';
44
+
45
+ // Masked info structure from IDP
46
+ interface MaskedInfo {
47
+ masked_email?: string;
48
+ masked_phone_number?: string;
49
+ has_authenticator?: boolean;
50
+ }
51
+
52
+ function VerifyCodeForm() {
53
+ const router = useRouter();
54
+ const searchParams = useSearchParams();
55
+ const callbackUrl = searchParams?.get('callbackUrl') || '/dashboard';
56
+
57
+ const { data: sessionData, isPending } = authClient.useSession();
58
+ const session = sessionData;
59
+ const status = isPending ? 'loading' : session ? 'authenticated' : 'unauthenticated';
60
+ // TODO: Better Auth session refresh
61
+ const updateSession = async () => { return session; };
62
+ const colors = useColors();
63
+
64
+ // Method selection
65
+ type Method = 'email' | 'sms' | null;
66
+ const [method, setMethod] = useState<Method>(null);
67
+ const [methodLocked, setMethodLocked] = useState(false);
68
+
69
+ // Form state
70
+ const [code, setCode] = useState('');
71
+ const [maskedInfo, setMaskedInfo] = useState<MaskedInfo | null>(null);
72
+ const [loadingMasked, setLoadingMasked] = useState(true);
73
+
74
+ // Atomic state - only one active at a time
75
+ const [sending, setSending] = useState(false);
76
+ const [verifying, setVerifying] = useState(false);
77
+ const [success, setSuccess] = useState(false);
78
+ const [error, setError] = useState<string | null>(null);
79
+
80
+ // Cooldown timers
81
+ const [emailCooldown, setEmailCooldown] = useState(0);
82
+ const [smsCooldown, setSmsCooldown] = useState(0);
83
+
84
+ // Toast notifications
85
+ const [toast, setToast] = useState<{ type: 'success' | 'error'; message: string } | null>(null);
86
+
87
+ // Refs
88
+ const codeInputRef = useRef<HTMLInputElement>(null);
89
+ const lastSubmittedCode = useRef<string>('');
90
+
91
+ // Track that user is intentionally on this page
92
+ const [verifyInProgress, setVerifyInProgress] = useState(false);
93
+
94
+ // ==========================================================================
95
+ // CRITICAL FIX: Mark that user is intentionally on verify page
96
+ // This prevents auto-redirect when background token refresh updates session
97
+ // ==========================================================================
98
+ useEffect(() => {
99
+ // On mount, mark that verification is in progress
100
+ if (typeof window !== 'undefined') {
101
+ const wasInProgress = sessionStorage.getItem(VERIFY_IN_PROGRESS_KEY) === 'true';
102
+ if (!wasInProgress) {
103
+ console.log('[2FA] User navigated to verify-code page, marking verify in progress');
104
+ sessionStorage.setItem(VERIFY_IN_PROGRESS_KEY, 'true');
105
+ }
106
+ setVerifyInProgress(true);
107
+ }
108
+ }, []);
109
+
110
+ // Auto-dismiss toast
111
+ useEffect(() => {
112
+ if (toast) {
113
+ const timer = setTimeout(() => setToast(null), 2500);
114
+ return () => clearTimeout(timer);
115
+ }
116
+ }, [toast]);
117
+
118
+ // Cooldown countdown
119
+ useEffect(() => {
120
+ if (emailCooldown > 0) {
121
+ const timer = setTimeout(() => setEmailCooldown(emailCooldown - 1), 1000);
122
+ return () => clearTimeout(timer);
123
+ }
124
+ }, [emailCooldown]);
125
+
126
+ useEffect(() => {
127
+ if (smsCooldown > 0) {
128
+ const timer = setTimeout(() => setSmsCooldown(smsCooldown - 1), 1000);
129
+ return () => clearTimeout(timer);
130
+ }
131
+ }, [smsCooldown]);
132
+
133
+ // Fetch masked info on mount
134
+ useEffect(() => {
135
+ const fetchMaskedInfo = async () => {
136
+ // BUGFIX: Always set loadingMasked=false, even if not authenticated
137
+ // Otherwise page stays stuck in loading spinner
138
+ if (status !== 'authenticated' || !session) {
139
+ setLoadingMasked(false);
140
+ return;
141
+ }
142
+
143
+ try {
144
+ const res = await fetch('/api/account/masked-info', {
145
+ method: 'POST',
146
+ credentials: 'include',
147
+ });
148
+
149
+ if (res.status === 401) {
150
+ // Session expired - redirect to login
151
+ setError('Your session has expired. Redirecting to login...');
152
+ setTimeout(async () => {
153
+ await authClient.signOut();
154
+ const safeCallback = callbackUrl.startsWith('/account-auth/') ? '/dashboard' : callbackUrl;
155
+ router.push(`/account-auth/login?callbackUrl=${encodeURIComponent(safeCallback)}`);
156
+ }, 1200);
157
+ return;
158
+ }
159
+
160
+ if (!res.ok) {
161
+ throw new Error('Failed to load contact information');
162
+ }
163
+
164
+ const data = await res.json();
165
+ setMaskedInfo(data);
166
+ } catch (err) {
167
+ console.error('[2FA] Error fetching masked info:', err);
168
+ setError('Could not load your contact information. Please try again.');
169
+ } finally {
170
+ setLoadingMasked(false);
171
+ }
172
+ };
173
+
174
+ fetchMaskedInfo();
175
+ }, [status, session, callbackUrl, router]);
176
+
177
+ // Auto-submit when code is 6 digits
178
+ useEffect(() => {
179
+ if (code.length === 6 && method && !verifying) {
180
+ handleVerifyCode();
181
+ }
182
+ }, [code, method, verifying]);
183
+
184
+ // ==========================================================================
185
+ // Session viability check - detect expiration early and warn user
186
+ // ==========================================================================
187
+ useEffect(() => {
188
+ if (status !== 'authenticated') return;
189
+
190
+ // Check session viability every 30 seconds
191
+ const checkSession = async () => {
192
+ try {
193
+ const res = await fetch('/api/session/viability', {
194
+ credentials: 'include',
195
+ });
196
+
197
+ if (res.status === 401) {
198
+ const data = await res.json().catch(() => ({}));
199
+
200
+ // Session is no longer valid - warn user and redirect
201
+ if (data.valid === false || data.mfaExpired === true) {
202
+ setError('Your session has expired. Redirecting to login...');
203
+ setTimeout(async () => {
204
+ await authClient.signOut();
205
+ if (typeof window !== 'undefined') {
206
+ sessionStorage.removeItem(VERIFY_IN_PROGRESS_KEY);
207
+ }
208
+ router.push(`/account-auth/login?error=SessionExpired`);
209
+ }, 2000);
210
+ }
211
+ }
212
+ } catch (err) {
213
+ // Silent fail - let the next actual API call handle the error
214
+ console.log('[2FA] Session viability check failed:', err);
215
+ }
216
+ };
217
+
218
+ // Initial check after 5 seconds, then every 30 seconds
219
+ const initialTimeout = setTimeout(checkSession, 5000);
220
+ const interval = setInterval(checkSession, 30000);
221
+
222
+ return () => {
223
+ clearTimeout(initialTimeout);
224
+ clearInterval(interval);
225
+ };
226
+ }, [status, router]);
227
+
228
+ const handleSendCode = async (selectedMethod: 'email' | 'sms') => {
229
+ setSending(true);
230
+ setError(null);
231
+
232
+ try {
233
+ const res = await fetch('/api/account/send-code', {
234
+ method: 'POST',
235
+ headers: { 'Content-Type': 'application/json' },
236
+ body: JSON.stringify({ method: selectedMethod }),
237
+ credentials: 'include',
238
+ });
239
+
240
+ if (res.status === 401) {
241
+ const errorData = await res.json().catch(() => ({}));
242
+ const isJwtExpired = errorData?.error?.includes('JWT') || errorData?.message?.includes('JWT') || errorData?.error?.includes('expired');
243
+
244
+ setError(isJwtExpired
245
+ ? 'Your 2FA session has expired. Please sign in again.'
246
+ : 'Your session has expired. Redirecting to login...'
247
+ );
248
+
249
+ setTimeout(async () => {
250
+ await authClient.signOut();
251
+ if (typeof window !== 'undefined') {
252
+ sessionStorage.removeItem(VERIFY_IN_PROGRESS_KEY);
253
+ }
254
+ const safeCallback = callbackUrl.startsWith('/account-auth/') ? '/dashboard' : callbackUrl;
255
+ const errorParam = isJwtExpired ? '&error=SessionExpired' : '';
256
+ router.push(`/account-auth/login?callbackUrl=${encodeURIComponent(safeCallback)}${errorParam}`);
257
+ }, 1500);
258
+ return;
259
+ }
260
+
261
+ if (!res.ok) {
262
+ const data = await res.json();
263
+ throw new Error(data.message || data.error || 'Failed to send code');
264
+ }
265
+
266
+ // Lock method and set cooldown
267
+ setMethod(selectedMethod);
268
+ setMethodLocked(true);
269
+
270
+ if (selectedMethod === 'email') {
271
+ setEmailCooldown(30);
272
+ } else {
273
+ setSmsCooldown(30);
274
+ }
275
+
276
+ setToast({
277
+ type: 'success',
278
+ message: `Verification code sent to your ${selectedMethod === 'email' ? 'email' : 'phone'}`,
279
+ });
280
+
281
+ // Focus code input
282
+ setTimeout(() => codeInputRef.current?.focus(), 100);
283
+ } catch (err) {
284
+ setError(err instanceof Error ? err.message : 'Failed to send verification code');
285
+ } finally {
286
+ setSending(false);
287
+ }
288
+ };
289
+
290
+ const handleVerifyCode = async () => {
291
+ if (!code || !method || code.length !== 6) {
292
+ return;
293
+ }
294
+
295
+ // Prevent duplicate submissions
296
+ if (lastSubmittedCode.current === code) {
297
+ console.log('[2FA] Duplicate submission prevented');
298
+ return;
299
+ }
300
+ lastSubmittedCode.current = code;
301
+
302
+ setVerifying(true);
303
+ setError(null);
304
+
305
+ try {
306
+ const endpoint = method === 'sms' ? '/api/account/verify-sms' : '/api/account/verify-email';
307
+
308
+ const res = await fetch(endpoint, {
309
+ method: 'POST',
310
+ headers: { 'Content-Type': 'application/json' },
311
+ body: JSON.stringify({ verificationCode: code }),
312
+ credentials: 'include',
313
+ });
314
+
315
+ if (res.status === 401) {
316
+ const errorData = await res.json().catch(() => ({}));
317
+ const isJwtExpired = errorData?.error?.includes('JWT') || errorData?.message?.includes('JWT') || errorData?.error?.includes('expired');
318
+
319
+ setError(isJwtExpired
320
+ ? 'Your 2FA session has expired. Please sign in again.'
321
+ : 'Your session has expired. Redirecting to login...'
322
+ );
323
+
324
+ setTimeout(async () => {
325
+ await authClient.signOut();
326
+ if (typeof window !== 'undefined') {
327
+ sessionStorage.removeItem(VERIFY_IN_PROGRESS_KEY);
328
+ }
329
+ const safeCallback = callbackUrl.startsWith('/account-auth/') ? '/dashboard' : callbackUrl;
330
+ const errorParam = isJwtExpired ? '&error=SessionExpired' : '';
331
+ router.push(`/account-auth/login?callbackUrl=${encodeURIComponent(safeCallback)}${errorParam}`);
332
+ }, 1500);
333
+ return;
334
+ }
335
+
336
+ if (!res.ok) {
337
+ const data = await res.json();
338
+ throw new Error(data.error || data.message || 'Verification failed');
339
+ }
340
+
341
+ const result = await res.json();
342
+
343
+ // Normalize response: support both enveloped and unwrapped payloads
344
+ const payload = (result && typeof result === 'object' && 'data' in result)
345
+ ? (result as any).data
346
+ : result;
347
+
348
+ // Check if verification was successful
349
+ const verified =
350
+ payload?.verificationSuccessful === true ||
351
+ payload?.twoFactorSessionVerified === true ||
352
+ payload?.success === true ||
353
+ // Accept token-based success (unwrapped raw tokens from backend)
354
+ (!!payload?.access_token && !!payload?.refresh_token);
355
+
356
+ if (!verified) {
357
+ throw new Error('Verification failed. Please try again.');
358
+ }
359
+
360
+ // CRITICAL: If tokens are included (unwrapped response), persist them in server session
361
+ if (payload?.access_token && payload?.refresh_token) {
362
+ try {
363
+ console.log('[2FA] Updating session with new MFA tokens...');
364
+ const updateRes = await fetch('/api/auth/update-session', {
365
+ method: 'POST',
366
+ headers: { 'Content-Type': 'application/json' },
367
+ credentials: 'include',
368
+ body: JSON.stringify({
369
+ access_token: payload.access_token,
370
+ refresh_token: payload.refresh_token
371
+ })
372
+ });
373
+
374
+ if (!updateRes.ok) {
375
+ console.warn('[2FA] update-session returned non-OK status:', updateRes.status);
376
+ const errorData = await updateRes.json();
377
+ console.warn('[2FA] update-session error:', errorData);
378
+ } else {
379
+ console.log('[2FA] Session updated successfully with MFA tokens');
380
+ }
381
+ } catch (e) {
382
+ console.warn('[2FA] Failed to call update-session:', e);
383
+ }
384
+ }
385
+
386
+ // Show success state
387
+ setSuccess(true);
388
+ setError(null);
389
+
390
+ // CRITICAL: Force NextAuth to refetch session from server
391
+ // This ensures useSession() gets the updated twoFactorComplete: true
392
+ console.log('[2FA] Forcing session refresh after verification...');
393
+ try {
394
+ await updateSession(); // This triggers /api/auth/session and updates useSession() state
395
+ console.log('[2FA] Session refresh completed');
396
+ } catch (e) {
397
+ console.warn('[2FA] updateSession failed:', e);
398
+ }
399
+
400
+ // Clear verify-in-progress flag before redirect
401
+ if (typeof window !== 'undefined') {
402
+ sessionStorage.removeItem(VERIFY_IN_PROGRESS_KEY);
403
+ }
404
+
405
+ // Redirect after showing success state
406
+ setTimeout(() => {
407
+ window.location.href = callbackUrl;
408
+ }, 1500);
409
+ } catch (err) {
410
+ setError(err instanceof Error ? err.message : 'Failed to verify code');
411
+ lastSubmittedCode.current = ''; // Allow retry
412
+ } finally {
413
+ setVerifying(false);
414
+ }
415
+ };
416
+
417
+ const handleResetMethod = () => {
418
+ setMethod(null);
419
+ setMethodLocked(false);
420
+ setCode('');
421
+ setError(null);
422
+ setEmailCooldown(0);
423
+ setSmsCooldown(0);
424
+ lastSubmittedCode.current = '';
425
+ };
426
+
427
+ const handleCodeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
428
+ const value = e.target.value.replace(/[^0-9]/g, '').slice(0, 6);
429
+ setCode(value);
430
+ };
431
+
432
+ // Loading state
433
+ if (status === 'loading' || loadingMasked) {
434
+ return (
435
+ <div className="flex flex-col items-center justify-center py-8" style={{ background: 'hsl(var(--background))' }}>
436
+ <svg className="animate-spin h-10 w-10" style={{ color: 'hsl(var(--primary))' }} viewBox="0 0 24 24" fill="none">
437
+ <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
438
+ <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z" />
439
+ </svg>
440
+ <p className="mt-4 text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>Loading...</p>
441
+ </div>
442
+ );
443
+ }
444
+
445
+ return (
446
+ <div className="flex items-center justify-center px-4 py-8" style={{ background: 'hsl(var(--background))' }}>
447
+ <div className="max-w-md w-full">
448
+ {/* Toast Notification */}
449
+ {toast && (
450
+ <div
451
+ className={`fixed top-4 right-4 p-4 rounded border transition-all duration-300 ${
452
+ toast.type === 'success' ? 'bg-green-50 text-green-800 border-green-200' : 'bg-red-50 text-red-800 border-red-200'
453
+ }`}
454
+ >
455
+ {toast.message}
456
+ </div>
457
+ )}
458
+
459
+ {/* Card */}
460
+ <div className="rounded-2xl border p-8" style={{ background: 'hsl(var(--card))', borderColor: 'hsl(var(--border))' }}>
461
+ {/* Header */}
462
+ <div className="mb-6">
463
+ <h1 className="text-2xl font-semibold mb-2" style={{ color: 'hsl(var(--foreground))' }}>Verify Your Identity</h1>
464
+ <p className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>Choose how you'd like to receive your verification code</p>
465
+ </div>
466
+
467
+ {/* Masked Info Display */}
468
+ {maskedInfo && (
469
+ <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))' }}>
470
+ {maskedInfo.masked_email && (
471
+ <div className="mb-1">
472
+ Email: <span className="font-mono">{maskedInfo.masked_email}</span>
473
+ </div>
474
+ )}
475
+ {maskedInfo.masked_phone_number && (
476
+ <div>
477
+ Phone: <span className="font-mono">{maskedInfo.masked_phone_number}</span>
478
+ </div>
479
+ )}
480
+ </div>
481
+ )}
482
+
483
+ {/* Method Selection or Code Input */}
484
+ {!method ? (
485
+ /* Method Selection */
486
+ <div className="space-y-3">
487
+ <button
488
+ type="button"
489
+ onClick={() => handleSendCode('email')}
490
+ disabled={sending || !maskedInfo?.masked_email}
491
+ className="w-full flex items-center justify-between p-3 border rounded disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
492
+ style={{
493
+ background: 'hsl(var(--card))',
494
+ borderColor: 'hsl(var(--border))',
495
+ color: 'hsl(var(--foreground))'
496
+ }}
497
+ >
498
+ <div className="text-left">
499
+ <p className="font-medium" style={{ color: 'hsl(var(--foreground))' }}>Email</p>
500
+ <p className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>{maskedInfo?.masked_email || 'Not available'}</p>
501
+ </div>
502
+ <span style={{ color: 'hsl(var(--muted-foreground))' }}>→</span>
503
+ </button>
504
+
505
+ <button
506
+ type="button"
507
+ onClick={() => handleSendCode('sms')}
508
+ disabled={sending || !maskedInfo?.masked_phone_number}
509
+ className="w-full flex items-center justify-between p-3 border rounded disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
510
+ style={{
511
+ background: 'hsl(var(--card))',
512
+ borderColor: 'hsl(var(--border))',
513
+ color: 'hsl(var(--foreground))'
514
+ }}
515
+ >
516
+ <div className="text-left">
517
+ <p className="font-medium" style={{ color: 'hsl(var(--foreground))' }}>SMS</p>
518
+ <p className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>{maskedInfo?.masked_phone_number || 'Not available'}</p>
519
+ </div>
520
+ <span style={{ color: 'hsl(var(--muted-foreground))' }}>→</span>
521
+ </button>
522
+ </div>
523
+ ) : (
524
+ /* Code Input */
525
+ <div className="space-y-4">
526
+ {/* Method indicator */}
527
+ <div className="flex items-center justify-between p-3 rounded border" style={{ background: 'hsl(var(--muted) / 0.1)', borderColor: 'hsl(var(--border))' }}>
528
+ <span className="text-sm" style={{ color: 'hsl(var(--foreground))' }}>
529
+ Code sent to your {method === 'email' ? 'email' : 'phone'}
530
+ </span>
531
+ <button type="button" onClick={handleResetMethod} className="text-sm hover:underline font-medium" style={{ color: 'hsl(var(--primary))' }}>
532
+ Change method
533
+ </button>
534
+ </div>
535
+
536
+ {/* Code input */}
537
+ <div>
538
+ <label htmlFor="code" className="block text-sm font-medium mb-2" style={{ color: 'hsl(var(--foreground))' }}>
539
+ Verification Code
540
+ </label>
541
+ <input
542
+ ref={codeInputRef}
543
+ id="code"
544
+ type="text"
545
+ inputMode="numeric"
546
+ pattern="[0-9]*"
547
+ maxLength={6}
548
+ value={code}
549
+ onChange={handleCodeChange}
550
+ className="w-full px-4 py-3 text-center text-2xl font-mono border rounded focus:ring-2 tracking-widest"
551
+ style={{
552
+ background: 'hsl(var(--input))',
553
+ borderColor: 'hsl(var(--border))',
554
+ color: 'hsl(var(--foreground))',
555
+ caretColor: 'hsl(var(--foreground))'
556
+ }}
557
+ placeholder="000000"
558
+ disabled={verifying || success}
559
+ autoComplete="one-time-code"
560
+ autoFocus
561
+ />
562
+ <p className="mt-2 text-sm text-center" style={{ color: 'hsl(var(--muted-foreground))' }}>Enter the 6-digit code</p>
563
+ </div>
564
+
565
+ {/* Status Display - Pre-sized container to prevent layout shift */}
566
+ <div className="min-h-[3.5rem] flex items-center">
567
+ {verifying ? (
568
+ <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))' }}>
569
+ <svg className="animate-spin w-4 h-4 mt-0.5" style={{ color: 'hsl(var(--primary))' }} fill="none" viewBox="0 0 24 24">
570
+ <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
571
+ <path
572
+ className="opacity-75"
573
+ fill="currentColor"
574
+ 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"
575
+ />
576
+ </svg>
577
+ <span className="text-sm" style={{ color: 'hsl(var(--foreground))' }}>Verifying code...</span>
578
+ </div>
579
+ ) : error ? (
580
+ <div className="w-full flex items-start space-x-2 p-3 rounded bg-red-50 border border-red-200">
581
+ <span className="text-red-700 text-sm font-medium">✗</span>
582
+ <span className="text-red-700 text-sm">{error}</span>
583
+ </div>
584
+ ) : success ? (
585
+ <div className="w-full flex items-start space-x-2 p-2.5 rounded bg-green-50 border border-green-200">
586
+ <span className="text-green-700 text-xs font-medium">✓</span>
587
+ <span className="text-green-700 text-xs">Verification successful! Redirecting...</span>
588
+ </div>
589
+ ) : null}
590
+ </div>
591
+
592
+ {/* Resend button */}
593
+ {methodLocked && (
594
+ <button
595
+ type="button"
596
+ onClick={() => handleSendCode(method)}
597
+ disabled={sending || (method === 'email' ? emailCooldown > 0 : smsCooldown > 0)}
598
+ className="w-full text-sm hover:underline font-medium disabled:no-underline disabled:cursor-not-allowed disabled:opacity-50"
599
+ style={{ color: 'hsl(var(--primary))' }}
600
+ >
601
+ {sending
602
+ ? 'Sending...'
603
+ : method === 'email'
604
+ ? emailCooldown > 0
605
+ ? `Resend code in ${emailCooldown}s`
606
+ : 'Resend code'
607
+ : smsCooldown > 0
608
+ ? `Resend code in ${smsCooldown}s`
609
+ : 'Resend code'}
610
+ </button>
611
+ )}
612
+ </div>
613
+ )}
614
+ </div>
615
+
616
+ {/* Back to login */}
617
+ <p className="mt-4 text-center text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>
618
+ <a href="/account-auth/login" className="hover:underline font-medium" style={{ color: 'hsl(var(--primary))' }}>
619
+ Back to login
620
+ </a>
621
+ </p>
622
+ </div>
623
+ </div>
624
+ );
625
+ }
626
+
627
+ function VerifyCodePageFallback() {
628
+ const colors = useColors();
629
+ return (
630
+ <div className="flex items-center justify-center py-8" style={{ background: 'hsl(var(--background))' }}>
631
+ <div className="text-center">
632
+ <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">
633
+ <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
634
+ <path
635
+ className="opacity-75"
636
+ fill="currentColor"
637
+ 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"
638
+ />
639
+ </svg>
640
+ <p className="mt-4" style={{ color: 'hsl(var(--muted-foreground))' }}>Loading...</p>
641
+ </div>
642
+ </div>
643
+ );
644
+ }
645
+
646
+ export default function VerifyCodePage() {
647
+ return (
648
+ <Suspense fallback={<VerifyCodePageFallback />}>
649
+ <VerifyCodeForm />
650
+ </Suspense>
651
+ );
652
+ }