| | import { COOKIE_NAME, MESSAGES_BEFORE_LOGIN } from "$env/static/private"; |
| | import type { Handle } from "@sveltejs/kit"; |
| | import { |
| | PUBLIC_GOOGLE_ANALYTICS_ID, |
| | PUBLIC_DEPRECATED_GOOGLE_ANALYTICS_ID, |
| | PUBLIC_ORIGIN, |
| | PUBLIC_APP_DISCLAIMER, |
| | } from "$env/static/public"; |
| | import { collections } from "$lib/server/database"; |
| | import { base } from "$app/paths"; |
| | import { refreshSessionCookie, requiresUser } from "$lib/server/auth"; |
| | import { ERROR_MESSAGES } from "$lib/stores/errors"; |
| |
|
| | export const handle: Handle = async ({ event, resolve }) => { |
| | const token = event.cookies.get(COOKIE_NAME); |
| |
|
| | event.locals.sessionId = token || crypto.randomUUID(); |
| |
|
| | function errorResponse(status: number, message: string) { |
| | const sendJson = |
| | event.request.headers.get("accept")?.includes("application/json") || |
| | event.request.headers.get("content-type")?.includes("application/json"); |
| | return new Response(sendJson ? JSON.stringify({ error: message }) : message, { |
| | status, |
| | headers: { |
| | "content-type": sendJson ? "application/json" : "text/plain", |
| | }, |
| | }); |
| | } |
| |
|
| | |
| | const requestContentType = event.request.headers.get("content-type")?.split(";")[0] ?? ""; |
| | |
| | const nativeFormContentTypes = [ |
| | "multipart/form-data", |
| | "application/x-www-form-urlencoded", |
| | "text/plain", |
| | ]; |
| | if (event.request.method === "POST" && nativeFormContentTypes.includes(requestContentType)) { |
| | const referer = event.request.headers.get("referer"); |
| |
|
| | if (!referer) { |
| | return errorResponse(403, "Non-JSON form requests need to have a referer"); |
| | } |
| |
|
| | const validOrigins = [ |
| | new URL(event.request.url).origin, |
| | ...(PUBLIC_ORIGIN ? [new URL(PUBLIC_ORIGIN).origin] : []), |
| | ]; |
| |
|
| | if (!validOrigins.includes(new URL(referer).origin)) { |
| | return errorResponse(403, "Invalid referer for POST request"); |
| | } |
| | } |
| |
|
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| |
|
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| |
|
| | |
| | |
| | |
| | |
| | |
| |
|
| | refreshSessionCookie(event.cookies, event.locals.sessionId); |
| |
|
| | let replaced = false; |
| |
|
| | const response = await resolve(event, { |
| | transformPageChunk: (chunk) => { |
| | |
| | if (replaced || !chunk.html.includes("%gaId%") || !chunk.html.includes("%gaIdDeprecated%")) { |
| | return chunk.html; |
| | } |
| | replaced = true; |
| |
|
| | return chunk.html |
| | .replace("%gaId%", PUBLIC_GOOGLE_ANALYTICS_ID) |
| | .replace("%gaIdDeprecated%", PUBLIC_DEPRECATED_GOOGLE_ANALYTICS_ID); |
| | }, |
| | }); |
| |
|
| | return response; |
| | }; |
| |
|