Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
chore(oauth): remove dead push-OTP, repurpose footer to cross-device verify (#2538)
t0saki8a3bfb68ffee
diff --git a/docs/design/mcp-oauth2-1.md b/docs/design/mcp-oauth2-1.mdindex a4b8c2009..e4a65b6d9 100644--- a/docs/design/mcp-oauth2-1.md+++ b/docs/design/mcp-oauth2-1.md@@ -16,18 +16,19 @@> 打开 `/studio/oauth/verify` 输入码完成授权。同设备的 quick-authorize> 面板(依赖 `sessionStorage.ov_console_api_key` 跨 tab 探测)已移除,> 不再需要把 API Key 写到 `localStorage`。-> - OTP push 流程的入口也搬到 Studio:`ConnectionDialog` 增加了 "OAuth-> client OTP" 区块(共用 `IdentityPicker`),可一键生成短期 OTP 给 MCP-> 客户端。`POST /api/v1/auth/otp` 后端端点未变。+> - OTP push 流程(`POST /api/v1/auth/otp` 签发、Studio 里"OAuth client OTP"+> 区块生成短期码交给客户端)从未接通消费端,已整体移除(后端端点 + 前端入口 ++> `otp_ttl_seconds` 配置)。Studio 侧边栏底部的那个槽位改造成"OAuth 验证"入口,+> 直接打开跨设备 `display_code` 验证表单。> - 旧的 `/console` 独立服务(8020 + `openviking.console` Python 包 +> `python -m openviking.console.bootstrap`)已在 #2160 整体下线,本次迁移> 是该 PR commit message 里明确指向的 OAuth follow-up。Caddy 仍保留> `:1934 → openviking:1933` 的 legacy 单上游反代以兼容旧书签,公网 HTTPS> 按 12-public-access 指南在 Caddyfile 里 append `:443` domain block。>-> 下文的 "Phase 1" 描述仍然刻画了 device-flow OTP 的核心思路;新迁移在此-> 之上把 UI 层从 `/console` 替换为 `/studio`,并把 Studio consent 作为同-> 设备主路径。+> 下文的 "Phase 1" 描述仍然刻画了 device-flow 的核心思路(含已移除的 OTP push+> 端点,仅作历史记录);新迁移在此之上把 UI 层从 `/console` 替换为 `/studio`,+> 并把 Studio consent 作为同设备主路径。## Context@@ -186,8 +187,8 @@ URL 走 §4 的 4 级回退。RFC 9728 客户端发现入口。|---|---|---|| `openviking/server/oauth/storage.py` | SQLite 5 张表 + CRUD + GC + verify/find_pending_by_display_code | ~620 || `openviking/server/oauth/provider.py` | `OAuthAuthorizationServerProvider` Protocol 适配;子类化 SDK 的 `AuthorizationCode/RefreshToken/AccessToken` 嵌入 `(account, user, role)`;`authorize()` 自动生成 display_code | ~280 |-| `openviking/server/oauth/router.py` | PRM、authorize page (HTML+JS)、page/status 轮询、`/api/v1/auth/oauth-verify`、legacy `/api/v1/auth/otp` | ~440 |-| `openviking/server/oauth/otp.py` | `generate_otp` / `hash_secret`(stdlib) | ~30 |+| `openviking/server/oauth/router.py` | PRM、authorize page (HTML+JS)、page/status 轮询、`/api/v1/auth/oauth-verify` | ~440 |+| `openviking/server/oauth/otp.py` | `generate_otp`(cross-device display_code)/ `hash_secret`(stdlib) | ~30 || `openviking_cli/utils/config/oauth_config.py` | `OAuthConfig` pydantic | ~70 |### 修改@@ -222,8 +223,7 @@ URL 走 §4 的 4 级回退。RFC 9728 客户端发现入口。| `/oauth/authorize/page/status` | GET | OpenViking | 无 | 返回 `{status: pending\|approved\|expired, redirect_url?}`;status=approved 时原子签发 auth_code 并删除 pending || `/token` | POST | SDK | client auth | SDK 验 PKCE / redirect_uri / client,调 `provider.exchange_authorization_code()` 或 `exchange_refresh_token()` || `/revoke` | POST | SDK | client auth | SDK 调 `provider.revoke_token()` |-| `POST /api/v1/auth/oauth-verify` | POST | OpenViking | 现有 API Key(`Depends(get_request_context)`) | 接受 `{code, decision: approve\|deny}`;approve 时把 caller 身份写入 pending;deny 时删除 pending |-| `POST /api/v1/auth/otp` | POST | OpenViking | 现有 API Key | **legacy push flow**:生成 OTP 绑定调用方身份;保留供 CLI/脚本场景使用 |+| `POST /api/v1/auth/oauth-verify` | POST | OpenViking | 现有 API Key(`Depends(get_request_context)`) | 接受 `{pending_id 或 code, decision: approve\|deny}`;approve 时把 caller 身份写入 pending;deny 时删除 pending |---@@ -294,7 +294,7 @@ server {- `OpenVikingOAuthProvider`(8 个 Protocol 方法)- 自定义 authorize HTML 页 + display_code 显示 + JS 轮询- `POST /api/v1/auth/oauth-verify`(device flow 确认入口)-- `POST /api/v1/auth/otp`(legacy push flow,保留)+- `POST /api/v1/auth/otp`(legacy push flow,**已移除**——从未接通消费端)- `GET /.well-known/oauth-protected-resource`(RFC 9728)- `app.py` 用 `create_auth_routes()` 挂 SDK 路由diff --git a/docs/en/guides/06-mcp-integration.md b/docs/en/guides/06-mcp-integration.mdindex c7d65ad8d..f20cd4855 100644--- a/docs/en/guides/06-mcp-integration.md+++ b/docs/en/guides/06-mcp-integration.md@@ -86,7 +86,7 @@ Add `--scope user` to make the config global (shared across all projects).These clients only accept OAuth 2.1 — API Keys cannot be passed directly.OpenViking ships a native OAuth 2.1 implementation (DCR + PKCE + opaque-tokens, backed by SQLite, with a console-driven OTP authorization page) so+tokens, backed by SQLite, with a Studio consent screen for authorization) sono external proxy is needed.If you already have HTTPS configured, just connect to `https://your-server.com/mcp` — the client will walk you through the authorization flow automatically.diff --git a/docs/en/guides/11-oauth.md b/docs/en/guides/11-oauth.mdindex d6dbce8d6..b89189d1c 100644--- a/docs/en/guides/11-oauth.md+++ b/docs/en/guides/11-oauth.md@@ -97,11 +97,10 @@ server-rendered HTML page at `/oauth/authorize/page`: it displays a 6-char`display_code`, which you type at `/studio/oauth/verify` on another devicethat's already signed in to Studio.-The "push" OTP endpoint `POST /api/v1/auth/otp` is still available for-CLI / scripted scenarios — and the **OAuth client OTP** block in the-Studio sidebar footer's **OAuth setup** entry (opens a dialog on desktop,-routes to `/studio/oauth/setup` on phone) gives you a one-click way to-mint a short-lived OTP to hand to an MCP client.+The Studio sidebar footer's **OAuth verify** entry opens this cross-device+verify form directly (a dialog on desktop, the `/studio/oauth/verify` page on+phone), so you can confirm from an already-signed-in device without first+visiting the authorize page.---@@ -141,9 +140,9 @@ endpoints, so this mode is only useful for local testing with tools like4. **Connect a local MCP client** (e.g. MCP Inspector) to`http://127.0.0.1:1933/mcp`. The client will hit the OAuth flow above andthe browser will land on `/studio/oauth/consent?pending=...`; click- Authorize and the client will receive a token. For push-style scenarios,- use the **OAuth client OTP** block in the sidebar footer's **OAuth- setup** entry (`/studio/oauth/setup` on phone).+ Authorize and the client will receive a token. To confirm from a different+ already-signed-in device, use the sidebar footer's **OAuth verify** entry+ (`/studio/oauth/verify` on phone).For Claude.ai / Claude Desktop on the public internet, see the[Public Access Guide](12-public-access.md).@@ -266,7 +265,6 @@ curl -X POST -H "Authorization: Bearer ovat_..." \"access_token_ttl_seconds": 3600, // 1 hour"refresh_token_ttl_seconds": 2592000, // 30 days"auth_code_ttl_seconds": 300, // 5 minutes- "otp_ttl_seconds": 300, // 5 minutes"db_filename": "oauth.db" // relative to storage.workspace}}@@ -314,8 +312,8 @@ The practical effects:- **Removing** a user (`remove_user`) has the same effect: the fingerprintlookup returns `None` and all the user's OAuth tokens stop working.- **ROOT** keys and **trusted-mode** identities cannot issue OAuth state- (no per-user key to bind to). `/api/v1/auth/otp` and- `/api/v1/auth/oauth-verify` reject these callers with 400.+ (no per-user key to bind to). `/api/v1/auth/oauth-verify` rejects these+ callers with 400.The fingerprint is `sha256(stored_key_value)`, where the stored value iseither the plaintext key (when API key hashing is disabled) or itsdiff --git a/docs/zh/guides/06-mcp-integration.md b/docs/zh/guides/06-mcp-integration.mdindex 544ab06ce..2b56d7f1a 100644--- a/docs/zh/guides/06-mcp-integration.md+++ b/docs/zh/guides/06-mcp-integration.md@@ -84,7 +84,7 @@ claude mcp add --transport http openviking \### Claude.ai / Claude Desktop(OAuth)-这些客户端只接受 OAuth 2.1,不接受 API Key。OpenViking 已经原生实现 OAuth 2.1(DCR + PKCE + opaque token,SQLite 后端,配合 console 驱动的 OTP 授权页),不再需要外部代理。+这些客户端只接受 OAuth 2.1,不接受 API Key。OpenViking 已经原生实现 OAuth 2.1(DCR + PKCE + opaque token,SQLite 后端,配合 Studio consent 授权页),不再需要外部代理。如果你已经为 OpenViking 服务配好了 HTTPS,直接连接 `https://your-server.com/mcp` 端点即可——客户端会自动引导完成 OAuth 授权流程。diff --git a/docs/zh/guides/11-oauth.md b/docs/zh/guides/11-oauth.mdindex 78aa8b46d..50a3218b2 100644--- a/docs/zh/guides/11-oauth.md+++ b/docs/zh/guides/11-oauth.md@@ -83,10 +83,9 @@ sessionStorage 里已经持有 API Key(你登录 Studio 时填的那个),c`/oauth/authorize/page`:页面显示 6 字符 `display_code`,让你在另一台已经登录 Studio 的设备上打开 `/studio/oauth/verify` 输入。-服务端还保留 "push 模式" 的 OTP 端点 `POST /api/v1/auth/otp` 供 CLI/脚本场-景使用。Studio 侧边栏底部"**OAuth 设置**"入口(桌面端弹出对话框,移动端-跳转 `/studio/oauth/setup`)里就有 **OAuth client OTP** 区块,可以一键生成-短期 OTP 交给 MCP 客户端。+Studio 侧边栏底部的"**OAuth 验证**"入口会直接打开这个跨设备验证表单(桌面端+弹出对话框,移动端跳转 `/studio/oauth/verify`),让你在另一台已登录的设备上确认+授权,而不必先打开授权页。---@@ -125,9 +124,9 @@ Claude.ai / Claude Desktop 等线上客户端**只接受公网 HTTPS**,所以4. **接一个本地 MCP 客户端**(例如 MCP Inspector)到`http://127.0.0.1:1933/mcp`。客户端会走上面那套流程,浏览器自动跳到- `/studio/oauth/consent?pending=...`,确认即可拿到 token。如果想用 push- 模式,从侧边栏底部"**OAuth 设置**"入口(`/studio/oauth/setup`)里的- **OAuth client OTP** 区块直接生成。+ `/studio/oauth/consent?pending=...`,确认即可拿到 token。如果想在另一台+ 已登录的设备上确认,用侧边栏底部"**OAuth 验证**"入口(移动端+ `/studio/oauth/verify`)。线上接 Claude.ai / Claude Desktop 走[公网访问指南](12-public-access.md)。@@ -244,7 +243,6 @@ curl -X POST -H "Authorization: Bearer ovat_..." \"access_token_ttl_seconds": 3600, // 1 小时"refresh_token_ttl_seconds": 2592000, // 30 天"auth_code_ttl_seconds": 300, // 5 分钟- "otp_ttl_seconds": 300, // 5 分钟"db_filename": "oauth.db" // 相对 storage.workspace}}@@ -287,8 +285,7 @@ token 拥有的权限 = 颁发它时所用 API Key 的权限,**不更多也不- **删除** 用户(`remove_user`)同理:指纹查找返回 `None`,所有 OAuthtoken 立即停用。- **ROOT** key 和 **trusted-mode** 身份无法签发 OAuth(没有 per-user- key 可绑定)。`/api/v1/auth/otp` 和 `/api/v1/auth/oauth-verify` 会以- 400 拒绝这类调用方。+ key 可绑定)。`/api/v1/auth/oauth-verify` 会以 400 拒绝这类调用方。指纹算法为 `sha256(stored_key_value)`:API Key 哈希未开启时即明文 key的 SHA-256,开启时即 Argon2id 哈希结果的 SHA-256。两种情况下 storeddiff --git a/openviking/server/app.py b/openviking/server/app.pyindex 0a9ff03ce..bdea7a580 100644--- a/openviking/server/app.py+++ b/openviking/server/app.py@@ -539,8 +539,8 @@ def create_app(app.include_router(bot_router, prefix="/bot/v1")# OAuth 2.1: when enabled, mount the official MCP SDK auth routes- # (DCR / authorize / token / metadata) plus our authorize page + OTP- # issuance endpoint. The Provider that backs the SDK routes is built+ # (DCR / authorize / token / metadata) plus our authorize page + consent /+ # verify endpoints. The Provider that backs the SDK routes is built# in the lifespan; here we only register the route handlers, since the# SDK routes inspect request.app.state at call time.try:@@ -552,14 +552,14 @@ def create_app(from openviking.server.oauth.router import router as oauth_router- # Custom routes (authorize page + /api/v1/auth/otp).+ # Custom routes (authorize page + consent / verify endpoints).app.include_router(oauth_router)# SDK-owned routes (DCR / authorize / token / metadata / revoke).# We need a live Provider here; create_auth_routes captures it by# reference. Re-build the same construction the lifespan does so# the routes work as soon as they're hit (lifespan re-binds the- # same instance to app.state for the OTP / authorize-page path).+ # same instance to app.state for the consent / authorize-page path).from pathlib import Path as _Pathfrom openviking.server.oauth.provider import OpenVikingOAuthProvider@@ -611,7 +611,7 @@ def create_app(app.routes.extend(sdk_routes)app.state.oauth_config = ov_cfg.oauthlogger.info(- "OAuth 2.1 routes mounted (SDK + authorize-page + otp): %s",+ "OAuth 2.1 routes mounted (SDK + authorize-page + consent): %s",[r.path for r in sdk_routes],)except Exception as e: # noqa: BLE001diff --git a/openviking/server/oauth/__init__.py b/openviking/server/oauth/__init__.pyindex 32469ca19..fac24a7b5 100644--- a/openviking/server/oauth/__init__.py+++ b/openviking/server/oauth/__init__.py@@ -1,3 +1,7 @@# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.# SPDX-License-Identifier: AGPL-3.0-"""OAuth 2.1 (MCP-flavored) server package — Phase 1: OTP-only authorization."""+"""OAuth 2.1 (MCP-flavored) server package.++Authorization happens in OpenViking Studio: the consent screen (same device)+or a cross-device fallback where the user re-types a 6-character display code.+"""diff --git a/openviking/server/oauth/otp.py b/openviking/server/oauth/otp.pyindex 38f5272f6..ff00fa0ac 100644--- a/openviking/server/oauth/otp.py+++ b/openviking/server/oauth/otp.py@@ -1,6 +1,11 @@# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.# SPDX-License-Identifier: AGPL-3.0-"""OTP and short-code utilities for the OAuth 2.1 Phase-1 OTP grant."""+"""Short-code and secret-hashing utilities for the OAuth 2.1 server.++``generate_otp`` mints the 6-character cross-device ``display_code`` shown on+the authorize page; ``hash_secret`` indexes auth codes / refresh / access+tokens. (The module name is retained for import stability.)+"""from __future__ import annotations@@ -8,7 +13,7 @@ import hashlibimport secrets# 32-character alphabet (24 letters + 8 digits) with visually ambiguous-# glyphs removed: O / 0 / I / 1. Used for the human-typed OTPs.+# glyphs removed: O / 0 / I / 1. Used for the human-typed cross-device codes._OTP_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"OTP_LENGTH = 6@@ -21,7 +26,7 @@ def generate_otp(length: int = OTP_LENGTH) -> str:def hash_secret(plain: str) -> str:- """SHA-256 hex digest used to index OTPs / auth codes / refresh tokens.+ """SHA-256 hex digest used to index auth codes / refresh / access tokens.All three are high-entropy random tokens (≥ 128 bits), so a fast unsalteddigest is sufficient — Argon2 is reserved for low-entropy user passwords.diff --git a/openviking/server/oauth/router.py b/openviking/server/oauth/router.pyindex 7f9115bf4..56e71ff1f 100644--- a/openviking/server/oauth/router.py+++ b/openviking/server/oauth/router.py@@ -14,9 +14,6 @@ metadata) is delegated to the official ``mcp.server.auth`` SDK (mounted frompending OAuth authorization. Accepts either ``pending_id`` (Studioconsent path) or ``code`` (the 6-character display_code typed on across-device fallback page).-- ``POST /api/v1/auth/otp`` — short-code issuance, authenticated with the- caller's existing API key. The OTP is bound to that API key's identity- (account / user / role) so it can be redeemed on the authorize page.- ``GET /oauth/authorize/page`` — server-rendered cross-device fallback.Default ``provider.authorize()`` redirects to ``/studio/oauth/consent``instead; this HTML page is reached only when the user clicks "Use@@ -37,7 +34,6 @@ from pydantic import AnyHttpUrl, BaseModel, Fieldfrom openviking.server.auth import get_request_contextfrom openviking.server.identity import RequestContext-from openviking.server.oauth.otp import generate_otpfrom openviking.server.oauth.provider import OpenVikingOAuthProviderfrom openviking.server.oauth.storage import OAuthStorefrom openviking_cli.exceptions import (@@ -506,77 +502,3 @@ async def oauth_verify("client_name": client.client_name if client else None,})---# ----------------------------------------------------------------------------# POST /api/v1/auth/otp-# ------------------------------------------------------------------------------class OTPRequest(BaseModel):- ttl_seconds: Optional[int] = Field(- default=None, ge=60, le=600, description="Override OTP lifetime (60-600 seconds)"- )---class OTPResponse(BaseModel):- otp: str- expires_at: int- ttl_seconds: int--[email protected]("/api/v1/auth/otp", response_model=OTPResponse)-async def issue_otp(- request: Request,- body: Optional[OTPRequest] = None,- ctx: RequestContext = Depends(get_request_context),-) -> JSONResponse:- """Issue a one-time passcode bound to the caller's identity.-- The caller must already be authenticated with an API key (or other- bearer accepted by ``resolve_identity``); the resulting OTP carries- that account / user / role triple, so any OAuth client that submits- the OTP on the authorize page is granted that identity.- """- store, provider = _get_store_and_provider(request)-- # Same gate as oauth_verify: an OAuth-issued bearer cannot mint a new- # OTP and re-launch the authorization flow. See router note on- # /api/v1/auth/oauth-verify.- if ctx.from_oauth:- raise PermissionDeniedError(- "OAuth-issued tokens cannot issue OTPs. "- "Use your API key or sign in to OpenViking Studio."- )-- cfg = getattr(request.app.state, "oauth_config", None)- default_ttl = getattr(cfg, "otp_ttl_seconds", 300) if cfg else 300- ttl = body.ttl_seconds if body and body.ttl_seconds else default_ttl- if ttl < 60 or ttl > 600:- raise InvalidArgumentError("ttl_seconds must be between 60 and 600")-- # See oauth_verify for the rationale: an OTP that can't be tied back to- # a real, current API key cannot uphold the lifecycle-binding invariant.- api_key_manager = getattr(request.app.state, "api_key_manager", None)- caller_fp: Optional[str] = None- if api_key_manager is not None and hasattr(api_key_manager, "get_user_key_fingerprint"):- caller_fp = api_key_manager.get_user_key_fingerprint(ctx.user.account_id, ctx.user.user_id)- if not caller_fp:- raise InvalidArgumentError(- "OTP issuance requires a caller with a registered API key "- "(ROOT or trusted-mode identities cannot issue OAuth OTPs)."- )-- otp = generate_otp()- expires_at = await store.insert_otp(- otp_plain=otp,- account_id=ctx.user.account_id,- user_id=ctx.user.user_id,- role=ctx.role.value,- authorizing_key_fp=caller_fp,- ttl_seconds=ttl,- )- return JSONResponse(- {"otp": otp, "expires_at": expires_at, "ttl_seconds": ttl},- headers={"Cache-Control": "no-store"},- )diff --git a/openviking/server/oauth/storage.py b/openviking/server/oauth/storage.pyindex d9606bd3b..9a2d8f1cd 100644--- a/openviking/server/oauth/storage.py+++ b/openviking/server/oauth/storage.py@@ -2,10 +2,10 @@# SPDX-License-Identifier: AGPL-3.0"""SQLite-backed OAuth state storage.-Holds three tables — DCR clients, short-lived codes (auth codes + OTPs share-this table, distinguished by ``kind``), and refresh tokens. Uses stdlib-``sqlite3`` wrapped in ``asyncio.to_thread`` for async ergonomics; Phase 1-QPS doesn't justify the new ``aiosqlite`` dependency.+Holds three tables — DCR clients, short-lived codes (the ``oauth_codes``+table, keyed by ``kind``; only authorization codes are written today), and+refresh tokens. Uses stdlib ``sqlite3`` wrapped in ``asyncio.to_thread`` for+async ergonomics; current QPS doesn't justify the new ``aiosqlite`` dependency.Concurrency: a single ``sqlite3.Connection`` is shared across worker threads(``check_same_thread=False``). Every DB access — both reads and writes —@@ -13,7 +13,7 @@ serializes through ``self._lock``, because the stdlib connection's cursorstate is not safe for concurrent use across threads. With ``isolation_level=None`` each statement is autocommitted, so the lock granularity is per-call.-Atomicity guarantee: one-shot consumption (OTP / auth code / refresh) is done+Atomicity guarantee: one-shot consumption (auth code / refresh) is donevia a single ``UPDATE ... WHERE used = 0 RETURNING ...`` so that two concurrentconsumers cannot both succeed — the loser sees zero rows and is rejected."""@@ -48,6 +48,8 @@ CREATE TABLE IF NOT EXISTS oauth_clients (CREATE TABLE IF NOT EXISTS oauth_codes (code_hash TEXT PRIMARY KEY,+ -- ``otp`` is retained for backward compatibility with existing DBs; only+ -- ``code`` (authorization codes) is written today.kind TEXT NOT NULL CHECK (kind IN ('otp', 'code')),client_id TEXT,redirect_uri TEXT,@@ -59,7 +61,7 @@ CREATE TABLE IF NOT EXISTS oauth_codes (user_id TEXT NOT NULL,role TEXT NOT NULL,-- SHA-256 hex of the API key value that authorized this row. Recorded at- -- OTP issuance / oauth-verify time and copied forward into refresh/access+ -- oauth-verify time and copied forward into refresh/access-- so that key rotation or deletion invalidates every derived OAuth token.-- Nullable only for backwards compat with rows written before this field-- existed; auth path treats NULL as fail-closed.@@ -262,54 +264,6 @@ class OAuthStore:async with self._lock:return await asyncio.to_thread(_query)- # ---- OTPs ------ async def insert_otp(- self,- *,- otp_plain: str,- account_id: str,- user_id: str,- role: str,- authorizing_key_fp: str,- ttl_seconds: int,- ) -> int:- """Insert an OTP row and return its expires_at timestamp.-- ``authorizing_key_fp`` is the SHA-256 fingerprint of the API key the- caller presented when requesting the OTP. It is propagated forward to- any auth code / access / refresh token derived from this OTP so that- rotating or removing the key invalidates the entire downstream chain.- """- now = int(time.time())- expires_at = now + ttl_seconds-- def _insert() -> None:- assert self._conn is not None- self._conn.execute(- "INSERT INTO oauth_codes "- "(code_hash, kind, account_id, user_id, role, "- "authorizing_key_fp, expires_at, created_at) "- "VALUES (?, 'otp', ?, ?, ?, ?, ?, ?)",- (- hash_secret(otp_plain),- account_id,- user_id,- role,- authorizing_key_fp,- expires_at,- now,- ),- )-- async with self._lock:- await asyncio.to_thread(_insert)- return expires_at-- async def consume_otp(self, otp_plain: str) -> Optional[dict[str, Any]]:- """Atomically mark an OTP used and return its identity claims, or None."""- return await self._atomic_consume_code(otp_plain, expected_kind="otp")-# ---- Auth codes ----async def insert_auth_code(@@ -628,9 +582,9 @@ class OAuthStore:"""Revoke all access + refresh tokens for a (account, user) pair.Used when an API key for that user is rotated / deleted: every OAuth- token derived from that user identity gets invalidated. Auth codes- and OTPs for the same user are also wiped to prevent in-flight- completion of an exchange started before the revocation.+ token derived from that user identity gets invalidated. Auth codes for+ the same user are also wiped to prevent in-flight completion of an+ exchange started before the revocation."""def _revoke() -> dict[str, int]:@@ -658,7 +612,7 @@ class OAuthStore:async with self._lock:return await asyncio.to_thread(_revoke)- # ---- Pending authorizations (carry OAuth params across the OTP page) ----+ # ---- Pending authorizations (carry OAuth params across the consent / authorize page) ----async def create_pending_authorization(self,diff --git a/openviking_cli/utils/config/oauth_config.py b/openviking_cli/utils/config/oauth_config.pyindex abf8f7974..5336fee35 100644--- a/openviking_cli/utils/config/oauth_config.py+++ b/openviking_cli/utils/config/oauth_config.py@@ -60,13 +60,6 @@ class OAuthConfig(BaseModel):description="Lifetime of authorization codes in seconds (RFC 6749 recommends short).",)- otp_ttl_seconds: int = Field(- default=300,- ge=60,- le=600,- description="Lifetime of one-time passcodes in seconds.",- )-db_filename: str = Field(default="oauth.db",description="SQLite database filename (relative to OpenVikingConfig.storage.workspace).",diff --git a/tests/server/oauth/test_router.py b/tests/server/oauth/test_router.pyindex f5c634d2d..003ec795f 100644--- a/tests/server/oauth/test_router.py+++ b/tests/server/oauth/test_router.py@@ -1,14 +1,14 @@# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.# SPDX-License-Identifier: AGPL-3.0-"""End-to-end tests for the OAuth flow: DCR → OTP → authorize page → token → /mcp.+"""End-to-end tests for the OAuth flow: DCR → authorize page → verify → token.The flow is:1. Caller registers a client (SDK's RegistrationHandler).-2. Caller, holding a valid API key, requests an OTP from /api/v1/auth/otp.-3. Caller hits /authorize, which redirects to /oauth/authorize/page?pending=...-4. Caller submits the OTP on the authorize page; we 302 back to redirect_uri- with a fresh ?code=...+2. Caller hits /authorize, which redirects to /oauth/authorize/page?pending=...+3. The page shows a 6-character display_code; a signed-in identity confirms by+ POSTing it to /api/v1/auth/oauth-verify, which binds the caller identity.+4. The page polls status and 302s back to redirect_uri with a fresh ?code=...5. Caller exchanges the code at /token (PKCE S256) for an opaque access+refresh.6. Access token is opaque ovat_-prefixed and resolves through auth.py."""@@ -68,7 +68,6 @@ class _StubOAuthCfg:access_token_ttl_seconds: int = 3600refresh_token_ttl_seconds: int = 86400auth_code_ttl_seconds: int = 300- otp_ttl_seconds: int = 300@pytest_asyncio.fixture@@ -88,9 +87,9 @@ async def app_with_oauth(tmp_path):app = FastAPI()app.state.config = ServerConfig(auth_mode="api_key", root_api_key="root-test-1234567890abcd")- # OTP / oauth-verify routes look up the caller's API key fingerprint via+ # The oauth-verify route looks up the caller's API key fingerprint via# ``api_key_manager.get_user_key_fingerprint(account_id, user_id)`` and- # refuse to issue OAuth state if the call returns None. Provide a tiny+ # refuses to bind OAuth state if the call returns None. Provide a tiny# stub that returns a stable fingerprint for the fixture's identity.app.state.api_key_manager = _FpOnlyKeyManager({("acct1", "alice"): "f" * 64})app.state.oauth_store = store@@ -104,8 +103,8 @@ async def app_with_oauth(tmp_path):status_code=ERROR_CODE_TO_HTTP_STATUS.get(exc.code, 500),)- # Override get_request_context so /api/v1/auth/otp can be hit without- # a real APIKeyManager. Returns a fixed identity.+ # Override get_request_context so /api/v1/auth/oauth-verify can be hit+ # without a real APIKeyManager. Returns a fixed identity.from openviking.server.identity import RequestContextfrom openviking_cli.session.user_id import UserIdentifier@@ -219,28 +218,7 @@ async def test_dcr_registers_client(client):# ----------------------------------------------------------------------------# OTP issuance-# ------------------------------------------------------------------------------async def test_otp_endpoint_returns_code(client):- resp = await client.post("/api/v1/auth/otp", json={})- assert resp.status_code == 200, resp.text- body = resp.json()- assert len(body["otp"]) == 6- assert body["ttl_seconds"] == 300- assert body["expires_at"] > 0---async def test_otp_endpoint_rejects_bad_ttl(client):- resp = await client.post("/api/v1/auth/otp", json={"ttl_seconds": 5})- assert resp.status_code in (400, 422)---# ----------------------------------------------------------------------------# Authorize page + OTP submit + token exchange (full happy path)+# Authorize page + display_code verify + token exchange (full happy path)# ---------------------------------------------------------------------------@@ -504,26 +482,11 @@ async def test_refresh_token_rotation(app_with_oauth, client):# ----------------------------------------------------------------------------async def test_otp_endpoint_rejects_caller_without_fingerprint(app_with_oauth, client):- """If the API-key manager has no fingerprint for the caller (e.g. ROOT or- trusted-mode identity), OTP issuance must refuse — there's no key whose- lifetime we could bind the resulting OAuth tokens to."""- app, _, _ = app_with_oauth- # Swap in an empty fingerprint map so get_user_key_fingerprint returns None- # for the fixture's (acct1, alice) identity.- app.state.api_key_manager = _FpOnlyKeyManager({})- resp = await client.post("/api/v1/auth/otp", json={})- assert resp.status_code == 400, resp.text- body = resp.json()- msg = body.get("error_description") or body.get("message") or ""- assert "registered API key" in msg--@pytest.mark.asyncioasync def test_oauth_verify_rejects_verifier_without_fingerprint(app_with_oauth, client):- """oauth-verify must refuse to bind OAuth state to an identity that has- no fingerprint — same invariant as OTP issuance."""+ """oauth-verify must refuse to bind OAuth state to an identity that has no+ fingerprint (e.g. ROOT or trusted-mode) — there's no key whose lifetime the+ resulting OAuth tokens could bind to."""app, store, _ = app_with_oauth_, pending_id, _, _ = await _start_authorize(client, redirect_uri="https://x.test/cb")code = (await store.load_pending_authorization(pending_id))["display_code"]@@ -564,44 +527,10 @@ async def test_dcr_downgrades_confidential_auth_to_public(app_with_oauth, clientassert record.get("client_secret_hash") is None-async def test_otp_rejects_oauth_issued_caller(app_with_oauth, client):- """A caller authenticated via an OAuth bearer (from_oauth=True) MUST- NOT be able to mint new OTPs — that would let a stolen access token- launder itself into a fresh refresh-token chain."""- app, _, _ = app_with_oauth- from openviking.server.identity import RequestContext- from openviking_cli.session.user_id import UserIdentifier-- def _oauth_ctx() -> RequestContext:- return RequestContext(- user=UserIdentifier("acct1", "alice"),- role=Role.USER,- from_oauth=True,- )-- app.dependency_overrides[get_request_context] = _oauth_ctx- try:- resp = await client.post("/api/v1/auth/otp", json={})- assert resp.status_code == 403, resp.text- msg = resp.json().get("error_description") or resp.json().get("message") or ""- assert "OAuth-issued tokens" in msg- finally:- # Reset to the fixture's default (non-OAuth) ctx for other tests.- def _fixed_ctx() -> RequestContext:- return RequestContext(- user=UserIdentifier("acct1", "alice"),- role=Role.USER,- )-- app.dependency_overrides[get_request_context] = _fixed_ctx--@pytest.mark.asyncioasync def test_oauth_verify_rejects_oauth_issued_caller(app_with_oauth, client):- """Same gate as OTP issuance: oauth-verify with an OAuth-issued ctx- must be refused, otherwise short-lived bearers can launder into- long-lived refresh tokens."""+ """oauth-verify with an OAuth-issued ctx (from_oauth=True) must be refused,+ otherwise short-lived bearers can launder into long-lived refresh tokens."""app, store, _ = app_with_oauthfrom openviking.server.identity import RequestContextfrom openviking_cli.session.user_id import UserIdentifierdiff --git a/tests/server/oauth/test_storage.py b/tests/server/oauth/test_storage.pyindex f91947a57..443dbabdc 100644--- a/tests/server/oauth/test_storage.py+++ b/tests/server/oauth/test_storage.py@@ -10,7 +10,7 @@ import timeimport pytestimport pytest_asyncio-from openviking.server.oauth.otp import generate_otp, hash_secret+from openviking.server.oauth.otp import hash_secretfrom openviking.server.oauth.storage import OAuthStore# Test stand-in for an API key fingerprint. Real fps come from@@ -116,101 +116,46 @@ async def test_get_client_missing(store):assert await store.get_client("nope") is None-async def test_otp_consume_returns_identity(store):- otp = generate_otp()- await store.insert_otp(- otp_plain=otp,- account_id="acct1",- user_id="user1",+def _insert_code(store, code, *, account_id="a", user_id="u", ttl_seconds=300):+ return store.insert_auth_code(+ code_plain=code,+ client_id="cx",+ redirect_uri="https://x.test/cb",+ code_challenge="ch",+ code_challenge_method="S256",+ scope=None,+ resource=None,+ account_id=account_id,+ user_id=user_id,role="user",authorizing_key_fp=_FP,- ttl_seconds=300,+ ttl_seconds=ttl_seconds,)- claims = await store.consume_otp(otp)- assert claims is not None- assert claims["account_id"] == "acct1"- assert claims["user_id"] == "user1"- assert claims["role"] == "user"- assert claims["authorizing_key_fp"] == _FP@pytest.mark.asyncio-async def test_otp_double_consume_only_one_wins(store):- otp = generate_otp()- await store.insert_otp(- otp_plain=otp,- account_id="a",- user_id="u",- role="user",- authorizing_key_fp=_FP,- ttl_seconds=300,+async def test_auth_code_concurrent_consume_race(store):+ """Two coroutines racing to consume the same code — exactly one wins."""+ code = "race-code"+ await _insert_code(store, code)+ results = await asyncio.gather(+ store.consume_auth_code(code), store.consume_auth_code(code))- first = await store.consume_otp(otp)- second = await store.consume_otp(otp)- assert first is not None- assert second is None # one-shot---async def test_otp_concurrent_consume_race(store):- """Two coroutines racing to consume the same OTP — exactly one wins."""- otp = generate_otp()- await store.insert_otp(- otp_plain=otp,- account_id="a",- user_id="u",- role="user",- authorizing_key_fp=_FP,- ttl_seconds=300,- )- results = await asyncio.gather(store.consume_otp(otp), store.consume_otp(otp))winners = [r for r in results if r is not None]assert len(winners) == 1@pytest.mark.asyncio-async def test_otp_expired_rejected(store):- otp = generate_otp()- # ttl=60 but we monkey-patch expiry by inserting and waiting — instead,- # directly insert a stale row using a tiny ttl plus manual time travel.- await store.insert_otp(- otp_plain=otp,- account_id="a",- user_id="u",- role="user",- authorizing_key_fp=_FP,- ttl_seconds=60,- )- # Fast path: forge expiry by editing the row to be in the past.+async def test_auth_code_expired_rejected(store):+ code = "stale-code"+ await _insert_code(store, code, ttl_seconds=60)+ # Forge expiry by editing the row to be in the past.assert store._conn is not Nonestore._conn.execute("UPDATE oauth_codes SET expires_at = ? WHERE used = 0",(int(time.time()) - 10,),)- assert await store.consume_otp(otp) is None---async def test_consume_unknown_otp_returns_none(store):- assert await store.consume_otp("NOTREAL") is None---async def test_otp_kind_isolation(store):- """An OTP cannot be consumed via the auth-code path or vice versa."""- otp = generate_otp()- await store.insert_otp(- otp_plain=otp,- account_id="a",- user_id="u",- role="user",- authorizing_key_fp=_FP,- ttl_seconds=300,- )- # Trying to consume as auth code must fail (kind mismatch) and leave OTP usable.- assert await store.consume_auth_code(otp) is None- assert await store.consume_otp(otp) is not None+ assert await store.consume_auth_code(code) is None@pytest.mark.asyncio@@ -380,15 +325,7 @@ async def test_revoke_user_tokens_cascades(store):authorizing_key_fp=_FP,ttl_seconds=3600,)- otp = generate_otp()- await store.insert_otp(- otp_plain=otp,- account_id="acct",- user_id="alice",- role="user",- authorizing_key_fp=_FP,- ttl_seconds=300,- )+ await _insert_code(store, "code-alice", account_id="acct", user_id="alice")counts = await store.revoke_user_tokens(account_id="acct", user_id="alice")assert counts["access_tokens_revoked"] == 1@@ -398,7 +335,7 @@ async def test_revoke_user_tokens_cascades(store):# Alice's everything dead, Bob's untouched.assert await store.load_access("at-1") is Noneassert await store.load_access("at-other") is not None- assert await store.consume_otp(otp) is None+ assert await store.consume_auth_code("code-alice") is None@pytest.mark.asyncio@@ -435,24 +372,10 @@ async def test_gc_keeps_refresh_tombstones_until_natural_expiry(store):@pytest.mark.asyncioasync def test_gc_expired_removes_stale_rows(store):- fresh = generate_otp()- stale = generate_otp()- await store.insert_otp(- otp_plain=fresh,- account_id="a",- user_id="u",- role="user",- authorizing_key_fp=_FP,- ttl_seconds=300,- )- await store.insert_otp(- otp_plain=stale,- account_id="a",- user_id="u",- role="user",- authorizing_key_fp=_FP,- ttl_seconds=300,- )+ fresh = "fresh-code"+ stale = "stale-code"+ await _insert_code(store, fresh)+ await _insert_code(store, stale)# Backdate stale rowassert store._conn is not Nonestore._conn.execute(@@ -462,4 +385,4 @@ async def test_gc_expired_removes_stale_rows(store):deleted = await store.gc_expired()assert deleted["codes_deleted"] >= 1# Fresh row still consumable.- assert await store.consume_otp(fresh) is not None+ assert await store.consume_auth_code(fresh) is not Nonediff --git a/web-studio/src/components/app-shell.tsx b/web-studio/src/components/app-shell.tsxindex 26161c7fb..ad86ddf83 100644--- a/web-studio/src/components/app-shell.tsx+++ b/web-studio/src/components/app-shell.tsx@@ -25,7 +25,7 @@ import {CollapsibleContent,CollapsibleTrigger,} from '#/components/ui/collapsible'-import { OAuthSetupDialog } from '#/components/oauth-setup-dialog'+import { CrossDeviceVerifyDialog } from '#/components/cross-device-verify-dialog'import { ScrollArea } from '#/components/ui/scroll-area'import {Sidebar,@@ -350,10 +350,11 @@ function AppShellInner({ children }: { children: React.ReactNode }) {const currentLanguage = resolveLanguage(i18n.resolvedLanguage ?? i18n.language,)- const [oauthSetupOpen, setOauthSetupOpen] = React.useState(false)+ const [crossDeviceVerifyOpen, setCrossDeviceVerifyOpen] =+ React.useState(false)const settingsActive = pathname === '/settings'- const oauthSetupActive =- pathname === '/oauth/setup' || pathname.startsWith('/oauth/setup/')+ const crossDeviceVerifyActive =+ pathname === '/oauth/verify' || pathname.startsWith('/oauth/verify/')const visibleNavItems = React.useMemo(() =>connectionRole === 'user'@@ -364,8 +365,8 @@ function AppShellInner({ children }: { children: React.ReactNode }) {[connectionRole],)- function openOAuthSetup(): void {- if (oauthSetupActive) {+ function openCrossDeviceVerify(): void {+ if (crossDeviceVerifyActive) {return}// Desktop: open the dialog so the user keeps the current page underneath.@@ -376,9 +377,9 @@ function AppShellInner({ children }: { children: React.ReactNode }) {typeof window.matchMedia === 'function' &&window.matchMedia('(min-width: 768px)').matchesif (useDialog) {- setOauthSetupOpen(true)+ setCrossDeviceVerifyOpen(true)} else {- void navigate({ to: '/oauth/setup' })+ void navigate({ to: '/oauth/verify' })}}@@ -466,14 +467,16 @@ function AppShellInner({ children }: { children: React.ReactNode }) {</SidebarMenuItem><SidebarMenuItem><SidebarMenuButton- onClick={openOAuthSetup}- isActive={oauthSetupActive}- tooltip={t('navigation.oauthSetup.title', { ns: 'appShell' })}+ onClick={openCrossDeviceVerify}+ isActive={crossDeviceVerifyActive}+ tooltip={t('navigation.crossDeviceVerify.title', {+ ns: 'appShell',+ })}className="text-base"><KeyRoundIcon className="size-5" /><span>- {t('navigation.oauthSetup.title', { ns: 'appShell' })}+ {t('navigation.crossDeviceVerify.title', { ns: 'appShell' })}</span></SidebarMenuButton></SidebarMenuItem>@@ -583,9 +586,9 @@ function AppShellInner({ children }: { children: React.ReactNode }) {</ScrollArea></SidebarInset>- <OAuthSetupDialog- open={oauthSetupOpen}- onOpenChange={setOauthSetupOpen}+ <CrossDeviceVerifyDialog+ open={crossDeviceVerifyOpen}+ onOpenChange={setCrossDeviceVerifyOpen}/></SidebarProvider>)diff --git a/web-studio/src/components/cross-device-verify-dialog.tsx b/web-studio/src/components/cross-device-verify-dialog.tsxnew file mode 100644index 000000000..c98b054a1--- /dev/null+++ b/web-studio/src/components/cross-device-verify-dialog.tsx@@ -0,0 +1,40 @@+import { useTranslation } from 'react-i18next'++import { Button } from '#/components/ui/button'+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '#/components/ui/dialog'+import { CrossDeviceVerifyForm } from '#/components/cross-device-verify-form'++export function CrossDeviceVerifyDialog({+ open,+ onOpenChange,+}: {+ open: boolean+ onOpenChange: (open: boolean) => void+}) {+ const { t } = useTranslation(['oauth', 'common'])+ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="max-w-lg">+ <DialogHeader>+ <DialogTitle>{t('verify.title', { ns: 'oauth' })}</DialogTitle>+ <DialogDescription>+ {t('verify.description', { ns: 'oauth' })}+ </DialogDescription>+ </DialogHeader>+ <CrossDeviceVerifyForm />+ <DialogFooter>+ <Button variant="outline" onClick={() => onOpenChange(false)}>+ {t('action.cancel', { ns: 'common' })}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}diff --git a/web-studio/src/components/cross-device-verify-form.tsx b/web-studio/src/components/cross-device-verify-form.tsxnew file mode 100644index 000000000..ad9d6a506--- /dev/null+++ b/web-studio/src/components/cross-device-verify-form.tsx@@ -0,0 +1,255 @@+import * as React from 'react'+import { useTranslation } from 'react-i18next'++import { Button } from '#/components/ui/button'+import { Field, FieldContent, FieldLabel } from '#/components/ui/field'+import {+ IdentityPicker,+ resolveEffectiveApiKey,+} from '#/components/identity-picker'+import type { IdentityPickerValue } from '#/components/identity-picker'+import { Input } from '#/components/ui/input'+import {+ summarizeConnectionIdentity,+ useAppConnection,+} from '#/hooks/use-app-connection'+import { useIdentityDirectory } from '#/hooks/use-identity-directory'++type Phase =+ | { kind: 'idle' }+ | { kind: 'verifying' }+ | { kind: 'success'; clientName: string | null }+ | { kind: 'error'; message: string }++/**+ * Cross-device verify form: enter the 6-character `display_code` shown on the+ * device that started the MCP client login, pick an identity, and approve.+ *+ * Rendered both as the standalone `/oauth/verify` route and inside the sidebar+ * footer's verify dialog, so it carries its own chrome-free layout and the host+ * (Card or Dialog) supplies the title/footer.+ */+export function CrossDeviceVerifyForm() {+ const { t } = useTranslation(['oauth', 'common'])+ const {+ connection,+ isConnectionRoleLoading,+ openConnectionSettings,+ serverMode,+ } = useAppConnection()+ const directory = useIdentityDirectory()++ const currentIdentity = React.useMemo(() => {+ const summary = summarizeConnectionIdentity(connection, serverMode)+ return summary.values?.identity ?? t(summary.labelKey, { ns: 'connection' })+ }, [connection, serverMode, t])++ const [identityValue, setIdentityValue] = React.useState<IdentityPickerValue>(+ () =>+ connection.apiKey ? { mode: 'current' } : { mode: 'custom', apiKey: '' },+ )+ // Set once the user manually picks a mode, so the default-mode effect stops+ // overriding their choice.+ const userTouchedRef = React.useRef(false)+ const handleIdentityChange = React.useCallback(+ (next: IdentityPickerValue) => {+ userTouchedRef.current = true+ setIdentityValue(next)+ },+ [],+ )++ // Default-mode selection (see consent.tsx for the rationale): root has no+ // usable "current" identity, so default to selecting a concrete account/user+ // once the directory is available.+ React.useEffect(() => {+ if (userTouchedRef.current || isConnectionRoleLoading) {+ return+ }+ const desiredMode = connection.apiKey+ ? 'current'+ : directory.available+ ? 'select'+ : 'custom'+ setIdentityValue((prev) => {+ if (prev.mode === desiredMode) {+ return prev+ }+ if (desiredMode === 'current') {+ return { mode: 'current' }+ }+ if (desiredMode === 'select') {+ return {+ mode: 'select',+ accountId: directory.selectedAccountId,+ userId: directory.selectedUserId,+ apiKey:+ directory.resolveUserKey(+ directory.selectedAccountId,+ directory.selectedUserId,+ ) ?? '',+ }+ }+ return { mode: 'custom', apiKey: '' }+ })+ }, [connection.apiKey, directory, isConnectionRoleLoading])++ // Keep the select payload in sync with the directory while in select mode.+ React.useEffect(() => {+ setIdentityValue((prev) => {+ if (prev.mode !== 'select') {+ return prev+ }+ const accountId = directory.selectedAccountId+ const userId = directory.selectedUserId+ const apiKey = directory.resolveUserKey(accountId, userId) ?? ''+ if (+ prev.accountId === accountId &&+ prev.userId === userId &&+ prev.apiKey === apiKey+ ) {+ return prev+ }+ return { mode: 'select', accountId, userId, apiKey }+ })+ }, [directory])++ const [code, setCode] = React.useState('')+ const [phase, setPhase] = React.useState<Phase>({ kind: 'idle' })++ async function submit(+ event: React.FormEvent<HTMLFormElement>,+ ): Promise<void> {+ event.preventDefault()+ const effectiveKey = resolveEffectiveApiKey(+ identityValue,+ connection.apiKey,+ )+ if (!effectiveKey) {+ setPhase({ kind: 'error', message: t('verify.noApiKey') })+ return+ }+ const normalized = code.trim().toUpperCase()+ if (!normalized) {+ return+ }+ setPhase({ kind: 'verifying' })+ try {+ const resp = await fetch('/api/v1/auth/oauth-verify', {+ method: 'POST',+ cache: 'no-store',+ headers: {+ 'Content-Type': 'application/json',+ Authorization: `Bearer ${effectiveKey}`,+ },+ body: JSON.stringify({ code: normalized, decision: 'approve' }),+ })+ if (!resp.ok) {+ const text = await resp.text().catch(() => '')+ setPhase({+ kind: 'error',+ message: extractMessage(text) || String(resp.status),+ })+ return+ }+ const body = (await resp.json()) as {+ client_name?: string | null+ }+ setPhase({ kind: 'success', clientName: body.client_name ?? null })+ } catch (err: unknown) {+ const message = err instanceof Error ? err.message : String(err)+ setPhase({ kind: 'error', message })+ }+ }++ const hasAnyKey = Boolean(+ resolveEffectiveApiKey(identityValue, connection.apiKey),+ )++ if (phase.kind === 'success') {+ return (+ <p className="text-sm text-foreground">+ {phase.clientName+ ? t('verify.success', { clientName: phase.clientName })+ : t('verify.successUnknownClient')}+ </p>+ )+ }++ return (+ <form onSubmit={(event) => void submit(event)} className="grid gap-5">+ {!connection.apiKey && !directory.available ? (+ <div className="grid gap-2 rounded-md border border-dashed p-3 text-sm">+ <p>{t('verify.signInRequired')}</p>+ <Button+ type="button"+ variant="outline"+ size="sm"+ className="w-fit"+ onClick={openConnectionSettings}+ disabled={phase.kind === 'verifying'}+ >+ {t('consent.openConnectionSettings')}+ </Button>+ </div>+ ) : null}++ <IdentityPicker+ value={identityValue}+ onChange={handleIdentityChange}+ currentApiKey={connection.apiKey}+ currentIdentityLabel={currentIdentity}+ directory={directory}+ disabled={phase.kind === 'verifying'}+ />++ <Field>+ <FieldLabel htmlFor="ov-oauth-verify-code">+ {t('verify.codeLabel')}+ </FieldLabel>+ <FieldContent>+ <Input+ id="ov-oauth-verify-code"+ autoFocus+ autoComplete="off"+ inputMode="text"+ maxLength={12}+ placeholder={t('verify.codePlaceholder')}+ value={code}+ onChange={(event) => setCode(event.target.value)}+ disabled={phase.kind === 'verifying'}+ className="font-mono uppercase tracking-widest"+ />+ </FieldContent>+ </Field>++ {phase.kind === 'error' ? (+ <p className="text-sm text-destructive">+ {t('verify.verifyError', { message: phase.message })}+ </p>+ ) : null}++ <div className="flex justify-end">+ <Button+ type="submit"+ disabled={+ phase.kind === 'verifying' || code.trim().length === 0 || !hasAnyKey+ }+ >+ {phase.kind === 'verifying'+ ? t('consent.verifying')+ : t('verify.submit')}+ </Button>+ </div>+ </form>+ )+}++function extractMessage(raw: string): string {+ try {+ const parsed = JSON.parse(raw) as { error?: { message?: string } }+ return parsed.error?.message || raw.slice(0, 200)+ } catch {+ return raw.slice(0, 200)+ }+}diff --git a/web-studio/src/components/oauth-setup-dialog.tsx b/web-studio/src/components/oauth-setup-dialog.tsxdeleted file mode 100644index 0874d3798..000000000--- a/web-studio/src/components/oauth-setup-dialog.tsx+++ /dev/null@@ -1,260 +0,0 @@-import * as React from 'react'-import { useTranslation } from 'react-i18next'-import { ExternalLinkIcon } from 'lucide-react'--import { Button } from '#/components/ui/button'-import {- Card,- CardContent,- CardDescription,- CardHeader,- CardTitle,-} from '#/components/ui/card'-import {- Dialog,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,-} from '#/components/ui/dialog'-import {- IdentityPicker,- resolveEffectiveApiKey,-} from '#/components/identity-picker'-import type { IdentityPickerValue } from '#/components/identity-picker'-import {- summarizeConnectionIdentity,- useAppConnection,-} from '#/hooks/use-app-connection'--type OtpResult = {- otp: string- expires_at: number- ttl_seconds: number-}--type OtpPhase =- | { kind: 'idle' }- | { kind: 'requesting' }- | { kind: 'ready'; result: OtpResult }- | { kind: 'error'; message: string }--const OAUTH_DOCS_URL =- 'https://github.com/volcengine/OpenViking/blob/main/docs/en/guides/11-oauth.md'--export function OAuthSetupDialog({- open,- onOpenChange,-}: {- open: boolean- onOpenChange: (open: boolean) => void-}) {- const { t } = useTranslation(['oauthSetup', 'connection', 'oauth', 'common'])- return (- <Dialog open={open} onOpenChange={onOpenChange}>- <DialogContent className="max-w-2xl">- <DialogHeader>- <DialogTitle>{t('page.title', { ns: 'oauthSetup' })}</DialogTitle>- <DialogDescription>- {t('page.intro', { ns: 'oauthSetup' })}- </DialogDescription>- </DialogHeader>- <a- href={OAUTH_DOCS_URL}- target="_blank"- rel="noopener noreferrer"- className="inline-flex items-center gap-1 text-sm font-medium text-primary hover:underline"- >- {t('page.docsLink', { ns: 'oauthSetup' })}- <ExternalLinkIcon className="size-3.5" />- </a>- <OAuthOtpForm />- <DialogFooter>- <Button variant="outline" onClick={() => onOpenChange(false)}>- {t('cancel', { ns: 'common', keyPrefix: 'action' })}- </Button>- </DialogFooter>- </DialogContent>- </Dialog>- )-}--export function OAuthOtpForm() {- const { t } = useTranslation(['connection', 'oauth'])- const { connection, serverMode } = useAppConnection()- const currentIdentity = React.useMemo(() => {- const summary = summarizeConnectionIdentity(connection, serverMode)- return summary.values?.identity ?? t(summary.labelKey, { ns: 'connection' })- }, [connection, serverMode, t])-- const [identityValue, setIdentityValue] = React.useState<IdentityPickerValue>(- () =>- connection.apiKey ? { mode: 'current' } : { mode: 'custom', apiKey: '' },- )- const [phase, setPhase] = React.useState<OtpPhase>({ kind: 'idle' })- const [remaining, setRemaining] = React.useState(0)- const [copied, setCopied] = React.useState(false)-- React.useEffect(() => {- if (phase.kind !== 'ready') {- return- }- const tick = () => {- const now = Math.floor(Date.now() / 1000)- setRemaining(Math.max(0, phase.result.expires_at - now))- }- tick()- const id = window.setInterval(tick, 1000)- return () => window.clearInterval(id)- }, [phase])-- React.useEffect(() => {- if (!copied) return- const id = window.setTimeout(() => setCopied(false), 1500)- return () => window.clearTimeout(id)- }, [copied])-- async function generateOtp(): Promise<void> {- const effectiveKey = resolveEffectiveApiKey(- identityValue,- connection.apiKey,- )- if (!effectiveKey) {- setPhase({- kind: 'error',- message: t('identityPicker.noCurrent', { ns: 'oauth' }),- })- return- }- setPhase({ kind: 'requesting' })- try {- const resp = await fetch('/api/v1/auth/otp', {- method: 'POST',- cache: 'no-store',- headers: {- 'Content-Type': 'application/json',- Authorization: `Bearer ${effectiveKey}`,- },- body: '{}',- })- if (!resp.ok) {- const text = await resp.text().catch(() => '')- setPhase({- kind: 'error',- message: extractMessage(text) || String(resp.status),- })- return- }- const result = (await resp.json()) as OtpResult- setPhase({ kind: 'ready', result })- } catch (err: unknown) {- const message = err instanceof Error ? err.message : String(err)- setPhase({ kind: 'error', message })- }- }-- async function copyOtp(): Promise<void> {- if (phase.kind !== 'ready') return- try {- await navigator.clipboard.writeText(phase.result.otp)- setCopied(true)- } catch {- // Clipboard may be unavailable (insecure context); ignore.- }- }-- const hasAnyKey = Boolean(- resolveEffectiveApiKey(identityValue, connection.apiKey),- )- const expired = phase.kind === 'ready' && remaining <= 0-- return (- <Card className="gap-3">- <CardHeader className="gap-1.5">- <CardTitle className="text-base">- {t('oauthOtp.title', { ns: 'connection' })}- </CardTitle>- <CardDescription>- {t('oauthOtp.description', { ns: 'connection' })}- </CardDescription>- </CardHeader>- <CardContent className="grid gap-4">- <IdentityPicker- value={identityValue}- onChange={setIdentityValue}- currentApiKey={connection.apiKey}- currentIdentityLabel={currentIdentity}- disabled={phase.kind === 'requesting'}- />-- {phase.kind === 'ready' && !expired ? (- <div className="grid gap-2 rounded-md border bg-muted/40 p-3">- <span className="text-xs text-muted-foreground">- {t('oauthOtp.codeLabel', { ns: 'connection' })}- </span>- <div className="flex items-center gap-3">- <span className="font-mono text-2xl tracking-[0.4em]">- {phase.result.otp}- </span>- <Button- type="button"- variant="outline"- size="sm"- onClick={() => void copyOtp()}- >- {copied- ? t('oauthOtp.copied', { ns: 'connection' })- : t('oauthOtp.copy', { ns: 'connection' })}- </Button>- </div>- <span className="text-xs text-muted-foreground">- {t('oauthOtp.expiresIn', {- ns: 'connection',- seconds: remaining,- })}- </span>- </div>- ) : null}-- {expired ? (- <p className="text-xs text-destructive">- {t('oauthOtp.expired', { ns: 'connection' })}- </p>- ) : null}-- {phase.kind === 'error' ? (- <p className="text-xs text-destructive">- {t('oauthOtp.generateError', {- ns: 'connection',- message: phase.message,- })}- </p>- ) : null}-- <div className="flex justify-end">- <Button- type="button"- variant="outline"- size="sm"- onClick={() => void generateOtp()}- disabled={phase.kind === 'requesting' || !hasAnyKey}- >- {phase.kind === 'ready' && !expired- ? t('oauthOtp.regenerate', { ns: 'connection' })- : t('oauthOtp.generate', { ns: 'connection' })}- </Button>- </div>- </CardContent>- </Card>- )-}--function extractMessage(raw: string): string {- try {- const parsed = JSON.parse(raw) as { error?: { message?: string } }- return parsed.error?.message || raw.slice(0, 200)- } catch {- return raw.slice(0, 200)- }-}diff --git a/web-studio/src/i18n/locales/en.ts b/web-studio/src/i18n/locales/en.tsindex 6b108430c..bc1fa2b91 100644--- a/web-studio/src/i18n/locales/en.ts+++ b/web-studio/src/i18n/locales/en.ts@@ -12,8 +12,8 @@ const en = {home: {title: 'Home',},- oauthSetup: {- title: 'OAuth setup',+ crossDeviceVerify: {+ title: 'OAuth verify',},operations: {title: 'Operations',@@ -100,19 +100,6 @@ const en = {placeholder: 'default',},},- oauthOtp: {- title: 'OAuth client OTP',- description:- 'Generate a short-lived code that an MCP client can submit to authorize as the selected identity.',- generate: 'Generate OTP',- regenerate: 'Regenerate',- copy: 'Copy',- copied: 'Copied',- codeLabel: 'One-time code',- expiresIn: 'Expires in {{seconds}}s',- expired: 'Expired — generate a new code.',- generateError: 'Could not generate OTP: {{message}}',- },},settings: {actions: {@@ -241,14 +228,6 @@ const en = {userCreated: 'User created',},},- oauthSetup: {- page: {- title: 'OAuth setup',- intro:- 'Use this page when authenticating an MCP client via OAuth — for example Claude.ai, Claude Desktop, ChatGPT, or Cursor. Generate a short-lived OTP here, then paste it into the MCP client to bind its connection to the selected identity.',- docsLink: 'Read the OAuth integration guide',- },- },home: {contextCommits: {description:diff --git a/web-studio/src/i18n/locales/zh-CN.ts b/web-studio/src/i18n/locales/zh-CN.tsindex 591f378fb..855cc8b45 100644--- a/web-studio/src/i18n/locales/zh-CN.ts+++ b/web-studio/src/i18n/locales/zh-CN.ts@@ -12,8 +12,8 @@ const zhCN = {home: {title: '首页',},- oauthSetup: {- title: 'OAuth 设置',+ crossDeviceVerify: {+ title: 'OAuth 验证',},operations: {title: '运维',@@ -100,19 +100,6 @@ const zhCN = {placeholder: 'default',},},- oauthOtp: {- title: 'OAuth 客户端 OTP',- description:- '生成一个短期一次性码,让 MCP 客户端凭此以所选身份完成 OAuth 授权。',- generate: '生成 OTP',- regenerate: '重新生成',- copy: '复制',- copied: '已复制',- codeLabel: '一次性码',- expiresIn: '{{seconds}} 秒后失效',- expired: '已过期 —— 请重新生成。',- generateError: '生成 OTP 失败:{{message}}',- },},settings: {actions: {@@ -241,14 +228,6 @@ const zhCN = {userCreated: 'User 已创建',},},- oauthSetup: {- page: {- title: 'OAuth 设置',- intro:- '当你需要让 MCP 客户端(例如 Claude.ai / Claude Desktop / ChatGPT / Cursor)通过 OAuth 完成鉴权时使用本页。在这里生成一个短期 OTP,粘到 MCP 客户端,它就会用所选身份完成 OAuth 授权。',- docsLink: '阅读 OAuth 接入指南',- },- },home: {contextCommits: {description:diff --git a/web-studio/src/routeTree.gen.ts b/web-studio/src/routeTree.gen.tsindex a7e9608be..4f8c425b2 100644--- a/web-studio/src/routeTree.gen.ts+++ b/web-studio/src/routeTree.gen.ts@@ -18,7 +18,6 @@ import { Route as HomeRouteRouteImport } from './routes/home/route'import { Route as IndexRouteImport } from './routes/index'import { Route as SessionsIndexRouteImport } from './routes/sessions/index'import { Route as OauthVerifyRouteImport } from './routes/oauth/verify'-import { Route as OauthSetupRouteImport } from './routes/oauth/setup'import { Route as OauthConsentRouteImport } from './routes/oauth/consent'const SettingsRouteRoute = SettingsRouteRouteImport.update({@@ -66,11 +65,6 @@ const OauthVerifyRoute = OauthVerifyRouteImport.update({path: '/oauth/verify',getParentRoute: () => rootRouteImport,} as any)-const OauthSetupRoute = OauthSetupRouteImport.update({- id: '/oauth/setup',- path: '/oauth/setup',- getParentRoute: () => rootRouteImport,-} as any)const OauthConsentRoute = OauthConsentRouteImport.update({id: '/oauth/consent',path: '/oauth/consent',@@ -86,7 +80,6 @@ export interface FileRoutesByFullPath {'/sessions': typeof SessionsRouteRouteWithChildren'/settings': typeof SettingsRouteRoute'/oauth/consent': typeof OauthConsentRoute- '/oauth/setup': typeof OauthSetupRoute'/oauth/verify': typeof OauthVerifyRoute'/sessions/': typeof SessionsIndexRoute}@@ -98,7 +91,6 @@ export interface FileRoutesByTo {'/retrieval': typeof RetrievalRouteRoute'/settings': typeof SettingsRouteRoute'/oauth/consent': typeof OauthConsentRoute- '/oauth/setup': typeof OauthSetupRoute'/oauth/verify': typeof OauthVerifyRoute'/sessions': typeof SessionsIndexRoute}@@ -112,7 +104,6 @@ export interface FileRoutesById {'/sessions': typeof SessionsRouteRouteWithChildren'/settings': typeof SettingsRouteRoute'/oauth/consent': typeof OauthConsentRoute- '/oauth/setup': typeof OauthSetupRoute'/oauth/verify': typeof OauthVerifyRoute'/sessions/': typeof SessionsIndexRoute}@@ -127,7 +118,6 @@ export interface FileRouteTypes {| '/sessions'| '/settings'| '/oauth/consent'- | '/oauth/setup'| '/oauth/verify'| '/sessions/'fileRoutesByTo: FileRoutesByTo@@ -139,7 +129,6 @@ export interface FileRouteTypes {| '/retrieval'| '/settings'| '/oauth/consent'- | '/oauth/setup'| '/oauth/verify'| '/sessions'id:@@ -152,7 +141,6 @@ export interface FileRouteTypes {| '/sessions'| '/settings'| '/oauth/consent'- | '/oauth/setup'| '/oauth/verify'| '/sessions/'fileRoutesById: FileRoutesById@@ -166,7 +154,6 @@ export interface RootRouteChildren {SessionsRouteRoute: typeof SessionsRouteRouteWithChildrenSettingsRouteRoute: typeof SettingsRouteRouteOauthConsentRoute: typeof OauthConsentRoute- OauthSetupRoute: typeof OauthSetupRouteOauthVerifyRoute: typeof OauthVerifyRoute}@@ -235,13 +222,6 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof OauthVerifyRouteImportparentRoute: typeof rootRouteImport}- '/oauth/setup': {- id: '/oauth/setup'- path: '/oauth/setup'- fullPath: '/oauth/setup'- preLoaderRoute: typeof OauthSetupRouteImport- parentRoute: typeof rootRouteImport- }'/oauth/consent': {id: '/oauth/consent'path: '/oauth/consent'@@ -273,7 +253,6 @@ const rootRouteChildren: RootRouteChildren = {SessionsRouteRoute: SessionsRouteRouteWithChildren,SettingsRouteRoute: SettingsRouteRoute,OauthConsentRoute: OauthConsentRoute,- OauthSetupRoute: OauthSetupRoute,OauthVerifyRoute: OauthVerifyRoute,}export const routeTree = rootRouteImportdiff --git a/web-studio/src/routes/oauth/setup.tsx b/web-studio/src/routes/oauth/setup.tsxdeleted file mode 100644index a07d906e2..000000000--- a/web-studio/src/routes/oauth/setup.tsx+++ /dev/null@@ -1,39 +0,0 @@-import { useTranslation } from 'react-i18next'-import { createFileRoute } from '@tanstack/react-router'-import { ExternalLinkIcon } from 'lucide-react'--import { OAuthOtpForm } from '#/components/oauth-setup-dialog'--export const Route = createFileRoute('/oauth/setup')({- component: OAuthSetupPage,-})--const OAUTH_DOCS_URL =- 'https://github.com/volcengine/OpenViking/blob/main/docs/en/guides/11-oauth.md'--function OAuthSetupPage() {- const { t } = useTranslation('oauthSetup')- return (- <div className="mx-auto w-full max-w-3xl space-y-6 p-4 sm:p-6">- <header className="space-y-2">- <h1 className="text-2xl font-semibold tracking-tight">- {t('page.title')}- </h1>- <p className="max-w-2xl text-sm leading-6 text-muted-foreground">- {t('page.intro')}- </p>- <a- href={OAUTH_DOCS_URL}- target="_blank"- rel="noopener noreferrer"- className="inline-flex items-center gap-1 text-sm font-medium text-primary hover:underline"- >- {t('page.docsLink')}- <ExternalLinkIcon className="size-3.5" />- </a>- </header>-- <OAuthOtpForm />- </div>- )-}diff --git a/web-studio/src/routes/oauth/verify.tsx b/web-studio/src/routes/oauth/verify.tsxindex 29f179982..421cc4719 100644--- a/web-studio/src/routes/oauth/verify.tsx+++ b/web-studio/src/routes/oauth/verify.tsx@@ -1,175 +1,21 @@-import * as React from 'react'import { useTranslation } from 'react-i18next'import { createFileRoute } from '@tanstack/react-router'-import { Button } from '#/components/ui/button'import {Card,CardContent,CardDescription,- CardFooter,CardHeader,CardTitle,} from '#/components/ui/card'-import { Field, FieldContent, FieldLabel } from '#/components/ui/field'-import {- IdentityPicker,- resolveEffectiveApiKey,-} from '#/components/identity-picker'-import type { IdentityPickerValue } from '#/components/identity-picker'-import { Input } from '#/components/ui/input'-import {- summarizeConnectionIdentity,- useAppConnection,-} from '#/hooks/use-app-connection'-import { useIdentityDirectory } from '#/hooks/use-identity-directory'--type Phase =- | { kind: 'idle' }- | { kind: 'verifying' }- | { kind: 'success'; clientName: string | null }- | { kind: 'error'; message: string }+import { CrossDeviceVerifyForm } from '#/components/cross-device-verify-form'export const Route = createFileRoute('/oauth/verify')({component: VerifyPage,})function VerifyPage() {- const { t } = useTranslation(['oauth', 'common'])- const {- connection,- isConnectionRoleLoading,- openConnectionSettings,- serverMode,- } = useAppConnection()- const directory = useIdentityDirectory()-- const currentIdentity = React.useMemo(() => {- const summary = summarizeConnectionIdentity(connection, serverMode)- return summary.values?.identity ?? t(summary.labelKey, { ns: 'connection' })- }, [connection, serverMode, t])-- const [identityValue, setIdentityValue] = React.useState<IdentityPickerValue>(- () =>- connection.apiKey ? { mode: 'current' } : { mode: 'custom', apiKey: '' },- )- // Set once the user manually picks a mode, so the default-mode effect stops- // overriding their choice.- const userTouchedRef = React.useRef(false)- const handleIdentityChange = React.useCallback(- (next: IdentityPickerValue) => {- userTouchedRef.current = true- setIdentityValue(next)- },- [],- )-- // Default-mode selection (see consent.tsx for the rationale): root has no- // usable "current" identity, so default to selecting a concrete account/user- // once the directory is available.- React.useEffect(() => {- if (userTouchedRef.current || isConnectionRoleLoading) {- return- }- const desiredMode = connection.apiKey- ? 'current'- : directory.available- ? 'select'- : 'custom'- setIdentityValue((prev) => {- if (prev.mode === desiredMode) {- return prev- }- if (desiredMode === 'current') {- return { mode: 'current' }- }- if (desiredMode === 'select') {- return {- mode: 'select',- accountId: directory.selectedAccountId,- userId: directory.selectedUserId,- apiKey:- directory.resolveUserKey(- directory.selectedAccountId,- directory.selectedUserId,- ) ?? '',- }- }- return { mode: 'custom', apiKey: '' }- })- }, [connection.apiKey, directory, isConnectionRoleLoading])-- // Keep the select payload in sync with the directory while in select mode.- React.useEffect(() => {- setIdentityValue((prev) => {- if (prev.mode !== 'select') {- return prev- }- const accountId = directory.selectedAccountId- const userId = directory.selectedUserId- const apiKey = directory.resolveUserKey(accountId, userId) ?? ''- if (- prev.accountId === accountId &&- prev.userId === userId &&- prev.apiKey === apiKey- ) {- return prev- }- return { mode: 'select', accountId, userId, apiKey }- })- }, [directory])-- const [code, setCode] = React.useState('')- const [phase, setPhase] = React.useState<Phase>({ kind: 'idle' })-- async function submit(- event: React.FormEvent<HTMLFormElement>,- ): Promise<void> {- event.preventDefault()- const effectiveKey = resolveEffectiveApiKey(- identityValue,- connection.apiKey,- )- if (!effectiveKey) {- setPhase({ kind: 'error', message: t('verify.noApiKey') })- return- }- const normalized = code.trim().toUpperCase()- if (!normalized) {- return- }- setPhase({ kind: 'verifying' })- try {- const resp = await fetch('/api/v1/auth/oauth-verify', {- method: 'POST',- cache: 'no-store',- headers: {- 'Content-Type': 'application/json',- Authorization: `Bearer ${effectiveKey}`,- },- body: JSON.stringify({ code: normalized, decision: 'approve' }),- })- if (!resp.ok) {- const text = await resp.text().catch(() => '')- setPhase({- kind: 'error',- message: extractMessage(text) || String(resp.status),- })- return- }- const body = (await resp.json()) as {- client_name?: string | null- }- setPhase({ kind: 'success', clientName: body.client_name ?? null })- } catch (err: unknown) {- const message = err instanceof Error ? err.message : String(err)- setPhase({ kind: 'error', message })- }- }-- const hasAnyKey = Boolean(- resolveEffectiveApiKey(identityValue, connection.apiKey),- )+ const { t } = useTranslation('oauth')return (<div className="flex min-h-[60vh] w-full items-center justify-center px-4 py-8">@@ -178,98 +24,10 @@ function VerifyPage() {<CardTitle>{t('verify.title')}</CardTitle><CardDescription>{t('verify.description')}</CardDescription></CardHeader>-- <form onSubmit={(event) => void submit(event)}>- <CardContent className="grid gap-5">- {phase.kind === 'success' ? (- <p className="text-sm text-foreground">- {phase.clientName- ? t('verify.success', { clientName: phase.clientName })- : t('verify.successUnknownClient')}- </p>- ) : (- <>- {!connection.apiKey && !directory.available ? (- <div className="grid gap-2 rounded-md border border-dashed p-3 text-sm">- <p>{t('verify.signInRequired')}</p>- <Button- type="button"- variant="outline"- size="sm"- className="w-fit"- onClick={openConnectionSettings}- disabled={phase.kind === 'verifying'}- >- {t('consent.openConnectionSettings')}- </Button>- </div>- ) : null}-- <IdentityPicker- value={identityValue}- onChange={handleIdentityChange}- currentApiKey={connection.apiKey}- currentIdentityLabel={currentIdentity}- directory={directory}- disabled={phase.kind === 'verifying'}- />-- <Field>- <FieldLabel htmlFor="ov-oauth-verify-code">- {t('verify.codeLabel')}- </FieldLabel>- <FieldContent>- <Input- id="ov-oauth-verify-code"- autoFocus- autoComplete="off"- inputMode="text"- maxLength={12}- placeholder={t('verify.codePlaceholder')}- value={code}- onChange={(event) => setCode(event.target.value)}- disabled={phase.kind === 'verifying'}- className="font-mono uppercase tracking-widest"- />- </FieldContent>- </Field>-- {phase.kind === 'error' ? (- <p className="text-sm text-destructive">- {t('verify.verifyError', { message: phase.message })}- </p>- ) : null}- </>- )}- </CardContent>-- {phase.kind === 'success' ? null : (- <CardFooter className="justify-end">- <Button- type="submit"- disabled={- phase.kind === 'verifying' ||- code.trim().length === 0 ||- !hasAnyKey- }- >- {phase.kind === 'verifying'- ? t('consent.verifying')- : t('verify.submit')}- </Button>- </CardFooter>- )}- </form>+ <CardContent>+ <CrossDeviceVerifyForm />+ </CardContent></Card></div>)}--function extractMessage(raw: string): string {- try {- const parsed = JSON.parse(raw) as { error?: { message?: string } }- return parsed.error?.message || raw.slice(0, 200)- } catch {- return raw.slice(0, 200)- }-}