Skip to content

Open source CapCut alternative.

TypeScript

refactor(site): share client IP parsing

David Le122e42c26640
diff --git a/site/src/lib/client-ip.ts b/site/src/lib/client-ip.ts
new file mode 100644
index 00000000..247b7bb5
--- /dev/null
+++ b/site/src/lib/client-ip.ts
@@ -0,0 +1,11 @@
+import { isValidIP } from "@better-auth/core/utils/ip";
+
+// The header the host puts the caller's address in, first entry first. Vercel
+// sets it on every request, and better-auth reads the same one.
+const FORWARDED_FOR = "x-forwarded-for";
+
+/** The address a request came from, or null when it carries no valid one. */
+export function clientIp(headers: Headers): string | null {
+ const ip = headers.get(FORWARDED_FOR)?.split(",")[0]?.trim();
+ return ip && isValidIP(ip) ? ip : null;
+}
diff --git a/site/src/lib/onboarding/signup-network.ts b/site/src/lib/onboarding/signup-network.ts
index 57fc5604..0b90f3e0 100644
--- a/site/src/lib/onboarding/signup-network.ts
+++ b/site/src/lib/onboarding/signup-network.ts
@@ -1,13 +1,10 @@
import { createHmac } from "node:crypto";
-import { isValidIP, normalizeIP } from "@better-auth/core/utils/ip";
+import { normalizeIP } from "@better-auth/core/utils/ip";
+import { clientIp } from "@/lib/client-ip";
import { prisma } from "@/lib/prisma";
-// The header the host puts the caller's address in, first entry first. Vercel
-// sets it on every request, and better-auth reads the same one.
-const FORWARDED_FOR = "x-forwarded-for";
-
// The block of IPv6 addresses one household or device is handed. Cycling
// addresses inside it still counts as one network.
const IPV6_NETWORK_PREFIX = 64;
@@ -21,8 +18,8 @@ type NetworkLimit = { limit: number; windowDays: number };
* address. Null when the request carries no readable address.
*/
export function signupNetworkKey(headers: Headers): string | null {
- const ip = headers.get(FORWARDED_FOR)?.split(",")[0]?.trim();
- if (!ip || !isValidIP(ip)) {
+ const ip = clientIp(headers);
+ if (!ip) {
return null;
}