-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathproxy.ts
More file actions
64 lines (49 loc) · 1.84 KB
/
proxy.ts
File metadata and controls
64 lines (49 loc) · 1.84 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
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { Settings } from '@/lib/config/settings';
const ALLOWED_ORIGINS = [
'http://localhost:3000',
'http://localhost:8080',
process.env.NEXT_PUBLIC_SITE_URL,
];
const EXCLUDED_PATHS = ['/api/docs', '/api/openapi.json', '/api/screenshot', '/api/github/stars', '/api/auth', '/_next', '/favicon.ico'];
export function proxy(request: NextRequest) {
const { pathname } = request.nextUrl;
if (EXCLUDED_PATHS.some(path => pathname.startsWith(path))) {
return NextResponse.next();
}
if (pathname.startsWith('/api/')) {
const origin = request.headers.get('origin') || '';
const apiKey = request.headers.get('x-api-key');
if (!Settings.DEBUG && !apiKey) {
return NextResponse.json(
{ detail: 'API Key header is missing' },
{ status: 401 }
);
}
if (!Settings.DEBUG && apiKey && !Settings.API_KEYS.includes(apiKey)) {
return NextResponse.json(
{ detail: 'Invalid API Key' },
{ status: 403 }
);
}
const response = NextResponse.next();
if (ALLOWED_ORIGINS.includes(origin)) {
response.headers.set('Access-Control-Allow-Origin', origin);
} else if (Settings.DEBUG) {
response.headers.set('Access-Control-Allow-Origin', '*');
}
response.headers.set('Access-Control-Allow-Credentials', 'true');
response.headers.set('Access-Control-Allow-Methods', 'GET, OPTIONS');
response.headers.set('Access-Control-Allow-Headers', 'Authorization, Content-Type, X-API-Key');
response.headers.set('Access-Control-Max-Age', '600');
if (request.method === 'OPTIONS') {
return new NextResponse(null, { status: 200, headers: response.headers });
}
return response;
}
return NextResponse.next();
}
export const config = {
matcher: ['/api/:path*'],
};