feat(webui): add SNOWLUMA_WEBUI_TRUST_PROXY for reverse-proxy deploys

The previous commit tightened login rate-limiting to key off the real
TCP socket peer, which fixed the X-Forwarded-For bypass but had the
known caveat of collapsing every client into a single global bucket
when the WebUI runs behind nginx / Caddy / a SaaS CDN.

Give operators an explicit, audited way to opt back into per-client
keying without re-introducing the spoof:

* `SNOWLUMA_WEBUI_TRUST_PROXY` env var. Modes:
    - unset / empty     → keep socket peer (safe default, unchanged)
    - "loopback"        → trust X-Real-IP / X-Forwarded-For when the
                          immediate socket peer is 127.0.0.1 / ::1
                          (nginx + WebUI on the same host)
    - "1" / "true" /    → trust headers from any peer (only safe behind
      "all"               a SaaS proxy that strips client-set headers)
    - comma-separated   → trust headers only when the socket peer
      IP list             matches one of these (proxy on another box)

* When trusting headers we prefer X-Real-IP (single value the proxy
  overwrites unconditionally) and fall back to the first hop of XFF.
  We deliberately do NOT walk the full XFF chain — without a fully
  trusted proxy chain the leftmost value is still spoofable; a
  single-tier proxy is the only setup this app realistically sees.

* Boot log prints "login rate-limit keyed by: …" so operators can
  verify the mode took effect, plus an extra WARN for "all" reminding
  them it's only safe with header-stripping in front.

Logic lives in webui/client-ip.ts as a pure pickClientIp() that takes
a socket-IP resolver, so the trust-proxy matrix can be exercised
without standing up a server — see webui-client-ip.test.ts for the
11 new unit tests covering parse + dispatch + loopback / list / all /
none modes.

Smoke-tested with SNOWLUMA_WEBUI_TRUST_PROXY=loopback:
  - 5× failed login w/ X-Forwarded-For: 1.1.1.1 → 401
  - 6th attempt same XFF → 429 (locked, per-XFF)
  - 6th attempt X-Forwarded-For: 2.2.2.2 → 401 (fresh bucket)
  - X-Real-IP overrides XFF when both present
This commit is contained in:
时瑾 authored and DrSmoothl committed 2026-05-16 21:31:54 +08:00
1 parent d66f0b2c6b
commit ffe0c57abf
3 files changed
+209 -13

No files matched your search

+106
View File
@@ -0,0 +1,106 @@
// Resolve the request's "real" client IP for per-IP rate limiting.
//
// Threat model:
// - By default we ONLY trust the TCP socket peer. `X-Forwarded-For` and
// `X-Real-IP` are client-controllable, so honoring them lets any
// client rotate the header to escape the 5-attempts/15-min login
// lockout.
// - Operators who actually run behind a reverse proxy (nginx, Caddy,
// a SaaS CDN) need a way to opt back into the real client IP. The
// `SNOWLUMA_WEBUI_TRUST_PROXY` env var lets them say "when the
// immediate TCP peer is THIS, treat the headers as authoritative".
//
// Supported values for SNOWLUMA_WEBUI_TRUST_PROXY:
// - unset / empty — default; ignore headers, use socket peer
// - "loopback" — trust headers when the socket peer is 127.0.0.1
// or ::1 (typical for nginx/Caddy on the same host)
// - "1" / "true" / — trust headers from any peer (only safe behind a
// "all" trusted SaaS CDN that strips client-set headers)
// - comma-separated — trust headers when the socket peer matches one
// IP list of these IPs (reverse proxy on another machine)
//
// When trusted, we prefer X-Real-IP (a single value the reverse proxy
// overwrites unconditionally) and fall back to the first hop of
// X-Forwarded-For. We never parse the FULL XFF chain — if the proxy
// chain isn't fully trusted, the leftmost value can still be spoofed
// by the original client, and a single-tier proxy is the only setup
// this app realistically sees.
import type { Context } from 'hono';
import { getConnInfo } from '@hono/node-server/conninfo';
export type TrustProxyMode =
| { kind: 'none' }
| { kind: 'loopback' }
| { kind: 'all' }
| { kind: 'ip-list'; ips: Set<string> };
export function parseTrustProxy(raw: string | undefined): TrustProxyMode {
const value = raw?.trim().toLowerCase() ?? '';
if (!value) return { kind: 'none' };
if (value === '1' || value === 'true' || value === 'all') return { kind: 'all' };
if (value === 'loopback') return { kind: 'loopback' };
const ips = new Set(
value.split(',').map((s) => s.trim()).filter(Boolean),
);
if (ips.size === 0) return { kind: 'none' };
return { kind: 'ip-list', ips };
}
export function describeTrustProxy(mode: TrustProxyMode): string {
switch (mode.kind) {
case 'none': return 'socket peer (default)';
case 'all': return 'X-Real-IP / X-Forwarded-For from any peer';
case 'loopback': return 'X-Real-IP / X-Forwarded-For when socket peer is loopback';
case 'ip-list': return `X-Real-IP / X-Forwarded-For when socket peer is in [${[...mode.ips].join(',')}]`;
}
}
function isLoopback(ip: string): boolean {
return ip === '127.0.0.1' || ip === '::1' || ip === '::ffff:127.0.0.1';
}
function shouldTrustHeaders(mode: TrustProxyMode, socketIp: string): boolean {
switch (mode.kind) {
case 'none': return false;
case 'all': return true;
case 'loopback': return isLoopback(socketIp);
case 'ip-list': return mode.ips.has(socketIp);
}
}
/**
* Pick the right "client IP" for rate-limit keying.
*
* Exposed as a pure function over a small dependency surface so the
* unit tests can fabricate request shapes without spinning up a server.
*/
export function pickClientIp(
c: Pick<Context, 'req'>,
mode: TrustProxyMode,
getSocketIp: () => string,
): string {
const socketIp = (() => {
try { return getSocketIp() || '127.0.0.1'; }
catch { return '127.0.0.1'; }
})();
if (!shouldTrustHeaders(mode, socketIp)) return socketIp;
const realIp = c.req.header('x-real-ip')?.trim();
if (realIp) return realIp;
const xff = c.req.header('x-forwarded-for');
if (xff) {
const first = xff.split(',')[0].trim();
if (first) return first;
}
return socketIp;
}
/** Convenience binding for the live server: read socket via getConnInfo. */
export function makeClientIpResolver(mode: TrustProxyMode): (c: Context) => string {
return (c) => pickClientIp(c, mode, () => {
try { return getConnInfo(c).remote.address ?? '127.0.0.1'; }
catch { return '127.0.0.1'; }
});
}
+11 -13
View File
@@ -1,7 +1,7 @@
import { serve } from '@hono/node-server';
import { getConnInfo } from '@hono/node-server/conninfo';
import { serveStatic } from '@hono/node-server/serve-static';
import { Hono, type Context } from 'hono';
import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip';
import { createLogger, getRecentLogs, subscribeLogs } from '../utils/logger';
import { randomBytes } from 'crypto';
import type { OneBotManager } from '../onebot/manager';
@@ -66,19 +66,13 @@ function purgeExpiredTokens() {
}
/**
* Resolve the client IP from the underlying TCP socket via the official
* @hono/node-server conninfo helper. We deliberately do NOT trust
* `X-Forwarded-For` — the WebUI listens on a local port with no required
* reverse proxy, so accepting that header would let any client rotate it
* to bypass the per-IP login lockout.
* Resolve the client IP for per-IP rate limiting. Default is the TCP
* socket peer (cannot be spoofed by the client). Operators behind a
* reverse proxy must opt in via the `SNOWLUMA_WEBUI_TRUST_PROXY` env
* var; see `./client-ip.ts` for the accepted values.
*/
function getClientIp(c: Context): string {
try {
return getConnInfo(c).remote.address ?? '127.0.0.1';
} catch {
return '127.0.0.1';
}
}
const trustProxyMode = parseTrustProxy(process.env.SNOWLUMA_WEBUI_TRUST_PROXY);
const getClientIp = makeClientIpResolver(trustProxyMode);
async function fetchQqAvatar(uin: string): Promise<{ body: Uint8Array; contentType: string }> {
const response = await fetch(`https://q1.qlogo.cn/g?b=qq&nk=${encodeURIComponent(uin)}&s=100`, {
@@ -109,6 +103,10 @@ export async function initWebUI(
} else if (auth.mustChangePassword()) {
log.warn('password change is still required');
}
log.info('login rate-limit keyed by: %s', describeTrustProxy(trustProxyMode));
if (trustProxyMode.kind === 'all') {
log.warn('SNOWLUMA_WEBUI_TRUST_PROXY=1 — only safe behind a reverse proxy that strips client-set X-Real-IP / X-Forwarded-For');
}
const app = new Hono();