@payez/next-mvp 4.1.10 → 4.1.20

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 (181) 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/mfa/backup-code-verify.d.ts +73 -0
  12. package/dist/api-handlers/mfa/backup-code-verify.js +153 -0
  13. package/dist/api-handlers/mfa/backup-codes.d.ts +7 -0
  14. package/dist/api-handlers/mfa/backup-codes.js +40 -0
  15. package/dist/api-handlers/mfa/methods.d.ts +3 -0
  16. package/dist/api-handlers/mfa/methods.js +41 -0
  17. package/dist/api-handlers/mfa/totp-confirm.d.ts +8 -0
  18. package/dist/api-handlers/mfa/totp-confirm.js +41 -0
  19. package/dist/api-handlers/mfa/totp-enroll.d.ts +8 -0
  20. package/dist/api-handlers/mfa/totp-enroll.js +41 -0
  21. package/dist/api-handlers/mfa/totp-verify.d.ts +47 -0
  22. package/dist/api-handlers/mfa/totp-verify.js +134 -0
  23. package/dist/api-handlers/passkeys/list.d.ts +7 -0
  24. package/dist/api-handlers/passkeys/list.js +29 -0
  25. package/dist/api-handlers/passkeys/manage.d.ts +3 -0
  26. package/dist/api-handlers/passkeys/manage.js +54 -0
  27. package/dist/api-handlers/passkeys/register-options.d.ts +8 -0
  28. package/dist/api-handlers/passkeys/register-options.js +41 -0
  29. package/dist/api-handlers/passkeys/register-verify.d.ts +7 -0
  30. package/dist/api-handlers/passkeys/register-verify.js +40 -0
  31. package/dist/api-handlers/session/viability.js +19 -0
  32. package/dist/auth/better-auth.d.ts +68 -5
  33. package/dist/auth/better-auth.js +271 -45
  34. package/dist/auth/utils/idp-client.d.ts +13 -22
  35. package/dist/auth/utils/idp-client.js +12 -82
  36. package/dist/client/better-auth-client.d.ts +14 -2
  37. package/dist/lib/ensure-fresh-access-token.js +13 -2
  38. package/dist/lib/session-store.js +28 -21
  39. package/dist/lib/startup-init.js +19 -19
  40. package/dist/lib/token-lifecycle.d.ts +2 -0
  41. package/dist/lib/token-lifecycle.js +61 -7
  42. package/dist/models/SessionModel.d.ts +17 -0
  43. package/dist/pages/login/page.d.ts +10 -1
  44. package/dist/pages/login/page.js +69 -80
  45. package/dist/pages/verify-code/page.d.ts +10 -1
  46. package/dist/pages/verify-code/page.js +72 -4
  47. package/dist/routes/auth/passkey-signin.d.ts +13 -0
  48. package/dist/routes/auth/passkey-signin.js +18 -0
  49. package/dist/routes/auth/viability.d.ts +2 -0
  50. package/dist/routes/auth/viability.js +88 -0
  51. package/dist/routes/mfa/backup-code-verify.d.ts +1 -0
  52. package/dist/routes/mfa/backup-code-verify.js +5 -0
  53. package/dist/routes/mfa/backup-codes.d.ts +10 -0
  54. package/dist/routes/mfa/backup-codes.js +14 -0
  55. package/dist/routes/mfa/methods.d.ts +21 -0
  56. package/dist/routes/mfa/methods.js +10 -0
  57. package/dist/routes/mfa/totp-confirm.d.ts +10 -0
  58. package/dist/routes/mfa/totp-confirm.js +14 -0
  59. package/dist/routes/mfa/totp-enroll.d.ts +10 -0
  60. package/dist/routes/mfa/totp-enroll.js +14 -0
  61. package/dist/routes/mfa/totp-verify.d.ts +14 -0
  62. package/dist/routes/mfa/totp-verify.js +18 -0
  63. package/dist/routes/passkeys/list.d.ts +10 -0
  64. package/dist/routes/passkeys/list.js +14 -0
  65. package/dist/routes/passkeys/manage.d.ts +18 -0
  66. package/dist/routes/passkeys/manage.js +13 -0
  67. package/dist/routes/passkeys/register-options.d.ts +10 -0
  68. package/dist/routes/passkeys/register-options.js +14 -0
  69. package/dist/routes/passkeys/register-verify.d.ts +10 -0
  70. package/dist/routes/passkeys/register-verify.js +14 -0
  71. package/dist/server/auth.d.ts +2 -2
  72. package/dist/server/decode-session.js +37 -3
  73. package/package.json +958 -893
  74. package/scripts/check-internal-url-usage.sh +73 -73
  75. package/src/api/index.ts +17 -17
  76. package/src/api-handlers/account/masked-info.ts +45 -45
  77. package/src/api-handlers/account/profile.ts +99 -80
  78. package/src/api-handlers/account/recovery/initiate.ts +23 -23
  79. package/src/api-handlers/account/recovery/send-code.ts +73 -25
  80. package/src/api-handlers/account/recovery/verify-code.ts +73 -25
  81. package/src/api-handlers/account/reset-password.ts +23 -23
  82. package/src/api-handlers/account/send-code.ts +76 -76
  83. package/src/api-handlers/account/validate-password.ts +118 -118
  84. package/src/api-handlers/account/verify-email.ts +15 -1
  85. package/src/api-handlers/account/verify-sms.ts +15 -1
  86. package/src/api-handlers/admin/stats.ts +249 -249
  87. package/src/api-handlers/anon/preferences.ts +123 -123
  88. package/src/api-handlers/auth/jwks.ts +20 -20
  89. package/src/api-handlers/auth/login.ts +240 -240
  90. package/src/api-handlers/auth/passkey-signin.ts +98 -0
  91. package/src/api-handlers/auth/validate.ts +43 -43
  92. package/src/api-handlers/mfa/backup-code-verify.ts +175 -0
  93. package/src/api-handlers/mfa/backup-codes.ts +41 -0
  94. package/src/api-handlers/mfa/methods.ts +46 -0
  95. package/src/api-handlers/mfa/totp-confirm.ts +42 -0
  96. package/src/api-handlers/mfa/totp-enroll.ts +42 -0
  97. package/src/api-handlers/mfa/totp-verify.ts +156 -0
  98. package/src/api-handlers/passkeys/list.ts +31 -0
  99. package/src/api-handlers/passkeys/manage.ts +54 -0
  100. package/src/api-handlers/passkeys/register-options.ts +42 -0
  101. package/src/api-handlers/passkeys/register-verify.ts +41 -0
  102. package/src/api-handlers/session/viability.ts +161 -142
  103. package/src/auth/better-auth.ts +708 -455
  104. package/src/auth/unauthenticated-routes.ts +2 -2
  105. package/src/auth/utils/idp-client.ts +13 -95
  106. package/src/client/better-auth-client.ts +70 -70
  107. package/src/client/fetchWithSession.ts +21 -21
  108. package/src/client/index.ts +13 -13
  109. package/src/client/useAnonSession.ts +131 -131
  110. package/src/components/admin/VibeAdminContext.tsx +87 -87
  111. package/src/config/logging-config.ts +82 -82
  112. package/src/config/unauthenticated-routes.ts +19 -19
  113. package/src/edge/internal-api-url.ts +65 -65
  114. package/src/edge/middleware.ts +42 -42
  115. package/src/hooks/useProfile.ts +75 -75
  116. package/src/lib/anon-session.ts +213 -213
  117. package/src/lib/auth-secret.ts +137 -137
  118. package/src/lib/demo-mode.ts +17 -17
  119. package/src/lib/ensure-fresh-access-token.ts +13 -2
  120. package/src/lib/idp-client-config.ts +559 -559
  121. package/src/lib/idp-fetch.ts +126 -126
  122. package/src/lib/internal-api.ts +171 -171
  123. package/src/lib/jwt-decode-client.ts +45 -45
  124. package/src/lib/rate-limit-service.ts +9 -9
  125. package/src/lib/redis.ts +26 -26
  126. package/src/lib/refresh-token-validator.ts +64 -64
  127. package/src/lib/secret-validation.ts +8 -8
  128. package/src/lib/session-store.ts +702 -695
  129. package/src/lib/session.ts +34 -34
  130. package/src/lib/startup-init.ts +251 -251
  131. package/src/lib/token-expiry.ts +40 -40
  132. package/src/lib/token-lifecycle.ts +533 -470
  133. package/src/lib/types/api-responses.ts +336 -336
  134. package/src/middleware/auth-decision.ts +43 -43
  135. package/src/models/DecodedAccessToken.ts +16 -16
  136. package/src/models/SessionModel.ts +282 -264
  137. package/src/pages/admin-roles/index.ts +9 -9
  138. package/src/pages/login/page.tsx +123 -228
  139. package/src/pages/security/EnhancedSecurityPage.tsx +9 -9
  140. package/src/pages/verify-code/page.tsx +71 -5
  141. package/src/routes/account/index.ts +31 -31
  142. package/src/routes/account/masked-info.ts +36 -36
  143. package/src/routes/account/send-code.ts +39 -39
  144. package/src/routes/account/verify-email.ts +40 -40
  145. package/src/routes/account/verify-sms.ts +40 -40
  146. package/src/routes/auth/index.ts +22 -22
  147. package/src/routes/auth/passkey-signin.ts +13 -0
  148. package/src/routes/auth/refresh.ts +48 -48
  149. package/src/routes/auth/session.ts +166 -166
  150. package/src/routes/auth/viability.ts +89 -0
  151. package/src/routes/index.ts +17 -17
  152. package/src/routes/mfa/backup-code-verify.ts +1 -0
  153. package/src/routes/mfa/backup-codes.ts +10 -0
  154. package/src/routes/mfa/methods.ts +22 -0
  155. package/src/routes/mfa/totp-confirm.ts +10 -0
  156. package/src/routes/mfa/totp-enroll.ts +10 -0
  157. package/src/routes/mfa/totp-verify.ts +14 -0
  158. package/src/routes/passkeys/list.ts +10 -0
  159. package/src/routes/passkeys/manage.ts +23 -0
  160. package/src/routes/passkeys/register-options.ts +10 -0
  161. package/src/routes/passkeys/register-verify.ts +10 -0
  162. package/src/routes/session/index.ts +7 -7
  163. package/src/routes/session/refresh-viability.ts +17 -17
  164. package/src/server/auth.ts +373 -373
  165. package/src/server/decode-session.ts +235 -202
  166. package/src/services/signalrActivityService.ts +258 -258
  167. package/src/theme/ThemeProvider.tsx +39 -39
  168. package/src/theme/default.ts +33 -33
  169. package/src/theme/index.ts +31 -31
  170. package/src/theme/types.ts +69 -69
  171. package/src/theme/useTheme.ts +57 -57
  172. package/src/theme/utils.ts +40 -40
  173. package/src/types/api.ts +12 -12
  174. package/src/types/auth.d.ts +23 -23
  175. package/src/types/auth.ts +22 -22
  176. package/src/types/logging.ts +11 -11
  177. package/src/types/recovery.ts +54 -54
  178. package/src/utils/api.ts +353 -353
  179. package/src/utils/circuitBreaker.ts +40 -40
  180. package/src/utils/error-message.ts +108 -108
  181. package/src/utils/layout/reservedSpace.ts +124 -124
@@ -0,0 +1,73 @@
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
+ import { NextRequest, NextResponse } from 'next/server';
56
+ export declare function POST(req: NextRequest): Promise<NextResponse<{
57
+ success: boolean;
58
+ error: string;
59
+ code: string;
60
+ }> | NextResponse<{
61
+ success: boolean;
62
+ error: any;
63
+ code: any;
64
+ meta: {
65
+ attemptedRefresh: boolean;
66
+ };
67
+ }> | NextResponse<{
68
+ success: boolean;
69
+ verificationSuccessful: boolean;
70
+ twoFactorSessionVerified: boolean;
71
+ codeConsumed: boolean;
72
+ message: any;
73
+ }>>;
@@ -0,0 +1,153 @@
1
+ "use strict";
2
+ /**
3
+ * Verify Backup Code 2FA Challenge Handler
4
+ *
5
+ * Verifies a single-use recovery code AT LOGIN and completes the 2FA flow,
6
+ * transitioning the session to MFA-verified.
7
+ *
8
+ * WHY THIS EXISTS (2026-08-02)
9
+ * The package shipped backup-code GENERATION (backup-codes.ts, POST
10
+ * /api/Account/mfa/backup-codes) and no way to SPEND one. Codes could be
11
+ * generated, displayed once, written down — and then never used to satisfy a
12
+ * login challenge. Exactly the gap TOTP had before totp-verify: the enrolment
13
+ * half without the challenge half.
14
+ *
15
+ * THIS IS THE FACTOR OF LAST RESORT. A user reaches for a backup code when they
16
+ * have lost the authenticator, so it is the one path that must work when
17
+ * everything else has already failed. A recovery mechanism that cannot be
18
+ * redeemed is worse than none: it invites people to rely on it.
19
+ *
20
+ * FIELD NAME: the IDP expects { "code": ... }
21
+ * (MfaBackupCodeVerifyRequest, [JsonPropertyName("code")]). The dash in
22
+ * 'xxxx-xxxx' is optional per the IDP contract, so the code is forwarded as
23
+ * typed and normalisation is left to the IDP rather than guessed here.
24
+ *
25
+ * SINGLE USE, CONSUMED ATOMICALLY. The IDP hash-compares against unused codes
26
+ * and stamps used_at + used_by_ip in the same operation (MfaController 5g).
27
+ * NEVER retry this call on a network error or an ambiguous response — a retry
28
+ * can burn a second code, and the user has ten.
29
+ *
30
+ * DO NOT MAKE GENERATION TRANSITION THE SESSION, the same trap totp-confirm
31
+ * carries: generating recovery codes is not proof of possessing one.
32
+ *
33
+ * THE STORED 2FA METHOD IS 'totp', NOT 'backup_code'. READ THIS BEFORE
34
+ * "CORRECTING" IT — it looks wrong and is not.
35
+ *
36
+ * 1. IT MATCHES THE IDP. MfaController 5g sets
37
+ * `TwoFactorMethod = TwoFactorMethodType.Totp` for this exact path,
38
+ * commented "Backup code = recovery proof of the TOTP factor", and the
39
+ * reissued token's amr carries mfa+totp. A backup code is not a separate
40
+ * factor; it is recovery proof of the authenticator factor.
41
+ *
42
+ * 2. INVENTING A NEW VALUE SILENTLY BREAKS TOKEN REFRESH. refresh.ts:279
43
+ * resolves the method with ['sms','totp','email'].includes(m). Anything
44
+ * outside that set is dropped, so `two_factor_method` never reaches the
45
+ * IDP on refresh, and a session established with a recovery code refreshes
46
+ * differently from one established with the authenticator — for the same
47
+ * underlying factor. It fails quietly, days later, as "sessions
48
+ * occasionally drop", with nothing pointing back to this string.
49
+ *
50
+ * The type union (email|sms|totp) is not the reason for the choice, it is a
51
+ * coincidence that caught it. Widening the union would have compiled and
52
+ * shipped the refresh bug.
53
+ *
54
+ * @package @payez/next-mvp
55
+ */
56
+ Object.defineProperty(exports, "__esModule", { value: true });
57
+ exports.POST = POST;
58
+ const server_1 = require("next/server");
59
+ const idp_fetch_1 = require("../../lib/idp-fetch");
60
+ const env_1 = require("../../config/env");
61
+ const test_aware_get_token_1 = require("../../lib/test-aware-get-token");
62
+ const session_store_1 = require("../../lib/session-store");
63
+ const jwt_decode_1 = require("../../lib/jwt-decode");
64
+ async function POST(req) {
65
+ try {
66
+ const body = await req.json();
67
+ const code = body.code || body.backupCode || body.verificationCode || body.verification_code;
68
+ if (!code) {
69
+ return server_1.NextResponse.json({
70
+ success: false,
71
+ error: 'Backup code is required',
72
+ code: 'INVALID_REQUEST',
73
+ }, { status: 400 });
74
+ }
75
+ const result = await (0, idp_fetch_1.idpFetchJSON)(req, `${env_1.ENV_CONFIG.IDP_URL}/api/ExternalAuth/twofa/backup-code/verify`, {
76
+ method: 'POST',
77
+ headers: { 'Content-Type': 'application/json' },
78
+ body: JSON.stringify({ code }),
79
+ });
80
+ if (!result.ok) {
81
+ return server_1.NextResponse.json({
82
+ success: false,
83
+ error: result.json?.message || 'Verification failed',
84
+ code: result.json?.code || 'IDP_ERROR',
85
+ meta: { attemptedRefresh: result.attemptedRefresh },
86
+ }, { status: result.status });
87
+ }
88
+ const unwrappedData = result.json?.data || result.json;
89
+ // Only a challenge that returns fresh tokens may transition the session.
90
+ let sessionTransitioned = false;
91
+ if (unwrappedData.access_token && unwrappedData.refresh_token) {
92
+ const token = await (0, test_aware_get_token_1.getTokenTestAware)(req);
93
+ const sessionToken = (token?.sessionToken || token?.redisSessionId);
94
+ if (sessionToken) {
95
+ let accessTokenExpires = Date.now() + 15 * 60 * 1000;
96
+ try {
97
+ const decoded = (0, jwt_decode_1.jwtDecode)(unwrappedData.access_token);
98
+ if (decoded?.exp)
99
+ accessTokenExpires = decoded.exp * 1000;
100
+ }
101
+ catch {
102
+ console.warn('[VERIFY_BACKUP_CODE] Could not decode access token, using default expiration');
103
+ }
104
+ let refreshTokenExpires = Date.now() + 3 * 24 * 60 * 60 * 1000;
105
+ try {
106
+ const decoded = (0, jwt_decode_1.jwtDecode)(unwrappedData.refresh_token);
107
+ if (decoded?.exp)
108
+ refreshTokenExpires = decoded.exp * 1000;
109
+ }
110
+ catch {
111
+ // Refresh token may carry no exp claim; default stands.
112
+ }
113
+ await (0, session_store_1.transitionTo2FASession)(sessionToken, {
114
+ accessToken: unwrappedData.access_token,
115
+ refreshToken: unwrappedData.refresh_token,
116
+ accessTokenExpires,
117
+ refreshTokenExpires,
118
+ },
119
+ // 'totp' is deliberate and load-bearing. See "THE STORED 2FA METHOD"
120
+ // in the file header before changing it.
121
+ 'totp');
122
+ sessionTransitioned = true;
123
+ console.log('[VERIFY_BACKUP_CODE] Session transitioned to 2FA-verified');
124
+ }
125
+ else {
126
+ console.warn('[VERIFY_BACKUP_CODE] IDP accepted the code but no session token was resolvable — session NOT transitioned. THE CODE IS ALREADY SPENT.');
127
+ }
128
+ }
129
+ else {
130
+ console.warn('[VERIFY_BACKUP_CODE] IDP returned 2xx without tokens — session NOT transitioned. THE CODE IS ALREADY SPENT.');
131
+ }
132
+ // twoFactorSessionVerified reports WHAT ACTUALLY HAPPENED, never a copy of
133
+ // `success`. It matters more here than anywhere else: the code is consumed
134
+ // the moment the IDP accepts it, so a client that trusted a hardcoded true
135
+ // would show the user as verified, leave the session unverified, and have
136
+ // burned one of their ten recovery codes to do it.
137
+ return server_1.NextResponse.json({
138
+ success: true,
139
+ verificationSuccessful: true,
140
+ twoFactorSessionVerified: sessionTransitioned,
141
+ codeConsumed: true,
142
+ message: unwrappedData.message || 'Backup code verified successfully',
143
+ }, { status: 200 });
144
+ }
145
+ catch (error) {
146
+ console.error('[VERIFY_BACKUP_CODE] Error:', error);
147
+ return server_1.NextResponse.json({
148
+ success: false,
149
+ error: 'Failed to verify backup code',
150
+ code: 'INTERNAL_ERROR',
151
+ }, { status: 500 });
152
+ }
153
+ }
@@ -0,0 +1,7 @@
1
+ import { NextRequest, NextResponse } from 'next/server';
2
+ /**
3
+ * Generate MFA backup codes (POST /api/Account/mfa/backup-codes, user JWT).
4
+ * Regeneration REPLACES the prior set — the response carries the new codes
5
+ * once; they are shown once and never retrievable again.
6
+ */
7
+ export declare function POST(req: NextRequest): Promise<NextResponse<any>>;
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.POST = POST;
4
+ const server_1 = require("next/server");
5
+ const idp_fetch_1 = require("../../lib/idp-fetch");
6
+ const env_1 = require("../../config/env");
7
+ /**
8
+ * Generate MFA backup codes (POST /api/Account/mfa/backup-codes, user JWT).
9
+ * Regeneration REPLACES the prior set — the response carries the new codes
10
+ * once; they are shown once and never retrievable again.
11
+ */
12
+ async function POST(req) {
13
+ let body = '{}';
14
+ try {
15
+ const raw = await req.text();
16
+ if (raw && raw.trim().length > 0)
17
+ body = raw;
18
+ }
19
+ catch { }
20
+ const result = await (0, idp_fetch_1.idpFetchJSON)(req, `${env_1.ENV_CONFIG.IDP_URL}/api/Account/mfa/backup-codes`, {
21
+ method: 'POST',
22
+ headers: { 'Content-Type': 'application/json' },
23
+ body,
24
+ });
25
+ if (!result.ok) {
26
+ return server_1.NextResponse.json({
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
+ }, { status: result.status });
32
+ }
33
+ const bodyJson = result.json;
34
+ if (bodyJson && typeof bodyJson === 'object' && 'success' in bodyJson && 'data' in bodyJson) {
35
+ if (bodyJson.success === true)
36
+ return server_1.NextResponse.json(bodyJson.data, { status: 200 });
37
+ return server_1.NextResponse.json(bodyJson, { status: 200 });
38
+ }
39
+ return server_1.NextResponse.json(bodyJson ?? {}, { status: 200 });
40
+ }
@@ -0,0 +1,3 @@
1
+ import { NextRequest, NextResponse } from 'next/server';
2
+ export declare function GET(req: NextRequest): Promise<NextResponse<any>>;
3
+ export declare function DELETE(req: NextRequest, id: string): Promise<NextResponse<any>>;
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GET = GET;
4
+ exports.DELETE = DELETE;
5
+ const server_1 = require("next/server");
6
+ const idp_fetch_1 = require("../../lib/idp-fetch");
7
+ const env_1 = require("../../config/env");
8
+ /**
9
+ * MFA methods (GET list / DELETE one, /api/Account/mfa/methods[/{id}],
10
+ * user JWT). Drives the method picker: an EMPTY list must route the user to
11
+ * ENROLMENT, never to a verify screen for a factor they do not hold.
12
+ */
13
+ function upstreamError(result) {
14
+ return server_1.NextResponse.json({
15
+ success: false,
16
+ message: 'Upstream error',
17
+ error: { code: 'UPSTREAM_SERVICE_ERROR', status: result.status, details: result.json },
18
+ meta: { attemptedRefresh: result.attemptedRefresh },
19
+ }, { status: result.status });
20
+ }
21
+ function passthrough(json) {
22
+ const bodyJson = json;
23
+ if (bodyJson && typeof bodyJson === 'object' && 'success' in bodyJson && 'data' in bodyJson) {
24
+ if (bodyJson.success === true)
25
+ return server_1.NextResponse.json(bodyJson.data ?? { success: true }, { status: 200 });
26
+ return server_1.NextResponse.json(bodyJson, { status: 200 });
27
+ }
28
+ return server_1.NextResponse.json(bodyJson ?? { success: true }, { status: 200 });
29
+ }
30
+ async function GET(req) {
31
+ const result = await (0, idp_fetch_1.idpFetchJSON)(req, `${env_1.ENV_CONFIG.IDP_URL}/api/Account/mfa/methods`, { method: 'GET' });
32
+ if (!result.ok)
33
+ return upstreamError(result);
34
+ return passthrough(result.json);
35
+ }
36
+ async function DELETE(req, id) {
37
+ const result = await (0, idp_fetch_1.idpFetchJSON)(req, `${env_1.ENV_CONFIG.IDP_URL}/api/Account/mfa/methods/${encodeURIComponent(id)}`, { method: 'DELETE' });
38
+ if (!result.ok)
39
+ return upstreamError(result);
40
+ return passthrough(result.json);
41
+ }
@@ -0,0 +1,8 @@
1
+ import { NextRequest, NextResponse } from 'next/server';
2
+ /**
3
+ * Confirm TOTP enrolment with the first authenticator code
4
+ * (POST /api/Account/mfa/totp/confirm, user JWT). Body forwarded verbatim —
5
+ * it carries the enrolment handle plus the code. Only after this succeeds is
6
+ * the method ACTIVE.
7
+ */
8
+ export declare function POST(req: NextRequest): Promise<NextResponse<any>>;
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.POST = POST;
4
+ const server_1 = require("next/server");
5
+ const idp_fetch_1 = require("../../lib/idp-fetch");
6
+ const env_1 = require("../../config/env");
7
+ /**
8
+ * Confirm TOTP enrolment with the first authenticator code
9
+ * (POST /api/Account/mfa/totp/confirm, user JWT). Body forwarded verbatim —
10
+ * it carries the enrolment handle plus the code. Only after this succeeds is
11
+ * the method ACTIVE.
12
+ */
13
+ async function POST(req) {
14
+ let body = '{}';
15
+ try {
16
+ const raw = await req.text();
17
+ if (raw && raw.trim().length > 0)
18
+ body = raw;
19
+ }
20
+ catch { }
21
+ const result = await (0, idp_fetch_1.idpFetchJSON)(req, `${env_1.ENV_CONFIG.IDP_URL}/api/Account/mfa/totp/confirm`, {
22
+ method: 'POST',
23
+ headers: { 'Content-Type': 'application/json' },
24
+ body,
25
+ });
26
+ if (!result.ok) {
27
+ return server_1.NextResponse.json({
28
+ success: false,
29
+ message: 'Upstream error',
30
+ error: { code: 'UPSTREAM_SERVICE_ERROR', status: result.status, details: result.json },
31
+ meta: { attemptedRefresh: result.attemptedRefresh },
32
+ }, { status: result.status });
33
+ }
34
+ const bodyJson = result.json;
35
+ if (bodyJson && typeof bodyJson === 'object' && 'success' in bodyJson && 'data' in bodyJson) {
36
+ if (bodyJson.success === true)
37
+ return server_1.NextResponse.json(bodyJson.data, { status: 200 });
38
+ return server_1.NextResponse.json(bodyJson, { status: 200 });
39
+ }
40
+ return server_1.NextResponse.json(bodyJson ?? {}, { status: 200 });
41
+ }
@@ -0,0 +1,8 @@
1
+ import { NextRequest, NextResponse } from 'next/server';
2
+ /**
3
+ * Begin TOTP enrolment (POST /api/Account/mfa/totp/enroll, user JWT).
4
+ * Returns the shared secret / otpauth URI for the QR. An enrolment left
5
+ * UNCONFIRMED is pending — it can only be RESTARTED, and must never render
6
+ * as "Active" (MFA honesty fixes, 2026-08-01).
7
+ */
8
+ export declare function POST(req: NextRequest): Promise<NextResponse<any>>;
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.POST = POST;
4
+ const server_1 = require("next/server");
5
+ const idp_fetch_1 = require("../../lib/idp-fetch");
6
+ const env_1 = require("../../config/env");
7
+ /**
8
+ * Begin TOTP enrolment (POST /api/Account/mfa/totp/enroll, user JWT).
9
+ * Returns the shared secret / otpauth URI for the QR. An enrolment left
10
+ * UNCONFIRMED is pending — it can only be RESTARTED, and must never render
11
+ * as "Active" (MFA honesty fixes, 2026-08-01).
12
+ */
13
+ async function POST(req) {
14
+ let body = '{}';
15
+ try {
16
+ const raw = await req.text();
17
+ if (raw && raw.trim().length > 0)
18
+ body = raw;
19
+ }
20
+ catch { }
21
+ const result = await (0, idp_fetch_1.idpFetchJSON)(req, `${env_1.ENV_CONFIG.IDP_URL}/api/Account/mfa/totp/enroll`, {
22
+ method: 'POST',
23
+ headers: { 'Content-Type': 'application/json' },
24
+ body,
25
+ });
26
+ if (!result.ok) {
27
+ return server_1.NextResponse.json({
28
+ success: false,
29
+ message: 'Upstream error',
30
+ error: { code: 'UPSTREAM_SERVICE_ERROR', status: result.status, details: result.json },
31
+ meta: { attemptedRefresh: result.attemptedRefresh },
32
+ }, { status: result.status });
33
+ }
34
+ const bodyJson = result.json;
35
+ if (bodyJson && typeof bodyJson === 'object' && 'success' in bodyJson && 'data' in bodyJson) {
36
+ if (bodyJson.success === true)
37
+ return server_1.NextResponse.json(bodyJson.data, { status: 200 });
38
+ return server_1.NextResponse.json(bodyJson, { status: 200 });
39
+ }
40
+ return server_1.NextResponse.json(bodyJson ?? {}, { status: 200 });
41
+ }
@@ -0,0 +1,47 @@
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
+ import { NextRequest, NextResponse } from 'next/server';
31
+ export declare function POST(req: NextRequest): Promise<NextResponse<{
32
+ success: boolean;
33
+ error: string;
34
+ code: string;
35
+ }> | NextResponse<{
36
+ success: boolean;
37
+ error: any;
38
+ code: any;
39
+ meta: {
40
+ attemptedRefresh: boolean;
41
+ };
42
+ }> | NextResponse<{
43
+ success: boolean;
44
+ verificationSuccessful: boolean;
45
+ twoFactorSessionVerified: boolean;
46
+ message: any;
47
+ }>>;
@@ -0,0 +1,134 @@
1
+ "use strict";
2
+ /**
3
+ * Verify TOTP 2FA Challenge Handler
4
+ *
5
+ * Verifies an authenticator-app code AT LOGIN and completes the 2FA flow,
6
+ * transitioning the session to MFA-verified.
7
+ *
8
+ * WHY THIS EXISTS (2026-08-02)
9
+ * The package shipped TOTP ENROLMENT (totp-enroll, totp-confirm, against
10
+ * /api/Account/mfa/totp/*) but no TOTP CHALLENGE. SMS and email both had one
11
+ * (verify-sms, verify-email, against /api/ExternalAuth/twofa/*), so TOTP could
12
+ * be enrolled and then never used to satisfy a login challenge — mfaVerified
13
+ * stayed false forever for authenticator-app users, even though the IDP
14
+ * advertises totp in allowed2FAMethods and exposes the endpoint.
15
+ *
16
+ * DO NOT "FIX" THIS BY MAKING totp-confirm TRANSITION THE SESSION. Three people
17
+ * proposed exactly that on the grounds that its SMS/email "siblings" do it. They
18
+ * are not siblings: totp-confirm is ENROLMENT. Flipping mfaVerified there would
19
+ * mean enrolling a factor counts as passing a challenge, letting a
20
+ * password-only session self-promote to MFA-verified by adding an
21
+ * authenticator. Enrolment must never set mfaVerified.
22
+ *
23
+ * FIELD NAME: the IDP expects { "code": ... } here
24
+ * (MfaTotpVerifyRequest, [JsonPropertyName("code")]), NOT the
25
+ * { "verification_code": ... } that the SMS endpoint takes. Copying verify-sms
26
+ * and changing only the URL produces a handler that reaches the IDP and is
27
+ * rejected, which reads as "wrong code" rather than "wrong shape".
28
+ *
29
+ * @package @payez/next-mvp
30
+ */
31
+ Object.defineProperty(exports, "__esModule", { value: true });
32
+ exports.POST = POST;
33
+ const server_1 = require("next/server");
34
+ const idp_fetch_1 = require("../../lib/idp-fetch");
35
+ const env_1 = require("../../config/env");
36
+ const test_aware_get_token_1 = require("../../lib/test-aware-get-token");
37
+ const session_store_1 = require("../../lib/session-store");
38
+ const jwt_decode_1 = require("../../lib/jwt-decode");
39
+ async function POST(req) {
40
+ try {
41
+ const body = await req.json();
42
+ // Accept the same aliases the client might send; the IDP field is `code`.
43
+ const code = body.code || body.totpCode || body.verificationCode || body.verification_code;
44
+ if (!code) {
45
+ return server_1.NextResponse.json({
46
+ success: false,
47
+ error: 'Authenticator code is required',
48
+ code: 'INVALID_REQUEST',
49
+ }, { status: 400 });
50
+ }
51
+ // idpFetchJSON injects the caller's Bearer from the session store.
52
+ const result = await (0, idp_fetch_1.idpFetchJSON)(req, `${env_1.ENV_CONFIG.IDP_URL}/api/ExternalAuth/twofa/totp/verify`, {
53
+ method: 'POST',
54
+ headers: { 'Content-Type': 'application/json' },
55
+ body: JSON.stringify({ code }),
56
+ });
57
+ if (!result.ok) {
58
+ return server_1.NextResponse.json({
59
+ success: false,
60
+ error: result.json?.message || 'Verification failed',
61
+ code: result.json?.code || 'IDP_ERROR',
62
+ meta: { attemptedRefresh: result.attemptedRefresh },
63
+ }, { status: result.status });
64
+ }
65
+ // Unwrap IDP envelope { success, data }
66
+ const unwrappedData = result.json?.data || result.json;
67
+ // Only a successful challenge that returns fresh tokens may transition the
68
+ // session. No tokens => no transition: we must not mark 2FA complete on the
69
+ // strength of a 200 alone.
70
+ let sessionTransitioned = false;
71
+ if (unwrappedData.access_token && unwrappedData.refresh_token) {
72
+ const token = await (0, test_aware_get_token_1.getTokenTestAware)(req);
73
+ const sessionToken = (token?.sessionToken || token?.redisSessionId);
74
+ if (sessionToken) {
75
+ let accessTokenExpires = Date.now() + 15 * 60 * 1000;
76
+ try {
77
+ const decoded = (0, jwt_decode_1.jwtDecode)(unwrappedData.access_token);
78
+ if (decoded?.exp)
79
+ accessTokenExpires = decoded.exp * 1000;
80
+ }
81
+ catch {
82
+ console.warn('[VERIFY_TOTP] Could not decode access token, using default expiration');
83
+ }
84
+ let refreshTokenExpires = Date.now() + 3 * 24 * 60 * 60 * 1000;
85
+ try {
86
+ const decoded = (0, jwt_decode_1.jwtDecode)(unwrappedData.refresh_token);
87
+ if (decoded?.exp)
88
+ refreshTokenExpires = decoded.exp * 1000;
89
+ }
90
+ catch {
91
+ // Refresh token may carry no exp claim; default stands.
92
+ }
93
+ await (0, session_store_1.transitionTo2FASession)(sessionToken, {
94
+ accessToken: unwrappedData.access_token,
95
+ refreshToken: unwrappedData.refresh_token,
96
+ accessTokenExpires,
97
+ refreshTokenExpires,
98
+ }, 'totp' // 2FA method, used by the refresh-token flow
99
+ );
100
+ sessionTransitioned = true;
101
+ console.log('[VERIFY_TOTP] Session transitioned to 2FA-verified');
102
+ }
103
+ else {
104
+ console.warn('[VERIFY_TOTP] IDP verified the code but no session token was resolvable — session NOT transitioned');
105
+ }
106
+ }
107
+ else {
108
+ console.warn('[VERIFY_TOTP] IDP returned 2xx without tokens — session NOT transitioned');
109
+ }
110
+ // Do not expose tokens to the client.
111
+ //
112
+ // twoFactorSessionVerified REPORTS WHAT ACTUALLY HAPPENED. It is NOT a copy
113
+ // of `success`. The code can verify at the IDP while the session is not
114
+ // transitioned — no tokens returned, or no resolvable session token — and a
115
+ // client that trusted a hardcoded `true` would show the user as MFA-verified
116
+ // while the session still says otherwise. That divergence between the guard
117
+ // and the report is the defect this field exists to avoid.
118
+ // (verify-sms.ts hardcodes it true and has the same flaw — reported upstream.)
119
+ return server_1.NextResponse.json({
120
+ success: true,
121
+ verificationSuccessful: true,
122
+ twoFactorSessionVerified: sessionTransitioned,
123
+ message: unwrappedData.message || 'Authenticator code verified successfully',
124
+ }, { status: 200 });
125
+ }
126
+ catch (error) {
127
+ console.error('[VERIFY_TOTP] Error:', error);
128
+ return server_1.NextResponse.json({
129
+ success: false,
130
+ error: 'Failed to verify code',
131
+ code: 'INTERNAL_ERROR',
132
+ }, { status: 500 });
133
+ }
134
+ }
@@ -0,0 +1,7 @@
1
+ import { NextRequest, NextResponse } from 'next/server';
2
+ /**
3
+ * List the signed-in user's passkeys (GET /api/Passkeys, user JWT).
4
+ * Probe-verified live 2026-08-01 (anon -> 401 = routed).
5
+ * No session -> upstream 401, passed through, never invented locally.
6
+ */
7
+ export declare function GET(req: NextRequest): Promise<NextResponse<any>>;
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GET = GET;
4
+ const server_1 = require("next/server");
5
+ const idp_fetch_1 = require("../../lib/idp-fetch");
6
+ const env_1 = require("../../config/env");
7
+ /**
8
+ * List the signed-in user's passkeys (GET /api/Passkeys, user JWT).
9
+ * Probe-verified live 2026-08-01 (anon -> 401 = routed).
10
+ * No session -> upstream 401, passed through, never invented locally.
11
+ */
12
+ async function GET(req) {
13
+ const result = await (0, idp_fetch_1.idpFetchJSON)(req, `${env_1.ENV_CONFIG.IDP_URL}/api/Passkeys`, { method: 'GET' });
14
+ if (!result.ok) {
15
+ return server_1.NextResponse.json({
16
+ success: false,
17
+ message: 'Upstream error',
18
+ error: { code: 'UPSTREAM_SERVICE_ERROR', status: result.status, details: result.json },
19
+ meta: { attemptedRefresh: result.attemptedRefresh },
20
+ }, { status: result.status });
21
+ }
22
+ const bodyJson = result.json;
23
+ if (bodyJson && typeof bodyJson === 'object' && 'success' in bodyJson && 'data' in bodyJson) {
24
+ if (bodyJson.success === true)
25
+ return server_1.NextResponse.json(bodyJson.data, { status: 200 });
26
+ return server_1.NextResponse.json(bodyJson, { status: 200 });
27
+ }
28
+ return server_1.NextResponse.json(bodyJson ?? {}, { status: 200 });
29
+ }
@@ -0,0 +1,3 @@
1
+ import { NextRequest, NextResponse } from 'next/server';
2
+ export declare function PATCH(req: NextRequest, id: string): Promise<NextResponse<any>>;
3
+ export declare function DELETE(req: NextRequest, id: string): Promise<NextResponse<any>>;