diff --git a/packages/core/src/webui/client-ip.ts b/packages/core/src/webui/client-ip.ts new file mode 100644 index 00000000..a8765bc1 --- /dev/null +++ b/packages/core/src/webui/client-ip.ts @@ -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 }; + +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, + 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'; } + }); +} diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index bf792788..c71a5d11 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -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(); diff --git a/packages/core/tests/webui-client-ip.test.ts b/packages/core/tests/webui-client-ip.test.ts new file mode 100644 index 00000000..0a8159f3 --- /dev/null +++ b/packages/core/tests/webui-client-ip.test.ts @@ -0,0 +1,92 @@ +import { describe, expect, it } from 'vitest'; +import { + describeTrustProxy, + parseTrustProxy, + pickClientIp, + type TrustProxyMode, +} from '../src/webui/client-ip'; + +function mockCtx(headers: Record = {}) { + return { + req: { + header: (name: string) => headers[name.toLowerCase()], + }, + } as unknown as Parameters[0]; +} + +describe('parseTrustProxy', () => { + it('treats empty / unset as none (safe default)', () => { + expect(parseTrustProxy(undefined)).toEqual({ kind: 'none' }); + expect(parseTrustProxy('')).toEqual({ kind: 'none' }); + expect(parseTrustProxy(' ')).toEqual({ kind: 'none' }); + }); + + it('recognises "1" / "true" / "all" as full trust', () => { + expect(parseTrustProxy('1')).toEqual({ kind: 'all' }); + expect(parseTrustProxy('true')).toEqual({ kind: 'all' }); + expect(parseTrustProxy('ALL')).toEqual({ kind: 'all' }); + }); + + it('recognises "loopback" case-insensitively', () => { + expect(parseTrustProxy('Loopback')).toEqual({ kind: 'loopback' }); + }); + + it('parses a comma-separated IP list', () => { + const mode = parseTrustProxy('10.0.0.1, 192.168.1.5, '); + expect(mode.kind).toBe('ip-list'); + if (mode.kind !== 'ip-list') throw new Error('unreachable'); + expect([...mode.ips].sort()).toEqual(['10.0.0.1', '192.168.1.5']); + }); +}); + +describe('pickClientIp', () => { + const xff = { 'x-forwarded-for': '203.0.113.7, 10.0.0.1' }; + const realIp = { 'x-real-ip': '203.0.113.42' }; + const both = { ...xff, ...realIp }; + + it('returns socket peer and IGNORES headers when trust=none (default)', () => { + const mode: TrustProxyMode = { kind: 'none' }; + expect(pickClientIp(mockCtx(both), mode, () => '198.51.100.9')).toBe('198.51.100.9'); + }); + + it('honors X-Real-IP first, then XFF first hop, when trust=all', () => { + const mode: TrustProxyMode = { kind: 'all' }; + expect(pickClientIp(mockCtx(both), mode, () => '10.0.0.1')).toBe('203.0.113.42'); + expect(pickClientIp(mockCtx(xff), mode, () => '10.0.0.1')).toBe('203.0.113.7'); + }); + + it('falls back to socket peer when trust=all but no headers present', () => { + const mode: TrustProxyMode = { kind: 'all' }; + expect(pickClientIp(mockCtx({}), mode, () => '10.0.0.1')).toBe('10.0.0.1'); + }); + + it('trust=loopback honors headers only when socket is loopback', () => { + const mode: TrustProxyMode = { kind: 'loopback' }; + expect(pickClientIp(mockCtx(both), mode, () => '127.0.0.1')).toBe('203.0.113.42'); + expect(pickClientIp(mockCtx(both), mode, () => '::1')).toBe('203.0.113.42'); + expect(pickClientIp(mockCtx(both), mode, () => '::ffff:127.0.0.1')).toBe('203.0.113.42'); + // Non-loopback peer → headers ignored, socket wins. + expect(pickClientIp(mockCtx(both), mode, () => '10.0.0.1')).toBe('10.0.0.1'); + }); + + it('trust=ip-list honors headers only when socket is in the list', () => { + const mode: TrustProxyMode = { kind: 'ip-list', ips: new Set(['10.0.0.1', '10.0.0.2']) }; + expect(pickClientIp(mockCtx(both), mode, () => '10.0.0.2')).toBe('203.0.113.42'); + expect(pickClientIp(mockCtx(both), mode, () => '10.0.0.9')).toBe('10.0.0.9'); + }); + + it('survives a socket resolver that throws', () => { + const mode: TrustProxyMode = { kind: 'none' }; + expect(pickClientIp(mockCtx({}), mode, () => { throw new Error('boom'); })).toBe('127.0.0.1'); + }); +}); + +describe('describeTrustProxy', () => { + it('renders each mode in a recognisable form for the boot log', () => { + expect(describeTrustProxy({ kind: 'none' })).toContain('socket peer'); + expect(describeTrustProxy({ kind: 'all' })).toContain('any peer'); + expect(describeTrustProxy({ kind: 'loopback' })).toContain('loopback'); + expect(describeTrustProxy({ kind: 'ip-list', ips: new Set(['10.0.0.1']) })) + .toContain('10.0.0.1'); + }); +});