aboutsummaryrefslogtreecommitdiff
path: root/src/lib/Utility/appOrigin.ts
blob: cdc539958e9655798ac79c2e54c57f0341ded436 (plain) (blame)
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
import { browser, dev } from "$app/environment";
import { env } from "$env/dynamic/public";

const LOCAL_ORIGIN = "http://localhost:5173";
const PRODUCTION_ORIGIN = "https://due.moe";

const normaliseOrigin = (origin: string) =>
	origin.endsWith("/") ? origin.slice(0, -1) : origin;

const isPrivateHostname = (hostname: string) =>
	hostname === "localhost" ||
	hostname === "127.0.0.1" ||
	hostname.endsWith(".local") ||
	/^10\./.test(hostname) ||
	/^192\.168\./.test(hostname) ||
	/^172\.(1[6-9]|2\d|3[0-1])\./.test(hostname);

export const appOrigin = () => {
	if (browser) return window.location.origin;

	if (env.PUBLIC_APP_ORIGIN) return normaliseOrigin(env.PUBLIC_APP_ORIGIN);

	return dev ? LOCAL_ORIGIN : PRODUCTION_ORIGIN;
};

export const siteUrl = (path = "/") =>
	`${appOrigin()}${path.startsWith("/") ? path : `/${path}`}`;

export const isLocalApp = () => {
	const { hostname } = new URL(appOrigin());

	return dev || isPrivateHostname(hostname);
};

export const appOriginHeaders = (
	headers: Record<string, string> = {},
): Record<string, string> => ({
	...headers,
	"Access-Control-Allow-Origin": appOrigin(),
});

export { LOCAL_ORIGIN, PRODUCTION_ORIGIN };