feat(32.2-02): every consent card state, account switch and login hint

- Loading skeleton (aria-busy, no buttons), Expired (404 or no request,
  no call), Load error with Try again, No grantable scope (Deny only),
  Returning with the continue link for http(s) redirects
- 422 shows scopes_required under the scopes; 5xx, network, 400 and a
  javascript:/data:/vbscript: redirect show decide_failed; ticks kept
- 401 hands over to expireSession; focus follows the state heading
- Use another account: logout() without the router, then login with the
  /connect?request= redirect
- LoginView shows mcp_connect.login_hint when the redirect is /connect
This commit is contained in:
Jakub Zych
2026-11-21 00:48:02 +01:00
parent f46c90f7fb
commit 6900bd1a72
3 changed files with 319 additions and 53 deletions

View File

@@ -1,11 +1,11 @@
<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 { computed, nextTick, onMounted, ref, watch } from 'vue'
import { RouterLink, useRoute, useRouter } from 'vue-router'
import { Bot, CircleAlert, Clock, 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'
import { currentUser, expireSession, logout } 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
@@ -13,17 +13,33 @@ import { currentUser } from '../state/useAuth'
// 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').
// Nothing is posted without a click, even for a client allowed before, and
// neither button gets initial focus or a hotkey (T-32.2-12).
type State = 'loading' | 'ready'
type State = 'loading' | 'ready' | 'expired' | 'load_error' | 'returning'
type InlineError = 'scopes_required' | 'decide_failed'
const route = useRoute()
const router = useRouter()
const CARD = 'flex flex-col gap-[18px] rounded-card bg-white p-8 text-[#141b2d] shadow-login'
const HEADING = 'text-[22px] font-bold tracking-[-0.02em] [overflow-wrap:anywhere]'
const ALERT = 'flex items-center gap-2.5 rounded-control bg-[#fdf0f0] px-3.5 py-3 text-[#c62828]'
const SECONDARY_BUTTON =
'inline-flex h-input items-center justify-center gap-2 rounded-control border border-[#d2d8e2] bg-white font-semibold text-[#141b2d] hover:bg-[#f1f3f7] disabled:opacity-60'
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)
const switching = ref(false)
const inlineError = ref<InlineError | null>(null)
const returnUri = ref('')
const heading = ref<HTMLElement | null>(null)
const alertBlock = ref<HTMLElement | null>(null)
let loadSeq = 0
let settled = false
const requestId = computed(() => {
const value = route.query.request
@@ -31,6 +47,7 @@ const requestId = computed(() => {
})
const scopes = computed(() => consent.value?.scopes ?? [])
const grantable = computed(() => scopes.value.length > 0)
const starChecked = computed(() => checked.value.has('*'))
const selected = computed(() => {
if (starChecked.value) {
@@ -38,7 +55,8 @@ const selected = computed(() => {
}
return scopes.value.map((scope) => scope.name).filter((name) => checked.value.has(name))
})
const canAllow = computed(() => busy.value === null && selected.value.length > 0)
const locked = computed(() => busy.value !== null || switching.value)
const canAllow = computed(() => !locked.value && grantable.value && selected.value.length > 0)
const clientName = computed(() => consent.value?.client.name || consent.value?.client.id || '')
const redirectHost = computed(() => consent.value?.client.redirect_host ?? '')
@@ -67,7 +85,7 @@ const adminValue = computed(() => {
let login = admin?.login?.trim() ?? ''
if (!admin || (name === '' && email === '' && login === '')) {
const user = currentUser.value
name = user ? `${user.first_name} ${user.last_name}`.trim() : ''
name = user ? `${user.first_name ?? ''} ${user.last_name ?? ''}`.trim() : ''
email = user?.email?.trim() ?? ''
login = user?.login ?? ''
}
@@ -77,6 +95,25 @@ const adminValue = computed(() => {
return name !== '' ? name : login
})
/** The host the Returning state names: the redirect's, else the client's. */
const returnHost = computed(() => {
try {
return new URL(returnUri.value).host || redirectHost.value
} catch {
return redirectHost.value
}
})
/** The fallback link is offered only for a web address. */
const returnLink = computed(() => {
try {
const protocol = new URL(returnUri.value).protocol
return protocol === 'http:' || protocol === 'https:' ? returnUri.value : ''
} catch {
return ''
}
})
/** 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)
@@ -89,20 +126,40 @@ function initialTicks(view: MCPConsent): Set<string> {
async function load(): Promise<void> {
const seq = ++loadSeq
state.value = 'loading'
inlineError.value = null
consent.value = null
returnUri.value = ''
const id = requestId.value
if (id === '') {
state.value = 'expired'
return
}
const result = await api.GET('/mcp/consent/{request}', { params: { path: { request: id } } })
if (seq !== loadSeq || !result.data) {
let result
try {
result = await api.GET('/mcp/consent/{request}', { params: { path: { request: id } } })
} catch {
if (seq === loadSeq) {
state.value = 'load_error'
}
return
}
const view = result.data.data
consent.value = view
checked.value = initialTicks(view)
offline.value = true
state.value = 'ready'
if (seq !== loadSeq) {
return
}
if (result.data) {
const view = result.data.data
consent.value = view
checked.value = initialTicks(view)
offline.value = true
state.value = 'ready'
return
}
const status = result.response.status
if (status === 401) {
expireSession(router)
return
}
state.value = status === 404 ? 'expired' : 'load_error'
}
function toggleScope(name: string, on: boolean): void {
@@ -122,13 +179,16 @@ function toggleScope(name: string, on: boolean): void {
}
}
checked.value = next
if (inlineError.value === 'scopes_required') {
inlineError.value = null
}
}
function scopeDisabled(name: string): boolean {
return starChecked.value && name !== '*'
}
/** The server-issued redirect, refused when its scheme could run script. */
/** The server-issued redirect, refused when its scheme could run script (T-32.2-09). */
function safeDestination(uri: string): string | null {
let url: URL
try {
@@ -143,34 +203,102 @@ function safeDestination(uri: string): string | null {
}
async function decide(decision: 'allow' | 'deny'): Promise<void> {
if (busy.value !== null || consent.value === null) {
if (locked.value || consent.value === null || state.value !== 'ready') {
return
}
if (decision === 'allow' && !canAllow.value) {
return
}
busy.value = decision
inlineError.value = null
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) {
let result
try {
result = await api.POST('/mcp/consent/{request}', {
params: { path: { request: requestId.value } },
body:
decision === 'allow'
? {
decision,
scopes: selected.value,
offline_access: consent.value.offline_access ? offline.value : false,
}
: { decision, scopes: [], offline_access: false },
})
} catch {
inlineError.value = 'decide_failed'
return
}
if (result.data) {
const destination = safeDestination(result.data.data.redirect_uri)
if (destination === null) {
inlineError.value = 'decide_failed'
return
}
returnUri.value = destination
state.value = 'returning'
window.location.assign(destination)
return
}
const status = result.response.status
if (status === 401) {
expireSession(router)
} else if (status === 404) {
state.value = 'expired'
} else if (status === 422 && decision === 'allow') {
inlineError.value = 'scopes_required'
} else {
inlineError.value = 'decide_failed'
}
} finally {
busy.value = null
}
}
/** Signs out of this browser only and returns through login to this request (D-06). */
async function switchAccount(): Promise<void> {
if (locked.value) {
return
}
switching.value = true
inlineError.value = null
const redirect = route.fullPath
try {
await logout()
await router.replace({ name: 'login', query: { redirect } })
} catch {
inlineError.value = 'decide_failed'
} finally {
switching.value = false
}
}
// Focus follows the state: the state's heading after every change past the
// first settled render (never Allow or Deny), the alert block for inline errors.
watch(
state,
async (next) => {
if (!settled) {
settled = next !== 'loading'
return
}
await nextTick()
heading.value?.focus()
},
{ flush: 'post' },
)
watch(
inlineError,
async (next) => {
if (next !== null) {
await nextTick()
alertBlock.value?.focus()
}
},
{ flush: 'post' },
)
onMounted(() => {
void load()
})
@@ -193,10 +321,76 @@ watch(requestId, () => {
<span class="text-[18px] font-bold text-white">Summer<span class="text-accent">CMS</span></span>
</div>
<!-- Loading: nothing can be submitted before the request is known. -->
<div v-if="state === 'loading'" data-connect-state="loading" aria-busy="true" :class="CARD">
<h1 ref="heading" tabindex="-1" class="sr-only">{{ t('backend::lang.mcp_connect.page_title') }}</h1>
<span class="size-12 rounded-full bg-[#eceff4]" aria-hidden="true" />
<div class="flex flex-col gap-2" aria-hidden="true">
<span class="h-3 w-56 rounded-[6px] bg-[#eceff4]" />
<span class="h-3 w-40 rounded-[6px] bg-[#eceff4]" />
</div>
<div class="overflow-hidden rounded-inner border border-[#e6e9ef]" aria-hidden="true">
<div
v-for="index in 3"
:key="index"
class="flex min-h-[56px] items-center gap-3 border-t border-[#e6e9ef] px-4 py-3 first:border-t-0"
>
<span class="size-5 shrink-0 rounded-[6px] bg-[#eceff4]" />
<span class="h-3 w-40 rounded-[6px] bg-[#eceff4]" />
</div>
</div>
</div>
<!-- Expired, unknown or used request (404, or no request parameter). -->
<div v-else-if="state === 'expired'" data-connect-state="expired" :class="CARD">
<span class="flex size-12 items-center justify-center rounded-full bg-[#f3f5f8]">
<Clock :size="24" class="text-[#566175]" aria-hidden="true" />
</span>
<div class="flex flex-col gap-2">
<h1 ref="heading" tabindex="-1" :class="HEADING">{{ t('backend::lang.mcp_connect.expired_heading') }}</h1>
<p class="text-[#566175]">{{ t('backend::lang.mcp_connect.expired_body') }}</p>
</div>
<RouterLink to="/" data-action="open-admin" :class="SECONDARY_BUTTON" class="w-full">
{{ t('backend::lang.mcp_connect.open_admin') }}
</RouterLink>
</div>
<!-- Load error: 5xx or network. -->
<div v-else-if="state === 'load_error'" data-connect-state="load-error" :class="CARD">
<h1 ref="heading" tabindex="-1" :class="HEADING">{{ t('backend::lang.mcp_connect.page_title') }}</h1>
<div role="alert" :class="ALERT">
<CircleAlert :size="18" class="shrink-0" aria-hidden="true" />
<span>{{ t('backend::lang.mcp_connect.load_failed') }}</span>
</div>
<button type="button" data-action="retry" :class="SECONDARY_BUTTON" class="w-full" @click="load">
{{ t('backend::lang.mcp_connect.retry') }}
</button>
</div>
<!-- Returning: the browser is leaving for the client. -->
<div v-else-if="state === 'returning'" data-connect-state="returning" :class="CARD">
<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>
<h1 ref="heading" tabindex="-1" :class="HEADING" class="flex items-center gap-2">
<span>{{ t('backend::lang.mcp_connect.returning', { host: returnHost }) }}</span>
<LoaderCircle :size="16" class="shrink-0 animate-spin" aria-hidden="true" />
</h1>
<a
v-if="returnLink"
:href="returnLink"
data-connect-continue
class="text-[13px] text-[#141b2d] underline [overflow-wrap:anywhere]"
>{{ t('backend::lang.mcp_connect.continue', { host: returnHost }) }}</a
>
</div>
<!-- Ready, and No grantable scope when the API returned no scope. -->
<form
v-if="state === 'ready' && consent"
v-else-if="consent"
data-connect-state="ready"
class="flex flex-col gap-[18px] rounded-card bg-white p-8 text-[#141b2d] shadow-login"
:class="CARD"
novalidate
@submit.prevent="decide('allow')"
>
@@ -206,7 +400,7 @@ watch(requestId, () => {
</span>
<div class="flex flex-col gap-2">
<h1 tabindex="-1" class="text-[22px] font-bold tracking-[-0.02em] [overflow-wrap:anywhere]">
<h1 ref="heading" tabindex="-1" :class="HEADING">
{{ t('backend::lang.mcp_connect.heading', { client: clientName }) }}
</h1>
<p class="text-[#566175]">{{ t('backend::lang.mcp_connect.subline') }}</p>
@@ -225,6 +419,15 @@ watch(requestId, () => {
<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>
<button
type="button"
data-action="switch-account"
:disabled="locked"
class="font-semibold text-[#141b2d] underline-offset-2 hover:underline disabled:opacity-60"
@click="switchAccount"
>
{{ t('backend::lang.mcp_connect.switch_account') }}
</button>
</dd>
</div>
<div class="flex flex-col gap-1">
@@ -233,14 +436,27 @@ watch(requestId, () => {
</div>
</dl>
<fieldset :disabled="busy !== null" class="flex min-w-0 flex-col gap-[18px]">
<div
v-if="!grantable"
role="alert"
data-connect-none-grantable
:class="ALERT"
class="items-start"
>
<CircleAlert :size="18" class="mt-0.5 shrink-0" aria-hidden="true" />
<span>{{ t('backend::lang.mcp_connect.none_grantable') }}</span>
</div>
<fieldset v-else :disabled="locked" 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]"
:aria-invalid="inlineError === 'scopes_required' ? 'true' : undefined"
:class="inlineError === 'scopes_required' ? 'border-[#c62828]' : 'border-[#e6e9ef]'"
class="overflow-hidden rounded-inner border"
>
<label
v-for="scope in scopes"
@@ -274,15 +490,22 @@ watch(requestId, () => {
<Info :size="14" class="shrink-0" aria-hidden="true" />
<span>{{ t('backend::lang.api_tokens.scope_all_includes') }}</span>
</p>
<div
v-if="inlineError === 'scopes_required'"
ref="alertBlock"
role="alert"
tabindex="-1"
data-connect-error="scopes_required"
:class="ALERT"
>
<CircleAlert :size="18" class="shrink-0" aria-hidden="true" />
<span>{{ t('backend::lang.api_tokens.scopes_required') }}</span>
</div>
</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]"
/>
<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]">{{
@@ -293,18 +516,32 @@ watch(requestId, () => {
</div>
</fieldset>
<div
v-if="inlineError === 'decide_failed'"
ref="alertBlock"
role="alert"
tabindex="-1"
data-connect-error="decide_failed"
:class="ALERT"
>
<CircleAlert :size="18" class="shrink-0" aria-hidden="true" />
<span>{{ t('backend::lang.mcp_connect.decide_failed') }}</span>
</div>
<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"
:disabled="locked"
:class="SECONDARY_BUTTON"
class="flex-1"
@click="decide('deny')"
>
<LoaderCircle v-if="busy === 'deny'" :size="16" class="animate-spin" aria-hidden="true" />
{{ t('backend::lang.mcp_connect.deny') }}
</button>
<button
v-if="grantable"
type="submit"
data-action="allow"
:disabled="!canAllow"
@@ -315,16 +552,6 @@ watch(requestId, () => {
</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

@@ -1,5 +1,5 @@
<script setup lang="ts">
import { ref } from 'vue'
import { computed, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { CircleAlert, Sun } from '@lucide/vue'
import { loadFieldTypes } from '../app/fieldTypes'
@@ -17,6 +17,12 @@ const password = ref('')
const failed = ref(false)
const busy = ref(false)
// The MCP consent screen sent the admin here: say why they are signing in.
const connectHint = computed(() => {
const target = safeRedirect(route.query.redirect)
return target !== null && new URL(target, 'http://admin.invalid').pathname === '/connect'
})
async function submit(): Promise<void> {
if (busy.value) {
return
@@ -56,6 +62,9 @@ async function submit(): Promise<void> {
@submit.prevent="submit"
>
<h1 class="text-[22px] font-bold tracking-[-0.02em]">{{ t('backend::lang.auth.title') }}</h1>
<p v-if="connectHint" data-login-hint class="text-[13px] text-[#566175]">
{{ t('backend::lang.mcp_connect.login_hint') }}
</p>
<label class="flex flex-col gap-1.5">
<span class="font-semibold">{{ t('backend::lang.auth.login') }}</span>
<input

View File

@@ -5,7 +5,7 @@
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'
import { API, mountApp, notFound, requestsTo, resetState, type Route } from '../helpers'
const REDIRECT = 'https://agent.example.test/callback?code=abc123&state=xyz'
@@ -84,4 +84,34 @@ describe('consent card (UI-SPEC C1)', () => {
}
}
})
it('shows the Expired state when the request is unknown (404 on load)', async () => {
const { wrapper, calls } = await mountApp('/connect?request=req1', {
[`GET ${API}/mcp/consent/req1`]: { status: 404, body: notFound },
})
const card = wrapper.find('[data-connect-state="expired"]')
expect(card.exists()).toBe(true)
expect(card.find('h1').text()).toBe('backend::lang.mcp_connect.expired_heading')
expect(card.find('[data-action="open-admin"]').attributes('href')).toBe('/')
expect(wrapper.find('[data-action="allow"]').exists()).toBe(false)
expect(requestsTo(calls, 'POST', `${API}/mcp/consent/req1`)).toHaveLength(0)
})
it('Use another account signs out and returns through login to the same request', async () => {
const { wrapper, calls, router } = await mountApp('/connect?request=req1', {
...consentRoutes(),
[`POST ${API}/auth/logout`]: { body: { data: {}, meta: {} } },
})
await wrapper.find('[data-action="switch-account"]').trigger('click')
await flushPromises()
expect(requestsTo(calls, 'POST', `${API}/auth/logout`)).toHaveLength(1)
expect(requestsTo(calls, 'POST', `${API}/mcp/consent/req1`)).toHaveLength(0)
expect(router.currentRoute.value.name).toBe('login')
expect(router.currentRoute.value.query.redirect).toBe('/connect?request=req1')
expect(wrapper.find('[data-login-hint]').text()).toBe('backend::lang.mcp_connect.login_hint')
expect(assign).not.toHaveBeenCalled()
})
})