Skip to content

Email for professionals and teams

Resolve client IP at the socket; never trust raw forwarded headers

ssthormessa0cdae49b368
diff --git a/server/index.ts b/server/index.ts
index a196bc3..45ed774 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -46,7 +46,26 @@ async function main() {
const handle = app.getRequestHandler();
await app.prepare();
+ // Set TRUST_PROXY=1 when a reverse proxy terminates in front of this
+ // process; the client IP it appended to x-forwarded-for is then trusted.
+ // Direct exposure must leave it unset so only the socket IP is trusted.
+ const trustProxy = ["1", "true", "yes"].includes((process.env.TRUST_PROXY ?? "").toLowerCase());
+
const server = createServer((request, response) => {
+ // The only client IP that cannot be forged is the socket's. Next sees
+ // re-serialized headers, so stamp the resolved IP into a private header
+ // after removing every client-supplied forwarding header — otherwise a
+ // direct attacker could rotate them to dodge the login rate limiter.
+ const forwarded = request.headers["x-forwarded-for"];
+ const hops = (Array.isArray(forwarded) ? forwarded.at(-1) : forwarded)
+ ?.split(",")
+ .map((hop) => hop.trim())
+ .filter(Boolean) ?? [];
+ const clientIp = (trustProxy ? hops.at(-1) : undefined) ?? request.socket.remoteAddress;
+ delete request.headers["cf-connecting-ip"];
+ delete request.headers["x-forwarded-for"];
+ delete request.headers["x-mailflare-client-ip"];
+ if (clientIp) request.headers["x-mailflare-client-ip"] = clientIp;
void handle(request, response, parse(request.url ?? "/", true));
});
diff --git a/src/lib/auth/activity.ts b/src/lib/auth/activity.ts
index 4abaff5..cb39a84 100644
--- a/src/lib/auth/activity.ts
+++ b/src/lib/auth/activity.ts
@@ -1,4 +1,5 @@
import { createAuditLog } from "@/lib/mailboxes/audit";
+import { getClientIp } from "./client-ip";
import type { AuthActivityAction, AuthActivityMetadata } from "./activity-types";
export async function recordAuthActivity(
@@ -34,10 +35,7 @@ export function getAuthActivityMetadata(request: Request): AuthActivityMetadata
}
function getRequestIpAddress(request: Request): string {
- const cfIp = getHeaderValue(request, "cf-connecting-ip");
- if (cfIp) return cfIp;
- const forwardedFor = getHeaderValue(request, "x-forwarded-for");
- return forwardedFor?.split(",")[0]?.trim() || "Unknown";
+ return getClientIp(request) ?? "Unknown";
}
function getHeaderValue(request: Request, name: string): string | null {
diff --git a/src/lib/auth/client-ip.ts b/src/lib/auth/client-ip.ts
new file mode 100644
index 0000000..a794bed
--- /dev/null
+++ b/src/lib/auth/client-ip.ts
@@ -0,0 +1,27 @@
+/**
+ * Resolve the real client IP for rate limiting and audit metadata.
+ *
+ * Forwarded headers are only meaningful when someone trustworthy set them:
+ * the self-host server resolves the IP at the socket (or the proxy hop it
+ * appended under TRUST_PROXY), stamps it into x-mailflare-client-ip, and
+ * strips every client-supplied forwarding header before app code runs. On
+ * Workers, cf-connecting-ip is platform-set and cannot be forged. A bare
+ * x-forwarded-for is the last resort for other runtimes — its rightmost
+ * hop is the least attacker-controlled entry.
+ */
+export function getClientIp(request: Request): string | null {
+ return (
+ // cf-connecting-ip first: on Workers it is platform-set and unforgeable,
+ // and checking it before x-mailflare-client-ip keeps a client-injected
+ // copy of the private header from winning there. The self-host server
+ // deletes cf-connecting-ip outright, so the stamped value is used next.
+ headerValue(request, "cf-connecting-ip") ||
+ headerValue(request, "x-mailflare-client-ip") ||
+ headerValue(request, "x-forwarded-for")?.split(",").at(-1)?.trim() ||
+ null
+ );
+}
+
+function headerValue(request: Request, name: string): string | null {
+ return request.headers.get(name)?.trim() || null;
+}
diff --git a/src/lib/auth/password-reset.ts b/src/lib/auth/password-reset.ts
index 59fa374..0fe782a 100644
--- a/src/lib/auth/password-reset.ts
+++ b/src/lib/auth/password-reset.ts
@@ -7,6 +7,7 @@ import { deleteUserSessions, hashSessionToken } from "@/lib/auth/session";
import { getBranding } from "@/lib/branding/service";
import { sendSystemEmail } from "@/lib/email/system-mail";
import { createAuditLog } from "@/lib/mailboxes/audit";
+import { getClientIp } from "@/lib/auth/client-ip";
import { buildPasswordResetEmail } from "@/lib/auth/password-reset-utils";
import type { Translator } from "@/lib/i18n/utils";
@@ -67,7 +68,7 @@ export async function completePasswordReset(
actorUserId: row.userId,
targetUserId: row.userId,
action: "auth.password_reset",
- metadata: { ipAddress: request.headers.get("cf-connecting-ip") ?? "unknown" },
+ metadata: { ipAddress: getClientIp(request) ?? "unknown" },
});
return { ok: true };
}
diff --git a/src/lib/auth/rate-limit.ts b/src/lib/auth/rate-limit.ts
index 83f89a2..1283729 100644
--- a/src/lib/auth/rate-limit.ts
+++ b/src/lib/auth/rate-limit.ts
@@ -1,16 +1,13 @@
+import { getClientIp } from "./client-ip";
+
/**
- * Client IP for rate-limit keys. On Workers, cf-connecting-ip is set by the
- * platform; self-hosted sits behind a reverse proxy, so fall back to the
- * proxy-set x-forwarded-for first hop. Without a real per-client key every
+ * Key rate limits by the resolved client IP. Without a per-client key every
* visitor lands in one shared "unknown" bucket and scanners can lock out
- * legitimate logins.
+ * legitimate logins; trusting raw forwarding headers here would be worse —
+ * a client could rotate them to leave the bucket entirely.
*/
function clientRateLimitKey(request: Request): string {
- return (
- request.headers.get("cf-connecting-ip")?.trim() ||
- request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ||
- "unknown"
- );
+ return getClientIp(request) ?? "unknown";
}
/** Mobile sign-ins have their own, stricter budget (they skip Turnstile). */
diff --git a/src/lib/auth/turnstile.ts b/src/lib/auth/turnstile.ts
index aedf32f..6a96ffb 100644
--- a/src/lib/auth/turnstile.ts
+++ b/src/lib/auth/turnstile.ts
@@ -1,4 +1,5 @@
import { newId } from "@/lib/ids";
+import { getClientIp } from "@/lib/auth/client-ip";
type TurnstileResponse = {
success: boolean;
@@ -23,7 +24,7 @@ export async function verifyTurnstileToken(
body: JSON.stringify({
secret,
response: token,
- remoteip: request.headers.get("cf-connecting-ip") ?? undefined,
+ remoteip: getClientIp(request) ?? undefined,
idempotency_key: newId("ts"),
}),
});