Context7 Platform -- Up-to-date docs for AI agents
fix(mcp): skip loopback and IPv6 private IPs in getClientIp (#2875)
石岳峰41878ecd18c0
diff --git a/.changeset/loud-camels-visit.md b/.changeset/loud-camels-visit.mdnew file mode 100644index 00000000..0332b200--- /dev/null+++ b/.changeset/loud-camels-visit.md@@ -0,0 +1,5 @@+---+"@upstash/context7-mcp": patch+---++Skip loopback (`127.0.0.0/8`), link-local (`169.254.0.0/16`), CGNAT (`100.64.0.0/10`), IPv6 loopback (`::1`), IPv6 link-local (`fe80::/10`), and IPv6 unique-local (`fc00::/7`) addresses when extracting the client IP from `X-Forwarded-For`, so proxy-internal hops no longer pollute the reported client IP.diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.tsindex 6f56fa92..17098155 100644--- a/packages/mcp/src/index.ts+++ b/packages/mcp/src/index.ts@@ -27,6 +27,7 @@ import {OPENAI_APPS_CHALLENGE_TOKEN,} from "./lib/constants.js";import { maybeElicitAuthSignIn } from "./lib/auth/auth-prompt.js";+import { getClientIp } from "./lib/client-ip.js";/** Default HTTP server port */const DEFAULT_PORT = 3000;@@ -108,36 +109,6 @@ function getClientContext(): ClientContext {};}-/**- * Extract client IP address from request headers.- * Handles X-Forwarded-For header for proxied requests.- */-function getClientIp(req: express.Request): string | undefined {- const forwardedFor = req.headers["x-forwarded-for"] || req.headers["X-Forwarded-For"];-- if (forwardedFor) {- const ips = Array.isArray(forwardedFor) ? forwardedFor[0] : forwardedFor;- const ipList = ips.split(",").map((ip) => ip.trim());-- for (const ip of ipList) {- const plainIp = ip.replace(/^::ffff:/, "");- if (- !plainIp.startsWith("10.") &&- !plainIp.startsWith("192.168.") &&- !/^172\.(1[6-9]|2[0-9]|3[0-1])\./.test(plainIp)- ) {- return plainIp;- }- }- return ipList[0].replace(/^::ffff:/, "");- }-- if (req.socket?.remoteAddress) {- return req.socket.remoteAddress.replace(/^::ffff:/, "");- }- return undefined;-}-function createMcpServer() {const server = new McpServer({diff --git a/packages/mcp/src/lib/client-ip.ts b/packages/mcp/src/lib/client-ip.tsnew file mode 100644index 00000000..5c8ab2d4--- /dev/null+++ b/packages/mcp/src/lib/client-ip.ts@@ -0,0 +1,78 @@+import type express from "express";++function stripIpv4MappedPrefix(ip: string): string {+ return ip.replace(/^::ffff:/i, "");+}++/**+ * Returns true for RFC1918, CGNAT, loopback, link-local, and IPv6 private ranges.+ */+export function isPrivateOrLocalIp(ip: string): boolean {+ const plainIp = stripIpv4MappedPrefix(ip).toLowerCase();++ if (plainIp.includes(".")) {+ return (+ plainIp.startsWith("10.") ||+ plainIp.startsWith("192.168.") ||+ /^172\.(1[6-9]|2[0-9]|3[0-1])\./.test(plainIp) ||+ /^100\.(6[4-9]|[7-9][0-9]|1[01][0-9]|12[0-7])\./.test(plainIp) ||+ plainIp.startsWith("127.") ||+ plainIp.startsWith("169.254.")+ );+ }++ // ::1 loopback in any textual form (e.g. "0::1", "0:0:0:0:0:0:0:1")+ if (/^[0:]+1$/.test(plainIp)) {+ return true;+ }++ // First hextets in fe80::/10 and fc00::/7 start with a non-zero digit, so a+ // valid textual form always spells out all 4 digits.++ // fe80::/10 link-local+ if (/^fe[89ab][0-9a-f]:/.test(plainIp)) {+ return true;+ }++ // fc00::/7 unique local+ if (/^f[cd][0-9a-f]{2}:/.test(plainIp)) {+ return true;+ }++ return false;+}++function pickClientIpFromForwardedList(ipList: string[]): string | undefined {+ for (const ip of ipList) {+ const plainIp = stripIpv4MappedPrefix(ip);+ if (!isPrivateOrLocalIp(plainIp)) {+ return plainIp;+ }+ }++ if (ipList.length === 0) {+ return undefined;+ }++ return stripIpv4MappedPrefix(ipList[0]);+}++/**+ * Extract client IP address from request headers.+ * Handles X-Forwarded-For header for proxied requests.+ */+export function getClientIp(req: express.Request): string | undefined {+ const forwardedFor = req.headers["x-forwarded-for"] || req.headers["X-Forwarded-For"];++ if (forwardedFor) {+ const ips = Array.isArray(forwardedFor) ? forwardedFor[0] : forwardedFor;+ const ipList = ips.split(",").map((ip) => ip.trim());+ return pickClientIpFromForwardedList(ipList);+ }++ if (req.socket?.remoteAddress) {+ return stripIpv4MappedPrefix(req.socket.remoteAddress);+ }++ return undefined;+}diff --git a/packages/mcp/test/client-ip.test.ts b/packages/mcp/test/client-ip.test.tsnew file mode 100644index 00000000..6b415297--- /dev/null+++ b/packages/mcp/test/client-ip.test.ts@@ -0,0 +1,96 @@+import { describe, expect, test } from "vitest";+import type express from "express";+import { getClientIp, isPrivateOrLocalIp } from "../src/lib/client-ip.js";++describe("isPrivateOrLocalIp", () => {+ test.each([+ "10.0.0.1",+ "192.168.1.1",+ "172.16.0.1",+ "127.0.0.1",+ "169.254.1.1",+ "100.64.0.1",+ "100.127.255.255",+ "::1",+ "0::1",+ "0:0:0:0:0:0:0:1",+ "fe80::1",+ "FE80::1",+ "febf::1",+ "fc00::1",+ "fd12::1",+ "fdff::1",+ "::ffff:127.0.0.1",+ ])("treats %s as private or local", (ip) => {+ expect(isPrivateOrLocalIp(ip)).toBe(true);+ });++ test.each([+ "8.8.8.8",+ "203.0.113.10",+ "100.63.255.255",+ "100.128.0.1",+ "2001:db8::1",+ "1::1",+ "::11",+ "::ffff:8.8.8.8",+ // abbreviated first hextets that look like fe80::/10 or fc00::/7 but are not+ "fe8::1",+ "fc::1",+ "fd0::1",+ // fec0::/10 (deprecated site-local) is outside fe80::/10+ "fec0::1",+ ])("treats %s as public", (ip) => {+ expect(isPrivateOrLocalIp(ip)).toBe(false);+ });+});++describe("getClientIp", () => {+ function makeRequest(headers: Record<string, string | string[]>): express.Request {+ return {+ headers,+ socket: undefined,+ } as express.Request;+ }++ test("skips loopback and link-local entries in X-Forwarded-For", () => {+ const req = makeRequest({+ "x-forwarded-for": "127.0.0.1, 8.8.8.8",+ });++ expect(getClientIp(req)).toBe("8.8.8.8");+ });++ test("skips RFC1918 and returns the first public forwarded IP", () => {+ const req = makeRequest({+ "x-forwarded-for": "10.0.0.1, 192.168.0.2, 203.0.113.10",+ });++ expect(getClientIp(req)).toBe("203.0.113.10");+ });++ test("skips IPv6 loopback and private ranges in X-Forwarded-For", () => {+ const req = makeRequest({+ "x-forwarded-for": "::1, fe80::1, fc00::1, 2001:db8::5",+ });++ expect(getClientIp(req)).toBe("2001:db8::5");+ });++ test("falls back to the first forwarded IP when all entries are private", () => {+ const req = makeRequest({+ "x-forwarded-for": "127.0.0.1, 10.0.0.1",+ });++ expect(getClientIp(req)).toBe("127.0.0.1");+ });++ test("uses socket remote address when X-Forwarded-For is absent", () => {+ const req = {+ headers: {},+ socket: { remoteAddress: "::ffff:203.0.113.10" },+ } as express.Request;++ expect(getClientIp(req)).toBe("203.0.113.10");+ });+});