feat(web,core): enterprise-managed authorization (EMA) (#1509) (#1512)

Adds enterprise-managed authorization (EMA): browser-side IdP login + RFC 8693 token-exchange and JWT-bearer resource-token mint, per-server EMA opt-in in Server Settings, IdP config in Client Settings, and IdP clientSecret keychain storage. Includes the v2/main merge and review follow-ups (400 on malformed client config; normalizeIdpIssuer import consolidation).
This commit is contained in:
Bob Dickinson 2026-06-24 19:15:12 -07:00 • committed by GitHub
commit 5de4e911e3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -1,20 +1,37 @@
/**
* Internal OAuth sub-manager for InspectorClient.
* Holds OAuth config, state machine, and guided state; orchestrates normal and guided flows.
* Holds OAuth config, state machine, and guided state; orchestrates quick and guided flows.
* Not part of the public API; InspectorClient delegates to this module.
*/
import { BaseOAuthClientProvider } from "../auth/providers.js";
import type { AuthGuidedState, OAuthStep } from "../auth/types.js";
import { EMPTY_GUIDED_STATE } from "../auth/types.js";
import type { AuthExecution, OAuthFlowState, OAuthStep } from "../auth/types.js";
import { EMPTY_OAUTH_FLOW_STATE } from "../auth/types.js";
import { OAuthStateMachine } from "../auth/state-machine.js";
import type { OAuthTokens } from "@modelcontextprotocol/sdk/shared/auth.js";
import { auth } from "@modelcontextprotocol/sdk/client/auth.js";
import type { OAuthClientInformation } from "@modelcontextprotocol/sdk/shared/auth.js";
import { parseOAuthState } from "../auth/utils.js";
import type { EnterpriseManagedAuthIdpConfig } from "../client/types.js";
import type { ClientConfig } from "../client/types.js";
import { EmaClientNotConfiguredError } from "../auth/ema/clientConfigError.js";
import {
completeEmaIdpAuthorizationAndMint,
refreshEmaResourceTokens,
startEmaIdpAuthorization,
trySilentEmaAuth,
type EmaFlowConfig,
} from "../auth/ema/emaFlow.js";
import {
buildOAuthConnectionState,
isServerOAuthConfigured,
protocolFromOAuthConfig,
} from "../auth/connection-state.js";
import type { OAuthConnectionState } from "../auth/types.js";
import { EmaTransportOAuthProvider } from "../auth/ema/transportProvider.js";
import type {
InspectorClientOptions,
InspectorClientEnvironment,
InspectorClientOptions,
} from "./types.js";
export type OAuthManagerConfig = NonNullable<InspectorClientOptions["oauth"]> &
@ -26,10 +43,13 @@ export interface OAuthManagerParams {
getEventTarget: () => EventTarget;
onBeforeOAuthRedirect?: (sessionId: string) => Promise<void>;
initialConfig: OAuthManagerConfig;
enterpriseManagedAuth?: { idp: EnterpriseManagedAuthIdpConfig };
/** Install-level EMA block (including when disabled) for user-facing errors. */
installEnterpriseManagedAuth?: ClientConfig["enterpriseManagedAuth"];
dispatchOAuthStepChange: (detail: {
step: OAuthStep;
previousStep: OAuthStep;
state: Partial<AuthGuidedState>;
state: Partial<OAuthFlowState>;
}) => void;
dispatchOAuthComplete: (detail: { tokens: OAuthTokens }) => void;
dispatchOAuthAuthorizationRequired: (detail: { url: URL }) => void;
@ -44,7 +64,7 @@ export class OAuthManager {
private params: OAuthManagerParams;
private oauthConfig: OAuthManagerConfig;
private oauthStateMachine: OAuthStateMachine | null = null;
private oauthState: AuthGuidedState | null = null;
private oauthFlowState: OAuthFlowState | null = null;
constructor(params: OAuthManagerParams) {
this.params = params;
@ -56,6 +76,7 @@ export class OAuthManager {
clientSecret?: string;
clientMetadataUrl?: string;
scope?: string;
enterpriseManaged?: boolean;
}): void {
this.oauthConfig = {
...this.oauthConfig,
@ -68,7 +89,7 @@ export class OAuthManager {
}
private async createOAuthProvider(
mode: "normal" | "guided",
execution: AuthExecution,
): Promise<BaseOAuthClientProvider> {
if (
!this.oauthConfig.storage ||
@ -89,7 +110,7 @@ export class OAuthManager {
navigation: this.oauthConfig.navigation,
clientMetadataUrl: this.oauthConfig.clientMetadataUrl,
},
mode,
execution,
);
provider.setEventTarget(this.params.getEventTarget());
@ -111,8 +132,82 @@ export class OAuthManager {
return provider;
}
async authenticate(): Promise<URL> {
const provider = await this.createOAuthProvider("normal");
/** Whether this connection uses enterprise-managed authorization (EMA). */
isEnterpriseManaged(): boolean {
return this.oauthConfig.enterpriseManaged === true;
}
private getEmaFlowConfig(): EmaFlowConfig {
if (!this.oauthConfig.storage || !this.oauthConfig.redirectUrlProvider) {
throw new Error(
"OAuth environment components (storage, redirectUrlProvider) are required.",
);
}
const idp = this.params.enterpriseManagedAuth?.idp;
if (!idp) {
const install = this.params.installEnterpriseManagedAuth;
throw new EmaClientNotConfiguredError(
install?.enabled === false && install.idp
? "disabled"
: "not_configured",
);
}
return {
serverUrl: this.getServerUrl(),
idp,
resourceClientId: this.oauthConfig.clientId,
resourceClientSecret: this.oauthConfig.clientSecret,
scope: this.oauthConfig.scope,
redirectUrl: this.oauthConfig.redirectUrlProvider.getRedirectUrl("quick"),
storage: this.oauthConfig.storage,
fetchFn: this.params.effectiveAuthFetch,
};
}
/** Attempt silent EMA (cached IdP session + legs 2–3). */
async trySilentEnterpriseManagedAuth(): Promise<boolean> {
if (!this.isEnterpriseManaged()) return false;
const result = await trySilentEmaAuth(this.getEmaFlowConfig());
if (result.status === "success") return true;
if (result.status === "mint_failed") throw result.error;
return false;
}
private async authenticateEnterpriseManaged(): Promise<URL | undefined> {
const config = this.getEmaFlowConfig();
const silent = await trySilentEmaAuth(config);
if (silent.status === "success") {
return undefined;
}
if (silent.status === "mint_failed") {
throw silent.error;
}
const authorizationUrl = await startEmaIdpAuthorization(config);
const stateParam = authorizationUrl.searchParams.get("state");
if (stateParam && this.params.onBeforeOAuthRedirect) {
const parsedState = parseOAuthState(stateParam);
if (parsedState?.authId) {
await this.params.onBeforeOAuthRedirect(parsedState.authId);
}
}
this.oauthConfig.navigation!.navigateToAuthorization(authorizationUrl);
this.oauthFlowState = {
...EMPTY_OAUTH_FLOW_STATE,
execution: "quick",
oauthStep: "authorization_code",
authorizationUrl,
};
return authorizationUrl;
}
async authenticate(): Promise<URL | undefined> {
if (this.isEnterpriseManaged()) {
return this.authenticateEnterpriseManaged();
}
const provider = await this.createOAuthProvider("quick");
const serverUrl = this.getServerUrl();
provider.clearCapturedAuthUrl();
@ -143,9 +238,9 @@ export class OAuthManager {
}
const clientInfo = await provider.clientInformation();
this.oauthState = {
...EMPTY_GUIDED_STATE,
authType: "normal",
this.oauthFlowState = {
...EMPTY_OAUTH_FLOW_STATE,
execution: "quick",
oauthStep: "authorization_code",
authorizationUrl: capturedUrl,
oauthClientInfo: clientInfo ?? null,
@ -157,9 +252,9 @@ export class OAuthManager {
const provider = await this.createOAuthProvider("guided");
const serverUrl = this.getServerUrl();
this.oauthState = { ...EMPTY_GUIDED_STATE };
this.oauthFlowState = { ...EMPTY_OAUTH_FLOW_STATE };
if (this.oauthConfig.clientId) {
this.oauthState.oauthClientInfo = {
this.oauthFlowState.oauthClientInfo = {
client_id: this.oauthConfig.clientId,
...(this.oauthConfig.clientSecret && {
client_secret: this.oauthConfig.clientSecret,
@ -170,12 +265,12 @@ export class OAuthManager {
serverUrl,
provider,
(updates) => {
const state = this.oauthState;
const state = this.oauthFlowState;
if (!state) throw new Error("OAuth state not initialized");
const previousStep = state.oauthStep;
this.oauthState = { ...state, ...updates };
this.oauthFlowState = { ...state, ...updates };
if (updates.oauthStep === "complete") {
this.oauthState!.completedAt = Date.now();
this.oauthFlowState!.completedAt = Date.now();
}
const step = updates.oauthStep ?? previousStep;
this.params.dispatchOAuthStepChange({
@ -187,11 +282,11 @@ export class OAuthManager {
this.params.effectiveAuthFetch,
);
await this.oauthStateMachine.executeStep(this.oauthState);
await this.oauthStateMachine.executeStep(this.oauthFlowState);
}
async runGuidedAuth(): Promise<URL | undefined> {
if (!this.oauthStateMachine || !this.oauthState) {
if (!this.oauthStateMachine || !this.oauthFlowState) {
await this.beginGuidedAuth();
}
@ -201,7 +296,7 @@ export class OAuthManager {
}
while (true) {
const state = this.oauthState;
const state = this.oauthFlowState;
if (!state) {
throw new Error("Guided auth failed to initialize state");
}
@ -214,7 +309,7 @@ export class OAuthManager {
await machine.executeStep(state);
}
const state = this.oauthState;
const state = this.oauthFlowState;
if (state?.oauthStep === "complete") {
return undefined;
}
@ -241,39 +336,39 @@ export class OAuthManager {
authorizationCode: string,
completeFlow: boolean = false,
): Promise<void> {
if (!this.oauthStateMachine || !this.oauthState) {
if (!this.oauthStateMachine || !this.oauthFlowState) {
throw new Error(
"Not in guided OAuth flow. Call beginGuidedAuth() first.",
);
}
const currentStep = this.oauthState.oauthStep;
const currentStep = this.oauthFlowState.oauthStep;
if (currentStep !== "authorization_code") {
throw new Error(
`Cannot set authorization code at step ${currentStep}. Expected step: authorization_code`,
);
}
this.oauthState.authorizationCode = authorizationCode;
this.oauthFlowState.authorizationCode = authorizationCode;
if (completeFlow) {
await this.oauthStateMachine.executeStep(this.oauthState);
let step: OAuthStep = this.oauthState.oauthStep;
await this.oauthStateMachine.executeStep(this.oauthFlowState);
let step: OAuthStep = this.oauthFlowState.oauthStep;
while (step !== "complete") {
await this.oauthStateMachine.executeStep(this.oauthState);
step = this.oauthState.oauthStep;
await this.oauthStateMachine.executeStep(this.oauthFlowState);
step = this.oauthFlowState.oauthStep;
}
if (!this.oauthState.oauthTokens) {
if (!this.oauthFlowState.oauthTokens) {
throw new Error("Failed to exchange authorization code for tokens");
}
this.params.dispatchOAuthComplete({
tokens: this.oauthState.oauthTokens,
tokens: this.oauthFlowState.oauthTokens,
});
} else {
this.params.dispatchOAuthStepChange({
step: this.oauthState.oauthStep,
previousStep: this.oauthState.oauthStep,
step: this.oauthFlowState.oauthStep,
previousStep: this.oauthFlowState.oauthStep,
state: { authorizationCode },
});
}
@ -281,10 +376,28 @@ export class OAuthManager {
async completeOAuthFlow(authorizationCode: string): Promise<void> {
try {
if (this.oauthStateMachine && this.oauthState) {
if (this.isEnterpriseManaged()) {
const config = this.getEmaFlowConfig();
const tokens = await completeEmaIdpAuthorizationAndMint(
config,
authorizationCode,
);
const completedAt = Date.now();
this.oauthFlowState = {
...EMPTY_OAUTH_FLOW_STATE,
execution: "quick",
oauthStep: "complete",
oauthTokens: tokens,
completedAt,
};
this.params.dispatchOAuthComplete({ tokens });
return;
}
if (this.oauthStateMachine && this.oauthFlowState) {
await this.setGuidedAuthorizationCode(authorizationCode, true);
} else {
const provider = await this.createOAuthProvider("normal");
const provider = await this.createOAuthProvider("quick");
const serverUrl = this.getServerUrl();
const result = await auth(provider, {
@ -306,17 +419,17 @@ export class OAuthManager {
const clientInfo = await provider.clientInformation();
const completedAt = Date.now();
this.oauthState = this.oauthState
this.oauthFlowState = this.oauthFlowState
? {
...this.oauthState,
...this.oauthFlowState,
oauthStep: "complete",
oauthTokens: tokens,
oauthClientInfo: clientInfo ?? null,
completedAt,
}
: {
...EMPTY_GUIDED_STATE,
authType: "normal",
...EMPTY_OAUTH_FLOW_STATE,
execution: "quick",
oauthStep: "complete",
oauthTokens: tokens,
oauthClientInfo: clientInfo ?? null,
@ -334,11 +447,11 @@ export class OAuthManager {
}
async getOAuthTokens(): Promise<OAuthTokens | undefined> {
if (this.oauthState?.oauthTokens) {
return this.oauthState.oauthTokens;
if (this.oauthFlowState?.oauthTokens) {
return this.oauthFlowState.oauthTokens;
}
const provider = await this.createOAuthProvider("normal");
const provider = await this.createOAuthProvider("quick");
try {
return await provider.tokens();
} catch {
@ -354,7 +467,7 @@ export class OAuthManager {
const serverUrl = this.getServerUrl();
this.oauthConfig.storage.clear(serverUrl);
this.oauthState = null;
this.oauthFlowState = null;
this.oauthStateMachine = null;
}
@ -363,29 +476,63 @@ export class OAuthManager {
return tokens !== undefined;
}
getOAuthState(): AuthGuidedState | undefined {
return this.oauthState ? { ...this.oauthState } : undefined;
getOAuthFlowState(): OAuthFlowState | undefined {
return this.oauthFlowState ? { ...this.oauthFlowState } : undefined;
}
getOAuthStep(): OAuthStep | undefined {
return this.oauthState?.oauthStep;
getOAuthFlowStep(): OAuthStep | undefined {
return this.oauthFlowState?.oauthStep;
}
/**
* Persisted OAuth authorization snapshot for this server (storage + config).
* Returns undefined when OAuth is not configured for the server.
*/
async getOAuthState(): Promise<OAuthConnectionState | undefined> {
if (!isServerOAuthConfigured(this.oauthConfig)) {
return undefined;
}
return buildOAuthConnectionState({
serverUrl: this.getServerUrl(),
protocol: protocolFromOAuthConfig(this.oauthConfig),
configuredScope: this.oauthConfig.scope,
enterpriseManagedAuth: this.params.enterpriseManagedAuth,
storage: this.oauthConfig.storage!,
flowState: this.oauthFlowState ?? undefined,
});
}
async proceedOAuthStep(): Promise<void> {
if (!this.oauthStateMachine || !this.oauthState) {
if (!this.oauthStateMachine || !this.oauthFlowState) {
throw new Error(
"Not in guided OAuth flow. Call authenticateGuided() first.",
);
}
await this.oauthStateMachine.executeStep(this.oauthState);
await this.oauthStateMachine.executeStep(this.oauthFlowState);
}
/**
* Re-run EMA legs 2–3 when resource tokens expire but IdP session remains valid.
*/
async refreshEnterpriseManagedTokens(): Promise<boolean> {
if (!this.isEnterpriseManaged()) return false;
const tokens = await refreshEmaResourceTokens(this.getEmaFlowConfig());
return tokens !== undefined;
}
/**
* Create an OAuth provider for transport auth (connect()).
* Used only when isHttpOAuthConfig() is true.
*/
async createOAuthProviderForTransport(): Promise<BaseOAuthClientProvider> {
return this.createOAuthProvider("normal");
async createOAuthProviderForTransport(): Promise<
BaseOAuthClientProvider | EmaTransportOAuthProvider
> {
const provider = await this.createOAuthProvider("quick");
if (this.isEnterpriseManaged()) {
return new EmaTransportOAuthProvider(provider, this.getEmaFlowConfig());
}
return provider;
}
}