-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmiddleware.ts
More file actions
72 lines (57 loc) · 1.75 KB
/
middleware.ts
File metadata and controls
72 lines (57 loc) · 1.75 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
import { NextRequest, NextResponse } from "next/server";
const getEnvAllowedOrigins = (): Set<string> => {
const allowed = new Set<string>();
if (process.env.NEXT_PUBLIC_APP_URL) {
allowed.add(process.env.NEXT_PUBLIC_APP_URL);
}
if (process.env.VERCEL_URL) {
allowed.add(`https://${process.env.VERCEL_URL}`);
}
return allowed;
};
const ALLOWED_FROM_ENV = getEnvAllowedOrigins();
const isAllowedReferer = (referer: string | null, allowedOrigins: Set<string>) => {
if (!referer) return false;
try {
const refererUrl = new URL(referer);
return allowedOrigins.has(`${refererUrl.protocol}//${refererUrl.host}`);
} catch {
return false;
}
};
export function middleware(req: NextRequest) {
if (!req.nextUrl.pathname.startsWith("/api/")) {
return NextResponse.next();
}
if (req.method === "OPTIONS") {
return new NextResponse(null, { status: 204 });
}
const allowedOrigins = new Set(ALLOWED_FROM_ENV);
allowedOrigins.add(req.nextUrl.origin);
const incomingOrigin = req.headers.get("origin");
const isAllowedOrigin =
incomingOrigin !== null && allowedOrigins.has(incomingOrigin);
const isRefererAllowed = isAllowedReferer(
req.headers.get("referer"),
allowedOrigins,
);
if (!isAllowedOrigin && !isRefererAllowed) {
return NextResponse.json(
{ error: "Forbidden - invalid Origin/Referer" },
{ status: 403 },
);
}
if (req.method === "POST") {
const contentType = (req.headers.get("content-type") || "").toLowerCase();
if (!contentType.startsWith("application/json")) {
return NextResponse.json(
{ error: "Unsupported Media Type" },
{ status: 415 },
);
}
}
return NextResponse.next();
}
export const config = {
matcher: ["/api/:path*"],
};