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
This commit is contained in:
parent
066676a241
commit
c299b6e9d8
1 changed files with 786 additions and 135 deletions
|
|
@ -20,18 +20,87 @@ import type {
|
|||
* 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.
|
||||
*/
|
||||
export class OAuthStorageBase implements OAuthStorage {
|
||||
private readonly store: ReturnType<typeof createOAuthStore>;
|
||||
private readonly hydrated: Promise<void>;
|
||||
private hydrationError?: Error;
|
||||
|
||||
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),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
async getClientInformation(
|
||||
serverUrl: string,
|
||||
isPreregistered?: boolean,
|
||||
): Promise<OAuthClientInformation | undefined> {
|
||||
await this.hydrated;
|
||||
const state = this.store.getState().getServerState(serverUrl);
|
||||
const clientInfo = isPreregistered
|
||||
? state.preregisteredClientInformation
|
||||
|
|
@ -56,6 +125,7 @@ export class OAuthStorageBase implements OAuthStorage {
|
|||
clientInformation: OAuthClientInformation,
|
||||
options: SaveClientInformationOptions,
|
||||
): Promise<void> {
|
||||
await this.hydrated;
|
||||
this.store.getState().setServerState(serverUrl, {
|
||||
clientInformation,
|
||||
clientRegistrationKind: options.registrationKind,
|
||||
|
|
@ -66,6 +136,7 @@ export class OAuthStorageBase implements OAuthStorage {
|
|||
serverUrl: string,
|
||||
clientInformation: OAuthClientInformation,
|
||||
): Promise<void> {
|
||||
await this.hydrated;
|
||||
this.store.getState().setServerState(serverUrl, {
|
||||
preregisteredClientInformation: clientInformation,
|
||||
clientRegistrationKind: "static",
|
||||
|
|
@ -86,6 +157,7 @@ export class OAuthStorageBase implements OAuthStorage {
|
|||
}
|
||||
|
||||
async getTokens(serverUrl: string): Promise<OAuthTokens | undefined> {
|
||||
await this.hydrated;
|
||||
const state = this.store.getState().getServerState(serverUrl);
|
||||
if (!state.tokens) {
|
||||
return undefined;
|
||||
|
|
@ -99,6 +171,7 @@ export class OAuthStorageBase implements OAuthStorage {
|
|||
tokens: OAuthTokens,
|
||||
options?: SaveTokensOptions,
|
||||
): Promise<void> {
|
||||
await this.hydrated;
|
||||
this.store.getState().setServerState(serverUrl, {
|
||||
tokens,
|
||||
...(options?.enterpriseManaged === true && { enterpriseManaged: true }),
|
||||
|
|
@ -109,7 +182,8 @@ export class OAuthStorageBase implements OAuthStorage {
|
|||
this.store.getState().setServerState(serverUrl, { tokens: undefined });
|
||||
}
|
||||
|
||||
getCodeVerifier(serverUrl: string): string | undefined {
|
||||
async getCodeVerifier(serverUrl: string): Promise<string | undefined> {
|
||||
await this.hydrated;
|
||||
const state = this.store.getState().getServerState(serverUrl);
|
||||
return state.codeVerifier;
|
||||
}
|
||||
|
|
@ -118,6 +192,7 @@ export class OAuthStorageBase implements OAuthStorage {
|
|||
serverUrl: string,
|
||||
codeVerifier: string,
|
||||
): Promise<void> {
|
||||
await this.hydrated;
|
||||
this.store.getState().setServerState(serverUrl, { codeVerifier });
|
||||
}
|
||||
|
||||
|
|
@ -127,12 +202,21 @@ export class OAuthStorageBase implements OAuthStorage {
|
|||
.setServerState(serverUrl, { codeVerifier: undefined });
|
||||
}
|
||||
|
||||
/**
|
||||
* Intentionally synchronous. The only caller is
|
||||
* {@link BaseOAuthClientProvider.scope}, a sync getter the SDK requires
|
||||
* (it feeds the sync `clientMetadata` getter). Scope is always set via
|
||||
* {@link saveScope} in the same session before it's read (during the
|
||||
* pre-redirect half of the flow), so the in-memory store has the value
|
||||
* regardless of async hydration.
|
||||
*/
|
||||
getScope(serverUrl: string): string | undefined {
|
||||
const state = this.store.getState().getServerState(serverUrl);
|
||||
return state.scope;
|
||||
}
|
||||
|
||||
async saveScope(serverUrl: string, scope: string | undefined): Promise<void> {
|
||||
await this.hydrated;
|
||||
this.store.getState().setServerState(serverUrl, { scope });
|
||||
}
|
||||
|
||||
|
|
@ -140,7 +224,8 @@ export class OAuthStorageBase implements OAuthStorage {
|
|||
this.store.getState().setServerState(serverUrl, { scope: undefined });
|
||||
}
|
||||
|
||||
getServerMetadata(serverUrl: string): OAuthMetadata | null {
|
||||
async getServerMetadata(serverUrl: string): Promise<OAuthMetadata | null> {
|
||||
await this.hydrated;
|
||||
const state = this.store.getState().getServerState(serverUrl);
|
||||
return state.serverMetadata || null;
|
||||
}
|
||||
|
|
@ -149,6 +234,7 @@ export class OAuthStorageBase implements OAuthStorage {
|
|||
serverUrl: string,
|
||||
metadata: OAuthMetadata,
|
||||
): Promise<void> {
|
||||
await this.hydrated;
|
||||
this.store
|
||||
.getState()
|
||||
.setServerState(serverUrl, { serverMetadata: metadata });
|
||||
|
|
@ -165,6 +251,7 @@ export class OAuthStorageBase implements OAuthStorage {
|
|||
}
|
||||
|
||||
async getIdpSession(issuer: string): Promise<IdpSessionState | undefined> {
|
||||
await this.hydrated;
|
||||
const session = this.store.getState().getIdpSession(issuer);
|
||||
if (
|
||||
!session.idToken &&
|
||||
|
|
@ -180,6 +267,7 @@ export class OAuthStorageBase implements OAuthStorage {
|
|||
issuer: string,
|
||||
session: Partial<IdpSessionState>,
|
||||
): Promise<void> {
|
||||
await this.hydrated;
|
||||
this.store.getState().setIdpSession(issuer, session);
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue