Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

♻️ refactor(trpc): resolve ctx.clientIp through an overridable module (#20213)

YuTengjingfd6687635ce7
diff --git a/packages/trpc/src/lambda/context.test.ts b/packages/trpc/src/lambda/context.test.ts
index add6a846c75..7be83e577fb 100644
--- a/packages/trpc/src/lambda/context.test.ts
+++ b/packages/trpc/src/lambda/context.test.ts
@@ -81,6 +81,15 @@ vi.mock('@/utils/apiKey', async (importOriginal) => {
const mockCanUseWorkspaceApiKeys = vi.hoisted(() => vi.fn(async () => true));
+const mockGetRequestClientIP = vi.hoisted(() => vi.fn());
+vi.mock('@/utils/requestClientIP', async (importOriginal) => {
+ const actual = (await importOriginal()) as {
+ getRequestClientIP: (headers: Headers) => string | undefined;
+ };
+ mockGetRequestClientIP.mockImplementation(actual.getRequestClientIP);
+ return { getRequestClientIP: mockGetRequestClientIP };
+});
+
vi.mock('@/business/server/workspaceApiKey', () => ({
canUseWorkspaceApiKeys: mockCanUseWorkspaceApiKeys,
}));
@@ -233,6 +242,17 @@ describe('createLambdaContext', () => {
});
});
+ it('should resolve clientIp through the overridable request IP module', async () => {
+ const request = new NextRequest('https://example.com/trpc/lambda', {
+ headers: { 'x-forwarded-for': '198.51.100.3, 10.0.0.1' },
+ });
+
+ const context = await createLambdaContext(request);
+
+ expect(mockGetRequestClientIP).toHaveBeenCalledWith(request.headers);
+ expect(context.clientIp).toBe('198.51.100.3');
+ });
+
it('should authenticate with API key and skip session fallback', async () => {
const apiKeyRecord = {
accessedAt: new Date(),
diff --git a/packages/trpc/src/lambda/context.ts b/packages/trpc/src/lambda/context.ts
index 0cdd74cea8f..f4f95b6633c 100644
--- a/packages/trpc/src/lambda/context.ts
+++ b/packages/trpc/src/lambda/context.ts
@@ -16,6 +16,7 @@ import { extractTraceContext } from '@/libs/observability/traceparent';
import { assertOIDCUserActive, isOIDCUserInactiveError } from '@/libs/oidc-provider/access-control';
import { validateOIDCJWT } from '@/libs/oidc-provider/jwt';
import { isApiKeyExpired, validateApiKeyFormat } from '@/utils/apiKey';
+import { getRequestClientIP } from '@/utils/requestClientIP';
import { describeOIDCAuthFailure, setAuthFailureHeader } from '../utils/authFailure';
import { HETERO_OPERATION_JWT_PURPOSE } from '../utils/internalJwt';
@@ -24,19 +25,6 @@ import { HETERO_OPERATION_JWT_PURPOSE } from '../utils/internalJwt';
const log = debug('lobe-trpc:lambda:context');
const LOBE_CHAT_API_KEY_HEADER = 'X-API-Key';
-const extractClientIp = (request: NextRequest): string | undefined => {
- const forwardedFor = request.headers.get('x-forwarded-for');
- if (forwardedFor) {
- const ip = forwardedFor.split(',')[0]?.trim();
- if (ip) return ip;
- }
-
- const realIp = request.headers.get('x-real-ip')?.trim();
- if (realIp) return realIp;
-
- return undefined;
-};
-
interface ValidatedApiKey {
scopes: string[] | null;
userId: string;
@@ -197,7 +185,7 @@ export const createLambdaContext = async (request: NextRequest): Promise<LambdaC
// for API-response caching see https://trpc.io/docs/v11/caching
const userAgent = request.headers.get('user-agent') || undefined;
- const clientIp = extractClientIp(request);
+ const clientIp = getRequestClientIP(request.headers);
// get marketAccessToken from cookies
const cookieHeader = request.headers.get('cookie');
diff --git a/packages/utils/src/requestClientIP.test.ts b/packages/utils/src/requestClientIP.test.ts
new file mode 100644
index 00000000000..2e00e67736d
--- /dev/null
+++ b/packages/utils/src/requestClientIP.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it } from 'vitest';
+
+import { getRequestClientIP } from './requestClientIP';
+
+describe('getRequestClientIP', () => {
+ it('should take the first x-forwarded-for entry before x-real-ip', () => {
+ const headers = new Headers({
+ 'x-forwarded-for': '198.51.100.3, 10.0.0.1',
+ 'x-real-ip': '198.51.100.2',
+ });
+
+ expect(getRequestClientIP(headers)).toBe('198.51.100.3');
+ });
+
+ it('should fall back to x-real-ip', () => {
+ expect(getRequestClientIP(new Headers({ 'x-real-ip': ' 198.51.100.2 ' }))).toBe('198.51.100.2');
+ });
+
+ it('should ignore client-suppliable cf-connecting-ip', () => {
+ expect(getRequestClientIP(new Headers({ 'cf-connecting-ip': '203.0.113.7' }))).toBeUndefined();
+ expect(
+ getRequestClientIP(
+ new Headers({ 'cf-connecting-ip': '203.0.113.7', 'x-real-ip': '198.51.100.2' }),
+ ),
+ ).toBe('198.51.100.2');
+ });
+
+ it('should return undefined without proxy headers', () => {
+ expect(getRequestClientIP(new Headers())).toBeUndefined();
+ });
+});
diff --git a/packages/utils/src/requestClientIP.ts b/packages/utils/src/requestClientIP.ts
new file mode 100644
index 00000000000..ee8cb3594ff
--- /dev/null
+++ b/packages/utils/src/requestClientIP.ts
@@ -0,0 +1,16 @@
+/**
+ * Visitor IP recorded on request-scoped server state such as tRPC `ctx.clientIp`.
+ *
+ * Reads only the headers a reverse proxy sets or overwrites (`x-forwarded-for`, then
+ * `x-real-ip`), never client-suppliable ones like `cf-connecting-ip`: behind Nginx or any
+ * non-Cloudflare proxy a caller could otherwise pick the IP that lands in audit records.
+ *
+ * Callers import it as `@/utils/requestClientIP` so a deployment behind a gateway it can
+ * verify may override this one module instead of patching every caller.
+ */
+export const getRequestClientIP = (headers: Headers): string | undefined => {
+ const forwardedFor = headers.get('x-forwarded-for')?.split(',')[0]?.trim();
+ if (forwardedFor) return forwardedFor;
+
+ return headers.get('x-real-ip')?.trim() || undefined;
+};