feat(32.2-02): admin consent card at /connect posts the decision and leaves for redirect_uri

- /connect route without shell and without public, so login round-trips back
- ConnectView ready state: client mark, fact box, catalog-order scope picker
  with the token-dialog * rule, Stay connected, Deny and Allow
- Allow/Deny POST /mcp/consent/{request}; the browser leaves through
  window.location.assign after refusing javascript:, data: and vbscript:
- MCPConsent, MCPConsentDecision and AccountItem type aliases
- backend::lang.mcp_connect copy in en and pl; connect page title
- smoke test: ticks, POST body, assign called, router never used
This commit is contained in:
Jakub Zych
2026-11-21 00:42:01 +01:00
parent 1d3e6df6ec
commit f46c90f7fb
7 changed files with 476 additions and 0 deletions

View File

@@ -74,6 +74,12 @@ export type AccountContribution = Schemas['cabana.AccountContributionView']
export type AccountContributionAction = Schemas['cabana.AccountContributionActionView']
/** An account contribution action's answer: the toast message and an optional URL. */
export type AccountActionResult = Schemas['cabana.AccountActionResultView']
/** One row of a contributed My account section with an Items function (id, title, subtitle, meta). */
export type AccountItem = Schemas['cabana.AccountItemView']
/** GET /mcp/consent/{request}: the pending MCP connection request an administrator decides. */
export type MCPConsent = Schemas['cabana.MCPConsentView']
/** POST /mcp/consent/{request}: where the browser goes after Allow or Deny. */
export type MCPConsentDecision = Schemas['cabana.MCPConsentDecisionView']
/** A declared bulk action's answer: the toast message and the affected count. */
export type BulkActionResult = Schemas['cabana.BulkActionResult']
/** Body of a widget action: the record id (absent on create) and fill values. */

View File

@@ -21,6 +21,9 @@ export function pageIndicator(route: RouteLocationNormalizedLoaded): string {
if (route.name === 'plugins') {
return t('backend::lang.plugins.title')
}
if (route.name === 'connect') {
return t('backend::lang.mcp_connect.page_title')
}
if (route.name === 'settings-form') {
return settingsEntry(String(route.params.code ?? ''))?.label ?? String(route.params.code ?? '')
}

View File

@@ -12,6 +12,7 @@ import ReorderView from '../views/ReorderView.vue'
import SettingsFormView from '../views/SettingsFormView.vue'
import SettingsIndexView from '../views/SettingsIndexView.vue'
import AccountView from '../views/AccountView.vue'
import ConnectView from '../views/ConnectView.vue'
import PluginsView from '../views/PluginsView.vue'
import NotFoundView from '../views/NotFoundView.vue'
@@ -74,6 +75,9 @@ export function createAdminRouter(history: RouterHistory = createWebHistory(runt
{ path: '/account', name: 'account', component: AccountView, meta: { shell: true } },
// The read-only Plugins screen (Settings → System, backend.view_plugins).
{ path: '/system/plugins', name: 'plugins', component: PluginsView, meta: { shell: true } },
// The MCP consent card: standalone (no shell) and not public, so an
// anonymous visitor goes through login and comes back here (D-03).
{ path: '/connect', name: 'connect', component: ConnectView },
{ path: '/:vendor/:plugin/:controller', name: 'list', component: ListView, meta: { shell: true } },
{ path: '/:vendor/:plugin/:controller/create', name: 'create', component: FormView, meta: { shell: true } },
// The tree reorder page of a list with config_reorder.yaml (D-09).

View File

@@ -0,0 +1,330 @@
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { Bot, Info, LoaderCircle, Sun } from '@lucide/vue'
import { api } from '../api/client'
import type { MCPConsent } from '../api/types'
import { t } from '../app/i18n'
import { currentUser } from '../state/useAuth'
// The MCP consent card (32.2 UI-SPEC C1). A standalone screen in the login
// flow: the same navy page and white card as LoginView, with light literal
// colours inside the card so it looks the same in light and dark mode. The
// decision is posted with fetch and the browser then leaves for the
// server-issued redirect_uri with window.location.assign: never the router,
// never safeRedirect, never a native form POST (CSP form-action 'self').
type State = 'loading' | 'ready'
const route = useRoute()
const state = ref<State>('loading')
const consent = ref<MCPConsent | null>(null)
const checked = ref<Set<string>>(new Set())
const offline = ref(true)
const busy = ref<'allow' | 'deny' | null>(null)
let loadSeq = 0
const requestId = computed(() => {
const value = route.query.request
return typeof value === 'string' ? value.trim() : ''
})
const scopes = computed(() => consent.value?.scopes ?? [])
const starChecked = computed(() => checked.value.has('*'))
const selected = computed(() => {
if (starChecked.value) {
return ['*']
}
return scopes.value.map((scope) => scope.name).filter((name) => checked.value.has(name))
})
const canAllow = computed(() => busy.value === null && selected.value.length > 0)
const clientName = computed(() => consent.value?.client.name || consent.value?.client.id || '')
const redirectHost = computed(() => consent.value?.client.redirect_host ?? '')
/** A logo only from a same-origin path or an https: URL (T-32.2-10). */
const logoUrl = computed(() => {
const raw = consent.value?.client.logo_url?.trim() ?? ''
if (raw === '') {
return ''
}
if (raw.startsWith('/') && !raw.startsWith('//') && !raw.startsWith('/\\')) {
return raw
}
try {
return new URL(raw).protocol === 'https:' ? raw : ''
} catch {
return ''
}
})
/** The signed-in administrator: the API's view, else the session profile. */
const adminValue = computed(() => {
const admin = consent.value?.admin
let name = admin?.name?.trim() ?? ''
let email = admin?.email?.trim() ?? ''
let login = admin?.login?.trim() ?? ''
if (!admin || (name === '' && email === '' && login === '')) {
const user = currentUser.value
name = user ? `${user.first_name} ${user.last_name}`.trim() : ''
email = user?.email?.trim() ?? ''
login = user?.login ?? ''
}
if (name !== '' && email !== '') {
return t('backend::lang.mcp_connect.admin_with_email', { name, email })
}
return name !== '' ? name : login
})
/** Every shown scope starts ticked except *, unless * is the only one. */
function initialTicks(view: MCPConsent): Set<string> {
const names = view.scopes.map((scope) => scope.name)
if (names.length === 1 && names[0] === '*') {
return new Set(names)
}
return new Set(names.filter((name) => name !== '*'))
}
async function load(): Promise<void> {
const seq = ++loadSeq
state.value = 'loading'
consent.value = null
const id = requestId.value
if (id === '') {
return
}
const result = await api.GET('/mcp/consent/{request}', { params: { path: { request: id } } })
if (seq !== loadSeq || !result.data) {
return
}
const view = result.data.data
consent.value = view
checked.value = initialTicks(view)
offline.value = true
state.value = 'ready'
}
function toggleScope(name: string, on: boolean): void {
const next = new Set(checked.value)
if (name === '*') {
if (on) {
next.clear()
next.add('*')
} else {
next.delete('*')
}
} else if (!starChecked.value) {
if (on) {
next.add(name)
} else {
next.delete(name)
}
}
checked.value = next
}
function scopeDisabled(name: string): boolean {
return starChecked.value && name !== '*'
}
/** The server-issued redirect, refused when its scheme could run script. */
function safeDestination(uri: string): string | null {
let url: URL
try {
url = new URL(uri)
} catch {
return null
}
if (url.protocol === 'javascript:' || url.protocol === 'data:' || url.protocol === 'vbscript:') {
return null
}
return uri
}
async function decide(decision: 'allow' | 'deny'): Promise<void> {
if (busy.value !== null || consent.value === null) {
return
}
if (decision === 'allow' && !canAllow.value) {
return
}
busy.value = decision
try {
const result = await api.POST('/mcp/consent/{request}', {
params: { path: { request: consent.value.request_id || requestId.value } },
body:
decision === 'allow'
? {
decision,
scopes: selected.value,
offline_access: consent.value.offline_access ? offline.value : false,
}
: { decision, scopes: [], offline_access: false },
})
const destination = result.data ? safeDestination(result.data.data.redirect_uri) : null
if (destination !== null) {
window.location.assign(destination)
}
} finally {
busy.value = null
}
}
onMounted(() => {
void load()
})
watch(requestId, () => {
void load()
})
</script>
<template>
<main
class="flex min-h-screen items-center justify-center px-4"
style="background: radial-gradient(ellipse at 50% 35%, #2b3a5c 0%, #1d2740 60%)"
>
<div class="flex w-full max-w-[480px] flex-col gap-6">
<div class="flex items-center justify-center gap-3">
<span class="flex size-[34px] items-center justify-center rounded-full bg-accent-soft">
<Sun :size="20" class="text-accent" aria-hidden="true" />
</span>
<span class="text-[18px] font-bold text-white">Summer<span class="text-accent">CMS</span></span>
</div>
<form
v-if="state === 'ready' && consent"
data-connect-state="ready"
class="flex flex-col gap-[18px] rounded-card bg-white p-8 text-[#141b2d] shadow-login"
novalidate
@submit.prevent="decide('allow')"
>
<img v-if="logoUrl" :src="logoUrl" alt="" class="size-12 rounded-inner object-contain" />
<span v-else class="flex size-12 items-center justify-center rounded-full bg-[#f3f5f8]">
<Bot :size="24" class="text-[#566175]" aria-hidden="true" />
</span>
<div class="flex flex-col gap-2">
<h1 tabindex="-1" class="text-[22px] font-bold tracking-[-0.02em] [overflow-wrap:anywhere]">
{{ t('backend::lang.mcp_connect.heading', { client: clientName }) }}
</h1>
<p class="text-[#566175]">{{ t('backend::lang.mcp_connect.subline') }}</p>
<p
v-if="consent.consent_required === false"
data-previously-allowed
class="flex items-center gap-2 text-[13px] text-[#566175] [overflow-wrap:anywhere]"
>
<Info :size="14" class="shrink-0" aria-hidden="true" />
<span>{{ t('backend::lang.mcp_connect.previously_allowed', { client: clientName }) }}</span>
</p>
</div>
<dl class="flex flex-col gap-3 rounded-inner bg-[#f3f5f8] px-4 py-3">
<div class="flex flex-col gap-1">
<dt class="font-semibold">{{ t('backend::lang.mcp_connect.signed_in_as') }}</dt>
<dd class="flex flex-col items-start gap-1">
<span data-connect-admin class="[overflow-wrap:anywhere]">{{ adminValue }}</span>
</dd>
</div>
<div class="flex flex-col gap-1">
<dt class="font-semibold">{{ t('backend::lang.mcp_connect.returns_to') }}</dt>
<dd data-connect-host class="font-mono text-[13px] [overflow-wrap:anywhere]">{{ redirectHost }}</dd>
</div>
</dl>
<fieldset :disabled="busy !== null" class="flex min-w-0 flex-col gap-[18px]">
<div class="flex min-w-0 flex-col gap-1.5">
<span id="connect-scopes-label" class="font-semibold">{{ t('backend::lang.api_tokens.scopes') }}</span>
<div
role="group"
aria-labelledby="connect-scopes-label"
data-scope-picker
class="overflow-hidden rounded-inner border border-[#e6e9ef]"
>
<label
v-for="scope in scopes"
:key="scope.name"
:data-scope="scope.name"
:class="scopeDisabled(scope.name) ? 'cursor-not-allowed opacity-60' : 'cursor-pointer'"
class="flex min-h-[56px] items-start gap-3 border-t border-[#e6e9ef] px-4 py-3 first:border-t-0"
>
<input
type="checkbox"
class="mt-0.5 size-5 shrink-0 rounded-[6px] accent-[#22304d]"
:checked="checked.has(scope.name)"
:disabled="scopeDisabled(scope.name)"
@change="toggleScope(scope.name, ($event.target as HTMLInputElement).checked)"
/>
<span class="flex min-w-0 flex-col">
<span class="flex flex-wrap items-center gap-1">
<span class="font-semibold [overflow-wrap:anywhere]">{{ scope.label }}</span>
<span class="font-mono text-[13px] text-[#566175] [overflow-wrap:anywhere]">{{ scope.name }}</span>
<span
v-if="scope.read_only"
class="inline-flex h-6 items-center rounded-pill bg-[#f3f5f8] px-2.5 text-[13px] font-semibold whitespace-nowrap text-[#566175]"
>{{ t('backend::lang.api_tokens.read_only') }}</span
>
</span>
<span class="text-[13px] text-[#566175] [overflow-wrap:anywhere]">{{ scope.description }}</span>
</span>
</label>
</div>
<p v-if="starChecked" data-scope-all-note class="flex items-center gap-2 text-[13px] text-[#566175]">
<Info :size="14" class="shrink-0" aria-hidden="true" />
<span>{{ t('backend::lang.api_tokens.scope_all_includes') }}</span>
</p>
</div>
<div v-if="consent.offline_access" class="overflow-hidden rounded-inner border border-[#e6e9ef]">
<label data-connect-offline class="flex min-h-[56px] cursor-pointer items-start gap-3 px-4 py-3">
<input
v-model="offline"
type="checkbox"
class="mt-0.5 size-5 shrink-0 rounded-[6px] accent-[#22304d]"
/>
<span class="flex min-w-0 flex-col">
<span class="font-semibold">{{ t('backend::lang.mcp_connect.offline') }}</span>
<span class="text-[13px] text-[#566175] [overflow-wrap:anywhere]">{{
t('backend::lang.mcp_connect.offline_description')
}}</span>
</span>
</label>
</div>
</fieldset>
<div class="flex gap-2.5">
<button
type="button"
data-action="deny"
:disabled="busy !== null"
class="inline-flex h-input flex-1 items-center justify-center gap-2 rounded-control border border-[#d2d8e2] bg-white font-semibold text-[#141b2d] hover:bg-[#f1f3f7] disabled:opacity-60"
@click="decide('deny')"
>
<LoaderCircle v-if="busy === 'deny'" :size="16" class="animate-spin" aria-hidden="true" />
{{ t('backend::lang.mcp_connect.deny') }}
</button>
<button
type="submit"
data-action="allow"
:disabled="!canAllow"
class="inline-flex h-input flex-1 items-center justify-center gap-2 rounded-control bg-[#22304d] font-semibold text-white hover:opacity-90 disabled:opacity-60"
>
<LoaderCircle v-if="busy === 'allow'" :size="16" class="animate-spin" aria-hidden="true" />
{{ busy === 'allow' ? t('backend::lang.mcp_connect.allowing') : t('backend::lang.mcp_connect.allow') }}
</button>
</div>
</form>
<div
v-else
data-connect-state="loading"
aria-busy="true"
class="flex flex-col gap-[18px] rounded-card bg-white p-8 text-[#141b2d] shadow-login"
>
<h1 class="sr-only">{{ t('backend::lang.mcp_connect.page_title') }}</h1>
<span class="size-12 rounded-full bg-[#eceff4]" aria-hidden="true" />
</div>
</div>
</main>
</template>

View File

@@ -0,0 +1,87 @@
// Smoke tests of the MCP consent card (Phase 32.2 UI-SPEC C1): a signed-in
// administrator opens /connect?request=…, keeps the ticks and clicks Allow,
// and the browser leaves for the server-issued redirect_uri through
// window.location.assign, never through the router. Fixtures are neutral.
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { enableAutoUnmount, flushPromises } from '@vue/test-utils'
import type { MCPConsent } from '../../src/api/types'
import { API, mountApp, requestsTo, resetState, type Route } from '../helpers'
const REDIRECT = 'https://agent.example.test/callback?code=abc123&state=xyz'
function consentView(overrides: Partial<MCPConsent> = {}): MCPConsent {
return {
request_id: 'req1',
client: { id: 'client-1', name: 'Acme Agent', redirect_host: 'agent.example.test', logo_url: '' },
admin: { login: 'dev', name: 'Dana Dev', email: 'dev@example.test' },
scopes: [
{ name: 'admin:read', label: 'Read the admin', description: 'Read every admin list.', read_only: true, known: true },
{ name: 'acme', label: 'Acme', description: 'Use the acme tools.', read_only: false, known: true },
],
offline_access: true,
consent_required: true,
expires_at: '2026-11-21T12:00:00Z',
...overrides,
}
}
function consentRoutes(view: MCPConsent = consentView(), decide?: Route): Record<string, Route> {
return {
[`GET ${API}/mcp/consent/req1`]: { body: { data: view, meta: {} } },
[`POST ${API}/mcp/consent/req1`]: decide ?? { body: { data: { redirect_uri: REDIRECT }, meta: {} } },
}
}
let assign: ReturnType<typeof vi.fn>
beforeEach(() => {
resetState()
assign = vi.fn()
vi.spyOn(window.location, 'assign').mockImplementation(assign)
})
afterEach(() => {
vi.restoreAllMocks()
document.body.innerHTML = ''
})
enableAutoUnmount(afterEach)
describe('consent card (UI-SPEC C1)', () => {
it('Allow posts the ticked scopes and Stay connected, then leaves for redirect_uri without the router', async () => {
const { wrapper, calls, router } = await mountApp('/connect?request=req1', consentRoutes())
const push = vi.spyOn(router, 'push')
const replace = vi.spyOn(router, 'replace')
expect(router.currentRoute.value.name).toBe('connect')
const card = wrapper.find('[data-connect-state="ready"]')
expect(card.exists()).toBe(true)
// Standalone: no navigation shell around the card.
expect(wrapper.find('nav[aria-label="backend::lang.nav.plugins"]').exists()).toBe(false)
expect(card.find('[data-connect-host]').text()).toBe('agent.example.test')
const scopeBoxes = card.findAll('[data-scope] input[type="checkbox"]')
expect(scopeBoxes).toHaveLength(2)
expect(scopeBoxes.map((box) => (box.element as HTMLInputElement).checked)).toEqual([true, true])
const offline = card.find('[data-connect-offline] input[type="checkbox"]')
expect((offline.element as HTMLInputElement).checked).toBe(true)
// Nothing is posted before the click.
expect(requestsTo(calls, 'POST', `${API}/mcp/consent/req1`)).toHaveLength(0)
await card.trigger('submit')
await flushPromises()
const posts = requestsTo(calls, 'POST', `${API}/mcp/consent/req1`)
expect(posts).toHaveLength(1)
expect(posts[0]!.headers.get('X-Requested-With')).toBe('XMLHttpRequest')
expect(await posts[0]!.json()).toEqual({ decision: 'allow', scopes: ['admin:read', 'acme'], offline_access: true })
expect(assign).toHaveBeenCalledWith(REDIRECT)
for (const spy of [push, replace]) {
expect(spy).not.toHaveBeenCalledWith(REDIRECT)
for (const call of spy.mock.calls) {
expect(JSON.stringify(call)).not.toContain('agent.example.test')
}
}
})
})

View File

@@ -351,6 +351,29 @@ api_tokens:
mcp_connect:
request_not_found: This connection request has expired or does not exist.
no_grantable_scopes: Choose at least one scope you can use.
page_title: Connect an agent
heading: Allow :client to use the admin as you?
subline: The agent gets your permissions, limited to the scopes you tick. It never gets more access than your own account.
signed_in_as: Signed in as
admin_with_email: ":name (:email)"
switch_account: Use another account
returns_to: Returns to
offline: Stay connected
offline_description: The agent can renew its access without asking you again. Untick it and the agent has to be allowed again when its access expires.
previously_allowed: You have allowed :client before.
allow: Allow
allowing: Allowing…
deny: Deny
returning: Returning you to :host…
continue: Continue to :host
login_hint: Sign in to finish connecting your MCP agent.
none_grantable: Your account has none of the permissions this agent asks for. Deny the request, or ask a superuser for the permissions and connect again.
expired_heading: This connection request has expired
expired_body: Connection requests are valid for a few minutes and work only once. Go back to your agent and connect again.
open_admin: Go to the admin panel
load_failed: The connection request could not be loaded. Check your connection and try again.
retry: Try again
decide_failed: Your answer could not be sent. Try again.
myaccount:
menu_label: My account
menu_description: Edit your name, email, subtitle and password, and manage your API tokens.

View File

@@ -373,6 +373,29 @@ api_tokens:
mcp_connect:
request_not_found: To żądanie połączenia wygasło albo nie istnieje.
no_grantable_scopes: Wybierz co najmniej jeden zakres, którego możesz użyć.
page_title: Połącz agenta
heading: Pozwolić aplikacji :client korzystać z panelu w Twoim imieniu?
subline: Agent otrzyma Twoje uprawnienia w granicach zaznaczonych zakresów. Nigdy nie dostanie szerszego dostępu niż Twoje konto.
signed_in_as: Zalogowano jako
admin_with_email: ":name (:email)"
switch_account: Użyj innego konta
returns_to: Wrócisz do
offline: Pozostań połączony
offline_description: Agent może odnawiać dostęp bez ponownego pytania. Po odznaczeniu trzeba będzie ponownie wyrazić zgodę, gdy jego dostęp wygaśnie.
previously_allowed: Aplikacja :client ma już Twoją zgodę.
allow: Zezwól
allowing: Zezwalanie…
deny: Odmów
returning: Wracasz do :host…
continue: Przejdź do :host
login_hint: Zaloguj się, aby dokończyć łączenie agenta MCP.
none_grantable: Twoje konto nie ma żadnego z uprawnień, o które prosi ten agent. Odmów albo poproś superużytkownika o uprawnienia i połącz się ponownie.
expired_heading: Ta prośba o połączenie wygasła
expired_body: Prośba o połączenie jest ważna kilka minut i działa tylko raz. Wróć do agenta i połącz się ponownie.
open_admin: Przejdź do panelu
load_failed: Nie udało się wczytać prośby o połączenie. Sprawdź połączenie i spróbuj ponownie.
retry: Spróbuj ponownie
decide_failed: Nie udało się wysłać odpowiedzi. Spróbuj ponownie.
myaccount:
menu_label: Moje konto
menu_description: Zmień imię, nazwisko, e-mail, podtytuł i hasło oraz zarządzaj tokenami API.