@payez/next-mvp 4.0.1 → 4.0.3
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.
- package/dist/api/auth-handler.d.ts +66 -0
- package/dist/api/auth-handler.js +397 -0
- package/dist/api/index.d.ts +10 -0
- package/dist/api/index.js +19 -0
- package/dist/api-handlers/account/change-password.d.ts +9 -0
- package/dist/api-handlers/account/change-password.js +110 -0
- package/dist/api-handlers/account/masked-info.d.ts +2 -0
- package/dist/api-handlers/account/masked-info.js +41 -0
- package/dist/api-handlers/account/profile.d.ts +3 -0
- package/dist/api-handlers/account/profile.js +63 -0
- package/dist/api-handlers/account/recovery/initiate.d.ts +2 -0
- package/dist/api-handlers/account/recovery/initiate.js +26 -0
- package/dist/api-handlers/account/recovery/send-code.d.ts +2 -0
- package/dist/api-handlers/account/recovery/send-code.js +28 -0
- package/dist/api-handlers/account/recovery/verify-code.d.ts +2 -0
- package/dist/api-handlers/account/recovery/verify-code.js +28 -0
- package/dist/api-handlers/account/reset-password.d.ts +2 -0
- package/dist/api-handlers/account/reset-password.js +26 -0
- package/dist/api-handlers/account/send-code.d.ts +24 -0
- package/dist/api-handlers/account/send-code.js +60 -0
- package/dist/api-handlers/account/update-phone.d.ts +27 -0
- package/dist/api-handlers/account/update-phone.js +64 -0
- package/dist/api-handlers/account/validate-password.d.ts +17 -0
- package/dist/api-handlers/account/validate-password.js +81 -0
- package/dist/api-handlers/account/verify-email.d.ts +26 -0
- package/dist/api-handlers/account/verify-email.js +106 -0
- package/dist/api-handlers/account/verify-sms.d.ts +26 -0
- package/dist/api-handlers/account/verify-sms.js +106 -0
- package/dist/api-handlers/admin/analytics.d.ts +19 -0
- package/dist/api-handlers/admin/analytics.js +378 -0
- package/dist/api-handlers/admin/audit.d.ts +19 -0
- package/dist/api-handlers/admin/audit.js +213 -0
- package/dist/api-handlers/admin/index.d.ts +21 -0
- package/dist/api-handlers/admin/index.js +42 -0
- package/dist/api-handlers/admin/redis-sessions.d.ts +35 -0
- package/dist/api-handlers/admin/redis-sessions.js +203 -0
- package/dist/api-handlers/admin/sessions.d.ts +20 -0
- package/dist/api-handlers/admin/sessions.js +283 -0
- package/dist/api-handlers/admin/site-logs.d.ts +45 -0
- package/dist/api-handlers/admin/site-logs.js +317 -0
- package/dist/api-handlers/admin/stats.d.ts +20 -0
- package/dist/api-handlers/admin/stats.js +239 -0
- package/dist/api-handlers/admin/users.d.ts +19 -0
- package/dist/api-handlers/admin/users.js +221 -0
- package/dist/api-handlers/admin/vibe-data.d.ts +79 -0
- package/dist/api-handlers/admin/vibe-data.js +267 -0
- package/dist/api-handlers/anon/preferences.d.ts +37 -0
- package/dist/api-handlers/anon/preferences.js +96 -0
- package/dist/api-handlers/auth/jwks.d.ts +2 -0
- package/dist/api-handlers/auth/jwks.js +24 -0
- package/dist/api-handlers/auth/login.d.ts +42 -0
- package/dist/api-handlers/auth/login.js +178 -0
- package/dist/api-handlers/auth/refresh.d.ts +74 -0
- package/dist/api-handlers/auth/refresh.js +633 -0
- package/dist/api-handlers/auth/signout.d.ts +37 -0
- package/dist/api-handlers/auth/signout.js +186 -0
- package/dist/api-handlers/auth/status.d.ts +8 -0
- package/dist/api-handlers/auth/status.js +23 -0
- package/dist/api-handlers/auth/update-session.d.ts +37 -0
- package/dist/api-handlers/auth/update-session.js +93 -0
- package/dist/api-handlers/auth/validate.d.ts +6 -0
- package/dist/api-handlers/auth/validate.js +43 -0
- package/dist/api-handlers/auth/verify-code.d.ts +43 -0
- package/dist/api-handlers/auth/verify-code.js +90 -0
- package/dist/api-handlers/session/refresh-viability.d.ts +14 -0
- package/dist/api-handlers/session/refresh-viability.js +39 -0
- package/dist/api-handlers/session/viability.d.ts +13 -0
- package/dist/api-handlers/session/viability.js +114 -0
- package/dist/api-handlers/test/force-expire.d.ts +23 -0
- package/dist/api-handlers/test/force-expire.js +59 -0
- package/dist/auth/auth-decision.d.ts +39 -0
- package/dist/auth/auth-decision.js +182 -0
- package/dist/auth/better-auth.d.ts +79 -0
- package/dist/auth/better-auth.js +119 -0
- package/dist/auth/route-config.d.ts +66 -0
- package/dist/auth/route-config.js +190 -0
- package/dist/auth/types/auth-types.d.ts +417 -0
- package/dist/auth/types/auth-types.js +53 -0
- package/dist/auth/types/index.d.ts +6 -0
- package/dist/auth/types/index.js +22 -0
- package/dist/auth/unauthenticated-routes.d.ts +1 -0
- package/dist/auth/unauthenticated-routes.js +19 -0
- package/dist/auth/utils/idp-client.d.ts +94 -0
- package/dist/auth/utils/idp-client.js +384 -0
- package/dist/auth/utils/index.d.ts +5 -0
- package/dist/auth/utils/index.js +21 -0
- package/dist/auth/utils/token-utils.d.ts +83 -0
- package/dist/auth/utils/token-utils.js +218 -0
- package/dist/client/AuthContext.d.ts +19 -0
- package/dist/client/AuthContext.js +115 -0
- package/dist/client/better-auth-client.d.ts +1020 -0
- package/dist/client/better-auth-client.js +68 -0
- package/dist/client/fetch-with-auth.d.ts +11 -0
- package/dist/client/fetch-with-auth.js +44 -0
- package/dist/client/fetchWithSession.d.ts +3 -0
- package/dist/client/fetchWithSession.js +24 -0
- package/dist/client/index.d.ts +9 -0
- package/dist/client/index.js +20 -0
- package/dist/client/useAnonSession.d.ts +36 -0
- package/dist/client/useAnonSession.js +99 -0
- package/dist/components/SessionSync.d.ts +13 -0
- package/dist/components/SessionSync.js +121 -0
- package/dist/components/SignalRHealthCheck.d.ts +10 -0
- package/dist/components/SignalRHealthCheck.js +97 -0
- package/dist/components/account/MobileNavDrawer.d.ts +32 -0
- package/dist/components/account/MobileNavDrawer.js +81 -0
- package/dist/components/account/UserAvatarMenu.d.ts +20 -0
- package/dist/components/account/UserAvatarMenu.js +91 -0
- package/dist/components/account/index.d.ts +9 -0
- package/dist/components/account/index.js +13 -0
- package/dist/components/admin/AlertSettingsTab.d.ts +48 -0
- package/dist/components/admin/AlertSettingsTab.js +351 -0
- package/dist/components/admin/AnalyticsTab.d.ts +22 -0
- package/dist/components/admin/AnalyticsTab.js +167 -0
- package/dist/components/admin/DataBrowserTab.d.ts +19 -0
- package/dist/components/admin/DataBrowserTab.js +252 -0
- package/dist/components/admin/LoggingSettingsTab.d.ts +73 -0
- package/dist/components/admin/LoggingSettingsTab.js +339 -0
- package/dist/components/admin/SessionsTab.d.ts +37 -0
- package/dist/components/admin/SessionsTab.js +165 -0
- package/dist/components/admin/StatsTab.d.ts +53 -0
- package/dist/components/admin/StatsTab.js +161 -0
- package/dist/components/admin/VibeAdminContext.d.ts +32 -0
- package/dist/components/admin/VibeAdminContext.js +38 -0
- package/dist/components/admin/VibeAdminLayout.d.ts +11 -0
- package/dist/components/admin/VibeAdminLayout.js +71 -0
- package/dist/components/admin/index.d.ts +29 -0
- package/dist/components/admin/index.js +44 -0
- package/dist/components/auth/FederatedAuthSection.d.ts +8 -0
- package/dist/components/auth/FederatedAuthSection.js +45 -0
- package/dist/components/auth/ModeAwareLoginPage.d.ts +10 -0
- package/dist/components/auth/ModeAwareLoginPage.js +42 -0
- package/dist/components/auth/ModeAwareSignupPage.d.ts +9 -0
- package/dist/components/auth/ModeAwareSignupPage.js +78 -0
- package/dist/components/auth/TraditionalAuthSection.d.ts +14 -0
- package/dist/components/auth/TraditionalAuthSection.js +20 -0
- package/dist/components/recovery/CompleteStep.d.ts +5 -0
- package/dist/components/recovery/CompleteStep.js +8 -0
- package/dist/components/recovery/InitiateRecoveryStep.d.ts +8 -0
- package/dist/components/recovery/InitiateRecoveryStep.js +20 -0
- package/dist/components/recovery/SelectMethodStep.d.ts +8 -0
- package/dist/components/recovery/SelectMethodStep.js +8 -0
- package/dist/components/recovery/SetPasswordStep.d.ts +6 -0
- package/dist/components/recovery/SetPasswordStep.js +20 -0
- package/dist/components/recovery/VerifyCodeStep.d.ts +10 -0
- package/dist/components/recovery/VerifyCodeStep.js +24 -0
- package/dist/components/reserved/ReservedRecoveryWarning.d.ts +38 -0
- package/dist/components/reserved/ReservedRecoveryWarning.js +92 -0
- package/dist/components/reserved/ReservedStatusBox.d.ts +30 -0
- package/dist/components/reserved/ReservedStatusBox.js +71 -0
- package/dist/components/ui/BetaBadge.d.ts +29 -0
- package/dist/components/ui/BetaBadge.js +38 -0
- package/dist/components/ui/Footer.d.ts +37 -0
- package/dist/components/ui/Footer.js +41 -0
- package/dist/config/env.d.ts +66 -0
- package/dist/config/env.js +57 -0
- package/dist/config/logger.d.ts +57 -0
- package/dist/config/logger.js +73 -0
- package/dist/config/logging-config.d.ts +30 -0
- package/dist/config/logging-config.js +122 -0
- package/dist/config/unauthenticated-routes.d.ts +17 -0
- package/dist/config/unauthenticated-routes.js +24 -0
- package/dist/config/vibe-log-transport.d.ts +81 -0
- package/dist/config/vibe-log-transport.js +212 -0
- package/dist/edge/internal-api-url.d.ts +53 -0
- package/dist/edge/internal-api-url.js +63 -0
- package/dist/edge/middleware.d.ts +14 -0
- package/dist/edge/middleware.js +32 -0
- package/dist/hooks/useAuth.d.ts +23 -0
- package/dist/hooks/useAuth.js +83 -0
- package/dist/hooks/useAuthSettings.d.ts +59 -0
- package/dist/hooks/useAuthSettings.js +93 -0
- package/dist/hooks/useAvailableProviders.d.ts +43 -0
- package/dist/hooks/useAvailableProviders.js +112 -0
- package/dist/hooks/usePasswordValidation.d.ts +27 -0
- package/dist/hooks/usePasswordValidation.js +102 -0
- package/dist/hooks/useProfile.d.ts +15 -0
- package/dist/hooks/useProfile.js +59 -0
- package/dist/hooks/usePublicAuthSettings.d.ts +56 -0
- package/dist/hooks/usePublicAuthSettings.js +131 -0
- package/dist/hooks/useSessionExpiration.d.ts +56 -0
- package/dist/hooks/useSessionExpiration.js +72 -0
- package/dist/hooks/useViabilitySession.d.ts +75 -0
- package/dist/hooks/useViabilitySession.js +269 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +53 -0
- package/dist/lib/anon-session.d.ts +74 -0
- package/dist/lib/anon-session.js +169 -0
- package/dist/lib/api-handler.d.ts +123 -0
- package/dist/lib/api-handler.js +478 -0
- package/dist/lib/app-slug.d.ts +95 -0
- package/dist/lib/app-slug.js +172 -0
- package/dist/lib/demo-mode.d.ts +6 -0
- package/dist/lib/demo-mode.js +16 -0
- package/dist/lib/geolocation.d.ts +64 -0
- package/dist/lib/geolocation.js +235 -0
- package/dist/lib/idp-client-config.d.ts +75 -0
- package/dist/lib/idp-client-config.js +425 -0
- package/dist/lib/idp-fetch.d.ts +14 -0
- package/dist/lib/idp-fetch.js +91 -0
- package/dist/lib/internal-api.d.ts +87 -0
- package/dist/lib/internal-api.js +122 -0
- package/dist/lib/jwt-decode-client.d.ts +10 -0
- package/dist/lib/jwt-decode-client.js +46 -0
- package/dist/lib/jwt-decode.d.ts +48 -0
- package/dist/lib/jwt-decode.js +57 -0
- package/dist/lib/rate-limit-service.d.ts +23 -0
- package/dist/lib/rate-limit-service.js +6 -0
- package/dist/lib/redis.d.ts +5 -0
- package/dist/lib/redis.js +28 -0
- package/dist/lib/refresh-token-validator.d.ts +13 -0
- package/dist/lib/refresh-token-validator.js +117 -0
- package/dist/lib/roles.d.ts +145 -0
- package/dist/lib/roles.js +168 -0
- package/dist/lib/secret-validation.d.ts +4 -0
- package/dist/lib/secret-validation.js +14 -0
- package/dist/lib/session-store.d.ts +170 -0
- package/dist/lib/session-store.js +545 -0
- package/dist/lib/session.d.ts +21 -0
- package/dist/lib/session.js +26 -0
- package/dist/lib/site-logger.d.ts +214 -0
- package/dist/lib/site-logger.js +210 -0
- package/dist/lib/standardized-client-api.d.ts +161 -0
- package/dist/lib/standardized-client-api.js +791 -0
- package/dist/lib/startup-init.d.ts +40 -0
- package/dist/lib/startup-init.js +257 -0
- package/dist/lib/test-aware-get-token.d.ts +2 -0
- package/dist/lib/test-aware-get-token.js +86 -0
- package/dist/lib/token-expiry.d.ts +14 -0
- package/dist/lib/token-expiry.js +39 -0
- package/dist/lib/token-lifecycle.d.ts +78 -0
- package/dist/lib/token-lifecycle.js +360 -0
- package/dist/lib/types/api-responses.d.ts +128 -0
- package/dist/lib/types/api-responses.js +171 -0
- package/dist/lib/user-agent-parser.d.ts +50 -0
- package/dist/lib/user-agent-parser.js +220 -0
- package/dist/logging/api/admin-analytics.d.ts +3 -0
- package/dist/logging/api/admin-analytics.js +45 -0
- package/dist/logging/api/audit-log.d.ts +3 -0
- package/dist/logging/api/audit-log.js +52 -0
- package/dist/logging/components/AdminAnalyticsLayout.d.ts +10 -0
- package/dist/logging/components/AdminAnalyticsLayout.js +11 -0
- package/dist/logging/components/AuditLogViewer.d.ts +7 -0
- package/dist/logging/components/AuditLogViewer.js +51 -0
- package/dist/logging/components/ErrorMetricsCard.d.ts +7 -0
- package/dist/logging/components/ErrorMetricsCard.js +16 -0
- package/dist/logging/components/HealthMetricsCard.d.ts +7 -0
- package/dist/logging/components/HealthMetricsCard.js +19 -0
- package/dist/logging/hooks/useAdminAnalytics.d.ts +24 -0
- package/dist/logging/hooks/useAdminAnalytics.js +22 -0
- package/dist/logging/hooks/useAuditLog.d.ts +6 -0
- package/dist/logging/hooks/useAuditLog.js +25 -0
- package/dist/logging/hooks/useErrorMetrics.d.ts +6 -0
- package/dist/logging/hooks/useErrorMetrics.js +38 -0
- package/dist/logging/hooks/useHealthMetrics.d.ts +6 -0
- package/dist/logging/hooks/useHealthMetrics.js +41 -0
- package/dist/logging/index.d.ts +11 -0
- package/dist/logging/index.js +40 -0
- package/dist/logging/types/analytics.d.ts +68 -0
- package/dist/logging/types/analytics.js +3 -0
- package/dist/logging/types/audit.d.ts +29 -0
- package/dist/logging/types/audit.js +2 -0
- package/dist/logging/types/index.d.ts +2 -0
- package/dist/logging/types/index.js +19 -0
- package/dist/middleware/auth-decision.d.ts +33 -0
- package/dist/middleware/auth-decision.js +65 -0
- package/dist/middleware/create-middleware.d.ts +102 -0
- package/dist/middleware/create-middleware.js +469 -0
- package/dist/middleware/rbac-check.d.ts +51 -0
- package/dist/middleware/rbac-check.js +219 -0
- package/dist/middleware/twofa-presets.d.ts +134 -0
- package/dist/middleware/twofa-presets.js +175 -0
- package/dist/models/DecodedAccessToken.d.ts +17 -0
- package/dist/models/DecodedAccessToken.js +2 -0
- package/dist/models/SessionModel.d.ts +122 -0
- package/dist/models/SessionModel.js +136 -0
- package/dist/pages/admin-login/page.d.ts +31 -0
- package/dist/pages/admin-login/page.js +73 -0
- package/dist/pages/admin-page-permissions/PagePermissionsAdminPage.d.ts +18 -0
- package/dist/pages/admin-page-permissions/PagePermissionsAdminPage.js +276 -0
- package/dist/pages/admin-page-permissions/index.d.ts +6 -0
- package/dist/pages/admin-page-permissions/index.js +13 -0
- package/dist/pages/admin-roles/RolesAdminPage.d.ts +16 -0
- package/dist/pages/admin-roles/RolesAdminPage.js +261 -0
- package/dist/pages/admin-roles/index.d.ts +8 -0
- package/dist/pages/admin-roles/index.js +15 -0
- package/dist/pages/admin-roles/modals.d.ts +72 -0
- package/dist/pages/admin-roles/modals.js +154 -0
- package/dist/pages/client-admin/ClientSiteAdminPage.d.ts +79 -0
- package/dist/pages/client-admin/ClientSiteAdminPage.js +179 -0
- package/dist/pages/client-admin/index.d.ts +32 -0
- package/dist/pages/client-admin/index.js +37 -0
- package/dist/pages/coming-soon/page.d.ts +8 -0
- package/dist/pages/coming-soon/page.js +28 -0
- package/dist/pages/login/page.d.ts +22 -0
- package/dist/pages/login/page.js +230 -0
- package/dist/pages/profile/EnhancedProfilePage.d.ts +13 -0
- package/dist/pages/profile/EnhancedProfilePage.js +150 -0
- package/dist/pages/profile/index.d.ts +8 -0
- package/dist/pages/profile/index.js +16 -0
- package/dist/pages/profile/page.d.ts +19 -0
- package/dist/pages/profile/page.js +47 -0
- package/dist/pages/recovery/page.d.ts +1 -0
- package/dist/pages/recovery/page.js +142 -0
- package/dist/pages/roles/MyRolesPage.d.ts +24 -0
- package/dist/pages/roles/MyRolesPage.js +71 -0
- package/dist/pages/roles/components.d.ts +63 -0
- package/dist/pages/roles/components.js +108 -0
- package/dist/pages/roles/index.d.ts +8 -0
- package/dist/pages/roles/index.js +19 -0
- package/dist/pages/security/EnhancedSecurityPage.d.ts +14 -0
- package/dist/pages/security/EnhancedSecurityPage.js +248 -0
- package/dist/pages/security/index.d.ts +8 -0
- package/dist/pages/security/index.js +16 -0
- package/dist/pages/security/page.d.ts +21 -0
- package/dist/pages/security/page.js +212 -0
- package/dist/pages/settings/EnhancedSettingsPage.d.ts +46 -0
- package/dist/pages/settings/EnhancedSettingsPage.js +231 -0
- package/dist/pages/settings/index.d.ts +8 -0
- package/dist/pages/settings/index.js +16 -0
- package/dist/pages/settings/page.d.ts +7 -0
- package/dist/pages/settings/page.js +26 -0
- package/dist/pages/showcase/ShowcasePage.d.ts +13 -0
- package/dist/pages/showcase/ShowcasePage.js +142 -0
- package/dist/pages/showcase/index.d.ts +12 -0
- package/dist/pages/showcase/index.js +17 -0
- package/dist/pages/test-env/EmergencyLogoutPage.d.ts +14 -0
- package/dist/pages/test-env/EmergencyLogoutPage.js +99 -0
- package/dist/pages/test-env/JwtInspectPage.d.ts +14 -0
- package/dist/pages/test-env/JwtInspectPage.js +116 -0
- package/dist/pages/test-env/RefreshTokenPage.d.ts +15 -0
- package/dist/pages/test-env/RefreshTokenPage.js +93 -0
- package/dist/pages/test-env/TestEnvPage.d.ts +13 -0
- package/dist/pages/test-env/TestEnvPage.js +51 -0
- package/dist/pages/test-env/index.d.ts +24 -0
- package/dist/pages/test-env/index.js +32 -0
- package/dist/pages/verify-code/page.d.ts +30 -0
- package/dist/pages/verify-code/page.js +412 -0
- package/dist/routes/account/index.d.ts +28 -0
- package/dist/routes/account/index.js +71 -0
- package/dist/routes/account/masked-info.d.ts +33 -0
- package/dist/routes/account/masked-info.js +39 -0
- package/dist/routes/account/send-code.d.ts +37 -0
- package/dist/routes/account/send-code.js +42 -0
- package/dist/routes/account/update-phone.d.ts +13 -0
- package/dist/routes/account/update-phone.js +17 -0
- package/dist/routes/account/verify-email.d.ts +38 -0
- package/dist/routes/account/verify-email.js +43 -0
- package/dist/routes/account/verify-sms.d.ts +38 -0
- package/dist/routes/account/verify-sms.js +43 -0
- package/dist/routes/auth/index.d.ts +19 -0
- package/dist/routes/auth/index.js +64 -0
- package/dist/routes/auth/logout.d.ts +31 -0
- package/dist/routes/auth/logout.js +98 -0
- package/dist/routes/auth/nextauth.d.ts +22 -0
- package/dist/routes/auth/nextauth.js +40 -0
- package/dist/routes/auth/refresh.d.ts +30 -0
- package/dist/routes/auth/refresh.js +51 -0
- package/dist/routes/auth/session.d.ts +43 -0
- package/dist/routes/auth/session.js +157 -0
- package/dist/routes/auth/settings.d.ts +25 -0
- package/dist/routes/auth/settings.js +55 -0
- package/dist/routes/auth/viability.d.ts +52 -0
- package/dist/routes/auth/viability.js +190 -0
- package/dist/routes/index.d.ts +12 -0
- package/dist/routes/index.js +54 -0
- package/dist/routes/session/index.d.ts +6 -0
- package/dist/routes/session/index.js +10 -0
- package/dist/routes/session/refresh-viability.d.ts +16 -0
- package/dist/routes/session/refresh-viability.js +20 -0
- package/dist/server/auth-guard.d.ts +46 -0
- package/dist/server/auth-guard.js +128 -0
- package/dist/server/auth.d.ts +50 -0
- package/dist/server/auth.js +62 -0
- package/dist/server/decode-session.d.ts +30 -0
- package/dist/server/decode-session.js +78 -0
- package/dist/server/slim-middleware.d.ts +23 -0
- package/dist/server/slim-middleware.js +89 -0
- package/dist/server/with-auth.d.ts +33 -0
- package/dist/server/with-auth.js +59 -0
- package/dist/services/signalrActivityService.d.ts +44 -0
- package/dist/services/signalrActivityService.js +257 -0
- package/dist/stores/authStore.d.ts +154 -0
- package/dist/stores/authStore.js +1527 -0
- package/dist/theme/ThemeProvider.d.ts +14 -0
- package/dist/theme/ThemeProvider.js +28 -0
- package/dist/theme/default.d.ts +8 -0
- package/dist/theme/default.js +33 -0
- package/dist/theme/index.d.ts +15 -0
- package/dist/theme/index.js +25 -0
- package/dist/theme/types.d.ts +56 -0
- package/dist/theme/types.js +8 -0
- package/dist/theme/useTheme.d.ts +60 -0
- package/dist/theme/useTheme.js +63 -0
- package/dist/theme/utils.d.ts +13 -0
- package/dist/theme/utils.js +39 -0
- package/dist/types/api.d.ts +134 -0
- package/dist/types/api.js +44 -0
- package/dist/types/auth.d.ts +19 -0
- package/dist/types/auth.js +2 -0
- package/dist/types/logging.d.ts +42 -0
- package/dist/types/logging.js +2 -0
- package/dist/types/recovery.d.ts +48 -0
- package/dist/types/recovery.js +2 -0
- package/dist/types/security.d.ts +1 -0
- package/dist/types/security.js +2 -0
- package/dist/utils/api.d.ts +85 -0
- package/dist/utils/api.js +287 -0
- package/dist/utils/circuitBreaker.d.ts +43 -0
- package/dist/utils/circuitBreaker.js +91 -0
- package/dist/utils/error-message.d.ts +1 -0
- package/dist/utils/error-message.js +103 -0
- package/dist/utils/layout/reservedSpace.d.ts +59 -0
- package/dist/utils/layout/reservedSpace.js +102 -0
- package/dist/utils/logout.d.ts +14 -0
- package/dist/utils/logout.js +32 -0
- package/dist/vibe/client.d.ts +261 -0
- package/dist/vibe/client.js +445 -0
- package/dist/vibe/enterprise-auth.d.ts +106 -0
- package/dist/vibe/enterprise-auth.js +173 -0
- package/dist/vibe/errors.d.ts +83 -0
- package/dist/vibe/errors.js +146 -0
- package/dist/vibe/generic.d.ts +234 -0
- package/dist/vibe/generic.js +369 -0
- package/dist/vibe/hooks/index.d.ts +169 -0
- package/dist/vibe/hooks/index.js +252 -0
- package/dist/vibe/index.d.ts +25 -0
- package/dist/vibe/index.js +72 -0
- package/dist/vibe/sessions.d.ts +161 -0
- package/dist/vibe/sessions.js +391 -0
- package/dist/vibe/types.d.ts +353 -0
- package/dist/vibe/types.js +315 -0
- package/package.json +1 -1
- package/src/auth/better-auth.ts +2 -2
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Enhanced Auth Handler with Coordinated Token Refresh
|
|
3
|
+
*
|
|
4
|
+
* Provides a middleware wrapper that automatically handles token lifecycle:
|
|
5
|
+
* - Checks token expiry before each request
|
|
6
|
+
* - Automatically refreshes expired or near-expired tokens
|
|
7
|
+
* - Uses Redis locks for coordinated refresh (prevents race conditions)
|
|
8
|
+
* - Retries requests on 401 responses with fresh tokens
|
|
9
|
+
*
|
|
10
|
+
* Pattern ported from website-membership simple-api-handler.ts
|
|
11
|
+
*
|
|
12
|
+
* @version 2.1.0
|
|
13
|
+
* @since auth-ready-v2
|
|
14
|
+
*/
|
|
15
|
+
import { NextRequest, NextResponse } from 'next/server';
|
|
16
|
+
export interface AuthContext {
|
|
17
|
+
token: any;
|
|
18
|
+
accessToken: string;
|
|
19
|
+
userId: string;
|
|
20
|
+
sessionToken: string;
|
|
21
|
+
refreshToken?: string;
|
|
22
|
+
}
|
|
23
|
+
export interface AuthHandlerOptions {
|
|
24
|
+
/** Whether authentication is required for this route (default: true) */
|
|
25
|
+
requireAuth?: boolean;
|
|
26
|
+
/** Automatically refresh expired or near-expired tokens (default: true) */
|
|
27
|
+
autoRefresh?: boolean;
|
|
28
|
+
/** Buffer time in seconds before token expiry to trigger refresh (default: 300 = 5 minutes) */
|
|
29
|
+
refreshBuffer?: number;
|
|
30
|
+
/** Retry request on 401 response after refreshing token (default: true) */
|
|
31
|
+
retryOn401?: boolean;
|
|
32
|
+
/** Maximum number of retry attempts on 401 (default: 1) */
|
|
33
|
+
maxRetries?: number;
|
|
34
|
+
/** NextAuth secret for JWT decoding */
|
|
35
|
+
nextAuthSecret?: string;
|
|
36
|
+
/** IDP base URL for refresh requests */
|
|
37
|
+
idpBaseUrl?: string;
|
|
38
|
+
/** OAuth client ID */
|
|
39
|
+
clientId?: string;
|
|
40
|
+
}
|
|
41
|
+
export type HandlerFunction = (req: NextRequest, context: any, auth: AuthContext) => Promise<NextResponse | Response>;
|
|
42
|
+
/**
|
|
43
|
+
* Creates an auth-aware handler with automatic token refresh
|
|
44
|
+
*
|
|
45
|
+
* @example
|
|
46
|
+
* ```typescript
|
|
47
|
+
* import { createAuthHandler } from '@payez/next-mvp/api';
|
|
48
|
+
*
|
|
49
|
+
* const handler = createAuthHandler({ requireAuth: true });
|
|
50
|
+
*
|
|
51
|
+
* export const GET = handler.handle(async (req, context, auth) => {
|
|
52
|
+
* // auth.accessToken is guaranteed to be fresh
|
|
53
|
+
* const response = await fetch('https://api.example.com/data', {
|
|
54
|
+
* headers: { 'Authorization': `Bearer ${auth.accessToken}` }
|
|
55
|
+
* });
|
|
56
|
+
* return NextResponse.json(await response.json());
|
|
57
|
+
* });
|
|
58
|
+
* ```
|
|
59
|
+
*/
|
|
60
|
+
export declare function createAuthHandler(options?: AuthHandlerOptions): {
|
|
61
|
+
handle: (handler: HandlerFunction) => (req: NextRequest, context?: any) => Promise<Response>;
|
|
62
|
+
};
|
|
63
|
+
/**
|
|
64
|
+
* Default export for convenience
|
|
65
|
+
*/
|
|
66
|
+
export default createAuthHandler;
|
|
@@ -0,0 +1,397 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Enhanced Auth Handler with Coordinated Token Refresh
|
|
4
|
+
*
|
|
5
|
+
* Provides a middleware wrapper that automatically handles token lifecycle:
|
|
6
|
+
* - Checks token expiry before each request
|
|
7
|
+
* - Automatically refreshes expired or near-expired tokens
|
|
8
|
+
* - Uses Redis locks for coordinated refresh (prevents race conditions)
|
|
9
|
+
* - Retries requests on 401 responses with fresh tokens
|
|
10
|
+
*
|
|
11
|
+
* Pattern ported from website-membership simple-api-handler.ts
|
|
12
|
+
*
|
|
13
|
+
* @version 2.1.0
|
|
14
|
+
* @since auth-ready-v2
|
|
15
|
+
*/
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
exports.createAuthHandler = createAuthHandler;
|
|
18
|
+
const server_1 = require("next/server");
|
|
19
|
+
const auth_1 = require("../server/auth");
|
|
20
|
+
const nanoid_1 = require("nanoid");
|
|
21
|
+
const session_store_1 = require("../lib/session-store");
|
|
22
|
+
/**
|
|
23
|
+
* Creates an auth-aware handler with automatic token refresh
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* ```typescript
|
|
27
|
+
* import { createAuthHandler } from '@payez/next-mvp/api';
|
|
28
|
+
*
|
|
29
|
+
* const handler = createAuthHandler({ requireAuth: true });
|
|
30
|
+
*
|
|
31
|
+
* export const GET = handler.handle(async (req, context, auth) => {
|
|
32
|
+
* // auth.accessToken is guaranteed to be fresh
|
|
33
|
+
* const response = await fetch('https://api.example.com/data', {
|
|
34
|
+
* headers: { 'Authorization': `Bearer ${auth.accessToken}` }
|
|
35
|
+
* });
|
|
36
|
+
* return NextResponse.json(await response.json());
|
|
37
|
+
* });
|
|
38
|
+
* ```
|
|
39
|
+
*/
|
|
40
|
+
function createAuthHandler(options = {}) {
|
|
41
|
+
const { requireAuth = true, autoRefresh = true, refreshBuffer = 60, // 60 seconds - matches website-membership proven threshold
|
|
42
|
+
retryOn401 = true, maxRetries = 1, nextAuthSecret = process.env.NEXTAUTH_SECRET, idpBaseUrl = process.env.IDP_URL, clientId = process.env.CLIENT_ID || process.env.NEXT_PUBLIC_IDP_CLIENT_ID } = options;
|
|
43
|
+
/**
|
|
44
|
+
* Performs coordinated token refresh with Redis locking
|
|
45
|
+
* This prevents multiple concurrent requests from all trying to refresh simultaneously
|
|
46
|
+
*/
|
|
47
|
+
async function performCoordinatedRefresh(sessionToken, requestId) {
|
|
48
|
+
// Check if refresh is already in progress
|
|
49
|
+
const existingLock = await (0, session_store_1.checkRefreshLock)(sessionToken);
|
|
50
|
+
if (existingLock) {
|
|
51
|
+
console.info('[AUTH_HANDLER] Refresh already in progress, waiting...', {
|
|
52
|
+
requestId,
|
|
53
|
+
lockOwner: existingLock.acquiredBy,
|
|
54
|
+
lockAge: Date.now() - existingLock.acquiredAt
|
|
55
|
+
});
|
|
56
|
+
// Wait for the refresh to complete
|
|
57
|
+
const waitResult = await waitForRefreshCompletion(sessionToken, requestId, 10000);
|
|
58
|
+
if (waitResult.success) {
|
|
59
|
+
// Get the fresh token from session
|
|
60
|
+
const freshSession = await (0, session_store_1.getSession)(sessionToken);
|
|
61
|
+
if (freshSession?.accessToken) {
|
|
62
|
+
return {
|
|
63
|
+
success: true,
|
|
64
|
+
accessToken: freshSession.accessToken,
|
|
65
|
+
refreshToken: freshSession.refreshToken,
|
|
66
|
+
expiresIn: freshSession.accessTokenExpires
|
|
67
|
+
? Math.floor((freshSession.accessTokenExpires - Date.now()) / 1000)
|
|
68
|
+
: undefined
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return { success: false, error: waitResult.reason || 'Wait for refresh failed' };
|
|
73
|
+
}
|
|
74
|
+
// Try to acquire the refresh lock
|
|
75
|
+
const lockAcquired = await (0, session_store_1.acquireRefreshLock)(sessionToken, requestId, 5000);
|
|
76
|
+
if (!lockAcquired) {
|
|
77
|
+
// Another request grabbed the lock, wait for it
|
|
78
|
+
console.info('[AUTH_HANDLER] Failed to acquire lock, waiting for other request', { requestId });
|
|
79
|
+
const waitResult = await waitForRefreshCompletion(sessionToken, requestId, 10000);
|
|
80
|
+
if (waitResult.success) {
|
|
81
|
+
const freshSession = await (0, session_store_1.getSession)(sessionToken);
|
|
82
|
+
if (freshSession?.accessToken) {
|
|
83
|
+
return {
|
|
84
|
+
success: true,
|
|
85
|
+
accessToken: freshSession.accessToken,
|
|
86
|
+
refreshToken: freshSession.refreshToken
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return { success: false, error: waitResult.reason || 'Wait for refresh failed' };
|
|
91
|
+
}
|
|
92
|
+
try {
|
|
93
|
+
// Double-check if tokens are still stale after acquiring lock
|
|
94
|
+
const latestSession = await (0, session_store_1.getSession)(sessionToken);
|
|
95
|
+
if (latestSession && !tokenNeedsRefresh(latestSession, refreshBuffer)) {
|
|
96
|
+
console.info('[AUTH_HANDLER] Tokens already fresh after acquiring lock, skipping refresh', { requestId });
|
|
97
|
+
return {
|
|
98
|
+
success: true,
|
|
99
|
+
accessToken: latestSession.accessToken,
|
|
100
|
+
refreshToken: latestSession.refreshToken
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
// Actually perform the refresh
|
|
104
|
+
return await executeRefresh(sessionToken, latestSession);
|
|
105
|
+
}
|
|
106
|
+
finally {
|
|
107
|
+
// Always release the lock
|
|
108
|
+
await (0, session_store_1.releaseRefreshLock)(sessionToken, requestId);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Wait for an in-progress refresh to complete
|
|
113
|
+
*/
|
|
114
|
+
async function waitForRefreshCompletion(sessionToken, requestId, maxWaitMs) {
|
|
115
|
+
const startTime = Date.now();
|
|
116
|
+
const pollInterval = 100;
|
|
117
|
+
while (Date.now() - startTime < maxWaitMs) {
|
|
118
|
+
const lockExists = await (0, session_store_1.checkRefreshLock)(sessionToken);
|
|
119
|
+
if (!lockExists) {
|
|
120
|
+
// Lock released, check if tokens are fresh
|
|
121
|
+
const session = await (0, session_store_1.getSession)(sessionToken);
|
|
122
|
+
if (session?.accessToken && !tokenNeedsRefresh(session, refreshBuffer)) {
|
|
123
|
+
return { success: true };
|
|
124
|
+
}
|
|
125
|
+
else {
|
|
126
|
+
return { success: false, reason: 'Lock released but tokens not fresh' };
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
await new Promise(resolve => setTimeout(resolve, pollInterval));
|
|
130
|
+
}
|
|
131
|
+
return { success: false, reason: `Timeout waiting for refresh (${maxWaitMs}ms)` };
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Check if token needs refresh based on expiry and buffer
|
|
135
|
+
*/
|
|
136
|
+
function tokenNeedsRefresh(session, bufferSeconds) {
|
|
137
|
+
if (!session.accessToken)
|
|
138
|
+
return true;
|
|
139
|
+
const expires = session.accessTokenExpires || 0;
|
|
140
|
+
const bufferMs = bufferSeconds * 1000;
|
|
141
|
+
const timeUntilExpiry = expires - Date.now();
|
|
142
|
+
return timeUntilExpiry <= bufferMs;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Execute the actual token refresh against IDP
|
|
146
|
+
*/
|
|
147
|
+
async function executeRefresh(sessionToken, currentSession) {
|
|
148
|
+
try {
|
|
149
|
+
if (!idpBaseUrl || !clientId) {
|
|
150
|
+
console.error('[AUTH_HANDLER] Missing IDP configuration for refresh');
|
|
151
|
+
return { success: false, error: 'Missing IDP configuration' };
|
|
152
|
+
}
|
|
153
|
+
if (!currentSession) {
|
|
154
|
+
console.error('[AUTH_HANDLER] No session found for refresh');
|
|
155
|
+
return { success: false, error: 'No session found' };
|
|
156
|
+
}
|
|
157
|
+
if (!currentSession.refreshToken) {
|
|
158
|
+
console.error('[AUTH_HANDLER] No refresh token available');
|
|
159
|
+
return { success: false, error: 'No refresh token' };
|
|
160
|
+
}
|
|
161
|
+
// Extract authentication methods from session
|
|
162
|
+
const authMethods = currentSession.authMethods ||
|
|
163
|
+
(currentSession.token?.amr ? JSON.parse(currentSession.token.amr) : ['pwd', 'mfa']);
|
|
164
|
+
const authLevel = String(currentSession.authenticationLevel || currentSession.token?.acr || '2');
|
|
165
|
+
const twoFactorMethod = currentSession.twoFactorMethod || 'authenticator';
|
|
166
|
+
// Build refresh request body
|
|
167
|
+
const refreshRequestBody = {
|
|
168
|
+
refresh_token: currentSession.refreshToken,
|
|
169
|
+
amr: authMethods,
|
|
170
|
+
acr: authLevel
|
|
171
|
+
};
|
|
172
|
+
if (currentSession.twoFactorComplete) {
|
|
173
|
+
refreshRequestBody.two_factor_verified = true;
|
|
174
|
+
}
|
|
175
|
+
if (twoFactorMethod) {
|
|
176
|
+
refreshRequestBody.two_factor_method = twoFactorMethod;
|
|
177
|
+
}
|
|
178
|
+
if (currentSession.mfaCompletedAt) {
|
|
179
|
+
refreshRequestBody.two_factor_completed_at = new Date(currentSession.mfaCompletedAt).toISOString();
|
|
180
|
+
}
|
|
181
|
+
console.info('[AUTH_HANDLER] Executing refresh against IDP', {
|
|
182
|
+
sessionToken: sessionToken.substring(0, 8) + '...',
|
|
183
|
+
hasRefreshToken: true
|
|
184
|
+
});
|
|
185
|
+
const response = await fetch(`${idpBaseUrl}/api/ExternalAuth/refresh`, {
|
|
186
|
+
method: 'POST',
|
|
187
|
+
headers: {
|
|
188
|
+
'Content-Type': 'application/json',
|
|
189
|
+
'X-Client-Id': clientId,
|
|
190
|
+
},
|
|
191
|
+
body: JSON.stringify(refreshRequestBody),
|
|
192
|
+
});
|
|
193
|
+
if (!response.ok) {
|
|
194
|
+
const errorText = await response.text().catch(() => 'Unknown error');
|
|
195
|
+
console.error('[AUTH_HANDLER] Refresh failed:', response.status, errorText);
|
|
196
|
+
return { success: false, error: `Refresh failed: ${response.status}` };
|
|
197
|
+
}
|
|
198
|
+
const data = await response.json();
|
|
199
|
+
if (data.success === false) {
|
|
200
|
+
return { success: false, error: data.error?.message || data.message || 'Refresh failed' };
|
|
201
|
+
}
|
|
202
|
+
const tokenData = data.data || data;
|
|
203
|
+
if (!tokenData.access_token) {
|
|
204
|
+
console.error('[AUTH_HANDLER] No access token in refresh response');
|
|
205
|
+
return { success: false, error: 'No access token received' };
|
|
206
|
+
}
|
|
207
|
+
// Update session with new tokens
|
|
208
|
+
const updatedSession = {
|
|
209
|
+
...currentSession,
|
|
210
|
+
accessToken: tokenData.access_token,
|
|
211
|
+
refreshToken: tokenData.refresh_token || currentSession.refreshToken,
|
|
212
|
+
accessTokenExpires: tokenData.expires_in
|
|
213
|
+
? Date.now() + (tokenData.expires_in * 1000)
|
|
214
|
+
: Date.now() + (3600 * 1000),
|
|
215
|
+
};
|
|
216
|
+
await (0, session_store_1.updateSession)(sessionToken, updatedSession);
|
|
217
|
+
console.info('[AUTH_HANDLER] Token refresh successful', {
|
|
218
|
+
newExpiry: new Date(updatedSession.accessTokenExpires).toISOString()
|
|
219
|
+
});
|
|
220
|
+
return {
|
|
221
|
+
success: true,
|
|
222
|
+
accessToken: tokenData.access_token,
|
|
223
|
+
refreshToken: tokenData.refresh_token,
|
|
224
|
+
expiresIn: tokenData.expires_in,
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
catch (error) {
|
|
228
|
+
console.error('[AUTH_HANDLER] Refresh exception:', error);
|
|
229
|
+
return { success: false, error: error instanceof Error ? error.message : 'Refresh failed' };
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Checks if auth context token needs refresh based on expiry and buffer
|
|
234
|
+
*/
|
|
235
|
+
function needsRefresh(auth) {
|
|
236
|
+
if (!autoRefresh)
|
|
237
|
+
return false;
|
|
238
|
+
// Check if we have token expiry information
|
|
239
|
+
const token = auth.token;
|
|
240
|
+
const expiresAt = token.accessTokenExpires || token.exp;
|
|
241
|
+
if (!expiresAt) {
|
|
242
|
+
// No expiry info, can't determine if refresh needed
|
|
243
|
+
return false;
|
|
244
|
+
}
|
|
245
|
+
const now = Math.floor(Date.now() / 1000);
|
|
246
|
+
const expiryTime = typeof expiresAt === 'number' && expiresAt > 1000000000000
|
|
247
|
+
? Math.floor(expiresAt / 1000) // Convert milliseconds to seconds
|
|
248
|
+
: expiresAt;
|
|
249
|
+
// Check if token expires within the buffer period
|
|
250
|
+
return (expiryTime - now) <= refreshBuffer;
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* Generate a unique request ID for coordinated refresh
|
|
254
|
+
*/
|
|
255
|
+
function generateRequestId() {
|
|
256
|
+
return (0, nanoid_1.nanoid)();
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Main handler wrapper
|
|
260
|
+
*/
|
|
261
|
+
return {
|
|
262
|
+
handle: (handler) => {
|
|
263
|
+
return async (req, context = {}) => {
|
|
264
|
+
// Extract session from Better Auth
|
|
265
|
+
const betterAuthSession = await (0, auth_1.getSession)(req);
|
|
266
|
+
const token = betterAuthSession ? { ...betterAuthSession.user, ...betterAuthSession.session } : null;
|
|
267
|
+
// Check if auth is required
|
|
268
|
+
if (requireAuth && !betterAuthSession) {
|
|
269
|
+
return server_1.NextResponse.json({ error: 'Authentication required', code: 'UNAUTHORIZED' }, { status: 401 });
|
|
270
|
+
}
|
|
271
|
+
// If no session and auth not required, call handler without auth context
|
|
272
|
+
if (!betterAuthSession) {
|
|
273
|
+
return handler(req, context, null);
|
|
274
|
+
}
|
|
275
|
+
// Validate client_slug (token confusion attack prevention)
|
|
276
|
+
// SECURITY: Fail closed - require configuration to be explicitly set
|
|
277
|
+
const expectedClientSlug = process.env.NEXT_PUBLIC_EXPECTED_CLIENT_SLUG;
|
|
278
|
+
if (!expectedClientSlug) {
|
|
279
|
+
console.error('[AUTH_HANDLER] SECURITY MISCONFIGURATION: NEXT_PUBLIC_EXPECTED_CLIENT_SLUG not set');
|
|
280
|
+
return server_1.NextResponse.json({
|
|
281
|
+
error: 'Server configuration error',
|
|
282
|
+
code: 'SECURITY_CONFIGURATION_MISSING'
|
|
283
|
+
}, { status: 500 });
|
|
284
|
+
}
|
|
285
|
+
// Extract client_slug from token (normalize property name)
|
|
286
|
+
const tokenClientSlug = token.client_slug || token.clientSlug;
|
|
287
|
+
// SECURITY: Require client_slug claim in all tokens (no backward compat)
|
|
288
|
+
if (!tokenClientSlug) {
|
|
289
|
+
console.warn('[AUTH_HANDLER] Token missing required client_slug claim');
|
|
290
|
+
return server_1.NextResponse.json({
|
|
291
|
+
error: 'Token missing required claim',
|
|
292
|
+
code: 'TOKEN_MISSING_CLIENT_SLUG'
|
|
293
|
+
}, { status: 401 });
|
|
294
|
+
}
|
|
295
|
+
// SECURITY: Case-insensitive comparison to avoid casing attacks
|
|
296
|
+
if (tokenClientSlug.toLowerCase() !== expectedClientSlug.toLowerCase()) {
|
|
297
|
+
// Log without exposing sensitive details
|
|
298
|
+
console.warn('[AUTH_HANDLER] Token client mismatch detected');
|
|
299
|
+
return server_1.NextResponse.json({
|
|
300
|
+
error: 'Token issued for different client',
|
|
301
|
+
code: 'TOKEN_CLIENT_MISMATCH'
|
|
302
|
+
}, { status: 401 });
|
|
303
|
+
}
|
|
304
|
+
// Build initial auth context
|
|
305
|
+
let authContext = {
|
|
306
|
+
token,
|
|
307
|
+
accessToken: token.accessToken || '',
|
|
308
|
+
userId: betterAuthSession.user?.id || token.userId || '',
|
|
309
|
+
sessionToken: betterAuthSession.session?.token || '',
|
|
310
|
+
refreshToken: token.refreshToken,
|
|
311
|
+
};
|
|
312
|
+
// Check if token needs refresh
|
|
313
|
+
if (needsRefresh(authContext) && authContext.refreshToken) {
|
|
314
|
+
const requestId = generateRequestId();
|
|
315
|
+
console.info('[AUTH_HANDLER] Token near expiry, initiating coordinated refresh', {
|
|
316
|
+
requestId,
|
|
317
|
+
sessionToken: authContext.sessionToken.substring(0, 8) + '...'
|
|
318
|
+
});
|
|
319
|
+
const refreshResult = await performCoordinatedRefresh(authContext.sessionToken, requestId);
|
|
320
|
+
if (refreshResult.success && refreshResult.accessToken) {
|
|
321
|
+
// Update auth context with fresh token
|
|
322
|
+
authContext.accessToken = refreshResult.accessToken;
|
|
323
|
+
if (refreshResult.refreshToken) {
|
|
324
|
+
authContext.refreshToken = refreshResult.refreshToken;
|
|
325
|
+
}
|
|
326
|
+
// Update token object for future checks
|
|
327
|
+
authContext.token.accessToken = refreshResult.accessToken;
|
|
328
|
+
if (refreshResult.expiresIn) {
|
|
329
|
+
authContext.token.accessTokenExpires = Date.now() + (refreshResult.expiresIn * 1000);
|
|
330
|
+
}
|
|
331
|
+
console.info('[AUTH_HANDLER] Coordinated refresh successful', { requestId });
|
|
332
|
+
}
|
|
333
|
+
else {
|
|
334
|
+
console.warn('[AUTH_HANDLER] Failed to refresh token:', refreshResult.error);
|
|
335
|
+
// Continue with potentially expired token - handler may still succeed
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
// Attach auth context to request for downstream use (following existing pattern)
|
|
339
|
+
// IMPORTANT: Set this ONCE before the retry loop to avoid overwriting with stale data
|
|
340
|
+
req.__authContext = {
|
|
341
|
+
accessToken: authContext.accessToken,
|
|
342
|
+
userId: authContext.userId,
|
|
343
|
+
sessionToken: authContext.sessionToken,
|
|
344
|
+
};
|
|
345
|
+
// Call the actual handler
|
|
346
|
+
let response;
|
|
347
|
+
let retryCount = 0;
|
|
348
|
+
while (retryCount <= maxRetries) {
|
|
349
|
+
try {
|
|
350
|
+
response = await handler(req, context, authContext);
|
|
351
|
+
// Check if we got a 401 and should retry
|
|
352
|
+
if (response.status === 401 &&
|
|
353
|
+
retryOn401 &&
|
|
354
|
+
retryCount < maxRetries &&
|
|
355
|
+
authContext.refreshToken) {
|
|
356
|
+
const retryRequestId = generateRequestId();
|
|
357
|
+
console.info('[AUTH_HANDLER] Got 401, attempting coordinated refresh and retry', { retryRequestId });
|
|
358
|
+
const refreshResult = await performCoordinatedRefresh(authContext.sessionToken, retryRequestId);
|
|
359
|
+
if (refreshResult.success && refreshResult.accessToken) {
|
|
360
|
+
console.info('[AUTH_HANDLER] Refresh succeeded, updating tokens', { retryRequestId });
|
|
361
|
+
// Update auth context with fresh token
|
|
362
|
+
authContext.accessToken = refreshResult.accessToken;
|
|
363
|
+
if (refreshResult.refreshToken) {
|
|
364
|
+
authContext.refreshToken = refreshResult.refreshToken;
|
|
365
|
+
}
|
|
366
|
+
// Update request context
|
|
367
|
+
req.__authContext.accessToken = refreshResult.accessToken;
|
|
368
|
+
console.info('[AUTH_HANDLER] Updated req.__authContext with new token, retrying request', { retryRequestId });
|
|
369
|
+
retryCount++;
|
|
370
|
+
continue; // Retry the request
|
|
371
|
+
}
|
|
372
|
+
else {
|
|
373
|
+
console.warn('[AUTH_HANDLER] Refresh failed on 401 retry:', refreshResult.error);
|
|
374
|
+
break; // Don't retry if refresh failed
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
// Success or non-401 error - return response
|
|
378
|
+
break;
|
|
379
|
+
}
|
|
380
|
+
catch (error) {
|
|
381
|
+
// Handler threw an error
|
|
382
|
+
console.error('[AUTH_HANDLER] Handler error:', error);
|
|
383
|
+
return server_1.NextResponse.json({
|
|
384
|
+
error: 'Internal server error',
|
|
385
|
+
details: error instanceof Error ? error.message : 'Unknown error'
|
|
386
|
+
}, { status: 500 });
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
return response;
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
/**
|
|
395
|
+
* Default export for convenience
|
|
396
|
+
*/
|
|
397
|
+
exports.default = createAuthHandler;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @payez/next-mvp API Module Exports
|
|
3
|
+
*
|
|
4
|
+
* Provides enhanced API route handlers with automatic token management
|
|
5
|
+
*
|
|
6
|
+
* @version 2.0.0
|
|
7
|
+
* @since auth-ready-v2
|
|
8
|
+
*/
|
|
9
|
+
export { createAuthHandler, type AuthContext, type AuthHandlerOptions, type HandlerFunction } from './auth-handler';
|
|
10
|
+
export { default } from './auth-handler';
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* @payez/next-mvp API Module Exports
|
|
4
|
+
*
|
|
5
|
+
* Provides enhanced API route handlers with automatic token management
|
|
6
|
+
*
|
|
7
|
+
* @version 2.0.0
|
|
8
|
+
* @since auth-ready-v2
|
|
9
|
+
*/
|
|
10
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
11
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
12
|
+
};
|
|
13
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
14
|
+
exports.default = exports.createAuthHandler = void 0;
|
|
15
|
+
var auth_handler_1 = require("./auth-handler");
|
|
16
|
+
Object.defineProperty(exports, "createAuthHandler", { enumerable: true, get: function () { return auth_handler_1.createAuthHandler; } });
|
|
17
|
+
// Default export for convenience
|
|
18
|
+
var auth_handler_2 = require("./auth-handler");
|
|
19
|
+
Object.defineProperty(exports, "default", { enumerable: true, get: function () { return __importDefault(auth_handler_2).default; } });
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.POST = POST;
|
|
4
|
+
const server_1 = require("next/server");
|
|
5
|
+
const auth_1 = require("../../server/auth");
|
|
6
|
+
const session_store_1 = require("../../lib/session-store");
|
|
7
|
+
const nanoid_1 = require("nanoid");
|
|
8
|
+
// ...
|
|
9
|
+
async function POST(req) {
|
|
10
|
+
const requestId = (0, nanoid_1.nanoid)();
|
|
11
|
+
try {
|
|
12
|
+
// Get session from Better Auth
|
|
13
|
+
const betterAuthSession = await (0, auth_1.getSession)(req);
|
|
14
|
+
const sessionToken = betterAuthSession?.session?.token;
|
|
15
|
+
if (!betterAuthSession || typeof sessionToken !== 'string') {
|
|
16
|
+
return server_1.NextResponse.json({ success: false, message: 'Unauthorized' }, { status: 401 });
|
|
17
|
+
}
|
|
18
|
+
const sessionData = await (0, session_store_1.getSession)(sessionToken);
|
|
19
|
+
// NOTE: Field is idpAccessToken (not accessToken) per normalized naming convention
|
|
20
|
+
if (!sessionData?.idpAccessToken) {
|
|
21
|
+
return server_1.NextResponse.json({
|
|
22
|
+
success: false,
|
|
23
|
+
message: 'Authentication required - no access token available',
|
|
24
|
+
error_code: 'UNAUTHORIZED',
|
|
25
|
+
request_id: requestId,
|
|
26
|
+
}, { status: 401 });
|
|
27
|
+
}
|
|
28
|
+
const body = await req.json();
|
|
29
|
+
const { current_password, new_password, confirm_password } = body;
|
|
30
|
+
// Validate input
|
|
31
|
+
if (!current_password || !new_password || !confirm_password) {
|
|
32
|
+
return server_1.NextResponse.json({
|
|
33
|
+
success: false,
|
|
34
|
+
message: 'Current password, new password, and confirmation are required',
|
|
35
|
+
error_code: 'VALIDATION_ERROR',
|
|
36
|
+
request_id: requestId,
|
|
37
|
+
}, { status: 400 });
|
|
38
|
+
}
|
|
39
|
+
if (new_password !== confirm_password) {
|
|
40
|
+
return server_1.NextResponse.json({
|
|
41
|
+
success: false,
|
|
42
|
+
message: 'New password and confirmation do not match',
|
|
43
|
+
error_code: 'VALIDATION_ERROR',
|
|
44
|
+
request_id: requestId,
|
|
45
|
+
}, { status: 400 });
|
|
46
|
+
}
|
|
47
|
+
// Get IDP base URL from environment
|
|
48
|
+
const idpBaseUrl = process.env.IDP_URL;
|
|
49
|
+
if (!idpBaseUrl) {
|
|
50
|
+
console.error('[CHANGE_PASSWORD] IDP_URL not configured');
|
|
51
|
+
return server_1.NextResponse.json({
|
|
52
|
+
success: false,
|
|
53
|
+
message: 'Service configuration error',
|
|
54
|
+
error_code: 'CONFIGURATION_ERROR',
|
|
55
|
+
request_id: requestId,
|
|
56
|
+
}, { status: 500 });
|
|
57
|
+
}
|
|
58
|
+
// Proxy request to IDP
|
|
59
|
+
const idpUrl = `${idpBaseUrl}/api/Account/change-password`;
|
|
60
|
+
const idpResponse = await fetch(idpUrl, {
|
|
61
|
+
method: 'POST',
|
|
62
|
+
headers: {
|
|
63
|
+
'Content-Type': 'application/json',
|
|
64
|
+
'Authorization': `Bearer ${sessionData.idpAccessToken}`,
|
|
65
|
+
'x-request-id': requestId,
|
|
66
|
+
},
|
|
67
|
+
body: JSON.stringify({
|
|
68
|
+
current_password,
|
|
69
|
+
new_password,
|
|
70
|
+
confirm_password,
|
|
71
|
+
}),
|
|
72
|
+
});
|
|
73
|
+
const responseData = await idpResponse.json().catch(() => ({}));
|
|
74
|
+
if (!idpResponse.ok) {
|
|
75
|
+
// Extract error message from IDP response
|
|
76
|
+
let errorMessage = 'Failed to change password';
|
|
77
|
+
if (responseData.message) {
|
|
78
|
+
errorMessage = responseData.message;
|
|
79
|
+
}
|
|
80
|
+
else if (responseData.details?.value && Array.isArray(responseData.details.value) && responseData.details.value.length > 0) {
|
|
81
|
+
errorMessage = responseData.details.value[0].message || errorMessage;
|
|
82
|
+
}
|
|
83
|
+
else if (responseData.details?.message) {
|
|
84
|
+
errorMessage = responseData.details.message;
|
|
85
|
+
}
|
|
86
|
+
return server_1.NextResponse.json({
|
|
87
|
+
success: false,
|
|
88
|
+
message: errorMessage,
|
|
89
|
+
error_code: responseData.error_code || 'CHANGE_PASSWORD_FAILED',
|
|
90
|
+
request_id: requestId,
|
|
91
|
+
details: responseData.details,
|
|
92
|
+
}, { status: idpResponse.status });
|
|
93
|
+
}
|
|
94
|
+
return server_1.NextResponse.json({
|
|
95
|
+
success: true,
|
|
96
|
+
message: responseData.message || 'Password changed successfully',
|
|
97
|
+
request_id: requestId,
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
catch (error) {
|
|
101
|
+
console.error('[CHANGE_PASSWORD] Error:', error);
|
|
102
|
+
const requestId = req.headers.get('x-request-id') ?? crypto.randomUUID();
|
|
103
|
+
return server_1.NextResponse.json({
|
|
104
|
+
success: false,
|
|
105
|
+
message: error instanceof Error ? error.message : 'Failed to change password',
|
|
106
|
+
error_code: 'INTERNAL_ERROR',
|
|
107
|
+
request_id: requestId,
|
|
108
|
+
}, { status: 500 });
|
|
109
|
+
}
|
|
110
|
+
}
|
|
@@ -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
|
+
// IDP masked-info is POST and uses capital 'A' in /api/Account
|
|
8
|
+
async function POST(req) {
|
|
9
|
+
const url = `${env_1.ENV_CONFIG.IDP_URL}/api/Account/masked-info`;
|
|
10
|
+
// Forward request body if present; IDP often accepts empty object
|
|
11
|
+
let body = '{}';
|
|
12
|
+
try {
|
|
13
|
+
const raw = await req.text();
|
|
14
|
+
if (raw && raw.trim().length > 0)
|
|
15
|
+
body = raw;
|
|
16
|
+
}
|
|
17
|
+
catch { }
|
|
18
|
+
const result = await (0, idp_fetch_1.idpFetchJSON)(req, url, {
|
|
19
|
+
method: 'POST',
|
|
20
|
+
headers: { 'Content-Type': 'application/json' },
|
|
21
|
+
body
|
|
22
|
+
});
|
|
23
|
+
if (!result.ok) {
|
|
24
|
+
return server_1.NextResponse.json({
|
|
25
|
+
success: false,
|
|
26
|
+
message: 'Upstream error',
|
|
27
|
+
error: { code: 'UPSTREAM_SERVICE_ERROR', status: result.status, details: result.json },
|
|
28
|
+
meta: { attemptedRefresh: result.attemptedRefresh },
|
|
29
|
+
}, { status: result.status });
|
|
30
|
+
}
|
|
31
|
+
const bodyJson = result.json;
|
|
32
|
+
// Unwrap if IDP returns envelope { success, data }
|
|
33
|
+
if (bodyJson && typeof bodyJson === 'object' && 'success' in bodyJson && 'data' in bodyJson) {
|
|
34
|
+
if (bodyJson.success === true) {
|
|
35
|
+
return server_1.NextResponse.json(bodyJson.data, { status: 200 });
|
|
36
|
+
}
|
|
37
|
+
return server_1.NextResponse.json(bodyJson, { status: 200 });
|
|
38
|
+
}
|
|
39
|
+
// Passthrough otherwise
|
|
40
|
+
return server_1.NextResponse.json(bodyJson ?? {}, { status: 200 });
|
|
41
|
+
}
|