Skip to content
Merged
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
1 change: 1 addition & 0 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -576,6 +576,7 @@ explicitly to one of `http`, `sse`, or `streamable-http`.
| `client_id` | string | No | OAuth client ID (uses Dynamic Client Registration if empty) |
| `client_secret` | string | No | OAuth client secret (can reference secure storage) |
| `redirect_uri` | string | No | Pins the loopback callback URL (auto-allocated if not provided) |
| `callback_base_url` | string | No | Explicit HTTPS origin for remote Web UI callbacks at `/oauth/callback/<server-name>`; loopback remains the default |
| `scopes` | array | No | OAuth scopes to request |
| `pkce_enabled` | boolean | No | PKCE is always enabled for security; this flag is currently ignored |
| `authorization_endpoint` | string | No | Overrides the authorization endpoint the authorization server advertises (see [Overriding OAuth discovery](#overriding-oauth-discovery)) |
Expand Down
42 changes: 42 additions & 0 deletions docs/features/oauth-authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,48 @@ mcpproxy upstream logs github-server --tail 50

## Troubleshooting

### Signing in through a remote Web UI

When MCPProxy runs on a headless host, the Web UI opens the authorization URL
in the browser where you clicked **Log in**. A blocked popup leaves a clickable
sign-in link; the proxy's API key is never placed in that URL.

OAuth's default loopback callback reaches the browser's machine, which may be
different from the proxy host. To finish sign-in without an SSH port forward,
serve MCPProxy's HTTP listener through an HTTPS reverse proxy (including
Tailscale Serve), and set the upstream's `oauth.callback_base_url` to that
external origin:

```json
{
"name": "linear",
"url": "https://mcp.linear.app/mcp",
"protocol": "http",
"oauth": {
"callback_base_url": "https://proxy.example.ts.net:8447"
}
}
```

The provider receives `https://proxy.example.ts.net:8447/oauth/callback/linear`
as its redirect URI. Forward that path to the main MCPProxy HTTP listener, just
like `/ui/` and `/api/`. Static OAuth clients must register this exact callback
URL with their provider; dynamically registered clients are re-registered when
their saved redirect URI changes. The provider must permit HTTPS callbacks.

`callback_base_url` accepts an HTTPS origin with no credentials, path, query or
fragment. It is explicit configuration, never inferred from request headers.
Only upstreams opting into it accept remote callbacks, validated against their
existing single-use state and PKCE flow. The callback needs no API key and does
not start an OAuth flow; missing, expired, reused and cross-server states fail.
Callback responses disable caching and referrer disclosure.

Leave `HEADLESS=true` on a remote host: the Web UI opens the user's browser;
turning off headless mode only attempts to open a browser on the proxy host.
Without `callback_base_url`, loopback callbacks behave as before. A configured
`redirect_uri` continues to pin the private loopback listener; the external
callback takes precedence for provider registration and token exchange.

### Browser Doesn't Open

```bash
Expand Down
10 changes: 6 additions & 4 deletions frontend/src/components/ServerCard.vue
Original file line number Diff line number Diff line change
Expand Up @@ -695,11 +695,13 @@ async function restart() {
async function triggerOAuth() {
loading.value = true
try {
await serversStore.triggerOAuthLogin(props.server.name)
const result = await serversStore.triggerOAuthLogin(props.server.name)
systemStore.addToast({
type: 'success',
title: 'OAuth Login Triggered',
message: `Check your browser for ${props.server.name} login`,
type: result.browser_opened ? 'info' : 'warning',
title: result.browser_opened ? 'Sign-in opened' : 'Open the sign-in page',
message: result.browser_opened ? `Finish signing in to ${props.server.name} in your browser.` : 'Your browser blocked the new tab. Use the link below to continue.',
link: result.auth_url ? { url: result.auth_url, label: `Sign in to ${props.server.name}` } : undefined,
duration: result.browser_opened ? 10000 : 0,
})
} catch (error) {
systemStore.addToast({
Expand Down
1 change: 1 addition & 0 deletions frontend/src/components/ToastContainer.vue
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@
v-if="toast.message"
class="text-sm opacity-90 whitespace-pre-wrap break-words max-w-md max-h-60 overflow-y-auto"
>{{ toast.message }}</div>
<a v-if="toast.link" :href="toast.link.url" target="_blank" rel="noopener noreferrer" class="link font-semibold">{{ toast.link.label }}</a>
</div>

<!-- Close button -->
Expand Down
13 changes: 2 additions & 11 deletions frontend/src/stores/servers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { ref, computed } from 'vue'
import type { Server, LoadingState } from '@/types'
import api from '@/services/api'
import { isServerConnected } from '@/utils/health'
import { openOAuthLogin } from '@/utils/oauthLogin'

export const useServersStore = defineStore('servers', () => {
// State
Expand Down Expand Up @@ -276,17 +277,7 @@ export const useServersStore = defineStore('servers', () => {
}

async function triggerOAuthLogin(serverName: string) {
try {
const response = await api.triggerOAuthLogin(serverName)
if (response.success) {
return true
} else {
throw new Error(response.error || 'Failed to trigger OAuth login')
}
} catch (error) {
console.error('Failed to trigger OAuth login:', error)
throw error
}
return openOAuthLogin(() => api.triggerOAuthLogin(serverName))
}

async function triggerOAuthLogout(serverName: string) {
Expand Down
1 change: 1 addition & 0 deletions frontend/src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ export interface Toast {
title: string
message?: string
duration?: number
link?: { url: string; label: string }
}

// Component prop types
Expand Down
64 changes: 64 additions & 0 deletions frontend/src/utils/oauthLogin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
export interface OAuthLoginResult {
browser_opened: boolean
auth_url?: string
browser_error?: string
}

export interface OAuthLoginOptions {
// True when the daemon's host browser is NOT the user's browser (the UI is
// served through Tailscale, a LAN address, or a container port mapping).
remote: boolean
}

// The login endpoint opens a browser on the DAEMON's host. That is the user's
// browser only when the Web UI is served from a loopback address; anywhere
// else the page must open the sign-in URL itself.
export function uiIsRemote(loc: { hostname: string } = window.location): boolean {
const host = loc.hostname.replace(/^\[|\]$/g, '').toLowerCase()
return !(host === 'localhost' || host === '127.0.0.1' || host === '::1' || host.endsWith('.localhost'))
}

// A remote UI reserves a tab during the user's click, before the API request
// loses the browser's user activation. A local UI leaves the daemon's own
// browser launch alone — reserving a tab there would open the sign-in page
// twice — and only opens a tab itself when the daemon could not.
export async function openOAuthLogin(
request: () => Promise<{ success: boolean; data?: OAuthLoginResult; error?: string }>,
options: OAuthLoginOptions = { remote: uiIsRemote() },
): Promise<OAuthLoginResult> {
const popup = options.remote ? window.open('about:blank', '_blank') : null
if (popup) popup.opener = null
try {
const response = await request()
if (!response.success) throw new Error(response.error || 'Failed to start sign-in')
const result = response.data
if (!result) throw new Error('The server returned no sign-in details')
if (result.auth_url) {
const url = new URL(result.auth_url)
if (!['https:', 'http:'].includes(url.protocol)) throw new Error('The server returned an invalid sign-in URL')
if (popup && !popup.closed) {
popup.location.replace(url.href)
return { ...result, browser_opened: true }
}
if (!options.remote && result.browser_opened) return result
if (!options.remote) {
// HEADLESS, Docker or no xdg-open: the daemon could not open a
// browser. The click is usually still recent enough for a popup; a
// blocked one leaves the persistent toast link.
const late = window.open(url.href, '_blank')
if (late) late.opener = null
return { ...result, browser_opened: !!late }
}
return { ...result, browser_opened: false }
}
if (!result.browser_opened) throw new Error(result.browser_error || 'No sign-in URL was returned')
// browser_opened describes the daemon's host browser, which a remote UI
// cannot see; without a URL there is nothing to open here.
if (options.remote) throw new Error('The server did not return a sign-in URL for this browser')
popup?.close()
return result
} catch (error) {
popup?.close()
throw error
}
}
10 changes: 6 additions & 4 deletions frontend/src/views/ServerDetail.vue
Original file line number Diff line number Diff line change
Expand Up @@ -3054,11 +3054,13 @@ async function triggerOAuth() {

actionLoading.value = true
try {
await serversStore.triggerOAuthLogin(server.value.name)
const result = await serversStore.triggerOAuthLogin(server.value.name)
systemStore.addToast({
type: 'success',
title: 'OAuth Login Triggered',
message: `Check your browser for ${server.value.name} login`,
type: result.browser_opened ? 'info' : 'warning',
title: result.browser_opened ? 'Sign-in opened' : 'Open the sign-in page',
message: result.browser_opened ? `Finish signing in to ${server.value.name} in your browser.` : 'Your browser blocked the new tab. Use the link below to continue.',
link: result.auth_url ? { url: result.auth_url, label: `Sign in to ${server.value.name}` } : undefined,
duration: result.browser_opened ? 10000 : 0,
})
} catch (error) {
systemStore.addToast({
Expand Down
69 changes: 69 additions & 0 deletions frontend/tests/unit/oauth-login.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { openOAuthLogin, uiIsRemote } from '@/utils/oauthLogin'

afterEach(() => vi.restoreAllMocks())
const url = 'https://provider.example/authorize?state=test'
const result = { success: true, data: { browser_opened: false, auth_url: url } }
const remote = { remote: true }
const local = { remote: false }

describe('remote browser OAuth login', () => {
it('reserves a tab before requesting the URL and removes its opener', async () => {
const replace = vi.fn(), close = vi.fn()
const popup = { opener: window, closed: false, location: { replace }, close }
const open = vi.spyOn(window, 'open').mockReturnValue(popup as unknown as Window)
const request = vi.fn(async () => { expect(open).toHaveBeenCalled(); expect(popup.opener).toBeNull(); return result })
expect((await openOAuthLogin(request, remote)).browser_opened).toBe(true)
expect(replace).toHaveBeenCalledWith(url)
expect(close).not.toHaveBeenCalled()
})
it('retains a safe clickable URL when the popup is blocked', async () => {
vi.spyOn(window, 'open').mockReturnValue(null)
expect(await openOAuthLogin(async () => result, remote)).toEqual(result.data)
})
it('does not report the daemon host browser as opened here when no URL comes back', async () => {
const close = vi.fn()
vi.spyOn(window, 'open').mockReturnValue({ opener: null, closed: false, close, location: { replace: vi.fn() } } as unknown as Window)
await expect(openOAuthLogin(async () => ({ success: true, data: { browser_opened: true } }), remote)).rejects.toThrow('sign-in URL')
expect(close).toHaveBeenCalledTimes(1)
})
it('closes the reserved tab on API failures or unsafe URLs', async () => {
const close = vi.fn(), replace = vi.fn()
vi.spyOn(window, 'open').mockReturnValue({ opener: null, closed: false, close, location: { replace } } as unknown as Window)
await expect(openOAuthLogin(async () => ({ success: false, error: 'Denied' }), remote)).rejects.toThrow('Denied')
await expect(openOAuthLogin(async () => ({ success: true, data: { browser_opened: false, auth_url: 'javascript:alert(1)' } }), remote)).rejects.toThrow('invalid sign-in URL')
expect(close).toHaveBeenCalledTimes(2); expect(replace).not.toHaveBeenCalled()
})
})

describe('local browser OAuth login', () => {
it('leaves the daemon-opened browser alone instead of opening the page twice', async () => {
const open = vi.spyOn(window, 'open')
const opened = { success: true, data: { browser_opened: true, auth_url: url } }
expect(await openOAuthLogin(async () => opened, local)).toEqual(opened.data)
expect(open).not.toHaveBeenCalled()
})
it('opens the page itself only when the daemon could not (HEADLESS, Docker)', async () => {
const late = { opener: window }
const open = vi.spyOn(window, 'open').mockReturnValue(late as unknown as Window)
expect((await openOAuthLogin(async () => result, local)).browser_opened).toBe(true)
expect(open).toHaveBeenCalledTimes(1)
expect(open).toHaveBeenCalledWith(url, '_blank')
expect(late.opener).toBeNull()
})
it('falls back to the toast link when the late popup is blocked', async () => {
vi.spyOn(window, 'open').mockReturnValue(null)
expect(await openOAuthLogin(async () => result, local)).toEqual(result.data)
})
})

describe('uiIsRemote', () => {
it('treats loopback hosts as local and everything else as remote', () => {
for (const hostname of ['localhost', '127.0.0.1', '[::1]', '::1', 'app.localhost', 'LOCALHOST']) {
expect(uiIsRemote({ hostname })).toBe(false)
}
for (const hostname of ['proxy.tailnet.ts.net', '192.168.1.20', 'kubic.home.arpa', 'mcpproxy.homelab.de']) {
expect(uiIsRemote({ hostname })).toBe(true)
}
})
})
4 changes: 2 additions & 2 deletions frontend/tests/unit/oauth-manual-signin.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ describe('manual OAuth sign-in', () => {
expect(canStartOAuthLogin({ ...server, oauth: undefined, authenticated: false })).toBe(true)
})
it('starts a fresh OAuth flow from the card even when reconnect is the primary action', async () => {
const spy = vi.spyOn(useServersStore(), 'triggerOAuthLogin').mockResolvedValue(true)
const spy = vi.spyOn(useServersStore(), 'triggerOAuthLogin').mockResolvedValue({ browser_opened: true })
const card = mount(ServerCard, { props: { server }, global: { stubs: { RouterLink: true } } })
const action = card.find('[data-test="server-card-menu-login"]')
expect(action.text()).toBe('Sign in again')
Expand All @@ -65,7 +65,7 @@ describe('manual OAuth sign-in', () => {
const router = createRouter({ history: createWebHistory(), routes: [{ path: '/servers/:serverName', component: { template: '<div/>' } }] })
await router.push('/servers/notion'); await router.isReady()
const pinia = createPinia(); setActivePinia(pinia)
const spy = vi.spyOn(useServersStore(), 'triggerOAuthLogin').mockResolvedValue(true)
const spy = vi.spyOn(useServersStore(), 'triggerOAuthLogin').mockResolvedValue({ browser_opened: true })
const detail = mount(ServerDetail, { props: { serverName: 'notion' }, global: { plugins: [pinia, router] } })
await flushPromises(); await flushPromises()
const action = detail.find('[data-test="server-detail-menu-login"]')
Expand Down
16 changes: 15 additions & 1 deletion frontend/tests/unit/server-card-quarantined-oauth-login.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { mount, flushPromises } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
import ServerCard from '@/components/ServerCard.vue'
import { useServersStore } from '@/stores/servers'
import { useSystemStore } from '@/stores/system'
import type { Server } from '@/types'

vi.mock('@/services/api', () => ({
Expand Down Expand Up @@ -89,12 +90,25 @@ describe('ServerCard — quarantined server that needs OAuth sign-in', () => {
it('the primary action triggers the OAuth flow for the server', async () => {
const card = mountCard(quarantinedOAuthServer())
const store = useServersStore()
const spy = vi.spyOn(store, 'triggerOAuthLogin').mockResolvedValue(undefined as never)
const spy = vi.spyOn(store, 'triggerOAuthLogin').mockResolvedValue({ browser_opened: true })

await card.find('[data-test="server-card-primary-action"]').trigger('click')
await flushPromises()

expect(spy).toHaveBeenCalledWith('github')
expect(useSystemStore().toasts.at(-1)?.title).toBe('Sign-in opened')
})

it('keeps a clickable sign-in link when the client browser blocks the popup', async () => {
const card = mountCard(quarantinedOAuthServer())
const url = 'https://provider.example/authorize?state=test'
vi.spyOn(useServersStore(), 'triggerOAuthLogin').mockResolvedValue({ browser_opened: false, auth_url: url })
await card.find('[data-test="server-card-primary-action"]').trigger('click')
await flushPromises()
const toast = useSystemStore().toasts.at(-1)
expect(toast?.type).toBe('warning')
expect(toast?.duration).toBe(0)
expect(toast?.link).toEqual({ url, label: 'Sign in to github' })
})

it('offers Review, not Sign in, for a quarantined server that does not need sign-in', () => {
Expand Down
19 changes: 13 additions & 6 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -809,12 +809,13 @@ type ServerConfig struct {

// OAuthConfig represents OAuth configuration for a server
type OAuthConfig struct {
ClientID string `json:"client_id,omitempty" mapstructure:"client_id"`
ClientSecret string `json:"client_secret,omitempty" mapstructure:"client_secret"`
RedirectURI string `json:"redirect_uri,omitempty" mapstructure:"redirect_uri"`
Scopes []string `json:"scopes,omitempty" mapstructure:"scopes"`
PKCEEnabled bool `json:"pkce_enabled,omitempty" mapstructure:"pkce_enabled"`
ExtraParams map[string]string `json:"extra_params,omitempty" mapstructure:"extra_params"` // Additional OAuth parameters (e.g., RFC 8707 resource)
ClientID string `json:"client_id,omitempty" mapstructure:"client_id"`
ClientSecret string `json:"client_secret,omitempty" mapstructure:"client_secret"`
RedirectURI string `json:"redirect_uri,omitempty" mapstructure:"redirect_uri"`
CallbackBaseURL string `json:"callback_base_url,omitempty" mapstructure:"callback_base_url"`
Scopes []string `json:"scopes,omitempty" mapstructure:"scopes"`
PKCEEnabled bool `json:"pkce_enabled,omitempty" mapstructure:"pkce_enabled"`
ExtraParams map[string]string `json:"extra_params,omitempty" mapstructure:"extra_params"` // Additional OAuth parameters (e.g., RFC 8707 resource)

// Spec 113-b: optional per-server discovery overrides. Each is an absolute
// https URL (http only on a loopback host) with no query, fragment or
Expand Down Expand Up @@ -2379,6 +2380,11 @@ func (c *Config) oauthRedirectURIErrors() []ValidationError {
if server == nil || server.OAuth == nil {
continue
}
if err := ValidateOAuthCallbackBaseURL(server.OAuth.CallbackBaseURL); err != nil {
errors = append(errors, ValidationError{
Field: fmt.Sprintf("mcpServers[%d].oauth.callback_base_url", i), Message: err.Error(),
})
}
if strings.TrimSpace(server.OAuth.RedirectURI) == "" {
continue
}
Expand Down Expand Up @@ -3058,6 +3064,7 @@ func OAuthConfigChanged(old, new *OAuthConfig) bool {
if old.ClientID != new.ClientID ||
old.ClientSecret != new.ClientSecret ||
old.RedirectURI != new.RedirectURI ||
old.CallbackBaseURL != new.CallbackBaseURL ||
old.PKCEEnabled != new.PKCEEnabled ||
old.AuthorizationEndpoint != new.AuthorizationEndpoint ||
old.TokenEndpoint != new.TokenEndpoint ||
Expand Down
12 changes: 8 additions & 4 deletions internal/config/merge.go
Original file line number Diff line number Diff line change
Expand Up @@ -579,6 +579,9 @@ func MergeOAuthConfig(base, patch *OAuthConfig, removeIfNil bool) *OAuthConfig {
if patch.RedirectURI != "" {
result.RedirectURI = patch.RedirectURI
}
if patch.CallbackBaseURL != "" {
result.CallbackBaseURL = patch.CallbackBaseURL
}

if patch.AuthorizationEndpoint != "" {
result.AuthorizationEndpoint = patch.AuthorizationEndpoint
Expand Down Expand Up @@ -777,10 +780,11 @@ func copyOAuthConfig(src *OAuthConfig) *OAuthConfig {
}

dst := &OAuthConfig{
ClientID: src.ClientID,
ClientSecret: src.ClientSecret,
RedirectURI: src.RedirectURI,
PKCEEnabled: src.PKCEEnabled,
ClientID: src.ClientID,
ClientSecret: src.ClientSecret,
RedirectURI: src.RedirectURI,
CallbackBaseURL: src.CallbackBaseURL,
PKCEEnabled: src.PKCEEnabled,

AuthorizationEndpoint: src.AuthorizationEndpoint,
TokenEndpoint: src.TokenEndpoint,
Expand Down
Loading
Loading