feat(auth): inject MCP_INSPECTOR_API_TOKEN into served index.html (#1378) (#1382)

* feat(auth): inject MCP_INSPECTOR_API_TOKEN into served index.html (#1378)

Reloading the web client at the bare URL (no `?MCP_INSPECTOR_API_TOKEN=…`
query string) with empty sessionStorage made every `/api/*` request 401 —
the browser had no way to recover the backend's auth token.

Embed the token into `index.html` on every page load so the browser no
longer depends on the query string surviving navigation:

- New shared helper `clients/web/server/inject-auth-token.ts` embeds
  `<script>window.__INSPECTOR_API_TOKEN__ = "…"</script>` (escaped against
  `</script>` injection; no-op when auth is dangerously omitted).
- Dev: the Vite plugin injects via `transformIndexHtml`.
- Prod: the Hono server injects on the `/` route.
- `App.tsx` `getAuthToken()` now reads the injected global first, then the
  query string, then sessionStorage (both fallbacks preserved).
- Shared global name lives in `INSPECTOR_API_TOKEN_GLOBAL`
  (`core/mcp/remote/constants.ts`).

Tests: helper unit coverage + an integration test exercising the real
prod server's `/` → `/api/*` flow (injected token authenticates; missing
token 401s). AGENTS.md documents the token-recovery order.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(auth): inject token into prod SPA fallback + prime sessionStorage + no-store (#1378)

Addresses code-review feedback on the token-injection PR:

- Prod `server.ts` SPA deep-link fallback (e.g. `/oauth/callback`) previously
  served the raw index.html off disk via serveStatic, bypassing injection — so
  a bookmark/reload at a non-`/` route with empty sessionStorage would 401.
  Route the SPA fallback through the same `serveIndexHtml` (inject) helper;
  real static assets (paths with a dot) still serve verbatim. Dev already
  injected on every HTML serve via Vite `transformIndexHtml`.
- `getAuthToken()` now persists the injected `window.__INSPECTOR_API_TOKEN__`
  to sessionStorage (not just the URL-param branch), priming the backstop for
  any later navigation that loses the global.
- Injected HTML responses now send `Cache-Control: no-store`, so a page
  carrying a token isn't cached and served stale after a restart regenerates
  the token.

Integration tests added: SPA fallback (`/oauth/callback`) carries the token,
`Cache-Control: no-store` on injected HTML, real assets served verbatim, and
unknown `/api` routes 404 rather than falling through to the HTML shell.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Cliff Hall 2026-05-30 20:10:27 -04:00 • committed by GitHub
commit 881ba4b5e8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 372 additions and 29 deletions

View file

@ -17,7 +17,10 @@ import type {
ServerEntry,
ServerType,
} from "@inspector/core/mcp/types.js";
import { API_SERVER_ENV_VARS } from "@inspector/core/mcp/remote/constants.js";
import {
API_SERVER_ENV_VARS,
INSPECTOR_API_TOKEN_GLOBAL,
} from "@inspector/core/mcp/remote/constants.js";
import { ManagedToolsState } from "@inspector/core/mcp/state/managedToolsState.js";
import { ManagedPromptsState } from "@inspector/core/mcp/state/managedPromptsState.js";
import { ManagedResourcesState } from "@inspector/core/mcp/state/managedResourcesState.js";
@ -65,25 +68,44 @@ const redirectUrlProvider: RedirectUrlProvider = {
getRedirectUrl: () => `${window.location.origin}/oauth/callback`,
};
// Pull the dev-backend's auth token off the URL the launcher banner prints.
// `npm run dev` opens `http://localhost:6274?MCP_INSPECTOR_API_TOKEN=…`;
// every browser request to /api/* needs the same token in the
// `x-mcp-remote-auth: Bearer …` header or the Hono backend returns 401.
// Persist to sessionStorage so SPA navigations / OAuth round-trips don't
// drop the token from the URL bar.
// Recover the backend's auth token. Every browser request to /api/* needs it
// in the `x-mcp-remote-auth: Bearer …` header or the Hono backend returns 401.
// Three sources, in priority order:
// 1. `window.__INSPECTOR_API_TOKEN__` — injected into index.html by the
// backend on every page load (dev Vite plugin + prod Hono server). This
// is the robust path: it survives a bare-URL reload, a bookmark, or a
// cleared sessionStorage, none of which carry the query string.
// 2. `?MCP_INSPECTOR_API_TOKEN=…` — the URL the launcher banner prints. Kept
// as a fallback for pasted full URLs and older integrations.
// 3. sessionStorage — backstop for SPA navigations / OAuth round-trips that
// land without either of the above.
// Both the injected global and the URL value are persisted to sessionStorage
// so a later navigation that drops them (e.g. a deep-link load that wasn't
// injected, or an iframe) still authenticates from the backstop.
function getAuthToken(): string | undefined {
if (typeof window === "undefined") return undefined;
const STORAGE_KEY = API_SERVER_ENV_VARS.AUTH_TOKEN;
// Best-effort persistence — sessionStorage may be unavailable (privacy
// mode, iframe sandboxing, etc.); the resolved value still works for the
// current page load regardless.
const persist = (token: string): void => {
try {
window.sessionStorage.setItem(STORAGE_KEY, token);
} catch {
// ignore — see note above
}
};
const fromGlobal = (window as unknown as Record<string, unknown>)[
INSPECTOR_API_TOKEN_GLOBAL
];
if (typeof fromGlobal === "string" && fromGlobal) {
persist(fromGlobal);
return fromGlobal;
}
const params = new URLSearchParams(window.location.search);
const fromUrl = params.get(API_SERVER_ENV_VARS.AUTH_TOKEN);
if (fromUrl) {
try {
window.sessionStorage.setItem(STORAGE_KEY, fromUrl);
} catch {
// Best-effort persistence — sessionStorage may be unavailable
// (privacy mode, iframe sandboxing, etc.); the URL value still
// works for the current page load.
}
persist(fromUrl);
return fromUrl;
}
try {

View file

@ -0,0 +1,67 @@
import { describe, it, expect } from "vitest";
import { injectAuthToken } from "../../../../server/inject-auth-token.js";
import { INSPECTOR_API_TOKEN_GLOBAL } from "../../../../../../core/mcp/remote/constants.js";
const TOKEN = "deadbeefcafef00d";
const scriptFor = (token: string) =>
`window.${INSPECTOR_API_TOKEN_GLOBAL} = ${JSON.stringify(token)};`;
describe("injectAuthToken", () => {
it("injects the token global just before </head>", () => {
const html = "<html><head><title>X</title></head><body></body></html>";
const out = injectAuthToken(html, TOKEN);
expect(out).toContain(scriptFor(TOKEN));
// The script must land inside <head>, ahead of the closing tag.
const scriptIdx = out.indexOf(scriptFor(TOKEN));
const headCloseIdx = out.indexOf("</head>");
expect(scriptIdx).toBeLessThan(headCloseIdx);
expect(scriptIdx).toBeGreaterThan(out.indexOf("<head>"));
});
it("falls back to before </body> when there is no </head>", () => {
const html = "<html><body><div id='root'></div></body></html>";
const out = injectAuthToken(html, TOKEN);
const scriptIdx = out.indexOf(scriptFor(TOKEN));
expect(scriptIdx).toBeGreaterThan(-1);
expect(scriptIdx).toBeLessThan(out.indexOf("</body>"));
});
it("prepends when there is neither </head> nor </body>", () => {
const html = "<div id='root'></div>";
const out = injectAuthToken(html, TOKEN);
expect(out.startsWith(`<script>${scriptFor(TOKEN)}</script>`)).toBe(true);
expect(out.endsWith(html)).toBe(true);
});
it("returns the html untouched for an empty token (auth disabled)", () => {
const html = "<html><head></head><body></body></html>";
expect(injectAuthToken(html, "")).toBe(html);
});
it("escapes a token containing </script> so the tag can't close early", () => {
const evil = "abc</script><script>alert(1)</script>";
const out = injectAuthToken("<head></head>", evil);
// The raw, unescaped sequence must not survive into the output.
expect(out).not.toContain("</script><script>alert(1)");
// The `<` of the embedded literal is escaped to its JS unicode form.
expect(out).toContain("\\u003c/script>");
// Exactly one opening + one closing script tag (our wrapper) remain.
expect(out.match(/<script>/g)).toHaveLength(1);
expect(out.match(/<\/script>/g)).toHaveLength(1);
});
it("round-trips the token value through JSON so the browser reads it back", () => {
const html = "<head></head>";
const out = injectAuthToken(html, TOKEN);
// Recover the JSON literal the browser would evaluate and confirm it
// parses back to the original token.
const match = out.match(
new RegExp(`window\\.${INSPECTOR_API_TOKEN_GLOBAL} = (.+?);</script>`),
);
expect(match).not.toBeNull();
const parsed = JSON.parse(
(match as RegExpMatchArray)[1].replace(/\\u003c/g, "<"),
);
expect(parsed).toBe(TOKEN);
});
});

View file

@ -0,0 +1,144 @@
import { describe, it, expect, beforeAll, afterAll } from "vitest";
import { createServer } from "node:net";
import { mkdtemp, writeFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { startHonoServer } from "../../../../server/server.js";
import type { WebServerConfig } from "../../../../server/web-server-config.js";
import type { WebServerHandle } from "../../../../server/types.js";
import { INSPECTOR_API_TOKEN_GLOBAL } from "../../../../../../core/mcp/remote/constants.js";
// Ask the OS for an ephemeral port, then release it for the server to claim.
// There's a vanishingly small reuse window between close and re-bind, but it's
// the standard pattern for "start a real server on a free port" in tests and
// far less flaky than hard-coding one.
async function findFreePort(): Promise<number> {
return new Promise((resolve, reject) => {
const srv = createServer();
srv.unref();
srv.on("error", reject);
srv.listen(0, "127.0.0.1", () => {
const addr = srv.address();
if (addr && typeof addr === "object") {
const { port } = addr;
srv.close(() => resolve(port));
} else {
srv.close(() => reject(new Error("Could not resolve a free port")));
}
});
});
}
// Pull the injected token back out of the served index.html the same way the
// browser would — read `window.__INSPECTOR_API_TOKEN__ = "…"`.
function tokenFromHtml(html: string): string | undefined {
const match = html.match(
new RegExp(`window\\.${INSPECTOR_API_TOKEN_GLOBAL} = (.+?);</script>`),
);
if (!match) return undefined;
return JSON.parse(match[1].replace(/\\u003c/g, "<")) as string;
}
const TOKEN = "test-injected-token-1234567890";
const INDEX_HTML =
"<!doctype html><html><head><title>Inspector</title></head>" +
'<body><div id="root"></div><script type="module" src="/src/main.tsx"></script></body></html>';
const ASSET_JS = 'console.log("static asset");\n';
describe("startHonoServer index.html token injection (/ -> /api/*)", () => {
let handle: WebServerHandle;
let baseUrl: string;
let staticRoot: string;
beforeAll(async () => {
staticRoot = await mkdtemp(join(tmpdir(), "inspector-inject-"));
await writeFile(join(staticRoot, "index.html"), INDEX_HTML, "utf-8");
// A real static asset (path has a file extension) to prove serveStatic
// still serves files verbatim rather than routing them through injection.
await writeFile(join(staticRoot, "asset.js"), ASSET_JS, "utf-8");
const port = await findFreePort();
baseUrl = `http://127.0.0.1:${port}`;
const config: WebServerConfig = {
port,
hostname: "127.0.0.1",
authToken: TOKEN,
dangerouslyOmitAuth: false,
initialMcpConfig: null,
storageDir: undefined,
// Allow the same-origin requests the test issues below.
allowedOrigins: [baseUrl],
sandboxPort: 0,
sandboxHost: "127.0.0.1",
logger: undefined,
autoOpen: false,
staticRoot,
};
handle = await startHonoServer(config);
});
afterAll(async () => {
await handle?.close();
if (staticRoot) await rm(staticRoot, { recursive: true, force: true });
});
it("embeds the auth token in the page served at /", async () => {
const res = await fetch(`${baseUrl}/`);
expect(res.status).toBe(200);
const html = await res.text();
expect(tokenFromHtml(html)).toBe(TOKEN);
});
it("the embedded token authenticates a subsequent /api/* request", async () => {
const indexRes = await fetch(`${baseUrl}/`);
const token = tokenFromHtml(await indexRes.text());
expect(token).toBe(TOKEN);
const apiRes = await fetch(`${baseUrl}/api/config`, {
headers: { "x-mcp-remote-auth": `Bearer ${token}` },
});
expect(apiRes.status).toBe(200);
});
it("rejects an /api/* request that omits the token (proving injection is what unblocks the flow)", async () => {
const apiRes = await fetch(`${baseUrl}/api/config`);
expect(apiRes.status).toBe(401);
});
it("injects the token into the SPA deep-link fallback (e.g. /oauth/callback)", async () => {
// A non-/api path with no file extension resolves to the SPA fallback,
// which must serve the *injected* index.html — not a raw file — so a
// bookmark or reload at the OAuth callback URL still authenticates.
const res = await fetch(`${baseUrl}/oauth/callback?code=abc&state=xyz`);
expect(res.status).toBe(200);
const html = await res.text();
expect(tokenFromHtml(html)).toBe(TOKEN);
});
it("sets Cache-Control: no-store on injected HTML so a restart's new token isn't served stale", async () => {
const root = await fetch(`${baseUrl}/`);
expect(root.headers.get("cache-control")).toBe("no-store");
const fallback = await fetch(`${baseUrl}/oauth/callback`);
expect(fallback.headers.get("cache-control")).toBe("no-store");
});
it("serves real static assets verbatim (no token injection)", async () => {
const res = await fetch(`${baseUrl}/asset.js`);
expect(res.status).toBe(200);
const body = await res.text();
expect(body).toBe(ASSET_JS);
expect(body).not.toContain(INSPECTOR_API_TOKEN_GLOBAL);
});
it("does not route /api paths through the SPA fallback", async () => {
// An unknown /api route must 404 as JSON-less notFound, never the HTML
// shell (which would mask real API errors behind a 200 page).
const res = await fetch(`${baseUrl}/api/does-not-exist`, {
headers: { "x-mcp-remote-auth": `Bearer ${TOKEN}` },
});
expect(res.status).toBe(404);
const body = await res.text();
expect(body).not.toContain(INSPECTOR_API_TOKEN_GLOBAL);
});
});