@payez/next-mvp 4.1.9 → 4.1.11

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 (164) hide show
  1. package/README.md +792 -792
  2. package/dist/api-handlers/auth/refresh.js +38 -15
  3. package/dist/auth/better-auth.js +4 -3
  4. package/dist/components/account/MobileNavDrawer.js +18 -18
  5. package/dist/components/account/UserAvatarMenu.js +1 -1
  6. package/dist/components/admin/AlertSettingsTab.js +40 -40
  7. package/dist/components/admin/LoggingSettingsTab.js +28 -28
  8. package/dist/lib/ensure-fresh-access-token.js +42 -8
  9. package/dist/lib/idp-fetch.js +25 -9
  10. package/dist/lib/session-store.d.ts +1 -0
  11. package/dist/lib/session-store.js +12 -8
  12. package/dist/lib/token-lifecycle.d.ts +2 -0
  13. package/dist/lib/token-lifecycle.js +21 -3
  14. package/dist/pages/login/page.js +28 -28
  15. package/dist/pages/settings/EnhancedSettingsPage.js +17 -17
  16. package/package.json +893 -893
  17. package/scripts/dev-broker.ps1 +35 -35
  18. package/scripts/dev-local.ps1 +45 -45
  19. package/src/api/auth-handler.ts +548 -548
  20. package/src/api-handlers/account/change-password.ts +142 -142
  21. package/src/api-handlers/account/update-phone.ts +79 -79
  22. package/src/api-handlers/account/verify-email.ts +125 -125
  23. package/src/api-handlers/account/verify-sms.ts +125 -125
  24. package/src/api-handlers/admin/analytics.ts +443 -443
  25. package/src/api-handlers/admin/audit.ts +223 -223
  26. package/src/api-handlers/admin/index.ts +63 -63
  27. package/src/api-handlers/admin/redis-sessions.ts +251 -251
  28. package/src/api-handlers/admin/sessions.ts +318 -318
  29. package/src/api-handlers/admin/site-logs.ts +365 -365
  30. package/src/api-handlers/admin/users.ts +242 -242
  31. package/src/api-handlers/admin/vibe-data.ts +324 -324
  32. package/src/api-handlers/auth/refresh.ts +705 -682
  33. package/src/api-handlers/auth/signout.ts +199 -199
  34. package/src/api-handlers/auth/status.ts +20 -20
  35. package/src/api-handlers/auth/update-session.ts +110 -110
  36. package/src/api-handlers/auth/verify-code.ts +112 -112
  37. package/src/api-handlers/session/refresh-viability.ts +36 -36
  38. package/src/api-handlers/test/force-expire.ts +60 -60
  39. package/src/auth/auth-decision.ts +229 -229
  40. package/src/auth/better-auth.ts +467 -466
  41. package/src/auth/route-config.ts +219 -219
  42. package/src/auth/types/auth-types.ts +555 -555
  43. package/src/auth/types/index.ts +7 -7
  44. package/src/auth/utils/idp-client.ts +445 -445
  45. package/src/auth/utils/index.ts +6 -6
  46. package/src/auth/utils/token-utils.ts +243 -243
  47. package/src/client/AuthContext.tsx +143 -143
  48. package/src/client/fetch-with-auth.ts +47 -47
  49. package/src/components/SessionSync.tsx +138 -138
  50. package/src/components/SignalRHealthCheck.tsx +131 -131
  51. package/src/components/account/MobileNavDrawer.tsx +305 -305
  52. package/src/components/account/UserAvatarMenu.tsx +266 -266
  53. package/src/components/account/index.ts +13 -13
  54. package/src/components/admin/AlertSettingsTab.tsx +728 -728
  55. package/src/components/admin/AnalyticsTab.tsx +703 -703
  56. package/src/components/admin/DataBrowserTab.tsx +505 -505
  57. package/src/components/admin/LoggingSettingsTab.tsx +665 -665
  58. package/src/components/admin/SessionsTab.tsx +414 -414
  59. package/src/components/admin/StatsTab.tsx +379 -379
  60. package/src/components/admin/VibeAdminLayout.tsx +187 -187
  61. package/src/components/admin/index.ts +59 -59
  62. package/src/components/auth/FederatedAuthSection.tsx +95 -95
  63. package/src/components/auth/ModeAwareLoginPage.tsx +135 -135
  64. package/src/components/auth/ModeAwareSignupPage.tsx +267 -267
  65. package/src/components/auth/TraditionalAuthSection.tsx +99 -99
  66. package/src/components/recovery/CompleteStep.tsx +36 -36
  67. package/src/components/recovery/InitiateRecoveryStep.tsx +68 -68
  68. package/src/components/recovery/SelectMethodStep.tsx +73 -73
  69. package/src/components/recovery/SetPasswordStep.tsx +97 -97
  70. package/src/components/recovery/VerifyCodeStep.tsx +90 -90
  71. package/src/components/reserved/ReservedRecoveryWarning.tsx +160 -160
  72. package/src/components/reserved/ReservedStatusBox.tsx +118 -118
  73. package/src/components/ui/BetaBadge.tsx +58 -58
  74. package/src/components/ui/Footer.tsx +93 -93
  75. package/src/config/env.ts +57 -57
  76. package/src/config/logger.ts +62 -62
  77. package/src/config/vibe-log-transport.ts +264 -264
  78. package/src/hooks/useAuth.ts +117 -117
  79. package/src/hooks/useAuthSettings.ts +97 -97
  80. package/src/hooks/useAvailableProviders.ts +120 -120
  81. package/src/hooks/usePasswordValidation.ts +127 -127
  82. package/src/hooks/usePublicAuthSettings.ts +149 -149
  83. package/src/hooks/useSessionExpiration.ts +101 -101
  84. package/src/hooks/useViabilitySession.ts +336 -336
  85. package/src/index.ts +60 -60
  86. package/src/lib/api-handler.ts +643 -643
  87. package/src/lib/app-slug.ts +178 -178
  88. package/src/lib/ensure-fresh-access-token.ts +369 -335
  89. package/src/lib/geolocation.ts +265 -265
  90. package/src/lib/idp-fetch.ts +26 -10
  91. package/src/lib/jwt-decode.ts +82 -82
  92. package/src/lib/roles.ts +177 -177
  93. package/src/lib/session-store.ts +4 -1
  94. package/src/lib/site-logger.ts +245 -245
  95. package/src/lib/standardized-client-api.ts +901 -901
  96. package/src/lib/test-aware-get-token.ts +41 -41
  97. package/src/lib/token-lifecycle.ts +30 -3
  98. package/src/lib/user-agent-parser.ts +252 -252
  99. package/src/logging/api/admin-analytics.ts +51 -51
  100. package/src/logging/api/audit-log.ts +53 -53
  101. package/src/logging/components/AdminAnalyticsLayout.tsx +49 -49
  102. package/src/logging/components/AuditLogViewer.tsx +125 -125
  103. package/src/logging/components/ErrorMetricsCard.tsx +98 -98
  104. package/src/logging/components/HealthMetricsCard.tsx +70 -70
  105. package/src/logging/hooks/useAdminAnalytics.ts +22 -22
  106. package/src/logging/hooks/useAuditLog.ts +24 -24
  107. package/src/logging/hooks/useErrorMetrics.ts +40 -40
  108. package/src/logging/hooks/useHealthMetrics.ts +44 -44
  109. package/src/logging/index.ts +18 -18
  110. package/src/logging/types/analytics.ts +81 -81
  111. package/src/logging/types/audit.ts +31 -31
  112. package/src/logging/types/index.ts +3 -3
  113. package/src/middleware/create-middleware.ts +663 -663
  114. package/src/middleware/rbac-check.ts +279 -279
  115. package/src/middleware/twofa-presets.ts +224 -224
  116. package/src/pages/admin-login/page.tsx +221 -221
  117. package/src/pages/admin-page-permissions/PagePermissionsAdminPage.tsx +527 -527
  118. package/src/pages/admin-page-permissions/index.ts +7 -7
  119. package/src/pages/admin-roles/RolesAdminPage.tsx +533 -533
  120. package/src/pages/admin-roles/modals.tsx +469 -469
  121. package/src/pages/client-admin/ClientSiteAdminPage.tsx +382 -382
  122. package/src/pages/client-admin/index.ts +33 -33
  123. package/src/pages/coming-soon/page.tsx +83 -83
  124. package/src/pages/login/page.tsx +456 -456
  125. package/src/pages/profile/EnhancedProfilePage.tsx +485 -485
  126. package/src/pages/profile/index.ts +9 -9
  127. package/src/pages/profile/page.tsx +166 -166
  128. package/src/pages/recovery/page.tsx +234 -234
  129. package/src/pages/roles/MyRolesPage.tsx +211 -211
  130. package/src/pages/roles/components.tsx +294 -294
  131. package/src/pages/roles/index.ts +17 -17
  132. package/src/pages/security/EnhancedSecurityPage.tsx +565 -565
  133. package/src/pages/security/index.ts +9 -9
  134. package/src/pages/security/page.tsx +507 -507
  135. package/src/pages/settings/EnhancedSettingsPage.tsx +642 -642
  136. package/src/pages/settings/index.ts +9 -9
  137. package/src/pages/settings/page.tsx +47 -47
  138. package/src/pages/showcase/ShowcasePage.tsx +532 -532
  139. package/src/pages/showcase/index.ts +13 -13
  140. package/src/pages/test-env/EmergencyLogoutPage.tsx +180 -180
  141. package/src/pages/test-env/JwtInspectPage.tsx +456 -456
  142. package/src/pages/test-env/RefreshTokenPage.tsx +157 -157
  143. package/src/pages/test-env/TestEnvPage.tsx +118 -118
  144. package/src/pages/test-env/index.ts +25 -25
  145. package/src/pages/verify-code/page.tsx +652 -652
  146. package/src/routes/account/update-phone.ts +13 -13
  147. package/src/routes/auth/logout.ts +108 -108
  148. package/src/routes/auth/nextauth.ts +45 -45
  149. package/src/routes/auth/settings.ts +75 -75
  150. package/src/routes/auth/viability.ts +224 -224
  151. package/src/server/auth-guard.ts +170 -170
  152. package/src/server/slim-middleware.ts +117 -117
  153. package/src/server/with-auth.ts +93 -93
  154. package/src/stores/authStore.ts +1899 -1899
  155. package/src/templates/instrumentation.ts +41 -41
  156. package/src/utils/logout.ts +30 -30
  157. package/src/vibe/client.ts +590 -590
  158. package/src/vibe/enterprise-auth.ts +208 -208
  159. package/src/vibe/errors.ts +185 -185
  160. package/src/vibe/generic.ts +431 -431
  161. package/src/vibe/hooks/index.ts +367 -367
  162. package/src/vibe/index.ts +132 -132
  163. package/src/vibe/sessions.ts +551 -551
  164. package/src/vibe/types.ts +577 -577
@@ -1,663 +1,663 @@
1
- /**
2
- * MVP Middleware - Authentication & Route Protection
3
- *
4
- * Creates a Next.js middleware handler that protects routes based on:
5
- * - Authentication status (session cookie → Redis viability check)
6
- * - 2FA completion status
7
- * - RBAC permissions (if enabled)
8
- *
9
- * Usage: Export the result from your app's middleware.ts:
10
- * export default createMvpMiddleware();
11
- *
12
- * With custom options:
13
- * export default createMvpMiddleware({
14
- * circuitBreaker: myCircuitBreaker,
15
- * logger: myLogger,
16
- * viabilityEndpoint: '/api/session/refresh-viability',
17
- * });
18
- */
19
-
20
- import { NextRequest, NextResponse } from 'next/server';
21
- import { isUnauthenticatedRoute, should2FABypass } from '../auth/route-config';
22
- import { getInternalApiUrl } from '../edge/internal-api-url';
23
- import { getSessionCookieName, getSecureSessionCookieName } from '../lib/app-slug';
24
- import { checkPagePermission, isRBACEnabled } from './rbac-check';
25
-
26
- // =============================================================================
27
- // TYPES
28
- // =============================================================================
29
-
30
- export interface AuthContext {
31
- pathname: string;
32
- isPublicRoute: boolean;
33
- isLoginPage: boolean;
34
- searchParams: URLSearchParams;
35
- sessionPointer: SessionPointer;
36
- sessionStatus: SessionStatus;
37
- circuitBreakerOpen: boolean;
38
- }
39
-
40
- export interface SessionPointer {
41
- exists: boolean;
42
- sessionToken?: string;
43
- expired?: boolean;
44
- hasRefreshToken?: boolean;
45
- roles: string[];
46
- clientId: string;
47
- }
48
-
49
- export interface SessionStatus {
50
- exists: boolean | null; // null = check failed/timeout
51
- forceInvalid: boolean | null; // null = check failed/timeout
52
- requires2FA: boolean;
53
- twoFactorComplete: boolean;
54
- }
55
-
56
- export type AuthAction =
57
- | { type: 'allow' }
58
- | { type: 'redirect'; location: string; reason: string; clearCookies?: boolean }
59
- | { type: 'service_error'; reason: string }
60
- | { type: 'refresh_needed' };
61
-
62
- // =============================================================================
63
- // CIRCUIT BREAKER INTERFACE
64
- // =============================================================================
65
-
66
- /**
67
- * Circuit breaker interface for middleware integration.
68
- * Implement this to provide custom circuit breaker behavior.
69
- */
70
- export interface CircuitBreakerProvider {
71
- /** Check if circuit breaker is currently open */
72
- isOpen(): boolean;
73
- /** Check if a refresh attempt is allowed (for HALF_OPEN state) */
74
- canAttemptRefresh(): boolean;
75
- /** Record a successful operation (closes the breaker) */
76
- recordSuccess(): void;
77
- /** Record a failed operation (may open the breaker) */
78
- recordFailure(error?: Error): void;
79
- /** Check if an error is a network error (vs HTTP error) */
80
- isNetworkError(error: any): boolean;
81
- }
82
-
83
- /**
84
- * Logger interface for middleware.
85
- * Implement this to provide custom logging.
86
- */
87
- export interface MiddlewareLogger {
88
- info(message: string, data?: Record<string, any>): void;
89
- warn(message: string, data?: Record<string, any>): void;
90
- error(message: string, data?: Record<string, any>): void;
91
- }
92
-
93
- /**
94
- * Configuration options for createMvpMiddleware
95
- */
96
- export interface MvpMiddlewareOptions {
97
- /** Custom circuit breaker implementation */
98
- circuitBreaker?: CircuitBreakerProvider;
99
- /** Custom logger implementation */
100
- logger?: MiddlewareLogger;
101
- /** Custom viability check endpoint (default: /api/session/viability) */
102
- viabilityEndpoint?: string;
103
- /** Custom refresh endpoint (default: /api/auth/refresh) */
104
- refreshEndpoint?: string;
105
- /** Hook called on successful refresh */
106
- onRefreshSuccess?: () => void;
107
- /** Hook called on refresh failure */
108
- onRefreshFailure?: (status: number, isNetworkError: boolean) => void;
109
- /** Additional paths to bypass middleware (beyond /api/auth/ and /api/session/) */
110
- bypassPaths?: string[];
111
- /** Paths exempt from RBAC checks (auth still enforced, just no page-permission check) */
112
- rbacExemptPaths?: string[];
113
- }
114
-
115
- // =============================================================================
116
- // DEFAULT IMPLEMENTATIONS
117
- // =============================================================================
118
-
119
- /** Default no-op circuit breaker (always closed) */
120
- const defaultCircuitBreaker: CircuitBreakerProvider = {
121
- isOpen: () => false,
122
- canAttemptRefresh: () => true,
123
- recordSuccess: () => {},
124
- recordFailure: () => {},
125
- isNetworkError: (error: any) => {
126
- return error?.cause?.code === 'ECONNREFUSED' ||
127
- error?.code === 'ECONNREFUSED' ||
128
- error?.message?.includes('ECONNREFUSED') ||
129
- error?.message?.includes('fetch failed') ||
130
- error?.message?.includes('ENOTFOUND') ||
131
- error?.message?.includes('ETIMEDOUT') ||
132
- error?.message?.includes('ECONNRESET');
133
- }
134
- };
135
-
136
- /** Default console logger */
137
- const defaultLogger: MiddlewareLogger = {
138
- info: (msg, data) => console.log(`[MIDDLEWARE] ${msg}`, data || ''),
139
- warn: (msg, data) => console.warn(`[MIDDLEWARE] ${msg}`, data || ''),
140
- error: (msg, data) => console.error(`[MIDDLEWARE] ${msg}`, data || ''),
141
- };
142
-
143
- // =============================================================================
144
- // HELPERS
145
- // =============================================================================
146
-
147
- const LOGIN_PAGE = '/account-auth/login';
148
- const VERIFY_CODE_PAGE = '/account-auth/verify-code';
149
-
150
- function isLoginPage(pathname: string): boolean {
151
- return pathname === LOGIN_PAGE;
152
- }
153
-
154
- /** Ensures callback URLs never point to auth pages (prevents redirect loops) */
155
- function getSafeCallbackUrl(pathname: string, searchParams?: URLSearchParams): string {
156
- if (pathname.startsWith('/account-auth/')) {
157
- return '/';
158
- }
159
- const existing = searchParams?.get('callbackUrl');
160
- if (existing && !existing.startsWith('/account-auth/')) {
161
- return existing;
162
- }
163
- return pathname;
164
- }
165
-
166
- /** Clear all session cookies on a response */
167
- function clearSessionCookies(response: NextResponse, request: NextRequest): void {
168
- const sessionCookie = getSessionCookieName();
169
- const secureCookie = getSecureSessionCookieName();
170
-
171
- // Clear main cookies
172
- response.cookies.set(sessionCookie, '', { path: '/', expires: new Date(0), httpOnly: true, sameSite: 'lax' });
173
- response.cookies.set(secureCookie, '', { path: '/', expires: new Date(0), httpOnly: true, sameSite: 'lax', secure: true });
174
-
175
- // Clear any chunked cookies (NextAuth chunks large cookies)
176
- for (const [name] of request.cookies) {
177
- if (name.startsWith(`${sessionCookie}.`) || name.startsWith(`${secureCookie}.`)) {
178
- const isSecure = name.startsWith('__Secure-');
179
- response.cookies.set(name, '', {
180
- path: '/',
181
- expires: new Date(0),
182
- httpOnly: true,
183
- sameSite: 'lax',
184
- ...(isSecure && { secure: true })
185
- });
186
- }
187
- }
188
- }
189
-
190
- /** Create redirect response, optionally clearing cookies */
191
- function redirectTo(
192
- request: NextRequest,
193
- location: string,
194
- clearCookies = false
195
- ): NextResponse {
196
- const response = NextResponse.redirect(new URL(location, request.url));
197
- if (clearCookies) {
198
- clearSessionCookies(response, request);
199
- }
200
- return response;
201
- }
202
-
203
- // =============================================================================
204
- // AUTH DECISION ENGINE
205
- // =============================================================================
206
-
207
- /**
208
- * Pure function that determines what action to take based on auth state.
209
- * No side effects - just examines context and returns a decision.
210
- */
211
- function makeAuthDecision(ctx: AuthContext): AuthAction {
212
- const { pathname, isPublicRoute, isLoginPage: onLoginPage, searchParams, sessionPointer, sessionStatus, circuitBreakerOpen } = ctx;
213
- const safeCallback = getSafeCallbackUrl(pathname);
214
-
215
- // --- Public routes: Allow, but enforce 2FA for authenticated users ---
216
- if (isPublicRoute && !onLoginPage) {
217
- if (needsTwoFactorRedirect(pathname, sessionPointer, sessionStatus)) {
218
- return redirect2FA(safeCallback);
219
- }
220
- return { type: 'allow' };
221
- }
222
-
223
- // --- Circuit breaker open: Service degraded ---
224
- if (circuitBreakerOpen) {
225
- if (onLoginPage) return { type: 'allow' };
226
- return {
227
- type: 'redirect',
228
- location: `${LOGIN_PAGE}?error=ServiceUnavailable`,
229
- reason: 'circuit_breaker_open',
230
- clearCookies: true
231
- };
232
- }
233
-
234
- // --- No session cookie: Need to login ---
235
- if (!sessionPointer.exists) {
236
- if (onLoginPage) return { type: 'allow' };
237
- if (pathname === '/') {
238
- const unauthUrl = process.env.UNAUTHENTICATED_REDIRECT_URL || '/account-auth/login';
239
- return { type: 'redirect', location: unauthUrl, reason: 'unauthenticated_root' };
240
- }
241
- if (pathname.startsWith('/api/')) {
242
- return { type: 'allow' }; // Let API return proper 401 JSON
243
- }
244
- return {
245
- type: 'redirect',
246
- location: `${LOGIN_PAGE}?callbackUrl=${encodeURIComponent(safeCallback)}`,
247
- reason: 'no_session'
248
- };
249
- }
250
-
251
- // --- Service error: Can't verify session ---
252
- if (sessionStatus.exists === null || sessionStatus.forceInvalid === null) {
253
- return { type: 'service_error', reason: 'viability_check_failed' };
254
- }
255
-
256
- // --- Session force-invalidated (admin action, password change, etc.) ---
257
- if (sessionStatus.forceInvalid) {
258
- if (onLoginPage) return { type: 'allow' };
259
- if (pathname.startsWith('/api/')) return { type: 'allow' };
260
- return {
261
- type: 'redirect',
262
- location: `${LOGIN_PAGE}?callbackUrl=${encodeURIComponent(safeCallback)}&reason=invalidated`,
263
- reason: 'force_invalidated',
264
- clearCookies: true
265
- };
266
- }
267
-
268
- // --- Stale session (cookie exists but Redis entry gone) ---
269
- if (!sessionStatus.exists) {
270
- if (onLoginPage) return { type: 'allow' };
271
- if (pathname.startsWith('/api/')) return { type: 'allow' };
272
- return {
273
- type: 'redirect',
274
- location: `${LOGIN_PAGE}?callbackUrl=${encodeURIComponent(safeCallback)}&reason=stale`,
275
- reason: 'stale_session',
276
- clearCookies: true
277
- };
278
- }
279
-
280
- // --- 2FA required but not completed ---
281
- if (needsTwoFactorRedirect(pathname, sessionPointer, sessionStatus)) {
282
- if (onLoginPage) {
283
- const cb = getSafeCallbackUrl(pathname, searchParams);
284
- return { type: 'redirect', location: `${VERIFY_CODE_PAGE}?callbackUrl=${encodeURIComponent(cb)}`, reason: '2fa_from_login' };
285
- }
286
- return redirect2FA(safeCallback);
287
- }
288
-
289
- // --- Token expired: Try refresh ---
290
- if (sessionPointer.expired) {
291
- if (onLoginPage) return { type: 'allow' };
292
- if (sessionPointer.hasRefreshToken) {
293
- return { type: 'refresh_needed' };
294
- }
295
- return {
296
- type: 'redirect',
297
- location: `${LOGIN_PAGE}?callbackUrl=${encodeURIComponent(safeCallback)}&error=SessionExpired`,
298
- reason: 'token_expired_no_refresh'
299
- };
300
- }
301
-
302
- // --- Authenticated user on login page: Send to their destination ---
303
- if (onLoginPage) {
304
- const dest = getSafeCallbackUrl(pathname, searchParams);
305
- return { type: 'redirect', location: dest, reason: 'already_authenticated' };
306
- }
307
-
308
- // --- All checks passed ---
309
- return { type: 'allow' };
310
- }
311
-
312
- /** Check if user needs 2FA redirect */
313
- function needsTwoFactorRedirect(pathname: string, session: SessionPointer, status: SessionStatus): boolean {
314
- if (!session.exists || !status.exists) return false;
315
- if (!status.requires2FA || status.twoFactorComplete) return false;
316
- if (pathname === VERIFY_CODE_PAGE) return false;
317
- if (should2FABypass(pathname)) return false;
318
- if (pathname.startsWith('/api/')) return false; // APIs return JSON errors
319
- return true;
320
- }
321
-
322
- function redirect2FA(callbackUrl: string): AuthAction {
323
- return {
324
- type: 'redirect',
325
- location: `${VERIFY_CODE_PAGE}?callbackUrl=${encodeURIComponent(callbackUrl)}`,
326
- reason: '2fa_required'
327
- };
328
- }
329
-
330
- // =============================================================================
331
- // MIDDLEWARE FACTORY
332
- // =============================================================================
333
-
334
- export function createMvpMiddleware(options: MvpMiddlewareOptions = {}) {
335
- // Resolve options with defaults
336
- const cb = options.circuitBreaker || defaultCircuitBreaker;
337
- const log = options.logger || defaultLogger;
338
- const viabilityEndpoint = options.viabilityEndpoint || '/api/session/viability';
339
- const refreshEndpoint = options.refreshEndpoint || '/api/auth/refresh';
340
- const bypassPaths = options.bypassPaths || [];
341
- const rbacExemptPaths = options.rbacExemptPaths || [];
342
-
343
- return async function middleware(request: NextRequest): Promise<NextResponse> {
344
- const { pathname, searchParams } = request.nextUrl;
345
-
346
- // =========================================================================
347
- // CRITICAL: Auth routes MUST bypass middleware
348
- // =========================================================================
349
- // These routes are called internally by middleware itself (viability check,
350
- // token refresh). Without this bypass, we get infinite loops or 403s.
351
- // This has caused production outages. DO NOT REMOVE.
352
- // =========================================================================
353
- if (pathname.startsWith('/api/auth/') || pathname.startsWith('/api/session/')) {
354
- return NextResponse.next();
355
- }
356
-
357
- // Check custom bypass paths
358
- for (const bypassPath of bypassPaths) {
359
- if (pathname.startsWith(bypassPath)) {
360
- return NextResponse.next();
361
- }
362
- }
363
-
364
- const isPublic = isUnauthenticatedRoute(pathname);
365
- const isLogin = isLoginPage(pathname);
366
-
367
- // --- Optimization: Skip viability check for unauthenticated public browsing ---
368
- if (isPublic && !isLogin) {
369
- const hasCookie = request.cookies.get(getSessionCookieName())?.value ||
370
- request.cookies.get(getSecureSessionCookieName())?.value;
371
- if (!hasCookie) {
372
- return NextResponse.next();
373
- }
374
- // Has cookie - continue to viability check for 2FA enforcement
375
- }
376
-
377
- // --- Fetch session viability from internal API ---
378
- const { sessionStatus, sessionPointer } = await checkViability(request, viabilityEndpoint, log);
379
-
380
- // --- Handle stale session early (cookie exists but session doesn't) ---
381
- if (!isPublic && sessionStatus.exists === false && sessionPointer.sessionToken) {
382
- const safeCallback = getSafeCallbackUrl(pathname);
383
- log.warn('Stale session detected', {
384
- sessionToken: sessionPointer.sessionToken?.substring(0, 8) + '...',
385
- pathname
386
- });
387
- return redirectTo(request, `${LOGIN_PAGE}?callbackUrl=${encodeURIComponent(safeCallback)}`, true);
388
- }
389
-
390
- // --- Run decision engine ---
391
- const decision = makeAuthDecision({
392
- pathname,
393
- isPublicRoute: isPublic,
394
- isLoginPage: isLogin,
395
- searchParams,
396
- sessionPointer,
397
- sessionStatus,
398
- circuitBreakerOpen: cb.isOpen(),
399
- });
400
-
401
- // --- Execute decision ---
402
- return executeDecision(request, decision, pathname, sessionPointer, sessionStatus, {
403
- circuitBreaker: cb,
404
- logger: log,
405
- refreshEndpoint,
406
- rbacExemptPaths,
407
- onRefreshSuccess: options.onRefreshSuccess,
408
- onRefreshFailure: options.onRefreshFailure,
409
- });
410
- };
411
- }
412
-
413
- /** Check session viability via internal API */
414
- async function checkViability(
415
- request: NextRequest,
416
- endpoint: string,
417
- log: MiddlewareLogger
418
- ): Promise<{
419
- sessionStatus: SessionStatus;
420
- sessionPointer: SessionPointer;
421
- }> {
422
- const sessionStatus: SessionStatus = {
423
- exists: false,
424
- forceInvalid: false,
425
- requires2FA: false,
426
- twoFactorComplete: false,
427
- };
428
- const sessionPointer: SessionPointer = {
429
- exists: false,
430
- sessionToken: undefined,
431
- expired: false,
432
- hasRefreshToken: false,
433
- roles: [],
434
- clientId: '',
435
- };
436
-
437
- try {
438
- const baseUrl = getInternalApiUrl(request);
439
- const response = await fetch(new URL(endpoint, baseUrl), {
440
- method: 'GET',
441
- headers: {
442
- 'Accept': 'application/json',
443
- 'Cache-Control': 'no-store',
444
- 'Cookie': request.headers.get('cookie') || ''
445
- },
446
- credentials: 'include',
447
- signal: AbortSignal.timeout(5000),
448
- });
449
-
450
- if (response.ok) {
451
- const data = await response.json();
452
- // Support both response formats (viability and refresh-viability)
453
- sessionStatus.exists = data.authenticated ?? (data.sessionToken && data.reason !== 'session_not_found');
454
- sessionStatus.requires2FA = data.requires2FA || false;
455
- sessionStatus.twoFactorComplete = data.twoFactorComplete || false;
456
- sessionPointer.exists = sessionStatus.exists ?? false;
457
- sessionPointer.sessionToken = data.sessionToken;
458
- sessionPointer.expired = data.accessTokenExpired || false;
459
- sessionPointer.hasRefreshToken = data.hasRefreshToken ?? data.canRefresh ?? false;
460
- sessionPointer.roles = data.roles || [];
461
- sessionPointer.clientId = data.clientId || '';
462
- } else {
463
- log.error('Viability check failed', { status: response.status });
464
- sessionStatus.exists = null;
465
- sessionStatus.forceInvalid = null;
466
- }
467
- } catch (error) {
468
- log.error('Viability check error', { error: error instanceof Error ? error.message : String(error) });
469
- sessionStatus.exists = null;
470
- sessionStatus.forceInvalid = null;
471
- }
472
-
473
- return { sessionStatus, sessionPointer };
474
- }
475
-
476
- /** Options passed to executeDecision */
477
- interface ExecuteOptions {
478
- circuitBreaker: CircuitBreakerProvider;
479
- logger: MiddlewareLogger;
480
- refreshEndpoint: string;
481
- rbacExemptPaths: string[];
482
- onRefreshSuccess?: () => void;
483
- onRefreshFailure?: (status: number, isNetworkError: boolean) => void;
484
- }
485
-
486
- /** Execute the auth decision */
487
- async function executeDecision(
488
- request: NextRequest,
489
- decision: AuthAction,
490
- pathname: string,
491
- sessionPointer: SessionPointer,
492
- sessionStatus: SessionStatus,
493
- opts: ExecuteOptions
494
- ): Promise<NextResponse> {
495
- const safeCallback = getSafeCallbackUrl(pathname);
496
-
497
- switch (decision.type) {
498
- case 'allow':
499
- return handleAllow(request, pathname, sessionPointer, sessionStatus, opts.rbacExemptPaths);
500
-
501
- case 'redirect':
502
- return redirectTo(request, decision.location, decision.clearCookies);
503
-
504
- case 'service_error':
505
- return NextResponse.redirect(new URL('/service-unavailable', request.url));
506
-
507
- case 'refresh_needed':
508
- return handleRefresh(request, safeCallback, opts);
509
- }
510
- }
511
-
512
- /** Paths that must never be RBAC-checked (they are RBAC redirect targets) */
513
- const RBAC_EXEMPT_PATHS = ['/error', '/unauthorized', '/service-unavailable'];
514
-
515
- /** Handle 'allow' decision - run RBAC if enabled */
516
- async function handleAllow(
517
- request: NextRequest,
518
- pathname: string,
519
- sessionPointer: SessionPointer,
520
- sessionStatus: SessionStatus,
521
- rbacExemptPaths: string[] = []
522
- ): Promise<NextResponse> {
523
- const isPublic = isUnauthenticatedRoute(pathname);
524
-
525
- if (isRBACEnabled() && !isPublic && sessionPointer.exists) {
526
- // Skip RBAC for error/fallback pages (prevent redirect loops) and app-configured exempt paths
527
- if (RBAC_EXEMPT_PATHS.some(p => pathname.startsWith(p)) ||
528
- rbacExemptPaths.some(p => pathname.startsWith(p))) {
529
- return NextResponse.next();
530
- }
531
-
532
- if (!sessionPointer.clientId) {
533
- console.error('[MIDDLEWARE] RBAC: No clientId — returning 401');
534
- if (pathname.startsWith('/api/')) {
535
- return NextResponse.json(
536
- { error: 'Unauthorized — missing clientId for RBAC' },
537
- { status: 401 }
538
- );
539
- }
540
- return NextResponse.redirect(new URL('/unauthorized', request.url));
541
- }
542
-
543
- try {
544
- const result = await checkPagePermission(pathname, sessionPointer.roles, sessionPointer.clientId);
545
-
546
- if (!result.allowed) {
547
- console.log('[MIDDLEWARE] RBAC denied:', { pathname, reason: result.reason });
548
-
549
- // In development, fail open - RBAC API may not be fully configured
550
- if (process.env.NODE_ENV !== 'production') {
551
- console.warn('[MIDDLEWARE] RBAC: Allowing in development despite denial:', result.reason);
552
- return NextResponse.next();
553
- }
554
-
555
- return NextResponse.redirect(new URL(result.redirect || '/unauthorized', request.url));
556
- }
557
-
558
- if (result.requires_2fa && !sessionStatus.twoFactorComplete) {
559
- return NextResponse.redirect(
560
- new URL(`${VERIFY_CODE_PAGE}?callbackUrl=${encodeURIComponent(pathname)}`, request.url)
561
- );
562
- }
563
- } catch (error) {
564
- console.error('[MIDDLEWARE] RBAC error:', error);
565
-
566
- // In development, fail open
567
- if (process.env.NODE_ENV !== 'production') {
568
- console.warn('[MIDDLEWARE] RBAC: Allowing in development despite error');
569
- return NextResponse.next();
570
- }
571
-
572
- return NextResponse.redirect(new URL('/error?code=rbac_error', request.url));
573
- }
574
- }
575
-
576
- return NextResponse.next();
577
- }
578
-
579
- /** Handle token refresh */
580
- async function handleRefresh(
581
- request: NextRequest,
582
- safeCallback: string,
583
- opts: ExecuteOptions
584
- ): Promise<NextResponse> {
585
- const { circuitBreaker: cb, logger: log, refreshEndpoint, onRefreshSuccess, onRefreshFailure } = opts;
586
-
587
- // Check if circuit breaker allows refresh attempt
588
- if (!cb.canAttemptRefresh()) {
589
- log.warn('Circuit breaker preventing refresh attempt');
590
- return redirectTo(
591
- request,
592
- `${LOGIN_PAGE}?callbackUrl=${encodeURIComponent(safeCallback)}&error=ServiceUnavailable`,
593
- true
594
- );
595
- }
596
-
597
- try {
598
- const baseUrl = getInternalApiUrl(request);
599
- const response = await fetch(new URL(refreshEndpoint, baseUrl), {
600
- method: 'POST',
601
- headers: {
602
- 'Accept': 'application/json',
603
- 'Content-Type': 'application/json',
604
- 'Cookie': request.headers.get('cookie') || '',
605
- 'x-session-token': request.cookies.get(getSessionCookieName())?.value ||
606
- request.cookies.get(getSecureSessionCookieName())?.value || ''
607
- },
608
- credentials: 'include',
609
- signal: AbortSignal.timeout(5000),
610
- });
611
-
612
- if (response.ok) {
613
- const data = await response.json();
614
- if (data.refreshed || data.reason === 'already_fresh') {
615
- cb.recordSuccess();
616
- onRefreshSuccess?.();
617
- log.info('Token refresh successful');
618
- return NextResponse.next();
619
- }
620
- }
621
-
622
- // Refresh failed - check for permanent failures (401/403) vs transient (5xx)
623
- // CRITICAL: Always clear cookies on 401/403 to prevent redirect loops
624
- // CRITICAL: Only record circuit breaker failures for network errors, not HTTP errors
625
- // HTTP 500 means the server responded - it's reachable. Only network failures should trip the breaker.
626
- const isPermanentFailure = response.status === 401 || response.status === 403;
627
- const errorParam = isPermanentFailure ? 'SessionExpired' : 'RefreshError';
628
-
629
- log.warn('Refresh failed', {
630
- status: response.status,
631
- isPermanentFailure,
632
- clearingCookies: isPermanentFailure
633
- });
634
-
635
- onRefreshFailure?.(response.status, false);
636
-
637
- return redirectTo(
638
- request,
639
- `${LOGIN_PAGE}?callbackUrl=${encodeURIComponent(safeCallback)}&error=${errorParam}`,
640
- isPermanentFailure
641
- );
642
- } catch (error: any) {
643
- const isNetwork = cb.isNetworkError(error);
644
- log.error('Refresh error', {
645
- error: error instanceof Error ? error.message : String(error),
646
- isNetworkError: isNetwork
647
- });
648
-
649
- // Only record circuit breaker failure for actual network errors
650
- if (isNetwork) {
651
- cb.recordFailure(error);
652
- }
653
-
654
- onRefreshFailure?.(0, isNetwork);
655
-
656
- // Network error - don't clear cookies, might be transient
657
- return redirectTo(
658
- request,
659
- `${LOGIN_PAGE}?callbackUrl=${encodeURIComponent(safeCallback)}&error=RefreshError`,
660
- false
661
- );
662
- }
663
- }
1
+ /**
2
+ * MVP Middleware - Authentication & Route Protection
3
+ *
4
+ * Creates a Next.js middleware handler that protects routes based on:
5
+ * - Authentication status (session cookie → Redis viability check)
6
+ * - 2FA completion status
7
+ * - RBAC permissions (if enabled)
8
+ *
9
+ * Usage: Export the result from your app's middleware.ts:
10
+ * export default createMvpMiddleware();
11
+ *
12
+ * With custom options:
13
+ * export default createMvpMiddleware({
14
+ * circuitBreaker: myCircuitBreaker,
15
+ * logger: myLogger,
16
+ * viabilityEndpoint: '/api/session/refresh-viability',
17
+ * });
18
+ */
19
+
20
+ import { NextRequest, NextResponse } from 'next/server';
21
+ import { isUnauthenticatedRoute, should2FABypass } from '../auth/route-config';
22
+ import { getInternalApiUrl } from '../edge/internal-api-url';
23
+ import { getSessionCookieName, getSecureSessionCookieName } from '../lib/app-slug';
24
+ import { checkPagePermission, isRBACEnabled } from './rbac-check';
25
+
26
+ // =============================================================================
27
+ // TYPES
28
+ // =============================================================================
29
+
30
+ export interface AuthContext {
31
+ pathname: string;
32
+ isPublicRoute: boolean;
33
+ isLoginPage: boolean;
34
+ searchParams: URLSearchParams;
35
+ sessionPointer: SessionPointer;
36
+ sessionStatus: SessionStatus;
37
+ circuitBreakerOpen: boolean;
38
+ }
39
+
40
+ export interface SessionPointer {
41
+ exists: boolean;
42
+ sessionToken?: string;
43
+ expired?: boolean;
44
+ hasRefreshToken?: boolean;
45
+ roles: string[];
46
+ clientId: string;
47
+ }
48
+
49
+ export interface SessionStatus {
50
+ exists: boolean | null; // null = check failed/timeout
51
+ forceInvalid: boolean | null; // null = check failed/timeout
52
+ requires2FA: boolean;
53
+ twoFactorComplete: boolean;
54
+ }
55
+
56
+ export type AuthAction =
57
+ | { type: 'allow' }
58
+ | { type: 'redirect'; location: string; reason: string; clearCookies?: boolean }
59
+ | { type: 'service_error'; reason: string }
60
+ | { type: 'refresh_needed' };
61
+
62
+ // =============================================================================
63
+ // CIRCUIT BREAKER INTERFACE
64
+ // =============================================================================
65
+
66
+ /**
67
+ * Circuit breaker interface for middleware integration.
68
+ * Implement this to provide custom circuit breaker behavior.
69
+ */
70
+ export interface CircuitBreakerProvider {
71
+ /** Check if circuit breaker is currently open */
72
+ isOpen(): boolean;
73
+ /** Check if a refresh attempt is allowed (for HALF_OPEN state) */
74
+ canAttemptRefresh(): boolean;
75
+ /** Record a successful operation (closes the breaker) */
76
+ recordSuccess(): void;
77
+ /** Record a failed operation (may open the breaker) */
78
+ recordFailure(error?: Error): void;
79
+ /** Check if an error is a network error (vs HTTP error) */
80
+ isNetworkError(error: any): boolean;
81
+ }
82
+
83
+ /**
84
+ * Logger interface for middleware.
85
+ * Implement this to provide custom logging.
86
+ */
87
+ export interface MiddlewareLogger {
88
+ info(message: string, data?: Record<string, any>): void;
89
+ warn(message: string, data?: Record<string, any>): void;
90
+ error(message: string, data?: Record<string, any>): void;
91
+ }
92
+
93
+ /**
94
+ * Configuration options for createMvpMiddleware
95
+ */
96
+ export interface MvpMiddlewareOptions {
97
+ /** Custom circuit breaker implementation */
98
+ circuitBreaker?: CircuitBreakerProvider;
99
+ /** Custom logger implementation */
100
+ logger?: MiddlewareLogger;
101
+ /** Custom viability check endpoint (default: /api/session/viability) */
102
+ viabilityEndpoint?: string;
103
+ /** Custom refresh endpoint (default: /api/auth/refresh) */
104
+ refreshEndpoint?: string;
105
+ /** Hook called on successful refresh */
106
+ onRefreshSuccess?: () => void;
107
+ /** Hook called on refresh failure */
108
+ onRefreshFailure?: (status: number, isNetworkError: boolean) => void;
109
+ /** Additional paths to bypass middleware (beyond /api/auth/ and /api/session/) */
110
+ bypassPaths?: string[];
111
+ /** Paths exempt from RBAC checks (auth still enforced, just no page-permission check) */
112
+ rbacExemptPaths?: string[];
113
+ }
114
+
115
+ // =============================================================================
116
+ // DEFAULT IMPLEMENTATIONS
117
+ // =============================================================================
118
+
119
+ /** Default no-op circuit breaker (always closed) */
120
+ const defaultCircuitBreaker: CircuitBreakerProvider = {
121
+ isOpen: () => false,
122
+ canAttemptRefresh: () => true,
123
+ recordSuccess: () => {},
124
+ recordFailure: () => {},
125
+ isNetworkError: (error: any) => {
126
+ return error?.cause?.code === 'ECONNREFUSED' ||
127
+ error?.code === 'ECONNREFUSED' ||
128
+ error?.message?.includes('ECONNREFUSED') ||
129
+ error?.message?.includes('fetch failed') ||
130
+ error?.message?.includes('ENOTFOUND') ||
131
+ error?.message?.includes('ETIMEDOUT') ||
132
+ error?.message?.includes('ECONNRESET');
133
+ }
134
+ };
135
+
136
+ /** Default console logger */
137
+ const defaultLogger: MiddlewareLogger = {
138
+ info: (msg, data) => console.log(`[MIDDLEWARE] ${msg}`, data || ''),
139
+ warn: (msg, data) => console.warn(`[MIDDLEWARE] ${msg}`, data || ''),
140
+ error: (msg, data) => console.error(`[MIDDLEWARE] ${msg}`, data || ''),
141
+ };
142
+
143
+ // =============================================================================
144
+ // HELPERS
145
+ // =============================================================================
146
+
147
+ const LOGIN_PAGE = '/account-auth/login';
148
+ const VERIFY_CODE_PAGE = '/account-auth/verify-code';
149
+
150
+ function isLoginPage(pathname: string): boolean {
151
+ return pathname === LOGIN_PAGE;
152
+ }
153
+
154
+ /** Ensures callback URLs never point to auth pages (prevents redirect loops) */
155
+ function getSafeCallbackUrl(pathname: string, searchParams?: URLSearchParams): string {
156
+ if (pathname.startsWith('/account-auth/')) {
157
+ return '/';
158
+ }
159
+ const existing = searchParams?.get('callbackUrl');
160
+ if (existing && !existing.startsWith('/account-auth/')) {
161
+ return existing;
162
+ }
163
+ return pathname;
164
+ }
165
+
166
+ /** Clear all session cookies on a response */
167
+ function clearSessionCookies(response: NextResponse, request: NextRequest): void {
168
+ const sessionCookie = getSessionCookieName();
169
+ const secureCookie = getSecureSessionCookieName();
170
+
171
+ // Clear main cookies
172
+ response.cookies.set(sessionCookie, '', { path: '/', expires: new Date(0), httpOnly: true, sameSite: 'lax' });
173
+ response.cookies.set(secureCookie, '', { path: '/', expires: new Date(0), httpOnly: true, sameSite: 'lax', secure: true });
174
+
175
+ // Clear any chunked cookies (NextAuth chunks large cookies)
176
+ for (const [name] of request.cookies) {
177
+ if (name.startsWith(`${sessionCookie}.`) || name.startsWith(`${secureCookie}.`)) {
178
+ const isSecure = name.startsWith('__Secure-');
179
+ response.cookies.set(name, '', {
180
+ path: '/',
181
+ expires: new Date(0),
182
+ httpOnly: true,
183
+ sameSite: 'lax',
184
+ ...(isSecure && { secure: true })
185
+ });
186
+ }
187
+ }
188
+ }
189
+
190
+ /** Create redirect response, optionally clearing cookies */
191
+ function redirectTo(
192
+ request: NextRequest,
193
+ location: string,
194
+ clearCookies = false
195
+ ): NextResponse {
196
+ const response = NextResponse.redirect(new URL(location, request.url));
197
+ if (clearCookies) {
198
+ clearSessionCookies(response, request);
199
+ }
200
+ return response;
201
+ }
202
+
203
+ // =============================================================================
204
+ // AUTH DECISION ENGINE
205
+ // =============================================================================
206
+
207
+ /**
208
+ * Pure function that determines what action to take based on auth state.
209
+ * No side effects - just examines context and returns a decision.
210
+ */
211
+ function makeAuthDecision(ctx: AuthContext): AuthAction {
212
+ const { pathname, isPublicRoute, isLoginPage: onLoginPage, searchParams, sessionPointer, sessionStatus, circuitBreakerOpen } = ctx;
213
+ const safeCallback = getSafeCallbackUrl(pathname);
214
+
215
+ // --- Public routes: Allow, but enforce 2FA for authenticated users ---
216
+ if (isPublicRoute && !onLoginPage) {
217
+ if (needsTwoFactorRedirect(pathname, sessionPointer, sessionStatus)) {
218
+ return redirect2FA(safeCallback);
219
+ }
220
+ return { type: 'allow' };
221
+ }
222
+
223
+ // --- Circuit breaker open: Service degraded ---
224
+ if (circuitBreakerOpen) {
225
+ if (onLoginPage) return { type: 'allow' };
226
+ return {
227
+ type: 'redirect',
228
+ location: `${LOGIN_PAGE}?error=ServiceUnavailable`,
229
+ reason: 'circuit_breaker_open',
230
+ clearCookies: true
231
+ };
232
+ }
233
+
234
+ // --- No session cookie: Need to login ---
235
+ if (!sessionPointer.exists) {
236
+ if (onLoginPage) return { type: 'allow' };
237
+ if (pathname === '/') {
238
+ const unauthUrl = process.env.UNAUTHENTICATED_REDIRECT_URL || '/account-auth/login';
239
+ return { type: 'redirect', location: unauthUrl, reason: 'unauthenticated_root' };
240
+ }
241
+ if (pathname.startsWith('/api/')) {
242
+ return { type: 'allow' }; // Let API return proper 401 JSON
243
+ }
244
+ return {
245
+ type: 'redirect',
246
+ location: `${LOGIN_PAGE}?callbackUrl=${encodeURIComponent(safeCallback)}`,
247
+ reason: 'no_session'
248
+ };
249
+ }
250
+
251
+ // --- Service error: Can't verify session ---
252
+ if (sessionStatus.exists === null || sessionStatus.forceInvalid === null) {
253
+ return { type: 'service_error', reason: 'viability_check_failed' };
254
+ }
255
+
256
+ // --- Session force-invalidated (admin action, password change, etc.) ---
257
+ if (sessionStatus.forceInvalid) {
258
+ if (onLoginPage) return { type: 'allow' };
259
+ if (pathname.startsWith('/api/')) return { type: 'allow' };
260
+ return {
261
+ type: 'redirect',
262
+ location: `${LOGIN_PAGE}?callbackUrl=${encodeURIComponent(safeCallback)}&reason=invalidated`,
263
+ reason: 'force_invalidated',
264
+ clearCookies: true
265
+ };
266
+ }
267
+
268
+ // --- Stale session (cookie exists but Redis entry gone) ---
269
+ if (!sessionStatus.exists) {
270
+ if (onLoginPage) return { type: 'allow' };
271
+ if (pathname.startsWith('/api/')) return { type: 'allow' };
272
+ return {
273
+ type: 'redirect',
274
+ location: `${LOGIN_PAGE}?callbackUrl=${encodeURIComponent(safeCallback)}&reason=stale`,
275
+ reason: 'stale_session',
276
+ clearCookies: true
277
+ };
278
+ }
279
+
280
+ // --- 2FA required but not completed ---
281
+ if (needsTwoFactorRedirect(pathname, sessionPointer, sessionStatus)) {
282
+ if (onLoginPage) {
283
+ const cb = getSafeCallbackUrl(pathname, searchParams);
284
+ return { type: 'redirect', location: `${VERIFY_CODE_PAGE}?callbackUrl=${encodeURIComponent(cb)}`, reason: '2fa_from_login' };
285
+ }
286
+ return redirect2FA(safeCallback);
287
+ }
288
+
289
+ // --- Token expired: Try refresh ---
290
+ if (sessionPointer.expired) {
291
+ if (onLoginPage) return { type: 'allow' };
292
+ if (sessionPointer.hasRefreshToken) {
293
+ return { type: 'refresh_needed' };
294
+ }
295
+ return {
296
+ type: 'redirect',
297
+ location: `${LOGIN_PAGE}?callbackUrl=${encodeURIComponent(safeCallback)}&error=SessionExpired`,
298
+ reason: 'token_expired_no_refresh'
299
+ };
300
+ }
301
+
302
+ // --- Authenticated user on login page: Send to their destination ---
303
+ if (onLoginPage) {
304
+ const dest = getSafeCallbackUrl(pathname, searchParams);
305
+ return { type: 'redirect', location: dest, reason: 'already_authenticated' };
306
+ }
307
+
308
+ // --- All checks passed ---
309
+ return { type: 'allow' };
310
+ }
311
+
312
+ /** Check if user needs 2FA redirect */
313
+ function needsTwoFactorRedirect(pathname: string, session: SessionPointer, status: SessionStatus): boolean {
314
+ if (!session.exists || !status.exists) return false;
315
+ if (!status.requires2FA || status.twoFactorComplete) return false;
316
+ if (pathname === VERIFY_CODE_PAGE) return false;
317
+ if (should2FABypass(pathname)) return false;
318
+ if (pathname.startsWith('/api/')) return false; // APIs return JSON errors
319
+ return true;
320
+ }
321
+
322
+ function redirect2FA(callbackUrl: string): AuthAction {
323
+ return {
324
+ type: 'redirect',
325
+ location: `${VERIFY_CODE_PAGE}?callbackUrl=${encodeURIComponent(callbackUrl)}`,
326
+ reason: '2fa_required'
327
+ };
328
+ }
329
+
330
+ // =============================================================================
331
+ // MIDDLEWARE FACTORY
332
+ // =============================================================================
333
+
334
+ export function createMvpMiddleware(options: MvpMiddlewareOptions = {}) {
335
+ // Resolve options with defaults
336
+ const cb = options.circuitBreaker || defaultCircuitBreaker;
337
+ const log = options.logger || defaultLogger;
338
+ const viabilityEndpoint = options.viabilityEndpoint || '/api/session/viability';
339
+ const refreshEndpoint = options.refreshEndpoint || '/api/auth/refresh';
340
+ const bypassPaths = options.bypassPaths || [];
341
+ const rbacExemptPaths = options.rbacExemptPaths || [];
342
+
343
+ return async function middleware(request: NextRequest): Promise<NextResponse> {
344
+ const { pathname, searchParams } = request.nextUrl;
345
+
346
+ // =========================================================================
347
+ // CRITICAL: Auth routes MUST bypass middleware
348
+ // =========================================================================
349
+ // These routes are called internally by middleware itself (viability check,
350
+ // token refresh). Without this bypass, we get infinite loops or 403s.
351
+ // This has caused production outages. DO NOT REMOVE.
352
+ // =========================================================================
353
+ if (pathname.startsWith('/api/auth/') || pathname.startsWith('/api/session/')) {
354
+ return NextResponse.next();
355
+ }
356
+
357
+ // Check custom bypass paths
358
+ for (const bypassPath of bypassPaths) {
359
+ if (pathname.startsWith(bypassPath)) {
360
+ return NextResponse.next();
361
+ }
362
+ }
363
+
364
+ const isPublic = isUnauthenticatedRoute(pathname);
365
+ const isLogin = isLoginPage(pathname);
366
+
367
+ // --- Optimization: Skip viability check for unauthenticated public browsing ---
368
+ if (isPublic && !isLogin) {
369
+ const hasCookie = request.cookies.get(getSessionCookieName())?.value ||
370
+ request.cookies.get(getSecureSessionCookieName())?.value;
371
+ if (!hasCookie) {
372
+ return NextResponse.next();
373
+ }
374
+ // Has cookie - continue to viability check for 2FA enforcement
375
+ }
376
+
377
+ // --- Fetch session viability from internal API ---
378
+ const { sessionStatus, sessionPointer } = await checkViability(request, viabilityEndpoint, log);
379
+
380
+ // --- Handle stale session early (cookie exists but session doesn't) ---
381
+ if (!isPublic && sessionStatus.exists === false && sessionPointer.sessionToken) {
382
+ const safeCallback = getSafeCallbackUrl(pathname);
383
+ log.warn('Stale session detected', {
384
+ sessionToken: sessionPointer.sessionToken?.substring(0, 8) + '...',
385
+ pathname
386
+ });
387
+ return redirectTo(request, `${LOGIN_PAGE}?callbackUrl=${encodeURIComponent(safeCallback)}`, true);
388
+ }
389
+
390
+ // --- Run decision engine ---
391
+ const decision = makeAuthDecision({
392
+ pathname,
393
+ isPublicRoute: isPublic,
394
+ isLoginPage: isLogin,
395
+ searchParams,
396
+ sessionPointer,
397
+ sessionStatus,
398
+ circuitBreakerOpen: cb.isOpen(),
399
+ });
400
+
401
+ // --- Execute decision ---
402
+ return executeDecision(request, decision, pathname, sessionPointer, sessionStatus, {
403
+ circuitBreaker: cb,
404
+ logger: log,
405
+ refreshEndpoint,
406
+ rbacExemptPaths,
407
+ onRefreshSuccess: options.onRefreshSuccess,
408
+ onRefreshFailure: options.onRefreshFailure,
409
+ });
410
+ };
411
+ }
412
+
413
+ /** Check session viability via internal API */
414
+ async function checkViability(
415
+ request: NextRequest,
416
+ endpoint: string,
417
+ log: MiddlewareLogger
418
+ ): Promise<{
419
+ sessionStatus: SessionStatus;
420
+ sessionPointer: SessionPointer;
421
+ }> {
422
+ const sessionStatus: SessionStatus = {
423
+ exists: false,
424
+ forceInvalid: false,
425
+ requires2FA: false,
426
+ twoFactorComplete: false,
427
+ };
428
+ const sessionPointer: SessionPointer = {
429
+ exists: false,
430
+ sessionToken: undefined,
431
+ expired: false,
432
+ hasRefreshToken: false,
433
+ roles: [],
434
+ clientId: '',
435
+ };
436
+
437
+ try {
438
+ const baseUrl = getInternalApiUrl(request);
439
+ const response = await fetch(new URL(endpoint, baseUrl), {
440
+ method: 'GET',
441
+ headers: {
442
+ 'Accept': 'application/json',
443
+ 'Cache-Control': 'no-store',
444
+ 'Cookie': request.headers.get('cookie') || ''
445
+ },
446
+ credentials: 'include',
447
+ signal: AbortSignal.timeout(5000),
448
+ });
449
+
450
+ if (response.ok) {
451
+ const data = await response.json();
452
+ // Support both response formats (viability and refresh-viability)
453
+ sessionStatus.exists = data.authenticated ?? (data.sessionToken && data.reason !== 'session_not_found');
454
+ sessionStatus.requires2FA = data.requires2FA || false;
455
+ sessionStatus.twoFactorComplete = data.twoFactorComplete || false;
456
+ sessionPointer.exists = sessionStatus.exists ?? false;
457
+ sessionPointer.sessionToken = data.sessionToken;
458
+ sessionPointer.expired = data.accessTokenExpired || false;
459
+ sessionPointer.hasRefreshToken = data.hasRefreshToken ?? data.canRefresh ?? false;
460
+ sessionPointer.roles = data.roles || [];
461
+ sessionPointer.clientId = data.clientId || '';
462
+ } else {
463
+ log.error('Viability check failed', { status: response.status });
464
+ sessionStatus.exists = null;
465
+ sessionStatus.forceInvalid = null;
466
+ }
467
+ } catch (error) {
468
+ log.error('Viability check error', { error: error instanceof Error ? error.message : String(error) });
469
+ sessionStatus.exists = null;
470
+ sessionStatus.forceInvalid = null;
471
+ }
472
+
473
+ return { sessionStatus, sessionPointer };
474
+ }
475
+
476
+ /** Options passed to executeDecision */
477
+ interface ExecuteOptions {
478
+ circuitBreaker: CircuitBreakerProvider;
479
+ logger: MiddlewareLogger;
480
+ refreshEndpoint: string;
481
+ rbacExemptPaths: string[];
482
+ onRefreshSuccess?: () => void;
483
+ onRefreshFailure?: (status: number, isNetworkError: boolean) => void;
484
+ }
485
+
486
+ /** Execute the auth decision */
487
+ async function executeDecision(
488
+ request: NextRequest,
489
+ decision: AuthAction,
490
+ pathname: string,
491
+ sessionPointer: SessionPointer,
492
+ sessionStatus: SessionStatus,
493
+ opts: ExecuteOptions
494
+ ): Promise<NextResponse> {
495
+ const safeCallback = getSafeCallbackUrl(pathname);
496
+
497
+ switch (decision.type) {
498
+ case 'allow':
499
+ return handleAllow(request, pathname, sessionPointer, sessionStatus, opts.rbacExemptPaths);
500
+
501
+ case 'redirect':
502
+ return redirectTo(request, decision.location, decision.clearCookies);
503
+
504
+ case 'service_error':
505
+ return NextResponse.redirect(new URL('/service-unavailable', request.url));
506
+
507
+ case 'refresh_needed':
508
+ return handleRefresh(request, safeCallback, opts);
509
+ }
510
+ }
511
+
512
+ /** Paths that must never be RBAC-checked (they are RBAC redirect targets) */
513
+ const RBAC_EXEMPT_PATHS = ['/error', '/unauthorized', '/service-unavailable'];
514
+
515
+ /** Handle 'allow' decision - run RBAC if enabled */
516
+ async function handleAllow(
517
+ request: NextRequest,
518
+ pathname: string,
519
+ sessionPointer: SessionPointer,
520
+ sessionStatus: SessionStatus,
521
+ rbacExemptPaths: string[] = []
522
+ ): Promise<NextResponse> {
523
+ const isPublic = isUnauthenticatedRoute(pathname);
524
+
525
+ if (isRBACEnabled() && !isPublic && sessionPointer.exists) {
526
+ // Skip RBAC for error/fallback pages (prevent redirect loops) and app-configured exempt paths
527
+ if (RBAC_EXEMPT_PATHS.some(p => pathname.startsWith(p)) ||
528
+ rbacExemptPaths.some(p => pathname.startsWith(p))) {
529
+ return NextResponse.next();
530
+ }
531
+
532
+ if (!sessionPointer.clientId) {
533
+ console.error('[MIDDLEWARE] RBAC: No clientId — returning 401');
534
+ if (pathname.startsWith('/api/')) {
535
+ return NextResponse.json(
536
+ { error: 'Unauthorized — missing clientId for RBAC' },
537
+ { status: 401 }
538
+ );
539
+ }
540
+ return NextResponse.redirect(new URL('/unauthorized', request.url));
541
+ }
542
+
543
+ try {
544
+ const result = await checkPagePermission(pathname, sessionPointer.roles, sessionPointer.clientId);
545
+
546
+ if (!result.allowed) {
547
+ console.log('[MIDDLEWARE] RBAC denied:', { pathname, reason: result.reason });
548
+
549
+ // In development, fail open - RBAC API may not be fully configured
550
+ if (process.env.NODE_ENV !== 'production') {
551
+ console.warn('[MIDDLEWARE] RBAC: Allowing in development despite denial:', result.reason);
552
+ return NextResponse.next();
553
+ }
554
+
555
+ return NextResponse.redirect(new URL(result.redirect || '/unauthorized', request.url));
556
+ }
557
+
558
+ if (result.requires_2fa && !sessionStatus.twoFactorComplete) {
559
+ return NextResponse.redirect(
560
+ new URL(`${VERIFY_CODE_PAGE}?callbackUrl=${encodeURIComponent(pathname)}`, request.url)
561
+ );
562
+ }
563
+ } catch (error) {
564
+ console.error('[MIDDLEWARE] RBAC error:', error);
565
+
566
+ // In development, fail open
567
+ if (process.env.NODE_ENV !== 'production') {
568
+ console.warn('[MIDDLEWARE] RBAC: Allowing in development despite error');
569
+ return NextResponse.next();
570
+ }
571
+
572
+ return NextResponse.redirect(new URL('/error?code=rbac_error', request.url));
573
+ }
574
+ }
575
+
576
+ return NextResponse.next();
577
+ }
578
+
579
+ /** Handle token refresh */
580
+ async function handleRefresh(
581
+ request: NextRequest,
582
+ safeCallback: string,
583
+ opts: ExecuteOptions
584
+ ): Promise<NextResponse> {
585
+ const { circuitBreaker: cb, logger: log, refreshEndpoint, onRefreshSuccess, onRefreshFailure } = opts;
586
+
587
+ // Check if circuit breaker allows refresh attempt
588
+ if (!cb.canAttemptRefresh()) {
589
+ log.warn('Circuit breaker preventing refresh attempt');
590
+ return redirectTo(
591
+ request,
592
+ `${LOGIN_PAGE}?callbackUrl=${encodeURIComponent(safeCallback)}&error=ServiceUnavailable`,
593
+ true
594
+ );
595
+ }
596
+
597
+ try {
598
+ const baseUrl = getInternalApiUrl(request);
599
+ const response = await fetch(new URL(refreshEndpoint, baseUrl), {
600
+ method: 'POST',
601
+ headers: {
602
+ 'Accept': 'application/json',
603
+ 'Content-Type': 'application/json',
604
+ 'Cookie': request.headers.get('cookie') || '',
605
+ 'x-session-token': request.cookies.get(getSessionCookieName())?.value ||
606
+ request.cookies.get(getSecureSessionCookieName())?.value || ''
607
+ },
608
+ credentials: 'include',
609
+ signal: AbortSignal.timeout(5000),
610
+ });
611
+
612
+ if (response.ok) {
613
+ const data = await response.json();
614
+ if (data.refreshed || data.reason === 'already_fresh') {
615
+ cb.recordSuccess();
616
+ onRefreshSuccess?.();
617
+ log.info('Token refresh successful');
618
+ return NextResponse.next();
619
+ }
620
+ }
621
+
622
+ // Refresh failed - check for permanent failures (401/403) vs transient (5xx)
623
+ // CRITICAL: Always clear cookies on 401/403 to prevent redirect loops
624
+ // CRITICAL: Only record circuit breaker failures for network errors, not HTTP errors
625
+ // HTTP 500 means the server responded - it's reachable. Only network failures should trip the breaker.
626
+ const isPermanentFailure = response.status === 401 || response.status === 403;
627
+ const errorParam = isPermanentFailure ? 'SessionExpired' : 'RefreshError';
628
+
629
+ log.warn('Refresh failed', {
630
+ status: response.status,
631
+ isPermanentFailure,
632
+ clearingCookies: isPermanentFailure
633
+ });
634
+
635
+ onRefreshFailure?.(response.status, false);
636
+
637
+ return redirectTo(
638
+ request,
639
+ `${LOGIN_PAGE}?callbackUrl=${encodeURIComponent(safeCallback)}&error=${errorParam}`,
640
+ isPermanentFailure
641
+ );
642
+ } catch (error: any) {
643
+ const isNetwork = cb.isNetworkError(error);
644
+ log.error('Refresh error', {
645
+ error: error instanceof Error ? error.message : String(error),
646
+ isNetworkError: isNetwork
647
+ });
648
+
649
+ // Only record circuit breaker failure for actual network errors
650
+ if (isNetwork) {
651
+ cb.recordFailure(error);
652
+ }
653
+
654
+ onRefreshFailure?.(0, isNetwork);
655
+
656
+ // Network error - don't clear cookies, might be transient
657
+ return redirectTo(
658
+ request,
659
+ `${LOGIN_PAGE}?callbackUrl=${encodeURIComponent(safeCallback)}&error=RefreshError`,
660
+ false
661
+ );
662
+ }
663
+ }