fix(desktop): preserve explicit local MCP OAuth without callback bridge
This commit is contained in:
@@ -1,10 +1,10 @@
|
||||
import { capabilityScoped } from '@/api/client'
|
||||
;('use client')
|
||||
'use client'
|
||||
|
||||
import { type ToolCallMessagePartProps, useAuiState } from '@assistant-ui/react'
|
||||
import { useStore } from '@nanostores/react'
|
||||
import { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
|
||||
import { capabilityScoped } from '@/api/client'
|
||||
import { useSessionView } from '@/app/chat/session-view'
|
||||
import { ToolFallback } from '@/components/assistant-ui/tool/fallback'
|
||||
import { WIDGET_SHELL_CLASS } from '@/components/chat/widget-shell'
|
||||
|
||||
@@ -74,6 +74,110 @@ afterEach(() => {
|
||||
})
|
||||
|
||||
describe('Desktop MCP client callback lifecycle', () => {
|
||||
it.each(['approved', 'cancel-start', 'cancel-poll', 'denial', 'poll', 'browser'])(
|
||||
'preserves explicit local OAuth without a bridge through %s and foreground switches',
|
||||
async outcome => {
|
||||
const { rpc, api, bridge, openExternal } = harness()
|
||||
window.hermesDesktop.mcpOauth = undefined
|
||||
setApiRequestConnection('local')
|
||||
setApiRequestProfile('origin-profile')
|
||||
let cancelled = false
|
||||
rpc.mockImplementation(async (_connection, _profile, method) => {
|
||||
if (method.endsWith('.start')) {
|
||||
setApiRequestConnection('other-gateway')
|
||||
setApiRequestProfile('other-profile')
|
||||
cancelled = outcome === 'cancel-start'
|
||||
|
||||
return started
|
||||
}
|
||||
|
||||
if (method.endsWith('.poll')) {
|
||||
cancelled = outcome === 'cancel-poll'
|
||||
|
||||
if (outcome === 'poll') {
|
||||
throw new Error('poll failed')
|
||||
}
|
||||
|
||||
return outcome === 'denial'
|
||||
? { ok: true, status: 'error', error_message: 'access_denied' }
|
||||
: { ok: true, status: 'approved', tools }
|
||||
}
|
||||
|
||||
return { ok: true }
|
||||
})
|
||||
|
||||
if (outcome === 'browser') {
|
||||
openExternal.mockRejectedValue(new Error('browser failed'))
|
||||
}
|
||||
|
||||
const action = completeMcpDesktopOAuth({
|
||||
serverName: 'reports',
|
||||
cancelled: () => cancelled,
|
||||
sleep: async () => {}
|
||||
})
|
||||
|
||||
if (outcome === 'approved') {
|
||||
await expect(action).resolves.toMatchObject({ status: 'approved', tools })
|
||||
} else if (outcome.startsWith('cancel-')) {
|
||||
await expect(action).rejects.toBeInstanceOf(McpOAuthCancelled)
|
||||
} else {
|
||||
await expect(action).rejects.toThrow(outcome === 'denial' ? 'access_denied' : `${outcome} failed`)
|
||||
}
|
||||
|
||||
expect(rpc).toHaveBeenCalledWith(
|
||||
'local',
|
||||
'origin-profile',
|
||||
'mcp.servers.oauth.start',
|
||||
{ name: 'reports' },
|
||||
60_000
|
||||
)
|
||||
expect(rpc.mock.calls.every(call => call[0] === 'local' && call[1] === 'origin-profile')).toBe(true)
|
||||
expect(rpc.mock.calls.filter(call => call[2].endsWith('.start'))).toHaveLength(1)
|
||||
expect(rpc.mock.calls.filter(call => call[2].endsWith('.cancel'))).toHaveLength(outcome === 'approved' ? 0 : 1)
|
||||
expect(rpc.mock.calls.filter(call => call[2].endsWith('.callback'))).toHaveLength(0)
|
||||
expect(openExternal.mock.calls).toEqual(outcome === 'cancel-start' ? [] : [[authUrl]])
|
||||
expect(bridge.listen).not.toHaveBeenCalled()
|
||||
expect(bridge.wait).not.toHaveBeenCalled()
|
||||
expect(bridge.cancel).not.toHaveBeenCalled()
|
||||
expect(api).not.toHaveBeenCalled()
|
||||
}
|
||||
)
|
||||
|
||||
it.each([
|
||||
{ connectionId: null, uri: redirectUri },
|
||||
{ connectionId: 'remote-gateway', uri: redirectUri },
|
||||
{ connectionId: 'local', uri: 'http://remote.example:49152/callback' },
|
||||
{ connectionId: 'local', uri: 'https://127.0.0.1:49152/callback' },
|
||||
{ connectionId: 'local', uri: 'http://127.0.0.1:49152/not-callback' },
|
||||
{ connectionId: 'local', uri: 'http://user@127.0.0.1:49152/callback' },
|
||||
{ connectionId: 'local', uri: 'http://127.0.0.1:49152/callback#fragment' },
|
||||
{ connectionId: 'local', uri: '' },
|
||||
{ connectionId: 'local', uri: redirectUri, listenerFailure: true }
|
||||
])('refuses unsafe compatibility paths: %j', async ({ connectionId, uri, listenerFailure }) => {
|
||||
const { rpc, api, bridge, openExternal } = harness()
|
||||
setApiRequestConnection(connectionId)
|
||||
|
||||
if (listenerFailure) {
|
||||
bridge.listen.mockRejectedValue(new Error('listen failed'))
|
||||
} else {
|
||||
window.hermesDesktop.mcpOauth = undefined
|
||||
}
|
||||
|
||||
rpc.mockResolvedValue({
|
||||
...started,
|
||||
auth_url: `https://idp.example/authorize?state=expected&redirect_uri=${encodeURIComponent(uri)}`
|
||||
})
|
||||
await expect(completeMcpDesktopOAuth({ serverName: 'reports' })).rejects.toThrow()
|
||||
expect(openExternal).not.toHaveBeenCalled()
|
||||
expect(api).not.toHaveBeenCalled()
|
||||
|
||||
if (connectionId !== 'local' || listenerFailure) {
|
||||
expect(rpc).not.toHaveBeenCalled()
|
||||
} else {
|
||||
expect(rpc.mock.calls.map(call => call[2])).toEqual(['mcp.servers.oauth.start', 'mcp.servers.oauth.cancel'])
|
||||
}
|
||||
})
|
||||
|
||||
it('bounds pending polls even after the browser callback arrives', async () => {
|
||||
const { rpc, bridge } = harness()
|
||||
const base = rpc.getMockImplementation()!
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ProfileScope } from '@/api/client'
|
||||
import { capabilityScoped, type ProfileScope } from '@/api/client'
|
||||
import { type McpOAuthFlow, mcpOAuthRpc } from '@/api/mcp'
|
||||
|
||||
import { isMissingRpcMethod } from './gateway-rpc'
|
||||
@@ -32,8 +32,8 @@ export class McpOAuthCancelled extends Error {
|
||||
const defaultSleep = (milliseconds: number) => new Promise<void>(resolve => window.setTimeout(resolve, milliseconds))
|
||||
const UPDATE_BACKEND = 'Update the Hermes backend to support Desktop MCP OAuth callbacks.'
|
||||
|
||||
/** The browser and redirect listener live on the Desktop machine, even when
|
||||
* the token-exchanging gateway is remote. Never fall back to its REST callback. */
|
||||
/** Remote gateways require the Desktop callback bridge. An explicitly local
|
||||
* gateway can host its own loopback listener when that capability is absent. */
|
||||
export async function completeMcpDesktopOAuth({
|
||||
serverName,
|
||||
profile,
|
||||
@@ -43,10 +43,12 @@ export async function completeMcpDesktopOAuth({
|
||||
timeoutMs = 360_000
|
||||
}: CompleteOptions): Promise<McpOAuthFlow> {
|
||||
const deadline = Date.now() + timeoutMs
|
||||
const rpc = mcpOAuthRpc(profile)
|
||||
const scope = capabilityScoped(profile)
|
||||
const rpc = mcpOAuthRpc(scope)
|
||||
const bridge = window.hermesDesktop.mcpOauth
|
||||
|
||||
if (!bridge) {
|
||||
// A legacy null connection can resolve to a remote registry primary.
|
||||
if (!bridge && scope.connectionId !== 'local') {
|
||||
throw new Error('Update Hermes Desktop to support MCP OAuth callbacks.')
|
||||
}
|
||||
|
||||
@@ -75,9 +77,13 @@ export async function completeMcpDesktopOAuth({
|
||||
|
||||
try {
|
||||
checkCancelled()
|
||||
listener = await bridge.listen()
|
||||
checkCancelled()
|
||||
const started = await request('start', { client_redirect_uri: listener.redirectUri })
|
||||
|
||||
if (bridge) {
|
||||
listener = await bridge.listen()
|
||||
checkCancelled()
|
||||
}
|
||||
|
||||
const started = await request('start', listener ? { client_redirect_uri: listener.redirectUri } : {})
|
||||
sessionId = started.session_id
|
||||
authUrl = started.auth_url
|
||||
// Start may have created a flow while the user cancelled. Keep its id so
|
||||
@@ -90,27 +96,51 @@ export async function completeMcpDesktopOAuth({
|
||||
|
||||
// Pre-relay backends silently ignore unknown start params. Do not open an
|
||||
// authorization URL whose DCR/PKCE flow points at a different machine.
|
||||
if (new URL(authUrl).searchParams.get('redirect_uri') !== listener.redirectUri) {
|
||||
const redirectUri = new URL(authUrl).searchParams.get('redirect_uri')
|
||||
|
||||
if (listener && redirectUri !== listener.redirectUri) {
|
||||
throw new Error(UPDATE_BACKEND)
|
||||
}
|
||||
|
||||
if (!listener) {
|
||||
// Match the existing backend-hosted listener, not an arbitrary local URL.
|
||||
const redirect = new URL(redirectUri || '')
|
||||
|
||||
if (
|
||||
redirect.protocol !== 'http:' ||
|
||||
redirect.hostname !== '127.0.0.1' ||
|
||||
!redirect.port ||
|
||||
Number(redirect.port) === 0 ||
|
||||
redirect.pathname !== '/callback' ||
|
||||
redirect.username ||
|
||||
redirect.password ||
|
||||
redirect.search ||
|
||||
redirect.hash
|
||||
) {
|
||||
throw new Error('OAuth server did not provide a local loopback callback URL')
|
||||
}
|
||||
}
|
||||
|
||||
const flowId = sessionId
|
||||
void bridge
|
||||
.wait(listener.id)
|
||||
.then(async callback => {
|
||||
if (closed || cancelled?.()) {
|
||||
return
|
||||
}
|
||||
|
||||
if (!callback.state) {
|
||||
throw new Error(callback.error || 'OAuth callback did not include state')
|
||||
}
|
||||
if (bridge && listener) {
|
||||
void bridge
|
||||
.wait(listener.id)
|
||||
.then(async callback => {
|
||||
if (closed || cancelled?.()) {
|
||||
return
|
||||
}
|
||||
|
||||
await request('callback', { session_id: flowId, ...callback })
|
||||
})
|
||||
.catch(error => {
|
||||
relayError = error
|
||||
})
|
||||
if (!callback.state) {
|
||||
throw new Error(callback.error || 'OAuth callback did not include state')
|
||||
}
|
||||
|
||||
await request('callback', { session_id: flowId, ...callback })
|
||||
})
|
||||
.catch(error => {
|
||||
relayError = error
|
||||
})
|
||||
}
|
||||
|
||||
await window.hermesDesktop.openExternal(authUrl)
|
||||
let pollFailures = 0
|
||||
@@ -177,7 +207,7 @@ export async function completeMcpDesktopOAuth({
|
||||
|
||||
// Stop the native waiter first: its synthetic cancellation is NOT a
|
||||
// provider callback and must never race cleanup back onto the gateway.
|
||||
if (listener) {
|
||||
if (bridge && listener) {
|
||||
await bridge.cancel(listener.id).catch(() => {})
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user