inspector/clients/web/server/inject-auth-token.ts
Cliff Hall 881ba4b5e8
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>
2026-05-30 20:10:27 -04:00

51 lines
2.3 KiB
TypeScript

/**
* Embed the remote API auth token into the served `index.html` so the browser
* doesn't depend on the `?MCP_INSPECTOR_API_TOKEN=…` query string surviving
* navigation, bookmarks, or a hand-typed reload at the bare URL. The dev Vite
* plugin (`vite-hono-plugin.ts`) and the prod Hono server (`server.ts`) both
* funnel through this single helper so the injected shape stays identical
* across both backends. `App.tsx`'s `getAuthToken()` reads the embedded global
* ahead of the URL / sessionStorage fallbacks.
*/
import { INSPECTOR_API_TOKEN_GLOBAL } from "../../../core/mcp/remote/constants.ts";
/**
* Serialize the token as a JS string literal safe to drop inside an inline
* `<script>`. `JSON.stringify` handles quotes / backslashes / control chars;
* the extra `<` → `<` escape closes the one hole that matters in an HTML
* context — a token containing the literal `</script>` would otherwise close
* the tag early. The token is normally a hex string, but it can be a
* user-supplied value (`MCP_INSPECTOR_API_TOKEN` env / `--auth-token`), so we
* don't assume it's benign.
*/
function serializeTokenForScript(token: string): string {
return JSON.stringify(token).replace(/</g, "\\u003c");
}
/**
* Return `html` with a `<script>window.__INSPECTOR_API_TOKEN__ = "…"</script>`
* tag injected. The script is placed just before `</head>` when present, else
* just before `</body>`, else prepended — in every case it runs before the app
* bundle (which lives further down the document) so the global is set by the
* time `getAuthToken()` reads it.
*
* An empty `token` (auth disabled via `DANGEROUSLY_OMIT_AUTH`) is a no-op: the
* page is returned untouched and no global is defined, matching the banner's
* "no token in the URL" behavior.
*/
export function injectAuthToken(html: string, token: string): string {
if (!token) return html;
const script = `<script>window.${INSPECTOR_API_TOKEN_GLOBAL} = ${serializeTokenForScript(
token,
)};</script>`;
const headClose = html.indexOf("</head>");
if (headClose !== -1) {
return html.slice(0, headClose) + script + html.slice(headClose);
}
const bodyClose = html.indexOf("</body>");
if (bodyClose !== -1) {
return html.slice(0, bodyClose) + script + html.slice(bodyClose);
}
return script + html;
}