Skip to content

Commit 025f06a

Browse files
cliffhallclaude
andcommitted
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) <[email protected]>
1 parent 4d893c1 commit 025f06a

3 files changed

Lines changed: 90 additions & 28 deletions

File tree

‎clients/web/server/server.ts‎

Lines changed: 34 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import open from "open";
1111
import { serve } from "@hono/node-server";
1212
import { serveStatic } from "@hono/node-server/serve-static";
1313
import { Hono } from "hono";
14+
import type { Context } from "hono";
1415
import { createRemoteApp } from "../../../core/mcp/remote/node/server.ts";
1516
import { createSandboxController } from "./sandbox-controller.js";
1617
import { injectAuthToken } from "./inject-auth-token.js";
@@ -61,33 +62,47 @@ export async function startHonoServer(
6162
return apiApp.fetch(c.req.raw);
6263
});
6364

65+
// Serve index.html with the API token injected so a reload at any bare URL
66+
// (no `?MCP_INSPECTOR_API_TOKEN=…`) still authenticates against /api/*.
67+
// No-op when auth is dangerously omitted (empty token). The dev Vite plugin
68+
// applies the same injection via `transformIndexHtml`. `Cache-Control:
69+
// no-store` keeps a browser/proxy from serving a page that carries a stale
70+
// token after a server restart regenerates it (randomBytes per start).
71+
const serveIndexHtml = (c: Context) => {
72+
const indexPath = join(rootPath, "index.html");
73+
const html = readFileSync(indexPath, "utf-8");
74+
c.header("Cache-Control", "no-store");
75+
return c.html(injectAuthToken(html, resolvedAuthToken));
76+
};
77+
6478
app.get("/", async (c) => {
6579
try {
66-
const indexPath = join(rootPath, "index.html");
67-
const html = readFileSync(indexPath, "utf-8");
68-
// Embed the API token so a reload at the bare URL (no
69-
// `?MCP_INSPECTOR_API_TOKEN=…`) still authenticates against /api/*.
70-
// No-op when auth is dangerously omitted (empty token). The dev Vite
71-
// plugin applies the same injection via `transformIndexHtml`.
72-
return c.html(injectAuthToken(html, resolvedAuthToken));
80+
return serveIndexHtml(c);
7381
} catch (error) {
7482
console.error("Error serving index.html:", error);
7583
return c.notFound();
7684
}
7785
});
7886

79-
app.use(
80-
"/*",
81-
serveStatic({
82-
root: rootPath,
83-
rewriteRequestPath: (path) => {
84-
if (!path.includes(".") && !path.startsWith("/api")) {
85-
return "/index.html";
86-
}
87-
return path;
88-
},
89-
}),
90-
);
87+
// Real static assets (paths with a file extension). Missing files fall
88+
// through to the SPA fallback below via `next()`.
89+
app.use("/*", serveStatic({ root: rootPath }));
90+
91+
// SPA deep-link fallback: any non-/api route that didn't resolve to a static
92+
// asset (e.g. `/oauth/callback`, the OAuth landing URL) serves the *injected*
93+
// index.html — not the raw file — so bookmarks and hand-typed reloads at
94+
// those paths get the token global too, matching the `/` route.
95+
app.get("*", async (c) => {
96+
if (c.req.path.startsWith("/api")) {
97+
return c.notFound();
98+
}
99+
try {
100+
return serveIndexHtml(c);
101+
} catch (error) {
102+
console.error("Error serving index.html:", error);
103+
return c.notFound();
104+
}
105+
});
91106

92107
const httpServer = serve(
93108
{

‎clients/web/src/App.tsx‎

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -79,27 +79,33 @@ const redirectUrlProvider: RedirectUrlProvider = {
7979
// as a fallback for pasted full URLs and older integrations.
8080
// 3. sessionStorage — backstop for SPA navigations / OAuth round-trips that
8181
// land without either of the above.
82-
// The URL value is persisted to sessionStorage so a later navigation that
83-
// drops it from the bar still authenticates.
82+
// Both the injected global and the URL value are persisted to sessionStorage
83+
// so a later navigation that drops them (e.g. a deep-link load that wasn't
84+
// injected, or an iframe) still authenticates from the backstop.
8485
function getAuthToken(): string | undefined {
8586
if (typeof window === "undefined") return undefined;
8687
const STORAGE_KEY = API_SERVER_ENV_VARS.AUTH_TOKEN;
88+
// Best-effort persistence — sessionStorage may be unavailable (privacy
89+
// mode, iframe sandboxing, etc.); the resolved value still works for the
90+
// current page load regardless.
91+
const persist = (token: string): void => {
92+
try {
93+
window.sessionStorage.setItem(STORAGE_KEY, token);
94+
} catch {
95+
// ignore — see note above
96+
}
97+
};
8798
const fromGlobal = (window as unknown as Record<string, unknown>)[
8899
INSPECTOR_API_TOKEN_GLOBAL
89100
];
90101
if (typeof fromGlobal === "string" && fromGlobal) {
102+
persist(fromGlobal);
91103
return fromGlobal;
92104
}
93105
const params = new URLSearchParams(window.location.search);
94106
const fromUrl = params.get(API_SERVER_ENV_VARS.AUTH_TOKEN);
95107
if (fromUrl) {
96-
try {
97-
window.sessionStorage.setItem(STORAGE_KEY, fromUrl);
98-
} catch {
99-
// Best-effort persistence — sessionStorage may be unavailable
100-
// (privacy mode, iframe sandboxing, etc.); the URL value still
101-
// works for the current page load.
102-
}
108+
persist(fromUrl);
103109
return fromUrl;
104110
}
105111
try {

‎clients/web/src/test/integration/server/server-token-injection.test.ts‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,8 @@ const INDEX_HTML =
4444
"<!doctype html><html><head><title>Inspector</title></head>" +
4545
'<body><div id="root"></div><script type="module" src="/src/main.tsx"></script></body></html>';
4646

47+
const ASSET_JS = 'console.log("static asset");\n';
48+
4749
describe("startHonoServer index.html token injection (/ -> /api/*)", () => {
4850
let handle: WebServerHandle;
4951
let baseUrl: string;
@@ -52,6 +54,9 @@ describe("startHonoServer index.html token injection (/ -> /api/*)", () => {
5254
beforeAll(async () => {
5355
staticRoot = await mkdtemp(join(tmpdir(), "inspector-inject-"));
5456
await writeFile(join(staticRoot, "index.html"), INDEX_HTML, "utf-8");
57+
// A real static asset (path has a file extension) to prove serveStatic
58+
// still serves files verbatim rather than routing them through injection.
59+
await writeFile(join(staticRoot, "asset.js"), ASSET_JS, "utf-8");
5560

5661
const port = await findFreePort();
5762
baseUrl = `http://127.0.0.1:${port}`;
@@ -100,4 +105,40 @@ describe("startHonoServer index.html token injection (/ -> /api/*)", () => {
100105
const apiRes = await fetch(`${baseUrl}/api/config`);
101106
expect(apiRes.status).toBe(401);
102107
});
108+
109+
it("injects the token into the SPA deep-link fallback (e.g. /oauth/callback)", async () => {
110+
// A non-/api path with no file extension resolves to the SPA fallback,
111+
// which must serve the *injected* index.html — not a raw file — so a
112+
// bookmark or reload at the OAuth callback URL still authenticates.
113+
const res = await fetch(`${baseUrl}/oauth/callback?code=abc&state=xyz`);
114+
expect(res.status).toBe(200);
115+
const html = await res.text();
116+
expect(tokenFromHtml(html)).toBe(TOKEN);
117+
});
118+
119+
it("sets Cache-Control: no-store on injected HTML so a restart's new token isn't served stale", async () => {
120+
const root = await fetch(`${baseUrl}/`);
121+
expect(root.headers.get("cache-control")).toBe("no-store");
122+
const fallback = await fetch(`${baseUrl}/oauth/callback`);
123+
expect(fallback.headers.get("cache-control")).toBe("no-store");
124+
});
125+
126+
it("serves real static assets verbatim (no token injection)", async () => {
127+
const res = await fetch(`${baseUrl}/asset.js`);
128+
expect(res.status).toBe(200);
129+
const body = await res.text();
130+
expect(body).toBe(ASSET_JS);
131+
expect(body).not.toContain(INSPECTOR_API_TOKEN_GLOBAL);
132+
});
133+
134+
it("does not route /api paths through the SPA fallback", async () => {
135+
// An unknown /api route must 404 as JSON-less notFound, never the HTML
136+
// shell (which would mask real API errors behind a 200 page).
137+
const res = await fetch(`${baseUrl}/api/does-not-exist`, {
138+
headers: { "x-mcp-remote-auth": `Bearer ${TOKEN}` },
139+
});
140+
expect(res.status).toBe(404);
141+
const body = await res.text();
142+
expect(body).not.toContain(INSPECTOR_API_TOKEN_GLOBAL);
143+
});
103144
});

0 commit comments

Comments
 (0)