forked from iflabx/agentifui
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
256 lines (226 loc) Β· 8.62 KB
/
middleware.ts
File metadata and controls
256 lines (226 loc) Β· 8.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
import {
createCorsHeaders,
handleCorsPreflightRequest,
} from '@lib/config/cors-config';
import {
AUTH_SYSTEM_ERRORS,
getAccountStatusError,
} from '@lib/constants/auth-errors';
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { CookieOptions, createServerClient } from '@supabase/ssr';
// This middleware intercepts all requests.
// Uses Supabase authentication logic for route protection.
export async function middleware(request: NextRequest) {
const url = new URL(request.url);
const pathname = url.pathname;
// 1. Prioritize CORS preflight requests
if (request.method === 'OPTIONS') {
console.log(`[Middleware] CORS preflight request: ${pathname}`);
return handleCorsPreflightRequest(request);
}
const response = NextResponse.next({
request: {
headers: request.headers,
},
});
// 2. Automatically add CORS headers to all API routes
// This ensures that all APIs receive uniform CORS protection, without manual addition
if (pathname.startsWith('/api/')) {
const origin = request.headers.get('origin');
const corsHeaders = createCorsHeaders(origin);
// Add CORS headers to the response
corsHeaders.forEach((value, key) => {
response.headers.set(key, value);
});
console.log(
`[Middleware] Add CORS headers to API route: ${pathname}${origin ? ` (Origin: ${origin})` : ' (No Origin header)'}`
);
}
// Highest priority: If the user directly accesses /chat, redirect to /chat/new
// This ensures that always starts from a clear new conversation state.
if (pathname === '/chat') {
const newChatUrl = new URL('/chat/new', request.url);
console.log(
`[Middleware] Exact /chat match. Redirecting to ${newChatUrl.toString()}`
);
return NextResponse.redirect(newChatUrl);
}
// Check if it is an SSO login success callback, if so, temporarily skip authentication check
// Allow the frontend to handle the SSO session establishment
const ssoLoginSuccess = url.searchParams.get('sso_login') === 'success';
const hasSsoUserCookie = request.cookies.get('sso_user_data');
const hasSsoSecureCookie = request.cookies.get('sso_user_data_secure');
// π Security: Only bypass authentication check for SSO processing paths
// This ensures that SSO users still go through normal status checks for protected routes
const isSsoProcessingPath =
pathname === '/sso/processing' ||
pathname.startsWith('/api/sso/') ||
pathname.startsWith('/api/auth/sso-signin');
if (
(ssoLoginSuccess || hasSsoUserCookie || hasSsoSecureCookie) &&
isSsoProcessingPath
) {
console.log(
`[Middleware] SSO processing path detected, allowing request to ${pathname}`
);
return response;
}
// Create Supabase client
const cookieStore = {
get: (name: string) => {
return request.cookies.get(name)?.value;
},
set: (name: string, value: string, options: CookieOptions) => {
// Setting cookies in the middleware requires through response
response.cookies.set(name, value, options);
},
remove: (name: string, options: CookieOptions) => {
// Deleting cookies in the middleware requires through response
response.cookies.set({
name,
value: '',
...options,
maxAge: 0,
});
},
};
const supabase = createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{
cookies: cookieStore,
}
);
// π Security fix: Use getUser() instead of getSession()
// getUser() will verify the authenticity of the JWT token with the Supabase Auth server
// Prevent privilege escalation attacks caused by tampering with local cookies
const {
data: { user },
error: authError,
} = await supabase.auth.getUser();
// Handle authentication errors
if (authError) {
console.log(`[Middleware] Auth verification failed: ${authError.message}`);
}
// Route protection logic based on user session status
// In sso mode, prohibit registration-related routes
const isAuthRoute = pathname.startsWith('/auth');
const isApiRoute = pathname.startsWith('/api');
const isAdminRoute = pathname.startsWith('/admin');
// Authentication-related page definitions (pages that should not be accessed by logged-in users)
const isAuthPage =
pathname === '/login' ||
pathname.startsWith('/register') ||
pathname === '/forgot-password' ||
pathname === '/reset-password' ||
pathname === '/phone-login';
const isPublicRoute =
pathname === '/' ||
pathname === '/about' ||
pathname.startsWith('/sso/processing') ||
(process.env.NEXT_PUBLIC_SSO_ONLY_MODE !== 'true' && isAuthPage) ||
(process.env.NEXT_PUBLIC_SSO_ONLY_MODE === 'true' && pathname === '/login');
// Enable route protection logic, ensuring that users who are not logged in cannot access protected routes
if (!user && !isAuthRoute && !isApiRoute && !isPublicRoute) {
console.log(
`[Middleware] User not authenticated, redirecting protected route ${pathname} to /login`
);
return NextResponse.redirect(new URL('/login', request.url));
}
// π Check user account status and admin permissions for authenticated users
// Query profile once to get both status and role for performance optimization
if (user) {
try {
const { data: profile, error } = await supabase
.from('profiles')
.select('role, status')
.eq('id', user.id) // π Use user.id that has been verified by the server
.single();
if (error) {
console.error(
`[SECURITY] Profile query failed for user ${user.id}:`,
error.message,
{ pathname, code: error.code }
);
await supabase.auth.signOut();
return NextResponse.redirect(
new URL(
`/login?error=${AUTH_SYSTEM_ERRORS.PROFILE_CHECK_FAILED}`,
request.url
)
);
}
// π Defense: Handle missing profile (should never happen but defensive)
if (!profile) {
console.error(
`[SECURITY] No profile found for authenticated user ${user.id}`
);
await supabase.auth.signOut();
return NextResponse.redirect(
new URL(
`/login?error=${AUTH_SYSTEM_ERRORS.PROFILE_NOT_FOUND}`,
request.url
)
);
}
// Now we have a valid profile, check status and permissions
{
// π Priority 1: Check account status using whitelist validation
// Only 'active' status users are allowed to access protected routes
// This prevents bypass via invalid status values (NULL, typos, unexpected enums)
if (profile.status !== 'active') {
const errorCode = getAccountStatusError(profile.status);
console.log(
`[Middleware] User with status '${profile.status}' attempting to access ${pathname}, signing out and redirecting to login`
);
await supabase.auth.signOut();
return NextResponse.redirect(
new URL(`/login?error=${errorCode}`, request.url)
);
}
// π Priority 2: Check admin route permissions
if (isAdminRoute && profile.role !== 'admin') {
console.log(
`[Middleware] Non-admin user attempting to access admin route ${pathname}, redirecting to /`
);
return NextResponse.redirect(new URL('/', request.url));
}
if (isAdminRoute) {
console.log(`[Middleware] Admin user accessing ${pathname}`);
}
}
} catch (error) {
console.error(
`[SECURITY] Unexpected error in account validation for user ${user.id}:`,
error instanceof Error ? error.message : 'Unknown error',
{ pathname }
);
await supabase.auth.signOut();
return NextResponse.redirect(
new URL(
`/login?error=${AUTH_SYSTEM_ERRORS.PERMISSION_CHECK_FAILED}`,
request.url
)
);
}
}
// When a logged-in user accesses the root directory or authentication page, redirect to the new chat page
if (user && (pathname === '/' || isAuthPage)) {
console.log(
`[Middleware] User logged in, redirecting ${pathname} to /chat/new`
);
return NextResponse.redirect(new URL('/chat/new', request.url));
}
return response;
}
// Configure the paths matched by the middleware
export const config = {
matcher: [
// Exclude static files and server-side APIs
'/((?!_next/static|_next/image|favicon.ico).*)',
'/chat', // Ensure /chat is intercepted to redirect
'/chat/:path*', // Intercept all paths under /chat
'/admin/:path*', // Intercept all paths under /admin
],
};