-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
97 lines (83 loc) · 2.64 KB
/
proxy.ts
File metadata and controls
97 lines (83 loc) · 2.64 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
import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
// Routes that require authentication
const PROTECTED_ROUTES = [
{ path: "/api/connect", methods: ["POST"] },
{ path: "/api/disconnect", methods: ["POST"] },
{ path: "/api/tools/call", methods: ["POST"] },
{ path: "/api/registry", methods: ["POST"] },
];
function isAuthRoute(pathname: string): boolean {
return pathname.startsWith("/api/auth/");
}
function isProtectedRoute(pathname: string, method: string): boolean {
return PROTECTED_ROUTES.some(
(route) => pathname === route.path && route.methods.includes(method)
);
}
function addCorsHeaders(
response: NextResponse,
origin: string,
allowedOrigins: string[]
): NextResponse {
const headers: Record<string, string> = {
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
"Access-Control-Max-Age": "86400",
};
if (allowedOrigins.length === 0 || allowedOrigins.includes(origin)) {
headers["Access-Control-Allow-Origin"] = origin || "*";
}
for (const [key, value] of Object.entries(headers)) {
response.headers.set(key, value);
}
return response;
}
function getAllowedOrigins(): string[] {
if (process.env.NEXT_PUBLIC_APP_URL) {
return [process.env.NEXT_PUBLIC_APP_URL];
}
if (process.env.NODE_ENV === "development") {
return [
"http://localhost:3000",
"http://localhost:3001",
"http://127.0.0.1:3000",
];
}
return [];
}
export default auth(function middleware(request) {
const { pathname } = request.nextUrl;
const origin = request.headers.get("origin") ?? "";
const allowedOrigins = getAllowedOrigins();
// Only handle API routes
if (!pathname.startsWith("/api/")) {
return NextResponse.next();
}
// CORS preflight
if (request.method === "OPTIONS") {
const response = new NextResponse(null, { status: 204 });
return addCorsHeaders(response, origin, allowedOrigins);
}
// Skip auth routes — NextAuth handles them
if (isAuthRoute(pathname)) {
const response = NextResponse.next();
return addCorsHeaders(response, origin, allowedOrigins);
}
// Protected route check
if (isProtectedRoute(pathname, request.method)) {
if (!request.auth?.user) {
const response = NextResponse.json(
{ error: "Authentication required" },
{ status: 401 }
);
return addCorsHeaders(response, origin, allowedOrigins);
}
}
// Default: pass through with CORS
const response = NextResponse.next();
return addCorsHeaders(response, origin, allowedOrigins);
});
export const config = {
matcher: "/api/:path*",
};