@payez/next-mvp 4.1.14 → 4.1.21

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 (116) hide show
  1. package/dist/api-handlers/account/profile.d.ts +38 -0
  2. package/dist/api-handlers/account/profile.js +73 -45
  3. package/dist/api-handlers/account/recovery/send-code.d.ts +33 -0
  4. package/dist/api-handlers/account/recovery/send-code.js +52 -18
  5. package/dist/api-handlers/account/recovery/verify-code.d.ts +33 -0
  6. package/dist/api-handlers/account/recovery/verify-code.js +52 -18
  7. package/dist/api-handlers/account/verify-email.js +15 -1
  8. package/dist/api-handlers/account/verify-sms.js +15 -1
  9. package/dist/api-handlers/auth/passkey-signin.d.ts +29 -0
  10. package/dist/api-handlers/auth/passkey-signin.js +97 -0
  11. package/dist/api-handlers/auth/refresh.js +38 -15
  12. package/dist/api-handlers/mfa/backup-code-verify.d.ts +73 -0
  13. package/dist/api-handlers/mfa/backup-code-verify.js +153 -0
  14. package/dist/api-handlers/mfa/backup-codes.d.ts +7 -0
  15. package/dist/api-handlers/mfa/backup-codes.js +40 -0
  16. package/dist/api-handlers/mfa/methods.d.ts +3 -0
  17. package/dist/api-handlers/mfa/methods.js +41 -0
  18. package/dist/api-handlers/mfa/totp-confirm.d.ts +8 -0
  19. package/dist/api-handlers/mfa/totp-confirm.js +41 -0
  20. package/dist/api-handlers/mfa/totp-enroll.d.ts +8 -0
  21. package/dist/api-handlers/mfa/totp-enroll.js +41 -0
  22. package/dist/api-handlers/mfa/totp-verify.d.ts +47 -0
  23. package/dist/api-handlers/mfa/totp-verify.js +134 -0
  24. package/dist/api-handlers/passkeys/list.d.ts +7 -0
  25. package/dist/api-handlers/passkeys/list.js +29 -0
  26. package/dist/api-handlers/passkeys/manage.d.ts +3 -0
  27. package/dist/api-handlers/passkeys/manage.js +54 -0
  28. package/dist/api-handlers/passkeys/register-options.d.ts +8 -0
  29. package/dist/api-handlers/passkeys/register-options.js +41 -0
  30. package/dist/api-handlers/passkeys/register-verify.d.ts +7 -0
  31. package/dist/api-handlers/passkeys/register-verify.js +40 -0
  32. package/dist/api-handlers/session/viability.js +19 -0
  33. package/dist/auth/better-auth.d.ts +68 -2
  34. package/dist/auth/better-auth.js +137 -18
  35. package/dist/auth/utils/idp-client.d.ts +13 -22
  36. package/dist/auth/utils/idp-client.js +12 -82
  37. package/dist/client/better-auth-client.d.ts +62 -62
  38. package/dist/lib/ensure-fresh-access-token.js +49 -8
  39. package/dist/lib/session-store.d.ts +1 -0
  40. package/dist/lib/session-store.js +19 -8
  41. package/dist/lib/token-lifecycle.d.ts +2 -0
  42. package/dist/lib/token-lifecycle.js +61 -7
  43. package/dist/models/SessionModel.d.ts +17 -0
  44. package/dist/pages/login/page.d.ts +10 -1
  45. package/dist/pages/login/page.js +69 -80
  46. package/dist/pages/verify-code/page.d.ts +10 -1
  47. package/dist/pages/verify-code/page.js +72 -4
  48. package/dist/routes/auth/passkey-signin.d.ts +13 -0
  49. package/dist/routes/auth/passkey-signin.js +18 -0
  50. package/dist/routes/auth/viability.d.ts +2 -0
  51. package/dist/routes/auth/viability.js +88 -0
  52. package/dist/routes/mfa/backup-code-verify.d.ts +1 -0
  53. package/dist/routes/mfa/backup-code-verify.js +5 -0
  54. package/dist/routes/mfa/backup-codes.d.ts +10 -0
  55. package/dist/routes/mfa/backup-codes.js +14 -0
  56. package/dist/routes/mfa/methods.d.ts +21 -0
  57. package/dist/routes/mfa/methods.js +10 -0
  58. package/dist/routes/mfa/totp-confirm.d.ts +10 -0
  59. package/dist/routes/mfa/totp-confirm.js +14 -0
  60. package/dist/routes/mfa/totp-enroll.d.ts +10 -0
  61. package/dist/routes/mfa/totp-enroll.js +14 -0
  62. package/dist/routes/mfa/totp-verify.d.ts +14 -0
  63. package/dist/routes/mfa/totp-verify.js +18 -0
  64. package/dist/routes/passkeys/list.d.ts +10 -0
  65. package/dist/routes/passkeys/list.js +14 -0
  66. package/dist/routes/passkeys/manage.d.ts +18 -0
  67. package/dist/routes/passkeys/manage.js +13 -0
  68. package/dist/routes/passkeys/register-options.d.ts +10 -0
  69. package/dist/routes/passkeys/register-options.js +14 -0
  70. package/dist/routes/passkeys/register-verify.d.ts +10 -0
  71. package/dist/routes/passkeys/register-verify.js +14 -0
  72. package/dist/server/auth.d.ts +29 -20
  73. package/dist/server/auth.js +8 -0
  74. package/dist/server/decode-session.js +37 -3
  75. package/package.json +958 -894
  76. package/scripts/check-internal-url-usage.sh +73 -73
  77. package/src/api-handlers/account/profile.ts +76 -57
  78. package/src/api-handlers/account/recovery/send-code.ts +65 -17
  79. package/src/api-handlers/account/recovery/verify-code.ts +65 -17
  80. package/src/api-handlers/account/verify-email.ts +15 -1
  81. package/src/api-handlers/account/verify-sms.ts +15 -1
  82. package/src/api-handlers/auth/passkey-signin.ts +98 -0
  83. package/src/api-handlers/auth/refresh.ts +38 -15
  84. package/src/api-handlers/mfa/backup-code-verify.ts +175 -0
  85. package/src/api-handlers/mfa/backup-codes.ts +41 -0
  86. package/src/api-handlers/mfa/methods.ts +46 -0
  87. package/src/api-handlers/mfa/totp-confirm.ts +42 -0
  88. package/src/api-handlers/mfa/totp-enroll.ts +42 -0
  89. package/src/api-handlers/mfa/totp-verify.ts +156 -0
  90. package/src/api-handlers/passkeys/list.ts +31 -0
  91. package/src/api-handlers/passkeys/manage.ts +54 -0
  92. package/src/api-handlers/passkeys/register-options.ts +42 -0
  93. package/src/api-handlers/passkeys/register-verify.ts +41 -0
  94. package/src/api-handlers/session/viability.ts +19 -0
  95. package/src/auth/better-auth.ts +158 -18
  96. package/src/auth/utils/idp-client.ts +13 -95
  97. package/src/lib/ensure-fresh-access-token.ts +49 -8
  98. package/src/lib/session-store.ts +11 -1
  99. package/src/lib/token-lifecycle.ts +70 -7
  100. package/src/models/SessionModel.ts +18 -0
  101. package/src/pages/login/page.tsx +123 -228
  102. package/src/pages/verify-code/page.tsx +71 -5
  103. package/src/routes/auth/passkey-signin.ts +13 -0
  104. package/src/routes/auth/viability.ts +89 -0
  105. package/src/routes/mfa/backup-code-verify.ts +1 -0
  106. package/src/routes/mfa/backup-codes.ts +10 -0
  107. package/src/routes/mfa/methods.ts +22 -0
  108. package/src/routes/mfa/totp-confirm.ts +10 -0
  109. package/src/routes/mfa/totp-enroll.ts +10 -0
  110. package/src/routes/mfa/totp-verify.ts +14 -0
  111. package/src/routes/passkeys/list.ts +10 -0
  112. package/src/routes/passkeys/manage.ts +23 -0
  113. package/src/routes/passkeys/register-options.ts +10 -0
  114. package/src/routes/passkeys/register-verify.ts +10 -0
  115. package/src/server/auth.ts +17 -1
  116. package/src/server/decode-session.ts +36 -3
@@ -0,0 +1,98 @@
1
+ import { NextRequest, NextResponse } from 'next/server';
2
+ import { ENV_CONFIG } from '../../config/env';
3
+ import { getIDPClientConfig } from '../../lib/idp-client-config';
4
+
5
+ /**
6
+ * Passkey SIGN-IN ceremony (ANONYMOUS — no session exists yet):
7
+ * optionsPOST -> POST /api/ExternalAuth/passwordless/passkey/options
8
+ * verifyPOST -> POST /api/ExternalAuth/passwordless/passkey/verify
9
+ *
10
+ * Anon idiom copied from auth/better-auth.ts (exchangeOAuthForIdpTokens):
11
+ * direct fetch to the IDP, client identified by client_id from the resolved
12
+ * IDP client config (slug preferred, numeric id fallback) — sent BOTH as the
13
+ * X-Client-Id header (the probe-verified routing key) and merged into the
14
+ * body when the caller did not supply one.
15
+ *
16
+ * The verify response is passed through WITHOUT unwrapping: this is a
17
+ * sign-in, its payload carries the grant the caller's session layer consumes.
18
+ */
19
+
20
+ async function clientKey(): Promise<string> {
21
+ const config = await getIDPClientConfig();
22
+ return config.clientSlug || String(config.clientId);
23
+ }
24
+
25
+ async function anonCall(req: NextRequest, path: string) {
26
+ let parsed: Record<string, unknown> = {};
27
+ try {
28
+ const raw = await req.text();
29
+ if (raw && raw.trim().length > 0) parsed = JSON.parse(raw);
30
+ } catch {}
31
+
32
+ const key = await clientKey();
33
+ const res = await fetch(`${ENV_CONFIG.IDP_URL}${path}`, {
34
+ method: 'POST',
35
+ headers: { 'Content-Type': 'application/json', 'X-Client-Id': key },
36
+ body: JSON.stringify({ client_id: key, ...parsed }),
37
+ cache: 'no-store',
38
+ });
39
+ const json = await res.json().catch(() => null);
40
+ return { res, json };
41
+ }
42
+
43
+ export async function optionsPOST(req: NextRequest) {
44
+ const { res, json } = await anonCall(req, '/api/ExternalAuth/passwordless/passkey/options');
45
+ return NextResponse.json(json ?? { success: false, message: 'Empty upstream response' }, { status: res.status });
46
+ }
47
+
48
+ /**
49
+ * VERIFY DOES NOT USE anonCall — IT MUST RESHAPE, NOT SPREAD.
50
+ *
51
+ * The IDP contract is three fields (PasskeyModels.cs:36 PasskeyAuthVerifyRequest):
52
+ * assertion_id : string
53
+ * response : the WHOLE AuthenticatorAssertionRawResponse from
54
+ * navigator.credentials.get()
55
+ * client_id : string
56
+ *
57
+ * anonCall SPREADS the caller's body (`{ client_id, ...parsed }`). For options
58
+ * that is harmless. For verify it is fatal: spreading an assertion hoists
59
+ * id/rawId/type to the top level and leaves `response` holding only the INNER
60
+ * {clientDataJSON, authenticatorData, signature, userHandle}. The IDP's guard
61
+ * then answers "response is required" in 4-12ms WITHOUT REACHING THE CRYPTO —
62
+ * a timing signature DotNetPert used to prove the caller was still spreading
63
+ * long after the graft-side plugin had been fixed.
64
+ *
65
+ * This route and the Better Auth plugin endpoint are TWO PATHS to the same IDP
66
+ * endpoint. Fixing only the plugin left this one live, spreading, and reachable
67
+ * on a URL one segment away from the correct one — which is what kept the
68
+ * sign-in leg red across several runs.
69
+ *
70
+ * Accepts the assertion either already nested (`{ assertion_id, response }`) or
71
+ * flat (`{ assertion_id, id, rawId, type, response }`) and normalises both, so a
72
+ * caller written against either shape works.
73
+ */
74
+ export async function verifyPOST(req: NextRequest) {
75
+ let parsed: Record<string, unknown> = {};
76
+ try {
77
+ const raw = await req.text();
78
+ if (raw && raw.trim().length > 0) parsed = JSON.parse(raw);
79
+ } catch { /* empty body -> the IDP's own validation answers */ }
80
+
81
+ const { assertion_id: assertionId, response, ...rest } = parsed;
82
+
83
+ // Already-nested callers send `response` holding a full assertion (it has an
84
+ // `id`). Flat callers send the assertion's own fields alongside assertion_id,
85
+ // and their `response` is the inner attestation half — not a whole assertion.
86
+ const nested = response && typeof response === 'object' && 'id' in (response as object);
87
+ const assertion = nested ? response : { ...rest, response };
88
+
89
+ const key = await clientKey();
90
+ const res = await fetch(`${ENV_CONFIG.IDP_URL}/api/ExternalAuth/passwordless/passkey/verify`, {
91
+ method: 'POST',
92
+ headers: { 'Content-Type': 'application/json', 'X-Client-Id': key },
93
+ body: JSON.stringify({ client_id: key, assertion_id: assertionId, response: assertion }),
94
+ cache: 'no-store',
95
+ });
96
+ const json = await res.json().catch(() => null);
97
+ return NextResponse.json(json ?? { success: false, message: 'Empty upstream response' }, { status: res.status });
98
+ }
@@ -400,7 +400,7 @@ export function createRefreshHandler(config: RefreshConfig) {
400
400
  const errorMessage = idpError.message || 'Token refresh failed';
401
401
  // CRITICAL: 401 means token is definitively invalid - always discard
402
402
  // This prevents redirect loops where viability check keeps returning canRefresh:true
403
- const discardToken = refreshResponse.status === 401 || idpError.discard_token === true;
403
+ let discardToken = refreshResponse.status === 401 || idpError.discard_token === true;
404
404
  const retryable = refreshResponse.status !== 401 && idpError.retryable === true;
405
405
  const resolution = idpError.resolution || null;
406
406
 
@@ -442,20 +442,43 @@ export function createRefreshHandler(config: RefreshConfig) {
442
442
 
443
443
  // If IDP signals to discard token, clear it from Redis
444
444
  if (discardToken) {
445
- console.error('[AUTH_REFRESH] ⚠️ REFRESH_TOKEN_REMOVAL: IDP signaled discard_token', {
446
- reason: 'IDP_DISCARD_TOKEN',
447
- errorCode,
448
- userId,
449
- sessionToken: sessionToken.substring(0, 8) + '...',
450
- hadRefreshToken: !!currentSession.idpRefreshToken,
451
- stack: new Error().stack
452
- });
453
- await updateSession(sessionToken, {
454
- idpRefreshToken: '',
455
- idpRefreshTokenExpires: undefined,
456
- refreshTokenClearedAt: Date.now(),
457
- refreshTokenClearedReason: `IDP_DISCARD_TOKEN:${errorCode}`
458
- });
445
+ // Race-safe discard (CAS): only clear if the refresh token we sent is STILL
446
+ // the current one. A concurrent refresh may have already rotated it — our 401
447
+ // is then stale, and wiping here would silently log out a healthy session
448
+ // (the rotation-race wipe, QA 6873 site 2). Skip the wipe + drop terminal if changed.
449
+ const postRefresh = await getSession(sessionToken);
450
+ const tokenUnchanged =
451
+ !!originalRefreshToken && postRefresh?.idpRefreshToken === originalRefreshToken;
452
+ if (tokenUnchanged) {
453
+ console.error('[AUTH_REFRESH] ⚠️ REFRESH_TOKEN_REMOVAL: IDP signaled discard_token', {
454
+ reason: 'IDP_DISCARD_TOKEN',
455
+ errorCode,
456
+ userId,
457
+ sessionToken: sessionToken.substring(0, 8) + '...',
458
+ hadRefreshToken: !!currentSession.idpRefreshToken,
459
+ stack: new Error().stack
460
+ });
461
+ await updateSession(sessionToken, {
462
+ idpRefreshToken: '',
463
+ idpRefreshTokenExpires: undefined,
464
+ refreshTokenClearedAt: Date.now(),
465
+ refreshTokenClearedReason: `IDP_DISCARD_TOKEN:${errorCode}`
466
+ });
467
+ } else {
468
+ // Concurrent refresh already rotated the token — our 401 is stale. Return the
469
+ // freshly-rotated token directly so the loser succeeds without a retry
470
+ // (race-fix follow-up #1).
471
+ discardToken = false;
472
+ console.warn('[AUTH_REFRESH] Discard suppressed: refresh token already rotated by a concurrent refresh — returning the fresh token (race-safe).');
473
+ if (postRefresh?.idpAccessToken && postRefresh.idpAccessTokenExpires) {
474
+ return NextResponse.json({
475
+ refreshed: true,
476
+ reason: 'completed_by_concurrent_request',
477
+ accessTokenExpires: postRefresh.idpAccessTokenExpires,
478
+ hasRefreshToken: !!postRefresh.idpRefreshToken,
479
+ });
480
+ }
481
+ }
459
482
  }
460
483
 
461
484
  return NextResponse.json({
@@ -0,0 +1,175 @@
1
+ /**
2
+ * Verify Backup Code 2FA Challenge Handler
3
+ *
4
+ * Verifies a single-use recovery code AT LOGIN and completes the 2FA flow,
5
+ * transitioning the session to MFA-verified.
6
+ *
7
+ * WHY THIS EXISTS (2026-08-02)
8
+ * The package shipped backup-code GENERATION (backup-codes.ts, POST
9
+ * /api/Account/mfa/backup-codes) and no way to SPEND one. Codes could be
10
+ * generated, displayed once, written down — and then never used to satisfy a
11
+ * login challenge. Exactly the gap TOTP had before totp-verify: the enrolment
12
+ * half without the challenge half.
13
+ *
14
+ * THIS IS THE FACTOR OF LAST RESORT. A user reaches for a backup code when they
15
+ * have lost the authenticator, so it is the one path that must work when
16
+ * everything else has already failed. A recovery mechanism that cannot be
17
+ * redeemed is worse than none: it invites people to rely on it.
18
+ *
19
+ * FIELD NAME: the IDP expects { "code": ... }
20
+ * (MfaBackupCodeVerifyRequest, [JsonPropertyName("code")]). The dash in
21
+ * 'xxxx-xxxx' is optional per the IDP contract, so the code is forwarded as
22
+ * typed and normalisation is left to the IDP rather than guessed here.
23
+ *
24
+ * SINGLE USE, CONSUMED ATOMICALLY. The IDP hash-compares against unused codes
25
+ * and stamps used_at + used_by_ip in the same operation (MfaController 5g).
26
+ * NEVER retry this call on a network error or an ambiguous response — a retry
27
+ * can burn a second code, and the user has ten.
28
+ *
29
+ * DO NOT MAKE GENERATION TRANSITION THE SESSION, the same trap totp-confirm
30
+ * carries: generating recovery codes is not proof of possessing one.
31
+ *
32
+ * THE STORED 2FA METHOD IS 'totp', NOT 'backup_code'. READ THIS BEFORE
33
+ * "CORRECTING" IT — it looks wrong and is not.
34
+ *
35
+ * 1. IT MATCHES THE IDP. MfaController 5g sets
36
+ * `TwoFactorMethod = TwoFactorMethodType.Totp` for this exact path,
37
+ * commented "Backup code = recovery proof of the TOTP factor", and the
38
+ * reissued token's amr carries mfa+totp. A backup code is not a separate
39
+ * factor; it is recovery proof of the authenticator factor.
40
+ *
41
+ * 2. INVENTING A NEW VALUE SILENTLY BREAKS TOKEN REFRESH. refresh.ts:279
42
+ * resolves the method with ['sms','totp','email'].includes(m). Anything
43
+ * outside that set is dropped, so `two_factor_method` never reaches the
44
+ * IDP on refresh, and a session established with a recovery code refreshes
45
+ * differently from one established with the authenticator — for the same
46
+ * underlying factor. It fails quietly, days later, as "sessions
47
+ * occasionally drop", with nothing pointing back to this string.
48
+ *
49
+ * The type union (email|sms|totp) is not the reason for the choice, it is a
50
+ * coincidence that caught it. Widening the union would have compiled and
51
+ * shipped the refresh bug.
52
+ *
53
+ * @package @payez/next-mvp
54
+ */
55
+
56
+ import { NextRequest, NextResponse } from 'next/server';
57
+ import { idpFetchJSON } from '../../lib/idp-fetch';
58
+ import { ENV_CONFIG } from '../../config/env';
59
+ import { getTokenTestAware } from '../../lib/test-aware-get-token';
60
+ import { transitionTo2FASession } from '../../lib/session-store';
61
+ import { jwtDecode } from '../../lib/jwt-decode';
62
+
63
+ export async function POST(req: NextRequest) {
64
+ try {
65
+ const body = await req.json();
66
+ const code = body.code || body.backupCode || body.verificationCode || body.verification_code;
67
+
68
+ if (!code) {
69
+ return NextResponse.json(
70
+ {
71
+ success: false,
72
+ error: 'Backup code is required',
73
+ code: 'INVALID_REQUEST',
74
+ },
75
+ { status: 400 }
76
+ );
77
+ }
78
+
79
+ const result = await idpFetchJSON(
80
+ req,
81
+ `${ENV_CONFIG.IDP_URL}/api/ExternalAuth/twofa/backup-code/verify`,
82
+ {
83
+ method: 'POST',
84
+ headers: { 'Content-Type': 'application/json' },
85
+ body: JSON.stringify({ code }),
86
+ }
87
+ );
88
+
89
+ if (!result.ok) {
90
+ return NextResponse.json(
91
+ {
92
+ success: false,
93
+ error: result.json?.message || 'Verification failed',
94
+ code: result.json?.code || 'IDP_ERROR',
95
+ meta: { attemptedRefresh: result.attemptedRefresh },
96
+ },
97
+ { status: result.status }
98
+ );
99
+ }
100
+
101
+ const unwrappedData = result.json?.data || result.json;
102
+
103
+ // Only a challenge that returns fresh tokens may transition the session.
104
+ let sessionTransitioned = false;
105
+
106
+ if (unwrappedData.access_token && unwrappedData.refresh_token) {
107
+ const token = await getTokenTestAware(req);
108
+ const sessionToken = (token?.sessionToken || token?.redisSessionId) as string | undefined;
109
+
110
+ if (sessionToken) {
111
+ let accessTokenExpires = Date.now() + 15 * 60 * 1000;
112
+ try {
113
+ const decoded = jwtDecode<{ exp?: number }>(unwrappedData.access_token);
114
+ if (decoded?.exp) accessTokenExpires = decoded.exp * 1000;
115
+ } catch {
116
+ console.warn('[VERIFY_BACKUP_CODE] Could not decode access token, using default expiration');
117
+ }
118
+
119
+ let refreshTokenExpires = Date.now() + 3 * 24 * 60 * 60 * 1000;
120
+ try {
121
+ const decoded = jwtDecode<{ exp?: number }>(unwrappedData.refresh_token);
122
+ if (decoded?.exp) refreshTokenExpires = decoded.exp * 1000;
123
+ } catch {
124
+ // Refresh token may carry no exp claim; default stands.
125
+ }
126
+
127
+ await transitionTo2FASession(
128
+ sessionToken,
129
+ {
130
+ accessToken: unwrappedData.access_token,
131
+ refreshToken: unwrappedData.refresh_token,
132
+ accessTokenExpires,
133
+ refreshTokenExpires,
134
+ },
135
+ // 'totp' is deliberate and load-bearing. See "THE STORED 2FA METHOD"
136
+ // in the file header before changing it.
137
+ 'totp'
138
+ );
139
+
140
+ sessionTransitioned = true;
141
+ console.log('[VERIFY_BACKUP_CODE] Session transitioned to 2FA-verified');
142
+ } else {
143
+ console.warn('[VERIFY_BACKUP_CODE] IDP accepted the code but no session token was resolvable — session NOT transitioned. THE CODE IS ALREADY SPENT.');
144
+ }
145
+ } else {
146
+ console.warn('[VERIFY_BACKUP_CODE] IDP returned 2xx without tokens — session NOT transitioned. THE CODE IS ALREADY SPENT.');
147
+ }
148
+
149
+ // twoFactorSessionVerified reports WHAT ACTUALLY HAPPENED, never a copy of
150
+ // `success`. It matters more here than anywhere else: the code is consumed
151
+ // the moment the IDP accepts it, so a client that trusted a hardcoded true
152
+ // would show the user as verified, leave the session unverified, and have
153
+ // burned one of their ten recovery codes to do it.
154
+ return NextResponse.json(
155
+ {
156
+ success: true,
157
+ verificationSuccessful: true,
158
+ twoFactorSessionVerified: sessionTransitioned,
159
+ codeConsumed: true,
160
+ message: unwrappedData.message || 'Backup code verified successfully',
161
+ },
162
+ { status: 200 }
163
+ );
164
+ } catch (error) {
165
+ console.error('[VERIFY_BACKUP_CODE] Error:', error);
166
+ return NextResponse.json(
167
+ {
168
+ success: false,
169
+ error: 'Failed to verify backup code',
170
+ code: 'INTERNAL_ERROR',
171
+ },
172
+ { status: 500 }
173
+ );
174
+ }
175
+ }
@@ -0,0 +1,41 @@
1
+ import { NextRequest, NextResponse } from 'next/server';
2
+ import { idpFetchJSON } from '../../lib/idp-fetch';
3
+ import { ENV_CONFIG } from '../../config/env';
4
+
5
+ /**
6
+ * Generate MFA backup codes (POST /api/Account/mfa/backup-codes, user JWT).
7
+ * Regeneration REPLACES the prior set — the response carries the new codes
8
+ * once; they are shown once and never retrievable again.
9
+ */
10
+ export async function POST(req: NextRequest) {
11
+ let body = '{}';
12
+ try {
13
+ const raw = await req.text();
14
+ if (raw && raw.trim().length > 0) body = raw;
15
+ } catch {}
16
+
17
+ const result = await idpFetchJSON(req, `${ENV_CONFIG.IDP_URL}/api/Account/mfa/backup-codes`, {
18
+ method: 'POST',
19
+ headers: { 'Content-Type': 'application/json' },
20
+ body,
21
+ });
22
+
23
+ if (!result.ok) {
24
+ return NextResponse.json(
25
+ {
26
+ success: false,
27
+ message: 'Upstream error',
28
+ error: { code: 'UPSTREAM_SERVICE_ERROR', status: result.status, details: result.json },
29
+ meta: { attemptedRefresh: result.attemptedRefresh },
30
+ },
31
+ { status: result.status },
32
+ );
33
+ }
34
+
35
+ const bodyJson: any = result.json;
36
+ if (bodyJson && typeof bodyJson === 'object' && 'success' in bodyJson && 'data' in bodyJson) {
37
+ if (bodyJson.success === true) return NextResponse.json(bodyJson.data, { status: 200 });
38
+ return NextResponse.json(bodyJson, { status: 200 });
39
+ }
40
+ return NextResponse.json(bodyJson ?? {}, { status: 200 });
41
+ }
@@ -0,0 +1,46 @@
1
+ import { NextRequest, NextResponse } from 'next/server';
2
+ import { idpFetchJSON } from '../../lib/idp-fetch';
3
+ import { ENV_CONFIG } from '../../config/env';
4
+
5
+ /**
6
+ * MFA methods (GET list / DELETE one, /api/Account/mfa/methods[/{id}],
7
+ * user JWT). Drives the method picker: an EMPTY list must route the user to
8
+ * ENROLMENT, never to a verify screen for a factor they do not hold.
9
+ */
10
+
11
+ function upstreamError(result: { status: number; json: unknown; attemptedRefresh: boolean }) {
12
+ return NextResponse.json(
13
+ {
14
+ success: false,
15
+ message: 'Upstream error',
16
+ error: { code: 'UPSTREAM_SERVICE_ERROR', status: result.status, details: result.json },
17
+ meta: { attemptedRefresh: result.attemptedRefresh },
18
+ },
19
+ { status: result.status },
20
+ );
21
+ }
22
+
23
+ function passthrough(json: unknown) {
24
+ const bodyJson: any = json;
25
+ if (bodyJson && typeof bodyJson === 'object' && 'success' in bodyJson && 'data' in bodyJson) {
26
+ if (bodyJson.success === true) return NextResponse.json(bodyJson.data ?? { success: true }, { status: 200 });
27
+ return NextResponse.json(bodyJson, { status: 200 });
28
+ }
29
+ return NextResponse.json(bodyJson ?? { success: true }, { status: 200 });
30
+ }
31
+
32
+ export async function GET(req: NextRequest) {
33
+ const result = await idpFetchJSON(req, `${ENV_CONFIG.IDP_URL}/api/Account/mfa/methods`, { method: 'GET' });
34
+ if (!result.ok) return upstreamError(result);
35
+ return passthrough(result.json);
36
+ }
37
+
38
+ export async function DELETE(req: NextRequest, id: string) {
39
+ const result = await idpFetchJSON(
40
+ req,
41
+ `${ENV_CONFIG.IDP_URL}/api/Account/mfa/methods/${encodeURIComponent(id)}`,
42
+ { method: 'DELETE' },
43
+ );
44
+ if (!result.ok) return upstreamError(result);
45
+ return passthrough(result.json);
46
+ }
@@ -0,0 +1,42 @@
1
+ import { NextRequest, NextResponse } from 'next/server';
2
+ import { idpFetchJSON } from '../../lib/idp-fetch';
3
+ import { ENV_CONFIG } from '../../config/env';
4
+
5
+ /**
6
+ * Confirm TOTP enrolment with the first authenticator code
7
+ * (POST /api/Account/mfa/totp/confirm, user JWT). Body forwarded verbatim —
8
+ * it carries the enrolment handle plus the code. Only after this succeeds is
9
+ * the method ACTIVE.
10
+ */
11
+ export async function POST(req: NextRequest) {
12
+ let body = '{}';
13
+ try {
14
+ const raw = await req.text();
15
+ if (raw && raw.trim().length > 0) body = raw;
16
+ } catch {}
17
+
18
+ const result = await idpFetchJSON(req, `${ENV_CONFIG.IDP_URL}/api/Account/mfa/totp/confirm`, {
19
+ method: 'POST',
20
+ headers: { 'Content-Type': 'application/json' },
21
+ body,
22
+ });
23
+
24
+ if (!result.ok) {
25
+ return NextResponse.json(
26
+ {
27
+ success: false,
28
+ message: 'Upstream error',
29
+ error: { code: 'UPSTREAM_SERVICE_ERROR', status: result.status, details: result.json },
30
+ meta: { attemptedRefresh: result.attemptedRefresh },
31
+ },
32
+ { status: result.status },
33
+ );
34
+ }
35
+
36
+ const bodyJson: any = result.json;
37
+ if (bodyJson && typeof bodyJson === 'object' && 'success' in bodyJson && 'data' in bodyJson) {
38
+ if (bodyJson.success === true) return NextResponse.json(bodyJson.data, { status: 200 });
39
+ return NextResponse.json(bodyJson, { status: 200 });
40
+ }
41
+ return NextResponse.json(bodyJson ?? {}, { status: 200 });
42
+ }
@@ -0,0 +1,42 @@
1
+ import { NextRequest, NextResponse } from 'next/server';
2
+ import { idpFetchJSON } from '../../lib/idp-fetch';
3
+ import { ENV_CONFIG } from '../../config/env';
4
+
5
+ /**
6
+ * Begin TOTP enrolment (POST /api/Account/mfa/totp/enroll, user JWT).
7
+ * Returns the shared secret / otpauth URI for the QR. An enrolment left
8
+ * UNCONFIRMED is pending — it can only be RESTARTED, and must never render
9
+ * as "Active" (MFA honesty fixes, 2026-08-01).
10
+ */
11
+ export async function POST(req: NextRequest) {
12
+ let body = '{}';
13
+ try {
14
+ const raw = await req.text();
15
+ if (raw && raw.trim().length > 0) body = raw;
16
+ } catch {}
17
+
18
+ const result = await idpFetchJSON(req, `${ENV_CONFIG.IDP_URL}/api/Account/mfa/totp/enroll`, {
19
+ method: 'POST',
20
+ headers: { 'Content-Type': 'application/json' },
21
+ body,
22
+ });
23
+
24
+ if (!result.ok) {
25
+ return NextResponse.json(
26
+ {
27
+ success: false,
28
+ message: 'Upstream error',
29
+ error: { code: 'UPSTREAM_SERVICE_ERROR', status: result.status, details: result.json },
30
+ meta: { attemptedRefresh: result.attemptedRefresh },
31
+ },
32
+ { status: result.status },
33
+ );
34
+ }
35
+
36
+ const bodyJson: any = result.json;
37
+ if (bodyJson && typeof bodyJson === 'object' && 'success' in bodyJson && 'data' in bodyJson) {
38
+ if (bodyJson.success === true) return NextResponse.json(bodyJson.data, { status: 200 });
39
+ return NextResponse.json(bodyJson, { status: 200 });
40
+ }
41
+ return NextResponse.json(bodyJson ?? {}, { status: 200 });
42
+ }
@@ -0,0 +1,156 @@
1
+ /**
2
+ * Verify TOTP 2FA Challenge Handler
3
+ *
4
+ * Verifies an authenticator-app code AT LOGIN and completes the 2FA flow,
5
+ * transitioning the session to MFA-verified.
6
+ *
7
+ * WHY THIS EXISTS (2026-08-02)
8
+ * The package shipped TOTP ENROLMENT (totp-enroll, totp-confirm, against
9
+ * /api/Account/mfa/totp/*) but no TOTP CHALLENGE. SMS and email both had one
10
+ * (verify-sms, verify-email, against /api/ExternalAuth/twofa/*), so TOTP could
11
+ * be enrolled and then never used to satisfy a login challenge — mfaVerified
12
+ * stayed false forever for authenticator-app users, even though the IDP
13
+ * advertises totp in allowed2FAMethods and exposes the endpoint.
14
+ *
15
+ * DO NOT "FIX" THIS BY MAKING totp-confirm TRANSITION THE SESSION. Three people
16
+ * proposed exactly that on the grounds that its SMS/email "siblings" do it. They
17
+ * are not siblings: totp-confirm is ENROLMENT. Flipping mfaVerified there would
18
+ * mean enrolling a factor counts as passing a challenge, letting a
19
+ * password-only session self-promote to MFA-verified by adding an
20
+ * authenticator. Enrolment must never set mfaVerified.
21
+ *
22
+ * FIELD NAME: the IDP expects { "code": ... } here
23
+ * (MfaTotpVerifyRequest, [JsonPropertyName("code")]), NOT the
24
+ * { "verification_code": ... } that the SMS endpoint takes. Copying verify-sms
25
+ * and changing only the URL produces a handler that reaches the IDP and is
26
+ * rejected, which reads as "wrong code" rather than "wrong shape".
27
+ *
28
+ * @package @payez/next-mvp
29
+ */
30
+
31
+ import { NextRequest, NextResponse } from 'next/server';
32
+ import { idpFetchJSON } from '../../lib/idp-fetch';
33
+ import { ENV_CONFIG } from '../../config/env';
34
+ import { getTokenTestAware } from '../../lib/test-aware-get-token';
35
+ import { transitionTo2FASession } from '../../lib/session-store';
36
+ import { jwtDecode } from '../../lib/jwt-decode';
37
+
38
+ export async function POST(req: NextRequest) {
39
+ try {
40
+ const body = await req.json();
41
+ // Accept the same aliases the client might send; the IDP field is `code`.
42
+ const code = body.code || body.totpCode || body.verificationCode || body.verification_code;
43
+
44
+ if (!code) {
45
+ return NextResponse.json(
46
+ {
47
+ success: false,
48
+ error: 'Authenticator code is required',
49
+ code: 'INVALID_REQUEST',
50
+ },
51
+ { status: 400 }
52
+ );
53
+ }
54
+
55
+ // idpFetchJSON injects the caller's Bearer from the session store.
56
+ const result = await idpFetchJSON(
57
+ req,
58
+ `${ENV_CONFIG.IDP_URL}/api/ExternalAuth/twofa/totp/verify`,
59
+ {
60
+ method: 'POST',
61
+ headers: { 'Content-Type': 'application/json' },
62
+ body: JSON.stringify({ code }),
63
+ }
64
+ );
65
+
66
+ if (!result.ok) {
67
+ return NextResponse.json(
68
+ {
69
+ success: false,
70
+ error: result.json?.message || 'Verification failed',
71
+ code: result.json?.code || 'IDP_ERROR',
72
+ meta: { attemptedRefresh: result.attemptedRefresh },
73
+ },
74
+ { status: result.status }
75
+ );
76
+ }
77
+
78
+ // Unwrap IDP envelope { success, data }
79
+ const unwrappedData = result.json?.data || result.json;
80
+
81
+ // Only a successful challenge that returns fresh tokens may transition the
82
+ // session. No tokens => no transition: we must not mark 2FA complete on the
83
+ // strength of a 200 alone.
84
+ let sessionTransitioned = false;
85
+
86
+ if (unwrappedData.access_token && unwrappedData.refresh_token) {
87
+ const token = await getTokenTestAware(req);
88
+ const sessionToken = (token?.sessionToken || token?.redisSessionId) as string | undefined;
89
+
90
+ if (sessionToken) {
91
+ let accessTokenExpires = Date.now() + 15 * 60 * 1000;
92
+ try {
93
+ const decoded = jwtDecode<{ exp?: number }>(unwrappedData.access_token);
94
+ if (decoded?.exp) accessTokenExpires = decoded.exp * 1000;
95
+ } catch {
96
+ console.warn('[VERIFY_TOTP] Could not decode access token, using default expiration');
97
+ }
98
+
99
+ let refreshTokenExpires = Date.now() + 3 * 24 * 60 * 60 * 1000;
100
+ try {
101
+ const decoded = jwtDecode<{ exp?: number }>(unwrappedData.refresh_token);
102
+ if (decoded?.exp) refreshTokenExpires = decoded.exp * 1000;
103
+ } catch {
104
+ // Refresh token may carry no exp claim; default stands.
105
+ }
106
+
107
+ await transitionTo2FASession(
108
+ sessionToken,
109
+ {
110
+ accessToken: unwrappedData.access_token,
111
+ refreshToken: unwrappedData.refresh_token,
112
+ accessTokenExpires,
113
+ refreshTokenExpires,
114
+ },
115
+ 'totp' // 2FA method, used by the refresh-token flow
116
+ );
117
+
118
+ sessionTransitioned = true;
119
+ console.log('[VERIFY_TOTP] Session transitioned to 2FA-verified');
120
+ } else {
121
+ console.warn('[VERIFY_TOTP] IDP verified the code but no session token was resolvable — session NOT transitioned');
122
+ }
123
+ } else {
124
+ console.warn('[VERIFY_TOTP] IDP returned 2xx without tokens — session NOT transitioned');
125
+ }
126
+
127
+ // Do not expose tokens to the client.
128
+ //
129
+ // twoFactorSessionVerified REPORTS WHAT ACTUALLY HAPPENED. It is NOT a copy
130
+ // of `success`. The code can verify at the IDP while the session is not
131
+ // transitioned — no tokens returned, or no resolvable session token — and a
132
+ // client that trusted a hardcoded `true` would show the user as MFA-verified
133
+ // while the session still says otherwise. That divergence between the guard
134
+ // and the report is the defect this field exists to avoid.
135
+ // (verify-sms.ts hardcodes it true and has the same flaw — reported upstream.)
136
+ return NextResponse.json(
137
+ {
138
+ success: true,
139
+ verificationSuccessful: true,
140
+ twoFactorSessionVerified: sessionTransitioned,
141
+ message: unwrappedData.message || 'Authenticator code verified successfully',
142
+ },
143
+ { status: 200 }
144
+ );
145
+ } catch (error) {
146
+ console.error('[VERIFY_TOTP] Error:', error);
147
+ return NextResponse.json(
148
+ {
149
+ success: false,
150
+ error: 'Failed to verify code',
151
+ code: 'INTERNAL_ERROR',
152
+ },
153
+ { status: 500 }
154
+ );
155
+ }
156
+ }