Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

fix(authz): close 2nd Host-spoof path (cliTokenAuth) + IPv6 loopback + Docker stamp

diegosouzapw729252008bbe
diff --git a/scripts/dev/run-standalone.mjs b/scripts/dev/run-standalone.mjs
index 9a91b9aa92..b1bef083b4 100644
--- a/scripts/dev/run-standalone.mjs
+++ b/scripts/dev/run-standalone.mjs
@@ -1,5 +1,6 @@
#!/usr/bin/env node
+import { existsSync } from "node:fs";
import {
resolveRuntimePorts,
withRuntimePortEnv,
@@ -10,7 +11,14 @@ import { bootstrapEnv } from "../build/bootstrap-env.mjs";
const env = bootstrapEnv();
const runtimePorts = resolveRuntimePorts(env);
-spawnWithForwardedSignals("node", ["server.js"], {
+// Prefer the WS-aware wrapper (server-ws.mjs) over the bare Next standalone
+// server.js: it installs the trusted peer-IP stamp (scripts/dev/peer-stamp.mjs)
+// that the authz middleware needs to allow loopback/LAN access to LOCAL_ONLY
+// routes. Falling back to server.js fails CLOSED (every LOCAL_ONLY request 403s)
+// rather than trusting the spoofable Host header.
+const entry = existsSync("server-ws.mjs") ? "server-ws.mjs" : "server.js";
+
+spawnWithForwardedSignals("node", [entry], {
stdio: "inherit",
env: withRuntimePortEnv(env, runtimePorts),
});
diff --git a/src/lib/middleware/cliTokenAuth.ts b/src/lib/middleware/cliTokenAuth.ts
index 1871503b72..f39f6dbca3 100644
--- a/src/lib/middleware/cliTokenAuth.ts
+++ b/src/lib/middleware/cliTokenAuth.ts
@@ -2,6 +2,7 @@ import crypto from "node:crypto";
import { headers } from "next/headers";
import { getLegacyCliTokenSync, getMachineTokenSync } from "@/lib/machineToken";
+import { AUTHZ_HEADER_PEER_LOCALITY } from "@/server/authz/headers";
const HEADER_NAME = "x-omniroute-cli-token";
@@ -43,20 +44,27 @@ function requestPeerAddress(request: RequestWithPeer): string | null {
}
async function isLocalCliRequest(request: RequestWithPeer): Promise<boolean> {
+ // 1. Direct / non-middleware callers (raw Node, unit tests) may carry a real
+ // socket peer.
const peerAddress = requestPeerAddress(request);
if (peerAddress) return isLoopback(peerAddress);
+ // 2. A forwarded request came through a proxy → it is not a local CLI call.
const forwardedPeer =
firstHeaderIp(await readHeader(request, "cf-connecting-ip")) ||
firstHeaderIp(await readHeader(request, "x-forwarded-for")) ||
firstHeaderIp(await readHeader(request, "x-real-ip"));
if (forwardedPeer) return false;
- try {
- return isLoopback(new URL(request.url).hostname);
- } catch {
- return false;
- }
+ // 3. Behind the authz pipeline, trust ONLY the locality verdict the middleware
+ // stamped from the real TCP peer IP. NEVER derive locality from the Host
+ // header (new URL(request.url).hostname) — it is client-controlled, so a
+ // remote caller with a stolen CLI token could send Host: 127.0.0.1 to pass.
+ const locality = await readHeader(request, AUTHZ_HEADER_PEER_LOCALITY);
+ if (locality !== null) return locality === "loopback";
+
+ // 4. No trusted locality signal → fail closed.
+ return false;
}
/**
diff --git a/src/server/authz/headers.ts b/src/server/authz/headers.ts
index dc5f4f548d..a7a3ec574e 100644
--- a/src/server/authz/headers.ts
+++ b/src/server/authz/headers.ts
@@ -37,6 +37,15 @@ export const CLI_TOKEN_HEADER = "x-omniroute-cli-token";
*/
export const PEER_IP_HEADER = "x-omniroute-peer-ip";
+/**
+ * Trusted locality verdict ("loopback" | "lan" | "remote") that the pipeline
+ * computes from the stamped real peer IP and forwards to route handlers. Route
+ * code (e.g. cliTokenAuth) reads THIS instead of re-deriving locality from the
+ * spoofable Host header. Like the other trusted headers it is stripped from
+ * client input and re-set by the pipeline, so a remote caller cannot forge it.
+ */
+export const AUTHZ_HEADER_PEER_LOCALITY = "x-omniroute-peer-locality";
+
/**
* Headers the pipeline must NEVER trust on incoming requests. They are
* stripped before route classification to prevent header-spoofing attacks.
@@ -47,4 +56,5 @@ export const AUTHZ_TRUSTED_HEADERS: ReadonlyArray<string> = [
AUTHZ_HEADER_AUTH_ID,
AUTHZ_HEADER_AUTH_LABEL,
AUTHZ_HEADER_AUTH_SCOPES,
+ AUTHZ_HEADER_PEER_LOCALITY,
];
diff --git a/src/server/authz/pipeline.ts b/src/server/authz/pipeline.ts
index 4504c3db9e..178ac5dd10 100644
--- a/src/server/authz/pipeline.ts
+++ b/src/server/authz/pipeline.ts
@@ -6,6 +6,8 @@ import { checkBodySize, getBodySizeLimit } from "../../shared/middleware/bodySiz
import { generateRequestId } from "../../shared/utils/requestId";
import { applyCorsHeaders } from "../cors/origins";
import { classifyRoute } from "./classify";
+import { classifyHostLocality } from "./routeGuard";
+import { resolveStampedPeer } from "./peerStamp";
import { clientApiPolicy } from "./policies/clientApi";
import { managementPolicy } from "./policies/management";
import { publicPolicy } from "./policies/public";
@@ -14,6 +16,7 @@ import {
AUTHZ_HEADER_AUTH_KIND,
AUTHZ_HEADER_AUTH_LABEL,
AUTHZ_HEADER_AUTH_SCOPES,
+ AUTHZ_HEADER_PEER_LOCALITY,
AUTHZ_HEADER_REQUEST_ID,
AUTHZ_HEADER_ROUTE_CLASS,
AUTHZ_TRUSTED_HEADERS,
@@ -236,6 +239,16 @@ export async function runAuthzPipeline(
requestHeaders.set(AUTHZ_HEADER_ROUTE_CLASS, classification.routeClass);
requestHeaders.set(AUTHZ_HEADER_REQUEST_ID, requestId);
+ // Stamp a trusted, non-secret locality verdict derived from the real stamped
+ // peer IP. Route handlers (e.g. cliTokenAuth) read this instead of re-deriving
+ // locality from the spoofable Host header. The client-supplied value (if any)
+ // was already removed by the AUTHZ_TRUSTED_HEADERS strip above.
+ requestHeaders.set(
+ AUTHZ_HEADER_PEER_LOCALITY,
+ classifyHostLocality(
+ resolveStampedPeer(request.headers.get(PEER_IP_HEADER), process.env.OMNIROUTE_PEER_STAMP_TOKEN)
+ )
+ );
if (method === "OPTIONS") {
const preflight = new NextResponse(null, { status: 204 });
diff --git a/src/server/authz/routeGuard.ts b/src/server/authz/routeGuard.ts
index 44ec9409cf..2c3f998201 100644
--- a/src/server/authz/routeGuard.ts
+++ b/src/server/authz/routeGuard.ts
@@ -76,19 +76,34 @@ export const ALWAYS_PROTECTED_API_PATHS: ReadonlyArray<string> = [
export function isLoopbackHost(hostHeader: string | null): boolean {
if (!hostHeader) return false;
- let host: string;
- if (hostHeader.startsWith("[")) {
+ let host = hostHeader.trim();
+ if (host.startsWith("[")) {
// IPv6 literal: [::1] or [::1]:port
- const bracketEnd = hostHeader.indexOf("]");
- host = bracketEnd >= 0 ? hostHeader.slice(1, bracketEnd) : hostHeader.slice(1);
- } else {
- // IPv4 / hostname: strip optional :port
- host = hostHeader.split(":")[0];
+ const bracketEnd = host.indexOf("]");
+ host = bracketEnd >= 0 ? host.slice(1, bracketEnd) : host.slice(1);
+ } else if ((host.match(/:/g) || []).length === 1) {
+ // IPv4 / hostname with a single :port — strip it. A bare IPv6 address
+ // ("::1", "::ffff:127.0.0.1") has multiple colons and must stay intact
+ // (splitting on ":" would mangle it to "" and miss the loopback match).
+ host = host.split(":")[0];
}
host = host.replace(/^::ffff:/i, "");
return LOOPBACK_HOSTS.has(host.toLowerCase());
}
+/**
+ * Classify a resolved peer IP into the locality tiers the authz layer cares
+ * about. `null`/unknown → "remote" (fail closed). Used by the pipeline to stamp
+ * a trusted locality marker that route handlers read without re-deriving it
+ * from the spoofable Host header.
+ */
+export function classifyHostLocality(ip: string | null): "loopback" | "lan" | "remote" {
+ if (!ip) return "remote";
+ if (isLoopbackHost(ip)) return "loopback";
+ if (isPrivateLanHost(ip)) return "lan";
+ return "remote";
+}
+
/**
* Private-LAN ranges (RFC 1918 IPv4 + IPv6 ULA/link-local). Matched against the
* real socket peer address (NOT the spoofable Host header), so a public-internet
diff --git a/tests/unit/cli-machine-token.test.ts b/tests/unit/cli-machine-token.test.ts
index 631c71df08..8b8d6f762a 100644
--- a/tests/unit/cli-machine-token.test.ts
+++ b/tests/unit/cli-machine-token.test.ts
@@ -91,3 +91,21 @@ test("OMNIROUTE_DISABLE_CLI_TOKEN desabilita auth (estrutura verificada)", async
const src = readFileSync(join(dir, "../../src/lib/middleware/cliTokenAuth.ts"), "utf8");
assert.ok(src.includes("OMNIROUTE_DISABLE_CLI_TOKEN"));
});
+
+test("cliTokenAuth must NOT derive loopback from the spoofable Host header", async () => {
+ const { readFileSync } = await import("node:fs");
+ const { join, dirname } = await import("node:path");
+ const { fileURLToPath } = await import("node:url");
+ const dir = dirname(fileURLToPath(import.meta.url));
+ const src = readFileSync(join(dir, "../../src/lib/middleware/cliTokenAuth.ts"), "utf8");
+ // Regression guard: a remote caller with a stolen CLI token could send
+ // Host: 127.0.0.1 if locality came from new URL(request.url).hostname.
+ assert.ok(
+ !/isLoopback\(\s*new URL\(request\.url\)\.hostname/.test(src),
+ "must not call isLoopback(new URL(request.url).hostname)"
+ );
+ assert.ok(
+ src.includes("AUTHZ_HEADER_PEER_LOCALITY"),
+ "must trust the middleware-stamped locality verdict instead"
+ );
+});
diff --git a/tests/unit/route-guard-private-lan.test.ts b/tests/unit/route-guard-private-lan.test.ts
index c8e7c9df06..fd2fc97d51 100644
--- a/tests/unit/route-guard-private-lan.test.ts
+++ b/tests/unit/route-guard-private-lan.test.ts
@@ -2,7 +2,12 @@ import test from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { join } from "node:path";
-import { isPrivateLanHost, isLoopbackHost, isLocalOnlyPath } from "../../src/server/authz/routeGuard.ts";
+import {
+ isPrivateLanHost,
+ isLoopbackHost,
+ isLocalOnlyPath,
+ classifyHostLocality,
+} from "../../src/server/authz/routeGuard.ts";
import { resolveStampedPeer } from "../../src/server/authz/peerStamp.ts";
test("isPrivateLanHost: accepts RFC1918 IPv4 (incl. :port and ::ffff: mapped)", () => {
@@ -38,10 +43,27 @@ test("isPrivateLanHost: rejects public IPs, loopback and junk", () => {
}
});
-test("isLoopbackHost stays loopback-only (unchanged)", () => {
+test("isLoopbackHost: IPv4, hostname:port, bracketed + bare IPv6, ::ffff: mapped", () => {
assert.equal(isLoopbackHost("127.0.0.1"), true);
assert.equal(isLoopbackHost("localhost:20128"), true);
+ // Bare IPv6 loopback forms that socket.remoteAddress produces on dual-stack
+ // (regression: split(":")[0] previously mangled these to "" → false → DoS).
+ assert.equal(isLoopbackHost("::1"), true);
+ assert.equal(isLoopbackHost("::ffff:127.0.0.1"), true);
+ assert.equal(isLoopbackHost("[::1]:20128"), true);
assert.equal(isLoopbackHost("192.168.0.15"), false);
+ assert.equal(isLoopbackHost("8.8.8.8"), false);
+});
+
+test("classifyHostLocality: loopback / lan / remote, with fail-closed null", () => {
+ assert.equal(classifyHostLocality("127.0.0.1"), "loopback");
+ assert.equal(classifyHostLocality("::1"), "loopback");
+ assert.equal(classifyHostLocality("::ffff:127.0.0.1"), "loopback");
+ assert.equal(classifyHostLocality("192.168.0.15"), "lan");
+ assert.equal(classifyHostLocality("::ffff:192.168.1.20"), "lan");
+ assert.equal(classifyHostLocality("8.8.8.8"), "remote");
+ assert.equal(classifyHostLocality("69.164.221.35"), "remote");
+ assert.equal(classifyHostLocality(null), "remote", "unknown peer must fail closed");
});
test("services + traffic-inspector remain LOCAL_ONLY paths", () => {