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

fix(auth): stop a same-host reverse proxy from waiving the setup code (#1287)

tashdroid5f9645cffb35
diff --git a/server/src/__tests__/routes/auth-setup-code.test.ts b/server/src/__tests__/routes/auth-setup-code.test.ts
index 7906ad00..c0658833 100644
--- a/server/src/__tests__/routes/auth-setup-code.test.ts
+++ b/server/src/__tests__/routes/auth-setup-code.test.ts
@@ -21,13 +21,13 @@ function appWithRemote(remoteAddr: string): Express {
return app;
}
-async function postSetup(app: Express, body: unknown) {
+async function postSetup(app: Express, body: unknown, headers: Record<string, string> = {}) {
const server = app.listen(0, '127.0.0.1');
if (!server.listening) await new Promise<void>(resolve => server.once('listening', () => resolve()));
const addr = server.address() as { port: number };
const res = await fetch(`http://127.0.0.1:${addr.port}/api/auth/setup`, {
method: 'POST',
- headers: { 'Content-Type': 'application/json' },
+ headers: { 'Content-Type': 'application/json', ...headers },
body: JSON.stringify(body),
});
const data = await res.json().catch(() => null);
@@ -90,6 +90,43 @@ describe('First-run setup code gate (FIX 1)', () => {
expect(typeof body.token).toBe('string');
});
+ // The documented reverse-proxy deployment (Caddy/nginx/Traefik on the same
+ // host, docs/en/proxy/OVERVIEW.md) makes every request a loopback socket, so
+ // the socket test alone said "local" for the entire internet and any visitor
+ // could claim an unclaimed dashboard with no code. A forwarded hop can never
+ // GRANT locality, but a non-loopback one withdraws it.
+ it('rejects a loopback socket whose forwarded hop is remote', async () => {
+ const { status, body } = await postSetup(
+ appWithRemote('127.0.0.1'),
+ CREDS,
+ { 'X-Forwarded-For': '203.0.113.7' },
+ );
+ expect(status).toBe(403);
+ expect(body.error.type).toBe('setup_code_required');
+ const count = (getDb().prepare('SELECT COUNT(*) AS c FROM users').get() as { c: number }).c;
+ expect(count).toBe(0);
+ });
+
+ it('still allows a same-host proxy that forwards a local browser', async () => {
+ const { status } = await postSetup(
+ appWithRemote('127.0.0.1'),
+ CREDS,
+ { 'X-Forwarded-For': '127.0.0.1' },
+ );
+ expect(status).toBe(201);
+ });
+
+ it('accepts the setup code through a proxy with a remote forwarded hop', async () => {
+ const code = getSetupCode();
+ expect(code).toBeTruthy();
+ const { status } = await postSetup(
+ appWithRemote('127.0.0.1'),
+ { ...CREDS, setupCode: code },
+ { 'X-Forwarded-For': '203.0.113.7' },
+ );
+ expect(status).toBe(201);
+ });
+
it('still 409s a second setup once an account exists (remote, even with a code)', async () => {
// Claim locally first.
expect((await postSetup(appWithRemote('127.0.0.1'), CREDS)).status).toBe(201);
diff --git a/server/src/routes/auth.ts b/server/src/routes/auth.ts
index d7a8ff93..88ee7ca6 100644
--- a/server/src/routes/auth.ts
+++ b/server/src/routes/auth.ts
@@ -91,18 +91,37 @@ function bearer(req: Request): string | undefined {
?? (req.headers['x-dashboard-token'] as string | undefined);
}
-// Is the caller connecting from the local machine? We check the actual socket
-// peer address, NOT req.ip or X-Forwarded-For: those are attacker-controlled
-// behind a proxy (and trust proxy is off by default anyway), so trusting them
-// here would let a remote caller pretend to be local and skip the setup code.
-function isLoopbackRemote(req: Request): boolean {
- let addr = req.socket.remoteAddress ?? '';
+function isLoopbackAddress(value: string | undefined): boolean {
+ let addr = (value ?? '').trim();
// Node reports IPv4 loopback over a dual-stack socket as "::ffff:127.0.0.1".
if (addr.startsWith('::ffff:')) addr = addr.slice(7);
if (addr === '::1') return true;
return /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(addr);
}
+// Is the caller connecting from the local machine? The socket peer address is
+// the authority, NOT req.ip: forwarded headers are attacker-controlled, so
+// letting one of them ASSERT locality would hand a remote caller the setup
+// code exemption outright.
+//
+// But the socket peer alone is not sufficient either, because the reverse-proxy
+// deployment this project documents (docs/en/proxy/OVERVIEW.md, and
+// docs/en/troubleshooting/01-common-issues.md on TRUST_PROXY) puts Caddy/nginx/
+// Traefik on the SAME host: every request then arrives from 127.0.0.1 and the
+// socket test is true for the entire internet. So a forwarded hop can never
+// grant locality, but it can withdraw it — exactly the treatment the Ollama
+// open-loopback mode already applies in routes/ollama.ts:25-38.
+function isLoopbackRemote(req: Request): boolean {
+ if (!isLoopbackAddress(req.socket.remoteAddress)) return false;
+ const forwarded = req.headers['x-forwarded-for'];
+ const firstForwarded = (Array.isArray(forwarded) ? forwarded[0] : forwarded)
+ ?.split(',')[0];
+ // A local reverse proxy is itself a loopback socket, but its first forwarded
+ // hop may be remote. Refuse that request rather than silently widening the
+ // no-code first-run path through the proxy.
+ return !firstForwarded || isLoopbackAddress(firstForwarded);
+}
+
// Has the dashboard been set up yet, and is this caller authenticated?
authRouter.get('/status', (req: Request, res: Response) => {
const session = validateSession(bearer(req));