@@ -659,6 +659,20 @@ const { t } = useI18n()
const appStore = useAppStore()
// Web Search global enabled state (loaded once on mount)
+// Platforms that support the account-level Web Search emulation toggle
+// (must stay in sync with the backend account-level whitelist in
+// backend/internal/service/account.go webSearchEmulationPlatformEnabled).
+// Both the rendering and the submit path use this set, so a platform added to
+// the backend whitelist automatically becomes configurable here.
+const WEB_SEARCH_EMULATION_PLATFORMS: ReadonlySet = new Set([
+ 'anthropic',
+ 'openai',
+ 'command_code',
+ 'opencode_go',
+ 'minimax',
+ 'zhipu',
+])
+
const webSearchGlobalEnabled = ref(false)
async function loadWebSearchGlobalState() {
try {
@@ -1150,15 +1164,13 @@ function formToAPI(): { group_ids: number[], model_pricing: ChannelModelPricing[
}
const uniqueGroupIds = Array.from(new Set(group_ids))
- // Collect web_search_emulation (only anthropic platform supports it)
- // Always write the key so that disabling in the UI correctly sets platform to false,
- // rather than leaving a stale true value from the cloned features_config.
+ // Collect web_search_emulation(whitelist platforms only: the UI is the single
+ // source of truth, so every whitelisted section is written explicitly — false
+ // included — to avoid leaving a stale `true` behind for disabled sections).
const wsEmulation: Record = {}
for (const section of form.platforms) {
- if (!section.enabled) continue
- if (section.platform === 'anthropic') {
- wsEmulation[section.platform] = !!section.web_search_emulation
- }
+ if (!WEB_SEARCH_EMULATION_PLATFORMS.has(section.platform)) continue
+ wsEmulation[section.platform] = section.enabled ? !!section.web_search_emulation : false
}
if (Object.keys(wsEmulation).length > 0) {
featuresConfig.web_search_emulation = wsEmulation
diff --git a/frontend/src/views/admin/GroupsView.vue b/frontend/src/views/admin/GroupsView.vue
index 8572f7b0bf..516441b821 100644
--- a/frontend/src/views/admin/GroupsView.vue
+++ b/frontend/src/views/admin/GroupsView.vue
@@ -919,6 +919,20 @@
/>
{{ t(imagePricingI18nKey(createForm.platform, "independentMultiplier")) }}
+
+
+ {{ t("admin.groups.imagePricing.perImageBilling") }}
+
{{ t(imagePricingI18nKey(editForm.platform, "independentMultiplier")) }}
+
+
+ {{ t("admin.groups.imagePricing.perImageBilling") }}
+
const resetDisabledBatchImagePricing = (
form: Pick<
ImagePricingFormState,
- "platform" | "allow_image_generation" | "allow_batch_image_generation" | "batch_image_discount_multiplier" | "batch_image_hold_multiplier"
+ | "platform"
+ | "allow_image_generation"
+ | "allow_batch_image_generation"
+ | "image_count_billing"
+ | "batch_image_discount_multiplier"
+ | "batch_image_hold_multiplier"
>,
) => {
if (form.platform !== "gemini" || !form.allow_image_generation) {
@@ -5544,6 +5580,12 @@ const resetDisabledBatchImagePricing = (
form.batch_image_discount_multiplier = 0.5;
form.batch_image_hold_multiplier = 0.6;
}
+ if (
+ !form.allow_image_generation ||
+ (form.platform !== "composite" && form.platform !== "openai")
+ ) {
+ form.image_count_billing = false;
+ }
};
// 根据分组类型返回不同的删除确认消息
@@ -5783,6 +5825,7 @@ const closeCreateModal = () => {
createForm.monthly_limit_usd = null;
createForm.allow_image_generation = false;
createForm.allow_batch_image_generation = false;
+ createForm.image_count_billing = false;
createForm.image_rate_independent = false;
createForm.image_rate_multiplier = 1;
createForm.batch_image_discount_multiplier = 0.5;
@@ -6078,6 +6121,7 @@ const handleEdit = async (group: AdminGroup) => {
editForm.allow_image_generation = group.allow_image_generation ?? false;
editForm.allow_batch_image_generation =
group.allow_batch_image_generation ?? false;
+ editForm.image_count_billing = group.image_count_billing ?? false;
editForm.image_rate_independent = group.image_rate_independent ?? false;
editForm.image_rate_multiplier = group.image_rate_multiplier ?? 1;
editForm.batch_image_discount_multiplier =
diff --git a/frontend/src/views/admin/SettingsView.vue b/frontend/src/views/admin/SettingsView.vue
index 5c344267fa..36bbfd4b4a 100644
--- a/frontend/src/views/admin/SettingsView.vue
+++ b/frontend/src/views/admin/SettingsView.vue
@@ -46,8 +46,10 @@
-
-
+
+
+
+ {{ t("adminAccessKeys.legacy") }}
@@ -86,48 +88,6 @@
{{ t("common.loading") }}
-
-
-
- {{ t("admin.settings.adminApiKey.notConfigured") }}
-
-
-
-
-
-
- {{
- adminApiKeyOperating
- ? t("admin.settings.adminApiKey.creating")
- : t("admin.settings.adminApiKey.create")
- }}
-
-
-
-
+
@@ -9048,6 +9008,7 @@ import {
isStepUpBlocked,
stepUpBlockReason,
} from "@/composables/useStepUp";
+import AdminAccessKeysSettings from "@/components/admin/settings/AdminAccessKeysSettings.vue";
import TotpStepUpDialog from "@/components/auth/TotpStepUpDialog.vue";
import { affiliatesAPI, type AffiliateAdminEntry, type SimpleUser as AffiliateSimpleUser } from "@/api/admin/affiliates";
import { extractApiErrorMessage, extractI18nErrorMessage } from "@/utils/apiError";
@@ -12029,15 +11990,17 @@ async function loadAdminApiKey() {
}
async function createAdminApiKey() {
+ if (!adminApiKeyExists.value) return;
adminApiKeyOperating.value = true;
try {
- const result = await adminAPI.settings.regenerateAdminApiKey();
+ const result = await settingsStepUp.run(() => adminAPI.settings.regenerateAdminApiKey());
newAdminApiKey.value = result.key;
adminApiKeyExists.value = true;
adminApiKeyMasked.value =
result.key.substring(0, 10) + "..." + result.key.slice(-4);
appStore.showSuccess(t("admin.settings.adminApiKey.keyGenerated"));
} catch (error: unknown) {
+ if (isStepUpCancelled(error)) return;
appStore.showError(extractApiErrorMessage(error, t("common.error")));
} finally {
adminApiKeyOperating.value = false;
@@ -12053,12 +12016,13 @@ async function deleteAdminApiKey() {
if (!confirm(t("admin.settings.adminApiKey.deleteConfirm"))) return;
adminApiKeyOperating.value = true;
try {
- await adminAPI.settings.deleteAdminApiKey();
+ await settingsStepUp.run(() => adminAPI.settings.deleteAdminApiKey());
adminApiKeyExists.value = false;
adminApiKeyMasked.value = "";
newAdminApiKey.value = "";
appStore.showSuccess(t("admin.settings.adminApiKey.keyDeleted"));
} catch (error: unknown) {
+ if (isStepUpCancelled(error)) return;
appStore.showError(extractApiErrorMessage(error, t("common.error")));
} finally {
adminApiKeyOperating.value = false;
diff --git a/frontend/src/views/admin/__tests__/ChannelsView.webSearchEmulation.spec.ts b/frontend/src/views/admin/__tests__/ChannelsView.webSearchEmulation.spec.ts
new file mode 100644
index 0000000000..361838cc93
--- /dev/null
+++ b/frontend/src/views/admin/__tests__/ChannelsView.webSearchEmulation.spec.ts
@@ -0,0 +1,41 @@
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+import { describe, expect, it } from 'vitest'
+
+/**
+ * Regression guard for features_config.web_search_emulation:
+ * the channel editor used to render and submit the anthropic dimension only,
+ * so any UI save overwrote the other platform dimensions written by the API.
+ * Both sides must now follow the platform whitelist.
+ */
+describe('ChannelsView web_search_emulation platform whitelist', () => {
+ const source = readFileSync(resolve('src/views/admin/ChannelsView.vue'), 'utf8')
+ const zh = readFileSync(resolve('src/i18n/locales/zh/admin/channels.ts'), 'utf8')
+ const en = readFileSync(resolve('src/i18n/locales/en/admin/channels.ts'), 'utf8')
+
+ it('declares the whitelist aligned with the backend platform whitelist', () => {
+ expect(source).toContain('const WEB_SEARCH_EMULATION_PLATFORMS: ReadonlySet
= new Set([')
+ for (const platform of ['anthropic', 'openai', 'command_code', 'opencode_go', 'minimax', 'zhipu']) {
+ expect(source).toContain(`'${platform}',`)
+ }
+ })
+
+ it('renders the toggle for every whitelisted platform section', () => {
+ expect(source).toContain('WEB_SEARCH_EMULATION_PLATFORMS.has(section.platform) && webSearchGlobalEnabled')
+ expect(source).not.toContain("section.platform === 'anthropic' && webSearchGlobalEnabled")
+ })
+
+ it('submits every whitelisted platform dimension on save', () => {
+ const block = source.match(/const wsEmulation[\s\S]*?delete featuresConfig\.web_search_emulation/)?.[0] ?? ''
+ expect(block).toContain('WEB_SEARCH_EMULATION_PLATFORMS.has(section.platform)')
+ expect(block).toContain('wsEmulation[section.platform] = section.enabled ? !!section.web_search_emulation : false')
+ expect(block).not.toContain("'anthropic'")
+ })
+
+ it('i18n hint no longer hardcodes Anthropic as the only platform', () => {
+ expect(zh).not.toContain('所有 Anthropic 分组的账号将自动拦截')
+ expect(en).not.toContain("Anthropic groups will intercept")
+ expect(zh).toContain('webSearchEmulationHint')
+ expect(en).toContain('webSearchEmulationHint')
+ })
+})
diff --git a/frontend/src/views/auth/MCPOAuthAuthorizeView.vue b/frontend/src/views/auth/MCPOAuthAuthorizeView.vue
new file mode 100644
index 0000000000..065a739272
--- /dev/null
+++ b/frontend/src/views/auth/MCPOAuthAuthorizeView.vue
@@ -0,0 +1,203 @@
+
+
+
+
+
+
+
{{ t('mcp.consentTitle') }}
+
{{ t('mcp.consentDescription') }}
+
+
+ {{ t('mcp.consentLoading') }}
+
+
{{ previewError }}
+
{{ t('mcp.consentRetryHint') }}
+
{{ t('mcp.backToConnections') }}
+
+
+
+
+
+
+
+
diff --git a/frontend/src/views/auth/__tests__/MCPLoginRedirect.spec.ts b/frontend/src/views/auth/__tests__/MCPLoginRedirect.spec.ts
new file mode 100644
index 0000000000..de6e6fb852
--- /dev/null
+++ b/frontend/src/views/auth/__tests__/MCPLoginRedirect.spec.ts
@@ -0,0 +1,105 @@
+import { flushPromises, mount } from '@vue/test-utils'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import LoginView from '../LoginView.vue'
+import EmailOAuthButtons from '@/components/auth/EmailOAuthButtons.vue'
+import LinuxDoOAuthSection from '@/components/auth/LinuxDoOAuthSection.vue'
+import OidcOAuthSection from '@/components/auth/OidcOAuthSection.vue'
+import DingTalkOAuthSection from '@/components/auth/DingTalkOAuthSection.vue'
+import WechatOAuthSection from '@/components/auth/WechatOAuthSection.vue'
+import OAuthCallbackView from '../OAuthCallbackView.vue'
+
+const { route, login, push, replace, exchangeCompletion } = vi.hoisted(() => ({
+ route: { path: '/login', query: {} as Record },
+ login: vi.fn(), push: vi.fn(), replace: vi.fn(), exchangeCompletion: vi.fn()
+}))
+vi.mock('vue-router', () => ({ useRoute: () => route, useRouter: () => ({ push, replace, currentRoute: { value: route } }) }))
+vi.mock('vue-i18n', () => ({
+ createI18n: () => ({ global: { t: (key: string) => key } }),
+ useI18n: () => ({ t: (key: string) => key, locale: { value: 'en' } })
+}))
+vi.mock('@/stores', () => ({
+ useAuthStore: () => ({ login, loginWithPasskey: vi.fn(), login2FA: vi.fn(), setToken: vi.fn() }),
+ useAppStore: () => ({ showError: vi.fn(), showSuccess: vi.fn(), showWarning: vi.fn(), cachedPublicSettings: {}, publicSettingsLoaded: true })
+}))
+vi.mock('@/api/client', () => ({ apiClient: { post: vi.fn() } }))
+vi.mock('@/api/auth', async () => {
+ const actual = await vi.importActual('@/api/auth')
+ return {
+ ...actual,
+ getPublicSettings: vi.fn().mockResolvedValue({ registration_enabled: false }),
+ isTotp2FARequired: () => false,
+ resolveWeChatOAuthStart: () => ({ mode: 'open' }),
+ exchangePendingOAuthCompletion: exchangeCompletion,
+ persistOAuthTokenContext: vi.fn()
+ }
+})
+vi.mock('@/composables/useClipboard', () => ({ useClipboard: () => ({ copyToClipboard: vi.fn() }) }))
+
+const authorizationPath = '/oauth/mcp/authorize?' + new URLSearchParams({
+ response_type: 'code', client_id: 'desktop', redirect_uri: 'http://127.0.0.1:54321/callback',
+ resource: 'https://api.example.com/api/v1/mcp', state: 'opaque+a&b=c',
+ code_challenge: 'a'.repeat(43), code_challenge_method: 'S256'
+}).toString()
+const mounted: ReturnType[] = []
+const originalLocation = window.location
+beforeEach(() => {
+ vi.clearAllMocks()
+ route.path = '/login'
+ route.query = { redirect: authorizationPath }
+ login.mockResolvedValue({})
+ Object.defineProperty(window, 'location', { configurable: true, value: { ...originalLocation, href: 'https://platform.example.com/auth/callback', hash: '' } })
+})
+afterEach(() => {
+ mounted.splice(0).forEach(wrapper => wrapper.unmount())
+ Object.defineProperty(window, 'location', { configurable: true, value: originalLocation })
+})
+
+describe('MCP authorization through existing sign-in flows', () => {
+ it('returns to the original OAuth query after password login', async () => {
+ const wrapper = mount(LoginView, {
+ global: { stubs: {
+ AuthLayout: { template: '
' },
+ DingTalkOAuthSection: true, EmailOAuthButtons: true, Icon: true, LinuxDoOAuthSection: true,
+ LoginAgreementPrompt: true, OidcOAuthSection: true, RouterLink: true, TotpLoginModal: true,
+ TurnstileWidget: true, WechatOAuthSection: true
+ } }
+ })
+ mounted.push(wrapper)
+ await flushPromises()
+ await wrapper.get('#email').setValue('user@example.com')
+ await wrapper.get('#password').setValue('local-test-password')
+ await wrapper.get('form').trigger('submit')
+ await flushPromises()
+ expect(login).toHaveBeenCalledTimes(1)
+ expect(push).toHaveBeenCalledWith(authorizationPath)
+ })
+
+ it.each([
+ ['github', EmailOAuthButtons, { githubEnabled: true }],
+ ['google', EmailOAuthButtons, { googleEnabled: true }],
+ ['linuxdo', LinuxDoOAuthSection, {}],
+ ['oidc', OidcOAuthSection, {}],
+ ['dingtalk', DingTalkOAuthSection, {}],
+ ['wechat', WechatOAuthSection, {}]
+ ] as const)('preserves the entire return path when starting %s sign-in', async (provider, component, props) => {
+ const wrapper = mount(component, { props, global: { stubs: { Icon: true } } })
+ mounted.push(wrapper)
+ await wrapper.get('button').trigger('click')
+ const event = wrapper.emitted('start')?.[0]?.[0] as { provider: string; params: Record }
+ expect(event.provider).toBe(provider)
+ expect(event.params.redirect).toBe(authorizationPath)
+ const { buildOAuthLoginStartURL } = await import('@/api/auth')
+ const start = new URL(buildOAuthLoginStartURL(event), 'https://platform.example.com')
+ expect(start.searchParams.get('redirect')).toBe(authorizationPath)
+ })
+
+ it('returns from successful social sign-in to the intact OAuth consent request', async () => {
+ route.path = '/auth/oauth/callback'
+ route.query = {}
+ exchangeCompletion.mockResolvedValue({ access_token: 'test-session', redirect: authorizationPath })
+ const wrapper = mount(OAuthCallbackView)
+ mounted.push(wrapper)
+ await flushPromises()
+ expect(replace).toHaveBeenCalledWith(authorizationPath)
+ })
+})
diff --git a/frontend/src/views/auth/__tests__/MCPOAuthAuthorizeView.spec.ts b/frontend/src/views/auth/__tests__/MCPOAuthAuthorizeView.spec.ts
new file mode 100644
index 0000000000..9ef63e66b3
--- /dev/null
+++ b/frontend/src/views/auth/__tests__/MCPOAuthAuthorizeView.spec.ts
@@ -0,0 +1,228 @@
+import { flushPromises, mount } from '@vue/test-utils'
+import { reactive } from 'vue'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import MCPOAuthAuthorizeView from '../MCPOAuthAuthorizeView.vue'
+import type { MCPAuthorization, MCPConsent } from '@/api/mcp'
+
+const { auth, previewAuthorization, authorize, routeState, assign } = vi.hoisted(() => ({
+ auth: { isAdmin: false, user: { email: 'user@example.com' } },
+ previewAuthorization: vi.fn(), authorize: vi.fn(), assign: vi.fn(),
+ routeState: { current: {} as { fullPath: string; query: Record } }
+}))
+vi.mock('vue-router', () => ({ useRoute: () => routeState.current }))
+vi.mock('@/api/mcp', () => ({ mcpAPI: { previewAuthorization, authorize } }))
+vi.mock('@/stores/auth', () => ({ useAuthStore: () => auth }))
+vi.mock('vue-i18n', () => ({ useI18n: () => ({ t: (key: string) => key }) }))
+vi.mock('@/components/auth/TotpStepUpDialog.vue', () => ({
+ default: {
+ props: ['controller'],
+ template: 'Verify Cancel
'
+ }
+}))
+const request: MCPAuthorization = {
+ response_type: 'code', client_id: 'client-1', redirect_uri: 'https://client.example.com/callback?workspace=team',
+ scope: 'mcp', state: 'opaque+value&with=reserved?characters', code_challenge: 'a'.repeat(43),
+ code_challenge_method: 'S256', resource: 'https://api.example.com/api/v1/mcp'
+}
+const consent: MCPConsent = {
+ client_id: request.client_id, client_name: 'Desktop assistant', redirect_uri: request.redirect_uri,
+ resource: request.resource, scope: 'mcp'
+}
+const redirectURL = `${request.redirect_uri}&code=opaque-code&state=encoded-state`
+const originalLocation = window.location
+const mounted: ReturnType[] = []
+function render() {
+ const wrapper = mount(MCPOAuthAuthorizeView, { global: { stubs: { Icon: true, RouterLink: true } } })
+ mounted.push(wrapper)
+ return wrapper
+}
+beforeEach(() => {
+ vi.clearAllMocks()
+ auth.isAdmin = false
+ routeState.current = reactive({ fullPath: '/oauth/mcp/authorize?request=1', query: { ...request } })
+ previewAuthorization.mockResolvedValue({ ...consent })
+ authorize.mockResolvedValue({ redirect_url: redirectURL })
+ Object.defineProperty(window, 'location', { configurable: true, value: { ...originalLocation, assign } })
+})
+afterEach(() => {
+ mounted.splice(0).forEach(wrapper => wrapper.unmount())
+ Object.defineProperty(window, 'location', { configurable: true, value: originalLocation })
+})
+
+describe('MCP OAuth consent', () => {
+ it('previews the exact query, displays the client and full return address, and waits for explicit consent', async () => {
+ const wrapper = render()
+ await flushPromises()
+ expect(previewAuthorization).toHaveBeenCalledWith(request)
+ expect(wrapper.get('[data-testid="client-name"]').text()).toBe(consent.client_name)
+ expect(wrapper.get('[data-testid="redirect-origin"]').text()).toBe('https://client.example.com')
+ expect(wrapper.get('[data-testid="redirect-uri"]').text()).toBe(request.redirect_uri)
+ expect(wrapper.text()).toContain('mcp.untrustedApplicationHint')
+ expect(authorize).not.toHaveBeenCalled()
+ expect(assign).not.toHaveBeenCalled()
+ expect(wrapper.find('#mcp-consent-scope option[value="admin"]').exists()).toBe(false)
+ await wrapper.get('form').trigger('submit')
+ await flushPromises()
+ expect(authorize).toHaveBeenCalledWith({ authorization: request, approved: true, scope: 'user', read_only: true })
+ expect(assign).toHaveBeenCalledWith(redirectURL)
+ })
+
+ it('allows an omitted OAuth scope without adding or changing request parameters', async () => {
+ delete routeState.current.query.scope
+ const wrapper = render()
+ await flushPromises()
+ await wrapper.get('form').trigger('submit')
+ await flushPromises()
+ const { scope: _scope, ...expected } = request
+ expect(previewAuthorization).toHaveBeenCalledWith(expected)
+ expect(authorize.mock.calls[0][0].authorization).toEqual(expected)
+ })
+
+ it('escapes untrusted application names', async () => {
+ previewAuthorization.mockResolvedValue({ ...consent, client_name: ' ' })
+ const wrapper = render()
+ await flushPromises()
+ expect(wrapper.get('[data-testid="client-name"]').text()).toBe(' ')
+ expect(wrapper.find('[data-testid="client-name"] img').exists()).toBe(false)
+ })
+
+ it.each([
+ { client_id: ['client-1', 'attacker'] },
+ { state: null },
+ { resource: undefined },
+ { response_type: 'token' },
+ { code_challenge_method: 'plain' },
+ { code_challenge: 'short' },
+ { scope: 'mcp admin' },
+ { extra: 'unsupported' }
+ ])('blocks malformed requests before preview: %j', async (override) => {
+ Object.assign(routeState.current.query, override)
+ const wrapper = render()
+ await flushPromises()
+ expect(previewAuthorization).not.toHaveBeenCalled()
+ expect(wrapper.get('[role="alert"]').text()).toBe('mcp.invalidRequest')
+ expect(wrapper.find('[data-testid="approve"]').exists()).toBe(false)
+ expect(authorize).not.toHaveBeenCalled()
+ expect(assign).not.toHaveBeenCalled()
+ })
+
+ it('does not offer approval or follow client redirect when preview is rejected', async () => {
+ previewAuthorization.mockRejectedValue({ message: 'Unregistered redirect URI' })
+ const wrapper = render()
+ await flushPromises()
+ expect(wrapper.get('[role="alert"]').text()).toBe('Unregistered redirect URI')
+ expect(wrapper.find('[data-testid="approve"]').exists()).toBe(false)
+ expect(authorize).not.toHaveBeenCalled()
+ expect(assign).not.toHaveBeenCalled()
+ })
+
+ it('rejects a preview whose client or redirect differs from the request', async () => {
+ previewAuthorization.mockResolvedValue({ ...consent, redirect_uri: 'https://unexpected.example/callback' })
+ const wrapper = render()
+ await flushPromises()
+ expect(wrapper.get('[role="alert"]').text()).toBe('mcp.invalidRequest')
+ expect(wrapper.find('form').exists()).toBe(false)
+ })
+
+ it('denies with the original authorization and follows only the server result', async () => {
+ const deniedURL = `${request.redirect_uri}&error=access_denied&state=encoded-state`
+ authorize.mockResolvedValue({ redirect_url: deniedURL })
+ const wrapper = render()
+ await flushPromises()
+ await wrapper.get('[data-testid="deny"]').trigger('click')
+ await flushPromises()
+ expect(authorize).toHaveBeenCalledWith({ authorization: request, approved: false, scope: 'user', read_only: true })
+ expect(assign).toHaveBeenCalledWith(deniedURL)
+ })
+
+ it('requires admin step-up before retrying approval and keeps selected permissions', async () => {
+ auth.isAdmin = true
+ authorize.mockRejectedValueOnce({ reason: 'STEP_UP_REQUIRED' }).mockResolvedValueOnce({ redirect_url: redirectURL })
+ const wrapper = render()
+ await flushPromises()
+ expect((wrapper.get('#mcp-consent-scope').element as HTMLSelectElement).value).toBe('user')
+ await wrapper.get('#mcp-consent-scope').setValue('admin')
+ await wrapper.get('#mcp-consent-permissions').setValue('false')
+ await wrapper.get('form').trigger('submit')
+ await flushPromises()
+ expect(authorize).toHaveBeenCalledTimes(1)
+ expect(assign).not.toHaveBeenCalled()
+ await wrapper.get('[data-testid="step-up-verify"]').trigger('click')
+ await flushPromises()
+ expect(authorize).toHaveBeenCalledTimes(2)
+ expect(authorize.mock.calls[1][0]).toEqual({ authorization: request, approved: true, scope: 'admin', read_only: false })
+ expect(assign).toHaveBeenCalledWith(redirectURL)
+ })
+
+ it('explains that administrator write access always needs two-factor verification', async () => {
+ auth.isAdmin = true
+ const wrapper = render()
+ await flushPromises()
+ expect(wrapper.find('[data-testid="admin-write-hint"]').exists()).toBe(false)
+ await wrapper.get('#mcp-consent-permissions').setValue('false')
+ expect(wrapper.find('[data-testid="admin-write-hint"]').exists()).toBe(false)
+ await wrapper.get('#mcp-consent-scope').setValue('admin')
+ expect(wrapper.get('[data-testid="admin-write-hint"]').text()).toBe('mcp.adminWriteHint')
+ await wrapper.get('#mcp-consent-permissions').setValue('true')
+ expect(wrapper.find('[data-testid="admin-write-hint"]').exists()).toBe(false)
+ })
+
+ it('cancels admin step-up without granting access', async () => {
+ auth.isAdmin = true
+ authorize.mockRejectedValue({ reason: 'STEP_UP_REQUIRED' })
+ const wrapper = render()
+ await flushPromises()
+ await wrapper.get('#mcp-consent-scope').setValue('admin')
+ await wrapper.get('form').trigger('submit')
+ await flushPromises()
+ await wrapper.get('[data-testid="step-up-cancel"]').trigger('click')
+ await flushPromises()
+ expect(authorize).toHaveBeenCalledTimes(1)
+ expect(assign).not.toHaveBeenCalled()
+ expect(wrapper.find('[role="alert"]').exists()).toBe(false)
+ expect((wrapper.get('[data-testid="approve"]').element as HTMLButtonElement).disabled).toBe(false)
+ })
+
+ it('reports submission failures without navigating', async () => {
+ authorize.mockRejectedValue({ message: 'Permission denied' })
+ const wrapper = render()
+ await flushPromises()
+ await wrapper.get('form').trigger('submit')
+ await flushPromises()
+ expect(wrapper.get('[role="alert"]').text()).toBe('Permission denied')
+ expect(assign).not.toHaveBeenCalled()
+ })
+
+ it.each(['https://attacker.example/callback', 'javascript:alert(1)', 'https://client.example.com/other'])('rejects unexpected server redirects: %s', async (destination) => {
+ authorize.mockResolvedValue({ redirect_url: destination })
+ const wrapper = render()
+ await flushPromises()
+ await wrapper.get('form').trigger('submit')
+ await flushPromises()
+ expect(wrapper.get('[role="alert"]').text()).toBe('mcp.invalidRedirect')
+ expect(assign).not.toHaveBeenCalled()
+ })
+
+ it('submits the query captured at preview even if its source object changes', async () => {
+ const wrapper = render()
+ await flushPromises()
+ routeState.current.query.state = 'changed-after-preview'
+ await wrapper.get('form').trigger('submit')
+ await flushPromises()
+ expect(authorize.mock.calls[0][0].authorization).toEqual(request)
+ })
+
+ it('clears old consent on route changes and ignores a late preview response', async () => {
+ let resolveFirst!: (value: MCPConsent) => void
+ previewAuthorization.mockReturnValueOnce(new Promise(resolve => { resolveFirst = resolve }))
+ const wrapper = render()
+ routeState.current.query = { ...request, client_id: 'client-2' }
+ routeState.current.fullPath = '/oauth/mcp/authorize?request=2'
+ previewAuthorization.mockResolvedValueOnce({ ...consent, client_id: 'client-2', client_name: 'Second client' })
+ await flushPromises()
+ expect(wrapper.get('[data-testid="client-name"]').text()).toBe('Second client')
+ resolveFirst(consent)
+ await flushPromises()
+ expect(wrapper.get('[data-testid="client-name"]').text()).toBe('Second client')
+ })
+})
diff --git a/frontend/src/views/user/MCPView.vue b/frontend/src/views/user/MCPView.vue
new file mode 100644
index 0000000000..3c50ca1d51
--- /dev/null
+++ b/frontend/src/views/user/MCPView.vue
@@ -0,0 +1,179 @@
+
+
+
+
+
+
+
+
+
+
{{ t('mcp.connectionTitle') }}
+
{{ t('mcp.connectionDescription') }}
+
+
+
+
{{ t('mcp.endpoint') }}
+
+
+ {{ t('mcp.copyEndpoint') }}
+
+
+
{{ connectionError }}
+
{{ t('common.refresh') }}
+
+
+ {{ t('mcp.connectStep1') }}
+ {{ t('mcp.connectStep2') }}
+ {{ t('mcp.connectStep3') }}
+
+
+ {{ t('mcp.capabilities') }}
+
+
+
+
+
+
{{ t('mcp.grantsTitle') }}
+
{{ t('mcp.grantsDescription') }}
+
+
{{ t('common.refresh') }}
+
+
+
{{ loadError }}
+
{{ t('mcp.loading') }}
+
{{ t('mcp.empty') }}
+
+
+
+
+ {{ grant.client_name }}
+ {{ grant.scope === 'admin' ? t('mcp.adminScope') : t('mcp.userScope') }}
+ {{ grant.read_only ? t('mcp.readOnly') : t('mcp.readWrite') }}
+ {{ grantStatus(grant) }}
+
+
{{ grant.client_id }}
+
+ {{ t('mcp.createdAt', { date: formatDate(grant.created_at) }) }}
+ {{ t('mcp.expiresAt', { date: formatDate(grant.expires_at) }) }}
+ {{ grant.last_used_at ? t('mcp.lastUsedAt', { date: formatDate(grant.last_used_at) }) : t('mcp.neverUsed') }}
+
+
+ {{ t('mcp.revoke') }}
+
+
+
+
+
+
+
+ {{ t('mcp.revokeConfirm', { name: revokeTarget?.client_name || '' }) }}
+ {{ revokeError }}
+
+
+ {{ t('common.cancel') }}
+ {{ revoking ? t('common.processing') : t('mcp.revoke') }}
+
+
+
+
+
+
+
diff --git a/frontend/src/views/user/__tests__/MCPView.spec.ts b/frontend/src/views/user/__tests__/MCPView.spec.ts
new file mode 100644
index 0000000000..61fef89c61
--- /dev/null
+++ b/frontend/src/views/user/__tests__/MCPView.spec.ts
@@ -0,0 +1,150 @@
+import { flushPromises, mount } from '@vue/test-utils'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import MCPView from '../MCPView.vue'
+import type { MCPGrant } from '@/api/mcp'
+
+const { getConnectionConfig, listGrants, revokeGrant, copyToClipboard, showSuccess } = vi.hoisted(() => ({
+ getConnectionConfig: vi.fn(), listGrants: vi.fn(), revokeGrant: vi.fn(), copyToClipboard: vi.fn(), showSuccess: vi.fn()
+}))
+vi.mock('@/api/mcp', () => ({ mcpAPI: { getConnectionConfig, listGrants, revokeGrant } }))
+vi.mock('@/stores/app', () => ({ useAppStore: () => ({ showSuccess }) }))
+vi.mock('@/composables/useClipboard', () => ({ useClipboard: () => ({ copyToClipboard }) }))
+vi.mock('@/utils/format', () => ({ formatDate: (value: string) => value }))
+vi.mock('@/components/layout/AppLayout.vue', () => ({ default: { template: ' ' } }))
+vi.mock('vue-i18n', () => ({ useI18n: () => ({ t: (key: string) => key }) }))
+
+const item: MCPGrant = {
+ id: 'grant-1', client_id: 'client-1', client_name: 'Desktop assistant', scope: 'user', read_only: true,
+ created_at: '2026-10-28T00:00:00Z', expires_at: '2099-11-27T00:00:00Z', last_used_at: null,
+ revoked_at: null, invalidated: false
+}
+const mounted: ReturnType[] = []
+function render() {
+ const wrapper = mount(MCPView, {
+ global: {
+ stubs: {
+ BaseDialog: {
+ props: ['show', 'title'], emits: ['close'],
+ template: ''
+ },
+ Icon: true
+ }
+ }
+ })
+ mounted.push(wrapper)
+ return wrapper
+}
+beforeEach(() => {
+ vi.clearAllMocks()
+ getConnectionConfig.mockResolvedValue({ resource: 'https://mcp.example.com/api/v1/mcp' })
+ listGrants.mockResolvedValue([])
+ revokeGrant.mockResolvedValue(undefined)
+})
+afterEach(() => { mounted.splice(0).forEach(wrapper => wrapper.unmount()) })
+
+describe('MCP OAuth connections', () => {
+ it('shows OAuth instructions and only copies the server URL, without static credential creation', async () => {
+ const wrapper = render()
+ await flushPromises()
+ expect(getConnectionConfig).toHaveBeenCalledTimes(1)
+ expect(listGrants).toHaveBeenCalledTimes(1)
+ expect((wrapper.get('#mcp-endpoint').element as HTMLInputElement).value).toBe('https://mcp.example.com/api/v1/mcp')
+ expect(wrapper.text()).toContain('mcp.connectStep2')
+ expect(wrapper.text()).toContain('mcp.empty')
+ expect(wrapper.find('form').exists()).toBe(false)
+ expect(wrapper.find('[data-testid="create-token"]').exists()).toBe(false)
+ expect(wrapper.find('textarea').exists()).toBe(false)
+ expect(wrapper.html()).not.toMatch(/Bearer|mcp-new-token|mcp-secret/)
+ await wrapper.get('[data-testid="copy-endpoint"]').trigger('click')
+ expect(copyToClipboard).toHaveBeenCalledWith('https://mcp.example.com/api/v1/mcp')
+ })
+
+ it('does not guess the resource when server configuration fails and keeps grants usable', async () => {
+ getConnectionConfig.mockRejectedValueOnce({ message: 'MCP public URL is not configured correctly' })
+ listGrants.mockResolvedValue([item])
+ const wrapper = render()
+ await flushPromises()
+ expect(wrapper.get('[role="alert"]').text()).toBe('MCP public URL is not configured correctly')
+ expect((wrapper.get('#mcp-endpoint').element as HTMLInputElement).value).toBe('')
+ expect((wrapper.get('[data-testid="copy-endpoint"]').element as HTMLButtonElement).disabled).toBe(true)
+ expect(wrapper.find('[data-grant-id="grant-1"] button').exists()).toBe(true)
+ await wrapper.get('[data-testid="retry-connection"]').trigger('click')
+ await flushPromises()
+ expect(wrapper.find('[role="alert"]').exists()).toBe(false)
+ expect((wrapper.get('#mcp-endpoint').element as HTMLInputElement).value).toBe('https://mcp.example.com/api/v1/mcp')
+ expect((wrapper.get('[data-testid="copy-endpoint"]').element as HTMLButtonElement).disabled).toBe(false)
+ expect(listGrants).toHaveBeenCalledTimes(1)
+ })
+
+ it('disables URL copying while configuration is loading independently from grants', async () => {
+ let resolveConfig!: (value: { resource: string }) => void
+ getConnectionConfig.mockReturnValueOnce(new Promise<{ resource: string }>(resolve => { resolveConfig = resolve }))
+ const wrapper = render()
+ await flushPromises()
+ expect(wrapper.text()).toContain('mcp.empty')
+ expect((wrapper.get('[data-testid="copy-endpoint"]').element as HTMLButtonElement).disabled).toBe(true)
+ resolveConfig({ resource: 'https://configured.example.com/api/v1/mcp' })
+ await flushPromises()
+ expect((wrapper.get('#mcp-endpoint').element as HTMLInputElement).value).toBe('https://configured.example.com/api/v1/mcp')
+ })
+
+ it('loads authorized applications and shows their permissions', async () => {
+ listGrants.mockResolvedValue([item, { ...item, id: 'grant-2', scope: 'admin', read_only: false }])
+ const wrapper = render()
+ await flushPromises()
+ expect(wrapper.get('[data-grant-id="grant-1"]').text()).toContain('Desktop assistant')
+ expect(wrapper.get('[data-grant-id="grant-1"]').text()).toContain('mcp.readOnly')
+ expect(wrapper.get('[data-grant-id="grant-2"]').text()).toContain('mcp.adminScope')
+ expect(wrapper.get('[data-grant-id="grant-2"]').text()).toContain('mcp.readWrite')
+ })
+
+ it('keeps loading failures visible and can refresh', async () => {
+ listGrants.mockRejectedValueOnce({ message: 'Service unavailable' }).mockResolvedValueOnce([item])
+ const wrapper = render()
+ await flushPromises()
+ expect(wrapper.get('[role="alert"]').text()).toBe('Service unavailable')
+ await wrapper.get('[data-testid="refresh-grants"]').trigger('click')
+ await flushPromises()
+ expect(wrapper.find('[role="alert"]').exists()).toBe(false)
+ expect(wrapper.find('[data-grant-id="grant-1"]').exists()).toBe(true)
+ })
+
+ it('revokes only after confirmation and updates the application state', async () => {
+ listGrants.mockResolvedValue([item])
+ const wrapper = render()
+ await flushPromises()
+ await wrapper.get('[data-grant-id="grant-1"] button').trigger('click')
+ expect(revokeGrant).not.toHaveBeenCalled()
+ await wrapper.get('[data-testid="confirm-revoke"]').trigger('click')
+ await flushPromises()
+ expect(revokeGrant).toHaveBeenCalledWith(item.id)
+ expect(wrapper.get('[data-grant-id="grant-1"]').text()).toContain('mcp.revoked')
+ expect(wrapper.find('[data-grant-id="grant-1"] button').exists()).toBe(false)
+ expect(showSuccess).toHaveBeenCalledWith('mcp.revokeSuccess')
+ })
+
+ it('keeps the revoke dialog and grant active when revocation fails', async () => {
+ listGrants.mockResolvedValue([item])
+ revokeGrant.mockRejectedValue({ message: 'Try again later' })
+ const wrapper = render()
+ await flushPromises()
+ await wrapper.get('[data-grant-id="grant-1"] button').trigger('click')
+ await wrapper.get('[data-testid="confirm-revoke"]').trigger('click')
+ await flushPromises()
+ expect(wrapper.get('[role="alert"]').text()).toBe('Try again later')
+ expect(wrapper.get('[data-grant-id="grant-1"]').text()).toContain('mcp.active')
+ expect(wrapper.find('[data-testid="confirm-revoke"]').exists()).toBe(true)
+ })
+
+ it('shows invalidated and expired grants as inactive while allowing revocation', async () => {
+ listGrants.mockResolvedValue([
+ { ...item, invalidated: true },
+ { ...item, id: 'grant-2', expires_at: '2000-01-01T00:00:00Z' }
+ ])
+ const wrapper = render()
+ await flushPromises()
+ expect(wrapper.get('[data-grant-id="grant-1"]').text()).toContain('mcp.invalidated')
+ expect(wrapper.get('[data-grant-id="grant-2"]').text()).toContain('mcp.expired')
+ expect(wrapper.find('[data-grant-id="grant-1"] button').exists()).toBe(true)
+ })
+})
diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts
index 5df99b8faa..5e109ead09 100644
--- a/frontend/vite.config.ts
+++ b/frontend/vite.config.ts
@@ -94,15 +94,11 @@ export default defineConfig(({ mode }) => {
resolve: {
alias: {
'@': resolve(__dirname, 'src'),
- // 使用 vue-i18n 运行时版本,避免 CSP unsafe-eval 问题
+ // 使用 vue-i18n 运行时版本,避免 CSP unsafe-eval 问题;
+ // v10 起 JIT 编译恒开启,消息编译为 AST 对象而非 JS 代码,无需 unsafe-eval
'vue-i18n': 'vue-i18n/dist/vue-i18n.runtime.esm-bundler.js'
}
},
- define: {
- // 启用 vue-i18n JIT 编译,在 CSP 环境下处理消息插值
- // JIT 编译器生成 AST 对象而非 JS 代码,无需 unsafe-eval
- __INTLIFY_JIT_COMPILATION__: true
- },
build: {
outDir: '../backend/internal/web/dist',
emptyOutDir: true,