inspector/core/react/useInitialConfig.ts
cliffhall bc408f5869 feat(auth): file-backed and in-memory SecretStore for hosts with no keychain
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>
2026-08-22 12:06:31 -04:00

152 lines
6.6 KiB
TypeScript

/**
* React hook over the `GET /api/config` endpoint — the single fetch of the
* static `InitialConfigPayload` the dev/prod web backends serve alongside the
* SPA (see `core/mcp/remote/node/server.ts`). It exposes the three fields the
* web app reads off that payload:
*
* - `sandboxUrl` — the MCP Apps sandbox proxy URL. The backend mounts
* `sandbox_proxy.html` on a separate controller port and advertises the URL
* here; the Apps screen embeds it as the trusted outer iframe. `undefined`
* until the fetch resolves, and whenever the backend omits it (legacy backend,
* or a build without the sandbox controller) — callers treat that as "Apps
* unavailable" rather than a blank iframe.
* - `writable` — whether the session's server list is a writable catalog or a
* read-only session (`--config` / ad-hoc `--server-url`). Defaults to `true`
* until the fetch resolves and whenever the field is absent (a legacy backend
* predating the flag), so the default catalog keeps full CRUD.
* - `version` — the Inspector version the backend reads from the root
* `package.json` (the browser can't read it off disk). `undefined` until the
* fetch resolves, and whenever the backend omits it (legacy backend) — the UI
* renders nothing then.
* - `secretStorage` — which store this session's secrets go to (#1950),
* resolved on the Node side where the keychain probe happens. `undefined`
* until the fetch resolves and on a backend that omits it; the settings-modal
* footers render nothing then, because a guessed answer under a secret field
* is worse than no answer.
*
* This consolidates the three former single-field hooks (`useSandboxUrl`,
* `useServerListWritable`, `useInspectorVersion`), each of which fetched the
* same static payload separately, into one request (#1643).
*
* Fetches on mount, and re-fetches if `baseUrl` or `authToken` changes (rare —
* effectively a full reload; the GET is idempotent). A response that resolves
* after unmount or a re-fetch is dropped rather than overwriting current state.
*/
import { useCallback, useEffect, useState } from "react";
import type { SecretStorageInfo } from "../auth/secret-storage-info.js";
export interface UseInitialConfigOptions {
/** Base URL of the remote server (typically `window.location.origin`). */
baseUrl: string;
/** Optional auth token for the `x-mcp-remote-auth` header. */
authToken?: string;
/** Fetch function to use (default: globalThis.fetch). Useful in tests. */
fetchFn?: typeof fetch;
}
export interface UseInitialConfigResult {
/** The Inspector version, or undefined when unavailable / not yet loaded. */
version: string | undefined;
/** The sandbox proxy URL, or undefined when unavailable / not yet loaded. */
sandboxUrl: string | undefined;
/** Whether the server list is writable (catalog) or read-only (session). */
writable: boolean;
/** Where this session's secrets are stored, or undefined when unknown. */
secretStorage: SecretStorageInfo | undefined;
/** True while the initial fetch is in flight. */
loading: boolean;
}
/** Minimal shape we read from the `/api/config` payload. */
interface ConfigPayload {
version?: unknown;
sandboxUrl?: unknown;
writable?: unknown;
secretStorage?: unknown;
}
/**
* Narrow the payload's `secretStorage` before trusting it.
*
* The footer states, in the UI, where a user's secret is about to go, so a
* malformed or partial descriptor must render as "unknown" rather than as a
* confident half-answer — the `kind` alone is what every label and tone
* derives from, so it is the field the check turns on.
*/
function usableSecretStorage(value: unknown): SecretStorageInfo | undefined {
if (typeof value !== "object" || value === null) return undefined;
const kind = (value as { kind?: unknown }).kind;
if (kind !== "keyring" && kind !== "file" && kind !== "memory") {
return undefined;
}
return value as SecretStorageInfo;
}
/** Coerce a payload field to a usable non-empty string, else undefined. */
function usableString(value: unknown): string | undefined {
return typeof value === "string" && value ? value : undefined;
}
export function useInitialConfig(
opts: UseInitialConfigOptions,
): UseInitialConfigResult {
const { baseUrl, authToken, fetchFn } = opts;
const doFetch = fetchFn ?? globalThis.fetch;
const base = baseUrl.replace(/\/$/, "");
const [version, setVersion] = useState<string | undefined>(undefined);
const [sandboxUrl, setSandboxUrl] = useState<string | undefined>(undefined);
// Default writable so the common (catalog) case shows CRUD immediately and a
// legacy backend that omits the field keeps working.
const [writable, setWritable] = useState<boolean>(true);
const [secretStorage, setSecretStorage] = useState<
SecretStorageInfo | undefined
>(undefined);
const [loading, setLoading] = useState<boolean>(true);
// `isCancelled` lets the effect drop a response that resolves after unmount or
// after a re-run (baseUrl/authToken change), so a stale payload can't overwrite
// current state. React 18 no longer warns on setState-after-unmount — it's a
// silent no-op — so the guard is about correctness, not the warning.
const load = useCallback(
async (isCancelled: () => boolean): Promise<void> => {
const headers: Record<string, string> = {};
if (authToken) headers["x-mcp-remote-auth"] = `Bearer ${authToken}`;
try {
const res = await doFetch(`${base}/api/config`, {
method: "GET",
headers,
});
if (isCancelled() || !res.ok) return;
const body = (await res.json()) as ConfigPayload;
if (isCancelled()) return;
// Tolerate missing/non-usable fields — a legacy backend that omits any
// of them leaves that value at its "unavailable" default rather than
// showing a bogus value.
setVersion(usableString(body.version));
setSandboxUrl(usableString(body.sandboxUrl));
// Only an explicit `false` makes the list read-only; a missing field
// (legacy backend) stays writable.
setWritable(body.writable !== false);
setSecretStorage(usableSecretStorage(body.secretStorage));
} catch {
// Network error / aborted fetch: leave every field at its default
// (version/sandboxUrl undefined, writable true).
} finally {
if (!isCancelled()) setLoading(false);
}
},
[base, authToken, doFetch],
);
useEffect(() => {
let cancelled = false;
void load(() => cancelled);
return () => {
cancelled = true;
};
}, [load]);
return { version, sandboxUrl, writable, secretStorage, loading };
}