Closes #1950 Before this, a box with no reachable OS keychain — the published container (no D-Bus session, #1848), Android/Termux (no platform binary, #1905), a minimal Linux install without libsecret — could not persist an OAuth client secret or a stdio `env:` value at all. `KeyringSecretStore` degraded into a store that silently holds nothing: `get` returned null, `delete` no-opped, and `set` hard-failed with a 503. That is the correct failure behavior, but it left the documented, supported way to run the Inspector with no secret persistence whatsoever. Adds the two missing implementations and, more importantly, the policy that picks one and the surfaces that say which was picked. - `FileSecretStore` — one `0600` JSON document at `~/.mcp-inspector/secrets.json`, encrypted with AES-256-GCM whenever `MCP_INSPECTOR_SECRET_KEY` is set (scrypt, per-file random salt). The whole map is encrypted as a unit rather than value-by-value so the account names — `${serverId}:${field}` — are hidden too; a per-value scheme would leave a readable index of which servers you hold a client secret for. A file that can no longer be decrypted reads as empty (matching the interface's read tolerance) but *refuses to be written*, because replacing a file of still-valid secrets to satisfy an additive request destroys data. - `secret-store-selection.ts` — the policy. `MCP_INSPECTOR_SECRET_STORE=keyring|file|memory` wins outright; otherwise probe the keychain and, if unreachable, fall back loudly. The fallback is `memory` in a container whose secrets directory is not on a mount, and `file` otherwise — so mounting the volume the README already recommends for the catalog flips the same run to durable storage with no configuration, and an unmounted container gets the honest answer rather than a file `--rm` will discard. Cached per process so the banner, `/api/config`, and the store doing the writing cannot disagree. - Automatic, but never silent. The downgrade prints at startup, rides `GET /api/config`, and is named in a permanent 32px footer at the bottom of both dialogs that accept a secret. A startup banner is seen once by whoever started the process; a toast is seen once; a dismissible banner is the thing a user dismisses before doing the work it describes. The plaintext and memory cases render their caveat inline in a warning tone — a warning you must hover to discover is not one. - `SecretStoreUnavailableError` is now the base every store's `set` throws, so the routes translate one condition into a 503 instead of matching `KeychainUnavailableError` by name. Docs: the container section of the root README gains a table of which store you get and how to make secrets survive, plus the `MCP_INSPECTOR_SECRET_KEY` upgrade/mismatch rules. Tests: the existing interface contract block is extracted to `secretStoreContract.ts` and run against all three implementations, so none can drift on the availability contract. `FileSecretStore` is tested against a real temp filesystem — mode, cross-instance round-trip, that the ciphertext does not contain the plaintext, the read-modify-write race, and every refusal path. Full `npm run ci` passes, per-file gate included. Signed-off-by: cliffhall <cliff@futurescale.com>
165 lines
5.7 KiB
TypeScript
165 lines
5.7 KiB
TypeScript
/**
|
|
* Hono production server. Export startHonoServer(config) for in-process use by
|
|
* the runner. The server is started programmatically via `runWeb` (in
|
|
* `run-web.ts`), which is the bundled `build/index.js` entry the `mcp-inspector`
|
|
* bin invokes — there is no separate standalone server entry.
|
|
*/
|
|
|
|
import { readFileSync } from "node:fs";
|
|
import { join, dirname } from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
import { randomBytes } from "node:crypto";
|
|
import { serve } from "@hono/node-server";
|
|
import { serveStatic } from "@hono/node-server/serve-static";
|
|
import { Hono } from "hono";
|
|
import type { Context } from "hono";
|
|
import { createRemoteApp } from "../../../core/mcp/remote/node/server.ts";
|
|
import { formatHostForUrl } from "../../../core/node/hostUrl.ts";
|
|
import { createSandboxController } from "./sandbox-controller.js";
|
|
import { injectAuthToken } from "./inject-auth-token.js";
|
|
import type { WebServerConfig } from "./web-server-config.js";
|
|
import { getSecretStorageInfo } from "../../../core/auth/node/secret-store-selection.ts";
|
|
import {
|
|
webServerConfigToInitialPayload,
|
|
printServerBanner,
|
|
openBrowser,
|
|
} from "./web-server-config.js";
|
|
import type { WebServerHandle } from "./types.js";
|
|
|
|
export type { WebServerHandle };
|
|
|
|
const __filename = fileURLToPath(import.meta.url);
|
|
const __dirname = dirname(__filename);
|
|
|
|
/**
|
|
* Start the Hono production server in-process. Returns a handle that closes sandbox then HTTP server.
|
|
* Caller owns SIGINT/SIGTERM; do not register signal handlers here.
|
|
*/
|
|
export async function startHonoServer(
|
|
config: WebServerConfig,
|
|
): Promise<WebServerHandle> {
|
|
const sandboxController = createSandboxController({
|
|
port: config.sandboxPort,
|
|
host: config.sandboxHost,
|
|
allowedOrigins: config.allowedOrigins,
|
|
});
|
|
await sandboxController.start();
|
|
|
|
const resolvedAuthToken =
|
|
config.authToken ||
|
|
(config.dangerouslyOmitAuth ? "" : randomBytes(32).toString("hex"));
|
|
|
|
const rootPath = config.staticRoot ?? __dirname;
|
|
// Resolve the secret store before the API is built so the descriptor the
|
|
// browser reads (`/api/config`) and the one the banner prints come from the
|
|
// same resolution — the selection is cached, so this is also the only place
|
|
// the keychain probe actually runs.
|
|
const secretStorage = await getSecretStorageInfo();
|
|
|
|
const { app: apiApp, close: closeApi } = createRemoteApp({
|
|
authToken: config.dangerouslyOmitAuth ? undefined : resolvedAuthToken,
|
|
dangerouslyOmitAuth: config.dangerouslyOmitAuth,
|
|
storageDir: config.storageDir,
|
|
mcpConfigPath: config.mcpConfigPath,
|
|
writable: config.writable,
|
|
initialServers: config.initialServers ?? undefined,
|
|
allowedOrigins: config.allowedOrigins,
|
|
sandboxUrl: sandboxController.getUrl() ?? undefined,
|
|
logger: config.logger,
|
|
initialConfig: webServerConfigToInitialPayload(config, secretStorage),
|
|
});
|
|
|
|
const app = new Hono();
|
|
app.use("/api/*", async (c) => {
|
|
return apiApp.fetch(c.req.raw);
|
|
});
|
|
|
|
// Serve index.html with the API token injected so a reload at any bare URL
|
|
// (no `?MCP_INSPECTOR_API_TOKEN=…`) still authenticates against /api/*.
|
|
// No-op when auth is dangerously omitted (empty token). The dev Vite plugin
|
|
// applies the same injection via `transformIndexHtml`. `Cache-Control:
|
|
// no-store` keeps a browser/proxy from serving a page that carries a stale
|
|
// token after a server restart regenerates it (randomBytes per start).
|
|
const serveIndexHtml = (c: Context) => {
|
|
const indexPath = join(rootPath, "index.html");
|
|
const html = readFileSync(indexPath, "utf-8");
|
|
c.header("Cache-Control", "no-store");
|
|
return c.html(injectAuthToken(html, resolvedAuthToken));
|
|
};
|
|
|
|
app.get("/", async (c) => {
|
|
try {
|
|
return serveIndexHtml(c);
|
|
} catch (error) {
|
|
console.error("Error serving index.html:", error);
|
|
return c.notFound();
|
|
}
|
|
});
|
|
|
|
// Real static assets (paths with a file extension). Missing files fall
|
|
// through to the SPA fallback below via `next()`.
|
|
app.use("/*", serveStatic({ root: rootPath }));
|
|
|
|
// SPA deep-link fallback: any non-/api route that didn't resolve to a static
|
|
// asset (e.g. `/oauth/callback`, the OAuth landing URL) serves the *injected*
|
|
// index.html — not the raw file — so bookmarks and hand-typed reloads at
|
|
// those paths get the token global too, matching the `/` route.
|
|
app.get("*", async (c) => {
|
|
if (c.req.path.startsWith("/api")) {
|
|
return c.notFound();
|
|
}
|
|
try {
|
|
return serveIndexHtml(c);
|
|
} catch (error) {
|
|
console.error("Error serving index.html:", error);
|
|
return c.notFound();
|
|
}
|
|
});
|
|
|
|
const httpServer = serve(
|
|
{
|
|
fetch: app.fetch,
|
|
port: config.port,
|
|
hostname: config.hostname,
|
|
},
|
|
(info) => {
|
|
const sandboxUrl = sandboxController.getUrl();
|
|
const url = printServerBanner(
|
|
config,
|
|
info.port,
|
|
resolvedAuthToken,
|
|
sandboxUrl ?? undefined,
|
|
secretStorage,
|
|
);
|
|
if (config.autoOpen) {
|
|
// Never a bare `open(url)`: this callback is synchronous, so a
|
|
// rejection would escape it. See openBrowser.
|
|
openBrowser(url);
|
|
}
|
|
},
|
|
);
|
|
|
|
httpServer.on("error", (err: Error) => {
|
|
if (err.message.includes("EADDRINUSE")) {
|
|
console.error(
|
|
`MCP Inspector PORT IS IN USE at http://${formatHostForUrl(config.hostname)}:${config.port}`,
|
|
);
|
|
process.exit(1);
|
|
} else {
|
|
throw err;
|
|
}
|
|
});
|
|
|
|
return {
|
|
async close(): Promise<void> {
|
|
await closeApi();
|
|
await sandboxController.close();
|
|
if ("closeAllConnections" in httpServer) {
|
|
httpServer.closeAllConnections();
|
|
}
|
|
await new Promise<void>((resolve, reject) => {
|
|
httpServer.close((err) => (err ? reject(err) : resolve()));
|
|
});
|
|
},
|
|
};
|
|
}
|