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

feat(authz): add 3-tier route guard (local-only + always-protected)

diegosouzapw8dcc21476bac
diff --git a/src/server/authz/policies/management.ts b/src/server/authz/policies/management.ts
index e14abb5df4..63892b88b3 100644
--- a/src/server/authz/policies/management.ts
+++ b/src/server/authz/policies/management.ts
@@ -4,16 +4,12 @@ import { getMachineTokenSync } from "../../../lib/machineToken";
import type { AuthOutcome, PolicyContext, RoutePolicy } from "../context";
import { allow, reject } from "../context";
import { CLI_TOKEN_HEADER } from "../headers";
+import { isAlwaysProtectedPath, isLocalOnlyPath, isLoopbackHost } from "../routeGuard";
const MODEL_SYNC_MANAGEMENT_PATH = /^\/api\/providers\/[^/]+\/(sync-models|models)$/;
-const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "::1"]);
function isLoopbackRequest(headers: Headers): boolean {
- const host = (headers.get("host") ?? "")
- .split(":")[0]
- .replace(/^\[|\]$/g, "")
- .toLowerCase();
- return LOOPBACK_HOSTS.has(host);
+ return isLoopbackHost(headers.get("host"));
}
function hasValidCliToken(headers: Headers): boolean {
@@ -37,8 +33,13 @@ function isInternalModelSyncRequest(ctx: PolicyContext): boolean {
export const managementPolicy: RoutePolicy = {
routeClass: "MANAGEMENT",
async evaluate(ctx: PolicyContext): Promise<AuthOutcome> {
- if (!(await isAuthRequired(ctx.request))) {
- return allow({ kind: "anonymous", id: "anonymous", label: "auth-disabled" });
+ const path = ctx.classification.normalizedPath;
+
+ // Tier 1: local-only gate — block spawn-capable routes from non-loopback.
+ if (isLocalOnlyPath(path)) {
+ if (!isLoopbackRequest(ctx.request.headers)) {
+ return reject(403, "LOCAL_ONLY", "This endpoint requires localhost access");
+ }
}
if (isInternalModelSyncRequest(ctx)) {
@@ -49,6 +50,11 @@ export const managementPolicy: RoutePolicy = {
return allow({ kind: "management_key", id: "cli", label: "local-cli-token" });
}
+ // Tier 2: always-protected routes skip the requireLogin=false bypass.
+ if (!isAlwaysProtectedPath(path) && !(await isAuthRequired(ctx.request))) {
+ return allow({ kind: "anonymous", id: "anonymous", label: "auth-disabled" });
+ }
+
if (await isDashboardSessionAuthenticated(ctx.request)) {
return allow({ kind: "dashboard_session", id: "dashboard" });
}
diff --git a/src/server/authz/routeGuard.ts b/src/server/authz/routeGuard.ts
new file mode 100644
index 0000000000..d746f74fa9
--- /dev/null
+++ b/src/server/authz/routeGuard.ts
@@ -0,0 +1,47 @@
+/**
+ * 3-tier route guard constants and helpers.
+ *
+ * Tier 1 — LOCAL_ONLY: accessible only from loopback. These routes spawn
+ * child processes; exposing them to non-local traffic is a known CVE class
+ * (GHSA-fhh6-4qxv-rpqj). Blocked unconditionally regardless of auth state.
+ *
+ * Tier 2 — ALWAYS_PROTECTED: auth is always required, even when
+ * requireLogin=false. Covers destructive / irreversible operations.
+ *
+ * Tier 3 — MANAGEMENT (default): auth required, but bypassed when
+ * requireLogin=false (existing behaviour).
+ */
+
+const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "::1"]);
+
+export const LOCAL_ONLY_API_PREFIXES: ReadonlyArray<string> = [
+ "/api/mcp/",
+ "/api/cli-tools/runtime/",
+];
+
+export const ALWAYS_PROTECTED_API_PATHS: ReadonlyArray<string> = [
+ "/api/shutdown",
+ "/api/settings/database",
+];
+
+export function isLoopbackHost(hostHeader: string | null): boolean {
+ if (!hostHeader) return false;
+ let host: string;
+ if (hostHeader.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];
+ }
+ return LOOPBACK_HOSTS.has(host.toLowerCase());
+}
+
+export function isLocalOnlyPath(path: string): boolean {
+ return LOCAL_ONLY_API_PREFIXES.some((p) => path === p || path.startsWith(p));
+}
+
+export function isAlwaysProtectedPath(path: string): boolean {
+ return ALWAYS_PROTECTED_API_PATHS.some((p) => path === p || path.startsWith(p));
+}
diff --git a/tests/unit/authz/routeGuard.test.ts b/tests/unit/authz/routeGuard.test.ts
new file mode 100644
index 0000000000..d9af73e666
--- /dev/null
+++ b/tests/unit/authz/routeGuard.test.ts
@@ -0,0 +1,87 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ isLocalOnlyPath,
+ isAlwaysProtectedPath,
+ isLoopbackHost,
+} from "../../../src/server/authz/routeGuard.ts";
+import { managementPolicy } from "../../../src/server/authz/policies/management.ts";
+import { getMachineTokenSync } from "../../../src/lib/machineToken.ts";
+import { CLI_TOKEN_HEADER } from "../../../src/server/authz/headers.ts";
+
+// ─── routeGuard helpers ────────────────────────────────────────────────────
+
+test("isLocalOnlyPath: /api/mcp/ prefix is local-only", () => {
+ assert.equal(isLocalOnlyPath("/api/mcp/sse"), true);
+ assert.equal(isLocalOnlyPath("/api/mcp/"), true);
+});
+
+test("isLocalOnlyPath: /api/cli-tools/runtime/ is local-only", () => {
+ assert.equal(isLocalOnlyPath("/api/cli-tools/runtime/claude"), true);
+});
+
+test("isLocalOnlyPath: regular management routes are not local-only", () => {
+ assert.equal(isLocalOnlyPath("/api/settings"), false);
+ assert.equal(isLocalOnlyPath("/api/providers"), false);
+});
+
+test("isAlwaysProtectedPath: /api/shutdown is always protected", () => {
+ assert.equal(isAlwaysProtectedPath("/api/shutdown"), true);
+});
+
+test("isAlwaysProtectedPath: /api/settings/database is always protected", () => {
+ assert.equal(isAlwaysProtectedPath("/api/settings/database"), true);
+});
+
+test("isAlwaysProtectedPath: ordinary settings routes are not always protected", () => {
+ assert.equal(isAlwaysProtectedPath("/api/settings"), false);
+ assert.equal(isAlwaysProtectedPath("/api/settings/proxy"), false);
+});
+
+test("isLoopbackHost: recognises localhost, 127.0.0.1, ::1", () => {
+ assert.equal(isLoopbackHost("localhost"), true);
+ assert.equal(isLoopbackHost("localhost:20128"), true);
+ assert.equal(isLoopbackHost("127.0.0.1"), true);
+ assert.equal(isLoopbackHost("127.0.0.1:3000"), true);
+ assert.equal(isLoopbackHost("[::1]"), true);
+});
+
+test("isLoopbackHost: rejects non-loopback hosts", () => {
+ assert.equal(isLoopbackHost("192.168.1.1"), false);
+ assert.equal(isLoopbackHost("example.com"), false);
+ assert.equal(isLoopbackHost(null), false);
+});
+
+// ─── management policy — local-only gate ──────────────────────────────────
+
+function makeCtx(path: string, headers: Record<string, string>) {
+ return {
+ request: {
+ method: "GET",
+ headers: new Headers(headers),
+ cookies: { get: () => undefined },
+ nextUrl: { pathname: path },
+ url: `http://localhost:20128${path}`,
+ },
+ classification: {
+ routeClass: "MANAGEMENT" as const,
+ normalizedPath: path,
+ method: "GET",
+ },
+ requestId: "test-req",
+ };
+}
+
+test("management policy rejects /api/mcp/ from non-localhost (status 403)", async () => {
+ const ctx = makeCtx("/api/mcp/sse", { host: "evil.tunnel.io" });
+ const outcome = await managementPolicy.evaluate(ctx);
+ assert.equal(outcome.allow, false);
+ if (!outcome.allow) assert.equal(outcome.status, 403);
+});
+
+test("management policy allows /api/mcp/ from localhost with valid CLI token", async () => {
+ const token = getMachineTokenSync();
+ const ctx = makeCtx("/api/mcp/sse", { host: "localhost", [CLI_TOKEN_HEADER]: token });
+ const outcome = await managementPolicy.evaluate(ctx);
+ assert.equal(outcome.allow, true);
+});