Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(mcp-oauth): keep discovery fetches off this machine and cap reads
KunjShah952898b40761e3
diff --git a/server/mcp-oauth-discovery.test.ts b/server/mcp-oauth-discovery.test.tsindex 3dc9d16d5a..80f0c942bb 100644--- a/server/mcp-oauth-discovery.test.ts+++ b/server/mcp-oauth-discovery.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { discoverMcpAuth, isAllowedAuthUrl, resourceMetadataUrl } from "./mcp-oauth-discovery.ts";+import { discoverMcpAuth, isAllowedAuthUrl, isAllowedDiscoveryUrl, resourceMetadataUrl } from "./mcp-oauth-discovery.ts";const AS = {issuer: "https://auth.example.com",@@ -121,6 +121,66 @@ describe("discoverMcpAuth", () => {const { impl } = stubFetch({});expect(await discoverMcpAuth("https://mcp.example.com/mcp", null, { fetch: impl })).toBeNull();});++ it("stops reading a metadata document past the cap", async () => {+ const impl = (async () => new Response("x".repeat(70_000), { status: 200 })) as typeof fetch;+ expect(await discoverMcpAuth("https://mcp.example.com/mcp", null, { fetch: impl })).toBeNull();+ });++ it.each([+ "http://127.0.0.1:8799/api/health",+ "http://localhost:5000/prm",+ "http://[::1]:5000/prm",+ "https://10.0.0.5/prm",+ "https://169.254.169.254/latest/meta-data",+ "https://[fd00:ec2::254]/prm",+ "https://metadata.google.internal/prm",+ ])("never follows a remote metadata hint to %s", async (hint) => {+ const { impl, asked } = stubFetch({});+ const meta = await discoverMcpAuth("https://mcp.example.com/mcp", `Bearer resource_metadata="${hint}"`, { fetch: impl });+ expect(meta).toBeNull();+ expect(asked).not.toContain(hint);+ });++ it("refuses an authorization server on this machine named by a public MCP server", async () => {+ const { impl, asked } = stubFetch({+ "https://mcp.example.com/.well-known/oauth-protected-resource": { authorization_servers: ["http://127.0.0.1:8799"] },+ });+ expect(await discoverMcpAuth("https://mcp.example.com/mcp", null, { fetch: impl })).toBeNull();+ expect(asked.some((url) => url.startsWith("http://127.0.0.1:8799"))).toBe(false);+ });++ it("refuses private endpoints named by a public authorization server", async () => {+ const { impl } = stubFetch({+ "https://mcp.example.com/.well-known/oauth-protected-resource": { authorization_servers: ["https://auth.example.com"] },+ "https://auth.example.com/.well-known/oauth-authorization-server": { ...AS, token_endpoint: "https://127.0.0.1:9000/token" },+ });+ expect(await discoverMcpAuth("https://mcp.example.com/mcp", null, { fetch: impl })).toBeNull();+ });++ it("still discovers a loopback MCP server's own endpoints", async () => {+ const local = { ...AS, issuer: "http://127.0.0.1:5000", authorization_endpoint: "http://127.0.0.1:5000/authorize", token_endpoint: "http://127.0.0.1:5000/token" };+ const { impl } = stubFetch({+ "http://127.0.0.1:5000/.well-known/oauth-protected-resource": { authorization_servers: ["http://127.0.0.1:5000"] },+ "http://127.0.0.1:5000/.well-known/oauth-authorization-server": local,+ });+ const meta = await discoverMcpAuth("http://127.0.0.1:5000/mcp", null, { fetch: impl });+ expect(meta?.tokenEndpoint).toBe("http://127.0.0.1:5000/token");+ });+});++describe("isAllowedDiscoveryUrl", () => {+ it("trusts a local MCP server with this machine's other ports, and a remote one with public HTTPS only", () => {+ expect(isAllowedDiscoveryUrl("http://127.0.0.1:5000/prm", "http://127.0.0.1:5000")).toBe(true);+ expect(isAllowedDiscoveryUrl("http://127.0.0.1:9000/prm", "http://127.0.0.1:5000")).toBe(true);+ expect(isAllowedDiscoveryUrl("https://10.0.0.5/prm", "https://10.0.0.5")).toBe(true);+ expect(isAllowedDiscoveryUrl("http://127.0.0.1:5000/prm", "https://mcp.example.com")).toBe(false);+ expect(isAllowedDiscoveryUrl("https://10.0.0.5/prm", "https://mcp.example.com")).toBe(false);+ expect(isAllowedDiscoveryUrl("https://169.254.169.254/prm", "https://mcp.example.com")).toBe(false);+ expect(isAllowedDiscoveryUrl("https://localhost/prm", "https://mcp.example.com")).toBe(false);+ expect(isAllowedDiscoveryUrl("https://auth.example.com/prm", "https://mcp.example.com")).toBe(true);+ expect(isAllowedDiscoveryUrl("https://user:[email protected]/prm", "https://mcp.example.com")).toBe(false);+ });});describe("isAllowedAuthUrl", () => {diff --git a/server/mcp-oauth-discovery.ts b/server/mcp-oauth-discovery.tsindex 04ec0c0cbb..072dc1ecf0 100644--- a/server/mcp-oauth-discovery.ts+++ b/server/mcp-oauth-discovery.ts@@ -1,4 +1,7 @@// Never follows a redirect or accepts a plain-http endpoint off this machine: a token endpoint is where a sign-in code is spent.+import { isIP } from "node:net";++import { isPublicDomainAddress } from "./custom-domain.ts";export interface McpAuthMetadata {issuer: string;@@ -21,6 +24,8 @@ const FETCH_TIMEOUT_MS = 5_000;const MAX_METADATA_BYTES = 65_536;const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "[::1]"]);+/** Scheme-only rule for a URL the owner configured or a browser opens. Discovery uses `isAllowedDiscoveryUrl` below,+ * because its URLs come from a remote server's response. */export function isAllowedAuthUrl(value: string): boolean {let url: URL;try {@@ -33,6 +38,47 @@ export function isAllowedAuthUrl(value: string): boolean {return url.protocol === "http:" && LOOPBACK_HOSTS.has(url.hostname);}+/** `.local`, `.internal` and the like name this machine's network on some resolver, so a remote document must not aim a+ * fetch there. A public name is otherwise let through: TLS still has to prove the host before any body is read. */+const LOCAL_SUFFIX = /(?:^|\.)(?:localhost|local|internal|lan|home|ts\.net|invalid)$/i;++/**+ * Whether a URL in OAuth discovery may be fetched. Only the MCP server's own origin (the URL the owner configured) is+ * trusted with loopback, private or plain-http addresses; metadata and endpoints it names are remote input, so they must+ * be public HTTPS. Without this a malicious MCP server's `WWW-Authenticate: resource_metadata="http://127.0.0.1:…"` would+ * make the harness call this machine's anonymous loopback surface.+ */+export function isAllowedDiscoveryUrl(value: string, trustedOrigin: string): boolean {+ let url: URL;+ try {+ url = new URL(value);+ } catch {+ return false;+ }+ if (url.username || url.password) return false;+ if (url.protocol !== "https:" && url.protocol !== "http:") return false;+ if (url.origin === trustedOrigin) return true;+ let trusted: URL;+ try {+ trusted = new URL(trustedOrigin);+ } catch {+ return false;+ }+ // A local MCP server may name a sign-in server on another loopback port: both are code the owner installed here.+ if (isLoopbackName(trusted.hostname) && isLoopbackName(url.hostname)) return true;+ if (url.protocol !== "https:") return false;+ const host = url.hostname.replace(/^\[|\]$/gu, "").replace(/\.$/u, "").toLowerCase();+ if (isIP(host)) return isPublicDomainAddress(host);+ return host.includes(".") && !LOCAL_SUFFIX.test(host);+}++function isLoopbackName(hostname: string): boolean {+ const host = hostname.replace(/^\[|\]$/gu, "").replace(/\.$/u, "").toLowerCase();+ if (host === "localhost") return true;+ if (isIP(host) === 4) return host.startsWith("127.");+ return isIP(host) === 6 && (host === "::1" || host === "0:0:0:0:0:0:0:1");+}+export function resourceMetadataUrl(wwwAuthenticate: string | null): string | null {if (!wwwAuthenticate) return null;const match = /resource_metadata\s*=\s*(?:"([^"]*)"|([^\s,]+))/i.exec(wwwAuthenticate);@@ -45,8 +91,8 @@ interface DiscoverOptions {signal?: AbortSignal;}-async function getJson(url: string, options: DiscoverOptions): Promise<Record<string, unknown> | null> {- if (!isAllowedAuthUrl(url)) return null;+async function getJson(url: string, trustedOrigin: string, options: DiscoverOptions): Promise<Record<string, unknown> | null> {+ if (!isAllowedDiscoveryUrl(url, trustedOrigin)) return null;const timeout = AbortSignal.timeout(FETCH_TIMEOUT_MS);const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;try {@@ -55,9 +101,23 @@ async function getJson(url: string, options: DiscoverOptions): Promise<Record<stvoid response.body?.cancel().catch(() => {});return null;}- const text = await response.text();- if (text.length > MAX_METADATA_BYTES) return null;- const parsed: unknown = JSON.parse(text);+ // A server named by metadata is remote: read at most the cap, never buffer whatever it decides to send.+ const reader = response.body?.getReader();+ if (!reader) return null;+ const chunks: Uint8Array[] = [];+ let size = 0;+ try {+ for (;;) {+ const { done, value } = await reader.read();+ if (done) break;+ size += value.byteLength;+ if (size > MAX_METADATA_BYTES) return null;+ chunks.push(value);+ }+ } finally {+ await reader.cancel().catch(() => {});+ }+ const parsed: unknown = JSON.parse(Buffer.concat(chunks).toString("utf8"));return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed as Record<string, unknown> : null;} catch {return null;@@ -68,7 +128,7 @@ function stringList(value: unknown): string[] | undefined {return Array.isArray(value) && value.every((entry) => typeof entry === "string") ? value as string[] : undefined;}-async function protectedResource(mcpUrl: URL, hint: string | null, options: DiscoverOptions) {+async function protectedResource(mcpUrl: URL, hint: string | null, trustedOrigin: string, options: DiscoverOptions) {const path = mcpUrl.pathname === "/" ? "" : mcpUrl.pathname;const candidates = [...(hint ? [hint] : []),@@ -76,13 +136,13 @@ async function protectedResource(mcpUrl: URL, hint: string | null, options: Disc`${mcpUrl.origin}/.well-known/oauth-protected-resource`,];for (const candidate of new Set(candidates)) {- const document = await getJson(candidate, options);+ const document = await getJson(candidate, trustedOrigin, options);if (document) return document;}return null;}-async function authorizationServer(issuer: string, options: DiscoverOptions) {+async function authorizationServer(issuer: string, trustedOrigin: string, options: DiscoverOptions) {const base = issuer.replace(/\/+$/, "");const url = new URL(base);const suffix = url.pathname === "/" ? "" : url.pathname;@@ -92,7 +152,7 @@ async function authorizationServer(issuer: string, options: DiscoverOptions) {...(suffix ? [`${base}/.well-known/openid-configuration`] : []),];for (const candidate of candidates) {- const document = await getJson(candidate, options);+ const document = await getJson(candidate, trustedOrigin, options);if (document) return document;}return null;@@ -109,23 +169,24 @@ export async function discoverMcpAuth(} catch {return null;}- const resource = await protectedResource(target, resourceMetadataUrl(wwwAuthenticate), options);+ const trustedOrigin = target.origin;+ const resource = await protectedResource(target, resourceMetadataUrl(wwwAuthenticate), trustedOrigin, options);const servers = stringList(resource?.authorization_servers);const named = servers?.[0];const issuer = named ?? target.origin;- if (!isAllowedAuthUrl(issuer)) return null;- const metadata = await authorizationServer(issuer, options);+ if (!isAllowedDiscoveryUrl(issuer, trustedOrigin)) return null;+ const metadata = await authorizationServer(issuer, trustedOrigin, options);if (!metadata) return null;const authorizationEndpoint = metadata.authorization_endpoint;const tokenEndpoint = metadata.token_endpoint;- if (typeof authorizationEndpoint !== "string" || !isAllowedAuthUrl(authorizationEndpoint)) return null;- if (typeof tokenEndpoint !== "string" || !isAllowedAuthUrl(tokenEndpoint)) return null;+ if (typeof authorizationEndpoint !== "string" || !isAllowedDiscoveryUrl(authorizationEndpoint, trustedOrigin)) return null;+ if (typeof tokenEndpoint !== "string" || !isAllowedDiscoveryUrl(tokenEndpoint, trustedOrigin)) return null;if (!stringList(metadata.code_challenge_methods_supported)?.includes("S256")) return null;// RFC 8414 §3.3: the metadata must be for the issuer it was fetched for.if (typeof metadata.issuer === "string" && metadata.issuer.replace(/\/+$/, "") !== issuer.replace(/\/+$/, "")) return null;- const optionalEndpoint = (value: unknown) => typeof value === "string" && isAllowedAuthUrl(value) ? value : undefined;+ const optionalEndpoint = (value: unknown) => typeof value === "string" && isAllowedDiscoveryUrl(value, trustedOrigin) ? value : undefined;const registrationEndpoint = optionalEndpoint(metadata.registration_endpoint);const revocationEndpoint = optionalEndpoint(metadata.revocation_endpoint);const scopes = stringList(resource?.scopes_supported);