Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions packages/opencode/src/mcp/oauth-callback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ import { createConnection } from "net"
import { createServer } from "http"
import { escapeHtml } from "@/util/html"
import { OAUTH_CALLBACK_PORT, OAUTH_CALLBACK_PATH, parseRedirectUri } from "./oauth-provider"
// altimate_change start — upstream_fix: accept MCP OAuth callbacks rewritten from 127.0.0.1 to localhost (anomalyco/opencode#63403)
import { noteCallbackHost, resetCallbackHost } from "./oauth-provider"
// altimate_change end

// Current callback server configuration (may differ from defaults if custom redirectUri is used)
let currentPort = OAUTH_CALLBACK_PORT
Expand Down Expand Up @@ -136,6 +139,9 @@ function handleRequest(req: import("http").IncomingMessage, res: import("http").
clearTimeout(pending.timeout)
pendingAuths.delete(state)
cleanupStateIndex(state)
// altimate_change start — upstream_fix: accept MCP OAuth callbacks rewritten from 127.0.0.1 to localhost (anomalyco/opencode#63403)
noteCallbackHost(currentPort, req.headers.host)
// altimate_change end
pending.resolve(code)

res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" })
Expand Down Expand Up @@ -172,6 +178,9 @@ export async function ensureRunning(redirectUri?: string): Promise<void> {
}

export function waitForCallback(oauthState: string, mcpName?: string): Promise<string> {
// altimate_change start — upstream_fix: accept MCP OAuth callbacks rewritten from 127.0.0.1 to localhost (anomalyco/opencode#63403)
resetCallbackHost(currentPort)
// altimate_change end
if (mcpName) mcpNameToState.set(mcpName, oauthState)
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
Expand Down
31 changes: 29 additions & 2 deletions packages/opencode/src/mcp/oauth-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,25 @@ import { McpAuth } from "./auth"
const OAUTH_CALLBACK_PORT = 19876
const OAUTH_CALLBACK_PATH = "/mcp/oauth/callback"

// altimate_change start — upstream_fix: accept MCP OAuth callbacks rewritten from 127.0.0.1 to localhost (anomalyco/opencode#63403)
// Some authorization servers rewrite a loopback redirect from 127.0.0.1 to localhost. Both hosts are
// registered, and the token exchange uses whichever one the browser actually reached.
const LOOPBACK_HOSTS = ["127.0.0.1", "localhost"] as const
const callbackHosts = new Map<number, (typeof LOOPBACK_HOSTS)[number]>()

/** Record the loopback host (from the request's Host header) a callback arrived on for `port`. */
export function noteCallbackHost(port: number, hostHeader: string | undefined): void {
const host = hostHeader?.replace(/:\d+$/, "").toLowerCase()
const match = LOOPBACK_HOSTS.find((item) => item === host)
if (match) callbackHosts.set(port, match)
}

/** Forget the host a previous flow reached, so a new flow starts from 127.0.0.1. */
export function resetCallbackHost(port: number): void {
callbackHosts.delete(port)
}
// altimate_change end

export interface McpOAuthConfig {
clientId?: string
clientSecret?: string
Expand All @@ -37,12 +56,20 @@ export class McpOAuthProvider implements OAuthClientProvider {
return this.config.redirectUri
}
const port = this.config.callbackPort ?? OAUTH_CALLBACK_PORT
return `http://127.0.0.1:${port}${OAUTH_CALLBACK_PATH}`
// altimate_change start — upstream_fix: accept MCP OAuth callbacks rewritten from 127.0.0.1 to localhost (anomalyco/opencode#63403)
return `http://${callbackHosts.get(port) ?? "127.0.0.1"}:${port}${OAUTH_CALLBACK_PATH}`

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Previous callback host breaks subsequent authorizations

After a localhost callback, beginAuth builds the next default-port authorization URL before waitForCallback resets the host. Another server's cached or pre-registered client accepting only 127.0.0.1 then rejects the localhost redirect. Authorization fails before the callback.

Learn more

The recorded host belongs to a port, not an individual authorization flow, and survives successful completion. In a long-running server, authenticate calls beginAuth before waitForCallback. beginAuth constructs the provider and captures the authorization URL during that earlier call. Resetting the host afterward cannot change the captured URL. clientInformation reuses configured or cached clients without updating their registered redirects.

Example: In one running server, authorize MCP server A whose callback is rewritten to localhost. Then authorize MCP server B with an existing client registered only for http://127.0.0.1:19876/mcp/oauth/callback. B's authorization URL requests localhost using A's recorded host, and B rejects that unregistered redirect before any callback occurs.

Recommended fix: Reset host selection before beginAuth constructs its authorization URL, including the separate startAuth entry point. Prefer keeping the observed callback host on the individual flow/provider rather than sharing it across all providers on a port. Add a sequential integration test covering a localhost callback followed by authorization against a different, previously registered client.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

// altimate_change end
}

get clientMetadata(): OAuthClientMetadata {
// altimate_change start — upstream_fix: accept MCP OAuth callbacks rewritten from 127.0.0.1 to localhost (anomalyco/opencode#63403)
const port = this.config.callbackPort ?? OAUTH_CALLBACK_PORT
const redirectUris = this.config.redirectUri
? [this.config.redirectUri]
: LOOPBACK_HOSTS.map((host) => `http://${host}:${port}${OAUTH_CALLBACK_PATH}`)
// altimate_change end
return {
redirect_uris: [this.redirectUrl],
redirect_uris: redirectUris,
// altimate_change start — branding (was "OpenCode" / "https://opencode.ai")
client_name: "Altimate Code",
client_uri: "https://altimate.ai",
Expand Down
33 changes: 32 additions & 1 deletion packages/opencode/test/mcp/oauth-callback.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
import { test, expect, describe, afterEach } from "bun:test"
import { createServer } from "net"
import { McpOAuthCallback } from "../../src/mcp/oauth-callback"
import { parseRedirectUri } from "../../src/mcp/oauth-provider"
// altimate_change start — upstream_fix: accept MCP OAuth callbacks rewritten from 127.0.0.1 to localhost (anomalyco/opencode#63403)
import {
McpOAuthProvider,
OAUTH_CALLBACK_PATH,
parseRedirectUri,
resetCallbackHost,
} from "../../src/mcp/oauth-provider"
import type { McpAuth } from "../../src/mcp/auth"
// altimate_change end

// altimate_change — find a free loopback port at runtime. The ensureRunning tests previously hardcoded
// ports (18000/18001/…), which collide with whatever else is listening on the dev machine (the server
Expand Down Expand Up @@ -62,6 +70,29 @@ describe("McpOAuthCallback.ensureRunning", () => {
expect(McpOAuthCallback.isRunning()).toBe(false)
})

// altimate_change start — upstream_fix: accept MCP OAuth callbacks rewritten from 127.0.0.1 to localhost (anomalyco/opencode#63403)
test("records a callback that reached localhost so the token exchange uses that redirect", async () => {
const port = await freePort()
await McpOAuthCallback.ensureRunning(`http://127.0.0.1:${port}${OAUTH_CALLBACK_PATH}`)
const provider = new McpOAuthProvider(
"test-server",
"https://mcp.example.com/mcp",
{ callbackPort: port },
{ onRedirect: async () => {} },
{} as McpAuth.Interface,
)
const callback = McpOAuthCallback.waitForCallback("rewritten")
expect(provider.redirectUrl).toBe(`http://127.0.0.1:${port}${OAUTH_CALLBACK_PATH}`)

const response = await fetch(`http://localhost:${port}${OAUTH_CALLBACK_PATH}?code=code&state=rewritten`)

expect(response.status).toBe(200)
expect(await callback).toBe("code")
expect(provider.redirectUrl).toBe(`http://localhost:${port}${OAUTH_CALLBACK_PATH}`)
resetCallbackHost(port)
})
// altimate_change end

test("escapes provider error markup in callback HTML", async () => {
const redirectUri = `http://127.0.0.1:${await freePort()}/custom/callback`
await McpOAuthCallback.ensureRunning(redirectUri)
Expand Down
57 changes: 54 additions & 3 deletions packages/opencode/test/mcp/oauth-provider.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import { test, expect, describe } from "bun:test"
import { McpOAuthProvider, OAUTH_CALLBACK_PORT, OAUTH_CALLBACK_PATH } from "../../src/mcp/oauth-provider"
import {
McpOAuthProvider,
OAUTH_CALLBACK_PORT,
OAUTH_CALLBACK_PATH,
noteCallbackHost,
resetCallbackHost,
} from "../../src/mcp/oauth-provider"
import type { McpAuth } from "../../src/mcp/auth"

// Stub auth — only synchronous getters are exercised in these tests
Expand Down Expand Up @@ -34,11 +40,21 @@ describe("McpOAuthProvider.redirectUrl", () => {
})

describe("McpOAuthProvider.clientMetadata", () => {
test("includes redirect_uris from redirectUrl", () => {
// altimate_change start — upstream_fix: accept MCP OAuth callbacks rewritten from 127.0.0.1 to localhost (anomalyco/opencode#63403)
test("registers both loopback hosts for the default callback", () => {
const provider = makeProvider({ callbackPort: 6620 })
expect(provider.clientMetadata.redirect_uris).toEqual([`http://127.0.0.1:6620${OAUTH_CALLBACK_PATH}`])
expect(provider.clientMetadata.redirect_uris).toEqual([
`http://127.0.0.1:6620${OAUTH_CALLBACK_PATH}`,
`http://localhost:6620${OAUTH_CALLBACK_PATH}`,
])
})

test("registers only an explicit redirectUri", () => {
const provider = makeProvider({ redirectUri: "http://127.0.0.1:9999/custom/callback" })
expect(provider.clientMetadata.redirect_uris).toEqual(["http://127.0.0.1:9999/custom/callback"])
})
// altimate_change end

test("includes scope when set in config", () => {
const provider = makeProvider({ scope: "openid offline_access" })
expect(provider.clientMetadata.scope).toBe("openid offline_access")
Expand All @@ -59,3 +75,38 @@ describe("McpOAuthProvider.clientMetadata", () => {
expect(provider.clientMetadata.token_endpoint_auth_method).toBe("none")
})
})

// altimate_change start — upstream_fix: accept MCP OAuth callbacks rewritten from 127.0.0.1 to localhost (anomalyco/opencode#63403)
describe("McpOAuthProvider.redirectUrl after a callback", () => {
test("uses the loopback host the callback actually reached", () => {
const provider = makeProvider({ callbackPort: 6621 })
try {
noteCallbackHost(6621, "localhost:6621")
expect(provider.redirectUrl).toBe(`http://localhost:6621${OAUTH_CALLBACK_PATH}`)
noteCallbackHost(6621, "127.0.0.1:6621")
expect(provider.redirectUrl).toBe(`http://127.0.0.1:6621${OAUTH_CALLBACK_PATH}`)
} finally {
resetCallbackHost(6621)
}
})

test("ignores non-loopback hosts and explicit redirectUri", () => {
try {
noteCallbackHost(6622, "evil.example.com:6622")
expect(makeProvider({ callbackPort: 6622 }).redirectUrl).toBe(`http://127.0.0.1:6622${OAUTH_CALLBACK_PATH}`)
noteCallbackHost(6622, "localhost:6622")
expect(makeProvider({ callbackPort: 6622, redirectUri: "http://127.0.0.1:6622/cb" }).redirectUrl).toBe(
"http://127.0.0.1:6622/cb",
)
} finally {
resetCallbackHost(6622)
}
})

test("a new flow starts from 127.0.0.1 again", () => {
noteCallbackHost(6623, "localhost:6623")
resetCallbackHost(6623)
expect(makeProvider({ callbackPort: 6623 }).redirectUrl).toBe(`http://127.0.0.1:6623${OAUTH_CALLBACK_PATH}`)
})
})
// altimate_change end
Loading