21 lines
880 B
TypeScript
21 lines
880 B
TypeScript
/** Use the actual Host header; Next may normalize request.url to localhost. */
|
|||
|
|
export function isSameOriginRequest(request: Request): boolean {
|
||
|
|
if (request.headers.get("sec-fetch-site") === "cross-site") return false;
|
||
|
|
const origin = request.headers.get("origin");
|
||
|
|
// Non-browser clients do not necessarily send an Origin header.
|
||
|
|
if (!origin) return true;
|
||
|
|
try {
|
||
|
|
const requestUrl = new URL(request.url);
|
||
|
|
const host = request.headers.get("host") ?? requestUrl.host;
|
||
|
|
if (!host || /[\s/\\?#@]/.test(host)) return false;
|
||
|
|
const expected = new URL(`${requestUrl.protocol}//${host}`);
|
||
|
|
const actual = new URL(origin);
|
||
|
|
if (actual.username || actual.password || actual.pathname !== "/" || actual.search || actual.hash) {
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
return actual.origin !== "null" && actual.origin === expected.origin;
|
||
|
|
} catch {
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
}
|