Skip to content

The Open Source DocuSign Alternative.

fix: get real ip for rate limit key

Lucas Smith20c8969272dc
diff --git a/apps/remix/server/router.ts b/apps/remix/server/router.ts
index 3e0e3f411..e64f7d292 100644
--- a/apps/remix/server/router.ts
+++ b/apps/remix/server/router.ts
@@ -9,6 +9,7 @@ import { tsRestHonoApp } from '@documenso/api/hono';
import { auth } from '@documenso/auth/server';
import { API_V2_BETA_URL } from '@documenso/lib/constants/app';
import { jobsClient } from '@documenso/lib/jobs/client';
+import { getIpAddress } from '@documenso/lib/universal/get-ip-address';
import { logger } from '@documenso/lib/utils/logger';
import { openApiDocument } from '@documenso/trpc/server/open-api';
@@ -35,7 +36,11 @@ const rateLimitMiddleware = rateLimiter({
windowMs: 60 * 1000, // 1 minute
limit: 100, // 100 requests per window
keyGenerator: (c) => {
- return c.req.header('x-forwarded-for') || c.req.header('x-real-ip') || 'unknown';
+ try {
+ return getIpAddress(c.req.raw);
+ } catch (error) {
+ return 'unknown';
+ }
},
message: {
error: 'Too many requests, please try again later.',
diff --git a/packages/lib/universal/get-ip-address.ts b/packages/lib/universal/get-ip-address.ts
new file mode 100644
index 000000000..8b838852b
--- /dev/null
+++ b/packages/lib/universal/get-ip-address.ts
@@ -0,0 +1,39 @@
+export const getIpAddress = (req: Request) => {
+ // Check for forwarded headers first (common in proxy setups)
+ const forwarded = req.headers.get('x-forwarded-for');
+
+ if (forwarded) {
+ // x-forwarded-for can contain multiple IPs, take the first one
+ return forwarded.split(',')[0].trim();
+ }
+
+ // Check for real IP header (used by some proxies)
+ const realIp = req.headers.get('x-real-ip');
+
+ if (realIp) {
+ return realIp;
+ }
+
+ // Check for client IP header
+ const clientIp = req.headers.get('x-client-ip');
+
+ if (clientIp) {
+ return clientIp;
+ }
+
+ // Check for CF-Connecting-IP (Cloudflare)
+ const cfConnectingIp = req.headers.get('cf-connecting-ip');
+
+ if (cfConnectingIp) {
+ return cfConnectingIp;
+ }
+
+ // Check for True-Client-IP (Akamai and Cloudflare)
+ const trueClientIp = req.headers.get('true-client-ip');
+
+ if (trueClientIp) {
+ return trueClientIp;
+ }
+
+ throw new Error('No IP address found');
+};