fix(mcp): coordinate OAuth token refresh and authorization polling
Prevent concurrent refresh-token rotation across instances, distinguish expired-but-refreshable tokens from active authorization, and bind OAuth popup polling to a per-attempt ID so stale tokens cannot satisfy new consent.
This commit is contained in:
@@ -365,13 +365,17 @@ export async function getEmbedMCPOAuthAuthorizeURL(
|
||||
visitorId: string,
|
||||
serviceId: string,
|
||||
body: { redirect_uri: string; frontend_redirect?: string },
|
||||
): Promise<string> {
|
||||
): Promise<{ authorizationUrl: string; authorizationAttempt: string }> {
|
||||
const response: any = await post(
|
||||
`/api/v1/embed/${channelId}/sessions/${encodeURIComponent(sessionId)}/mcp-services/${encodeURIComponent(serviceId)}/oauth/authorize-url`,
|
||||
body,
|
||||
{ headers: embedSessionHeaders(token, sessionSig, visitorId) },
|
||||
)
|
||||
return (response.data ?? response)?.authorization_url ?? ''
|
||||
const data = response.data ?? response
|
||||
return {
|
||||
authorizationUrl: data?.authorization_url ?? '',
|
||||
authorizationAttempt: data?.authorization_attempt ?? '',
|
||||
}
|
||||
}
|
||||
|
||||
export async function getEmbedMCPOAuthStatus(
|
||||
@@ -381,9 +385,13 @@ export async function getEmbedMCPOAuthStatus(
|
||||
sessionSig: string,
|
||||
visitorId: string,
|
||||
serviceId: string,
|
||||
authorizationAttempt?: string,
|
||||
): Promise<boolean> {
|
||||
const query = authorizationAttempt
|
||||
? `?authorization_attempt=${encodeURIComponent(authorizationAttempt)}`
|
||||
: ''
|
||||
const response: any = await get(
|
||||
`/api/v1/embed/${channelId}/sessions/${encodeURIComponent(sessionId)}/mcp-services/${encodeURIComponent(serviceId)}/oauth/status`,
|
||||
`/api/v1/embed/${channelId}/sessions/${encodeURIComponent(sessionId)}/mcp-services/${encodeURIComponent(serviceId)}/oauth/status${query}`,
|
||||
{ headers: embedSessionHeaders(token, sessionSig, visitorId) },
|
||||
)
|
||||
return Boolean((response.data ?? response)?.authorized)
|
||||
|
||||
@@ -194,21 +194,59 @@ export async function deleteMCPCredentialField(
|
||||
// to avoid a route conflict, and allow-listed for no-auth in the backend).
|
||||
export const MCP_OAUTH_CALLBACK_PATH = '/api/v1/mcp-oauth/callback'
|
||||
|
||||
// Begin authorization for the current user. Returns the URL to open in a popup.
|
||||
export interface MCPOAuthAuthorization {
|
||||
authorizationUrl: string
|
||||
authorizationAttempt: string
|
||||
}
|
||||
|
||||
export type MCPOAuthTokenState = 'authorized' | 'refreshable' | 'reauth_required' | 'pending'
|
||||
|
||||
export interface MCPOAuthStatus {
|
||||
authorized: boolean
|
||||
state: MCPOAuthTokenState
|
||||
refresh_available: boolean
|
||||
expires_at?: string
|
||||
}
|
||||
|
||||
// Begin authorization for the current user. The attempt id binds polling to
|
||||
// this popup, so an older stored token cannot be mistaken for fresh consent.
|
||||
export async function getMCPOAuthAuthorizeURL(
|
||||
serviceId: string,
|
||||
body: { redirect_uri: string; frontend_redirect?: string }
|
||||
): Promise<string> {
|
||||
): Promise<MCPOAuthAuthorization> {
|
||||
const response: any = await post(`/api/v1/mcp-services/${serviceId}/oauth/authorize-url`, body)
|
||||
return (response.data ?? response)?.authorization_url ?? ''
|
||||
const data = response.data ?? response
|
||||
return {
|
||||
authorizationUrl: data?.authorization_url ?? '',
|
||||
authorizationAttempt: data?.authorization_attempt ?? '',
|
||||
}
|
||||
}
|
||||
|
||||
// Whether the current user has authorized this service.
|
||||
export async function getMCPOAuthStatus(serviceId: string): Promise<boolean> {
|
||||
const response: any = await get(`/api/v1/mcp-services/${serviceId}/oauth/status`)
|
||||
export async function getMCPOAuthStatus(
|
||||
serviceId: string,
|
||||
authorizationAttempt?: string,
|
||||
): Promise<boolean> {
|
||||
const query = authorizationAttempt
|
||||
? `?authorization_attempt=${encodeURIComponent(authorizationAttempt)}`
|
||||
: ''
|
||||
const response: any = await get(`/api/v1/mcp-services/${serviceId}/oauth/status${query}`)
|
||||
return Boolean((response.data ?? response)?.authorized)
|
||||
}
|
||||
|
||||
// Full lifecycle status for management surfaces. Expired access tokens with a
|
||||
// refresh token are "refreshable", not falsely presented as already usable.
|
||||
export async function getMCPOAuthAuthorizationStatus(serviceId: string): Promise<MCPOAuthStatus> {
|
||||
const response: any = await get(`/api/v1/mcp-services/${serviceId}/oauth/status`)
|
||||
const data = response.data ?? response
|
||||
return {
|
||||
authorized: Boolean(data?.authorized),
|
||||
state: data?.state ?? 'reauth_required',
|
||||
refresh_available: Boolean(data?.refresh_available),
|
||||
expires_at: data?.expires_at,
|
||||
}
|
||||
}
|
||||
|
||||
// Revoke the current user's token (forces re-authorization).
|
||||
export async function revokeMCPOAuthToken(serviceId: string): Promise<void> {
|
||||
await del(`/api/v1/mcp-services/${serviceId}/oauth/token`)
|
||||
|
||||
@@ -4997,6 +4997,7 @@ export default {
|
||||
authTypeNone: 'None / Custom Header',
|
||||
authTypeApiKey: 'API Key / Token',
|
||||
authTypeOAuth: 'OAuth 2.0 (authorize on first connect)',
|
||||
oauthRefreshable: 'Token expired; it will refresh automatically on next use',
|
||||
oauthAuthorizeHint: 'Clicking "Authorize" saves the current config first, then starts authorization (each user authorizes individually).',
|
||||
apiKeyHeader: 'Header Name',
|
||||
apiKeyHeaderDesc: 'Defaults to X-API-Key. For Bearer, set Authorization and put "Bearer <token>" in the value below; for raw-token services use Authorization with the raw token.',
|
||||
|
||||
@@ -5045,6 +5045,7 @@ export default {
|
||||
oauthScopes: "Scopes(可选,空格分隔)",
|
||||
oauthAuthorization: "授权状态",
|
||||
oauthAuthorized: "已授权",
|
||||
oauthRefreshable: "Token 已过期,将在下次使用时自动刷新",
|
||||
oauthUnauthorized: "未授权",
|
||||
oauthAuthorize: "去授权",
|
||||
oauthReauthorize: "重新授权",
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import test from 'node:test'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const cardSource = readFileSync(join(here, 'McpOAuthCard.vue'), 'utf8')
|
||||
const settingsSource = readFileSync(join(here, '../../settings/components/McpServiceDialog.vue'), 'utf8')
|
||||
const apiSource = readFileSync(join(here, '../../../api/mcp-service.ts'), 'utf8')
|
||||
|
||||
test('in-chat OAuth polling is bound to the newly opened authorization attempt', () => {
|
||||
assert.match(cardSource, /authorization\.authorizationAttempt/)
|
||||
assert.match(
|
||||
cardSource,
|
||||
/getMCPOAuthStatus\(props\.serviceId, authorization\.authorizationAttempt\)/,
|
||||
)
|
||||
assert.match(
|
||||
cardSource,
|
||||
/props\.serviceId,\s*authorization\.authorizationAttempt,\s*\)/,
|
||||
)
|
||||
})
|
||||
|
||||
test('settings OAuth polling cannot accept a pre-existing token as fresh authorization', () => {
|
||||
assert.match(
|
||||
settingsSource,
|
||||
/getMCPOAuthStatus\(serviceId, authorization\.authorizationAttempt\)/,
|
||||
)
|
||||
})
|
||||
|
||||
test('OAuth status API sends the attempt id to the backend', () => {
|
||||
assert.match(apiSource, /authorization_attempt=\$\{encodeURIComponent\(authorizationAttempt\)\}/)
|
||||
})
|
||||
|
||||
test('settings distinguishes refreshable tokens from usable authorization', () => {
|
||||
assert.match(settingsSource, /getMCPOAuthAuthorizationStatus\(props\.service\.id\)/)
|
||||
assert.match(settingsSource, /oauthTokenState === 'refreshable'/)
|
||||
assert.match(apiSource, /state: data\?\.state \?\? 'reauth_required'/)
|
||||
})
|
||||
@@ -175,7 +175,7 @@ const authorize = async () => {
|
||||
const frontendRedirect = useEmbedOAuth()
|
||||
? window.location.origin + window.location.pathname + window.location.search
|
||||
: window.location.origin + '/'
|
||||
const authUrl = useEmbedOAuth()
|
||||
const authorization = useEmbedOAuth()
|
||||
? await getEmbedMCPOAuthAuthorizeURL(
|
||||
props.embedChannelId!,
|
||||
props.embedToken!,
|
||||
@@ -189,12 +189,12 @@ const authorize = async () => {
|
||||
redirect_uri: redirectUri,
|
||||
frontend_redirect: frontendRedirect,
|
||||
})
|
||||
if (!authUrl) {
|
||||
if (!authorization.authorizationUrl || !authorization.authorizationAttempt) {
|
||||
MessagePlugin.error(t('agentStream.mcpOAuth.startFailed'))
|
||||
authorizing.value = false
|
||||
return
|
||||
}
|
||||
const popup = window.open(authUrl, 'mcp_oauth', 'width=600,height=720')
|
||||
const popup = window.open(authorization.authorizationUrl, 'mcp_oauth', 'width=600,height=720')
|
||||
poll = window.setInterval(async () => {
|
||||
const closed = !popup || popup.closed
|
||||
let ok = false
|
||||
@@ -207,8 +207,9 @@ const authorize = async () => {
|
||||
props.embedSessionSig!,
|
||||
props.embedVisitorId!,
|
||||
props.serviceId,
|
||||
authorization.authorizationAttempt,
|
||||
)
|
||||
: await getMCPOAuthStatus(props.serviceId)
|
||||
: await getMCPOAuthStatus(props.serviceId, authorization.authorizationAttempt)
|
||||
} catch {
|
||||
/* transient; keep polling */
|
||||
}
|
||||
|
||||
@@ -220,9 +220,12 @@
|
||||
<div class="form-item">
|
||||
<label class="form-label">{{ t('mcpServiceDialog.oauthAuthorization', '授权状态') }}</label>
|
||||
<div class="oauth-status">
|
||||
<t-tag v-if="oauthAuthorized" theme="success" variant="light">
|
||||
<t-tag v-if="oauthTokenState === 'authorized'" theme="success" variant="light">
|
||||
{{ t('mcpServiceDialog.oauthAuthorized', '已授权') }}
|
||||
</t-tag>
|
||||
<t-tag v-else-if="oauthTokenState === 'refreshable'" theme="primary" variant="light">
|
||||
{{ t('mcpServiceDialog.oauthRefreshable', 'Token 已过期,将自动刷新') }}
|
||||
</t-tag>
|
||||
<t-tag v-else theme="warning" variant="light">
|
||||
{{ t('mcpServiceDialog.oauthUnauthorized', '未授权') }}
|
||||
</t-tag>
|
||||
@@ -232,10 +235,10 @@
|
||||
:loading="oauthAuthorizing || oauthChecking || submitting"
|
||||
@click="handleAuthorize"
|
||||
>
|
||||
{{ oauthAuthorized ? t('mcpServiceDialog.oauthReauthorize', '重新授权') : t('mcpServiceDialog.oauthAuthorize', '去授权') }}
|
||||
{{ oauthTokenState === 'reauth_required' ? t('mcpServiceDialog.oauthAuthorize', '去授权') : t('mcpServiceDialog.oauthReauthorize', '重新授权') }}
|
||||
</t-button>
|
||||
<t-button
|
||||
v-if="oauthAuthorized && props.service?.id"
|
||||
v-if="oauthTokenState !== 'reauth_required' && props.service?.id"
|
||||
size="small"
|
||||
theme="danger"
|
||||
variant="outline"
|
||||
@@ -374,12 +377,14 @@ import {
|
||||
deleteMCPCredentialField,
|
||||
testMCPService,
|
||||
getMCPOAuthAuthorizeURL,
|
||||
getMCPOAuthAuthorizationStatus,
|
||||
getMCPOAuthStatus,
|
||||
revokeMCPOAuthToken,
|
||||
MCP_OAUTH_CALLBACK_PATH,
|
||||
type MCPService,
|
||||
type McpCredentialField,
|
||||
type MCPTestResult,
|
||||
type MCPOAuthTokenState,
|
||||
} from '@/api/mcp-service'
|
||||
import SettingDrawer from '@/components/settings/SettingDrawer.vue'
|
||||
import McpTestResultBody from './McpTestResultBody.vue'
|
||||
@@ -607,6 +612,7 @@ const authTypeOptions = computed(() => [
|
||||
|
||||
// ---- OAuth authorization state (edit mode only) ----
|
||||
const oauthAuthorized = ref(false)
|
||||
const oauthTokenState = ref<MCPOAuthTokenState>('reauth_required')
|
||||
const oauthChecking = ref(false)
|
||||
const oauthAuthorizing = ref(false)
|
||||
|
||||
@@ -614,7 +620,9 @@ async function refreshOAuthStatus() {
|
||||
if (props.mode !== 'edit' || !props.service?.id || !isOAuth.value) return
|
||||
oauthChecking.value = true
|
||||
try {
|
||||
oauthAuthorized.value = await getMCPOAuthStatus(props.service.id)
|
||||
const status = await getMCPOAuthAuthorizationStatus(props.service.id)
|
||||
oauthAuthorized.value = status.authorized
|
||||
oauthTokenState.value = status.state
|
||||
} catch (e) {
|
||||
console.error('Failed to query MCP OAuth status:', e)
|
||||
} finally {
|
||||
@@ -634,21 +642,22 @@ async function startAuthorize(serviceId: string) {
|
||||
// app root is harmless; the popup is closed by the opener below once the
|
||||
// authorization status flips, so this page is only shown briefly.
|
||||
const frontendRedirect = window.location.origin + '/'
|
||||
const authUrl = await getMCPOAuthAuthorizeURL(serviceId, {
|
||||
const authorization = await getMCPOAuthAuthorizeURL(serviceId, {
|
||||
redirect_uri: redirectUri,
|
||||
frontend_redirect: frontendRedirect,
|
||||
})
|
||||
if (!authUrl) {
|
||||
if (!authorization.authorizationUrl || !authorization.authorizationAttempt) {
|
||||
MessagePlugin.error(t('mcpServiceDialog.toasts.authorizeFailed', '发起授权失败') as string)
|
||||
oauthAuthorizing.value = false
|
||||
return
|
||||
}
|
||||
const popup = window.open(authUrl, 'mcp_oauth', 'width=600,height=720')
|
||||
const popup = window.open(authorization.authorizationUrl, 'mcp_oauth', 'width=600,height=720')
|
||||
// Poll for completion: either the popup closes or the status flips.
|
||||
const timer = window.setInterval(async () => {
|
||||
const closed = !popup || popup.closed
|
||||
try {
|
||||
oauthAuthorized.value = await getMCPOAuthStatus(serviceId)
|
||||
oauthAuthorized.value = await getMCPOAuthStatus(serviceId, authorization.authorizationAttempt)
|
||||
if (oauthAuthorized.value) oauthTokenState.value = 'authorized'
|
||||
} catch { /* keep polling */ }
|
||||
if (oauthAuthorized.value || closed) {
|
||||
window.clearInterval(timer)
|
||||
@@ -704,6 +713,7 @@ async function handleRevokeOAuth() {
|
||||
try {
|
||||
await revokeMCPOAuthToken(props.service.id)
|
||||
oauthAuthorized.value = false
|
||||
oauthTokenState.value = 'reauth_required'
|
||||
MessagePlugin.success(t('mcpServiceDialog.toasts.revoked', '已撤销授权') as string)
|
||||
} catch (e) {
|
||||
console.error('Failed to revoke MCP OAuth token:', e)
|
||||
@@ -961,6 +971,7 @@ watch(
|
||||
},
|
||||
}
|
||||
oauthAuthorized.value = false
|
||||
oauthTokenState.value = 'reauth_required'
|
||||
refreshOAuthStatus()
|
||||
} else {
|
||||
resetForm()
|
||||
|
||||
Reference in New Issue
Block a user