merge: v2/1548-web-remote-oauth-storage (#1592)

# Conflicts:
#	clients/web/src/test/core/auth/utils.test.ts
This commit is contained in:
cliffhall 2026-07-01 22:05:52 -04:00
commit e425602295
3 changed files with 988 additions and 151 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,56 @@
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.
*
* The cache key is intentionally `{baseUrl, authToken}` only — `fetchFn` is NOT
* part of it. Whichever call constructs an instance first wins, so a later
* caller's `fetchFn` is ignored. This is safe today because every call site
* either omits `fetchFn` (defaulting to {@link webOAuthFetch}) or passes an
* `environmentFactory` wrapper that is functionally identical (`globalThis.fetch`),
* so the shared-instance goal (one whole-blob writer per backend) matters more
* than which wrapper is used. A future caller needing a genuinely different
* transport must key on it (or bypass the cache).
*/
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;
}