diff options
| author | Adam Soltys <[email protected]> | 2026-01-27 10:42:54 -0800 |
|---|---|---|
| committer | Adam Soltys <[email protected]> | 2026-01-27 10:42:54 -0800 |
| commit | 4a752a834b349b4aa8841cc5b3cab09854a5dca3 (patch) | |
| tree | b827d45108b1eba36acf79485c62450549fddd4c | |
| parent | c28b2c4d44f2aeff4e84f2627d76d1138b473bd3 (diff) | |
| download | coinos-ui-4a752a834b349b4aa8841cc5b3cab09854a5dca3.tar.gz coinos-ui-4a752a834b349b4aa8841cc5b3cab09854a5dca3.zip | |
forward ip to backend
| -rw-r--r-- | src/hooks.server.ts | 11 | ||||
| -rw-r--r-- | src/lib/server/ip.ts | 2 | ||||
| -rw-r--r-- | src/lib/utils.ts | 17 |
3 files changed, 28 insertions, 2 deletions
diff --git a/src/hooks.server.ts b/src/hooks.server.ts new file mode 100644 index 00000000..3dd9913a --- /dev/null +++ b/src/hooks.server.ts @@ -0,0 +1,11 @@ +import { ipStore } from "$lib/server/ip"; +import type { Handle } from "@sveltejs/kit"; + +export const handle: Handle = async ({ event, resolve }) => { + const ip = + event.request.headers.get("cf-connecting-ip") || + event.request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() || + event.getClientAddress(); + + return ipStore.run(ip, () => resolve(event)); +}; diff --git a/src/lib/server/ip.ts b/src/lib/server/ip.ts new file mode 100644 index 00000000..cfd933ac --- /dev/null +++ b/src/lib/server/ip.ts @@ -0,0 +1,2 @@ +import { AsyncLocalStorage } from "node:async_hooks"; +export const ipStore = new AsyncLocalStorage<string>(); diff --git a/src/lib/utils.ts b/src/lib/utils.ts index f220ed45..1b2bdfba 100644 --- a/src/lib/utils.ts +++ b/src/lib/utils.ts @@ -21,11 +21,23 @@ export function scroll(section: any) { const base = browser ? "" : PUBLIC_COINOS_URL; +let ipStore: any; +if (!browser) { + import("$lib/server/ip").then((m) => { + ipStore = m.ipStore; + }); +} + +const ipHeaders = (): Record<string, string> => { + const ip = ipStore?.getStore(); + return ip ? { "cf-connecting-ip": ip } : {}; +}; + export const punk = (k: string) => `${Math.floor((parseInt(k.slice(-2), 16) / 256) * 64) + 1}.webp`; export const g = (url: string, fetch: any, headers: object) => - fetch(base + url, { headers }) + fetch(base + url, { headers: { ...ipHeaders(), ...headers } }) .then((r: Response) => r.text()) .then((body: string) => { try { @@ -36,7 +48,7 @@ export const g = (url: string, fetch: any, headers: object) => }); export const get = (url: string, headers = {}) => { - return fetch(base + url, { headers }) + return fetch(base + url, { headers: { ...ipHeaders(), ...headers } }) .then(async (r) => { if (r.ok) return r.text(); throw new Error(await r.text()); @@ -58,6 +70,7 @@ export const post = async ( headers = { "content-type": "application/json", accept: "application/json", + ...ipHeaders(), ...headers, }; |
