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
feat(oauth): move authorize UI into web-studio (#2160 follow-up) (#2170)
t0sakida592895919c
diff --git a/Caddyfile b/Caddyfileindex 50cbc24e2..42d559102 100644--- a/Caddyfile+++ b/Caddyfile@@ -1,11 +1,11 @@-# OpenViking aggregated reverse proxy+# OpenViking reverse proxy — legacy fallback#-# Port 1934 fronts the OV server (1933) under one stable origin. This block-# always serves plain HTTP — suitable for local dev, internal networks, and-# as an upstream behind your own TLS-terminating proxy.+# Port 1934 is retained only as a legacy entrypoint for existing deployments+# that already reference it. Its primary remaining purpose is as the upstream+# target for a TLS-terminating proxy (e.g. HTTPS via Caddy domain block).#-# Web Studio (the in-server SPA) is served by OV itself at `/studio`, so a-# single upstream is all that's needed here.+# For new deployments, connect directly to the OV server on port 1933.+# Web Studio is served by OV itself at /studio — no separate proxy needed.## To add public HTTPS, append a domain block below (Caddy auto-provisions# Let's Encrypt certs):diff --git a/docker-compose.yml b/docker-compose.ymlindex c9a32e3eb..54d64ad5c 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -32,8 +32,8 @@ services:start_period: 30srestart: unless-stopped- # Aggregated reverse proxy — fronts OV (1933) on port 1934 under one stable- # origin. Always enabled, plain HTTP by default.+ # Legacy reverse proxy — port 1934 is retained for existing deployments.+ # New setups can connect directly to openviking:1933.## For public HTTPS: edit the Caddyfile to add a domain block, set# OPENVIKING_PUBLIC_BASE_URL in .env, uncomment the 80/443 port linesdiff --git a/docs/design/mcp-oauth2-1.md b/docs/design/mcp-oauth2-1.mdindex b44d3a061..a4b8c2009 100644--- a/docs/design/mcp-oauth2-1.md+++ b/docs/design/mcp-oauth2-1.md@@ -1,5 +1,34 @@# OpenViking 原生 OAuth 2.1(MCP 客户端授权)实施方案+> **更新(Studio 迁移)**:本文档保留 Phase 1 的设计与术语作为历史记录。当前+> 默认授权 UI 已经从独立的 `/console` (端口 8020) 迁移到主服务上的 OpenViking+> Studio(同源、挂载在 `/studio`)。要点:+>+> - `provider.authorize()` 默认 redirect 到 `/studio/oauth/consent?pending=<id>`+> 而不是 `/oauth/authorize/page`。consent SPA 跑在 Studio 自己的 tab 里,+> 直接复用 `sessionStorage` 里已有的 API Key 调+> `POST /api/v1/auth/oauth-verify`(请求体改用 `pending_id` 取代+> `display_code`,并通过新增的公开端点+> `GET /api/v1/auth/oauth/pending/{pending_id}` 拿 client_name /+> redirect_host / scopes 渲染 consent 卡片)。+> - 服务端 HTML 页面 `/oauth/authorize/page` 退化为**跨设备 fallback**:+> 显示 6 字符 `display_code` + 引导文案,让用户在另一台已登录 Studio 的设备+> 打开 `/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` 后端端点未变。+> - 旧的 `/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 作为同+> 设备主路径。+## Context**问题**:Claude.ai / Claude Desktop / ChatGPT 等只接受 OAuth 2.1 的 MCP 客户端,必须经由社区项目 [MCP-Key2OAuth](https://github.com/t0saki/MCP-Key2OAuth) 的 Cloudflare Workers 代理才能连接 OpenViking 的 `/mcp`。痛点:diff --git a/docs/en/guides/11-oauth.md b/docs/en/guides/11-oauth.mdindex 9ca48c09f..cc19db0d9 100644--- a/docs/en/guides/11-oauth.md+++ b/docs/en/guides/11-oauth.md@@ -28,11 +28,11 @@ work just as well.3. **Restart** (`docker compose restart openviking`).4. **Connect a client.** In Claude.ai → Connectors → Add, enter- `https://ov.your-domain.com/mcp`. The browser will open an authorize page- that displays a 6-character code; open- `https://ov.your-domain.com/console`, sign in with your API key, paste- the code in Settings → "Authorize an MCP client", click Authorize. The- browser flips back to Claude.ai and the connector is live.+ `https://ov.your-domain.com/mcp`. The browser flips to+ `https://ov.your-domain.com/studio/oauth/consent`: if you aren't already+ signed in to Studio, paste your API key into the "Connection & Identity"+ dialog; then click **Authorize** on the consent card. Claude.ai gets the+ token and the connector is live.That's the whole production path. The rest of this guide explains why eachpiece exists, how to test locally without HTTPS, and how to verify with curl@@ -57,9 +57,9 @@ API-Key auth still works as before — OAuth layers on top.## How it works-OpenViking implements a **device-flow style** OTP exchange (closer to RFC 8628-than the original push flow). When an MCP client opens the browser to-authorize:+OpenViking's authorize UI runs inside **OpenViking Studio** by default+(same-origin with the main server and sharing Studio's session). When an MCP+client opens the browser to authorize:```1. MCP client POST /mcp → 401 + WWW-Authenticate header@@ -67,29 +67,40 @@ authorize:3. MCP client GET /.well-known/oauth-authorization-server (RFC 8414)4. MCP client POST /register (Dynamic Client Registration, RFC 7591)5. MCP client GET /authorize?... (browser redirect)-6. Server → /oauth/authorize/page?pending=...- (page displays a 6-character code, e.g. "AB3X7K")-7. User opens the OpenViking web console (already signed in)- → Settings → "Authorize an MCP client" → enters AB3X7K → Authorize-8. Server marks the pending authorization as verified, binding the- console user's identity (account / user / role)-9. Page polls /oauth/authorize/page/status, sees "approved",+6. Server → /studio/oauth/consent?pending=...+ (consent SPA loads and fetches+ /api/v1/auth/oauth/pending/<id> to render+ client_name / redirect_host / scopes)+7. User confirms on the consent card in their already signed-in+ Studio tab (or picks "Use a different API key" in the+ IdentityPicker to do a one-off authorize)+8. Studio POST /api/v1/auth/oauth-verify+ (Authorization: Bearer <api-key>,+ body: {pending_id, decision})+ Server marks pending as verified and binds the caller's+ identity (account / user / role).+9. Studio polls /oauth/authorize/page/status, sees "approved",redirects browser to the MCP client's redirect_uri with code10. MCP client POST /token (PKCE S256) → access_token (ovat_...) +refresh_token (ovrt_...)11. MCP client POST /mcp (Authorization: Bearer ovat_...) → tool list```-The 6-character code is shown on the authorize page and **typed into the-console**, not the other way around. This means the user always confirms from-an environment where they're already authenticated. If the console is on the-same origin as the OAuth page (recommended deployment), the page can also-detect the user's signed-in console session and offer a one-click "Quick-authorize" button — but the click is still required, never automatic.+Consent happens inside Studio, so there's **no cross-tab code copying** on+the happy path. Studio already holds your API key in `sessionStorage` (the+one you entered when signing in); the consent SPA uses it as+`Authorization: Bearer` against `/api/v1/auth/oauth-verify`.-A legacy "push" flow is also retained for CLI-driven scenarios: the console-has a "Generate OTP" button, and `POST /api/v1/auth/otp` issues a one-time-passcode bound to the caller's API key.+If you can't open Studio on the current device (CLI MCP clients, cross-device+authorize), the consent page's "Use another device →" link falls back to the+server-rendered HTML page at `/oauth/authorize/page`: it displays a 6-char+`display_code`, which you type at `/studio/oauth/verify` on another device+that'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 at the bottom+of the Studio "Connection & Identity" dialog gives you a one-click way to+mint a short-lived OTP to hand to an MCP client.---@@ -121,19 +132,16 @@ endpoints, so this mode is only useful for local testing with tools like```bashopenviking-server- # in another terminal- python -m openviking.console.bootstrap --write-enabled```-3. **Sign in to the console** at <http://127.0.0.1:1934/console> (or- `:8020/console` if running without the aggregated proxy), paste your API- key into Settings, click Save. The "Authorize an MCP client" form is now- available.+3. **Open Studio and sign in** at <http://127.0.0.1:1933/studio>. From the+ top-right open "Connection & Identity", paste your API key, click Save.4. **Connect a local MCP client** (e.g. MCP Inspector) to- `http://127.0.0.1:1934/mcp` (or `:1933/mcp`). The client will hit the- OAuth flow above; copy the 6-character code from the authorize page into- the console form, click Authorize, and the client will receive a token.+ `http://127.0.0.1:1933/mcp`. The client will hit the OAuth flow above and+ the 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 Connection & Identity dialog.For Claude.ai / Claude Desktop on the public internet, see the[Public Access Guide](12-public-access.md).@@ -163,10 +171,18 @@ Once HTTPS + OAuth are both up, connect clients as described below.1. Settings → Connectors → **Add connector**.2. Enter `https://my.ov/mcp` as the server URL.-3. Claude opens an authorize page in a popup; copy the 6-character code.-4. Open <https://my.ov/console> in another tab (the popup also has a link).-5. Sign in if needed → Settings → "Authorize an MCP client" → paste the code → **Authorize**.-6. The popup automatically redirects back to Claude with a fresh access token.+3. Claude opens an authorize page that redirects to+ `https://my.ov/studio/oauth/consent?pending=...`.+4. If you're not yet signed in to Studio, paste your API key in the+ "Connection & Identity" dialog (or pick "Use a different API key" in the+ IdentityPicker for a one-off authorize).+5. Confirm client_name / redirect_host on the consent card → **Authorize**.+6. The popup redirects back to Claude with a fresh access token.++> If you triggered authorization from a CLI device with no local browser,+> either copy the authorize URL to a desktop browser, or click "Use another+> device →" on the consent page to switch to the 6-character display_code+> path (enter it on another device's `/studio/oauth/verify`).### Claude Desktop / Claude Code@@ -213,9 +229,11 @@ CHALLENGE=$(printf "%s" "$VERIFIER" | openssl dgst -sha256 -binary | basenc --ba# 3. Open the authorize URL in a browser. The page shows a 6-char code.echo "https://my.ov/authorize?response_type=code&client_id=$CID&redirect_uri=http://127.0.0.1:9999/cb&code_challenge=$CHALLENGE&code_challenge_method=S256&state=xyz"-# 4. Approve the displayed code from the console (or via API).-curl -X POST -H "X-Api-Key: $API_KEY" -H "Content-Type: application/json" \- -d '{"code":"AB3X7K","decision":"approve"}' \+# 4. Approve from the Studio consent page (or via API).+# - Studio path uses pending_id (?pending=... from the authorize URL).+# - Cross-device path uses the 6-char display_code.+curl -X POST -H "Authorization: Bearer $API_KEY" -H "Content-Type: application/json" \+ -d '{"pending_id":"<pending-id-from-authorize-url>","decision":"approve"}' \https://my.ov/api/v1/auth/oauth-verify# 5. The browser auto-redirects to /cb?code=ovac_...&state=xyz. Copy the code.@@ -328,12 +346,12 @@ Either:- Set `oauth.issuer` to an `https://` URL in `ov.conf`, or- For local testing only, ensure your client connects via `http://127.0.0.1:1933` directly-### The authorize page shows a code, but the console says "Invalid code"+### The cross-device fallback shows a code, but `/studio/oauth/verify` says "Invalid code"Codes are 6 characters, **uppercase**, and case-sensitive on the wire. The-console form normalizes input to uppercase. If you're typing manually, check-for letters that look like digits (the alphabet excludes `O`, `0`, `I`, `1`-to reduce confusion).+`/studio/oauth/verify` input normalizes to uppercase. If you're typing+manually, check for letters that look like digits (the alphabet excludes+`O`, `0`, `I`, `1` to reduce confusion).### Token rotates but the next refresh is rejecteddiff --git a/docs/en/guides/12-public-access.md b/docs/en/guides/12-public-access.mdindex d770092a5..21ee2953e 100644--- a/docs/en/guides/12-public-access.md+++ b/docs/en/guides/12-public-access.md@@ -1,55 +1,23 @@# Public Access & Reverse Proxy-OpenViking runs two internal services:+OpenViking serves REST API, MCP, OAuth, `.well-known/*`, and Web Studio+(`/studio`) on port 1933 by default. This guide shows how to put it behind a+public HTTPS domain.-| Port | Service | Handles |-|------|---------|---------|-| 1933 | API server | REST API, MCP, OAuth, `.well-known/*` |-| 8020 | Console | Web UI at `/console/...` |+> **Why HTTPS**: OAuth 2.1 / the MCP SDK **require HTTPS** for any+> non-localhost issuer — Claude.ai, Claude Desktop, ChatGPT, Cursor and other+> OAuth MCP clients refuse to connect over plain HTTP and report "Issuer URL+> must be HTTPS". API-key-only clients (including Claude Code with+> `--header`) work over HTTP, but TLS is still strongly recommended for+> production.-The bundled **Caddy reverse proxy** merges them into a single port — **1934** — so-clients only need one URL. This works out of the box with `docker compose up`.+Prerequisites: a public domain, ports 80 + 443 reachable, DNS pointing at+your host.-## Port overview+## Option A: bundled Caddy with auto Let's Encrypt (recommended)-```- ┌────────────────────────┐-Internet / LAN ──► │ Caddy :1934 (HTTP) │- │ │- │ /console/* → :8020 │- │ /* → :1933 │- └────────────────────────┘-```--Port 1934 is plain HTTP — fine for local development, internal networks, and-as an upstream target behind your own TLS-terminating proxy or CDN.--For **public HTTPS** (required for OAuth with MCP clients like Claude.ai,-ChatGPT, Cursor), Caddy can also serve port 443 with automatic Let's Encrypt-certificates. See [Adding HTTPS](#adding-https-for-public-access) below.--## Quick start (local / internal)--```bash-docker compose up -d-```--Both services are now reachable on one port:--```bash-curl http://localhost:1934/health # API server health-curl http://localhost:1934/api/v1/system/status \- -H "X-Api-Key: YOUR_KEY" # REST API-open http://localhost:1934/console # Web console-```--You can still access 1933 and 8020 directly — those port mappings are left in-`docker-compose.yml` for debugging. Once you're confident everything works-through 1934, feel free to comment them out.--## Adding HTTPS for public access--You need: a public domain, ports 80 + 443 reachable, DNS pointing here.+`docker compose up` already brings up a Caddy reverse-proxy container. Add a+domain block to it and you get HTTPS on 443 with auto-renewal.### 1. Create `.env`@@ -58,31 +26,20 @@ OPENVIKING_PUBLIC_BASE_URL=https://ov.your-domain.com[email protected] # optional; recommended for Let's Encrypt```-`OPENVIKING_PUBLIC_BASE_URL` is read by both the OpenViking container (it-publishes this URL in OAuth metadata and `WWW-Authenticate` headers) and by-Caddy (as the site address for the HTTPS block).+`OPENVIKING_PUBLIC_BASE_URL` is read by both the OpenViking container (used+as the issuer in OAuth metadata and `WWW-Authenticate` headers) and Caddy+(as the HTTPS site address).### 2. Add a domain block to `Caddyfile`-Append this below the existing `:1934` block:-```caddyfile{$OPENVIKING_PUBLIC_BASE_URL} {- @console path /console /console/*- handle @console {- reverse_proxy openviking:8020- }- handle {- reverse_proxy openviking:1933- }+ reverse_proxy openviking:1933# Pin ACME registration email (optional):# tls {$OV_ACME_EMAIL}}```-The `:1934` block stays — it continues to serve HTTP for local/internal-access. The new block serves HTTPS on 443 for the public domain.-### 3. Uncomment HTTPS lines in `docker-compose.yml`Three places:@@ -119,15 +76,17 @@ curl https://ov.your-domain.com/health# OAuth metadata (if oauth.enabled = true):curl https://ov.your-domain.com/.well-known/oauth-authorization-server++# Open Studio in the browser:+open https://ov.your-domain.com/studio```-## Using your own reverse proxy+## Option B: bring your own reverse proxy-If you already have nginx, Traefik, or another proxy handling TLS, point it-at port 1934 instead of juggling 1933 + 8020 separately. Port 1934 already-does the path-based routing internally.+If you already run nginx / Traefik / Envoy / Cloudflare for TLS termination,+point the upstream straight at OV's 1933.-### nginx (TLS termination at nginx, plain HTTP to 1934)+### nginx```nginxserver {@@ -138,7 +97,7 @@ server {ssl_certificate_key /etc/letsencrypt/live/ov.your-domain.com/privkey.pem;location / {- proxy_pass http://127.0.0.1:1934;+ proxy_pass http://127.0.0.1:1933;proxy_set_header Host $host;proxy_set_header X-Forwarded-Proto $scheme;proxy_set_header X-Forwarded-Host $host;@@ -152,35 +111,30 @@ server {}```-With this setup, remove the Caddy HTTPS block from the Caddyfile — keep only-the `:1934` block.--### Caddy (external, without docker-compose Caddy)--If you run Caddy on the host rather than inside compose:+### Caddy (host install, no compose)```caddyfileov.your-domain.com {- reverse_proxy 127.0.0.1:1934+ reverse_proxy 127.0.0.1:1933}```### Cloudflare / CDN-Point the CDN origin at `http://your-server-ip:1934`. Set+Point the CDN origin at `http://your-server-ip:1933`. Set`OPENVIKING_PUBLIC_BASE_URL=https://ov.your-domain.com` so the server knows-its public-facing origin. Ensure the CDN forwards `Host`,-`X-Forwarded-Proto`, and `X-Forwarded-Host` headers.+its public address. Make sure the CDN forwards `Host`, `X-Forwarded-Proto`,+and `X-Forwarded-Host`.-## Tell the server its public URL+## Telling the server its public URL-OAuth metadata, `WWW-Authenticate` headers, and resource URLs all need to-contain the public-facing origin. Resolution order (highest priority first):+OAuth metadata, `WWW-Authenticate` headers, and resource URLs need to embed+the public origin. Resolution order (**highest to lowest**):1. `OPENVIKING_PUBLIC_BASE_URL` environment variable2. `oauth.issuer` in `ov.conf`3. `X-Forwarded-Proto` + `X-Forwarded-Host` request headers-4. The request `Host` header+4. The request's `Host` headerBehind any reverse proxy, set option 1 explicitly:@@ -188,7 +142,7 @@ Behind any reverse proxy, set option 1 explicitly:export OPENVIKING_PUBLIC_BASE_URL="https://ov.your-domain.com"```-Or in `ov.conf`:+or in `ov.conf`:```jsonc{@@ -199,64 +153,16 @@ Or in `ov.conf`:}```-## HTTPS and OAuth--OAuth 2.1 (and the MCP SDK) **requires HTTPS** for any non-localhost issuer.-If the server's published origin is `http://` on a non-loopback address, MCP-clients will refuse to connect with an "Issuer URL must be HTTPS" error.--This is a protocol-level requirement, not an OpenViking limitation. For local-testing, `http://127.0.0.1:1934` works without HTTPS. For anything else, set-up TLS as described above.--Non-OAuth API access (API key auth) works fine over HTTP if you accept the-risk — the protocol doesn't enforce TLS for bearer tokens.+## Compatibility note: the `:1934` single-upstream proxy-## Without Docker--If you run `openviking-server` and the console directly (systemd, bare-metal, etc.), install Caddy on the host and use the same Caddyfile pattern-with `127.0.0.1` upstreams:--```caddyfile-:1934 {- @console path /console /console/*- handle @console {- reverse_proxy 127.0.0.1:8020- }- handle {- reverse_proxy 127.0.0.1:1933- }-}--# Add domain block for HTTPS if needed:-# ov.your-domain.com { ... }-```--Or with nginx:--```nginx-server {- listen 1934;-- location /console {- proxy_pass http://127.0.0.1:8020;- proxy_set_header Host $host;- proxy_set_header X-Forwarded-Proto $scheme;- proxy_set_header X-Forwarded-Host $host;- }-- location / {- proxy_pass http://127.0.0.1:1933;- proxy_set_header Host $host;- proxy_set_header X-Forwarded-Proto $scheme;- proxy_set_header X-Forwarded-Host $host;- }-}-```+`docker compose up` also ships a Caddy reverse proxy on port 1934, simply+`reverse_proxy openviking:1933` — **kept only for compatibility with+deployments that already bookmarked 1934**. New deployments can connect to+1933 directly; there is no routing value here. Remove the caddy service and+the 1934 port mapping in `docker-compose.yml` if you don't need it.## Related- [Deployment Guide](03-deployment.md) — Docker, systemd, Kubernetes-- [OAuth Guide](11-oauth.md) — OAuth 2.1 configuration and client setup+- [OAuth Guide](11-oauth.md) — OAuth 2.1 setup and client onboarding- [Authentication](04-authentication.md) — API key managementdiff --git a/docs/zh/guides/11-oauth.md b/docs/zh/guides/11-oauth.mdindex 02afc28cc..cf306a0a8 100644--- a/docs/zh/guides/11-oauth.md+++ b/docs/zh/guides/11-oauth.md@@ -24,10 +24,10 @@ token、metadata)由官方 `mcp.server.auth` SDK 提供,整体遵循 OAuth 23. **重启**(`docker compose restart openviking`)。4. **接入客户端。** Claude.ai → Connectors → Add → 输入- `https://ov.your-domain.com/mcp`。浏览器打开授权页,显示一个 6 字符码;- 再打开 `https://ov.your-domain.com/console`,用 API Key 登录,把码粘到- Settings → "Authorize an MCP client" → 点 Authorize。浏览器自动跳回- Claude.ai,连接器就位。+ `https://ov.your-domain.com/mcp`。浏览器跳到+ `https://ov.your-domain.com/studio/oauth/consent`:如果尚未登录 Studio,+ 先在弹出的"连接与身份"对话框里粘入 API Key;然后在 consent 卡片上点+ **Authorize**。浏览器自动跳回 Claude.ai,连接器就位。线上路径就这四步。后续章节解释每一块为什么这样设计、本地怎么不走 HTTPS 做联调、出问题时怎么用 curl 排查。@@ -50,9 +50,8 @@ API Key 认证仍按原方式工作,OAuth 只是叠加层。## 工作原理-OpenViking 实现的是 **device-flow 风格**的 OTP 流程(更接近 RFC 8628),-而不是早期"console 取码 → page 输入"的 push 流程。MCP 客户端打开浏览器-授权时:+OpenViking 授权 UI 默认走 **OpenViking Studio** 内的 consent 页面(与主服务+同源、与 Studio 共用 session)。MCP 客户端打开浏览器授权时:```1. MCP 客户端 POST /mcp → 401 + WWW-Authenticate@@ -60,27 +59,33 @@ OpenViking 实现的是 **device-flow 风格**的 OTP 流程(更接近 RFC 8623. MCP 客户端 GET /.well-known/oauth-authorization-server (RFC 8414)4. MCP 客户端 POST /register 动态客户端注册 (RFC 7591)5. MCP 客户端 GET /authorize?... (浏览器重定向)-6. 服务端 → /oauth/authorize/page?pending=...- 页面显示一个 6 字符码,例如 "AB3X7K"-7. 用户 打开 OpenViking Web Console(已登录状态)- → Settings → "Authorize an MCP client" → 输入 AB3X7K → 点 Authorize-8. 服务端 把 pending 标记为 verified,绑定 console 用户的身份- (account / user / role)-9. 页面 轮询 /oauth/authorize/page/status,命中 "approved",+6. 服务端 → /studio/oauth/consent?pending=...+ consent 页加载,并 fetch /api/v1/auth/oauth/pending/<id>+ 渲染 client_name / redirect_host / scopes+7. 用户 在 Studio 已登录的 tab 上点 Authorize(也可在 IdentityPicker+ 里临时粘贴另一个 API Key 完成一次性授权)+8. Studio POST /api/v1/auth/oauth-verify (Authorization: Bearer <api-key>,+ body: {pending_id, decision}),服务端把 pending 标记为 verified+ 并绑定调用方的身份(account / user / role)+9. Studio 轮询 /oauth/authorize/page/status,命中 "approved",自动跳转回 MCP 客户端的 redirect_uri 并附 auth code10. MCP 客户端 POST /token (PKCE S256) → access_token (ovat_...)+ refresh_token (ovrt_...)11. MCP 客户端 POST /mcp (Authorization: Bearer ovat_...) → 调工具```-6 字符码显示在 authorize 页,**用户把它输入到 console 表单**(而不是反过来)。-这样确认动作发生在用户已登录的环境,符合"我在已登录的地方批准那边的请求"的直觉。+授权 consent 直接发生在 Studio 内,**不需要跨标签复制验证码**。Studio 的+sessionStorage 里已经持有 API Key(你登录 Studio 时填的那个),consent 页用+它做 `Authorization: Bearer` 调 verify。-如果 console 与 OAuth 页面同源(推荐部署形态),page 还会检测用户已有的 console-session,提供一键 "Quick authorize" 按钮 — **依然需要点一下**,不会自动跳。+如果当前设备打不开 Studio(例如 CLI MCP 客户端、跨设备授权场景),consent+页底部的 "Use another device →" 链接会回退到服务端 HTML 授权页+`/oauth/authorize/page`:页面显示 6 字符 `display_code`,让你在另一台已经+登录 Studio 的设备上打开 `/studio/oauth/verify` 输入。-服务端还保留了"push 模式"的 OTP 端点 `POST /api/v1/auth/otp` 供 CLI 场景使用:-console 也提供一个折叠的 "Generate OTP" 入口供脚本类客户端使用。+服务端还保留 "push 模式" 的 OTP 端点 `POST /api/v1/auth/otp` 供 CLI/脚本场+景使用。在 Studio 的"连接与身份"对话框底部就有 **OAuth client OTP** 区块,+可以一键生成短期 OTP 交给 MCP 客户端。---@@ -112,18 +117,15 @@ Claude.ai / Claude Desktop 等线上客户端**只接受公网 HTTPS**,所以```bashopenviking-server- # 另开一个终端- python -m openviking.console.bootstrap --write-enabled```-3. **登录 console**:访问 <http://127.0.0.1:1934/console>(不走聚合代理时用- `:8020/console`),把 API Key 粘到 Settings → 点 Save。"Authorize an MCP- client" 表单现在可用。+3. **打开 Studio 并登录**:访问 <http://127.0.0.1:1933/studio>,在右上角+ 打开"连接与身份"对话框,把 API Key 粘进去 → Save。4. **接一个本地 MCP 客户端**(例如 MCP Inspector)到- `http://127.0.0.1:1934/mcp`(或 `:1933/mcp`)。客户端会走上面那套流程;把- authorize 页显示的 6 字符码复制到 console 表单 → 点 Authorize → 客户端拿到- token。+ `http://127.0.0.1:1933/mcp`。客户端会走上面那套流程,浏览器自动跳到+ `/studio/oauth/consent?pending=...`,确认即可拿到 token。如果想用 push+ 模式,"连接与身份"对话框底部有 **OAuth client OTP** 区块直接生成。线上接 Claude.ai / Claude Desktop 走[公网访问指南](12-public-access.md)。@@ -152,10 +154,17 @@ HTTPS + OAuth 就绪后,按下面的方式接入客户端。1. Settings → Connectors → **Add connector**。2. 输入 `https://my.ov/mcp` 作为服务器 URL。-3. Claude 弹出授权页面,记下 6 字符码。-4. 另开标签访问 <https://my.ov/console>(弹出页里也有这个链接)。-5. 登录(如未登录)→ Settings → "Authorize an MCP client" → 粘码 → **Authorize**。-6. 弹出页自动跳回 Claude,token 已颁发。+3. Claude 弹出授权页面,自动跳到+ `https://my.ov/studio/oauth/consent?pending=...`。+4. 如未登录 Studio,先在弹出的"连接与身份"对话框里填 API Key(也可在+ IdentityPicker 里临时粘一个 key 一次性授权)。+5. 在 consent 卡片确认 client_name / redirect_host 后点 **Authorize**。+6. 浏览器自动跳回 Claude,token 已颁发。++> 如果你在 CLI 设备上触发授权(本地浏览器打不开 consent),把+> authorize URL 复制到桌面浏览器,或在 consent 页底部点 "Use another+> device →" 走 6 字符码的跨设备路径(在另一台已登录 Studio 的设备打开+> `/studio/oauth/verify` 输入码)。### Claude Desktop / Claude Code@@ -198,9 +207,11 @@ CHALLENGE=$(printf "%s" "$VERIFIER" | openssl dgst -sha256 -binary | basenc --ba# 3. 浏览器访问 authorize URL,页面会显示 6 字符码echo "https://my.ov/authorize?response_type=code&client_id=$CID&redirect_uri=http://127.0.0.1:9999/cb&code_challenge=$CHALLENGE&code_challenge_method=S256&state=xyz"-# 4. 在 console 输入码(或直接 curl)-curl -X POST -H "X-Api-Key: $API_KEY" -H "Content-Type: application/json" \- -d '{"code":"AB3X7K","decision":"approve"}' \+# 4. 在 Studio consent 页确认(或直接 curl)+# - Studio 路径用 pending_id(authorize 页的 ?pending=... 参数)+# - 跨设备路径用 6 字符 display_code+curl -X POST -H "Authorization: Bearer $API_KEY" -H "Content-Type: application/json" \+ -d '{"pending_id":"<pending-id-from-authorize-url>","decision":"approve"}' \https://my.ov/api/v1/auth/oauth-verify# 5. 浏览器自动 302 到 /cb?code=ovac_...&state=xyz,记下 code@@ -305,9 +316,10 @@ MCP SDK 拒绝非 `127.0.0.1` / `localhost` 的 `http://` issuer。三选一:- 在 `ov.conf` 里把 `oauth.issuer` 写成 `https://...`- 仅本地测试时让客户端直连 `http://127.0.0.1:1933`-### Authorize 页有码,但 console 报 "Invalid code"+### 跨设备 fallback 页有码,但 `/studio/oauth/verify` 报 "Invalid code"-码是 6 字符**全大写**,传输时区分大小写。console 的输入框会自动转大写。如果手+码是 6 字符**全大写**,传输时区分大小写。`/studio/oauth/verify` 的输入框会+自动转大写。如果手动输入,注意字母与数字的混淆字符(字母表已经排除了 `O`、`0`、`I`、`1`)。### Refresh 一次后再用旧 token 被拒diff --git a/docs/zh/guides/12-public-access.md b/docs/zh/guides/12-public-access.mdindex 93f7409f8..e43712efb 100644--- a/docs/zh/guides/12-public-access.md+++ b/docs/zh/guides/12-public-access.md@@ -1,54 +1,20 @@# 公网访问与反向代理-OpenViking 运行两个内部服务:+OpenViking 默认在 1933 端口对外提供 REST API、MCP、OAuth、`.well-known/*`+以及 Web Studio (`/studio`)。本指南讲怎么把它放到公网 HTTPS 域名后面。-| 端口 | 服务 | 处理内容 |-|------|------|---------|-| 1933 | API 服务 | REST API、MCP、OAuth、`.well-known/*` |-| 8020 | Console | Web 管理界面,路径前缀 `/console/...` |+> **为什么需要 HTTPS**:OAuth 2.1 / MCP SDK 对非 localhost 的 issuer+> **强制要求 HTTPS** —— Claude.ai、Claude Desktop、ChatGPT、Cursor 等 OAuth+> MCP 客户端没有 TLS 拒绝连接,会报 "Issuer URL must be HTTPS"。+> 仅 API Key 鉴权的客户端(含 Claude Code `--header` 直连)在 HTTP 下也能+> 工作,但生产环境仍建议上 TLS。-自带的 **Caddy 反向代理**将两者合并到一个端口 — **1934** — 客户端只需一个-URL。`docker compose up` 即可开箱使用。--## 端口总览--```- ┌────────────────────────┐-Internet / LAN ──► │ Caddy :1934 (HTTP) │- │ │- │ /console/* → :8020 │- │ /* → :1933 │- └────────────────────────┘-```--1934 端口是纯 HTTP — 适用于本地开发、内网环境,也可以作为外部 TLS 终止代理-或 CDN 的上游。--如果需要**公网 HTTPS**(Claude.ai、ChatGPT、Cursor 等 MCP 客户端走 OAuth 时-必须),Caddy 还能在 443 端口自动签发 Let's Encrypt 证书。见下方-[添加 HTTPS](#添加-https-公网访问)。--## 快速开始(本地 / 内网)--```bash-docker compose up -d-```--两个服务在一个端口上可达:--```bash-curl http://localhost:1934/health # API 健康检查-curl http://localhost:1934/api/v1/system/status \- -H "X-Api-Key: YOUR_KEY" # REST API-open http://localhost:1934/console # Web Console-```--1933 和 8020 仍可直接访问 — `docker-compose.yml` 里保留了端口映射方便调试。-确认 1934 一切正常后,可以把那两行注释掉。+前提:有公网域名、80 + 443 端口可达、DNS 已指向。-## 添加 HTTPS(公网访问)+## 方式 A:用自带 Caddy 自动签发 Let's Encrypt 证书(推荐)-前提:有公网域名、80 + 443 端口可达、DNS 已指向。+`docker compose up` 默认带一个 Caddy 反代容器。给它追加一个域名块即可让+443 端口跑起来。### 1. 创建 `.env`@@ -62,25 +28,14 @@ [email protected] # 可选;推荐用于 Let's Encrypt### 2. 在 `Caddyfile` 追加域名块-在已有的 `:1934` 块下面添加:-```caddyfile{$OPENVIKING_PUBLIC_BASE_URL} {- @console path /console /console/*- handle @console {- reverse_proxy openviking:8020- }- handle {- reverse_proxy openviking:1933- }+ reverse_proxy openviking:1933# 绑定 ACME 注册邮箱(可选):# tls {$OV_ACME_EMAIL}}```-`:1934` 块保留 — 继续为本地/内网提供 HTTP 访问。新块在 443 端口为公网域名-提供 HTTPS。-### 3. 取消 `docker-compose.yml` 中的 HTTPS 注释三处:@@ -116,14 +71,17 @@ curl https://ov.your-domain.com/health# OAuth 元数据(如果 oauth.enabled = true):curl https://ov.your-domain.com/.well-known/oauth-authorization-server++# 浏览器访问 Studio:+open https://ov.your-domain.com/studio```-## 使用自己的反向代理+## 方式 B:用你自己的反向代理-如果你已有 nginx、Traefik 或其他 TLS 终止代理,直接指向 1934 端口,不用分别-处理 1933 + 8020。1934 内部已经做好了路径路由。+已经有 nginx / Traefik / Envoy / Cloudflare 在做 TLS 终止时,直接把上游指向+OV 服务的 1933 端口。-### nginx(TLS 在 nginx 终止,HTTP 到 1934)+### nginx```nginxserver {@@ -134,7 +92,7 @@ server {ssl_certificate_key /etc/letsencrypt/live/ov.your-domain.com/privkey.pem;location / {- proxy_pass http://127.0.0.1:1934;+ proxy_pass http://127.0.0.1:1933;proxy_set_header Host $host;proxy_set_header X-Forwarded-Proto $scheme;proxy_set_header X-Forwarded-Host $host;@@ -148,21 +106,19 @@ server {}```-这种方案下,Caddyfile 只保留 `:1934` 块,不加域名块。-### Caddy(宿主机运行,不走 compose)```caddyfileov.your-domain.com {- reverse_proxy 127.0.0.1:1934+ reverse_proxy 127.0.0.1:1933}```### Cloudflare / CDN-CDN 源站指向 `http://your-server-ip:1934`。设置-`OPENVIKING_PUBLIC_BASE_URL=https://ov.your-domain.com` 让服务端知道自己的公网-地址。确保 CDN 转发 `Host`、`X-Forwarded-Proto`、`X-Forwarded-Host` 头。+CDN 源站指向 `http://your-server-ip:1933`。设置+`OPENVIKING_PUBLIC_BASE_URL=https://ov.your-domain.com` 让服务端知道自己的+公网地址。确保 CDN 转发 `Host`、`X-Forwarded-Proto`、`X-Forwarded-Host` 头。## 告诉服务端公网 URL@@ -191,59 +147,12 @@ export OPENVIKING_PUBLIC_BASE_URL="https://ov.your-domain.com"}```-## HTTPS 与 OAuth--OAuth 2.1(以及 MCP SDK)对非 localhost 的 issuer **强制要求 HTTPS**。-如果服务端发布的 origin 是非回环地址的 `http://`,MCP 客户端会拒绝连接并报-"Issuer URL must be HTTPS"。--这是协议层面的要求,不是 OpenViking 的限制。本地测试时-`http://127.0.0.1:1934` 无需 HTTPS。其他场景请按上面的方式配置 TLS。--非 OAuth 的 API 访问(API Key 认证)在 HTTP 下也能正常工作 — 协议本身不强制-bearer token 走 TLS,用户自行评估风险。--## 不用 Docker--如果直接运行 `openviking-server` 和 console(systemd、裸机等),在宿主机装-Caddy 并使用相同的 Caddyfile 模式,上游改为 `127.0.0.1`:--```caddyfile-:1934 {- @console path /console /console/*- handle @console {- reverse_proxy 127.0.0.1:8020- }- handle {- reverse_proxy 127.0.0.1:1933- }-}--# 需要 HTTPS 时追加域名块:-# ov.your-domain.com { ... }-```--或者 nginx:--```nginx-server {- listen 1934;+## 兼容备注:`:1934` 单上游反代- location /console {- proxy_pass http://127.0.0.1:8020;- proxy_set_header Host $host;- proxy_set_header X-Forwarded-Proto $scheme;- proxy_set_header X-Forwarded-Host $host;- }-- location / {- proxy_pass http://127.0.0.1:1933;- proxy_set_header Host $host;- proxy_set_header X-Forwarded-Proto $scheme;- proxy_set_header X-Forwarded-Host $host;- }-}-```+`docker compose up` 默认在 1934 端口启一个 Caddy 反代,单纯 `reverse_proxy+openviking:1933`,**仅为兼容已经书签到 1934 的旧部署保留**。新部署直接连+1933 即可,没有任何路由价值;不需要这个入口可以从 `docker-compose.yml` 注释+掉 caddy 服务和 1934 端口映射。## 相关文档diff --git a/openviking/server/oauth/provider.py b/openviking/server/oauth/provider.pyindex 00eeea9e5..7edbff06b 100644--- a/openviking/server/oauth/provider.py+++ b/openviking/server/oauth/provider.py@@ -46,6 +46,15 @@ ACCESS_TOKEN_PREFIX = "ovat_"REFRESH_TOKEN_PREFIX = "ovrt_"AUTH_CODE_PREFIX = "ovac_"+# Primary authorize page: a /studio SPA route that runs in the same tab as+# the user's Studio session, so it can read the session-stored API key.+DEFAULT_AUTHORIZE_PAGE = "/studio/oauth/consent"+# Server-rendered fallback used when the user can't open /studio on the+# current device (e.g. CLI MCP clients). The HTML page shows the+# 6-character display_code and points the user at /studio/oauth/verify on+# another already-signed-in device.+FALLBACK_AUTHORIZE_PAGE = "/oauth/authorize/page"+class OVAuthorizationCode(AuthorizationCode):"""AuthorizationCode subtype that pins the issuing identity."""@@ -86,7 +95,7 @@ class OpenVikingOAuthProvider(access_token_ttl_seconds: int = 3600,refresh_token_ttl_seconds: int = 30 * 24 * 3600,auth_code_ttl_seconds: int = 300,- authorize_page_path: str = "/oauth/authorize/page",+ authorize_page_path: str = DEFAULT_AUTHORIZE_PAGE,role_resolver: Optional[Callable[[str, str], "Role"]] = None,) -> None:self._store = store@@ -169,12 +178,15 @@ class OpenVikingOAuthProvider() -> str:"""Mint a verification code and stash the AuthorizationParams.- Returns the URL of our authorize page, which displays a 6-character- verification code. The user re-types that code into the OpenViking- console (where they're already authenticated), the console calls our- ``/api/v1/auth/oauth-verify`` endpoint to bind the caller's identity- to the pending row, and the page polls until verified to redirect- back to the client's redirect_uri.+ Returns the URL of the configured authorize page. By default this is+ ``/studio/oauth/consent``, a SPA route inside OpenViking Studio that+ renders a consent card using the Studio user's existing session and+ calls ``/api/v1/auth/oauth-verify`` directly. For CLI / cross-device+ flows the user can switch to ``/oauth/authorize/page`` (the+ server-rendered fallback) which displays a 6-character display_code+ and asks the user to enter it on another device's Studio at+ ``/studio/oauth/verify``. Either path polls until verified and then+ redirects back to the client's ``redirect_uri``."""assert client.client_id is not Nonedisplay_code = generate_otp()diff --git a/openviking/server/oauth/router.py b/openviking/server/oauth/router.pyindex 8a5943f9c..7f9115bf4 100644--- a/openviking/server/oauth/router.py+++ b/openviking/server/oauth/router.py@@ -6,13 +6,21 @@ The OAuth 2.1 protocol surface (DCR, /authorize parsing, /token, well-knownmetadata) is delegated to the official ``mcp.server.auth`` SDK (mounted from``app.py``). This module only owns:-- ``/oauth/authorize/page`` — HTML form where the user submits an OTP. The- SDK's AuthorizationHandler returns this URL from ``provider.authorize()``;- on successful OTP submission we mint an authorization code and 302 back- to the client's redirect_uri.+- ``GET /api/v1/auth/oauth/pending/{{pending_id}}`` — public metadata+ endpoint consumed by the Studio consent UI. Returns the minimum info+ needed to render the consent card (client_name, redirect_host, scopes);+ never the display_code or full redirect_uri.+- ``POST /api/v1/auth/oauth-verify`` — binds the caller's identity to a+ pending OAuth authorization. Accepts either ``pending_id`` (Studio+ consent path) or ``code`` (the 6-character display_code typed on a+ cross-device fallback page).- ``POST /api/v1/auth/otp`` — short-code issuance, authenticated with thecaller'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+ another device" or has no Studio access on the current device."""from __future__ import annotations@@ -20,7 +28,7 @@ from __future__ import annotationsimport htmlimport osfrom typing import Optional-from urllib.parse import urlencode+from urllib.parse import urlencode, urlparsefrom fastapi import APIRouter, Depends, Requestfrom fastapi.responses import HTMLResponse, JSONResponse@@ -76,22 +84,13 @@ _AUTHORIZE_PAGE_TEMPLATE = """<!DOCTYPE html>margin: 1.5rem 0 1rem; text-align: center; }}.code {{ font-family: ui-monospace, monospace; font-size: 2.4rem;letter-spacing: 0.4rem; font-weight: 600; color: #1d1d1f; }}- .console-link {{ display: inline-block; margin-top: 0.5rem; padding: 0.4rem 0.85rem;- border-radius: 6px; background: #0071e3; color: white;- text-decoration: none; font-size: 0.9rem; }}- .console-link:hover {{ background: #0077ed; }}+ .studio-link {{ display: inline-block; margin-top: 0.75rem; padding: 0.4rem 0.85rem;+ border-radius: 6px; background: #0071e3; color: white;+ text-decoration: none; font-size: 0.9rem; word-break: break-all; }}+ .studio-link:hover {{ background: #0077ed; }}.hint {{ font-size: 0.85rem; color: #86868b; margin-top: 1rem; }}code {{ background: #f5f5f7; padding: 1px 6px; border-radius: 4px;font-family: ui-monospace, monospace; font-size: 0.85rem; }}- .same-origin-panel {{ display: none; background: #f1f8e9; border: 1px solid #c5e1a5;- border-radius: 8px; padding: 1rem; margin: 1rem 0; }}- .same-origin-panel.visible {{ display: block; }}- .same-origin-panel h2 {{ margin: 0 0 0.5rem; font-size: 1rem; color: #33691e; }}- .same-origin-panel button {{ margin-top: 0.75rem; padding: 0.6rem 1.25rem; border: 0;- border-radius: 6px; background: #33691e; color: white;- font-size: 0.95rem; cursor: pointer; }}- .same-origin-panel button:hover {{ background: #3d7a22; }}- .same-origin-panel button:disabled {{ background: #aab; cursor: not-allowed; }}.status {{ margin-top: 1rem; padding: 0.6rem 0.75rem; border-radius: 6px;font-size: 0.9rem; display: none; }}.status.visible {{ display: block; }}@@ -102,22 +101,20 @@ _AUTHORIZE_PAGE_TEMPLATE = """<!DOCTYPE html><body><div class="card"><h1>Authorize <span class="client">{client_name}</span></h1>- <p>This client is requesting access to your OpenViking workspace. To continue,- go to the OpenViking console and enter the verification code below.</p>+ <p>This is the cross-device authorization page. On another device that is+ signed in to OpenViking Studio, open the link below and enter the+ verification code.</p><div class="codebox"><div class="code" id="displayCode">{display_code}</div>- <a class="console-link" href="{public_base_url}/console" target="_blank" rel="noopener">- Open OpenViking console →+ <a class="studio-link" href="{public_base_url}/studio/oauth/verify" target="_blank" rel="noopener">+ Open {public_base_url}/studio/oauth/verify</a></div>- <div class="same-origin-panel" id="sameOriginPanel">- <h2>Quick authorize</h2>- <p style="margin: 0;">You're signed in to the console in this browser.- Click below to authorize <strong>{client_name}</strong> with that identity.</p>- <button id="quickAuthBtn" type="button">Authorize</button>- </div>+ <p class="hint">If you can open OpenViking Studio on <em>this</em> device,+ go back to the link your MCP client gave you — Studio will let you+ authorize without typing this code.</p><div class="status" id="statusBox"></div>@@ -127,65 +124,14 @@ _AUTHORIZE_PAGE_TEMPLATE = """<!DOCTYPE html><script>(function() {{const PENDING = "{pending_id}";- const DISPLAY_CODE = "{display_code}";const STATUS_URL = "/oauth/authorize/page/status?pending=" + encodeURIComponent(PENDING);- // Same-origin verify endpoint exposed by the 8020 console proxy. When the- // console isn't reverse-proxied to the same origin as this page, the- // detection below will simply not find a key and the panel stays hidden.- const VERIFY_URL = "/console/api/v1/ov/auth/oauth-verify";- const SESSION_KEY = "ov_console_api_key";const statusEl = document.getElementById("statusBox");- const panelEl = document.getElementById("sameOriginPanel");- const buttonEl = document.getElementById("quickAuthBtn");function showStatus(msg, kind) {{statusEl.textContent = msg;statusEl.className = "status visible " + (kind || "info");}}- function clearStatus() {{- statusEl.className = "status";- }}- // Show the quick-authorize panel only if we can find an API key in this- // browser's localStorage (i.e. the console is on the same origin and- // the user is signed in). The console persists the API key here for- // cross-tab use; sessionStorage holds a per-tab copy that this page- // (a different tab) can't see, so we deliberately read localStorage.- // Click still requires explicit confirmation.- let sameOriginKey = null;- try {{- sameOriginKey = window.localStorage.getItem(SESSION_KEY)- || window.sessionStorage.getItem(SESSION_KEY);- }} catch (e) {{ /* storage may be unavailable; ignore */ }}- if (sameOriginKey) {{- panelEl.classList.add("visible");- buttonEl.addEventListener("click", async function() {{- buttonEl.disabled = true;- clearStatus();- try {{- const resp = await fetch(VERIFY_URL, {{- method: "POST",- headers: {{- "Content-Type": "application/json",- "X-Api-Key": sameOriginKey,- }},- body: JSON.stringify({{code: DISPLAY_CODE, decision: "approve"}}),- }});- if (!resp.ok) {{- const text = await resp.text();- showStatus("Authorize failed: " + text.slice(0, 200), "error");- buttonEl.disabled = false;- return;- }}- showStatus("Authorized — redirecting…", "info");- }} catch (err) {{- showStatus("Network error: " + err.message, "error");- buttonEl.disabled = false;- }}- }});- }}-- // Poll the status endpoint until verified, then redirect.async function pollOnce() {{try {{const resp = await fetch(STATUS_URL, {{cache: "no-store"}});@@ -385,13 +331,75 @@ async def authorize_page_status(request: Request, pending: str = "") -> JSONResp)+# ---------------------------------------------------------------------------+# GET /api/v1/auth/oauth/pending/{pending_id}+#+# Public metadata endpoint consumed by the Studio consent UI. Given a+# pending_id from the authorize URL, returns the minimum info the SPA needs+# to render the consent card (client_name, redirect_host, scopes).+#+# Intentionally does NOT return:+# - display_code: would defeat the cross-device input-code brute-force+# protection (a leaked pending_id could otherwise be converted into a+# valid OTP).+# - full redirect_uri: only the host portion is shown to the user. The+# full URI lives server-side in the pending row and is only revealed+# when the verify step turns into a 302 to the client.+# ---------------------------------------------------------------------------+++class OAuthPendingInfo(BaseModel):+ client_id: str+ client_name: Optional[str] = None+ redirect_host: Optional[str] = None+ scopes: list[str] = Field(default_factory=list)+++ "/api/v1/auth/oauth/pending/{pending_id}",+ response_model=OAuthPendingInfo,+)+async def oauth_pending_info(request: Request, pending_id: str) -> JSONResponse:+ """Return public-safe metadata about a pending OAuth authorization."""+ store, provider = _get_store_and_provider(request)+ record = await store.load_pending_authorization(pending_id)+ if record is None:+ return JSONResponse({"error": "expired"}, status_code=404)++ client = await provider.get_client(record["client_id"])+ redirect_uri = record.get("redirect_uri") or ""+ redirect_host = urlparse(redirect_uri).netloc or None++ return JSONResponse(+ OAuthPendingInfo(+ client_id=record["client_id"],+ client_name=client.client_name if client else None,+ redirect_host=redirect_host,+ scopes=list(record.get("scopes") or []),+ ).model_dump(mode="json"),+ headers={"Cache-Control": "no-store"},+ )++# ---------------------------------------------------------------------------# POST /api/v1/auth/oauth-verify (authenticated; binds caller identity)# ---------------------------------------------------------------------------class OAuthVerifyRequest(BaseModel):- code: str = Field(..., description="The 6-character display code from the authorize page")+ # Exactly one of (code, pending_id) must be set. ``code`` is the+ # 6-character display_code used by the cross-device fallback page+ # (/oauth/authorize/page). ``pending_id`` is the opaque pending_id used+ # by the same-device Studio consent UI, which already has the id on+ # hand from the authorize URL and doesn't need a re-typed OTP.+ code: Optional[str] = Field(+ default=None,+ description="6-character display code (cross-device fallback path)",+ )+ pending_id: Optional[str] = Field(+ default=None,+ description="Opaque pending_id from the authorize URL (Studio consent path)",+ )decision: str = Field(default="approve",description="'approve' to authorize the client, 'deny' to reject",@@ -412,11 +420,17 @@ async def oauth_verify() -> JSONResponse:"""Bind the caller's identity to a pending OAuth authorization.- The user reads a 6-character verification code off the MCP client's- authorize page, then submits it here from a session that's already- authenticated (typically via the OpenViking console). On approve we- write the caller's (account, user, role) into the pending row; the- authorize page's polling then catches that and redirects the client+ Two entry points converge here:++ - Same-device Studio consent: ``/studio/oauth/consent`` posts ``pending_id``+ using the user's already-loaded Studio session as Bearer.+ - Cross-device fallback: the user reads a 6-character display_code off the+ MCP client's authorize page (``/oauth/authorize/page``) and re-types it+ on another already-signed-in device at ``/studio/oauth/verify``, which+ posts ``code``.++ On approve we write the caller's (account, user, role) into the pending+ row; the authorize page's polling catches that and redirects the clientback to ``redirect_uri`` with a fresh authorization code."""store, provider = _get_store_and_provider(request)@@ -430,16 +444,27 @@ async def oauth_verify(if ctx.from_oauth:raise PermissionDeniedError("OAuth-issued tokens cannot authorize new OAuth clients. "- "Use your API key or sign in to the console to verify."+ "Use your API key or sign in to OpenViking Studio to verify.")decision = body.decision.lower().strip()if decision not in {"approve", "deny"}:raise InvalidArgumentError("decision must be 'approve' or 'deny'")- record = await store.find_pending_by_display_code(body.code)- if record is None:- raise InvalidArgumentError("Invalid or expired verification code")+ # Two callers, two lookup paths: Studio's consent SPA has the pending_id+ # straight off the authorize URL; the cross-device fallback page asks+ # the user to type the 6-char display_code on a different device. Both+ # converge to the same pending row.+ if body.pending_id:+ record = await store.load_pending_authorization(body.pending_id)+ if record is None or record.get("verified"):+ raise InvalidArgumentError("Invalid or expired pending authorization")+ elif body.code:+ record = await store.find_pending_by_display_code(body.code)+ if record is None:+ raise InvalidArgumentError("Invalid or expired verification code")+ else:+ raise InvalidArgumentError("Must provide either 'pending_id' or 'code'")if decision == "deny":await store.delete_pending_authorization(record["pending_id"])@@ -520,7 +545,8 @@ async def issue_otp(# /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 the console."+ "OAuth-issued tokens cannot issue OTPs. "+ "Use your API key or sign in to OpenViking Studio.")cfg = getattr(request.app.state, "oauth_config", None)diff --git a/tests/server/oauth/test_router.py b/tests/server/oauth/test_router.pyindex 35d54ce49..3206d24d4 100644--- a/tests/server/oauth/test_router.py+++ b/tests/server/oauth/test_router.py@@ -34,7 +34,10 @@ from openviking.server.auth import get_request_contextfrom openviking.server.config import ServerConfigfrom openviking.server.identity import Rolefrom openviking.server.models import ERROR_CODE_TO_HTTP_STATUS-from openviking.server.oauth.provider import OpenVikingOAuthProvider+from openviking.server.oauth.provider import (+ FALLBACK_AUTHORIZE_PAGE,+ OpenVikingOAuthProvider,+)from openviking.server.oauth.router import router as oauth_routerfrom openviking.server.oauth.storage import OAuthStorefrom openviking_cli.exceptions import OpenVikingError@@ -74,7 +77,14 @@ async def app_with_oauth(tmp_path):store = OAuthStore(tmp_path / "oauth.db")await store.initialize()issuer = "http://127.0.0.1"- provider = OpenVikingOAuthProvider(store=store, issuer=issuer)+ # Default authorize page is the /studio SPA consent route, which isn't+ # mounted in this minimal test app. Pin to the server-rendered fallback+ # so the existing full-flow test can drive the HTML page directly.+ provider = OpenVikingOAuthProvider(+ store=store,+ issuer=issuer,+ authorize_page_path=FALLBACK_AUTHORIZE_PAGE,+ )app = FastAPI()app.state.config = ServerConfig(auth_mode="api_key", root_api_key="root-test-1234567890abcd")@@ -337,6 +347,62 @@ async def test_full_device_flow(app_with_oauth, client):assert record.role == "user"+async def test_oauth_pending_info_endpoint(app_with_oauth, client):+ """Public GET endpoint returns minimum info for the Studio consent UI;+ never exposes display_code or the full redirect_uri."""+ _, store, _ = app_with_oauth+ client_id, pending_id, _, _ = await _start_authorize(+ client, redirect_uri="https://claude.ai/cb"+ )++ resp = await client.get(f"/api/v1/auth/oauth/pending/{pending_id}")+ assert resp.status_code == 200+ body = resp.json()+ assert body["client_id"] == client_id+ assert body["client_name"] == "Claude"+ assert body["redirect_host"] == "claude.ai"+ assert "display_code" not in body+ assert "redirect_uri" not in body+ # Sanity: the real display_code IS stored, we just don't return it.+ record = await store.load_pending_authorization(pending_id)+ assert record is not None and record["display_code"]+++async def test_oauth_pending_info_404_when_missing(client):+ resp = await client.get("/api/v1/auth/oauth/pending/doesnotexist")+ assert resp.status_code == 404+++async def test_oauth_verify_by_pending_id(app_with_oauth, client):+ """Studio consent path: verify with pending_id instead of display_code."""+ _, store, _ = app_with_oauth+ client_id, pending_id, _, _ = await _start_authorize(+ client, redirect_uri="https://claude.ai/cb", state="abc"+ )++ verify = await client.post(+ "/api/v1/auth/oauth-verify",+ json={"pending_id": pending_id, "decision": "approve"},+ )+ assert verify.status_code == 200, verify.text+ body = verify.json()+ assert body["status"] == "approved"+ assert body["client_id"] == client_id++ record = await store.load_pending_authorization(pending_id)+ assert record is not None+ assert record["verified"] is True+++async def test_oauth_verify_requires_pending_or_code(client):+ resp = await client.post("/api/v1/auth/oauth-verify", json={"decision": "approve"})+ assert resp.status_code == 400++@pytest.mark.asyncioasync def test_oauth_verify_unknown_code(app_with_oauth, client):_, _, _ = app_with_oauthdiff --git a/web-studio/src/components/connection-dialog.tsx b/web-studio/src/components/connection-dialog.tsxindex 4a84efaaa..6c93acebd 100644--- a/web-studio/src/components/connection-dialog.tsx+++ b/web-studio/src/components/connection-dialog.tsx@@ -1,7 +1,10 @@import * as React from 'react'import { useTranslation } from 'react-i18next'-import { useAppConnection } from '#/hooks/use-app-connection'+import {+ summarizeConnectionIdentity,+ useAppConnection,+} from '#/hooks/use-app-connection'import { Button } from '#/components/ui/button'import {@@ -25,10 +28,27 @@ import {FieldLabel,FieldSet,} from '#/components/ui/field'+import {+ IdentityPicker,+ resolveEffectiveApiKey,+} from '#/components/identity-picker'+import type { IdentityPickerValue } from '#/components/identity-picker'import { Input } from '#/components/ui/input'+type OtpResult = {+ otp: string+ expires_at: number+ ttl_seconds: number+}++type OtpPhase =+ | { kind: 'idle' }+ | { kind: 'requesting' }+ | { kind: 'ready'; result: OtpResult }+ | { kind: 'error'; message: string }+export function ConnectionDialog() {- const { t } = useTranslation(['connection', 'common'])+ const { t } = useTranslation(['connection', 'oauth', 'common'])const {connection,isConnectionDialogOpen,@@ -186,6 +206,8 @@ export function ConnectionDialog() {</>)}</Card>++ <OAuthOtpSection /></FieldGroup></FieldSet>@@ -209,3 +231,182 @@ export function ConnectionDialog() {</Dialog>)}++function OAuthOtpSection() {+ 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 size="sm" className="gap-3 border bg-background/70 shadow-none">+ <CardHeader className="gap-1.5">+ <CardTitle className="text-sm">+ {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>+ <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/components/identity-picker.tsx b/web-studio/src/components/identity-picker.tsxnew file mode 100644index 000000000..ddda480be--- /dev/null+++ b/web-studio/src/components/identity-picker.tsx@@ -0,0 +1,110 @@+import * as React from 'react'+import { useTranslation } from 'react-i18next'++import { Field, FieldContent, FieldLabel } from '#/components/ui/field'+import { Input } from '#/components/ui/input'+import { RadioGroup, RadioGroupItem } from '#/components/ui/radio-group'++export type IdentityPickerValue =+ | { mode: 'current' }+ | { mode: 'custom'; apiKey: string }++type IdentityPickerProps = {+ value: IdentityPickerValue+ onChange: (value: IdentityPickerValue) => void+ currentApiKey: string+ currentIdentityLabel: string+ customKeyId?: string+ disabled?: boolean+}++export function resolveEffectiveApiKey(+ value: IdentityPickerValue,+ currentApiKey: string,+): string {+ return value.mode === 'current' ? currentApiKey : value.apiKey+}++export function IdentityPicker({+ value,+ onChange,+ currentApiKey,+ currentIdentityLabel,+ customKeyId = 'identity-picker-custom-key',+ disabled = false,+}: IdentityPickerProps) {+ const { t } = useTranslation(['oauth', 'common'])+ const hasCurrentKey = Boolean(currentApiKey)++ React.useEffect(() => {+ if (!hasCurrentKey && value.mode === 'current') {+ onChange({ mode: 'custom', apiKey: '' })+ }+ }, [hasCurrentKey, value, onChange])++ return (+ <RadioGroup+ value={value.mode}+ onValueChange={(next) => {+ if (next === 'current') {+ onChange({ mode: 'current' })+ } else {+ onChange({+ mode: 'custom',+ apiKey: value.mode === 'custom' ? value.apiKey : '',+ })+ }+ }}+ disabled={disabled}+ >+ <label className="flex items-start gap-3 cursor-pointer">+ <RadioGroupItem+ value="current"+ disabled={disabled || !hasCurrentKey}+ className="mt-0.5"+ />+ <div className="flex flex-col gap-0.5">+ <span className="text-sm font-medium leading-none">+ {t('identityPicker.useCurrent', { ns: 'oauth' })}+ </span>+ <span className="text-xs text-muted-foreground">+ {hasCurrentKey+ ? currentIdentityLabel+ : t('identityPicker.noCurrent', { ns: 'oauth' })}+ </span>+ </div>+ </label>++ <label className="flex items-start gap-3 cursor-pointer">+ <RadioGroupItem value="custom" disabled={disabled} className="mt-0.5" />+ <div className="flex flex-1 flex-col gap-2">+ <span className="text-sm font-medium leading-none">+ {t('identityPicker.useCustom', { ns: 'oauth' })}+ </span>+ {value.mode === 'custom' ? (+ <Field>+ <FieldLabel htmlFor={customKeyId} className="sr-only">+ {t('identityPicker.customKeyLabel', { ns: 'oauth' })}+ </FieldLabel>+ <FieldContent>+ <Input+ id={customKeyId}+ type="password"+ autoComplete="off"+ placeholder={t('identityPicker.customKeyPlaceholder', {+ ns: 'oauth',+ })}+ value={value.apiKey}+ onChange={(event) =>+ onChange({ mode: 'custom', apiKey: event.target.value })+ }+ disabled={disabled}+ />+ </FieldContent>+ </Field>+ ) : null}+ </div>+ </label>+ </RadioGroup>+ )+}diff --git a/web-studio/src/i18n/locales/en.ts b/web-studio/src/i18n/locales/en.tsindex 88ff480b2..efbd1ec99 100644--- a/web-studio/src/i18n/locales/en.ts+++ b/web-studio/src/i18n/locales/en.ts@@ -96,6 +96,19 @@ 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}}',+ },},home: {agentAccess: {@@ -585,6 +598,57 @@ const en = {title: 'No session selected',},},+ oauth: {+ identityPicker: {+ useCurrent: 'Authorize as the current identity',+ noCurrent:+ 'No identity set. Open Connection & Identity to sign in first, or use a different API key below.',+ useCustom: 'Use a different API key',+ customKeyLabel: 'API key',+ customKeyPlaceholder: 'Paste an API key (not persisted)',+ },+ consent: {+ title: 'Authorize {{clientName}}',+ loading: 'Loading authorization request…',+ expired:+ 'This authorization has expired or is no longer valid. Restart the flow from your MCP client.',+ missingPending:+ 'Missing authorization id. Open the link your MCP client gave you.',+ requestSummary:+ '{{clientName}} is requesting access to your OpenViking workspace.',+ redirectLabel: 'Redirect',+ scopesLabel: 'Scopes',+ scopesNone: '(none)',+ signInRequired:+ 'Sign in to OpenViking Studio (Connection & Identity) or paste an API key below to authorize this client.',+ openConnectionDialog: 'Open Connection & Identity',+ authorize: 'Authorize',+ deny: 'Deny',+ useAnotherDevice: 'Use another device →',+ waitingRedirect: 'Authorized — redirecting back to the client…',+ verifying: 'Verifying…',+ denying: 'Denying…',+ denied: 'Denied. You can close this tab.',+ verifyError: 'Authorization failed: {{message}}',+ noApiKey: 'No API key available. Select an identity or paste a key.',+ },+ verify: {+ title: 'Cross-device verify',+ description:+ 'Enter the 6-character code shown on the device that started the MCP client login.',+ codeLabel: 'Verification code',+ codePlaceholder: '6-character code',+ submit: 'Authorize',+ success:+ 'Authorized for {{clientName}}. You can close this tab and return to the original device.',+ successUnknownClient:+ 'Authorized. You can close this tab and return to the original device.',+ verifyError: 'Authorization failed: {{message}}',+ noApiKey: 'No API key available. Select an identity or paste a key.',+ signInRequired:+ 'Sign in to OpenViking Studio (Connection & Identity) or paste an API key below to verify.',+ },+ },} as constexport default endiff --git a/web-studio/src/i18n/locales/zh-CN.ts b/web-studio/src/i18n/locales/zh-CN.tsindex d8cd7fac0..7efe42a7c 100644--- a/web-studio/src/i18n/locales/zh-CN.ts+++ b/web-studio/src/i18n/locales/zh-CN.ts@@ -96,6 +96,19 @@ const zhCN = {placeholder: 'default',},},+ oauthOtp: {+ title: 'OAuth 客户端 OTP',+ description:+ '生成一个短期一次性码,让 MCP 客户端凭此以所选身份完成 OAuth 授权。',+ generate: '生成 OTP',+ regenerate: '重新生成',+ copy: '复制',+ copied: '已复制',+ codeLabel: '一次性码',+ expiresIn: '{{seconds}} 秒后失效',+ expired: '已过期 —— 请重新生成。',+ generateError: '生成 OTP 失败:{{message}}',+ },},home: {agentAccess: {@@ -574,6 +587,51 @@ const zhCN = {title: '未选择会话',},},+ oauth: {+ identityPicker: {+ useCurrent: '以当前身份授权',+ noCurrent:+ '尚未配置身份。请先在“连接与身份”中登录,或在下方临时粘贴一个 API key。',+ useCustom: '使用其他 API key',+ customKeyLabel: 'API key',+ customKeyPlaceholder: '粘贴一个 API key(不会持久化)',+ },+ consent: {+ title: '授权 {{clientName}}',+ loading: '正在加载授权请求…',+ expired: '此次授权已过期或不再有效,请从 MCP 客户端重新发起。',+ missingPending: '缺少授权 ID,请打开 MCP 客户端给出的链接。',+ requestSummary: '{{clientName}} 请求访问你的 OpenViking 工作区。',+ redirectLabel: '回跳地址',+ scopesLabel: '权限范围',+ scopesNone: '(无)',+ signInRequired:+ '请先在“连接与身份”中登录 OpenViking Studio,或在下方临时粘贴 API key 完成授权。',+ openConnectionDialog: '打开连接与身份',+ authorize: '授权',+ deny: '拒绝',+ useAnotherDevice: '在另一台设备上授权 →',+ waitingRedirect: '已授权——正在回跳到客户端…',+ verifying: '正在验证…',+ denying: '正在拒绝…',+ denied: '已拒绝,可以关闭此页。',+ verifyError: '授权失败:{{message}}',+ noApiKey: '没有可用的 API key。请选择一个身份或粘贴 key。',+ },+ verify: {+ title: '跨设备验证',+ description: '请输入发起 MCP 客户端登录的那台设备上显示的 6 位验证码。',+ codeLabel: '验证码',+ codePlaceholder: '6 位验证码',+ submit: '授权',+ success: '已为 {{clientName}} 授权,可以关闭此页并回到原设备。',+ successUnknownClient: '已授权,可以关闭此页并回到原设备。',+ verifyError: '授权失败:{{message}}',+ noApiKey: '没有可用的 API key。请选择一个身份或粘贴 key。',+ signInRequired:+ '请先在“连接与身份”中登录 OpenViking Studio,或在下方临时粘贴 API key 完成授权。',+ },+ },} as constexport default zhCNdiff --git a/web-studio/src/routeTree.gen.ts b/web-studio/src/routeTree.gen.tsindex db03bbb32..0719c5634 100644--- a/web-studio/src/routeTree.gen.ts+++ b/web-studio/src/routeTree.gen.ts@@ -17,6 +17,8 @@ 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 ResourcesIndexRouteImport } from './routes/resources/index'+import { Route as OauthVerifyRouteImport } from './routes/oauth/verify'+import { Route as OauthConsentRouteImport } from './routes/oauth/consent'const SessionsRouteRoute = SessionsRouteRouteImport.update({id: '/sessions',@@ -58,6 +60,16 @@ const ResourcesIndexRoute = ResourcesIndexRouteImport.update({path: '/',getParentRoute: () => ResourcesRouteRoute,} as any)+const OauthVerifyRoute = OauthVerifyRouteImport.update({+ id: '/oauth/verify',+ path: '/oauth/verify',+ getParentRoute: () => rootRouteImport,+} as any)+const OauthConsentRoute = OauthConsentRouteImport.update({+ id: '/oauth/consent',+ path: '/oauth/consent',+ getParentRoute: () => rootRouteImport,+} as any)export interface FileRoutesByFullPath {'/': typeof IndexRoute@@ -66,6 +78,8 @@ export interface FileRoutesByFullPath {'/resources': typeof ResourcesRouteRouteWithChildren'/retrieval': typeof RetrievalRouteRoute'/sessions': typeof SessionsRouteRouteWithChildren+ '/oauth/consent': typeof OauthConsentRoute+ '/oauth/verify': typeof OauthVerifyRoute'/resources/': typeof ResourcesIndexRoute'/sessions/': typeof SessionsIndexRoute}@@ -74,6 +88,8 @@ export interface FileRoutesByTo {'/home': typeof HomeRouteRoute'/request-logs': typeof RequestLogsRouteRoute'/retrieval': typeof RetrievalRouteRoute+ '/oauth/consent': typeof OauthConsentRoute+ '/oauth/verify': typeof OauthVerifyRoute'/resources': typeof ResourcesIndexRoute'/sessions': typeof SessionsIndexRoute}@@ -85,6 +101,8 @@ export interface FileRoutesById {'/resources': typeof ResourcesRouteRouteWithChildren'/retrieval': typeof RetrievalRouteRoute'/sessions': typeof SessionsRouteRouteWithChildren+ '/oauth/consent': typeof OauthConsentRoute+ '/oauth/verify': typeof OauthVerifyRoute'/resources/': typeof ResourcesIndexRoute'/sessions/': typeof SessionsIndexRoute}@@ -97,6 +115,8 @@ export interface FileRouteTypes {| '/resources'| '/retrieval'| '/sessions'+ | '/oauth/consent'+ | '/oauth/verify'| '/resources/'| '/sessions/'fileRoutesByTo: FileRoutesByTo@@ -105,6 +125,8 @@ export interface FileRouteTypes {| '/home'| '/request-logs'| '/retrieval'+ | '/oauth/consent'+ | '/oauth/verify'| '/resources'| '/sessions'id:@@ -115,6 +137,8 @@ export interface FileRouteTypes {| '/resources'| '/retrieval'| '/sessions'+ | '/oauth/consent'+ | '/oauth/verify'| '/resources/'| '/sessions/'fileRoutesById: FileRoutesById@@ -126,6 +150,8 @@ export interface RootRouteChildren {ResourcesRouteRoute: typeof ResourcesRouteRouteWithChildrenRetrievalRouteRoute: typeof RetrievalRouteRouteSessionsRouteRoute: typeof SessionsRouteRouteWithChildren+ OauthConsentRoute: typeof OauthConsentRoute+ OauthVerifyRoute: typeof OauthVerifyRoute}declare module '@tanstack/react-router' {@@ -186,6 +212,20 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof ResourcesIndexRouteImportparentRoute: typeof ResourcesRouteRoute}+ '/oauth/verify': {+ id: '/oauth/verify'+ path: '/oauth/verify'+ fullPath: '/oauth/verify'+ preLoaderRoute: typeof OauthVerifyRouteImport+ parentRoute: typeof rootRouteImport+ }+ '/oauth/consent': {+ id: '/oauth/consent'+ path: '/oauth/consent'+ fullPath: '/oauth/consent'+ preLoaderRoute: typeof OauthConsentRouteImport+ parentRoute: typeof rootRouteImport+ }}}@@ -220,6 +260,8 @@ const rootRouteChildren: RootRouteChildren = {ResourcesRouteRoute: ResourcesRouteRouteWithChildren,RetrievalRouteRoute: RetrievalRouteRoute,SessionsRouteRoute: SessionsRouteRouteWithChildren,+ OauthConsentRoute: OauthConsentRoute,+ OauthVerifyRoute: OauthVerifyRoute,}export const routeTree = rootRouteImport._addFileChildren(rootRouteChildren)diff --git a/web-studio/src/routes/oauth/consent.tsx b/web-studio/src/routes/oauth/consent.tsxnew file mode 100644index 000000000..a68801c3f--- /dev/null+++ b/web-studio/src/routes/oauth/consent.tsx@@ -0,0 +1,333 @@+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 {+ IdentityPicker,+ resolveEffectiveApiKey,+} from '#/components/identity-picker'+import type { IdentityPickerValue } from '#/components/identity-picker'+import {+ summarizeConnectionIdentity,+ useAppConnection,+} from '#/hooks/use-app-connection'++type ConsentSearch = {+ pending: string+}++type PendingInfo = {+ client_id: string+ client_name: string | null+ redirect_host: string | null+ scopes: string[]+}++type Phase =+ | { kind: 'loading' }+ | { kind: 'ready' }+ | { kind: 'verifying' }+ | { kind: 'denying' }+ | { kind: 'denied' }+ | { kind: 'waitingRedirect' }+ | { kind: 'expired' }+ | { kind: 'error'; message: string }++export const Route = createFileRoute('/oauth/consent')({+ validateSearch: (search: Record<string, unknown>): ConsentSearch => ({+ pending: typeof search.pending === 'string' ? search.pending : '',+ }),+ component: ConsentPage,+})++function ConsentPage() {+ const { t } = useTranslation(['oauth', 'common'])+ const { pending } = Route.useSearch()+ const { connection, openConnectionDialog, serverMode } = useAppConnection()++ const currentIdentity = React.useMemo(() => {+ const summary = summarizeConnectionIdentity(connection, serverMode)+ return summary.values?.identity ?? t(summary.labelKey, { ns: 'connection' })+ }, [connection, serverMode, t])++ const [pendingInfo, setPendingInfo] = React.useState<PendingInfo | null>(null)+ const [phase, setPhase] = React.useState<Phase>({ kind: 'loading' })+ const [identityValue, setIdentityValue] = React.useState<IdentityPickerValue>(+ () =>+ connection.apiKey ? { mode: 'current' } : { mode: 'custom', apiKey: '' },+ )++ React.useEffect(() => {+ if (!pending) {+ setPhase({ kind: 'error', message: t('consent.missingPending') })+ return+ }++ let cancelled = false+ setPhase({ kind: 'loading' })++ void fetch(`/api/v1/auth/oauth/pending/${encodeURIComponent(pending)}`, {+ cache: 'no-store',+ })+ .then(async (resp) => {+ if (cancelled) return+ if (resp.status === 404 || resp.status === 410) {+ setPhase({ kind: 'expired' })+ return+ }+ if (!resp.ok) {+ const text = await resp.text().catch(() => '')+ setPhase({+ kind: 'error',+ message: text.slice(0, 200) || String(resp.status),+ })+ return+ }+ const body = (await resp.json()) as PendingInfo+ setPendingInfo(body)+ setPhase({ kind: 'ready' })+ })+ .catch((err: unknown) => {+ if (cancelled) return+ const message = err instanceof Error ? err.message : String(err)+ setPhase({ kind: 'error', message })+ })++ return () => {+ cancelled = true+ }+ }, [pending, t])++ async function pollStatusAndRedirect(): Promise<void> {+ for (;;) {+ try {+ const resp = await fetch(+ `/oauth/authorize/page/status?pending=${encodeURIComponent(pending)}`,+ { cache: 'no-store' },+ )+ if (resp.status === 410) {+ setPhase({ kind: 'expired' })+ return+ }+ const body = (await resp.json()) as {+ status: string+ redirect_url?: string+ }+ if (body.status === 'approved' && body.redirect_url) {+ window.location.replace(body.redirect_url)+ return+ }+ } catch {+ // Transient — retry.+ }+ await new Promise((r) => setTimeout(r, 1000))+ }+ }++ async function postVerify(decision: 'approve' | 'deny'): Promise<void> {+ const effectiveKey = resolveEffectiveApiKey(+ identityValue,+ connection.apiKey,+ )+ if (decision === 'approve' && !effectiveKey) {+ setPhase({ kind: 'error', message: t('consent.noApiKey') })+ return+ }+ setPhase({ kind: decision === 'approve' ? 'verifying' : 'denying' })+ try {+ const resp = await fetch('/api/v1/auth/oauth-verify', {+ method: 'POST',+ cache: 'no-store',+ headers: {+ 'Content-Type': 'application/json',+ ...(effectiveKey ? { Authorization: `Bearer ${effectiveKey}` } : {}),+ },+ body: JSON.stringify({ pending_id: pending, decision }),+ })+ if (!resp.ok) {+ const text = await resp.text().catch(() => '')+ setPhase({+ kind: 'error',+ message: extractMessage(text) || String(resp.status),+ })+ return+ }+ if (decision === 'deny') {+ setPhase({ kind: 'denied' })+ return+ }+ setPhase({ kind: 'waitingRedirect' })+ void pollStatusAndRedirect()+ } catch (err: unknown) {+ const message = err instanceof Error ? err.message : String(err)+ setPhase({ kind: 'error', message })+ }+ }++ const clientName =+ pendingInfo?.client_name || pendingInfo?.client_id || 'MCP client'+ const fallbackHref = `/oauth/authorize/page?pending=${encodeURIComponent(pending)}`+ const hasAnyKey = Boolean(+ resolveEffectiveApiKey(identityValue, connection.apiKey),+ )++ return (+ <div className="flex min-h-[60vh] w-full items-center justify-center px-4 py-8">+ <Card className="w-full max-w-lg">+ <CardHeader>+ <CardTitle>{t('consent.title', { clientName })}</CardTitle>+ {phase.kind === 'ready' && pendingInfo ? (+ <CardDescription>+ {t('consent.requestSummary', { clientName })}+ </CardDescription>+ ) : null}+ </CardHeader>++ <CardContent className="grid gap-5">+ {phase.kind === 'loading' ? (+ <p className="text-sm text-muted-foreground">+ {t('consent.loading')}+ </p>+ ) : null}++ {phase.kind === 'expired' ? (+ <p className="text-sm text-destructive">{t('consent.expired')}</p>+ ) : null}++ {phase.kind === 'error' ? (+ <p className="text-sm text-destructive">+ {t('consent.verifyError', { message: phase.message })}+ </p>+ ) : null}++ {pendingInfo &&+ (phase.kind === 'ready' ||+ phase.kind === 'verifying' ||+ phase.kind === 'denying' ||+ phase.kind === 'waitingRedirect') ? (+ <>+ <dl className="grid gap-2 text-sm">+ <div className="flex justify-between gap-4">+ <dt className="text-muted-foreground">+ {t('consent.redirectLabel')}+ </dt>+ <dd className="font-mono text-foreground break-all">+ {pendingInfo.redirect_host ?? '—'}+ </dd>+ </div>+ <div className="flex justify-between gap-4">+ <dt className="text-muted-foreground">+ {t('consent.scopesLabel')}+ </dt>+ <dd className="font-mono text-foreground break-all">+ {pendingInfo.scopes.length > 0+ ? pendingInfo.scopes.join(' ')+ : t('consent.scopesNone')}+ </dd>+ </div>+ </dl>++ {!connection.apiKey ? (+ <div className="grid gap-2 rounded-md border border-dashed p-3 text-sm">+ <p>{t('consent.signInRequired')}</p>+ <Button+ variant="outline"+ size="sm"+ className="w-fit"+ onClick={openConnectionDialog}+ disabled={+ phase.kind === 'verifying' || phase.kind === 'denying'+ }+ >+ {t('consent.openConnectionDialog')}+ </Button>+ </div>+ ) : null}++ <IdentityPicker+ value={identityValue}+ onChange={setIdentityValue}+ currentApiKey={connection.apiKey}+ currentIdentityLabel={currentIdentity}+ disabled={+ phase.kind === 'verifying' ||+ phase.kind === 'denying' ||+ phase.kind === 'waitingRedirect'+ }+ />++ {phase.kind === 'waitingRedirect' ? (+ <p className="text-sm text-muted-foreground">+ {t('consent.waitingRedirect')}+ </p>+ ) : null}+ </>+ ) : null}++ {phase.kind === 'denied' ? (+ <p className="text-sm text-muted-foreground">+ {t('consent.denied')}+ </p>+ ) : null}+ </CardContent>++ {pendingInfo &&+ (phase.kind === 'ready' ||+ phase.kind === 'verifying' ||+ phase.kind === 'denying') ? (+ <CardFooter className="flex flex-col gap-3">+ <div className="flex w-full justify-end gap-2">+ <Button+ variant="outline"+ onClick={() => void postVerify('deny')}+ disabled={+ phase.kind === 'verifying' || phase.kind === 'denying'+ }+ >+ {phase.kind === 'denying'+ ? t('consent.denying')+ : t('consent.deny')}+ </Button>+ <Button+ onClick={() => void postVerify('approve')}+ disabled={+ phase.kind === 'verifying' ||+ phase.kind === 'denying' ||+ !hasAnyKey+ }+ >+ {phase.kind === 'verifying'+ ? t('consent.verifying')+ : t('consent.authorize')}+ </Button>+ </div>+ <a+ href={fallbackHref}+ className="self-end text-xs text-muted-foreground hover:text-foreground"+ >+ {t('consent.useAnotherDevice')}+ </a>+ </CardFooter>+ ) : null}+ </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)+ }+}diff --git a/web-studio/src/routes/oauth/verify.tsx b/web-studio/src/routes/oauth/verify.tsxnew file mode 100644index 000000000..584b33838--- /dev/null+++ b/web-studio/src/routes/oauth/verify.tsx@@ -0,0 +1,201 @@+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'++type Phase =+ | { kind: 'idle' }+ | { kind: 'verifying' }+ | { kind: 'success'; clientName: string | null }+ | { kind: 'error'; message: string }++export const Route = createFileRoute('/oauth/verify')({+ component: VerifyPage,+})++function VerifyPage() {+ const { t } = useTranslation(['oauth', 'common'])+ const { connection, openConnectionDialog, 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 [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),+ )++ return (+ <div className="flex min-h-[60vh] w-full items-center justify-center px-4 py-8">+ <Card className="w-full max-w-lg">+ <CardHeader>+ <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 ? (+ <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={openConnectionDialog}+ disabled={phase.kind === 'verifying'}+ >+ {t('consent.openConnectionDialog')}+ </Button>+ </div>+ ) : null}++ <IdentityPicker+ value={identityValue}+ onChange={setIdentityValue}+ currentApiKey={connection.apiKey}+ currentIdentityLabel={currentIdentity}+ 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>+ </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)+ }+}