From adb09c36cf40ff117d24f5893ecf8d47f3d02e93 Mon Sep 17 00:00:00 2001 From: Ronal Sagala Date: Mon, 23 Nov 2026 05:27:32 +0700 Subject: [PATCH] fix(security): rate-limit and log the real visitor IP behind Cloudflare Production traffic is visitor -> Cloudflare -> Coolify proxy -> app, and with trust proxy = 1 req.ip is the Cloudflare edge address. Edges rotate per request and are shared by unrelated visitors, so every IP-keyed limiter (login, register, email, payment, referral) was effectively off: 12 demo logins in a row from one machine all passed on the live API. Add lib/clientIp.ts: use CF-Connecting-IP only when the sending hop is in Cloudflare's published ranges, otherwise the hop address. Both getRateLimitIp copies use it, and the referral, affiliate and payment routes stop trusting the first X-Forwarded-For entry, which the visitor controls. Co-Authored-By: Claude Opus 5.5 --- backend/src/core/middleware.ts | 3 +- backend/src/lib/clientIp.test.ts | 50 ++++++++++++++++++++++++++++++ backend/src/lib/clientIp.ts | 52 ++++++++++++++++++++++++++++++++ backend/src/lib/rateLimiters.ts | 3 +- backend/src/routes/affiliate.ts | 9 ++---- backend/src/routes/payment.ts | 9 ++---- backend/src/routes/referrals.ts | 9 ++---- 7 files changed, 112 insertions(+), 23 deletions(-) create mode 100644 backend/src/lib/clientIp.test.ts create mode 100644 backend/src/lib/clientIp.ts diff --git a/backend/src/core/middleware.ts b/backend/src/core/middleware.ts index cda35e6..a864817 100644 --- a/backend/src/core/middleware.ts +++ b/backend/src/core/middleware.ts @@ -5,6 +5,7 @@ import { createHash, randomBytes } from 'node:crypto'; import type { NextFunction, Request, RequestHandler, Response } from 'express'; import { env, adminEmails } from './env'; +import { getClientIp } from '../lib/clientIp'; import { pool } from './db'; import { ApiError, log, serializeError } from './errors'; import { writeAuditLog } from '../lib/auditLog'; @@ -239,7 +240,7 @@ function normalizeRateLimitPart(value: unknown) { } export function getRateLimitIp(req: Request) { - return req.ip || req.header('x-forwarded-for')?.split(',')[0]?.trim() || 'unknown'; + return getClientIp(req) ?? 'unknown'; } export function createRateLimiter(options: RateLimitOptions): RequestHandler { diff --git a/backend/src/lib/clientIp.test.ts b/backend/src/lib/clientIp.test.ts new file mode 100644 index 0000000..b1cd823 --- /dev/null +++ b/backend/src/lib/clientIp.test.ts @@ -0,0 +1,50 @@ +import type { Request } from 'express'; +import { getClientIp, isCloudflareIp } from './clientIp'; + +function request(ip: string | undefined, headers: Record = {}) { + const lower = Object.fromEntries(Object.entries(headers).map(([k, v]) => [k.toLowerCase(), v])); + return { + ip, + socket: { remoteAddress: ip }, + header: (name: string) => lower[name.toLowerCase()], + } as unknown as Request; +} + +describe('isCloudflareIp', () => { + it.each([ + ['162.158.189.100', true], + ['::ffff:172.68.10.5', true], + ['2606:4700:10::6816:1', true], + ['84.247.150.77', false], + ['10.0.1.11', false], + ['not-an-ip', false], + ])('%s → %s', (ip, expected) => { + expect(isCloudflareIp(ip)).toBe(expected); + }); +}); + +describe('getClientIp', () => { + it('uses CF-Connecting-IP when the request came through Cloudflare', () => { + expect(getClientIp(request('162.158.189.100', { 'CF-Connecting-IP': '36.71.140.22' }))).toBe('36.71.140.22'); + }); + + it('ignores CF-Connecting-IP from a hop that is not Cloudflare (no spoofing via the origin)', () => { + expect(getClientIp(request('84.247.150.77', { 'CF-Connecting-IP': '1.2.3.4' }))).toBe('84.247.150.77'); + }); + + it('ignores X-Forwarded-For entirely; the visitor controls its first entry', () => { + expect(getClientIp(request('162.158.189.100', { 'X-Forwarded-For': '1.2.3.4' }))).toBe('162.158.189.100'); + }); + + it('falls back to the hop when the Cloudflare header is missing or invalid', () => { + expect(getClientIp(request('162.158.189.100', { 'CF-Connecting-IP': 'garbage' }))).toBe('162.158.189.100'); + }); + + it('unwraps IPv4-mapped IPv6 addresses for local requests', () => { + expect(getClientIp(request('::ffff:127.0.0.1'))).toBe('127.0.0.1'); + }); + + it('returns null when nothing usable is known', () => { + expect(getClientIp(request(undefined))).toBeNull(); + }); +}); diff --git a/backend/src/lib/clientIp.ts b/backend/src/lib/clientIp.ts new file mode 100644 index 0000000..b9253ad --- /dev/null +++ b/backend/src/lib/clientIp.ts @@ -0,0 +1,52 @@ +import { BlockList, isIP } from 'node:net'; +import type { Request } from 'express'; + +// Production traffic reaches the app as visitor → Cloudflare → Coolify proxy → app. With +// `trust proxy` = 1, req.ip is the Cloudflare edge address, which rotates per request and is shared +// by unrelated visitors, so it is useless for rate limits and audit trails. Cloudflare puts the +// visitor's address in CF-Connecting-IP; trust that header only when the hop that sent it really is +// Cloudflare, otherwise anyone calling the origin directly could choose their own IP. +// +// Ranges from https://www.cloudflare.com/ips-v4 and https://www.cloudflare.com/ips-v6. +const CLOUDFLARE_IPV4 = [ + '173.245.48.0/20', '103.21.244.0/22', '103.22.200.0/22', '103.31.4.0/22', '141.101.64.0/18', + '108.162.192.0/18', '190.93.240.0/20', '188.114.96.0/20', '197.234.240.0/22', '198.41.128.0/17', + '162.158.0.0/15', '104.16.0.0/13', '104.24.0.0/14', '172.64.0.0/13', '131.0.72.0/22', +]; +const CLOUDFLARE_IPV6 = [ + '2400:cb00::/32', '2606:4700::/32', '2803:f800::/32', '2405:b500::/32', '2405:8100::/32', + '2a06:98c0::/29', '2c0f:f248::/32', +]; + +const cloudflare = new BlockList(); +for (const range of CLOUDFLARE_IPV4) { + const [address, prefix] = range.split('/'); + cloudflare.addSubnet(address, Number(prefix), 'ipv4'); +} +for (const range of CLOUDFLARE_IPV6) { + const [address, prefix] = range.split('/'); + cloudflare.addSubnet(address, Number(prefix), 'ipv6'); +} + +function normalizeIp(value: string | undefined | null) { + const trimmed = value?.trim() ?? ''; + // IPv4 clients on a dual-stack socket appear as ::ffff:1.2.3.4. + const unmapped = trimmed.startsWith('::ffff:') && isIP(trimmed.slice(7)) === 4 ? trimmed.slice(7) : trimmed; + return isIP(unmapped) ? unmapped : null; +} + +export function isCloudflareIp(value: string | undefined | null) { + const ip = normalizeIp(value); + if (!ip) return false; + return cloudflare.check(ip, isIP(ip) === 6 ? 'ipv6' : 'ipv4'); +} + +/** The visitor's IP address, or null when it cannot be determined. */ +export function getClientIp(req: Request): string | null { + const hop = normalizeIp(req.ip ?? req.socket?.remoteAddress); + if (hop && isCloudflareIp(hop)) { + const visitor = normalizeIp(req.header('cf-connecting-ip')); + if (visitor) return visitor; + } + return hop; +} diff --git a/backend/src/lib/rateLimiters.ts b/backend/src/lib/rateLimiters.ts index 74f5840..36bc9df 100644 --- a/backend/src/lib/rateLimiters.ts +++ b/backend/src/lib/rateLimiters.ts @@ -2,6 +2,7 @@ * Centralized rate limiter configurations for all endpoints. * Extracted from index.ts for better organization. */ +import { getClientIp } from './clientIp'; import type { Request, RequestHandler } from 'express'; import { env } from '../core/env'; @@ -26,7 +27,7 @@ function normalizeRateLimitPart(value: unknown) { } export function getRateLimitIp(req: Request) { - return req.ip || req.header('x-forwarded-for')?.split(',')[0]?.trim() || 'unknown'; + return getClientIp(req) ?? 'unknown'; } export function createRateLimiter(options: RateLimitOptions): RequestHandler { diff --git a/backend/src/routes/affiliate.ts b/backend/src/routes/affiliate.ts index afa9e4a..0300c81 100644 --- a/backend/src/routes/affiliate.ts +++ b/backend/src/routes/affiliate.ts @@ -1,4 +1,5 @@ import { Router } from 'express'; +import { getClientIp } from '../lib/clientIp'; import { z } from 'zod'; import { authenticate, @@ -43,12 +44,6 @@ const markPaidSchema = z.object({ payoutReference: z.string().trim().max(120).optional().nullable(), }); -function getRequestIp(req: Parameters[1]>[0]) { - const forwarded = req.headers['x-forwarded-for']; - if (typeof forwarded === 'string' && forwarded.trim()) return forwarded.split(',')[0]?.trim() ?? null; - return req.ip || req.socket.remoteAddress || null; -} - function readString(query: Record, key: string) { const value = query[key]; if (Array.isArray(value)) return typeof value[0] === 'string' && value[0].trim() ? value[0].trim() : undefined; @@ -84,7 +79,7 @@ router.post('/api/affiliate/apply', authenticate, async (req, res, next) => { payoutAccountHolder: payload.payoutAccountHolder, acceptedTerms: payload.acceptedTerms, termsVersion: payload.termsVersion, - ip: getRequestIp(req), + ip: getClientIp(req), })); res.status(201).json({ affiliate_profile: affiliateProfile }); } catch (error) { diff --git a/backend/src/routes/payment.ts b/backend/src/routes/payment.ts index 526f7d1..e157c2b 100644 --- a/backend/src/routes/payment.ts +++ b/backend/src/routes/payment.ts @@ -1,4 +1,5 @@ import { Router } from 'express'; +import { getClientIp } from '../lib/clientIp'; import { randomUUID } from 'node:crypto'; import { z } from 'zod'; import { @@ -57,12 +58,6 @@ function ensureSubscriptionPaymentSchema() { return subscriptionSchemaReady; } -function getRequestIp(req: Parameters[1]>[0]) { - const forwarded = req.headers['x-forwarded-for']; - if (typeof forwarded === 'string' && forwarded.trim()) return forwarded.split(',')[0].trim(); - return req.ip || req.socket.remoteAddress || null; -} - function createSubscriptionOrderId(providerName: string, userId: string, plan: string, billingCycle: string) { const prefix = providerName.toUpperCase(); const planCode = plan.replace(/[^a-z0-9]/gi, '').slice(0, 3).toUpperCase() || 'SUB'; @@ -71,7 +66,7 @@ function createSubscriptionOrderId(providerName: string, userId: string, plan: s } async function createTransaction(req: Parameters[1]>[0], res: Parameters[1]>[1], next: Parameters[1]>[2]) { - const ip = getRequestIp(req); + const ip = getClientIp(req); const userAgent = req.headers['user-agent'] ?? null; let payload: z.infer | null = null; diff --git a/backend/src/routes/referrals.ts b/backend/src/routes/referrals.ts index 935fb39..6b553f1 100644 --- a/backend/src/routes/referrals.ts +++ b/backend/src/routes/referrals.ts @@ -1,4 +1,5 @@ import { Router } from 'express'; +import { getClientIp } from '../lib/clientIp'; import { z } from 'zod'; import { authenticate, @@ -30,12 +31,6 @@ function firstQueryValue(value: unknown) { return typeof value === 'string' && value.trim() ? value.trim() : null; } -function getRequestIp(req: Parameters[1]>[0]) { - const forwarded = req.headers['x-forwarded-for']; - if (typeof forwarded === 'string' && forwarded.trim()) return forwarded.split(',')[0]?.trim() ?? null; - return req.ip || req.socket.remoteAddress || null; -} - router.get('/api/ref/:code', publicReferralRateLimiter, async (req, res, next) => { try { if (!isReferralEnabled()) { @@ -54,7 +49,7 @@ router.get('/api/ref/:code', publicReferralRateLimiter, async (req, res, next) = await trackingService.trackClick({ referralCodeId: referralCode.id as string, - ip: getRequestIp(req), + ip: getClientIp(req), userAgent: req.headers['user-agent'] ?? null, landingPage: firstQueryValue(req.query.landing_page) ?? firstQueryValue(req.query.landingPage), utmSource: firstQueryValue(req.query.utm_source),