Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion backend/src/core/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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 {
Expand Down
50 changes: 50 additions & 0 deletions backend/src/lib/clientIp.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import type { Request } from 'express';
import { getClientIp, isCloudflareIp } from './clientIp';

function request(ip: string | undefined, headers: Record<string, string> = {}) {
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();
});
});
52 changes: 52 additions & 0 deletions backend/src/lib/clientIp.ts
Original file line number Diff line number Diff line change
@@ -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;
}
3 changes: 2 additions & 1 deletion backend/src/lib/rateLimiters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand All @@ -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 {
Expand Down
9 changes: 2 additions & 7 deletions backend/src/routes/affiliate.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Router } from 'express';
import { getClientIp } from '../lib/clientIp';
import { z } from 'zod';
import {
authenticate,
Expand Down Expand Up @@ -43,12 +44,6 @@ const markPaidSchema = z.object({
payoutReference: z.string().trim().max(120).optional().nullable(),
});

function getRequestIp(req: Parameters<Parameters<typeof router.post>[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<string, unknown>, key: string) {
const value = query[key];
if (Array.isArray(value)) return typeof value[0] === 'string' && value[0].trim() ? value[0].trim() : undefined;
Expand Down Expand Up @@ -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) {
Expand Down
9 changes: 2 additions & 7 deletions backend/src/routes/payment.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Router } from 'express';
import { getClientIp } from '../lib/clientIp';
import { randomUUID } from 'node:crypto';
import { z } from 'zod';
import {
Expand Down Expand Up @@ -57,12 +58,6 @@ function ensureSubscriptionPaymentSchema() {
return subscriptionSchemaReady;
}

function getRequestIp(req: Parameters<Parameters<typeof router.post>[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';
Expand All @@ -71,7 +66,7 @@ function createSubscriptionOrderId(providerName: string, userId: string, plan: s
}

async function createTransaction(req: Parameters<Parameters<typeof router.post>[1]>[0], res: Parameters<Parameters<typeof router.post>[1]>[1], next: Parameters<Parameters<typeof router.post>[1]>[2]) {
const ip = getRequestIp(req);
const ip = getClientIp(req);
const userAgent = req.headers['user-agent'] ?? null;
let payload: z.infer<typeof paymentCreateSchema> | null = null;

Expand Down
9 changes: 2 additions & 7 deletions backend/src/routes/referrals.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Router } from 'express';
import { getClientIp } from '../lib/clientIp';
import { z } from 'zod';
import {
authenticate,
Expand Down Expand Up @@ -30,12 +31,6 @@ function firstQueryValue(value: unknown) {
return typeof value === 'string' && value.trim() ? value.trim() : null;
}

function getRequestIp(req: Parameters<Parameters<typeof router.get>[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()) {
Expand All @@ -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),
Expand Down
Loading