Merge remote-tracking branch 'origin/v2/main' into 1579-wave-1

# Conflicts:
#	clients/cli/package-lock.json
#	clients/cli/package.json
#	clients/web/src/App.tsx
#	clients/web/src/lib/environmentFactory.test.ts
#	clients/web/src/lib/environmentFactory.ts
#	clients/web/src/lib/remoteOAuthStorage.test.ts
#	clients/web/src/lib/remoteOAuthStorage.ts
#	clients/web/src/test/core/auth/connection-state.test.ts
#	clients/web/src/test/core/auth/providers.test.ts
#	clients/web/src/test/core/auth/storage-browser.test.ts
#	clients/web/src/test/core/auth/storage-remote.test.ts
#	clients/web/src/test/core/mcp/oauthManager.test.ts
#	clients/web/src/test/integration/auth/node/storage.test.ts
#	clients/web/src/test/integration/storage/adapters.test.ts
#	clients/web/src/utils/clearServerOAuthState.test.ts
#	clients/web/src/utils/clearServerOAuthState.ts
#	core/auth/connection-state.ts
#	core/auth/oauth-storage.ts
#	core/auth/providers.ts
#	core/auth/storage.ts
#	core/auth/store.ts
#	core/storage/adapters/remote-storage.ts
This commit is contained in:
cliffhall 2026-07-09 09:41:08 -04:00
commit 32a3610737
13 changed files with 5046 additions and 3271 deletions

View file

@ -1,16 +1,14 @@
import { createJSONStorage } from "zustand/middleware";
import { OAuthStorageBase } from "../oauth-storage.js";
import { createOAuthStore } from "../store.js";
import { OAuthMemoryStore } from "../store.js";
import { createSessionOAuthPersistBackend } from "../oauth-persist.js";
/**
* Browser storage implementation using Zustand with sessionStorage.
* Browser storage implementation using sessionStorage.
* For web client (can be used by InspectorClient in browser).
*/
export class BrowserOAuthStorage extends OAuthStorageBase {
constructor() {
// Use Zustand's built-in sessionStorage adapter
// The `name` option in persist() ("mcp-inspector-oauth") becomes the sessionStorage key
super(createOAuthStore(createJSONStorage(() => sessionStorage)));
super(new OAuthMemoryStore(), createSessionOAuthPersistBackend());
}
}

View file

@ -88,13 +88,13 @@ export async function buildOAuthConnectionState(
const preregistered = await storage.getClientInformation(serverUrl, true);
const dynamic = await storage.getClientInformation(serverUrl);
const storageScope = storage.getScope(serverUrl);
const storageScope = await storage.getScope(serverUrl);
const serverMetadata = await storage.getServerMetadata(serverUrl);
const authorized = isAccessTokenUsable(tokens);
const grantedScope = resolveGrantedScope(tokens, storageScope);
const registrationKind = storage.getClientRegistrationKind(serverUrl);
const registrationKind = await storage.getClientRegistrationKind(serverUrl);
const dynamicRegistrationKind =
registrationKind === "dcr" || registrationKind === "cimd"
? registrationKind
@ -123,9 +123,7 @@ export async function buildOAuthConnectionState(
const idp = params.enterpriseManagedAuth.idp;
const issuer = normalizeIdpIssuer(idp.issuer);
const idpSession = await getEmaIdpLoginState(storage, issuer);
const idpMetadata = await storage.getServerMetadata(
idpOAuthStorageKey(issuer),
);
const idpMetadata = await storage.getServerMetadata(idpOAuthStorageKey(issuer));
state.ema = {
idpIssuer: issuer,
idpClientId: idp.clientId,

View file

@ -63,7 +63,7 @@ export async function startIdpOidcAuthorization(params: {
fetchFn?: typeof fetch;
}): Promise<{ authorizationUrl: URL }> {
const issuer = normalizeIdpIssuer(params.idp.issuer);
const metadata = await discoverIdpMetadata(issuer, params.fetchFn);
const metadata = await resolveIdpMetadata(issuer, params.storage, params.fetchFn);
const clientInformation = idpClientInformation(params.idp);
const storageKey = idpOAuthStorageKey(issuer);
const state = generateOAuthState();
@ -131,7 +131,7 @@ export async function completeIdpOidcAuthorization(params: {
throw new Error("IdP token response did not include an ID Token");
}
params.storage.clearCodeVerifier(storageKey);
await params.storage.clearCodeVerifier(storageKey);
const idTokenExpiresAt = jwtExpiresAtMs(idToken);
await params.storage.saveIdpSession(issuer, {
idToken,

View file

@ -21,10 +21,13 @@ export async function getEmaIdpLoginState(
return "expired";
}
export function clearEmaIdpSession(storage: OAuthStorage, issuer: string): void {
export async function clearEmaIdpSession(
storage: OAuthStorage,
issuer: string,
): Promise<void> {
const normalized = normalizeIdpIssuer(issuer);
if (!normalized) return;
storage.clearIdpSession(normalized);
storage.clear(idpOAuthStorageKey(normalized));
storage.clearEnterpriseManagedResourceServers();
await storage.clearIdpSession(normalized);
await storage.clear(idpOAuthStorageKey(normalized));
await storage.clearEnterpriseManagedResourceServers();
}

View file

@ -1,7 +1,5 @@
export {
NodeOAuthStorage,
getOAuthStore,
getStateFilePath,
clearAllOAuthClientState,
} from "./storage-node.js";
export {

View file

@ -0,0 +1,42 @@
/**
* Node-only file backend for OAuth persistence. Kept out of the isomorphic
* `core/auth/oauth-persist.ts` because it imports `store-io.js` (which pulls
* `node:fs`/`atomically`); the browser must never load that. Node consumers
* (e.g. `NodeOAuthStorage`) import the file backend from here, while the
* shared blob (de)serialization and browser/remote backends stay isomorphic.
*/
import {
readStoreFile,
writeStoreFile,
deleteStoreFile,
} from "../../storage/store-io.js";
import {
parseOAuthPersistBlob,
serializeOAuthPersistBlob,
type OAuthPersistBackend,
} from "../oauth-persist.js";
export interface FileOAuthPersistBackendOptions {
filePath: string;
}
export function createFileOAuthPersistBackend(
options: FileOAuthPersistBackendOptions,
): OAuthPersistBackend {
return {
async read() {
const raw = await readStoreFile(options.filePath);
return parseOAuthPersistBlob(raw);
},
async write(snapshot) {
await writeStoreFile(
options.filePath,
serializeOAuthPersistBlob(snapshot),
);
},
async remove() {
await deleteStoreFile(options.filePath);
},
};
}

View file

@ -1,6 +1,6 @@
import { OAuthStorageBase } from "../oauth-storage.js";
import { createOAuthStore } from "../store.js";
import { createFileStorageAdapter } from "../../storage/adapters/file-storage.js";
import { OAuthMemoryStore } from "../store.js";
import { createFileOAuthPersistBackend } from "./oauth-persist-file.js";
import {
getDefaultStorageDir,
getStoreFilePath,
@ -23,22 +23,27 @@ export function getStateFilePath(customPath?: string): string {
);
}
const storeCache = new Map<string, ReturnType<typeof createOAuthStore>>();
const memoryCache = new Map<string, OAuthMemoryStore>();
const storageCache = new Map<string, NodeOAuthStorage>();
function getSharedMemory(stateFilePath?: string): OAuthMemoryStore {
const key = getStateFilePath(stateFilePath);
let memory = memoryCache.get(key);
if (!memory) {
memory = new OAuthMemoryStore();
memoryCache.set(key, memory);
}
return memory;
}
/**
* Get or create the OAuth store instance for the given path.
* @param stateFilePath - Optional custom path to state file. Default: ~/.mcp-inspector/storage/oauth.json
* Drop cached in-memory and {@link NodeOAuthStorage} instances for a path.
* @internal Test isolation only.
*/
export function getOAuthStore(stateFilePath?: string) {
export function resetNodeOAuthStorageCache(stateFilePath?: string): void {
const key = getStateFilePath(stateFilePath);
let store = storeCache.get(key);
if (!store) {
const filePath = getStateFilePath(stateFilePath);
const storage = createFileStorageAdapter({ filePath });
store = createOAuthStore(storage);
storeCache.set(key, store);
}
return store;
memoryCache.delete(key);
storageCache.delete(key);
}
/**
@ -46,24 +51,40 @@ export function getOAuthStore(stateFilePath?: string) {
* Useful for test isolation in E2E OAuth tests.
* Use a custom-path store and clear per serverUrl if you need to clear non-default storage.
*/
export function clearAllOAuthClientState(): void {
const store = getOAuthStore();
const state = store.getState();
const urls = Object.keys(state.servers ?? {});
export async function clearAllOAuthClientState(): Promise<void> {
const storage = getNodeOAuthStorage();
const filePath = getStateFilePath();
const snapshot = await createFileOAuthPersistBackend({ filePath }).read();
const urls = Object.keys(snapshot?.servers ?? {});
for (const url of urls) {
state.clearServerState(url);
await storage.clear(url);
}
}
/**
* Node.js storage implementation using Zustand with file-based persistence.
* Node.js storage implementation with file-based persistence.
* For InspectorClient, CLI, and TUI.
*/
export class NodeOAuthStorage extends OAuthStorageBase {
/**
* @param storagePath - Optional path to state file. Default: ~/.mcp-inspector/oauth/state.json
* @param storagePath - Optional path to state file. Default: ~/.mcp-inspector/storage/oauth.json
*/
constructor(storagePath?: string) {
super(getOAuthStore(storagePath));
const filePath = getStateFilePath(storagePath);
super(
getSharedMemory(storagePath),
createFileOAuthPersistBackend({ filePath }),
);
}
}
/** Cached NodeOAuthStorage instances keyed by resolved file path. */
function getNodeOAuthStorage(storagePath?: string): NodeOAuthStorage {
const key = getStateFilePath(storagePath);
let storage = storageCache.get(key);
if (!storage) {
storage = new NodeOAuthStorage(storagePath);
storageCache.set(key, storage);
}
return storage;
}

173
core/auth/oauth-persist.ts Normal file
View file

@ -0,0 +1,173 @@
/**
* OAuth persistence format and isomorphic backends (remote HTTP,
* sessionStorage). Writes plain JSON `{ servers, idpSessions }`. On read,
* accepts legacy persist envelopes `{ state: { servers, idpSessions },
* version }` and promotes the inner payload.
*
* This module must stay browser-safe: it imports only the Node-free
* `store-serialize` helpers, never `store-io` (which pulls `node:fs`). The
* Node-only file backend lives in `./node/oauth-persist-file.ts`.
*/
import { serializeStore, parseStore } from "../storage/store-serialize.js";
import type { IdpSessionState } from "./storage.js";
import type { ServerOAuthState } from "./store.js";
export const OAUTH_PERSIST_STORAGE_KEY = "mcp-inspector-oauth";
export interface OAuthPersistSnapshot {
servers: Record<string, ServerOAuthState>;
idpSessions: Record<string, IdpSessionState>;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function snapshotFromPayload(
payload: Partial<OAuthPersistSnapshot>,
): OAuthPersistSnapshot {
return {
servers: payload.servers ?? {},
idpSessions: payload.idpSessions ?? {},
};
}
/**
* Parse OAuth store JSON from disk, remote API, or sessionStorage.
* Accepts plain `{ servers, idpSessions }` or legacy `{ state, version }`.
* `raw` may be a JSON string or an already-parsed object (e.g. from `res.json()`).
*/
export function parseOAuthPersistBlob(
raw: string | null | unknown,
): OAuthPersistSnapshot | null {
if (raw === null || raw === undefined) {
return null;
}
const parsed = typeof raw === "string" ? (raw ? parseStore(raw) : null) : raw;
if (!isRecord(parsed)) {
return null;
}
if (isRecord(parsed.state) && "version" in parsed) {
return snapshotFromPayload(parsed.state as Partial<OAuthPersistSnapshot>);
}
if ("servers" in parsed || "idpSessions" in parsed) {
return snapshotFromPayload(parsed as Partial<OAuthPersistSnapshot>);
}
return null;
}
export function serializeOAuthPersistBlob(
snapshot: OAuthPersistSnapshot,
): string {
return serializeStore(snapshot);
}
export interface OAuthPersistBackend {
read(): Promise<OAuthPersistSnapshot | null>;
write(snapshot: OAuthPersistSnapshot): Promise<void>;
remove?(): Promise<void>;
}
export interface RemoteOAuthPersistBackendOptions {
baseUrl: string;
storeId: string;
authToken?: string;
fetchFn?: typeof fetch;
}
export function createRemoteOAuthPersistBackend(
options: RemoteOAuthPersistBackendOptions,
): OAuthPersistBackend {
const baseUrl = options.baseUrl.replace(/\/$/, "");
const fetchFn = options.fetchFn ?? globalThis.fetch;
return {
async read() {
const headers: Record<string, string> = {};
if (options.authToken) {
headers["x-mcp-remote-auth"] = `Bearer ${options.authToken}`;
}
const res = await fetchFn(`${baseUrl}/api/storage/${options.storeId}`, {
method: "GET",
headers,
});
if (!res.ok) {
if (res.status === 404) {
return null;
}
throw new Error(`Failed to read store: ${res.status}`);
}
// parseOAuthPersistBlob already returns null for {} (the server's
// missing-file response, server.ts) and for a literal null body, so no
// empty-object guard is needed — and Object.keys(null) would throw.
const store = await res.json();
return parseOAuthPersistBlob(store);
},
async write(snapshot) {
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
if (options.authToken) {
headers["x-mcp-remote-auth"] = `Bearer ${options.authToken}`;
}
const res = await fetchFn(`${baseUrl}/api/storage/${options.storeId}`, {
method: "POST",
headers,
body: serializeOAuthPersistBlob(snapshot),
});
if (!res.ok) {
throw new Error(`Failed to write store: ${res.status}`);
}
},
async remove() {
const headers: Record<string, string> = {};
if (options.authToken) {
headers["x-mcp-remote-auth"] = `Bearer ${options.authToken}`;
}
const res = await fetchFn(`${baseUrl}/api/storage/${options.storeId}`, {
method: "DELETE",
headers,
});
if (!res.ok && res.status !== 404) {
throw new Error(`Failed to delete store: ${res.status}`);
}
},
};
}
export interface SessionOAuthPersistBackendOptions {
storageKey?: string;
getStorage?: () => Storage;
}
export function createSessionOAuthPersistBackend(
options: SessionOAuthPersistBackendOptions = {},
): OAuthPersistBackend {
const storageKey = options.storageKey ?? OAUTH_PERSIST_STORAGE_KEY;
const getStorage = options.getStorage ?? (() => sessionStorage);
return {
async read() {
return parseOAuthPersistBlob(getStorage().getItem(storageKey));
},
async write(snapshot) {
getStorage().setItem(storageKey, serializeOAuthPersistBlob(snapshot));
},
async remove() {
getStorage().removeItem(storageKey);
},
};
}

View file

@ -8,7 +8,8 @@ import {
OAuthTokensSchema,
} from "@modelcontextprotocol/sdk/shared/auth.js";
import type { OAuthStorage } from "./storage.js";
import { type createOAuthStore, type ServerOAuthState } from "./store.js";
import { type OAuthMemoryStore, type ServerOAuthState } from "./store.js";
import type { OAuthPersistBackend } from "./oauth-persist.js";
import type {
IdpSessionState,
OAuthClientRegistrationKind,
@ -17,119 +18,60 @@ import type {
} from "./storage.js";
/**
* Concrete OAuthStorage implementation parameterized on a Zustand store.
* The store carries the storage adapter (sessionStorage, file, remote HTTP, …),
* so the same body works for browser, Node, and remote environments.
*
* With an async storage adapter (file, remote HTTP) the store is empty until
* hydration completes. Every read used on the post-OAuth-redirect callback path
* (`getCodeVerifier`, `getServerMetadata`, `getClientInformation`, `getTokens`)
* — and every save — therefore awaits {@link ready} first; saves wait so a
* late hydration merge cannot clobber a value written before it landed. The
* underlying store is created with `skipHydration: true`
* ({@link createOAuthStore}), so the constructor's `rehydrate()` is the single
* hydration and there is no auto-hydration to race it. With a synchronous
* adapter (sessionStorage) hydration resolves on the next microtask and the
* behaviour is effectively unchanged.
* Concrete OAuthStorage implementation backed by in-memory state and an explicit
* persist backend (file, remote HTTP, sessionStorage, …).
*/
export class OAuthStorageBase implements OAuthStorage {
private readonly store: ReturnType<typeof createOAuthStore>;
private readonly hydrated: Promise<void>;
private hydrationError?: Error;
private loaded = false;
private loadPromise: Promise<void> | undefined;
/** Serializes persist writes so concurrent mutators cannot reorder POSTs. */
private persistQueue: Promise<void> = Promise.resolve();
private readonly memory: OAuthMemoryStore;
private readonly backend: OAuthPersistBackend;
constructor(store: ReturnType<typeof createOAuthStore>) {
this.store = store;
// The store is created with `skipHydration: true` so this is the SOLE
// hydration. Driving it explicitly (rather than relying on persist's
// auto-hydration + onFinishHydration) lets us catch a rejecting adapter —
// onFinishHydration only fires on success, so a throwing getItem would
// otherwise leave `hydrated` pending forever and hang every getter.
// A failed hydration resolves to "empty store", which is the correct
// fallback (reads return undefined; writes proceed) — but the failure is
// recorded so callers can distinguish "no token stored" from "could not
// read the store" (e.g. corrupt file, EACCES, backend 500).
const recordFailure = (err: unknown) => {
this.hydrationError =
err instanceof Error
? err
: new Error(
typeof err === "string"
? err
: "OAuth storage hydration failed (adapter getItem threw or returned invalid data)",
);
console.warn(
"[OAuthStorage] hydration failed; continuing with empty state:",
this.hydrationError,
);
};
this.hydrated = this.store.persist.hasHydrated()
? Promise.resolve()
: Promise.resolve(this.store.persist.rehydrate()).then(
() => {
// Zustand swallows getItem errors internally (routing them to
// onRehydrateStorage) and resolves rehydrate() regardless;
// hasHydrated() only flips true on success, so use it to detect a
// silently-failed hydration. The underlying error is lost in this
// path — record a generic one so getHydrationError() is non-null.
if (!this.store.persist.hasHydrated()) recordFailure(undefined);
},
(err: unknown) => recordFailure(err),
);
constructor(memory: OAuthMemoryStore, backend: OAuthPersistBackend) {
this.memory = memory;
this.backend = backend;
}
/**
* If hydration failed (adapter threw, file unreadable/corrupt, backend
* non-2xx), the captured error. Undefined when hydration succeeded or has
* not yet completed — call after `await ready()`. Lets callers report
* "oauth.json is unreadable" instead of a misleading "no token stored".
*/
getHydrationError(): Error | undefined {
return this.hydrationError;
}
/**
* Resolves once the underlying persist adapter has hydrated the store.
* Callers that need to read state outside the typed getters can await this
* directly (e.g. before reading the store via `getState()` for diagnostics).
*/
ready(): Promise<void> {
return this.hydrated;
}
/**
* Run a `clear*` mutation against a hydrated store: synchronously if
* hydration has already landed, otherwise deferred until it does.
*
* `clear*` are declared synchronous in {@link OAuthStorage} (some feed sync
* SDK getters), so unlike the `save*` family they cannot `await this.hydrated`
* up front. But a clear applied to the still-empty pre-hydration store is
* doubly wrong: (a) the pending `rehydrate()` would merge the persisted
* (un-cleared) blob back over it, resurrecting the credential; and worse,
* (b) applying it triggers a persist write of the near-empty store, which for
* a whole-blob adapter (file / remote HTTP) can clobber the on-disk blob —
* every other server's tokens included — before hydration ever reads it.
* Deferring the mutation until after hydration avoids both: it merges onto
* the real persisted state. The common case (hydration already settled) stays
* synchronous and immediately observable. A failed hydration still resolves
* {@link hydrated} (see constructor), so a deferred clear runs harmlessly
* against the empty store. The effect of a pre-hydration clear is therefore
* asynchronous, which is safe: the only callers are fire-and-forget
* invalidations that never synchronously read the value straight back.
*/
private clearAfterHydration(mutate: () => void): void {
if (this.store.persist.hasHydrated()) {
mutate();
} else {
void this.hydrated.then(mutate);
load(): Promise<void> {
if (!this.loadPromise) {
this.loadPromise = this.doLoad();
}
return this.loadPromise;
}
private async doLoad(): Promise<void> {
if (this.loaded) {
return;
}
const snapshot = await this.backend.read();
if (snapshot) {
this.memory.replace(snapshot);
}
this.loaded = true;
}
private async ensureLoaded(): Promise<void> {
await this.load();
}
private async persist(): Promise<void> {
const snapshot = this.memory.snapshot();
const prior = this.persistQueue;
const tracked = prior
.catch(() => {})
.then(() => this.backend.write(snapshot));
this.persistQueue = tracked;
await tracked;
}
async getClientInformation(
serverUrl: string,
isPreregistered?: boolean,
): Promise<OAuthClientInformation | undefined> {
await this.hydrated;
const state = this.store.getState().getServerState(serverUrl);
await this.ensureLoaded();
const state = this.memory.getState().getServerState(serverUrl);
const clientInfo = isPreregistered
? state.preregisteredClientInformation
: state.clientInformation;
@ -141,20 +83,11 @@ export class OAuthStorageBase implements OAuthStorage {
return await OAuthClientInformationSchema.parseAsync(clientInfo);
}
/**
* Intentionally synchronous — same invariant as {@link getScope}: safe
* without awaiting hydration only because a preceding awaited read has
* already flushed it. Its sole caller, `buildOAuthConnectionState`
* (`connection-state.ts`), reads this right after awaiting
* `getClientInformation`/`getServerMetadata`, so on the post-redirect
* callback path (where the in-memory store is reset) hydration has landed
* by the time this runs. A future refactor reading it without a preceding
* awaited storage read would get a pre-hydration `undefined`.
*/
getClientRegistrationKind(
async getClientRegistrationKind(
serverUrl: string,
): OAuthClientRegistrationKind | undefined {
return this.store.getState().getServerState(serverUrl)
): Promise<OAuthClientRegistrationKind | undefined> {
await this.ensureLoaded();
return this.memory.getState().getServerState(serverUrl)
.clientRegistrationKind;
}
@ -163,40 +96,47 @@ export class OAuthStorageBase implements OAuthStorage {
clientInformation: OAuthClientInformation,
options: SaveClientInformationOptions,
): Promise<void> {
await this.hydrated;
this.store.getState().setServerState(serverUrl, {
await this.ensureLoaded();
this.memory.getState().setServerState(serverUrl, {
clientInformation,
clientRegistrationKind: options.registrationKind,
});
await this.persist();
}
async savePreregisteredClientInformation(
serverUrl: string,
clientInformation: OAuthClientInformation,
): Promise<void> {
await this.hydrated;
this.store.getState().setServerState(serverUrl, {
await this.ensureLoaded();
this.memory.getState().setServerState(serverUrl, {
preregisteredClientInformation: clientInformation,
clientRegistrationKind: "static",
});
await this.persist();
}
clearClientInformation(serverUrl: string, isPreregistered?: boolean): void {
this.clearAfterHydration(() => {
const updates: Partial<ServerOAuthState> = {};
if (isPreregistered) {
updates.preregisteredClientInformation = undefined;
} else {
updates.clientInformation = undefined;
updates.clientRegistrationKind = undefined;
}
this.store.getState().setServerState(serverUrl, updates);
});
async clearClientInformation(
serverUrl: string,
isPreregistered?: boolean,
): Promise<void> {
await this.ensureLoaded();
const updates: Partial<ServerOAuthState> = {};
if (isPreregistered) {
updates.preregisteredClientInformation = undefined;
} else {
updates.clientInformation = undefined;
updates.clientRegistrationKind = undefined;
}
this.memory.getState().setServerState(serverUrl, updates);
await this.persist();
}
async getTokens(serverUrl: string): Promise<OAuthTokens | undefined> {
await this.hydrated;
const state = this.store.getState().getServerState(serverUrl);
await this.ensureLoaded();
const state = this.memory.getState().getServerState(serverUrl);
if (!state.tokens) {
return undefined;
}
@ -209,22 +149,23 @@ export class OAuthStorageBase implements OAuthStorage {
tokens: OAuthTokens,
options?: SaveTokensOptions,
): Promise<void> {
await this.hydrated;
this.store.getState().setServerState(serverUrl, {
await this.ensureLoaded();
this.memory.getState().setServerState(serverUrl, {
tokens,
...(options?.enterpriseManaged === true && { enterpriseManaged: true }),
});
await this.persist();
}
clearTokens(serverUrl: string): void {
this.clearAfterHydration(() =>
this.store.getState().setServerState(serverUrl, { tokens: undefined }),
);
async clearTokens(serverUrl: string): Promise<void> {
await this.ensureLoaded();
this.memory.getState().setServerState(serverUrl, { tokens: undefined });
await this.persist();
}
async getCodeVerifier(serverUrl: string): Promise<string | undefined> {
await this.hydrated;
const state = this.store.getState().getServerState(serverUrl);
await this.ensureLoaded();
const state = this.memory.getState().getServerState(serverUrl);
return state.codeVerifier;
}
@ -232,53 +173,38 @@ export class OAuthStorageBase implements OAuthStorage {
serverUrl: string,
codeVerifier: string,
): Promise<void> {
await this.hydrated;
this.store.getState().setServerState(serverUrl, { codeVerifier });
await this.ensureLoaded();
this.memory.getState().setServerState(serverUrl, { codeVerifier });
await this.persist();
}
clearCodeVerifier(serverUrl: string): void {
this.clearAfterHydration(() =>
this.store
.getState()
.setServerState(serverUrl, { codeVerifier: undefined }),
);
async clearCodeVerifier(serverUrl: string): Promise<void> {
await this.ensureLoaded();
this.memory.getState().setServerState(serverUrl, { codeVerifier: undefined });
await this.persist();
}
/**
* Intentionally synchronous. The only caller is
* {@link BaseOAuthClientProvider.scope}, a sync getter the SDK requires
* (it feeds the sync `clientMetadata` getter). It is safe without awaiting
* hydration because of an ordering invariant the callers uphold: some
* awaited read always precedes it, flushing hydration first.
* - Pre-redirect half of the flow: `saveScope` (which awaits hydration)
* writes the value in the same session, so the in-memory store has it.
* - Post-redirect callback path: the in-memory store is reset, so the
* value comes from hydration — but `buildOAuthConnectionState`
* (`connection-state.ts`) awaits `getClientInformation`/
* `getServerMetadata` (both of which await hydration) before it reads
* `getScope`, so hydration has already landed by then.
* A future refactor that reads `getScope` without a preceding awaited
* storage read would break this invariant.
*/
getScope(serverUrl: string): string | undefined {
const state = this.store.getState().getServerState(serverUrl);
async getScope(serverUrl: string): Promise<string | undefined> {
await this.ensureLoaded();
const state = this.memory.getState().getServerState(serverUrl);
return state.scope;
}
async saveScope(serverUrl: string, scope: string | undefined): Promise<void> {
await this.hydrated;
this.store.getState().setServerState(serverUrl, { scope });
await this.ensureLoaded();
this.memory.getState().setServerState(serverUrl, { scope });
await this.persist();
}
clearScope(serverUrl: string): void {
this.clearAfterHydration(() =>
this.store.getState().setServerState(serverUrl, { scope: undefined }),
);
async clearScope(serverUrl: string): Promise<void> {
await this.ensureLoaded();
this.memory.getState().setServerState(serverUrl, { scope: undefined });
await this.persist();
}
async getServerMetadata(serverUrl: string): Promise<OAuthMetadata | null> {
await this.hydrated;
const state = this.store.getState().getServerState(serverUrl);
await this.ensureLoaded();
const state = this.memory.getState().getServerState(serverUrl);
return state.serverMetadata || null;
}
@ -286,29 +212,28 @@ export class OAuthStorageBase implements OAuthStorage {
serverUrl: string,
metadata: OAuthMetadata,
): Promise<void> {
await this.hydrated;
this.store
await this.ensureLoaded();
this.memory.getState().setServerState(serverUrl, { serverMetadata: metadata });
await this.persist();
}
async clearServerMetadata(serverUrl: string): Promise<void> {
await this.ensureLoaded();
this.memory
.getState()
.setServerState(serverUrl, { serverMetadata: metadata });
.setServerState(serverUrl, { serverMetadata: undefined });
await this.persist();
}
clearServerMetadata(serverUrl: string): void {
this.clearAfterHydration(() =>
this.store
.getState()
.setServerState(serverUrl, { serverMetadata: undefined }),
);
}
clear(serverUrl: string): void {
this.clearAfterHydration(() =>
this.store.getState().clearServerState(serverUrl),
);
async clear(serverUrl: string): Promise<void> {
await this.ensureLoaded();
this.memory.getState().clearServerState(serverUrl);
await this.persist();
}
async getIdpSession(issuer: string): Promise<IdpSessionState | undefined> {
await this.hydrated;
const session = this.store.getState().getIdpSession(issuer);
await this.ensureLoaded();
const session = this.memory.getState().getIdpSession(issuer);
if (
!session.idToken &&
!session.refreshToken &&
@ -323,19 +248,20 @@ export class OAuthStorageBase implements OAuthStorage {
issuer: string,
session: Partial<IdpSessionState>,
): Promise<void> {
await this.hydrated;
this.store.getState().setIdpSession(issuer, session);
await this.ensureLoaded();
this.memory.getState().setIdpSession(issuer, session);
await this.persist();
}
clearIdpSession(issuer: string): void {
this.clearAfterHydration(() =>
this.store.getState().clearIdpSession(issuer),
);
async clearIdpSession(issuer: string): Promise<void> {
await this.ensureLoaded();
this.memory.getState().clearIdpSession(issuer);
await this.persist();
}
clearEnterpriseManagedResourceServers(): void {
this.clearAfterHydration(() =>
this.store.getState().clearEnterpriseManagedResourceServers(),
);
async clearEnterpriseManagedResourceServers(): Promise<void> {
await this.ensureLoaded();
this.memory.getState().clearEnterpriseManagedResourceServers();
await this.persist();
}
}

View file

@ -103,6 +103,8 @@ export class BaseOAuthClientProvider implements OAuthClientProvider {
private capturedAuthUrl: URL | null = null;
private eventTarget: EventTarget | null = null;
private suppressAuthorizationNavigation = false;
/** Cached after {@link prepareForAuth} for sync SDK `clientMetadata.scope`. */
private cachedScope: string | undefined;
protected serverUrl: string;
protected storage: OAuthStorage;
@ -118,6 +120,14 @@ export class BaseOAuthClientProvider implements OAuthClientProvider {
this.clientMetadataUrl = oauthConfig.clientMetadataUrl;
}
/**
* Load persisted scope into {@link cachedScope} before SDK `auth()` (which
* reads {@link clientMetadata.scope} synchronously).
*/
async prepareForAuth(): Promise<void> {
this.cachedScope = await this.storage.getScope(this.serverUrl);
}
/**
* Set the event target for dispatching oauthAuthorizationRequired events
*/
@ -145,7 +155,7 @@ export class BaseOAuthClientProvider implements OAuthClientProvider {
}
get scope(): string | undefined {
return this.storage.getScope(this.serverUrl);
return this.cachedScope;
}
get redirectUrl(): string {
@ -200,6 +210,7 @@ export class BaseOAuthClientProvider implements OAuthClientProvider {
async saveScope(scope: string | undefined): Promise<void> {
await this.storage.saveScope(this.serverUrl, scope);
this.cachedScope = scope;
}
async savePreregisteredClientInformation(
@ -247,12 +258,12 @@ export class BaseOAuthClientProvider implements OAuthClientProvider {
return verifier;
}
clear(): void {
this.storage.clear(this.serverUrl);
async clear(): Promise<void> {
await this.storage.clear(this.serverUrl);
}
async getServerMetadata(): Promise<OAuthMetadata | null> {
return await this.storage.getServerMetadata(this.serverUrl);
return this.storage.getServerMetadata(this.serverUrl);
}
async saveServerMetadata(metadata: OAuthMetadata): Promise<void> {

View file

@ -1,12 +1,11 @@
/**
* Remote HTTP storage implementation for OAuth state.
* Uses Zustand with remote storage adapter (HTTP API).
* For web clients that need to share state with Node apps.
*/
import { OAuthStorageBase } from "../oauth-storage.js";
import { createOAuthStore } from "../store.js";
import { createRemoteStorageAdapter } from "../../storage/adapters/remote-storage.js";
import { OAuthMemoryStore } from "../store.js";
import { createRemoteOAuthPersistBackend } from "../oauth-persist.js";
export interface RemoteOAuthStorageOptions {
/** Base URL of the remote server (e.g. http://localhost:3000) */
@ -20,21 +19,20 @@ export interface RemoteOAuthStorageOptions {
}
/**
* Remote HTTP storage implementation using Zustand with remote storage adapter.
* Remote HTTP storage implementation.
* Stores OAuth state via HTTP API (GET/POST/DELETE /api/storage/:storeId).
* For web clients that need to share state with Node apps (TUI, CLI).
*/
export class RemoteOAuthStorage extends OAuthStorageBase {
constructor(options: RemoteOAuthStorageOptions) {
super(
createOAuthStore(
createRemoteStorageAdapter({
baseUrl: options.baseUrl,
storeId: options.storeId ?? "oauth",
authToken: options.authToken,
fetchFn: options.fetchFn,
}),
),
new OAuthMemoryStore(),
createRemoteOAuthPersistBackend({
baseUrl: options.baseUrl,
storeId: options.storeId ?? "oauth",
authToken: options.authToken,
fetchFn: options.fetchFn,
}),
);
}
}

View file

@ -7,7 +7,7 @@ import type { OAuthClientRegistrationKind } from "./types.js";
/**
* Abstract storage interface for OAuth state
* Supports both browser (sessionStorage) and Node.js (Zustand) environments
* Supports browser (sessionStorage), Node.js (file), and remote HTTP backends.
*/
export interface SaveTokensOptions {
/** Marks resource tokens minted via EMA (legs 2–3) for sign-out cleanup. */
@ -22,10 +22,11 @@ export interface SaveClientInformationOptions {
export interface OAuthStorage {
/**
* Resolves once any async hydration of the underlying store has completed.
* With a synchronous storage adapter this resolves immediately.
* Optional preload of persisted state into memory. Getters and setters load
* automatically when needed; use this only for fail-fast at known boundaries
* (e.g. OAuth callback resume after a full-page navigation).
*/
ready(): Promise<void>;
load(): Promise<void>;
/**
* Get client information (preregistered or dynamically registered)
@ -40,7 +41,7 @@ export interface OAuthStorage {
*/
getClientRegistrationKind(
serverUrl: string,
): OAuthClientRegistrationKind | undefined;
): Promise<OAuthClientRegistrationKind | undefined>;
/**
* Save client information (dynamically registered)
@ -62,7 +63,10 @@ export interface OAuthStorage {
/**
* Clear client information
*/
clearClientInformation(serverUrl: string, isPreregistered?: boolean): void;
clearClientInformation(
serverUrl: string,
isPreregistered?: boolean,
): Promise<void>;
/**
* Get OAuth tokens
@ -81,14 +85,10 @@ export interface OAuthStorage {
/**
* Clear OAuth tokens
*/
clearTokens(serverUrl: string): void;
clearTokens(serverUrl: string): Promise<void>;
/**
* Get code verifier (for PKCE).
*
* Async because the backend-backed store may still be hydrating when this is
* read on the post-redirect OAuth callback path; the implementation awaits
* hydration before reading.
* Get code verifier (for PKCE)
*/
getCodeVerifier(serverUrl: string): Promise<string | undefined>;
@ -100,12 +100,12 @@ export interface OAuthStorage {
/**
* Clear code verifier
*/
clearCodeVerifier(serverUrl: string): void;
clearCodeVerifier(serverUrl: string): Promise<void>;
/**
* Get scope
*/
getScope(serverUrl: string): string | undefined;
getScope(serverUrl: string): Promise<string | undefined>;
/**
* Save scope
@ -115,14 +115,10 @@ export interface OAuthStorage {
/**
* Clear scope
*/
clearScope(serverUrl: string): void;
clearScope(serverUrl: string): Promise<void>;
/**
* Get server metadata discovered during OAuth.
*
* Async because the backend-backed store may still be hydrating when this is
* read on the post-redirect OAuth callback path; the implementation awaits
* hydration before reading.
* Get server metadata discovered during OAuth
*/
getServerMetadata(serverUrl: string): Promise<OAuthMetadata | null>;
@ -134,12 +130,12 @@ export interface OAuthStorage {
/**
* Clear server metadata
*/
clearServerMetadata(serverUrl: string): void;
clearServerMetadata(serverUrl: string): Promise<void>;
/**
* Clear all OAuth data for a server
*/
clear(serverUrl: string): void;
clear(serverUrl: string): Promise<void>;
/**
* Get cached IdP OIDC session for EMA (keyed by issuer).
@ -157,12 +153,12 @@ export interface OAuthStorage {
/**
* Clear cached IdP session for an issuer.
*/
clearIdpSession(issuer: string): void;
clearIdpSession(issuer: string): Promise<void>;
/**
* Remove per-server OAuth state for MCP servers whose tokens were minted via EMA.
*/
clearEnterpriseManagedResourceServers(): void;
clearEnterpriseManagedResourceServers(): Promise<void>;
}
/**

View file

@ -1,10 +1,8 @@
/**
* OAuth store factory using Zustand.
* Creates a store with any storage adapter (file, remote, sessionStorage).
* In-memory OAuth state store (servers + IdP sessions).
* Persisted via `OAuthStorageBase` + `OAuthPersistBackend` backends.
*/
import { createStore } from "zustand/vanilla";
import { persist, createJSONStorage } from "zustand/middleware";
import type {
OAuthClientInformation,
OAuthTokens,
@ -14,6 +12,7 @@ import type {
IdpSessionState,
OAuthClientRegistrationKind,
} from "./storage.js";
import type { OAuthPersistSnapshot } from "./oauth-persist.js";
/**
* OAuth state for a single server
@ -32,27 +31,7 @@ export interface ServerOAuthState {
}
/**
* Normalize a server URL to its canonical form for use as a store key.
*
* Different callers (web deep-link parser, CLI `--server-url`, the SDK's own
* client constructor) can present the same endpoint with cosmetic differences
* — host case, a trailing slash on a bare-origin URL, default-port omission —
* that `new URL().href` collapses. Keying by the canonical form means a token
* the web inspector saved under `https://Example.com/mcp` is found when the
* CLI later asks for `https://example.com/mcp/`. Non-URL strings (e.g. a
* stdio server name) are returned trimmed so the store still works for them.
*/
export function normalizeServerUrl(serverUrl: string): string {
const trimmed = serverUrl.trim();
try {
return new URL(trimmed).href;
} catch {
return trimmed;
}
}
/**
* Zustand store state (all servers)
* OAuth store state (all servers) plus mutation helpers.
*/
export interface OAuthStoreState {
servers: Record<string, ServerOAuthState>;
@ -67,109 +46,80 @@ export interface OAuthStoreState {
}
/**
* Creates a Zustand store for OAuth state with the given storage adapter.
* The storage adapter handles persistence (file, remote HTTP, sessionStorage, etc.).
*
* @param storage - Zustand storage adapter (from createJSONStorage)
* @returns Zustand store instance
* Mutable in-memory OAuth state keyed by server URL and IdP issuer.
*/
export function createOAuthStore(
storage: ReturnType<typeof createJSONStorage>,
) {
return createStore<OAuthStoreState>()(
persist(
(set, get) => ({
servers: {},
idpSessions: {},
getServerState: (serverUrl: string) => {
const servers = get().servers;
// Look up by canonical key, falling back to the raw key so an
// already-persisted blob written before normalization existed (or by
// another writer) is still found.
return (
servers[normalizeServerUrl(serverUrl)] ?? servers[serverUrl] ?? {}
);
},
setServerState: (
serverUrl: string,
updates: Partial<ServerOAuthState>,
) => {
const key = normalizeServerUrl(serverUrl);
set((state) => {
const servers = { ...state.servers };
// Mirror getServerState's canonical→raw fallback for writes: if no
// canonical entry exists yet but a pre-normalization blob lives
// under the raw key, migrate it onto the canonical key so this
// partial write MERGES onto the existing credential instead of
// shadowing it with a fresh canonical entry (which would orphan the
// raw-key blob's other fields — e.g. a token — behind the new
// canonical one that getServerState now prefers).
let base = servers[key];
if (base === undefined && servers[serverUrl] !== undefined) {
// Reaching here implies `serverUrl !== key`: if they were equal,
// `servers[serverUrl]` would equal the `servers[key]` we just
// found undefined, so the guard above could not have passed.
base = servers[serverUrl];
delete servers[serverUrl];
}
servers[key] = { ...base, ...updates };
return { servers };
});
},
clearServerState: (serverUrl: string) => {
const key = normalizeServerUrl(serverUrl);
set((state) => {
const rest = { ...state.servers };
delete rest[key];
// Also drop a pre-normalization blob under the raw key so a clear
// fully removes the credential rather than leaving an orphan that
// getServerState's raw-key fallback would keep surfacing.
if (serverUrl !== key) delete rest[serverUrl];
return { servers: rest };
});
},
getIdpSession: (issuer: string) => {
return get().idpSessions[issuer] || {};
},
setIdpSession: (issuer: string, updates: Partial<IdpSessionState>) => {
set((state) => ({
idpSessions: {
...state.idpSessions,
[issuer]: {
...state.idpSessions[issuer],
...updates,
},
},
}));
},
clearIdpSession: (issuer: string) => {
set((state) => {
const rest = { ...state.idpSessions };
delete rest[issuer];
return { idpSessions: rest };
});
},
clearEnterpriseManagedResourceServers: () => {
set((state) => {
const rest = { ...state.servers };
for (const [url, serverState] of Object.entries(state.servers)) {
if (serverState.enterpriseManaged === true) {
delete rest[url];
}
}
return { servers: rest };
});
},
}),
{
name: "mcp-inspector-oauth",
storage,
// OAuthStorageBase drives `persist.rehydrate()` itself so it can await
// (and catch errors from) the single hydration. Auto-hydration here
// would race the explicit one and could clobber a save that landed
// between them.
skipHydration: true,
export class OAuthMemoryStore {
private servers: Record<string, ServerOAuthState> = {};
private idpSessions: Record<string, IdpSessionState> = {};
constructor(initial?: OAuthPersistSnapshot) {
if (initial) {
this.replace(initial);
}
}
getState(): OAuthStoreState {
return {
servers: this.servers,
idpSessions: this.idpSessions,
getServerState: (serverUrl: string) => {
return this.servers[serverUrl] || {};
},
),
);
setServerState: (
serverUrl: string,
updates: Partial<ServerOAuthState>,
) => {
this.servers = {
...this.servers,
[serverUrl]: {
...this.servers[serverUrl],
...updates,
},
};
},
clearServerState: (serverUrl: string) => {
const rest = { ...this.servers };
delete rest[serverUrl];
this.servers = rest;
},
getIdpSession: (issuer: string) => {
return this.idpSessions[issuer] || {};
},
setIdpSession: (issuer: string, updates: Partial<IdpSessionState>) => {
this.idpSessions = {
...this.idpSessions,
[issuer]: {
...this.idpSessions[issuer],
...updates,
},
};
},
clearIdpSession: (issuer: string) => {
const rest = { ...this.idpSessions };
delete rest[issuer];
this.idpSessions = rest;
},
clearEnterpriseManagedResourceServers: () => {
const rest = { ...this.servers };
for (const [url, serverState] of Object.entries(this.servers)) {
if (serverState.enterpriseManaged === true) {
delete rest[url];
}
}
this.servers = rest;
},
};
}
snapshot(): OAuthPersistSnapshot {
return {
servers: { ...this.servers },
idpSessions: { ...this.idpSessions },
};
}
replace(snapshot: OAuthPersistSnapshot): void {
this.servers = { ...(snapshot.servers ?? {}) };
this.idpSessions = { ...(snapshot.idpSessions ?? {}) };
}
}