@payez/next-mvp 4.8.1 → 4.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (302) hide show
  1. package/POST-INSTALL.md +408 -408
  2. package/README.md +859 -859
  3. package/dist/components/account/MobileNavDrawer.js +18 -18
  4. package/dist/components/account/UserAvatarMenu.js +1 -1
  5. package/dist/components/admin/AlertSettingsTab.js +40 -40
  6. package/dist/components/admin/LoggingSettingsTab.js +28 -28
  7. package/dist/lib/session-store.js +21 -21
  8. package/dist/lib/startup-init.js +19 -19
  9. package/dist/pages/login/page.js +28 -28
  10. package/dist/pages/settings/EnhancedSettingsPage.js +17 -17
  11. package/dist/vibe/sessions.js +28 -3
  12. package/package.json +2 -2
  13. package/scripts/check-publish-eol.mjs +33 -15
  14. package/src/api/auth-handler.ts +550 -550
  15. package/src/api/index.ts +17 -17
  16. package/src/api-handlers/account/change-password.ts +170 -170
  17. package/src/api-handlers/account/masked-info.ts +46 -46
  18. package/src/api-handlers/account/profile.ts +99 -99
  19. package/src/api-handlers/account/recovery/forward.ts +117 -117
  20. package/src/api-handlers/account/recovery/initiate.ts +59 -59
  21. package/src/api-handlers/account/recovery/send-code.ts +21 -21
  22. package/src/api-handlers/account/recovery/verify-code.ts +20 -20
  23. package/src/api-handlers/account/reset-password.ts +87 -87
  24. package/src/api-handlers/account/send-code.ts +70 -70
  25. package/src/api-handlers/account/update-phone.ts +84 -84
  26. package/src/api-handlers/account/validate-password.ts +139 -139
  27. package/src/api-handlers/account/verify-email.ts +134 -134
  28. package/src/api-handlers/account/verify-sms.ts +134 -134
  29. package/src/api-handlers/admin/analytics.ts +452 -452
  30. package/src/api-handlers/admin/audit.ts +232 -232
  31. package/src/api-handlers/admin/index.ts +63 -63
  32. package/src/api-handlers/admin/redis-sessions.ts +259 -259
  33. package/src/api-handlers/admin/sessions.ts +327 -327
  34. package/src/api-handlers/admin/site-logs.ts +388 -388
  35. package/src/api-handlers/admin/stats.ts +260 -260
  36. package/src/api-handlers/admin/users.ts +251 -251
  37. package/src/api-handlers/admin/vibe-data.ts +333 -333
  38. package/src/api-handlers/anon/preferences.ts +123 -123
  39. package/src/api-handlers/auth/credential-login-email-code.ts +92 -92
  40. package/src/api-handlers/auth/credential-login.ts +948 -948
  41. package/src/api-handlers/auth/jwks.ts +31 -31
  42. package/src/api-handlers/auth/login.ts +252 -252
  43. package/src/api-handlers/auth/passkey-signin.ts +116 -116
  44. package/src/api-handlers/auth/refresh.ts +829 -829
  45. package/src/api-handlers/auth/signout.ts +201 -201
  46. package/src/api-handlers/auth/status.ts +23 -23
  47. package/src/api-handlers/auth/update-session.ts +144 -144
  48. package/src/api-handlers/auth/validate.ts +45 -45
  49. package/src/api-handlers/auth/verify-code.ts +116 -116
  50. package/src/api-handlers/mfa/backup-code-verify.ts +170 -170
  51. package/src/api-handlers/mfa/backup-codes.ts +42 -42
  52. package/src/api-handlers/mfa/methods.ts +47 -47
  53. package/src/api-handlers/mfa/totp-confirm.ts +43 -43
  54. package/src/api-handlers/mfa/totp-enroll.ts +43 -43
  55. package/src/api-handlers/mfa/totp-verify.ts +172 -172
  56. package/src/api-handlers/oauth/resume.ts +182 -182
  57. package/src/api-handlers/onboarding/send-email-code.ts +18 -18
  58. package/src/api-handlers/onboarding/set-password.ts +21 -21
  59. package/src/api-handlers/onboarding/verify-code.ts +20 -20
  60. package/src/api-handlers/onboarding/verify-welcome-email.ts +17 -17
  61. package/src/api-handlers/passkeys/list.ts +32 -32
  62. package/src/api-handlers/passkeys/manage.ts +55 -55
  63. package/src/api-handlers/passkeys/register-options.ts +43 -43
  64. package/src/api-handlers/passkeys/register-verify.ts +42 -42
  65. package/src/api-handlers/session/refresh-viability.ts +56 -56
  66. package/src/api-handlers/session/viability.ts +238 -238
  67. package/src/api-handlers/test/force-expire.ts +167 -167
  68. package/src/auth/auth-decision.ts +292 -292
  69. package/src/auth/better-auth.ts +1688 -1688
  70. package/src/auth/idp-oauth.ts +310 -310
  71. package/src/auth/password-reset-bridge.ts +98 -98
  72. package/src/auth/revocation-fields.ts +16 -16
  73. package/src/auth/route-config.ts +236 -236
  74. package/src/auth/safe-callback.ts +199 -199
  75. package/src/auth/session-cookie-clear.ts +30 -30
  76. package/src/auth/session-reset-link.ts +159 -159
  77. package/src/auth/session-response-sanitizer.ts +151 -151
  78. package/src/auth/types/auth-types.ts +555 -555
  79. package/src/auth/types/index.ts +7 -7
  80. package/src/auth/unauthenticated-routes.ts +2 -2
  81. package/src/auth/utils/idp-client.ts +364 -364
  82. package/src/auth/utils/index.ts +6 -6
  83. package/src/auth/utils/token-utils.ts +243 -243
  84. package/src/client/AuthContext.tsx +192 -192
  85. package/src/client/better-auth-client.ts +70 -70
  86. package/src/client/fetch-with-auth.ts +47 -47
  87. package/src/client/fetchWithSession.ts +21 -21
  88. package/src/client/index.ts +13 -13
  89. package/src/client/useAnonSession.ts +131 -131
  90. package/src/components/SessionSync.tsx +138 -138
  91. package/src/components/SignalRHealthCheck.tsx +131 -131
  92. package/src/components/account/MobileNavDrawer.tsx +305 -305
  93. package/src/components/account/UserAvatarMenu.tsx +277 -277
  94. package/src/components/account/index.ts +13 -13
  95. package/src/components/admin/AlertSettingsTab.tsx +728 -728
  96. package/src/components/admin/AnalyticsTab.tsx +703 -703
  97. package/src/components/admin/DataBrowserTab.tsx +508 -508
  98. package/src/components/admin/LoggingSettingsTab.tsx +665 -665
  99. package/src/components/admin/SessionsTab.tsx +421 -421
  100. package/src/components/admin/StatsTab.tsx +379 -379
  101. package/src/components/admin/VibeAdminContext.tsx +87 -87
  102. package/src/components/admin/VibeAdminLayout.tsx +187 -187
  103. package/src/components/admin/index.ts +59 -59
  104. package/src/components/auth/CredentialSignInForm.tsx +240 -240
  105. package/src/components/auth/FederatedAuthSection.tsx +129 -129
  106. package/src/components/auth/ModeAwareLoginPage.tsx +146 -146
  107. package/src/components/auth/ModeAwareSignupPage.tsx +200 -200
  108. package/src/components/auth/PasswordResetBridge.tsx +30 -30
  109. package/src/components/auth/TraditionalAuthSection.tsx +103 -103
  110. package/src/components/recovery/CompleteStep.tsx +36 -36
  111. package/src/components/recovery/InitiateRecoveryStep.tsx +68 -68
  112. package/src/components/recovery/RequestedStep.tsx +30 -30
  113. package/src/components/recovery/SelectMethodStep.tsx +73 -73
  114. package/src/components/recovery/SetPasswordStep.tsx +118 -118
  115. package/src/components/recovery/VerifyCodeStep.tsx +90 -90
  116. package/src/components/reserved/ReservedRecoveryWarning.tsx +160 -160
  117. package/src/components/reserved/ReservedStatusBox.tsx +118 -118
  118. package/src/components/ui/BetaBadge.tsx +58 -58
  119. package/src/components/ui/Footer.tsx +93 -93
  120. package/src/config/env.ts +55 -55
  121. package/src/config/logger.ts +62 -62
  122. package/src/config/logging-config.ts +82 -82
  123. package/src/config/unauthenticated-routes.ts +19 -19
  124. package/src/config/vibe-log-transport.ts +264 -264
  125. package/src/edge/internal-api-url.ts +65 -65
  126. package/src/edge/middleware.ts +42 -42
  127. package/src/hooks/useAuth.ts +117 -117
  128. package/src/hooks/useAuthSettings.ts +109 -109
  129. package/src/hooks/useAvailableProviders.ts +143 -143
  130. package/src/hooks/usePasswordValidation.ts +127 -127
  131. package/src/hooks/useProfile.ts +82 -82
  132. package/src/hooks/usePublicAuthSettings.ts +171 -171
  133. package/src/hooks/useSessionExpiration.ts +101 -101
  134. package/src/hooks/useViabilitySession.ts +337 -337
  135. package/src/index.ts +64 -64
  136. package/src/lib/anon-session.ts +213 -213
  137. package/src/lib/api-handler.ts +643 -643
  138. package/src/lib/app-slug.ts +228 -228
  139. package/src/lib/authorize-resume.ts +172 -172
  140. package/src/lib/bearer-fetch.ts +31 -31
  141. package/src/lib/client-key.ts +88 -88
  142. package/src/lib/code-step-copy.ts +83 -83
  143. package/src/lib/credential-sign-in-client.ts +101 -101
  144. package/src/lib/demo-mode.ts +18 -18
  145. package/src/lib/device-id.ts +67 -67
  146. package/src/lib/ensure-fresh-access-token.ts +509 -509
  147. package/src/lib/geolocation.ts +265 -265
  148. package/src/lib/idp-client-config.ts +1005 -1005
  149. package/src/lib/idp-fetch.ts +169 -169
  150. package/src/lib/idp-url-guard.ts +37 -37
  151. package/src/lib/internal-api.ts +171 -171
  152. package/src/lib/jwt-decode-client.ts +45 -45
  153. package/src/lib/jwt-decode.ts +82 -82
  154. package/src/lib/lock-window.ts +49 -49
  155. package/src/lib/login-error-message.ts +41 -41
  156. package/src/lib/never-in-response.ts +64 -64
  157. package/src/lib/nextauth-secret.ts +168 -168
  158. package/src/lib/onboarding-proxy.ts +57 -57
  159. package/src/lib/password-rules.ts +50 -50
  160. package/src/lib/rate-limit-service.ts +9 -9
  161. package/src/lib/redis.ts +105 -105
  162. package/src/lib/refresh-token-validator.ts +64 -64
  163. package/src/lib/roles.ts +177 -177
  164. package/src/lib/safe-error-response.ts +149 -149
  165. package/src/lib/secret-validation.ts +8 -8
  166. package/src/lib/session-cookie-shape.ts +185 -185
  167. package/src/lib/session-store.ts +1092 -1092
  168. package/src/lib/session.ts +34 -34
  169. package/src/lib/single-flight.ts +64 -64
  170. package/src/lib/site-logger.ts +245 -245
  171. package/src/lib/standardized-client-api.ts +901 -901
  172. package/src/lib/startup-init.ts +276 -276
  173. package/src/lib/test-aware-get-token.ts +41 -41
  174. package/src/lib/token-expiry.ts +40 -40
  175. package/src/lib/token-lifecycle.ts +546 -546
  176. package/src/lib/token-log-id.ts +69 -69
  177. package/src/lib/twofa-rejection.ts +91 -91
  178. package/src/lib/types/api-responses.ts +336 -336
  179. package/src/lib/user-agent-parser.ts +252 -252
  180. package/src/logging/api/admin-analytics.ts +51 -51
  181. package/src/logging/api/audit-log.ts +53 -53
  182. package/src/logging/components/AdminAnalyticsLayout.tsx +49 -49
  183. package/src/logging/components/AuditLogViewer.tsx +125 -125
  184. package/src/logging/components/ErrorMetricsCard.tsx +98 -98
  185. package/src/logging/components/HealthMetricsCard.tsx +70 -70
  186. package/src/logging/hooks/useAdminAnalytics.ts +22 -22
  187. package/src/logging/hooks/useAuditLog.ts +24 -24
  188. package/src/logging/hooks/useErrorMetrics.ts +40 -40
  189. package/src/logging/hooks/useHealthMetrics.ts +44 -44
  190. package/src/logging/index.ts +18 -18
  191. package/src/logging/types/analytics.ts +81 -81
  192. package/src/logging/types/audit.ts +31 -31
  193. package/src/logging/types/index.ts +3 -3
  194. package/src/middleware/create-middleware.ts +1141 -1141
  195. package/src/middleware/rbac-check.ts +279 -279
  196. package/src/middleware/twofa-presets.ts +224 -224
  197. package/src/models/DecodedAccessToken.ts +16 -16
  198. package/src/models/SessionModel.ts +331 -331
  199. package/src/pages/admin-login/page.tsx +111 -111
  200. package/src/pages/admin-page-permissions/PagePermissionsAdminPage.tsx +527 -527
  201. package/src/pages/admin-page-permissions/index.ts +7 -7
  202. package/src/pages/admin-roles/RolesAdminPage.tsx +533 -533
  203. package/src/pages/admin-roles/index.ts +9 -9
  204. package/src/pages/admin-roles/modals.tsx +469 -469
  205. package/src/pages/client-admin/ClientSiteAdminPage.tsx +382 -382
  206. package/src/pages/client-admin/index.ts +33 -33
  207. package/src/pages/coming-soon/page.tsx +83 -83
  208. package/src/pages/login/page.tsx +338 -338
  209. package/src/pages/onboarding/index.ts +11 -11
  210. package/src/pages/onboarding/page.tsx +212 -212
  211. package/src/pages/profile/EnhancedProfilePage.tsx +514 -514
  212. package/src/pages/profile/index.ts +9 -9
  213. package/src/pages/profile/page.tsx +166 -166
  214. package/src/pages/recovery/page.tsx +267 -267
  215. package/src/pages/roles/MyRolesPage.tsx +211 -211
  216. package/src/pages/roles/components.tsx +294 -294
  217. package/src/pages/roles/index.ts +17 -17
  218. package/src/pages/security/EnhancedSecurityPage.tsx +660 -660
  219. package/src/pages/security/index.ts +12 -12
  220. package/src/pages/security/page.tsx +507 -507
  221. package/src/pages/service-unavailable/page.tsx +63 -63
  222. package/src/pages/settings/EnhancedSettingsPage.tsx +642 -642
  223. package/src/pages/settings/index.ts +9 -9
  224. package/src/pages/settings/page.tsx +47 -47
  225. package/src/pages/showcase/ShowcasePage.tsx +532 -532
  226. package/src/pages/showcase/index.ts +13 -13
  227. package/src/pages/test-env/EmergencyLogoutPage.tsx +192 -192
  228. package/src/pages/test-env/JwtInspectPage.tsx +449 -449
  229. package/src/pages/test-env/RefreshTokenPage.tsx +178 -178
  230. package/src/pages/test-env/TestEnvPage.tsx +130 -130
  231. package/src/pages/test-env/guarded.tsx +81 -81
  232. package/src/pages/test-env/index.ts +77 -77
  233. package/src/pages/test-env/redact-credentials.ts +96 -96
  234. package/src/pages/verify-code/page.tsx +746 -746
  235. package/src/routes/account/index.ts +31 -31
  236. package/src/routes/account/masked-info.ts +36 -36
  237. package/src/routes/account/send-code.ts +39 -39
  238. package/src/routes/account/update-phone.ts +13 -13
  239. package/src/routes/account/verify-email.ts +40 -40
  240. package/src/routes/account/verify-sms.ts +40 -40
  241. package/src/routes/auth/credential-login-email-code.ts +6 -6
  242. package/src/routes/auth/credential-login.ts +6 -6
  243. package/src/routes/auth/index.ts +22 -22
  244. package/src/routes/auth/logout.ts +111 -111
  245. package/src/routes/auth/nextauth.ts +45 -45
  246. package/src/routes/auth/passkey-signin.ts +13 -13
  247. package/src/routes/auth/refresh.ts +77 -77
  248. package/src/routes/auth/session-reset.ts +37 -37
  249. package/src/routes/auth/session.ts +261 -261
  250. package/src/routes/auth/settings.ts +181 -181
  251. package/src/routes/auth/viability.ts +519 -519
  252. package/src/routes/index.ts +17 -17
  253. package/src/routes/mfa/backup-code-verify.ts +1 -1
  254. package/src/routes/mfa/backup-codes.ts +10 -10
  255. package/src/routes/mfa/methods.ts +22 -22
  256. package/src/routes/mfa/totp-confirm.ts +10 -10
  257. package/src/routes/mfa/totp-enroll.ts +10 -10
  258. package/src/routes/mfa/totp-verify.ts +14 -14
  259. package/src/routes/onboarding/index.ts +15 -15
  260. package/src/routes/onboarding/send-email-code.ts +2 -2
  261. package/src/routes/onboarding/set-password.ts +2 -2
  262. package/src/routes/onboarding/verify-code.ts +2 -2
  263. package/src/routes/onboarding/verify-welcome-email.ts +2 -2
  264. package/src/routes/passkeys/list.ts +10 -10
  265. package/src/routes/passkeys/manage.ts +23 -23
  266. package/src/routes/passkeys/register-options.ts +10 -10
  267. package/src/routes/passkeys/register-verify.ts +10 -10
  268. package/src/routes/session/index.ts +7 -7
  269. package/src/routes/session/refresh-viability.ts +17 -17
  270. package/src/server/auth-guard.ts +203 -203
  271. package/src/server/auth.ts +486 -486
  272. package/src/server/decode-session.ts +309 -309
  273. package/src/server/slim-middleware.ts +117 -117
  274. package/src/server/verified-session-token.ts +103 -103
  275. package/src/server/with-auth.ts +93 -93
  276. package/src/services/signalrActivityService.ts +258 -258
  277. package/src/stores/authStore.ts +1900 -1900
  278. package/src/templates/instrumentation.ts +60 -60
  279. package/src/theme/ThemeProvider.tsx +39 -39
  280. package/src/theme/default.ts +33 -33
  281. package/src/theme/index.ts +31 -31
  282. package/src/theme/types.ts +69 -69
  283. package/src/theme/useTheme.ts +57 -57
  284. package/src/theme/utils.ts +40 -40
  285. package/src/types/api.ts +12 -12
  286. package/src/types/auth.d.ts +23 -23
  287. package/src/types/auth.ts +48 -48
  288. package/src/types/logging.ts +11 -11
  289. package/src/types/recovery.ts +54 -54
  290. package/src/utils/api.ts +401 -401
  291. package/src/utils/circuitBreaker.ts +40 -40
  292. package/src/utils/error-message.ts +108 -108
  293. package/src/utils/layout/reservedSpace.ts +124 -124
  294. package/src/utils/logout.ts +30 -30
  295. package/src/vibe/client.ts +877 -877
  296. package/src/vibe/enterprise-auth.ts +208 -208
  297. package/src/vibe/errors.ts +209 -209
  298. package/src/vibe/generic.ts +339 -339
  299. package/src/vibe/hooks/index.ts +367 -367
  300. package/src/vibe/index.ts +133 -133
  301. package/src/vibe/sessions.ts +925 -899
  302. package/src/vibe/types.ts +577 -577
@@ -1,546 +1,546 @@
1
- /**
2
- * Token Lifecycle Management for @payez/next-mvp
3
- *
4
- * Ensures tokens are fresh before making API calls.
5
- * Checks expiration and triggers refresh if needed.
6
- *
7
- * Pattern: Check first, refresh if needed, fail gracefully if refresh fails.
8
- *
9
- * HANDLES CONCURRENT REFRESH: When multiple API calls arrive simultaneously
10
- * with expired tokens, only one will actually perform the refresh. Others
11
- * receive 409 (conflict) and wait for the refresh to complete, then use
12
- * the freshly refreshed tokens.
13
- *
14
- * REQUIRED: Your app must expose the refresh route:
15
- * ```typescript
16
- * // app/api/auth/refresh/route.ts
17
- * export { POST } from '@payez/next-mvp/routes/auth/refresh';
18
- * ```
19
- *
20
- * @version 2.0.0
21
- */
22
-
23
- import { NextRequest } from 'next/server';
24
- import { getSession as getRedisSession, SessionData } from './session-store';
25
- import { getSession as getBetterAuthSession } from '../server/auth';
26
- import { getRedis } from './redis';
27
- import { getAppSlug } from './app-slug';
28
- import { tokenLogId } from './token-log-id';
29
-
30
- // 5 minute threshold for "needs refresh" - matches refresh handler pattern
31
- const REFRESH_THRESHOLD_MS = 5 * 60 * 1000;
32
-
33
- // Concurrent refresh handling configuration
34
- const CONCURRENT_REFRESH_POLL_INTERVAL_MS = 200; // How often to poll session during concurrent refresh
35
- const CONCURRENT_REFRESH_MAX_WAIT_MS = 8000; // Max time to wait for concurrent refresh to complete
36
- const REFRESH_RETRY_DELAY_MS = 500; // Delay before retrying after failed concurrent refresh
37
- const KEY_PROPAGATION_DELAY_MS = 150; // Delay after refresh to allow JWKS cache updates in downstream services
38
-
39
- export interface TokenResult {
40
- success: true;
41
- accessToken: string;
42
- sessionData: SessionData;
43
- }
44
-
45
- export interface TokenError {
46
- success: false;
47
- error: 'NO_SESSION' | 'NO_TOKEN' | 'EXPIRED' | 'REFRESH_FAILED' | 'SESSION_EXPIRED_NO_REFRESH';
48
- message: string;
49
- terminal?: boolean; // If true, don't retry - redirect to login
50
- // WO-1 (genuine-dead refresh): the VERBATIM upstream reason from the IDP, preserved
51
- // end-to-end so the consumer can surface an honest error + halt a futile re-auth loop
52
- // (e.g. an unapproved user whose login mints a bearer but whose refresh terminally
53
- // fails). `error` stays the stable category for existing consumers; `code`/`resolution`
54
- // carry the real cause. Never soften — surface it.
55
- code?: string; // Upstream IDP error code (e.g. UNAUTHORIZED, USER_NOT_APPROVED)
56
- resolution?: string; // Upstream human-readable resolution hint, if any
57
- }
58
-
59
- export type EnsureFreshTokenResult = TokenResult | TokenError;
60
-
61
- /**
62
- * Check if token needs refresh based on expiration time
63
- */
64
- function needsRefresh(accessTokenExpires: number | undefined): boolean {
65
- if (!accessTokenExpires) return true;
66
- const timeUntilExpiry = accessTokenExpires - Date.now();
67
- return timeUntilExpiry <= REFRESH_THRESHOLD_MS;
68
- }
69
-
70
- /**
71
- * Helper to delay execution
72
- */
73
- function delay(ms: number): Promise<void> {
74
- return new Promise(resolve => setTimeout(resolve, ms));
75
- }
76
-
77
- /**
78
- * Wait for a concurrent refresh to complete by polling the session.
79
- * Returns true if session becomes fresh, false if timeout reached.
80
- */
81
- async function waitForConcurrentRefresh(
82
- sessionToken: string,
83
- maxWaitMs: number = CONCURRENT_REFRESH_MAX_WAIT_MS
84
- ): Promise<{ success: boolean; sessionData?: SessionData }> {
85
- const startTime = Date.now();
86
-
87
- while (Date.now() - startTime < maxWaitMs) {
88
- await delay(CONCURRENT_REFRESH_POLL_INTERVAL_MS);
89
-
90
- const sessionData = await getRedisSession(sessionToken);
91
-
92
- if (!sessionData) {
93
- return { success: false };
94
- }
95
-
96
- // Check if token is now fresh
97
- if (!needsRefresh(sessionData.idpAccessTokenExpires)) {
98
- return { success: true, sessionData };
99
- }
100
-
101
- // Check if session has a new access token (even if still within threshold)
102
- if (sessionData.idpAccessToken && sessionData.idpAccessTokenExpires &&
103
- sessionData.idpAccessTokenExpires > Date.now()) {
104
- return { success: true, sessionData };
105
- }
106
- }
107
-
108
- return { success: false };
109
- }
110
-
111
- /**
112
- * Get the internal API URL for making internal service calls.
113
- * INTERNAL_API_URL is REQUIRED - no fallbacks.
114
- */
115
- function getInternalApiUrl(request: NextRequest): string {
116
- const internalUrl = process.env.INTERNAL_API_URL;
117
- if (!internalUrl) {
118
- throw new Error(
119
- '[INTERNAL_API_URL] FATAL: INTERNAL_API_URL environment variable is REQUIRED. ' +
120
- 'Set it to this app\'s internal K8s service URL (e.g., http://myapp.namespace.svc.cluster.local:80) ' +
121
- 'or http://localhost:3000 for local development.'
122
- );
123
- }
124
- return internalUrl;
125
- }
126
-
127
- /**
128
- * Result of triggerRefresh - includes terminal flag for unrecoverable errors
129
- */
130
- interface RefreshResult {
131
- success: boolean;
132
- terminal?: boolean; // If true, session is dead - don't retry, redirect to login
133
- code?: string; // Error code from refresh endpoint
134
- message?: string; // WO-1: verbatim human message from the refresh endpoint
135
- resolution?: string; // WO-1: verbatim resolution hint from the refresh endpoint
136
- }
137
-
138
- /**
139
- * Trigger a token refresh via the refresh API endpoint.
140
- *
141
- * HANDLES CONCURRENT REFRESH (409):
142
- * When another request is already refreshing the token, this function
143
- * waits for that refresh to complete instead of failing immediately.
144
- * This prevents race conditions where multiple parallel API calls
145
- * could cause unnecessary refresh failures.
146
- *
147
- * TERMINAL STATES:
148
- * Returns { success: false, terminal: true } when the session cannot be
149
- * recovered (e.g., no refresh token). Callers should redirect to login.
150
- */
151
- async function triggerRefresh(
152
- request: NextRequest,
153
- sessionToken: string,
154
- retryCount: number = 0
155
- ): Promise<RefreshResult> {
156
- const maxRetries = 2;
157
-
158
- try {
159
- const baseUrl = getInternalApiUrl(request);
160
- const requestId = `refresh_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
161
-
162
- const response = await fetch(`${baseUrl}/api/auth/refresh`, {
163
- method: 'POST',
164
- headers: {
165
- 'Content-Type': 'application/json',
166
- 'Cookie': request.headers.get('cookie') || '',
167
- 'X-Session-Token': sessionToken,
168
- 'X-Request-Id': requestId,
169
- },
170
- });
171
-
172
- // Handle 409 Conflict - another refresh is in progress
173
- if (response.status === 409) {
174
- // Wait for the concurrent refresh to complete
175
- const waitResult = await waitForConcurrentRefresh(sessionToken);
176
-
177
- if (waitResult.success) {
178
- return { success: true };
179
- }
180
-
181
- // Concurrent refresh didn't produce a fresh token - try again if we have retries left
182
- if (retryCount < maxRetries) {
183
- await delay(REFRESH_RETRY_DELAY_MS);
184
- return triggerRefresh(request, sessionToken, retryCount + 1);
185
- }
186
-
187
- return { success: false };
188
- }
189
-
190
- // Handle other non-OK responses
191
- if (!response.ok) {
192
- // Parse response body to check for terminal errors
193
- let responseData: any = {};
194
- try {
195
- responseData = await response.json();
196
- } catch {
197
- // Ignore parse errors
198
- }
199
-
200
- // Log the failure for debugging
201
- console.warn('[TOKEN_LIFECYCLE] Refresh request failed:', {
202
- status: response.status,
203
- statusText: response.statusText,
204
- baseUrl,
205
- retryCount,
206
- code: responseData.code,
207
- terminal: responseData.terminal
208
- });
209
-
210
- // CHECK FOR TERMINAL STATE: No refresh token = session is dead
211
- // Don't retry - user must re-authenticate
212
- if (responseData.code === 'NO_REFRESH_TOKEN' || responseData.terminal === true) {
213
- console.error('[TOKEN_LIFECYCLE] TERMINAL: Session has no refresh token - user must re-login');
214
- // WO-1: preserve the verbatim upstream reason. refresh.ts puts the human
215
- // message in `error` and the code in `code`; carry both up so the consumer
216
- // can tell the user WHY (not just "session expired") and stop a futile loop.
217
- return {
218
- success: false,
219
- terminal: true,
220
- code: responseData.code,
221
- message: responseData.error,
222
- resolution: responseData.resolution,
223
- };
224
- }
225
-
226
- // For other 401s, check if maybe session was refreshed by another request
227
- if (response.status === 401 && retryCount < maxRetries) {
228
- await delay(REFRESH_RETRY_DELAY_MS);
229
-
230
- const sessionData = await getRedisSession(sessionToken);
231
- if (sessionData && !needsRefresh(sessionData.idpAccessTokenExpires)) {
232
- return { success: true };
233
- }
234
- }
235
-
236
- return { success: false, code: responseData.code };
237
- }
238
-
239
- const result = await response.json();
240
- const success = result.refreshed === true || result.reason === 'already_fresh';
241
- return { success };
242
- } catch (error) {
243
- // Log network errors for debugging
244
- console.error('[TOKEN_LIFECYCLE] Refresh network error:', {
245
- error: error instanceof Error ? error.message : String(error),
246
- retryCount
247
- });
248
-
249
- // On network error, check if maybe another request refreshed the token
250
- if (retryCount < maxRetries) {
251
- await delay(REFRESH_RETRY_DELAY_MS);
252
- const sessionData = await getRedisSession(sessionToken);
253
- if (sessionData && !needsRefresh(sessionData.idpAccessTokenExpires)) {
254
- return { success: true };
255
- }
256
- }
257
-
258
- return { success: false };
259
- }
260
- }
261
-
262
- /**
263
- * Ensures we have a fresh access token before making API calls.
264
- *
265
- * This utility checks token expiration and triggers a refresh if needed,
266
- * preventing 401 errors from expired tokens being sent to downstream APIs.
267
- *
268
- * @param request - The incoming NextRequest
269
- * @returns TokenResult with accessToken and sessionData, or TokenError
270
- *
271
- * @example
272
- * ```typescript
273
- * import { ensureFreshToken } from '@payez/next-mvp/lib/token-lifecycle';
274
- *
275
- * export async function GET(request: NextRequest) {
276
- * const tokenResult = await ensureFreshToken(request);
277
- * if (!tokenResult.success) {
278
- * return NextResponse.json({ error: tokenResult.error }, { status: 401 });
279
- * }
280
- *
281
- * // Use tokenResult.accessToken for downstream API calls
282
- * const response = await fetch('https://api.example.com/data', {
283
- * headers: { 'Authorization': `Bearer ${tokenResult.accessToken}` }
284
- * });
285
- * }
286
- * ```
287
- */
288
- export async function ensureFreshToken(
289
- request: NextRequest
290
- ): Promise<EnsureFreshTokenResult> {
291
- try {
292
- // 1. Get Better Auth session to extract sessionToken
293
- const betterAuthSession = await getBetterAuthSession(request);
294
-
295
- if (!betterAuthSession?.session?.token) {
296
- console.warn('[TOKEN_LIFECYCLE] NO_SESSION - Better Auth session not found');
297
- return {
298
- success: false,
299
- error: 'NO_SESSION',
300
- message: 'No session available',
301
- };
302
- }
303
-
304
- const sessionToken = betterAuthSession.session.token;
305
-
306
- // 2. Get session data from Redis (legacy prefix), or Better Auth's secondary storage
307
- let sessionData = await getRedisSession(sessionToken);
308
-
309
- if (!sessionData) {
310
- // Try Better Auth's secondaryStorage key (ba:{slug}:{token})
311
- try {
312
- const baKey = `ba:${getAppSlug()}:${sessionToken}`;
313
- const baRaw = await getRedis().get(baKey);
314
- if (baRaw) {
315
- const baSession = JSON.parse(baRaw);
316
- const idpTokens = baSession.idpTokens;
317
-
318
- sessionData = {
319
- userId: idpTokens?.userId || baSession.user?.id || betterAuthSession.user?.id || '',
320
- email: idpTokens?.email || baSession.user?.email || betterAuthSession.user?.email || '',
321
- name: idpTokens?.name || baSession.user?.name || betterAuthSession.user?.name,
322
- roles: idpTokens?.roles || [],
323
- idpAccessToken: idpTokens?.idpAccessToken,
324
- idpRefreshToken: idpTokens?.idpRefreshToken,
325
- idpAccessTokenExpires: idpTokens?.idpAccessTokenExpires
326
- || (baSession.session?.expiresAt ? new Date(baSession.session.expiresAt).getTime() : Date.now() + 24 * 60 * 60 * 1000),
327
- /**
328
- * ⚠ THESE WERE HARDCODED `true` / `'google'`. (QAPert finding #3,
329
- * BAPert ruling, card 167892.)
330
- *
331
- * This rebuild path assumed EVERY session is a Google OAuth sign-in
332
- * that completed MFA. It reads `idpTokens` for everything else —
333
- * including roles, two lines up — and then IGNORED the stored
334
- * mfaVerified sitting in that same object and asserted `true`.
335
- *
336
- * WHY IT MATTERS MORE THAN A WRONG FIELD: a passkey sign-in stores
337
- * an HONEST mfaVerified derived from the token's `amr`. On any
338
- * Redis miss this path OVERWROTE that false with true — so the
339
- * session claimed an MFA the user never performed, and the honest
340
- * derivation upstream was not weakened but VOIDED. Same defect
341
- * class as the mints that assert completion they never did,
342
- * arriving through a cache-miss rather than a mint.
343
- *
344
- * `oauthProvider: 'google'` was the second lie on the same line:
345
- * a passkey session rebuilt here was relabelled a Google sign-in,
346
- * destroying the provenance the sign-in path deliberately records.
347
- * The IDP emits NO provider claim (DotNetPert), so the honest
348
- * answer when it was not stored is UNSET — not a guess.
349
- *
350
- * Both now default to the SAFE direction: absent/false is
351
- * fail-closed at every consumer we measured (`!!mfaVerified`,
352
- * `mfaVerified || ... || false`).
353
- */
354
- mfaVerified: idpTokens?.mfaVerified ?? false,
355
- // R807 (362550): the fail-closed default above stays exactly as documented;
356
- // this records whether it was a measurement or a default. `!== undefined`
357
- // deliberately - an explicit `false` is a signal.
358
- mfaSignalPresent: idpTokens?.mfaVerified !== undefined,
359
- oauthProvider: idpTokens?.oauthProvider ?? baSession.oauthProvider ?? undefined,
360
- idpClientId: idpTokens?.idpClientId ?? idpTokens?.clientId ?? baSession.idpClientId,
361
- merchantId: idpTokens?.merchantId ?? baSession.merchantId,
362
- } as SessionData;
363
- }
364
- } catch { /* Redis unavailable */ }
365
- }
366
-
367
- if (!sessionData && betterAuthSession.user) {
368
- // Last resort: build from Better Auth in-memory session (no IDP tokens)
369
- sessionData = {
370
- userId: betterAuthSession.user.id || '',
371
- email: betterAuthSession.user.email || '',
372
- name: betterAuthSession.user.name,
373
- roles: [],
374
- idpAccessTokenExpires: Date.now() + 24 * 60 * 60 * 1000,
375
- /**
376
- * ⚠ ALSO HARDCODED `true` / `'google'`, and this path is the worse of
377
- * the two: it runs with NO IDP TOKENS AT ALL — the comment above says
378
- * so — and still asserted that MFA was completed. It fabricated an
379
- * assurance claim from nothing, for every consumer, not just passkey.
380
- *
381
- * With nothing to derive from, FALSE is the only honest value and
382
- * UNSET is the only honest provider. Both are fail-closed.
383
- */
384
- mfaVerified: false,
385
- /**
386
- * R807 (362550) - FIFTH construction site, not in the ruling's list of four.
387
- * This path has NO IDP TOKENS AT ALL, so there is no producer statement to
388
- * record: the `false` above is a DEFAULT, never a measurement. `false` is
389
- * therefore the honest signal value, and it is the conservative one for
390
- * viability (absent/false -> do not force a re-challenge).
391
- */
392
- mfaSignalPresent: false,
393
- oauthProvider: undefined,
394
- } as SessionData;
395
- }
396
-
397
- if (!sessionData) {
398
- return {
399
- success: false,
400
- error: 'NO_SESSION',
401
- message: 'Session expired or not found',
402
- };
403
- }
404
-
405
- // DEBUG: Log session data before refresh check
406
- const tokenExpiresStr = sessionData.idpAccessTokenExpires
407
- ? new Date(sessionData.idpAccessTokenExpires).toISOString()
408
- : 'undefined';
409
- let needsRefreshNow = needsRefresh(sessionData.idpAccessTokenExpires);
410
-
411
- // VALIDATION: Check if the actual JWT token's exp matches what Redis claims
412
- // This catches cases where accessTokenExpires was updated but accessToken wasn't
413
- let tokenMismatch = false;
414
- if (sessionData.idpAccessToken && !needsRefreshNow) {
415
- try {
416
- const tokenParts = sessionData.idpAccessToken.split('.');
417
- if (tokenParts.length === 3) {
418
- const payload = JSON.parse(Buffer.from(tokenParts[1], 'base64url').toString());
419
- const jwtExpMs = (payload.exp || 0) * 1000;
420
- const now = Date.now();
421
-
422
- // If the JWT is actually expired, force a refresh regardless of what Redis says
423
- if (jwtExpMs < now) {
424
- console.warn('[TOKEN_LIFECYCLE] Token mismatch detected! JWT expired but Redis claims valid', {
425
- jwtExp: new Date(jwtExpMs).toISOString(),
426
- redisAccessTokenExpires: tokenExpiresStr,
427
- now: new Date(now).toISOString(),
428
- mismatchMs: sessionData.idpAccessTokenExpires ? sessionData.idpAccessTokenExpires - jwtExpMs : 'N/A'
429
- });
430
- needsRefreshNow = true;
431
- tokenMismatch = true;
432
- }
433
- }
434
- } catch (e) {
435
- // If we can't decode, proceed with normal logic
436
- console.warn('[TOKEN_LIFECYCLE] Could not validate JWT exp claim:', e);
437
- }
438
- }
439
-
440
- console.log('[TOKEN_LIFECYCLE] ensureFreshToken check:', {
441
- sessionToken: tokenLogId(sessionToken),
442
- accessTokenExpires: tokenExpiresStr,
443
- now: new Date().toISOString(),
444
- needsRefresh: needsRefreshNow,
445
- tokenMismatch,
446
- hasRefreshToken: !!sessionData.idpRefreshToken
447
- });
448
-
449
- // 3. Check if token needs refresh
450
- if (needsRefreshNow) {
451
- // 4. Trigger refresh
452
- console.log('[TOKEN_LIFECYCLE] Triggering refresh...');
453
- const refreshResult = await triggerRefresh(request, sessionToken);
454
-
455
- if (!refreshResult.success) {
456
- // Check for terminal state - session cannot be recovered
457
- if (refreshResult.terminal) {
458
- console.error('[TOKEN_LIFECYCLE] TERMINAL: Session expired - redirect to login', {
459
- code: refreshResult.code,
460
- message: refreshResult.message,
461
- });
462
- // WO-1: keep `error` as the stable terminal category (existing consumers
463
- // branch on SESSION_EXPIRED_NO_REFRESH) but surface the verbatim upstream
464
- // reason via code/message/resolution so the user learns WHY and a genuinely
465
- // dead session (e.g. unapproved account) doesn't loop login→bounce→login.
466
- return {
467
- success: false,
468
- error: 'SESSION_EXPIRED_NO_REFRESH',
469
- message: refreshResult.message || 'Session expired. Please sign in again.',
470
- terminal: true,
471
- code: refreshResult.code,
472
- resolution: refreshResult.resolution,
473
- };
474
- }
475
-
476
- console.warn('[TOKEN_LIFECYCLE] Refresh failed');
477
- return {
478
- success: false,
479
- error: 'REFRESH_FAILED',
480
- message: 'Token refresh failed',
481
- };
482
- }
483
-
484
- // 5. Re-fetch session data after refresh
485
- sessionData = await getRedisSession(sessionToken);
486
- console.log('[TOKEN_LIFECYCLE] After refresh:', {
487
- hasAccessToken: !!sessionData?.idpAccessToken,
488
- newAccessTokenExpires: sessionData?.idpAccessTokenExpires
489
- ? new Date(sessionData.idpAccessTokenExpires).toISOString()
490
- : 'undefined'
491
- });
492
-
493
- if (!sessionData?.idpAccessToken) {
494
- return {
495
- success: false,
496
- error: 'REFRESH_FAILED',
497
- message: 'No access token after refresh',
498
- };
499
- }
500
-
501
- // 5.5. Key propagation delay - allow downstream services (like Vibe) to cache new JWKS
502
- // This is critical when IDP rotates signing keys - the new token's kid may not be
503
- // immediately available in Vibe's JWKS cache
504
- await delay(KEY_PROPAGATION_DELAY_MS);
505
- }
506
-
507
- // 6. Return session — accessToken may be empty for social-only OAuth sessions
508
- return {
509
- success: true,
510
- accessToken: sessionData.idpAccessToken || '',
511
- sessionData,
512
- };
513
- } catch (error) {
514
- console.error('[TOKEN_LIFECYCLE] Error:', error);
515
- return {
516
- success: false,
517
- error: 'NO_SESSION',
518
- message: error instanceof Error ? error.message : 'Unknown error',
519
- };
520
- }
521
- }
522
-
523
- /**
524
- * Get authorization header from fresh token.
525
- * Convenience wrapper for API routes.
526
- *
527
- * @param request - The incoming NextRequest
528
- * @returns Authorization header string or null if token unavailable
529
- *
530
- * @example
531
- * ```typescript
532
- * const authHeader = await getFreshAuthHeader(request);
533
- * if (!authHeader) {
534
- * return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
535
- * }
536
- * ```
537
- */
538
- export async function getFreshAuthHeader(
539
- request: NextRequest
540
- ): Promise<string | null> {
541
- const result = await ensureFreshToken(request);
542
- if (!result.success) {
543
- return null;
544
- }
545
- return `Bearer ${result.accessToken}`;
546
- }
1
+ /**
2
+ * Token Lifecycle Management for @payez/next-mvp
3
+ *
4
+ * Ensures tokens are fresh before making API calls.
5
+ * Checks expiration and triggers refresh if needed.
6
+ *
7
+ * Pattern: Check first, refresh if needed, fail gracefully if refresh fails.
8
+ *
9
+ * HANDLES CONCURRENT REFRESH: When multiple API calls arrive simultaneously
10
+ * with expired tokens, only one will actually perform the refresh. Others
11
+ * receive 409 (conflict) and wait for the refresh to complete, then use
12
+ * the freshly refreshed tokens.
13
+ *
14
+ * REQUIRED: Your app must expose the refresh route:
15
+ * ```typescript
16
+ * // app/api/auth/refresh/route.ts
17
+ * export { POST } from '@payez/next-mvp/routes/auth/refresh';
18
+ * ```
19
+ *
20
+ * @version 2.0.0
21
+ */
22
+
23
+ import { NextRequest } from 'next/server';
24
+ import { getSession as getRedisSession, SessionData } from './session-store';
25
+ import { getSession as getBetterAuthSession } from '../server/auth';
26
+ import { getRedis } from './redis';
27
+ import { getAppSlug } from './app-slug';
28
+ import { tokenLogId } from './token-log-id';
29
+
30
+ // 5 minute threshold for "needs refresh" - matches refresh handler pattern
31
+ const REFRESH_THRESHOLD_MS = 5 * 60 * 1000;
32
+
33
+ // Concurrent refresh handling configuration
34
+ const CONCURRENT_REFRESH_POLL_INTERVAL_MS = 200; // How often to poll session during concurrent refresh
35
+ const CONCURRENT_REFRESH_MAX_WAIT_MS = 8000; // Max time to wait for concurrent refresh to complete
36
+ const REFRESH_RETRY_DELAY_MS = 500; // Delay before retrying after failed concurrent refresh
37
+ const KEY_PROPAGATION_DELAY_MS = 150; // Delay after refresh to allow JWKS cache updates in downstream services
38
+
39
+ export interface TokenResult {
40
+ success: true;
41
+ accessToken: string;
42
+ sessionData: SessionData;
43
+ }
44
+
45
+ export interface TokenError {
46
+ success: false;
47
+ error: 'NO_SESSION' | 'NO_TOKEN' | 'EXPIRED' | 'REFRESH_FAILED' | 'SESSION_EXPIRED_NO_REFRESH';
48
+ message: string;
49
+ terminal?: boolean; // If true, don't retry - redirect to login
50
+ // WO-1 (genuine-dead refresh): the VERBATIM upstream reason from the IDP, preserved
51
+ // end-to-end so the consumer can surface an honest error + halt a futile re-auth loop
52
+ // (e.g. an unapproved user whose login mints a bearer but whose refresh terminally
53
+ // fails). `error` stays the stable category for existing consumers; `code`/`resolution`
54
+ // carry the real cause. Never soften — surface it.
55
+ code?: string; // Upstream IDP error code (e.g. UNAUTHORIZED, USER_NOT_APPROVED)
56
+ resolution?: string; // Upstream human-readable resolution hint, if any
57
+ }
58
+
59
+ export type EnsureFreshTokenResult = TokenResult | TokenError;
60
+
61
+ /**
62
+ * Check if token needs refresh based on expiration time
63
+ */
64
+ function needsRefresh(accessTokenExpires: number | undefined): boolean {
65
+ if (!accessTokenExpires) return true;
66
+ const timeUntilExpiry = accessTokenExpires - Date.now();
67
+ return timeUntilExpiry <= REFRESH_THRESHOLD_MS;
68
+ }
69
+
70
+ /**
71
+ * Helper to delay execution
72
+ */
73
+ function delay(ms: number): Promise<void> {
74
+ return new Promise(resolve => setTimeout(resolve, ms));
75
+ }
76
+
77
+ /**
78
+ * Wait for a concurrent refresh to complete by polling the session.
79
+ * Returns true if session becomes fresh, false if timeout reached.
80
+ */
81
+ async function waitForConcurrentRefresh(
82
+ sessionToken: string,
83
+ maxWaitMs: number = CONCURRENT_REFRESH_MAX_WAIT_MS
84
+ ): Promise<{ success: boolean; sessionData?: SessionData }> {
85
+ const startTime = Date.now();
86
+
87
+ while (Date.now() - startTime < maxWaitMs) {
88
+ await delay(CONCURRENT_REFRESH_POLL_INTERVAL_MS);
89
+
90
+ const sessionData = await getRedisSession(sessionToken);
91
+
92
+ if (!sessionData) {
93
+ return { success: false };
94
+ }
95
+
96
+ // Check if token is now fresh
97
+ if (!needsRefresh(sessionData.idpAccessTokenExpires)) {
98
+ return { success: true, sessionData };
99
+ }
100
+
101
+ // Check if session has a new access token (even if still within threshold)
102
+ if (sessionData.idpAccessToken && sessionData.idpAccessTokenExpires &&
103
+ sessionData.idpAccessTokenExpires > Date.now()) {
104
+ return { success: true, sessionData };
105
+ }
106
+ }
107
+
108
+ return { success: false };
109
+ }
110
+
111
+ /**
112
+ * Get the internal API URL for making internal service calls.
113
+ * INTERNAL_API_URL is REQUIRED - no fallbacks.
114
+ */
115
+ function getInternalApiUrl(request: NextRequest): string {
116
+ const internalUrl = process.env.INTERNAL_API_URL;
117
+ if (!internalUrl) {
118
+ throw new Error(
119
+ '[INTERNAL_API_URL] FATAL: INTERNAL_API_URL environment variable is REQUIRED. ' +
120
+ 'Set it to this app\'s internal K8s service URL (e.g., http://myapp.namespace.svc.cluster.local:80) ' +
121
+ 'or http://localhost:3000 for local development.'
122
+ );
123
+ }
124
+ return internalUrl;
125
+ }
126
+
127
+ /**
128
+ * Result of triggerRefresh - includes terminal flag for unrecoverable errors
129
+ */
130
+ interface RefreshResult {
131
+ success: boolean;
132
+ terminal?: boolean; // If true, session is dead - don't retry, redirect to login
133
+ code?: string; // Error code from refresh endpoint
134
+ message?: string; // WO-1: verbatim human message from the refresh endpoint
135
+ resolution?: string; // WO-1: verbatim resolution hint from the refresh endpoint
136
+ }
137
+
138
+ /**
139
+ * Trigger a token refresh via the refresh API endpoint.
140
+ *
141
+ * HANDLES CONCURRENT REFRESH (409):
142
+ * When another request is already refreshing the token, this function
143
+ * waits for that refresh to complete instead of failing immediately.
144
+ * This prevents race conditions where multiple parallel API calls
145
+ * could cause unnecessary refresh failures.
146
+ *
147
+ * TERMINAL STATES:
148
+ * Returns { success: false, terminal: true } when the session cannot be
149
+ * recovered (e.g., no refresh token). Callers should redirect to login.
150
+ */
151
+ async function triggerRefresh(
152
+ request: NextRequest,
153
+ sessionToken: string,
154
+ retryCount: number = 0
155
+ ): Promise<RefreshResult> {
156
+ const maxRetries = 2;
157
+
158
+ try {
159
+ const baseUrl = getInternalApiUrl(request);
160
+ const requestId = `refresh_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
161
+
162
+ const response = await fetch(`${baseUrl}/api/auth/refresh`, {
163
+ method: 'POST',
164
+ headers: {
165
+ 'Content-Type': 'application/json',
166
+ 'Cookie': request.headers.get('cookie') || '',
167
+ 'X-Session-Token': sessionToken,
168
+ 'X-Request-Id': requestId,
169
+ },
170
+ });
171
+
172
+ // Handle 409 Conflict - another refresh is in progress
173
+ if (response.status === 409) {
174
+ // Wait for the concurrent refresh to complete
175
+ const waitResult = await waitForConcurrentRefresh(sessionToken);
176
+
177
+ if (waitResult.success) {
178
+ return { success: true };
179
+ }
180
+
181
+ // Concurrent refresh didn't produce a fresh token - try again if we have retries left
182
+ if (retryCount < maxRetries) {
183
+ await delay(REFRESH_RETRY_DELAY_MS);
184
+ return triggerRefresh(request, sessionToken, retryCount + 1);
185
+ }
186
+
187
+ return { success: false };
188
+ }
189
+
190
+ // Handle other non-OK responses
191
+ if (!response.ok) {
192
+ // Parse response body to check for terminal errors
193
+ let responseData: any = {};
194
+ try {
195
+ responseData = await response.json();
196
+ } catch {
197
+ // Ignore parse errors
198
+ }
199
+
200
+ // Log the failure for debugging
201
+ console.warn('[TOKEN_LIFECYCLE] Refresh request failed:', {
202
+ status: response.status,
203
+ statusText: response.statusText,
204
+ baseUrl,
205
+ retryCount,
206
+ code: responseData.code,
207
+ terminal: responseData.terminal
208
+ });
209
+
210
+ // CHECK FOR TERMINAL STATE: No refresh token = session is dead
211
+ // Don't retry - user must re-authenticate
212
+ if (responseData.code === 'NO_REFRESH_TOKEN' || responseData.terminal === true) {
213
+ console.error('[TOKEN_LIFECYCLE] TERMINAL: Session has no refresh token - user must re-login');
214
+ // WO-1: preserve the verbatim upstream reason. refresh.ts puts the human
215
+ // message in `error` and the code in `code`; carry both up so the consumer
216
+ // can tell the user WHY (not just "session expired") and stop a futile loop.
217
+ return {
218
+ success: false,
219
+ terminal: true,
220
+ code: responseData.code,
221
+ message: responseData.error,
222
+ resolution: responseData.resolution,
223
+ };
224
+ }
225
+
226
+ // For other 401s, check if maybe session was refreshed by another request
227
+ if (response.status === 401 && retryCount < maxRetries) {
228
+ await delay(REFRESH_RETRY_DELAY_MS);
229
+
230
+ const sessionData = await getRedisSession(sessionToken);
231
+ if (sessionData && !needsRefresh(sessionData.idpAccessTokenExpires)) {
232
+ return { success: true };
233
+ }
234
+ }
235
+
236
+ return { success: false, code: responseData.code };
237
+ }
238
+
239
+ const result = await response.json();
240
+ const success = result.refreshed === true || result.reason === 'already_fresh';
241
+ return { success };
242
+ } catch (error) {
243
+ // Log network errors for debugging
244
+ console.error('[TOKEN_LIFECYCLE] Refresh network error:', {
245
+ error: error instanceof Error ? error.message : String(error),
246
+ retryCount
247
+ });
248
+
249
+ // On network error, check if maybe another request refreshed the token
250
+ if (retryCount < maxRetries) {
251
+ await delay(REFRESH_RETRY_DELAY_MS);
252
+ const sessionData = await getRedisSession(sessionToken);
253
+ if (sessionData && !needsRefresh(sessionData.idpAccessTokenExpires)) {
254
+ return { success: true };
255
+ }
256
+ }
257
+
258
+ return { success: false };
259
+ }
260
+ }
261
+
262
+ /**
263
+ * Ensures we have a fresh access token before making API calls.
264
+ *
265
+ * This utility checks token expiration and triggers a refresh if needed,
266
+ * preventing 401 errors from expired tokens being sent to downstream APIs.
267
+ *
268
+ * @param request - The incoming NextRequest
269
+ * @returns TokenResult with accessToken and sessionData, or TokenError
270
+ *
271
+ * @example
272
+ * ```typescript
273
+ * import { ensureFreshToken } from '@payez/next-mvp/lib/token-lifecycle';
274
+ *
275
+ * export async function GET(request: NextRequest) {
276
+ * const tokenResult = await ensureFreshToken(request);
277
+ * if (!tokenResult.success) {
278
+ * return NextResponse.json({ error: tokenResult.error }, { status: 401 });
279
+ * }
280
+ *
281
+ * // Use tokenResult.accessToken for downstream API calls
282
+ * const response = await fetch('https://api.example.com/data', {
283
+ * headers: { 'Authorization': `Bearer ${tokenResult.accessToken}` }
284
+ * });
285
+ * }
286
+ * ```
287
+ */
288
+ export async function ensureFreshToken(
289
+ request: NextRequest
290
+ ): Promise<EnsureFreshTokenResult> {
291
+ try {
292
+ // 1. Get Better Auth session to extract sessionToken
293
+ const betterAuthSession = await getBetterAuthSession(request);
294
+
295
+ if (!betterAuthSession?.session?.token) {
296
+ console.warn('[TOKEN_LIFECYCLE] NO_SESSION - Better Auth session not found');
297
+ return {
298
+ success: false,
299
+ error: 'NO_SESSION',
300
+ message: 'No session available',
301
+ };
302
+ }
303
+
304
+ const sessionToken = betterAuthSession.session.token;
305
+
306
+ // 2. Get session data from Redis (legacy prefix), or Better Auth's secondary storage
307
+ let sessionData = await getRedisSession(sessionToken);
308
+
309
+ if (!sessionData) {
310
+ // Try Better Auth's secondaryStorage key (ba:{slug}:{token})
311
+ try {
312
+ const baKey = `ba:${getAppSlug()}:${sessionToken}`;
313
+ const baRaw = await getRedis().get(baKey);
314
+ if (baRaw) {
315
+ const baSession = JSON.parse(baRaw);
316
+ const idpTokens = baSession.idpTokens;
317
+
318
+ sessionData = {
319
+ userId: idpTokens?.userId || baSession.user?.id || betterAuthSession.user?.id || '',
320
+ email: idpTokens?.email || baSession.user?.email || betterAuthSession.user?.email || '',
321
+ name: idpTokens?.name || baSession.user?.name || betterAuthSession.user?.name,
322
+ roles: idpTokens?.roles || [],
323
+ idpAccessToken: idpTokens?.idpAccessToken,
324
+ idpRefreshToken: idpTokens?.idpRefreshToken,
325
+ idpAccessTokenExpires: idpTokens?.idpAccessTokenExpires
326
+ || (baSession.session?.expiresAt ? new Date(baSession.session.expiresAt).getTime() : Date.now() + 24 * 60 * 60 * 1000),
327
+ /**
328
+ * ⚠ THESE WERE HARDCODED `true` / `'google'`. (QAPert finding #3,
329
+ * BAPert ruling, card 167892.)
330
+ *
331
+ * This rebuild path assumed EVERY session is a Google OAuth sign-in
332
+ * that completed MFA. It reads `idpTokens` for everything else —
333
+ * including roles, two lines up — and then IGNORED the stored
334
+ * mfaVerified sitting in that same object and asserted `true`.
335
+ *
336
+ * WHY IT MATTERS MORE THAN A WRONG FIELD: a passkey sign-in stores
337
+ * an HONEST mfaVerified derived from the token's `amr`. On any
338
+ * Redis miss this path OVERWROTE that false with true — so the
339
+ * session claimed an MFA the user never performed, and the honest
340
+ * derivation upstream was not weakened but VOIDED. Same defect
341
+ * class as the mints that assert completion they never did,
342
+ * arriving through a cache-miss rather than a mint.
343
+ *
344
+ * `oauthProvider: 'google'` was the second lie on the same line:
345
+ * a passkey session rebuilt here was relabelled a Google sign-in,
346
+ * destroying the provenance the sign-in path deliberately records.
347
+ * The IDP emits NO provider claim (DotNetPert), so the honest
348
+ * answer when it was not stored is UNSET — not a guess.
349
+ *
350
+ * Both now default to the SAFE direction: absent/false is
351
+ * fail-closed at every consumer we measured (`!!mfaVerified`,
352
+ * `mfaVerified || ... || false`).
353
+ */
354
+ mfaVerified: idpTokens?.mfaVerified ?? false,
355
+ // R807 (362550): the fail-closed default above stays exactly as documented;
356
+ // this records whether it was a measurement or a default. `!== undefined`
357
+ // deliberately - an explicit `false` is a signal.
358
+ mfaSignalPresent: idpTokens?.mfaVerified !== undefined,
359
+ oauthProvider: idpTokens?.oauthProvider ?? baSession.oauthProvider ?? undefined,
360
+ idpClientId: idpTokens?.idpClientId ?? idpTokens?.clientId ?? baSession.idpClientId,
361
+ merchantId: idpTokens?.merchantId ?? baSession.merchantId,
362
+ } as SessionData;
363
+ }
364
+ } catch { /* Redis unavailable */ }
365
+ }
366
+
367
+ if (!sessionData && betterAuthSession.user) {
368
+ // Last resort: build from Better Auth in-memory session (no IDP tokens)
369
+ sessionData = {
370
+ userId: betterAuthSession.user.id || '',
371
+ email: betterAuthSession.user.email || '',
372
+ name: betterAuthSession.user.name,
373
+ roles: [],
374
+ idpAccessTokenExpires: Date.now() + 24 * 60 * 60 * 1000,
375
+ /**
376
+ * ⚠ ALSO HARDCODED `true` / `'google'`, and this path is the worse of
377
+ * the two: it runs with NO IDP TOKENS AT ALL — the comment above says
378
+ * so — and still asserted that MFA was completed. It fabricated an
379
+ * assurance claim from nothing, for every consumer, not just passkey.
380
+ *
381
+ * With nothing to derive from, FALSE is the only honest value and
382
+ * UNSET is the only honest provider. Both are fail-closed.
383
+ */
384
+ mfaVerified: false,
385
+ /**
386
+ * R807 (362550) - FIFTH construction site, not in the ruling's list of four.
387
+ * This path has NO IDP TOKENS AT ALL, so there is no producer statement to
388
+ * record: the `false` above is a DEFAULT, never a measurement. `false` is
389
+ * therefore the honest signal value, and it is the conservative one for
390
+ * viability (absent/false -> do not force a re-challenge).
391
+ */
392
+ mfaSignalPresent: false,
393
+ oauthProvider: undefined,
394
+ } as SessionData;
395
+ }
396
+
397
+ if (!sessionData) {
398
+ return {
399
+ success: false,
400
+ error: 'NO_SESSION',
401
+ message: 'Session expired or not found',
402
+ };
403
+ }
404
+
405
+ // DEBUG: Log session data before refresh check
406
+ const tokenExpiresStr = sessionData.idpAccessTokenExpires
407
+ ? new Date(sessionData.idpAccessTokenExpires).toISOString()
408
+ : 'undefined';
409
+ let needsRefreshNow = needsRefresh(sessionData.idpAccessTokenExpires);
410
+
411
+ // VALIDATION: Check if the actual JWT token's exp matches what Redis claims
412
+ // This catches cases where accessTokenExpires was updated but accessToken wasn't
413
+ let tokenMismatch = false;
414
+ if (sessionData.idpAccessToken && !needsRefreshNow) {
415
+ try {
416
+ const tokenParts = sessionData.idpAccessToken.split('.');
417
+ if (tokenParts.length === 3) {
418
+ const payload = JSON.parse(Buffer.from(tokenParts[1], 'base64url').toString());
419
+ const jwtExpMs = (payload.exp || 0) * 1000;
420
+ const now = Date.now();
421
+
422
+ // If the JWT is actually expired, force a refresh regardless of what Redis says
423
+ if (jwtExpMs < now) {
424
+ console.warn('[TOKEN_LIFECYCLE] Token mismatch detected! JWT expired but Redis claims valid', {
425
+ jwtExp: new Date(jwtExpMs).toISOString(),
426
+ redisAccessTokenExpires: tokenExpiresStr,
427
+ now: new Date(now).toISOString(),
428
+ mismatchMs: sessionData.idpAccessTokenExpires ? sessionData.idpAccessTokenExpires - jwtExpMs : 'N/A'
429
+ });
430
+ needsRefreshNow = true;
431
+ tokenMismatch = true;
432
+ }
433
+ }
434
+ } catch (e) {
435
+ // If we can't decode, proceed with normal logic
436
+ console.warn('[TOKEN_LIFECYCLE] Could not validate JWT exp claim:', e);
437
+ }
438
+ }
439
+
440
+ console.log('[TOKEN_LIFECYCLE] ensureFreshToken check:', {
441
+ sessionToken: tokenLogId(sessionToken),
442
+ accessTokenExpires: tokenExpiresStr,
443
+ now: new Date().toISOString(),
444
+ needsRefresh: needsRefreshNow,
445
+ tokenMismatch,
446
+ hasRefreshToken: !!sessionData.idpRefreshToken
447
+ });
448
+
449
+ // 3. Check if token needs refresh
450
+ if (needsRefreshNow) {
451
+ // 4. Trigger refresh
452
+ console.log('[TOKEN_LIFECYCLE] Triggering refresh...');
453
+ const refreshResult = await triggerRefresh(request, sessionToken);
454
+
455
+ if (!refreshResult.success) {
456
+ // Check for terminal state - session cannot be recovered
457
+ if (refreshResult.terminal) {
458
+ console.error('[TOKEN_LIFECYCLE] TERMINAL: Session expired - redirect to login', {
459
+ code: refreshResult.code,
460
+ message: refreshResult.message,
461
+ });
462
+ // WO-1: keep `error` as the stable terminal category (existing consumers
463
+ // branch on SESSION_EXPIRED_NO_REFRESH) but surface the verbatim upstream
464
+ // reason via code/message/resolution so the user learns WHY and a genuinely
465
+ // dead session (e.g. unapproved account) doesn't loop login→bounce→login.
466
+ return {
467
+ success: false,
468
+ error: 'SESSION_EXPIRED_NO_REFRESH',
469
+ message: refreshResult.message || 'Session expired. Please sign in again.',
470
+ terminal: true,
471
+ code: refreshResult.code,
472
+ resolution: refreshResult.resolution,
473
+ };
474
+ }
475
+
476
+ console.warn('[TOKEN_LIFECYCLE] Refresh failed');
477
+ return {
478
+ success: false,
479
+ error: 'REFRESH_FAILED',
480
+ message: 'Token refresh failed',
481
+ };
482
+ }
483
+
484
+ // 5. Re-fetch session data after refresh
485
+ sessionData = await getRedisSession(sessionToken);
486
+ console.log('[TOKEN_LIFECYCLE] After refresh:', {
487
+ hasAccessToken: !!sessionData?.idpAccessToken,
488
+ newAccessTokenExpires: sessionData?.idpAccessTokenExpires
489
+ ? new Date(sessionData.idpAccessTokenExpires).toISOString()
490
+ : 'undefined'
491
+ });
492
+
493
+ if (!sessionData?.idpAccessToken) {
494
+ return {
495
+ success: false,
496
+ error: 'REFRESH_FAILED',
497
+ message: 'No access token after refresh',
498
+ };
499
+ }
500
+
501
+ // 5.5. Key propagation delay - allow downstream services (like Vibe) to cache new JWKS
502
+ // This is critical when IDP rotates signing keys - the new token's kid may not be
503
+ // immediately available in Vibe's JWKS cache
504
+ await delay(KEY_PROPAGATION_DELAY_MS);
505
+ }
506
+
507
+ // 6. Return session — accessToken may be empty for social-only OAuth sessions
508
+ return {
509
+ success: true,
510
+ accessToken: sessionData.idpAccessToken || '',
511
+ sessionData,
512
+ };
513
+ } catch (error) {
514
+ console.error('[TOKEN_LIFECYCLE] Error:', error);
515
+ return {
516
+ success: false,
517
+ error: 'NO_SESSION',
518
+ message: error instanceof Error ? error.message : 'Unknown error',
519
+ };
520
+ }
521
+ }
522
+
523
+ /**
524
+ * Get authorization header from fresh token.
525
+ * Convenience wrapper for API routes.
526
+ *
527
+ * @param request - The incoming NextRequest
528
+ * @returns Authorization header string or null if token unavailable
529
+ *
530
+ * @example
531
+ * ```typescript
532
+ * const authHeader = await getFreshAuthHeader(request);
533
+ * if (!authHeader) {
534
+ * return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
535
+ * }
536
+ * ```
537
+ */
538
+ export async function getFreshAuthHeader(
539
+ request: NextRequest
540
+ ): Promise<string | null> {
541
+ const result = await ensureFreshToken(request);
542
+ if (!result.success) {
543
+ return null;
544
+ }
545
+ return `Bearer ${result.accessToken}`;
546
+ }