Skip to content

7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.

TypeScript

feat(security): Host-header allowlist against DNS rebinding (ALLOWED_HOSTS, #1637) (#1644)

tashdroid298a59cc4258
diff --git a/.env.example b/.env.example
index 5e5c8245..4319dc04 100644
--- a/.env.example
+++ b/.env.example
@@ -397,6 +397,17 @@ REQUEST_ANALYTICS_MAX_ROWS=100000
# TRUST_PROXY=100.64.0.0/10,192.168.1.10
# TRUST_PROXY=false
+# Host-header allowlist against DNS rebinding (#1637). Off by default. Once
+# set, a request whose Host header names anything other than loopback
+# (localhost, 127.0.0.1, ::1, *.localhost) or a listed hostname gets 403
+# before auth or routing. List every hostname/IP you reach the server by,
+# comma-separated. Loopback-only:
+# ALLOWED_HOSTS=localhost
+# LAN or reverse proxy:
+# ALLOWED_HOSTS=192.168.1.50,freellmapi.home.arpa
+# Unset (or *) leaves the check off.
+# ALLOWED_HOSTS=
+
# Per-model routing score multipliers (#738), JSON object of model id → 0..2.
# 1.0 leaves a model unchanged, below 1 demotes it, above 1 promotes it, and 0
# means the automatic router never picks it (Manual priority still can).
diff --git a/docs/en/env/01-variables.md b/docs/en/env/01-variables.md
index 83ee198f..cdeabf14 100644
--- a/docs/en/env/01-variables.md
+++ b/docs/en/env/01-variables.md
@@ -47,6 +47,7 @@ First-run note: the first dashboard account is normally created from a browser o
| Variable | Default | Purpose |
| --- | --- | --- |
+| `ALLOWED_HOSTS` | unset (off) | Opt-in Host-header allowlist against DNS rebinding. When set to a comma-separated list of hostnames/IPs (e.g. `localhost` for loopback-only, or `192.168.1.50,freellmapi.home.arpa`), requests whose `Host` names anything but those or loopback (`localhost`, `127.0.0.1`, `::1`, `*.localhost`) are rejected with 403 before auth or routing. Unset or `*` leaves the check off. Parsed by `parseAllowedHosts()` in `server/src/lib/config.ts`, enforced by `server/src/middleware/allowed-hosts.ts` (#1637). |
| `PROXY_RATE_LIMIT_RPM` | `120` | Max `/v1` proxy requests per minute per client IP. Set to `0` to disable proxy rate limiting. See [03-outbound-proxies.md](03-outbound-proxies.md) for related knobs. When `TRUST_PROXY` is set, the limiter counts the real client IP from `X-Forwarded-For` instead of the socket peer. |
| `ADMIN_RATE_LIMIT_RPM` | `600` | Max `/api` dashboard requests per minute per client IP. A flood guard — login has its own per-email lockout and key export its own much tighter cap. Set to `0` to disable. Also respects `TRUST_PROXY`. |
diff --git a/server/src/__tests__/routes/allowed-hosts.test.ts b/server/src/__tests__/routes/allowed-hosts.test.ts
new file mode 100644
index 00000000..6bb79d2c
--- /dev/null
+++ b/server/src/__tests__/routes/allowed-hosts.test.ts
@@ -0,0 +1,129 @@
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import http from 'node:http';
+import type { Express } from 'express';
+import { createApp } from '../../app.js';
+import { initDb } from '../../db/index.js';
+
+// Host-header allowlist (#1637). node:http rather than fetch(): undici
+// silently rewrites Host to the connect target, and Host is the header under
+// test (same trick as csp-security.test.ts / auth-desktop-session.test.ts).
+
+let previousAllowed: string | undefined;
+
+function appWithAllowed(allowed: string | undefined): Express {
+ if (allowed === undefined) delete process.env.ALLOWED_HOSTS;
+ else process.env.ALLOWED_HOSTS = allowed;
+ return createApp();
+}
+
+function call(
+ app: Express,
+ path: string,
+ host: string | undefined,
+): Promise<{ status: number; body: string }> {
+ return new Promise((resolve, reject) => {
+ const server = app.listen(0, '127.0.0.1', () => {
+ const { port } = server.address() as { port: number };
+ const headers: Record<string, string> = {};
+ if (host !== undefined) headers.host = host;
+ const req = http.request(
+ { host: '127.0.0.1', port, path, headers },
+ res => {
+ let body = '';
+ res.setEncoding('utf8');
+ res.on('data', chunk => { body += chunk; });
+ res.on('end', () => {
+ server.close();
+ resolve({ status: res.statusCode ?? 0, body });
+ });
+ },
+ );
+ req.on('error', err => { server.close(); reject(err); });
+ req.end();
+ });
+ });
+}
+
+describe('Host-header guard (#1637)', () => {
+ beforeAll(() => {
+ previousAllowed = process.env.ALLOWED_HOSTS;
+ process.env.ENCRYPTION_KEY = '0'.repeat(64);
+ initDb(':memory:');
+ });
+
+ afterAll(() => {
+ if (previousAllowed === undefined) delete process.env.ALLOWED_HOSTS;
+ else process.env.ALLOWED_HOSTS = previousAllowed;
+ });
+
+ describe('default (no ALLOWED_HOSTS): guard off', () => {
+ // Opt-in on purpose: a loopback-only default would 403 LAN, Docker-network,
+ // desktop-LAN and reverse-proxy installs the moment they upgraded.
+ it('lets any Host through, including LAN IPs, container names and proxies', async () => {
+ const app = appWithAllowed(undefined);
+ for (const host of ['localhost:3001', '192.168.1.50:3001', 'freellmapi:3001', 'proxy.example.com', 'evil.example:3001']) {
+ expect((await call(app, '/api/ping', host)).status, host).toBe(200);
+ }
+ });
+
+ it('an empty ALLOWED_HOSTS is also off', async () => {
+ expect((await call(appWithAllowed(' '), '/api/ping', '192.168.1.50:3001')).status).toBe(200);
+ });
+ });
+
+ describe('loopback-only (ALLOWED_HOSTS=localhost)', () => {
+ it('rejects a rebinding hostname with 403 before routing', async () => {
+ const res = await call(appWithAllowed('localhost'), '/api/ping', 'evil.example:3001');
+ expect(res.status).toBe(403);
+ expect(JSON.parse(res.body).error.message).toContain('ALLOWED_HOSTS');
+ });
+
+ it('accepts the loopback names on any port', async () => {
+ const app = appWithAllowed('localhost');
+ for (const host of ['localhost:3001', '127.0.0.1:3001', '[::1]:3001', 'app.localhost']) {
+ const res = await call(app, '/api/ping', host);
+ expect(res.status, host).toBe(200);
+ }
+ });
+
+ it('accepts a bare 127.0.0.1 Host with no port', async () => {
+ expect((await call(appWithAllowed('localhost'), '/api/ping', '127.0.0.1')).status).toBe(200);
+ });
+
+ it('rejects an unlisted LAN IP', async () => {
+ expect((await call(appWithAllowed('localhost'), '/api/ping', '192.168.1.50:3001')).status).toBe(403);
+ });
+ });
+
+ describe('ALLOWED_HOSTS entries', () => {
+ it('accepts a listed hostname, case-insensitively, ignoring the port', async () => {
+ const app = appWithAllowed('ai.home.arpa, DASH.Example.COM');
+ expect((await call(app, '/api/ping', 'ai.home.arpa:3001')).status).toBe(200);
+ expect((await call(app, '/api/ping', 'dash.example.com')).status).toBe(200);
+ });
+
+ it('still rejects unlisted hostnames', async () => {
+ const app = appWithAllowed('ai.home.arpa');
+ expect((await call(app, '/api/ping', 'evil.example:3001')).status).toBe(403);
+ // A suffix-lookalike of an allowed name is not allowed.
+ expect((await call(app, '/api/ping', 'ai.home.arpa.evil.example')).status).toBe(403);
+ });
+
+ it('still accepts loopback alongside the entries', async () => {
+ const app = appWithAllowed('ai.home.arpa');
+ expect((await call(app, '/api/ping', 'localhost:3001')).status).toBe(200);
+ });
+
+ it('a single * disables the guard', async () => {
+ const app = appWithAllowed('*');
+ expect((await call(app, '/api/ping', 'evil.example:3001')).status).toBe(200);
+ });
+ });
+
+ describe('guard runs before auth', () => {
+ it('403s an unauthenticated /api/keys call on a bad Host (not 401)', async () => {
+ const res = await call(appWithAllowed('localhost'), '/api/keys', 'evil.example:3001');
+ expect(res.status).toBe(403);
+ });
+ });
+});
diff --git a/server/src/app.ts b/server/src/app.ts
index cf9ce2c1..0fc5408a 100644
--- a/server/src/app.ts
+++ b/server/src/app.ts
@@ -36,6 +36,7 @@ import { urlTokenRouter } from './routes/url-tokens.js';
import { updateRouter } from './routes/update.js';
import { moderationRouter } from './routes/moderation.js';
import { requireAuth } from './middleware/requireAuth.js';
+import { createHostGuard } from './middleware/allowed-hosts.js';
import { createProxyRateLimiter, createAdminRateLimiter } from './middleware/rateLimit.js';
// Password-guess ceiling for GET /api/keys/export. Deliberately low: a real
@@ -105,6 +106,13 @@ export function createApp(config?: Config) {
// /CIDRs trusts only those proxies. Must be set before client-context and
// the rate-limit middleware, which both resolve the client IP.
app.set('trust proxy', cfg.trustProxy);
+ // DNS-rebinding guard (#1637), first middleware so a rebinding request is
+ // rejected before helmet, CORS, body parsing, auth or routing. Opt-in: off
+ // until ALLOWED_HOSTS lists a hostname, then loopback + those names pass
+ // ('*' keeps it off). Must sit
+ // above everything below — its whole value is answering before any state or
+ // credential is touched.
+ app.use(createHostGuard(cfg.allowedHosts));
const allowedCorsOrigins = new Set([
...DEFAULT_DASHBOARD_ORIGINS,
...cfg.dashboardOrigins,
diff --git a/server/src/lib/config.ts b/server/src/lib/config.ts
index ed5e9937..86712373 100644
--- a/server/src/lib/config.ts
+++ b/server/src/lib/config.ts
@@ -65,6 +65,14 @@ export interface Config {
* - false: never emit (let HTTP LAN installs render the dashboard).
*/
cspUpgradeInsecureRequests: boolean | undefined;
+ /**
+ * Extra Host-header names accepted by the DNS-rebinding guard (#1637),
+ * parsed from ALLOWED_HOSTS (comma-separated). Empty (the default) leaves
+ * the guard off. Once set, loopback (localhost / 127.0.0.1 / ::1 /
+ * *.localhost) is always accepted on top of these names. A single `*` also
+ * leaves the guard off.
+ */
+ allowedHosts: string[];
}
export function loadConfig(): Config {
@@ -89,9 +97,23 @@ export function loadConfig(): Config {
// unset (the default) leaves it on auto — emit only when the request is
// already TLS or forwarded as https, so HTTP LAN installs still render.
cspUpgradeInsecureRequests: parseCspUpgradeInsecureRequests(),
+ allowedHosts: parseAllowedHosts(),
};
}
+// Parse ALLOWED_HOSTS (#1637). unset/empty → [] (guard off).
+// Otherwise a comma-separated list of exact hostnames (case-insensitive) that
+// the Host header may name, on top of the loopback default. A single '*'
+// disables the guard entirely — the middleware reads that sentinel.
+function parseAllowedHosts(): string[] {
+ const raw = process.env.ALLOWED_HOSTS;
+ if (raw === undefined || raw.trim() === '') return [];
+ return raw
+ .split(',')
+ .map(s => s.trim().toLowerCase())
+ .filter(Boolean);
+}
+
// Parse TRUST_PROXY (#1024). unset/empty/false → false (do not trust forwarded
// headers); true → trust all proxies; a non-negative integer → that many hops
// from the socket peer (so `TRUST_PROXY=1` means "one proxy in front", the
diff --git a/server/src/middleware/allowed-hosts.ts b/server/src/middleware/allowed-hosts.ts
new file mode 100644
index 00000000..951e8320
--- /dev/null
+++ b/server/src/middleware/allowed-hosts.ts
@@ -0,0 +1,86 @@
+import type { Request, Response, NextFunction } from 'express';
+
+// Host-header allowlist (#1637): DNS-rebinding defense for localhost installs.
+//
+// Docker Compose publishes the server on 127.0.0.1 by default, which keeps it
+// off the LAN but NOT off the browser: a page on a hostname the attacker
+// controls can re-resolve that name to 127.0.0.1 mid-session (rebinding) and
+// then issue "same-origin" requests that arrive with `Host: attacker.example`.
+// Auth covers /v1 and the dashboard API, but unauthenticated routes (login,
+// status, first-run setup) and the login form itself are reachable that way.
+//
+// The fix is the standard one: unless the Host header names a host the operator
+// declared, reject with 403 before routing or auth runs. The guard is OPT-IN:
+// with ALLOWED_HOSTS unset it does nothing, because a loopback-only default
+// would lock out every LAN, Docker-network, desktop-LAN and reverse-proxy
+// install on upgrade. Once ALLOWED_HOSTS lists any hostname, the allow list is
+// those names plus the loopback set — localhost, 127.0.0.1, ::1, and
+// *.localhost (which browsers treat as loopback-equivalent secure contexts).
+// '*' keeps it off explicitly.
+//
+// Matching is on the HOSTNAME ONLY, never host:port: Compose remaps the outer
+// port freely (HOST_BIND + ports: "127.0.0.1:${HOST_PORT:-3001}:3001") and the
+// rebinding threat has nothing to do with ports.
+
+const DEFAULT_ALLOWED_HOSTS = ['localhost', '127.0.0.1', '::1'];
+
+/** Lowercase hostname from a raw Host header value, or null if malformed.
+ * URL parsing is what makes `[::1]:3001` (bracketed IPv6), `host` and
+ * `host:port` all yield a comparable bare hostname. WHATWG URL keeps the
+ * brackets on an IPv6 hostname (`[::1]`), so they are stripped for the
+ * comparison set. */
+function hostnameOf(hostHeader: string | undefined): string | null {
+ if (!hostHeader) return null;
+ try {
+ const host = new URL(`http://${hostHeader}`).hostname.toLowerCase();
+ return host.startsWith('[') && host.endsWith(']') ? host.slice(1, -1) : host;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Express middleware enforcing the Host allowlist.
+ * @param allowed raw host patterns from ALLOWED_HOSTS (empty → guard off). Exact, case-insensitive hostnames; a single `*` disables the
+ * guard. `*.example.com` entries match any single-label subdomain wildcard
+ * is NOT supported — name every host you serve.
+ */
+export function createHostGuard(allowed: string[]) {
+ const wildcard = allowed.includes('*');
+ const names = new Set(
+ allowed
+ .filter(h => h !== '*')
+ .map(h => h.trim().toLowerCase())
+ .filter(Boolean),
+ );
+ const isAllowedHost = (host: string): boolean =>
+ DEFAULT_ALLOWED_HOSTS.includes(host) ||
+ host.endsWith('.localhost') ||
+ names.has(host);
+
+ return function hostGuard(req: Request, res: Response, next: NextFunction): void {
+ if (wildcard || names.size === 0) {
+ next();
+ return;
+ }
+ // A request with two Host headers never reaches here: Node's HTTP parser
+ // rejects it with a 400 before Express sees it. The header value is a
+ // plain string by the time this runs.
+ const host = hostnameOf(req.headers.host);
+ if (host === null || !isAllowedHost(host)) {
+ res
+ .status(403)
+ .json({
+ error: {
+ message:
+ 'Host header not allowed. If you reach this server by IP or by a ' +
+ 'custom hostname, add that hostname to ALLOWED_HOSTS (comma-' +
+ 'separated; ALLOWED_HOSTS=* disables this check).',
+ type: 'invalid_request_error',
+ },
+ });
+ return;
+ }
+ next();
+ };
+}