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:
cliffhall 2026-07-01 18:39:17 -04:00
commit c299b6e9d8
3 changed files with 786 additions and 135 deletions

View file

@ -4,11 +4,9 @@ import {
createRemoteFetch,
createRemoteLogger,
} from "@inspector/core/mcp/remote/index.js";
import {
getBrowserOAuthStorage,
BrowserNavigation,
} from "@inspector/core/auth/browser/index.js";
import { BrowserNavigation } from "@inspector/core/auth/browser/index.js";
import type { RedirectUrlProvider } from "@inspector/core/auth/index.js";
import { getRemoteOAuthStorage } from "./remoteOAuthStorage";
export interface WebEnvironmentResult {
environment: InspectorClientEnvironment;
@ -20,8 +18,11 @@ export interface WebEnvironmentResult {
* - transport / fetch / logger all routed through the in-process Hono
* backend at `window.location.origin` (the `clients/web/server`
* dev-backend wires this in `/api/*`).
* - OAuth storage + navigation use the `BrowserOAuthStorage` (sessionStorage)
* and `BrowserNavigation` (full-page redirect) adapters.
* - OAuth storage uses `RemoteOAuthStorage` (POSTs to the same backend's
* `/api/storage/oauth`, which writes `~/.mcp-inspector/storage/oauth.json`
* mode 0600), so a token obtained in this browser session is also
* available to the CLI/TUI on the same host. Navigation still uses
* `BrowserNavigation` (full-page redirect).
*
* Returns both the assembled environment and the logger so callers can share
* the same pino instance for any direct logging they need to do, instead of
@ -67,7 +68,7 @@ export function createWebEnvironment(
}),
logger,
oauth: {
storage: getBrowserOAuthStorage(),
storage: getRemoteOAuthStorage(baseUrl, authToken, fetchFn),
navigation: new BrowserNavigation(undefined, onBeforeOAuthRedirect),
redirectUrlProvider,
},

View file

@ -0,0 +1,64 @@
import { describe, it, expect, vi } from "vitest";
import { RemoteOAuthStorage } from "@inspector/core/auth/remote/index.js";
import {
getRemoteOAuthStorage,
getWebOAuthBaseUrl,
webOAuthFetch,
} from "./remoteOAuthStorage";
const NOOP_FETCH = vi.fn(
async () =>
new Response(JSON.stringify({ state: { servers: {} }, version: 0 }), {
status: 200,
}),
) as unknown as typeof fetch;
describe("remoteOAuthStorage", () => {
it("getWebOAuthBaseUrl derives the backend origin from window.location", () => {
expect(getWebOAuthBaseUrl()).toBe(
`${window.location.protocol}//${window.location.host}`,
);
});
it("returns a RemoteOAuthStorage instance", () => {
const storage = getRemoteOAuthStorage(
"http://a.example",
undefined,
NOOP_FETCH,
);
expect(storage).toBeInstanceOf(RemoteOAuthStorage);
});
it("memoizes one instance per {baseUrl, authToken}", () => {
const a1 = getRemoteOAuthStorage("http://memo.example", "tok", NOOP_FETCH);
const a2 = getRemoteOAuthStorage("http://memo.example", "tok", NOOP_FETCH);
expect(a1).toBe(a2);
// A different auth token is a distinct key → distinct instance.
const b = getRemoteOAuthStorage("http://memo.example", "other", NOOP_FETCH);
expect(b).not.toBe(a1);
// A different base URL is a distinct key → distinct instance.
const c = getRemoteOAuthStorage("http://memo2.example", "tok", NOOP_FETCH);
expect(c).not.toBe(a1);
});
it("treats an undefined authToken as its own stable key", () => {
const a = getRemoteOAuthStorage("http://undef.example", undefined);
const b = getRemoteOAuthStorage("http://undef.example", undefined);
expect(a).toBe(b);
});
it("webOAuthFetch delegates to globalThis.fetch preserving the receiver", async () => {
const spy = vi
.spyOn(globalThis, "fetch")
.mockResolvedValue(new Response("ok", { status: 200 }));
try {
const res = await webOAuthFetch("http://x.example");
expect(spy).toHaveBeenCalledWith("http://x.example");
expect(res.status).toBe(200);
} finally {
spy.mockRestore();
}
});
});

View file

@ -0,0 +1,45 @@
import { RemoteOAuthStorage } from "@inspector/core/auth/remote/index.js";
/**
* Shared `RemoteOAuthStorage` accessor for the web client.
*
* The browser's OAuth state is persisted through the in-process Hono backend
* (`POST /api/storage/oauth` → `~/.mcp-inspector/storage/oauth.json`, mode
* 0600) rather than `sessionStorage`, so a credential obtained in the browser
* is the same blob the TUI/CLI read on the same host (web ⇄ TUI ⇄ CLI parity).
*
* One instance per `{baseUrl, authToken}`. The environment factory is called
* per-connect (a fresh `InspectorClient` is built for each server switch), but
* the OAuth blob on disk is a single shared resource: a stale instance's
* whole-blob POST could clobber a write made by a newer one. Memoizing also
* avoids re-hydrating the same file on every connect, and lets the connection
* path, the EMA IdP hook, and the per-server "clear OAuth" action all share
* one in-memory view of the store.
*/
const oauthStorageCache = new Map<string, RemoteOAuthStorage>();
/** Backend origin the web client talks to (same origin that serves the SPA). */
export function getWebOAuthBaseUrl(): string {
return `${window.location.protocol}//${window.location.host}`;
}
/**
* `window.fetch` loses its `this` binding when extracted, raising "Illegal
* invocation"; wrap so the call site preserves the global receiver.
*/
export const webOAuthFetch: typeof fetch = (...args) =>
globalThis.fetch(...args);
/** Memoized `RemoteOAuthStorage` for the given backend + auth token. */
export function getRemoteOAuthStorage(
baseUrl: string,
authToken: string | undefined,
fetchFn: typeof fetch = webOAuthFetch,
): RemoteOAuthStorage {
const key = `${baseUrl} ${authToken ?? ""}`;
const cached = oauthStorageCache.get(key);
if (cached) return cached;
const storage = new RemoteOAuthStorage({ baseUrl, authToken, fetchFn });
oauthStorageCache.set(key, storage);
return storage;
}