-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathproxy.ts
More file actions
86 lines (78 loc) · 2.7 KB
/
proxy.ts
File metadata and controls
86 lines (78 loc) · 2.7 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
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getSessionCookie } from "better-auth/cookies";
import {
matchRule,
extractKey,
rateLimitHeaders,
getBackend,
} from "@/lib/api/rate-limit";
const UUID_RE =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
/**
* Next.js proxy — session protection + rate limiting + validation.
* MCP/API auth is handled by JWT verification in route handlers.
* @param request - Incoming request.
* @returns Redirect, error response, or pass-through.
*/
export async function proxy(request: NextRequest) {
const { pathname } = request.nextUrl;
const session = getSessionCookie(request);
// Auth pages: redirect to home if already signed in
if (session && (pathname === "/sign-in" || pathname === "/sign-up")) {
return NextResponse.redirect(new URL("/", request.url));
}
// Protected app pages: redirect to sign-in if not authenticated.
// Only auth endpoints and MCP routes are public — all other API
// routes require a session cookie to prevent unauthenticated access.
const isPublicPath =
pathname === "/sign-in" ||
pathname === "/sign-up" ||
pathname === "/consent" ||
pathname.startsWith("/api/auth/") ||
pathname === "/api/mcp" ||
pathname.startsWith("/.well-known/");
if (!session && !isPublicPath) {
return NextResponse.redirect(new URL("/sign-in", request.url));
}
// Rate limiting — runs before auth so brute-force attempts are throttled
let rlHeaders: Record<string, string> | null = null;
if (!pathname.startsWith("/api/auth/")) {
const rule = matchRule(pathname);
if (rule) {
const key = await extractKey(request, rule.keyStrategy);
if (key) {
const result = await getBackend().check(
`${rule.pattern}:${key}`,
rule.max,
rule.window,
);
rlHeaders = rateLimitHeaders(result, rule);
if (!result.allowed) {
return NextResponse.json(
{ error: "Too many requests. Please try again later." },
{ status: 429, headers: rlHeaders },
);
}
}
}
}
// UUID validation for project routes
const match = pathname.match(/^\/api\/project\/([^/]+)/);
if (match && !UUID_RE.test(match[1])) {
return NextResponse.json(
{ error: "Invalid project ID" },
{ status: 400 },
);
}
const response = NextResponse.next();
if (rlHeaders) {
for (const [k, v] of Object.entries(rlHeaders)) {
response.headers.set(k, v);
}
}
return response;
}
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon\\.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp|ico|txt|xml|json|webmanifest)$).*)"],
};