|
| 1 | +import type { NextRequest } from 'next/server' |
| 2 | +import { NextResponse } from 'next/server' |
| 3 | + |
| 4 | +/** Kapa widget backend; browser/iframe may send this Origin when requesting docs assets. */ |
| 5 | +const KAPA_WIDGET_PROXY = 'https://kapa-widget-proxy-la7dkmplpq-uc.a.run.app' |
| 6 | + |
| 7 | +function corsAllowedOrigin(origin: string | null): string | null { |
| 8 | + if (!origin) { |
| 9 | + return null |
| 10 | + } |
| 11 | + if (origin === KAPA_WIDGET_PROXY) { |
| 12 | + return origin |
| 13 | + } |
| 14 | + if (origin === 'https://docs.plural.sh') { |
| 15 | + return origin |
| 16 | + } |
| 17 | + if (/^https:\/\/docs-pr-\d+\.plural\.sh$/.test(origin)) { |
| 18 | + return origin |
| 19 | + } |
| 20 | + if (origin.startsWith('http://localhost:')) { |
| 21 | + return origin |
| 22 | + } |
| 23 | + |
| 24 | + return null |
| 25 | +} |
| 26 | + |
| 27 | +export function middleware(request: NextRequest) { |
| 28 | + const origin = request.headers.get('origin') |
| 29 | + const allowOrigin = corsAllowedOrigin(origin) |
| 30 | + |
| 31 | + if (request.method === 'OPTIONS' && allowOrigin) { |
| 32 | + return new NextResponse(null, { |
| 33 | + status: 204, |
| 34 | + headers: { |
| 35 | + 'Access-Control-Allow-Origin': allowOrigin, |
| 36 | + 'Access-Control-Allow-Methods': 'GET, HEAD, POST, OPTIONS', |
| 37 | + 'Access-Control-Allow-Headers': |
| 38 | + request.headers.get('access-control-request-headers') || '*', |
| 39 | + 'Access-Control-Max-Age': '86400', |
| 40 | + Vary: 'Origin', |
| 41 | + }, |
| 42 | + }) |
| 43 | + } |
| 44 | + |
| 45 | + const res = NextResponse.next() |
| 46 | + |
| 47 | + if (allowOrigin) { |
| 48 | + res.headers.set('Access-Control-Allow-Origin', allowOrigin) |
| 49 | + res.headers.set('Vary', 'Origin') |
| 50 | + } |
| 51 | + |
| 52 | + return res |
| 53 | +} |
| 54 | + |
| 55 | +export const config = { |
| 56 | + matcher: ['/((?!_next/static|_next/image).*)'], |
| 57 | +} |
0 commit comments