Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
0.9.7: sign in to tool servers with Client ID Metadata Documents (ElevenLabs) (#574)
Oleksandr Ivanchenkoad035614de1e
diff --git a/docs/mcp-api.md b/docs/mcp-api.mdindex 6e706762..e142e9c1 100644--- a/docs/mcp-api.md+++ b/docs/mcp-api.md@@ -96,20 +96,43 @@ An http server that answers 401 while kwnt has no usable sign-in (and the user shttp servers that require sign-in (e.g. `https://mcp.notion.com/mcp`) use the MCP authorizationspec (2025-06-18): kwnt reads the 401's `WWW-Authenticate: Bearer resource_metadata=…` (or`/.well-known/oauth-protected-resource`), then the authorization server's metadata-(`/.well-known/oauth-authorization-server`, falling back to OpenID discovery), registers itself-as client `kwnt` (dynamic client registration, RFC 7591), and runs the authorization code flow-with PKCE S256 and the `resource` parameter (RFC 8707). Authorization-server endpoints must be-https (plain http only on loopback).+(`/.well-known/oauth-authorization-server`, falling back to OpenID discovery), gets a client+(below), and runs the authorization code flow with PKCE S256 and the `resource` parameter+(RFC 8707). Authorization-server endpoints must be https (plain http only on loopback).++How kwnt gets a client, in order:+1. A client stored earlier for this server, callback URL and authorization server.+2. Dynamic client registration (RFC 7591) as client `kwnt`, when the server has a+ `registration_endpoint`.+3. A client ID metadata document (MCP spec 2025-11-25), when the server says+ `client_id_metadata_document_supported: true` and has no registration endpoint, or refused+ the registration. The client_id is the document's https URL, with no client secret:+ - kwant opened on this computer (`127.0.0.1`, `localhost`, `[::1]`):+ `https://kwant.si/oauth/client.json`. It lists the callback on those hosts without a port+ and on port 8799; servers that match the port exactly only work on port 8799.+ - kwant on a public https address: `<origin>/api/mcp/oauth/client.json`, served by kwnt+ itself (below), so the server must be able to reach that address.+ - kwant on plain http elsewhere (a LAN address): no document; `502` with+ `"code": "cimd_needs_https"`.+4. Neither: `502` with `"code": "no_client_registration"`. The server only accepts clients registered with it in advance, and kwnt has no field for a client ID made that way, so retrying can't help.### `POST /api/mcp/servers/:id/oauth/start`Body: `{"origin": "https://kwnt.example.com"}`: the browser's `location.origin`. It must be http(s)with no path, and its host must equal the request's `Host` or `X-Forwarded-Host`. The callback is`<origin>/api/mcp/oauth/callback`, so the same build works on localhost and behind a proxy.`200` → `{"authorize_url": "https://…"}`: open it in a popup. `400` bad origin or a stdio server,-`404` unknown server, `502` discovery or registration failed (`{"error": "…"}`).+`404` unknown server, `502` discovery or registration failed (`{"error": "…"}`). A `502` with a+`code` (`no_client_registration`, `cimd_needs_https`) can't succeed on retry; without one it may.The sign-in must finish within 10 minutes; starting again for the same server replaces theearlier attempt. Registrations are reused per server, callback URL and authorization server.+### `GET /api/mcp/oauth/client.json`+kwnt's client ID metadata document for a self-hosted kwant, fetched by authorization servers+without an API token. Built from `X-Forwarded-Host` (first value) or `Host`, always as https:+`{"client_id": "https://<host>/api/mcp/oauth/client.json", "redirect_uris":+["https://<host>/api/mcp/oauth/callback"], "token_endpoint_auth_method": "none", …}`. `404` on a+loopback or malformed host (kwant on this computer uses kwant.si's document).+### `GET /api/mcp/oauth/callback?code=…&state=…` (or `?error=…&state=…`)Where the provider redirects the popup. kwnt exchanges the code and stores the tokens, thenreturns a small HTML page that runsdiff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex 183a47bf..d23dc416 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -38,7 +38,8 @@ import {turnsAwaitingStep,} from './humanSteps';import { notifyBrowserPages, pageTeam, stepPage } from './browserPages';-import { McpSuggestionCard } from './components/McpSuggestionCard';+import { McpSuggestionCard, type SuggestionSignInResult } from './components/McpSuggestionCard';+import { isSignInDeadEndCode } from './mcpSignInDeadEnd';import { ConnectionSuggestionCard } from './components/ConnectionSuggestionCard';import type { ConnectionSuggestionMeta } from './connectionSuggestions';import { Suggestion, SuggestionMeta, applySuggestion, suggestionsApi } from './mcpSuggestions';@@ -2507,7 +2508,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({};// Same flow as the servers screen: the window opens inside the click, the address comes after.// In the Mac app the sign-in opens in the default browser and the server is watched instead.- const handleSuggestionSignIn = async (serverId: string): Promise<string | void> => {+ const handleSuggestionSignIn = async (serverId: string): Promise<SuggestionSignInResult> => {const macApp = inDesktopApp();const popup = macApp ? null : window.open('', 'kwnt-mcp-oauth', 'popup,width=520,height=720');const before = macApp ? await mcpSignIn(serverId).catch(() => undefined) : undefined;@@ -2519,6 +2520,11 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({body: JSON.stringify({ origin: window.location.origin }),});const data = await res.json().catch(() => null);+ // A code means retrying can't help: the card swaps its button for a next step.+ if (!res.ok && isSignInDeadEndCode(data?.code)) {+ popup?.close();+ return { code: data.code };+ }if (!res.ok) throw new Error(typeof data?.error === 'string' ? data.error : `Request failed (HTTP ${res.status}).`);if (typeof data?.authorize_url !== 'string' || !/^https?:\/\//.test(data.authorize_url)) throw new Error('The server didn’t return a sign-in page.');url = data.authorize_url;diff --git a/frontend/src/components/McpServersModal.tsx b/frontend/src/components/McpServersModal.tsxindex d302bc3a..3e3dda18 100644--- a/frontend/src/components/McpServersModal.tsx+++ b/frontend/src/components/McpServersModal.tsx@@ -54,6 +54,7 @@ import {} from '../mcp';import { inDesktopApp, leaveForSignIn, pollUntil, signInChanged } from '../externalLinks';import { useEscapeLayer } from '../escape';+import { signInDeadEnd } from '../mcpSignInDeadEnd';import { ChooseBotsTarget, FindTool, FindToolApi } from './FindTool';import { DirectoryEntry, connectionsApi } from '../connections';@@ -91,6 +92,59 @@ const readError = async (res: Response) => {return `Something went wrong (HTTP ${res.status}).`;};+/** A sign-in that couldn't start: the server's message, and its `code` when retrying can't help. */+export interface OAuthFailure {+ message: string;+ code?: string;+}++/**+ * The amber "asks you to sign in" box on a server card. When the start call returned a dead-end code+ * (no_client_registration, cimd_needs_https) there is no Connect or Retry: one grey next step instead.+ */+export const SignInBox: React.FC<{+ serverName: string;+ isConnecting: boolean;+ macApp: boolean;+ failure?: OAuthFailure;+ onConnect: () => void;+}> = ({ serverName, isConnecting, macApp, failure, onConnect }) => {+ const deadEnd = failure && !isConnecting ? signInDeadEnd(failure.code, serverName, 'servers') : null;+ return (+ <div className="mt-2.5 ml-12 p-2.5 rounded-lg bg-amber-500/5 border border-amber-500/20 text-[11px] space-y-2">+ <div className="flex items-start gap-2 text-amber-100/90">+ <KeyRound size={13} className="flex-shrink-0 mt-px text-amber-400" />+ <span>+ {isConnecting+ ? macApp+ ? 'Finish signing in in your browser. This updates by itself when you’re done.'+ : 'Waiting for you to approve access in the sign-in window…'+ : 'This server asks you to sign in and approve access.'}+ </span>+ </div>+ {failure && !isConnecting && (+ <p role="alert" className="flex items-start gap-1.5 text-rose-300">+ <AlertCircle size={12} className="flex-shrink-0 mt-px" />+ <span>{deadEnd ? deadEnd.error : failure.message}</span>+ </p>+ )}+ {deadEnd ? (+ <p className="text-zinc-400">{deadEnd.next}</p>+ ) : (+ <button+ type="button"+ onClick={onConnect}+ disabled={isConnecting && !macApp}+ className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md text-[11px] font-medium text-white bg-sky-600 hover:bg-sky-500 transition-colors shadow-sm disabled:opacity-60"+ >+ {isConnecting && !macApp ? <Loader2 size={12} className="animate-spin" /> : <KeyRound size={12} />}+ {isConnecting ? (macApp ? 'Open the sign-in again' : 'Waiting…') : failure ? 'Retry' : 'Connect'}+ </button>+ )}+ </div>+ );+};+const StatusPill: React.FC<{ server: McpServer; status?: StoredStatus; testing: boolean }> = ({ server, status, testing }) => {const kind = serverStatusKind(server, status, testing);let cls = 'bg-zinc-800/60 text-zinc-400 border-zinc-700/60';@@ -325,7 +379,7 @@ export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClosconst [fromDirectory, setFromDirectory] = useState<DirectoryEntry | null>(null);// Sign-in: the server whose popup is open, sign-in errors per server, and a pending disconnect.const [connecting, setConnecting] = useState<string | null>(null);- const [oauthErrors, setOauthErrors] = useState<Record<string, string>>({});+ const [oauthErrors, setOauthErrors] = useState<Record<string, OAuthFailure>>({});const [confirmDisconnect, setConfirmDisconnect] = useState<string | null>(null);const popupRef = useRef<Window | null>(null);const popupWatch = useRef<number | null>(null);@@ -433,7 +487,7 @@ export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClosrefresh();runTest(id);} else {- setOauthErrors((e) => ({ ...e, [id]: msg.error || 'Sign-in didn’t finish. Try again.' }));+ setOauthErrors((e) => ({ ...e, [id]: { message: msg.error || 'Sign-in didn’t finish. Try again.' } }));playSfx('alert');}};@@ -468,20 +522,26 @@ export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClos}setConnecting(server.id);let url: string;+ let code: string | undefined;try {const res = await fetch(`/api/mcp/servers/${server.id}/oauth/start`, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ origin: window.location.origin }),});- if (!res.ok) throw new Error(await readError(res));- const body = await res.json();+ // Read the body once: a failed start carries `error` and, when retrying can't help, `code`.+ const body = await res.json().catch(() => null);+ if (!res.ok) {+ if (typeof body?.code === 'string') code = body.code;+ throw new Error(body?.error ? String(body.error) : `Something went wrong (HTTP ${res.status}).`);+ }if (typeof body?.authorize_url !== 'string' || !/^https?:\/\//.test(body.authorize_url)) throw new Error('The server didn’t return a sign-in page.');url = body.authorize_url;} catch (err) {popup?.close();setConnecting(null);- setOauthErrors((e) => ({ ...e, [server.id]: err instanceof Error ? err.message : 'Could not reach the server.' }));+ const message = err instanceof Error ? err.message : 'Could not reach the server.';+ setOauthErrors((e) => ({ ...e, [server.id]: { message, code } }));playSfx('alert');return;}@@ -774,33 +834,13 @@ export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClos</div>)}{(kind === 'needs_sign_in' || oauthError) && server.transport === 'http' && server.enabled && (- <div className="mt-2.5 ml-12 p-2.5 rounded-lg bg-amber-500/5 border border-amber-500/20 text-[11px] space-y-2">- <div className="flex items-start gap-2 text-amber-100/90">- <KeyRound size={13} className="flex-shrink-0 mt-px text-amber-400" />- <span>- {isConnecting- ? macApp- ? 'Finish signing in in your browser. This updates by itself when you’re done.'- : 'Waiting for you to approve access in the sign-in window…'- : 'This server asks you to sign in and approve access.'}- </span>- </div>- {oauthError && !isConnecting && (- <p role="alert" className="flex items-start gap-1.5 text-rose-300">- <AlertCircle size={12} className="flex-shrink-0 mt-px" />- <span>{oauthError}</span>- </p>- )}- <button- type="button"- onClick={() => connect(server)}- disabled={isConnecting && !macApp}- className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md text-[11px] font-medium text-white bg-sky-600 hover:bg-sky-500 transition-colors shadow-sm disabled:opacity-60"- >- {isConnecting && !macApp ? <Loader2 size={12} className="animate-spin" /> : <KeyRound size={12} />}- {isConnecting ? (macApp ? 'Open the sign-in again' : 'Waiting…') : oauthError ? 'Retry' : 'Connect'}- </button>- </div>+ <SignInBox+ serverName={server.name}+ isConnecting={isConnecting}+ macApp={macApp}+ failure={oauthError}+ onConnect={() => connect(server)}+ />)}{result && !result.ok && kind !== 'needs_sign_in' && (<div className="mt-2.5 ml-12 p-2.5 rounded-lg bg-rose-500/5 border border-rose-500/20 text-[11px] text-rose-200 space-y-1">diff --git a/frontend/src/components/McpSuggestionCard.tsx b/frontend/src/components/McpSuggestionCard.tsxindex 09c28b6f..68e698af 100644--- a/frontend/src/components/McpSuggestionCard.tsx+++ b/frontend/src/components/McpSuggestionCard.tsx@@ -3,6 +3,10 @@ import { AlertTriangle, CheckCircle2, ExternalLink, Globe, KeyRound, Loader2, Miimport { ModernAvatar } from './ModernAvatar';import { Suggestion, SuggestionMeta, failureText, inputKey, inputLabel, installPayload, runsLine, suggestionView } from '../mcpSuggestions';import { inDesktopApp } from '../externalLinks';+import { type SignInDeadEnd, type SignInDeadEndCode, signInDeadEnd } from '../mcpSignInDeadEnd';++/** What a sign-in attempt from the card reports: an error message, or a code retrying can't fix. */+export type SuggestionSignInResult = string | { code: SignInDeadEndCode } | void;export interface McpSuggestionCardProps {meta: SuggestionMeta;@@ -14,8 +18,11 @@ export interface McpSuggestionCardProps {/** Resolves to an error message on failure; `signIn` true when the server still needs a sign-in. */onInstall: (suggestionId: string, body: { env?: Record<string, string>; headers?: Record<string, string> }) => Promise<{ error?: string; signIn?: boolean }>;onDismiss: (suggestionId: string) => Promise<string | void>;- /** Opens the server's sign-in; resolves to an error message, or nothing once signed in. */- onSignIn: (serverId: string) => Promise<string | void>;+ /**+ * Opens the server's sign-in; resolves to an error message, a dead-end `code` (the button goes and+ * a next step shows), or nothing once signed in.+ */+ onSignIn: (serverId: string) => Promise<SuggestionSignInResult>;/** The install said this server needs a sign-in that hasn't happened yet. */needsSignIn?: boolean;flash?: boolean;@@ -43,7 +50,7 @@ export const McpSuggestionCard: React.FC<McpSuggestionCardProps> = ({const [busy, setBusy] = useState<'install' | 'dismiss' | 'signin' | null>(null);const [error, setError] = useState<string | null>(null);const [dismissError, setDismissError] = useState<string | null>(null);- const [signInError, setSignInError] = useState<string | null>(null);+ const [signInError, setSignInError] = useState<string | SignInDeadEnd | null>(null);const headingId = `mcp-s-${messageId}`;const pending = view.status === 'pending' && busy !== 'install';@@ -80,9 +87,10 @@ export const McpSuggestionCard: React.FC<McpSuggestionCardProps> = ({if (!view.server_id || busy) return;setBusy('signin');setSignInError(null);- const err = await onSignIn(view.server_id);+ const res = await onSignIn(view.server_id);setBusy(null);- if (err) setSignInError(err);+ if (typeof res === 'string') setSignInError(res);+ else if (res) setSignInError(signInDeadEnd(res.code, view.title, 'card'));};const border =@@ -238,22 +246,7 @@ export const McpSuggestionCard: React.FC<McpSuggestionCardProps> = ({)}</p>{view.status === 'installed' && needsSignIn && view.server_id && (- <div className="flex flex-wrap items-center gap-2">- <button- type="button"- onClick={signIn}- disabled={busy !== null}- className="inline-flex items-center gap-1.5 min-h-[40px] sm:min-h-[34px] px-3.5 rounded-xl text-sm font-medium bg-amber-500 text-zinc-950 hover:bg-amber-400 disabled:opacity-60 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-amber-400"- >- {busy === 'signin' && <Loader2 size={13} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />}- {busy === 'signin' ? (inDesktopApp() ? 'Finish signing in in your browser…' : 'Waiting for sign-in…') : signInError ? 'Try signing in again' : 'Sign in'}- </button>- {signInError && (- <span role="alert" className="text-rose-300 break-words">- {signInError}- </span>- )}- </div>+ <SuggestionSignIn busy={busy === 'signin'} disabled={busy !== null} error={signInError} onSignIn={signIn} />)}{dismissError && (<p role="alert" className="text-rose-300 break-words">@@ -265,3 +258,43 @@ export const McpSuggestionCard: React.FC<McpSuggestionCardProps> = ({</section>);};++/**+ * The card's sign-in row. A plain error keeps "Try signing in again"; a dead end (the server can't let+ * this app in from here) has no button, just the error and one next step under it.+ */+export const SuggestionSignIn: React.FC<{+ busy: boolean;+ disabled: boolean;+ error: string | SignInDeadEnd | null;+ onSignIn: () => void;+}> = ({ busy, disabled, error, onSignIn }) => {+ if (error && typeof error !== 'string') {+ return (+ <div className="space-y-1">+ <p role="alert" className="text-rose-300 break-words">+ {error.error}+ </p>+ <p className="text-zinc-400 break-words">{error.next}</p>+ </div>+ );+ }+ return (+ <div className="flex flex-wrap items-center gap-2">+ <button+ type="button"+ onClick={onSignIn}+ disabled={disabled}+ className="inline-flex items-center gap-1.5 min-h-[40px] sm:min-h-[34px] px-3.5 rounded-xl text-sm font-medium bg-amber-500 text-zinc-950 hover:bg-amber-400 disabled:opacity-60 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-amber-400"+ >+ {busy && <Loader2 size={13} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />}+ {busy ? (inDesktopApp() ? 'Finish signing in in your browser…' : 'Waiting for sign-in…') : error ? 'Try signing in again' : 'Sign in'}+ </button>+ {error && (+ <span role="alert" className="text-rose-300 break-words">+ {error}+ </span>+ )}+ </div>+ );+};diff --git a/frontend/src/mcpSignInDeadEnd.ts b/frontend/src/mcpSignInDeadEnd.tsnew file mode 100644index 00000000..aaf2c2c1--- /dev/null+++ b/frontend/src/mcpSignInDeadEnd.ts@@ -0,0 +1,42 @@+// Sign-ins that can never work from here (Mira's design check for #574). The server's start call+// returns one of these codes; retrying can't help, so the button goes and one next step takes its place.++export type SignInDeadEndCode = 'no_client_registration' | 'cimd_needs_https';++/** Where the copy shows: the Tool servers screen, or a bot's suggestion card in the chat. */+export type SignInSurface = 'servers' | 'card';++export interface SignInDeadEnd {+ code: SignInDeadEndCode;+ /** The rose error line. */+ error: string;+ /** The grey line that replaces Retry, Connect or "Try signing in again". */+ next: string;+}++export const isSignInDeadEndCode = (code: unknown): code is SignInDeadEndCode =>+ code === 'no_client_registration' || code === 'cimd_needs_https';++const ERROR: Record<SignInDeadEndCode, string> = {+ no_client_registration: 'This server only lets in apps that were set up with it in advance, so signing in from here can’t work.',+ cimd_needs_https: 'This server’s sign-in only works from localhost or an https address, not from a plain http address like this one.',+};++const LOCALHOST = 'Open this app in a browser on the computer it runs on, at localhost, and sign in there. Your bots here use that sign-in too.';++const next = (code: SignInDeadEndCode, name: string, surface: SignInSurface) => {+ if (code === 'cimd_needs_https') return LOCALHOST;+ return surface === 'servers'+ ? `If ${name} gives you an API key, edit this server and add the key under Headers instead.`+ : `If ${name} gives you an API key, add it under Headers in Settings › Apps & accounts › Advanced › Tool servers.`;+};++/**+ * The copy for a sign-in that can't work, or null for any other code (or none): then the screen keeps+ * today's error and its Retry. `name` is the server's name, or the suggestion's title on the card.+ */+export const signInDeadEnd = (code: unknown, name: string, surface: SignInSurface): SignInDeadEnd | null => {+ if (!isSignInDeadEndCode(code)) return null;+ const error = surface === 'card' ? `Couldn’t start the sign-in. ${ERROR[code]}` : ERROR[code];+ return { code, error, next: next(code, name, surface) };+};diff --git a/frontend/tests/mcpSignInDeadEnd.test.mjs b/frontend/tests/mcpSignInDeadEnd.test.mjsnew file mode 100644index 00000000..0e3159a7--- /dev/null+++ b/frontend/tests/mcpSignInDeadEnd.test.mjs@@ -0,0 +1,104 @@+// #574, Mira's design check: a sign-in that can never work from here (the start call returned+// no_client_registration or cimd_needs_https) has no Retry, Connect or "Try signing in again"; one grey+// next step takes the button's place, on the Tool servers screen and on the chat card.+import assert from 'node:assert/strict';+import test from 'node:test';+import { loadBundled } from './bundle.mjs';++// The servers screen's module reads saved statuses when it loads.+globalThis.localStorage ??= { getItem: () => null, setItem: () => {}, removeItem: () => {} };++const ui = await loadBundled(`+ import React from 'react';+ import { renderToStaticMarkup } from 'react-dom/server.browser';+ import { SignInBox } from './src/components/McpServersModal';+ import { SuggestionSignIn } from './src/components/McpSuggestionCard';+ export * from './src/mcpSignInDeadEnd';+ const noop = () => {};+ export const box = (failure, over = {}) =>+ renderToStaticMarkup(React.createElement(SignInBox, { serverName: 'ElevenLabs', isConnecting: false, macApp: false, failure, onConnect: noop, ...over }));+ export const card = (error, over = {}) =>+ renderToStaticMarkup(React.createElement(SuggestionSignIn, { busy: false, disabled: false, error, onSignIn: noop, ...over }));+`);++// renderToStaticMarkup escapes apostrophes; compare against the text a person reads.+const text = (html) => html.replace(/<[^>]+>/g, ' ').replace(/'/g, "'").replace(/"/g, '"').replace(/&/g, '&').replace(/\s+/g, ' ');++const NO_REG = 'This server only lets in apps that were set up with it in advance, so signing in from here can’t work.';+const HTTPS = 'This server’s sign-in only works from localhost or an https address, not from a plain http address like this one.';+const LOCALHOST = 'Open this app in a browser on the computer it runs on, at localhost, and sign in there. Your bots here use that sign-in too.';++test('copy per code and surface is Mira’s, word for word', () => {+ assert.deepEqual(ui.signInDeadEnd('no_client_registration', 'ElevenLabs', 'servers'), {+ code: 'no_client_registration',+ error: NO_REG,+ next: 'If ElevenLabs gives you an API key, edit this server and add the key under Headers instead.',+ });+ assert.deepEqual(ui.signInDeadEnd('no_client_registration', 'ElevenLabs', 'card'), {+ code: 'no_client_registration',+ error: `Couldn’t start the sign-in. ${NO_REG}`,+ next: 'If ElevenLabs gives you an API key, add it under Headers in Settings › Apps & accounts › Advanced › Tool servers.',+ });+ assert.deepEqual(ui.signInDeadEnd('cimd_needs_https', 'ElevenLabs', 'servers'), { code: 'cimd_needs_https', error: HTTPS, next: LOCALHOST });+ assert.deepEqual(ui.signInDeadEnd('cimd_needs_https', 'ElevenLabs', 'card'), {+ code: 'cimd_needs_https',+ error: `Couldn’t start the sign-in. ${HTTPS}`,+ next: LOCALHOST,+ });+ // Any other code, or none, keeps today's error and its button.+ for (const c of [undefined, null, '', 'invalid_redirect', 42]) assert.equal(ui.signInDeadEnd(c, 'X', 'card'), null);+ assert.equal(ui.isSignInDeadEndCode('cimd_needs_https'), true);+ assert.equal(ui.isSignInDeadEndCode('NO_CLIENT_REGISTRATION'), false);+});++test('tool servers screen, no_client_registration: no Retry or Connect, the API-key step shows', () => {+ const html = ui.box({ message: "this server only lets in apps that were set up with it in advance, so signing in from here can't work", code: 'no_client_registration' });+ assert.doesNotMatch(html, /<button/);+ assert.doesNotMatch(text(html), /\bRetry\b|\bConnect\b/);+ assert.match(text(html), /This server asks you to sign in and approve access\./);+ assert.match(html, /<p role="alert" class="flex items-start gap-1.5 text-rose-300">/);+ assert.ok(text(html).includes(NO_REG));+ assert.ok(html.includes('<p class="text-zinc-400">If ElevenLabs gives you an API key, edit this server and add the key under Headers instead.</p>'));+});++test('tool servers screen, cimd_needs_https: no Retry or Connect, the localhost step shows', () => {+ const html = ui.box({ message: 'whatever the server said', code: 'cimd_needs_https' });+ assert.doesNotMatch(html, /<button/);+ assert.ok(text(html).includes(HTTPS));+ assert.doesNotMatch(text(html), /whatever the server said/);+ assert.ok(html.includes(`<p class="text-zinc-400">${LOCALHOST}</p>`));+});++test('tool servers screen keeps Retry for other errors, and Connect with none', () => {+ const failed = ui.box({ message: 'token request failed: 500' });+ assert.match(failed, /<button[^>]*>.*Retry<\/button>/);+ assert.match(text(failed), /token request failed: 500/);+ assert.doesNotMatch(failed, /text-zinc-400/);+ assert.match(ui.box(undefined), /<button[^>]*>.*Connect<\/button>/);+ // A new attempt in progress shows the waiting state, not the old dead end.+ const waiting = ui.box({ message: 'm', code: 'cimd_needs_https' }, { isConnecting: true });+ assert.match(waiting, /Waiting…<\/button>/);+ assert.doesNotMatch(waiting, /localhost/);+});++test('chat card, no_client_registration: "Try signing in again" is gone, the API-key step shows', () => {+ const html = ui.card(ui.signInDeadEnd('no_client_registration', 'ElevenLabs', 'card'));+ assert.doesNotMatch(html, /<button/);+ assert.doesNotMatch(text(html), /Try signing in again|Sign in\b/);+ assert.ok(html.includes(`<p role="alert" class="text-rose-300 break-words">Couldn’t start the sign-in. ${NO_REG.replace("'", ''')}</p>`));+ assert.ok(html.includes('<p class="text-zinc-400 break-words">If ElevenLabs gives you an API key, add it under Headers in Settings › Apps & accounts › Advanced › Tool servers.</p>'));+});++test('chat card, cimd_needs_https: "Try signing in again" is gone, the localhost step shows', () => {+ const html = ui.card(ui.signInDeadEnd('cimd_needs_https', 'ElevenLabs', 'card'));+ assert.doesNotMatch(html, /<button/);+ assert.ok(text(html).includes(`Couldn’t start the sign-in. ${HTTPS}`));+ assert.ok(html.includes(`<p class="text-zinc-400 break-words">${LOCALHOST}</p>`));+});++test('chat card keeps "Try signing in again" for a plain error, and "Sign in" before any try', () => {+ const failed = ui.card("Couldn't start the sign-in: token request failed: 500");+ assert.match(failed, /Try signing in again<\/button>/);+ assert.match(text(failed), /token request failed: 500/);+ assert.match(ui.card(null), />Sign in<\/button>/);+});diff --git a/site/_headers b/site/_headersindex 3b1c4b5c..d285ea29 100644--- a/site/_headers+++ b/site/_headers@@ -29,3 +29,9 @@/install.shContent-Type: text/plain; charset=utf-8Cache-Control: public, max-age=300, must-revalidate++# kwant's OAuth client ID metadata document (MCP sign-in, src/mcp/oauth.rs static_client_document):+# authorization servers fetch it, so JSON, and a change reaches them within minutes+/oauth/client.json+ Content-Type: application/json+ Cache-Control: public, max-age=300diff --git a/site/oauth/client.json b/site/oauth/client.jsonnew file mode 100644index 00000000..4999e241--- /dev/null+++ b/site/oauth/client.json@@ -0,0 +1,23 @@+{+ "client_id": "https://kwant.si/oauth/client.json",+ "client_name": "kwant",+ "client_uri": "https://kwant.si",+ "logo_uri": "https://kwant.si/apple-touch-icon.png",+ "application_type": "native",+ "redirect_uris": [+ "http://127.0.0.1/api/mcp/oauth/callback",+ "http://127.0.0.1:8799/api/mcp/oauth/callback",+ "http://localhost/api/mcp/oauth/callback",+ "http://localhost:8799/api/mcp/oauth/callback",+ "http://[::1]/api/mcp/oauth/callback",+ "http://[::1]:8799/api/mcp/oauth/callback"+ ],+ "grant_types": [+ "authorization_code",+ "refresh_token"+ ],+ "response_types": [+ "code"+ ],+ "token_endpoint_auth_method": "none"+}diff --git a/src/main.rs b/src/main.rsindex 828e53e6..9a69ab77 100644--- a/src/main.rs+++ b/src/main.rs@@ -125,7 +125,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {if let Some(Commands::McpOauthMockServer { host, port, expires_in }) = &cli.command {let listener = tokio::net::TcpListener::bind((host.as_str(), *port)).await?;println!("mock OAuth MCP server: http://{}/mcp", listener.local_addr()?);- kwnt::mcp::oauth_mock::serve(listener, kwnt::mcp::oauth_mock::MockOptions { expires_in: *expires_in }).await?;+ kwnt::mcp::oauth_mock::serve(listener, kwnt::mcp::oauth_mock::MockOptions { expires_in: *expires_in, ..Default::default() }).await?;return Ok(());}diff --git a/src/mcp/oauth.rs b/src/mcp/oauth.rsindex 75209c7c..008f6a02 100644--- a/src/mcp/oauth.rs+++ b/src/mcp/oauth.rs@@ -1,6 +1,7 @@-//! OAuth sign-in for http MCP servers (MCP authorization spec 2025-06-18): protected-resource-//! and authorization-server discovery, dynamic client registration (RFC 7591), the-//! authorization code flow with PKCE S256 and `resource` (RFC 8707), and token refresh.+//! OAuth sign-in for http MCP servers (MCP authorization spec 2025-06-18, plus Client ID+//! Metadata Documents from 2025-11-25): protected-resource and authorization-server discovery,+//! dynamic client registration (RFC 7591) or a client ID metadata document, the authorization+//! code flow with PKCE S256 and `resource` (RFC 8707), and token refresh.//!//! This module talks HTTP but not to the database; `server::mcp_oauth` stores what it returns.@@ -23,12 +24,26 @@ const MAX_PENDING: usize = 64;const HTTP_TIMEOUT: Duration = Duration::from_secs(15);const CLIENT_NAME: &str = "kwnt";+/// The client ID metadata document for kwant on this computer (loopback callbacks), published+/// at kwant.si from `site/oauth/client.json`. [`static_client_document`] is its content.+pub const STATIC_CLIENT_ID: &str = "https://kwant.si/oauth/client.json";+/// Where a self-hosted kwant serves its own client ID metadata document.+pub const CLIENT_DOCUMENT_PATH: &str = "/api/mcp/oauth/client.json";+const CALLBACK_PATH: &str = "/api/mcp/oauth/callback";+const DOCUMENT_CLIENT_NAME: &str = "kwant";+const CLIENT_URI: &str = "https://kwant.si";+const LOGO_URI: &str = "https://kwant.si/apple-touch-icon.png";+#[derive(Error, Debug)]pub enum OAuthError {#[error("{0}")]Discovery(String),- #[error("this server's sign-in does not support automatic client registration")]+ #[error("this server only lets in apps that were set up with it in advance, so signing in from here can't work")]NoRegistration,+ #[error(+ "this server's sign-in only works from localhost or an https address, not from a plain http address like this one"+ )]+ CimdNeedsHttps,#[error("client registration failed: {0}")]Registration(String),#[error("token request failed: {0}")]@@ -37,6 +52,18 @@ pub enum OAuthError {Http(String),}+impl OAuthError {+ /// A stable code for errors that trying again can't fix, so the app can say what to do+ /// instead of offering Retry.+ pub fn code(&self) -> Option<&'static str> {+ match self {+ OAuthError::NoRegistration => Some("no_client_registration"),+ OAuthError::CimdNeedsHttps => Some("cimd_needs_https"),+ _ => None,+ }+ }+}+fn http_err(e: reqwest::Error) -> OAuthError {OAuthError::Http(e.without_url().to_string())}@@ -287,6 +314,22 @@ pub struct AuthServerMetadata {pub code_challenge_methods_supported: Option<Vec<String>>,#[serde(default)]pub token_endpoint_auth_methods_supported: Option<Vec<String>>,+ /// Client ID Metadata Documents (MCP authorization 2025-11-25): the client_id may be an+ /// https URL of a JSON document describing the client.+ #[serde(default, deserialize_with = "lenient_bool")]+ pub client_id_metadata_document_supported: Option<bool>,+}++/// A flag that is not a JSON boolean counts as absent, so one odd field never hides the rest of+/// the metadata.+fn lenient_bool<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<bool>, D::Error> {+ Ok(Value::deserialize(d)?.as_bool())+}++impl AuthServerMetadata {+ pub fn supports_client_documents(&self) -> bool {+ self.client_id_metadata_document_supported == Some(true)+ }}/// Everything discovery found for one MCP server.@@ -425,6 +468,7 @@ pub async fn discover(registration_endpoint: Some(format!("{origin}/register")),code_challenge_methods_supported: None,token_endpoint_auth_methods_supported: None,+ client_id_metadata_document_supported: None,},None => return Err(OAuthError::Discovery("could not find the server's sign-in metadata".into())),};@@ -485,6 +529,97 @@ pub async fn register_client(Ok(ClientRegistration { client_id, client_secret, auth_method })}+fn is_loopback_url(url: &Url) -> bool {+ match url.host() {+ Some(url::Host::Domain(d)) => d.eq_ignore_ascii_case("localhost"),+ Some(url::Host::Ipv4(ip)) => ip.is_loopback(),+ Some(url::Host::Ipv6(ip)) => ip.is_loopback(),+ None => false,+ }+}++fn client_document(client_id: &str, application_type: &str, redirect_uris: Vec<String>) -> Value {+ json!({+ "client_id": client_id,+ "client_name": DOCUMENT_CLIENT_NAME,+ "client_uri": CLIENT_URI,+ "logo_uri": LOGO_URI,+ "application_type": application_type,+ "redirect_uris": redirect_uris,+ "grant_types": ["authorization_code", "refresh_token"],+ "response_types": ["code"],+ "token_endpoint_auth_method": "none",+ })+}++/// The document at [`STATIC_CLIENT_ID`]: kwant on this computer. Loopback callbacks without a+/// port (servers that follow RFC 8252 §7.3 accept any port) and on the default port (servers+/// that match exactly).+pub fn static_client_document() -> Value {+ let port = crate::config::DEFAULT_PORT;+ let mut uris = Vec::new();+ for host in ["127.0.0.1", "localhost", "[::1]"] {+ uris.push(format!("http://{host}{CALLBACK_PATH}"));+ uris.push(format!("http://{host}:{port}{CALLBACK_PATH}"));+ }+ client_document(STATIC_CLIENT_ID, "native", uris)+}++/// The document a self-hosted kwant serves at `{origin}`[`CLIENT_DOCUMENT_PATH`]: its own+/// callback only. `None` unless `origin` is a public https origin.+pub fn self_hosted_client_document(origin: &str) -> Option<Value> {+ let url = Url::parse(origin).ok()?;+ if url.scheme() != "https" || is_loopback_url(&url) || url.host().is_none() || url.path() != "/" {+ return None;+ }+ let origin = url.origin().ascii_serialization();+ Some(client_document(&format!("{origin}{CLIENT_DOCUMENT_PATH}"), "web", vec![callback_url(&origin)]))+}++/// The client_id kwant uses with a server that supports client ID metadata documents, for a+/// sign-in started on `origin` (already checked by [`validate_origin`]).+pub fn client_document_id(origin: &str) -> Result<String, OAuthError> {+ let url = Url::parse(origin).map_err(|_| OAuthError::CimdNeedsHttps)?;+ if is_loopback_url(&url) {+ return Ok(STATIC_CLIENT_ID.to_string());+ }+ self_hosted_client_document(origin)+ .and_then(|d| d["client_id"].as_str().map(str::to_string))+ .ok_or(OAuthError::CimdNeedsHttps)+}++/// Picks how kwant identifies itself to a new authorization server: dynamic registration when+/// the server offers it (falling back to a client ID metadata document if registration is+/// refused), otherwise a client ID metadata document. See autonomy/mcp-oauth-cimd/impl.md.+pub async fn obtain_client(+ http: &reqwest::Client,+ meta: &AuthServerMetadata,+ origin: &str,+ redirect_uri: &str,+) -> Result<ClientRegistration, OAuthError> {+ let documents = meta.supports_client_documents();+ if meta.registration_endpoint.is_some() {+ match register_client(http, meta, redirect_uri).await {+ Err(OAuthError::Registration(e)) if documents => {+ if let Ok(client_id) = client_document_id(origin) {+ tracing::info!(error = %e, "MCP OAuth registration refused; using kwant's client ID metadata document");+ return Ok(document_client(client_id));+ }+ return Err(OAuthError::Registration(e));+ }+ other => return other,+ }+ }+ if documents {+ return client_document_id(origin).map(document_client);+ }+ Err(OAuthError::NoRegistration)+}++fn document_client(client_id: String) -> ClientRegistration {+ ClientRegistration { client_id, client_secret: None, auth_method: "none".into() }+}+/// The URL the user's browser opens to sign in.pub fn authorize_url(discovery: &Discovery,@@ -651,7 +786,7 @@ pub fn validate_origin(origin: &str, hosts: &[&str]) -> Result<String, String> {}pub fn callback_url(origin: &str) -> String {- format!("{origin}/api/mcp/oauth/callback")+ format!("{origin}{CALLBACK_PATH}")}#[cfg(test)]@@ -800,4 +935,93 @@ mod tests {assert!(validate_origin("http://k.dev:8080", &["k.dev"]).is_err());assert_eq!(callback_url("https://k.dev"), "https://k.dev/api/mcp/oauth/callback");}++ /// ElevenLabs' hosted MCP (read Nov 13 2026): no registration endpoint, client documents yes.+ #[test]+ fn reads_client_document_support() {+ let meta: AuthServerMetadata = serde_json::from_value(json!({+ "issuer": "https://api.us.elevenlabs.io",+ "authorization_endpoint": "https://elevenlabs.io/app/oauth/authorize",+ "token_endpoint": "https://api.us.elevenlabs.io/v1/oauth/token",+ "code_challenge_methods_supported": ["S256"],+ "token_endpoint_auth_methods_supported": ["none", "client_secret_post", "private_key_jwt"],+ "client_id_metadata_document_supported": true+ }))+ .unwrap();+ assert!(meta.supports_client_documents());+ assert_eq!(meta.registration_endpoint, None);++ let base = json!({"authorization_endpoint": "https://a.dev/a", "token_endpoint": "https://a.dev/t"});+ let without: AuthServerMetadata = serde_json::from_value(base.clone()).unwrap();+ assert!(!without.supports_client_documents());+ // An odd value never hides the rest of the metadata+ for odd in [json!("true"), json!(1), Value::Null] {+ let mut m = base.clone();+ m["client_id_metadata_document_supported"] = odd;+ let parsed: AuthServerMetadata = serde_json::from_value(m).unwrap();+ assert!(!parsed.supports_client_documents());+ assert_eq!(parsed.token_endpoint, "https://a.dev/t");+ }+ }++ #[test]+ fn picks_the_client_document_for_the_origin() {+ for loopback in ["http://127.0.0.1:8799", "http://127.0.0.1:51234", "http://localhost:8799", "http://[::1]:8799"] {+ assert_eq!(client_document_id(loopback).unwrap(), STATIC_CLIENT_ID, "{loopback}");+ }+ assert_eq!(+ client_document_id("https://kwant.example.com").unwrap(),+ "https://kwant.example.com/api/mcp/oauth/client.json"+ );+ assert_eq!(+ client_document_id("https://kwant.example.com:8443").unwrap(),+ "https://kwant.example.com:8443/api/mcp/oauth/client.json"+ );+ // Plain http on a LAN or public name: no document can name it+ for no in ["http://192.168.1.5:8799", "http://kwant.example.com", "not a url"] {+ assert!(matches!(client_document_id(no), Err(OAuthError::CimdNeedsHttps)), "{no}");+ }+ }++ #[test]+ fn self_hosted_document_names_only_its_own_callback() {+ let doc = self_hosted_client_document("https://kwant.example.com").unwrap();+ assert_eq!(doc["client_id"], "https://kwant.example.com/api/mcp/oauth/client.json");+ assert_eq!(doc["redirect_uris"], json!(["https://kwant.example.com/api/mcp/oauth/callback"]));+ assert_eq!(doc["token_endpoint_auth_method"], "none");+ assert_eq!(doc["grant_types"], json!(["authorization_code", "refresh_token"]));+ assert_eq!(doc["response_types"], json!(["code"]));+ assert_eq!(doc["client_name"], "kwant");+ assert_eq!(doc["application_type"], "web");+ for no in ["http://kwant.example.com", "https://localhost:8443", "https://127.0.0.1", "https://k.dev/x", "nope"] {+ assert!(self_hosted_client_document(no).is_none(), "{no}");+ }+ }++ /// site/oauth/client.json is what kwant.si serves as STATIC_CLIENT_ID; it must say what the+ /// code expects (loopback callbacks, with and without the default port).+ #[test]+ fn static_document_matches_the_site_file() {+ let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("site/oauth/client.json");+ let file: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();+ let doc = static_client_document();+ assert_eq!(file, doc, "update site/oauth/client.json to match static_client_document()");+ assert_eq!(doc["client_id"], STATIC_CLIENT_ID);+ assert_eq!(doc["application_type"], "native");+ let uris: Vec<&str> = doc["redirect_uris"].as_array().unwrap().iter().filter_map(Value::as_str).collect();+ assert!(uris.contains(&"http://127.0.0.1:8799/api/mcp/oauth/callback"));+ assert!(uris.contains(&"http://127.0.0.1/api/mcp/oauth/callback"));+ assert!(uris.iter().all(|u| {+ let url = Url::parse(u).unwrap();+ url.scheme() == "http" && is_loopback_url(&url) && url.path() == CALLBACK_PATH+ }));+ }++ #[test]+ fn dead_end_errors_have_codes() {+ assert_eq!(OAuthError::NoRegistration.code(), Some("no_client_registration"));+ assert_eq!(OAuthError::CimdNeedsHttps.code(), Some("cimd_needs_https"));+ assert_eq!(OAuthError::Registration("x".into()).code(), None);+ assert!(!OAuthError::NoRegistration.to_string().contains("automatic client registration"));+ }}diff --git a/src/mcp/oauth_mock.rs b/src/mcp/oauth_mock.rsindex 07732f37..4ec959df 100644--- a/src/mcp/oauth_mock.rs+++ b/src/mcp/oauth_mock.rs@@ -1,7 +1,7 @@//! A small OAuth-protected streamable-HTTP MCP server, run with the hidden//! `kwnt mcp-oauth-mock-server` subcommand. It implements just enough of the MCP authorization-//! spec (protected-resource and authorization-server metadata, dynamic registration, PKCE S256,-//! `resource`, refresh with rotation) for tests and live checks of kwnt's sign-in without a+//! spec (protected-resource and authorization-server metadata, dynamic registration or client ID+//! metadata documents, PKCE S256, `resource`, refresh with rotation) for tests and live checks of kwnt's sign-in without a//! real provider.//!//! `/authorize` shows an "Allow" link instead of asking for credentials; its target is also sent@@ -25,11 +25,31 @@ use std::sync::{Arc, Mutex};pub struct MockOptions {/// `expires_in` of issued access tokens. Below 60 makes kwnt refresh on every use.pub expires_in: i64,+ /// Offer dynamic client registration (`registration_endpoint`).+ pub registration: bool,+ /// Advertise `client_id_metadata_document_supported`: an https client_id is fetched as a+ /// client ID metadata document and the redirect_uri checked against its `redirect_uris`.+ pub client_documents: bool,+ /// For client documents: a loopback http redirect_uri matches a listed one on any port+ /// (RFC 8252 §7.3). Off: exact match only.+ pub loopback_any_port: bool,+ /// Where to fetch client documents of a given origin instead (tests have no public https):+ /// `https://kwant.si` → `http://127.0.0.1:1234`. The original host goes in `Host`.+ pub document_hosts: HashMap<String, String>,+ /// Refuse every dynamic registration (a server that has the endpoint but says no).+ pub refuse_registration: bool,}impl Default for MockOptions {fn default() -> Self {- Self { expires_in: 3600 }+ Self {+ expires_in: 3600,+ registration: true,+ client_documents: false,+ loopback_any_port: true,+ document_hosts: HashMap::new(),+ refuse_registration: false,+ }}}@@ -55,6 +75,8 @@ pub struct MockState {pub registrations: AtomicU64,pub code_exchanges: AtomicU64,pub refreshes: AtomicU64,+ /// Client documents fetched (each authorize with a document client_id fetches once).+ pub document_fetches: AtomicU64,inner: Mutex<Inner>,}@@ -97,16 +119,82 @@ async fn resource_metadata(State(s): State<Shared>) -> Json<Value> {async fn server_metadata(State(s): State<Shared>) -> Json<Value> {let b = &s.base_url;- Json(json!({+ let mut meta = json!({"issuer": b,"authorization_endpoint": format!("{b}/authorize"),"token_endpoint": format!("{b}/token"),- "registration_endpoint": format!("{b}/register"),"response_types_supported": ["code"],"grant_types_supported": ["authorization_code", "refresh_token"],"code_challenge_methods_supported": ["S256"],"token_endpoint_auth_methods_supported": ["none"],- }))+ });+ if s.options.registration {+ meta["registration_endpoint"] = json!(format!("{b}/register"));+ }+ if s.options.client_documents {+ meta["client_id_metadata_document_supported"] = json!(true);+ }+ Json(meta)+}++/// Whether `redirect_uri` is one of `listed`: exactly, or (with `any_port`) a loopback http URI+/// that differs only in its port.+fn redirect_listed(listed: &[String], redirect_uri: &str, any_port: bool) -> bool {+ if listed.iter().any(|u| u == redirect_uri) {+ return true;+ }+ let Ok(want) = url::Url::parse(redirect_uri) else { return false };+ let loopback = |u: &url::Url| {+ u.scheme() == "http"+ && match u.host() {+ Some(url::Host::Ipv4(ip)) => ip.is_loopback(),+ Some(url::Host::Ipv6(ip)) => ip.is_loopback(),+ Some(url::Host::Domain(d)) => d == "localhost",+ None => false,+ }+ };+ any_port+ && loopback(&want)+ && listed.iter().filter_map(|u| url::Url::parse(u).ok()).any(|mut u| {+ let _ = u.set_port(want.port());+ loopback(&u) && u == want+ })+}++/// Fetches and checks a client ID metadata document; returns its redirect_uris.+async fn fetch_client_document(s: &MockState, client_id: &str) -> Result<Vec<String>, String> {+ let url = url::Url::parse(client_id).map_err(|_| "client_id is not a URL")?;+ if url.scheme() != "https" || url.path() == "/" || url.fragment().is_some() {+ return Err("a document client_id must be an https URL with a path".into());+ }+ let origin = url.origin().ascii_serialization();+ let host = url.host_str().unwrap_or_default().to_string();+ let target = match s.options.document_hosts.get(&origin) {+ Some(local) => format!("{}{}", local.trim_end_matches('/'), &client_id[origin.len()..]),+ None => client_id.to_string(),+ };+ s.document_fetches.fetch_add(1, Ordering::SeqCst);+ let resp = reqwest::Client::new()+ .get(&target)+ .header("host", host)+ .header("accept", "application/json")+ .send()+ .await+ .map_err(|e| format!("could not fetch the client document: {e}"))?;+ if !resp.status().is_success() {+ return Err(format!("client document answered {}", resp.status()));+ }+ let doc: Value = resp.json().await.map_err(|_| "client document is not JSON")?;+ if doc["client_id"].as_str() != Some(client_id) {+ return Err("client document's client_id does not match its URL".into());+ }+ if doc["token_endpoint_auth_method"].as_str().is_some_and(|m| m != "none") {+ return Err("the mock only takes public document clients".into());+ }+ Ok(doc["redirect_uris"]+ .as_array()+ .map(|a| a.iter().filter_map(|u| u.as_str().map(str::to_string)).collect())+ .unwrap_or_default())}async fn register(State(s): State<Shared>, Json(body): Json<Value>) -> Response {@@ -117,6 +205,9 @@ async fn register(State(s): State<Shared>, Json(body): Json<Value>) -> Responseif uris.is_empty() {return oauth_error("invalid_redirect_uri", "redirect_uris is required");}+ if s.options.refuse_registration {+ return oauth_error("invalid_client_metadata", "registration is closed");+ }s.registrations.fetch_add(1, Ordering::SeqCst);let client_id = s.next("client");s.inner.lock().unwrap().clients.insert(client_id.clone(), uris.clone());@@ -131,7 +222,17 @@ fn escape(s: &str) -> String {async fn authorize(State(s): State<Shared>, Query(q): Query<HashMap<String, String>>) -> Response {let get = |k: &str| q.get(k).cloned().unwrap_or_default();let (client_id, redirect_uri, state) = (get("client_id"), get("redirect_uri"), get("state"));- let known = s.inner.lock().unwrap().clients.get(&client_id).is_some_and(|u| u.contains(&redirect_uri));+ let registered = s.inner.lock().unwrap().clients.get(&client_id).cloned();+ let known = match registered {+ Some(uris) => uris.contains(&redirect_uri),+ None if s.options.client_documents && client_id.starts_with("https://") => {+ match fetch_client_document(&s, &client_id).await {+ Ok(uris) => redirect_listed(&uris, &redirect_uri, s.options.loopback_any_port),+ Err(e) => return (StatusCode::BAD_REQUEST, format!("invalid_client: {e}")).into_response(),+ }+ }+ None => false,+ };if !known {return (StatusCode::BAD_REQUEST, "unknown client or redirect_uri").into_response();}@@ -245,6 +346,7 @@ pub fn router(base_url: &str, options: MockOptions) -> (Router, Shared) {registrations: AtomicU64::new(0),code_exchanges: AtomicU64::new(0),refreshes: AtomicU64::new(0),+ document_fetches: AtomicU64::new(0),inner: Mutex::default(),});let app = Router::new()@@ -265,3 +367,19 @@ pub async fn serve(listener: tokio::net::TcpListener, options: MockOptions) -> slet (app, _) = router(&base, options);axum::serve(listener, app).await}++#[cfg(test)]+mod tests {+ use super::redirect_listed;++ #[test]+ fn loopback_redirects_match_on_any_port_only_when_allowed() {+ let listed = vec!["http://127.0.0.1/cb".to_string(), "https://k.dev/cb".to_string()];+ assert!(redirect_listed(&listed, "http://127.0.0.1/cb", false));+ assert!(redirect_listed(&listed, "http://127.0.0.1:51234/cb", true));+ assert!(!redirect_listed(&listed, "http://127.0.0.1:51234/cb", false));+ assert!(!redirect_listed(&listed, "http://127.0.0.1:51234/other", true));+ assert!(!redirect_listed(&listed, "https://k.dev:8443/cb", true), "only loopback http ports vary");+ assert!(!redirect_listed(&listed, "http://evil.test/cb", true));+ }+}diff --git a/src/server/auth.rs b/src/server/auth.rsindex bfe2ee22..60b301c4 100644--- a/src/server/auth.rs+++ b/src/server/auth.rs@@ -312,12 +312,14 @@ fn is_loopback_host(host: &str) -> bool {}/// Paths that never need the token: health, the login endpoints themselves, the OAuth redirect-/// (the provider's page sends the browser there) and the MCP endpoints, which carry their own+/// (the provider's page sends the browser there), the OAuth client document and the MCP endpoints, which carry their own/// per-turn tokens.fn exempt(path: &str) -> bool {path == "/api/health"|| path.starts_with("/api/auth/")|| path == "/api/mcp/oauth/callback"+ // The client ID metadata document authorization servers fetch (public by design)+ || path == crate::mcp::oauth::CLIENT_DOCUMENT_PATH|| path.starts_with("/api/mcp/permission/")|| path.starts_with("/api/mcp/gateway")|| path == "/api/mcp/self"diff --git a/src/server/mcp_oauth.rs b/src/server/mcp_oauth.rsindex 418799b3..45eb75ae 100644--- a/src/server/mcp_oauth.rs+++ b/src/server/mcp_oauth.rs@@ -194,7 +194,13 @@ pub async fn start(let origin = oauth::validate_origin(&body.origin, &host_refs).map_err(|m| err(StatusCode::BAD_REQUEST, m))?;let redirect_uri = oauth::callback_url(&origin);let http = &state.mcp_oauth.http;- let upstream = |e: OAuthError| err(StatusCode::BAD_GATEWAY, e.to_string());+ let upstream = |e: OAuthError| {+ let mut body = json!({ "error": e.to_string() });+ if let Some(code) = e.code() {+ body["code"] = json!(code);+ }+ (StatusCode::BAD_GATEWAY, Json(body))+ };let challenge = oauth::probe_challenge(http, &server_url).await;let discovery = oauth::discover(http, &server_url, challenge.as_ref()).await.map_err(upstream)?;@@ -205,7 +211,7 @@ pub async fn start(auth_method: c.auth_method,},None => {- let reg = oauth::register_client(http, &discovery.metadata, &redirect_uri).await.map_err(upstream)?;+ let reg = oauth::obtain_client(http, &discovery.metadata, &origin, &redirect_uri).await.map_err(upstream)?;state.db.save_mcp_oauth_client(&McpOAuthClient {@@ -228,6 +234,33 @@ pub async fn start(Ok(Json(json!({ "authorize_url": authorize_url })))}+/// `GET /api/mcp/oauth/client.json`: this kwant's client ID metadata document, fetched by+/// authorization servers that use them (no login). Only on a public https name; kwant on+/// loopback uses the document on kwant.si instead.+pub async fn client_document(headers: HeaderMap) -> Response {+ // The public name: a proxy's X-Forwarded-Host (its first value), else Host+ let host = ["x-forwarded-host", header::HOST.as_str()]+ .iter()+ .find_map(|name| headers.get(*name)?.to_str().ok()?.split(',').next().map(|h| h.trim().to_string()))+ .filter(|h| !h.is_empty() && !h.contains(['/', '\\', '@', '?', '#']));+ let document = host.and_then(|h| oauth::self_hosted_client_document(&format!("https://{h}")));+ match document {+ Some(doc) => (+ StatusCode::OK,+ [+ (header::CONTENT_TYPE, "application/json"),+ (header::CACHE_CONTROL, "public, max-age=300"),+ // Built from the request's host, so a shared cache must not hand one name's+ // document to another+ (header::VARY, "Host, X-Forwarded-Host"),+ ],+ doc.to_string(),+ )+ .into_response(),+ None => (StatusCode::NOT_FOUND, Json(json!({ "error": "no client document on this address" }))).into_response(),+ }+}+#[derive(Debug, Deserialize)]pub struct CallbackQuery {pub code: Option<String>,diff --git a/src/server/mod.rs b/src/server/mod.rsindex 505de12b..ccfb262f 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -430,6 +430,7 @@ pub fn create_router(state: AppState) -> Router {.route("/api/mcp/servers/:id/oauth/start", post(mcp_oauth::start)).route("/api/mcp/servers/:id/oauth", delete(mcp_oauth::disconnect)).route("/api/mcp/oauth/callback", get(mcp_oauth::callback))+ .route("/api/mcp/oauth/client.json", get(mcp_oauth::client_document)).route("/api/kwants/:id/mcp-servers", get(mcp_routes::get_kwant_servers).put(mcp_routes::set_kwant_servers)).route("/api/mcp/permission/:token", post(mcp_runtime::permission_endpoint)).route("/api/mcp/gateway", post(mcp_runtime::gateway_endpoint))diff --git a/tests/mcp_oauth_test.rs b/tests/mcp_oauth_test.rsindex 25547a27..a805af5c 100644--- a/tests/mcp_oauth_test.rs+++ b/tests/mcp_oauth_test.rs@@ -103,41 +103,85 @@ async fn create_http_server(e: &Env) -> String {/// Start → follow the mock's Allow link → callback. Returns the callback page.async fn sign_in(e: &Env, id: &str) -> String {- let (status, started) =- call(&e.app, "POST", &format!("/api/mcp/servers/{id}/oauth/start"), Some(json!({"origin": ORIGIN}))).await;- assert_eq!(status, StatusCode::OK, "{started}");- let authorize_url = started["authorize_url"].as_str().unwrap();- let parsed = url::Url::parse(authorize_url).unwrap();- let q: std::collections::HashMap<_, _> = parsed.query_pairs().into_owned().collect();- assert_eq!(q["response_type"], "code");- assert_eq!(q["code_challenge_method"], "S256");- assert_eq!(q["redirect_uri"], format!("{ORIGIN}/api/mcp/oauth/callback"));- assert_eq!(q["resource"], format!("{}/mcp", e.mock.base_url));- assert_eq!(q["scope"], "mcp");- assert!(!q.contains_key("code_verifier"));+ sign_in_at(e, id, ORIGIN, HOST).await+}+/// [`sign_in`] from another address of kwnt (`origin` as the browser sees it, `host` as sent).+async fn sign_in_at(e: &Env, id: &str, origin: &str, host: &str) -> String {+ let authorize_url = start_at(e, id, origin, host).await;let resp = reqwest::Client::builder().redirect(reqwest::redirect::Policy::none()).build().unwrap()- .get(authorize_url)+ .get(&authorize_url).send().await.unwrap();- assert_eq!(resp.status(), 200);+ assert_eq!(resp.status(), 200, "{}", resp.text().await.unwrap_or_default());let redirect = resp.headers()["x-mock-redirect"].to_str().unwrap().to_string();let redirect = url::Url::parse(&redirect).unwrap();- assert_eq!(redirect.origin().ascii_serialization(), ORIGIN);+ assert_eq!(redirect.origin().ascii_serialization(), origin);let path_and_query = format!("{}?{}", redirect.path(), redirect.query().unwrap());- let (status, page) = send(&e.app, "GET", &path_and_query, None, HOST).await;+ let (status, page) = send(&e.app, "GET", &path_and_query, None, host).await;assert_eq!(status, StatusCode::OK);// The state is single use- let (_, again) = send(&e.app, "GET", &path_and_query, None, HOST).await;+ let (_, again) = send(&e.app, "GET", &path_and_query, None, host).await;assert!(again.contains("\"ok\":false") && again.contains("expired or was already used"), "{again}");page}+/// Starts a sign-in and checks the authorize URL; returns it.+async fn start_at(e: &Env, id: &str, origin: &str, host: &str) -> String {+ let (status, text) =+ send(&e.app, "POST", &format!("/api/mcp/servers/{id}/oauth/start"), Some(json!({"origin": origin})), host).await;+ assert_eq!(status, StatusCode::OK, "{text}");+ let started: Value = serde_json::from_str(&text).unwrap();+ let authorize_url = started["authorize_url"].as_str().unwrap().to_string();+ let parsed = url::Url::parse(&authorize_url).unwrap();+ let q: std::collections::HashMap<_, _> = parsed.query_pairs().into_owned().collect();+ assert_eq!(q["response_type"], "code");+ assert_eq!(q["code_challenge_method"], "S256");+ assert_eq!(q["redirect_uri"], format!("{origin}/api/mcp/oauth/callback"));+ assert_eq!(q["resource"], format!("{}/mcp", e.mock.base_url));+ assert_eq!(q["scope"], "mcp");+ assert!(!q.contains_key("code_verifier"));+ authorize_url+}++fn client_id_of(authorize_url: &str) -> String {+ url::Url::parse(authorize_url).unwrap().query_pairs().find(|(k, _)| k == "client_id").unwrap().1.into_owned()+}++/// Serves `router` on a loopback port; returns its base URL.+async fn serve_local(router: Router) -> String {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let base = format!("http://{}", listener.local_addr().unwrap());+ tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });+ base+}++/// Stands in for kwant.si: serves the committed site/oauth/client.json.+async fn serve_kwant_si() -> String {+ let file = std::fs::read_to_string(std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("site/oauth/client.json")).unwrap();+ serve_local(Router::new().route(+ "/oauth/client.json",+ axum::routing::get(move || async move { ([("content-type", "application/json")], file) }),+ ))+ .await+}++/// A mock that has no dynamic registration but takes client ID metadata documents (ElevenLabs).+async fn document_only(loopback_any_port: bool) -> oauth_mock::MockOptions {+ oauth_mock::MockOptions {+ registration: false,+ client_documents: true,+ loopback_any_port,+ document_hosts: [("https://kwant.si".to_string(), serve_kwant_si().await)].into(),+ ..Default::default()+ }+}+async fn stored_token(e: &Env, id: &str) -> Option<kwnt::db::models::McpOAuthToken> {e.state.db.get_mcp_oauth_token(id).await.unwrap()}@@ -219,7 +263,7 @@ async fn sign_in_flow_end_to_end() {#[tokio::test]async fn short_lived_tokens_are_refreshed_before_use() {- let e = env(oauth_mock::MockOptions { expires_in: 30 }).await;+ let e = env(oauth_mock::MockOptions { expires_in: 30, ..Default::default() }).await;let id = create_http_server(&e).await;sign_in(&e, &id).await;let first = stored_token(&e, &id).await.unwrap();@@ -339,3 +383,197 @@ async fn callback_reports_provider_errors_and_bad_state() {.unwrap();assert_eq!(e.app.clone().oneshot(req).await.unwrap().status(), StatusCode::OK);}++/// The Mac app (kwant on 127.0.0.1:8799) signs in to a server without dynamic registration with+/// the document on kwant.si, which the server fetches and checks the redirect against.+#[tokio::test]+async fn client_document_sign_in_on_this_computer() {+ let e = env(document_only(false).await).await;+ let id = create_http_server(&e).await;+ let (origin, host) = ("http://127.0.0.1:8799", "127.0.0.1:8799");++ let page = sign_in_at(&e, &id, origin, host).await;+ assert!(page.contains("\"ok\":true"), "{page}");+ assert_eq!(e.mock.registrations.load(Ordering::SeqCst), 0);+ assert_eq!(e.mock.document_fetches.load(Ordering::SeqCst), 1);+ assert_eq!(e.mock.code_exchanges.load(Ordering::SeqCst), 1);+ let token = stored_token(&e, &id).await.expect("token stored");+ assert_eq!(token.client_id, "https://kwant.si/oauth/client.json");+ assert_eq!(token.auth_method, "none");+ assert_eq!(token.client_secret, None);+ let client = e+ .state+ .db+ .get_mcp_oauth_client(&id, &format!("{origin}/api/mcp/oauth/callback"), &e.mock.base_url)+ .await+ .unwrap()+ .expect("the document client is stored like a registration");+ assert_eq!(client.client_id, "https://kwant.si/oauth/client.json");++ // The token works, and a second sign-in reuses the stored client+ let (_, tested) = call(&e.app, "POST", &format!("/api/mcp/servers/{id}/test"), None).await;+ assert_eq!(tested["ok"], true, "{tested}");+ sign_in_at(&e, &id, origin, host).await;+ assert_eq!(e.mock.registrations.load(Ordering::SeqCst), 0);++ // Refresh sends the document client_id too+ assert!(kwnt::server::mcp_oauth::retry_after_unauthorized(&e.state, &e.state.db.get_mcp_server(&id).await.unwrap().unwrap())+ .await+ .is_some());+ assert_eq!(e.mock.refreshes.load(Ordering::SeqCst), 1);+}++/// kwant on another loopback port: fine where the server accepts any loopback port (RFC 8252),+/// refused by a server that matches redirects exactly (the document lists port 8799 only).+#[tokio::test]+async fn client_document_loopback_ports() {+ let (origin, host) = ("http://127.0.0.1:51234", "127.0.0.1:51234");+ let e = env(document_only(true).await).await;+ let id = create_http_server(&e).await;+ assert!(sign_in_at(&e, &id, origin, host).await.contains("\"ok\":true"));++ let e = env(document_only(false).await).await;+ let id = create_http_server(&e).await;+ let authorize_url = start_at(&e, &id, origin, host).await;+ assert_eq!(client_id_of(&authorize_url), "https://kwant.si/oauth/client.json");+ let resp = reqwest::get(&authorize_url).await.unwrap();+ assert_eq!(resp.status(), 400);+ assert_eq!(resp.text().await.unwrap(), "unknown client or redirect_uri");+}++/// A self-hosted kwant on a public https name serves its own document, without a login, and+/// the server fetches it from there.+#[tokio::test]+async fn client_document_sign_in_self_hosted() {+ // The mock reaches "https://kwnt.example.test" at a real listener running the same app+ let mut e = env(oauth_mock::MockOptions::default()).await;+ let kwnt_base = serve_local(e.app.clone()).await;+ let options = oauth_mock::MockOptions {+ registration: false,+ client_documents: true,+ document_hosts: [(ORIGIN.to_string(), kwnt_base)].into(),+ ..Default::default()+ };+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let base = format!("http://{}", listener.local_addr().unwrap());+ let (mock_app, mock) = oauth_mock::router(&base, options);+ tokio::spawn(async move { axum::serve(listener, mock_app).await.unwrap() });+ e.mock = mock;++ let id = create_http_server(&e).await;+ let authorize_url = start_at(&e, &id, ORIGIN, HOST).await;+ assert_eq!(client_id_of(&authorize_url), format!("{ORIGIN}/api/mcp/oauth/client.json"));+ // Starting only builds the link; the server fetches the document when the link is opened+ assert_eq!(e.mock.document_fetches.load(Ordering::SeqCst), 0);+ assert!(sign_in(&e, &id).await.contains("\"ok\":true"));+ assert_eq!(e.mock.document_fetches.load(Ordering::SeqCst), 1);+ assert_eq!(e.mock.registrations.load(Ordering::SeqCst), 0);+ assert_eq!(stored_token(&e, &id).await.unwrap().client_id, format!("{ORIGIN}/api/mcp/oauth/client.json"));+}++#[tokio::test]+async fn client_document_endpoint() {+ let e = env(oauth_mock::MockOptions::default()).await;+ let get = |host: &'static str, forwarded: Option<&'static str>| {+ let app = e.app.clone();+ async move {+ // No API token: authorization servers fetch it anonymously+ let mut req = Request::builder().uri("/api/mcp/oauth/client.json").header("host", host);+ if let Some(f) = forwarded {+ req = req.header("x-forwarded-host", f);+ }+ let resp = app.oneshot(req.body(Body::empty()).unwrap()).await.unwrap();+ let status = resp.status();+ let header = |name: &str| resp.headers().get(name).map(|v| v.to_str().unwrap().to_string());+ let ctype = header("content-type");+ if status == StatusCode::OK {+ assert_eq!(header("vary").as_deref(), Some("Host, X-Forwarded-Host"));+ }+ let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ (status, ctype, serde_json::from_slice::<Value>(&bytes).unwrap_or(Value::Null))+ }+ };+ let (status, ctype, doc) = get(HOST, None).await;+ assert_eq!(status, StatusCode::OK, "{doc}");+ assert_eq!(ctype.as_deref(), Some("application/json"));+ assert_eq!(doc["client_id"], format!("{ORIGIN}/api/mcp/oauth/client.json"));+ assert_eq!(doc["redirect_uris"], json!([format!("{ORIGIN}/api/mcp/oauth/callback")]));++ // Behind a proxy the public name wins+ let (_, _, doc) = get("127.0.0.1:8799", Some("kwant.example.com, inner.proxy")).await;+ assert_eq!(doc["client_id"], "https://kwant.example.com/api/mcp/oauth/client.json");++ // Loopback uses kwant.si's document; odd hosts get nothing+ for (host, fwd) in [("127.0.0.1:8799", None), ("localhost:8799", None), (HOST, Some("evil.test/x")), (HOST, Some("[email protected]"))] {+ let (status, _, body) = get(host, fwd).await;+ assert_eq!(status, StatusCode::NOT_FOUND, "{host} {fwd:?}: {body}");+ }+}++/// Servers that offer both keep using dynamic registration; if it is refused, kwant falls back+/// to its document.+#[tokio::test]+async fn registration_first_then_client_document() {+ let mut options = document_only(false).await;+ options.registration = true;+ let e = env(options.clone()).await;+ let id = create_http_server(&e).await;+ sign_in_at(&e, &id, "http://127.0.0.1:8799", "127.0.0.1:8799").await;+ assert_eq!(e.mock.registrations.load(Ordering::SeqCst), 1);+ assert_eq!(e.mock.document_fetches.load(Ordering::SeqCst), 0);+ assert_ne!(stored_token(&e, &id).await.unwrap().client_id, "https://kwant.si/oauth/client.json");++ options.refuse_registration = true;+ let e = env(options).await;+ let id = create_http_server(&e).await;+ sign_in_at(&e, &id, "http://127.0.0.1:8799", "127.0.0.1:8799").await;+ assert_eq!(e.mock.document_fetches.load(Ordering::SeqCst), 1);+ assert_eq!(stored_token(&e, &id).await.unwrap().client_id, "https://kwant.si/oauth/client.json");+}++/// Dead ends say so with a code (the card shows what to do, not Retry) and store nothing.+#[tokio::test]+async fn no_way_to_register_is_a_clear_error() {+ let e = env(oauth_mock::MockOptions { registration: false, ..Default::default() }).await;+ let id = create_http_server(&e).await;+ let (status, body) = call(&e.app, "POST", &format!("/api/mcp/servers/{id}/oauth/start"), Some(json!({"origin": ORIGIN}))).await;+ assert_eq!(status, StatusCode::BAD_GATEWAY);+ assert_eq!(body["code"], "no_client_registration", "{body}");+ assert_eq!(+ body["error"],+ "this server only lets in apps that were set up with it in advance, so signing in from here can't work"+ );++ // Documents need https or loopback: kwant on a LAN address can't use them+ let e = env(document_only(false).await).await;+ let id = create_http_server(&e).await;+ let (status, text) = send(+ &e.app,+ "POST",+ &format!("/api/mcp/servers/{id}/oauth/start"),+ Some(json!({"origin": "http://192.168.1.5:8799"})),+ "192.168.1.5:8799",+ )+ .await;+ assert_eq!(status, StatusCode::BAD_GATEWAY);+ let body: Value = serde_json::from_str(&text).unwrap();+ assert_eq!(body["code"], "cimd_needs_https", "{body}");+ assert_eq!(+ body["error"],+ "this server's sign-in only works from localhost or an https address, not from a plain http address like this one"+ );+ assert!(e+ .state+ .db+ .get_mcp_oauth_client(&id, "http://192.168.1.5:8799/api/mcp/oauth/callback", &e.mock.base_url)+ .await+ .unwrap()+ .is_none());++ // Other failures carry no code (Retry may help)+ let e = env(oauth_mock::MockOptions { refuse_registration: true, ..Default::default() }).await;+ let id = create_http_server(&e).await;+ let (status, body) = call(&e.app, "POST", &format!("/api/mcp/servers/{id}/oauth/start"), Some(json!({"origin": ORIGIN}))).await;+ assert_eq!(status, StatusCode::BAD_GATEWAY);+ assert!(body.get("code").is_none(), "{body}");+}