inspector/core/auth/connection-state.ts
cliffhall c299b6e9d8 feat(web): migrate OAuth store to shared /store API (RemoteOAuthStorage parity) (closes #1548)
Migrate the web client's OAuth storage from BrowserOAuthStorage
(sessionStorage) to RemoteOAuthStorage, which POSTs through the backend's
/api/storage/oauth route to ~/.mcp-inspector/storage/oauth.json (mode 0600).
A credential obtained in the browser is now the same blob the TUI/CLI read
on the same host, giving web ⇄ TUI ⇄ CLI parity (Wave 1 of #1579).

Core (shared with TUI/CLI):
- OAuthStorageBase now drives a single async hydration (`ready()`,
  `getHydrationError()`); every post-redirect read (getClientInformation,
  getTokens, getCodeVerifier, getServerMetadata, getIdpSession) and every
  save awaits it so a late hydration merge cannot clobber a fresh write.
  getCodeVerifier/getServerMetadata become async; the store is created with
  skipHydration:true so there is no auto-hydration to race the explicit one.
- store.ts adds normalizeServerUrl so a token saved under
  https://Example.com/mcp is found when the CLI asks for
  https://example.com/mcp/; getServerState falls back to the raw key.
- remote-storage adapter POSTs with keepalive so the write survives the
  OAuth authorize redirect, surfaces swallowed persist failures, and gives
  richer read/write error messages.
- generateOAuthState throws instead of silently degrading to Math.random.
- NodeOAuthStorage honors MCP_INSPECTOR_OAUTH_STATE_PATH for isolated
  fixtures. Provider codeVerifier()/getServerMetadata() + the EMA idpOidc and
  connection-state readers await the now-async storage.

Web:
- environmentFactory + a new shared lib/remoteOAuthStorage accessor
  (memoized per {baseUrl, authToken}) wire RemoteOAuthStorage into the
  connection path, the EMA IdP hook, and the per-server "clear OAuth" action
  so all three share one in-memory view of oauth.json.

Tests: async-hydration + normalizeServerUrl suite, keepalive/error-path
coverage, and the sync→async migration across existing storage/provider/EMA
tests. Web validate + coverage gate + integration suite green; CLI/TUI/
launcher validate green.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01S3fTN8H3R8YV4yUGvZjYnX
2026-07-01 18:39:17 -04:00

176 lines
5.5 KiB
TypeScript

import type {
OAuthClientInformation,
OAuthTokens,
} from "@modelcontextprotocol/sdk/shared/auth.js";
import type { EnterpriseManagedAuthIdpConfig } from "../client/types.js";
import { getEmaIdpLoginState, normalizeIdpIssuer } from "./ema/idpSession.js";
import { idpOAuthStorageKey } from "./ema/storage.js";
import { isJwtExpired } from "./ema/jwt.js";
import type { OAuthStorage } from "./storage.js";
import type { AuthProtocol, OAuthClientRegistrationKind, OAuthConnectionState, OAuthFlowState } from "./types.js";
import { authProtocolFromEnterpriseManaged } from "./types.js";
export interface BuildOAuthConnectionStateParams {
serverUrl: string;
protocol: AuthProtocol;
configuredScope?: string;
enterpriseManagedAuth?: { idp: EnterpriseManagedAuthIdpConfig };
storage: OAuthStorage;
flowState?: OAuthFlowState;
}
function isAccessTokenUsable(tokens: OAuthTokens | undefined): boolean {
if (!tokens?.access_token) return false;
return !isJwtExpired(tokens.access_token);
}
function resolveClient(
preregistered: OAuthClientInformation | undefined,
dynamic: OAuthClientInformation | undefined,
dynamicRegistrationKind: Extract<
OAuthClientRegistrationKind,
"dcr" | "cimd"
> | undefined,
): OAuthConnectionState["client"] | undefined {
if (preregistered?.client_id) {
return {
registrationKind: "static",
clientId: preregistered.client_id,
hasClientSecret:
preregistered.client_secret !== undefined &&
preregistered.client_secret !== "",
};
}
if (!dynamic?.client_id) return undefined;
return {
...(dynamicRegistrationKind && {
registrationKind: dynamicRegistrationKind,
}),
clientId: dynamic.client_id,
hasClientSecret:
dynamic.client_secret !== undefined && dynamic.client_secret !== "",
};
}
function resolveGrantedScope(
tokens: OAuthTokens | undefined,
storageScope: string | undefined,
): string | undefined {
const tokenScope =
typeof tokens?.scope === "string" ? tokens.scope.trim() : undefined;
if (tokenScope) return tokenScope;
const stored =
typeof storageScope === "string" ? storageScope.trim() : undefined;
return stored || undefined;
}
/**
* Assembles persisted OAuth connection state for an HTTP MCP server.
* Reads storage and config only — no network discovery.
*/
export async function buildOAuthConnectionState(
params: BuildOAuthConnectionStateParams,
): Promise<OAuthConnectionState> {
const { serverUrl, storage, flowState } = params;
const protocol = params.protocol;
const storedTokens = await storage.getTokens(serverUrl);
const flowTokens = flowState?.oauthTokens ?? undefined;
const tokens =
flowTokens && isAccessTokenUsable(flowTokens)
? flowTokens
: storedTokens && isAccessTokenUsable(storedTokens)
? storedTokens
: flowTokens ?? storedTokens;
const preregistered = await storage.getClientInformation(serverUrl, true);
const dynamic = await storage.getClientInformation(serverUrl);
const storageScope = storage.getScope(serverUrl);
const serverMetadata = await storage.getServerMetadata(serverUrl);
const authorized = isAccessTokenUsable(tokens);
const grantedScope = resolveGrantedScope(tokens, storageScope);
const registrationKind = storage.getClientRegistrationKind(serverUrl);
const dynamicRegistrationKind =
registrationKind === "dcr" || registrationKind === "cimd"
? registrationKind
: undefined;
const client = resolveClient(
preregistered,
dynamic,
preregistered?.client_id ? undefined : dynamicRegistrationKind,
);
const state: OAuthConnectionState = {
authorized,
protocol,
serverUrl,
...(params.configuredScope?.trim() && {
configuredScope: params.configuredScope.trim(),
}),
...(grantedScope && { grantedScope }),
...(tokens && { tokens }),
...(client && { client }),
...(serverMetadata && { authorizationServerMetadata: serverMetadata }),
};
if (protocol === "ema" && params.enterpriseManagedAuth?.idp) {
const idp = params.enterpriseManagedAuth.idp;
const issuer = normalizeIdpIssuer(idp.issuer);
const idpSession = await getEmaIdpLoginState(storage, issuer);
const idpMetadata = await storage.getServerMetadata(
idpOAuthStorageKey(issuer),
);
state.ema = {
idpIssuer: issuer,
idpClientId: idp.clientId,
idpSession,
...(idpMetadata && { idpMetadata }),
};
state.enterpriseManaged = true;
}
return state;
}
/** Whether server-level OAuth options are configured on the client. */
export function isServerOAuthConfigured(config: {
clientId?: string;
clientSecret?: string;
scope?: string;
enterpriseManaged?: boolean;
clientMetadataUrl?: string;
}): boolean {
return (
config.enterpriseManaged === true ||
!!config.clientId?.trim() ||
!!config.clientSecret?.trim() ||
!!config.scope?.trim() ||
!!config.clientMetadataUrl?.trim()
);
}
/** True when persisted OAuth storage has tokens or client registration for a server. */
export async function hasPersistedOAuthServerState(
storage: OAuthStorage,
serverUrl: string,
): Promise<boolean> {
const [tokens, preregistered, dynamic] = await Promise.all([
storage.getTokens(serverUrl),
storage.getClientInformation(serverUrl, true),
storage.getClientInformation(serverUrl),
]);
return !!(
tokens?.access_token ||
preregistered?.client_id ||
dynamic?.client_id
);
}
export function protocolFromOAuthConfig(config: {
enterpriseManaged?: boolean;
}): AuthProtocol {
return authProtocolFromEnterpriseManaged(config.enterpriseManaged);
}