inspector/core/mcp/remote/node/server.ts
Cliff Hall 0ead1deea6
feat(core): port v1.5 InspectorClient + transports + auth subsystem (#1302) (#1306)
* wip(core): bulk-copy v1.5 InspectorClient runtime files (#1302)

Verbatim ports from origin/v1.5/main into v2/main core/:

- logging/ (2 files)
- storage/ + storage/adapters/ (4 files)
- auth/ + auth/browser/ + auth/node/ + auth/remote/ (16 files)
- mcp/config.ts + mcp/node/ (4 files, stdio transport)
- mcp/remote/ + mcp/remote/node/ (12 files, HTTP/SSE transport)
- mcp/inspectorClient.ts (~2169 LOC), messageTrackingTransport,
  fetchTracking, oauthManager, index, state/index

Total: ~7,800 LOC of source files, copied unmodified via
`git show origin/v1.5/main:<path> > <dest>`.

Also:
- Add deps: pino, hono, @hono/node-server, atomically, zustand, @types/node
- tsconfig.app.json: extend paths to resolve new node-only deps from
  core/, add "node" to types, disable erasableSyntaxOnly (v1.5 code
  uses parameter properties — TODO to re-enable in follow-up)

Compiles down to 47 type errors, all in three categories:
- 24 TS2305: v2 dropped v1.5 type exports (InspectorClientOptions,
  CreateTransport, InspectorClientEnvironment, AppRendererClient,
  SamplingCreateMessage class, ElicitationCreateMessage class,
  jsonUtils helpers, OAuth events). Per user direction, will re-add
  these to v2's diverged files (types.ts, samplingCreateMessage.ts,
  etc.) so the ported code stays verbatim.
- 15 TS7006: implicit-any params in v1.5 code (v1.5 tsconfig was
  looser than v2's noImplicitAny). Need explicit annotations.
- 8 other TS errors: ../package.json import, Transport|null narrowing,
  hono Context generic mismatch, one unused parameter.

Tests not yet ported (19 files, ~11,170 LOC).

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

* wip(core): integrate ported v1.5 InspectorClient + port tests (#1302)

Source integration (typecheck + build now pass):
- Re-add v1.5 types/classes dropped during v2 evolution:
  - types.ts: CreateTransport*, AppRendererClient, InspectorClient{Environment,Options}
  - samplingCreateMessage.ts / elicitationCreateMessage.ts: classes + keep v2's
    InspectorPending{Sampling,Elicitation} interface
  - inspectorClientEventTarget.ts: oauth* event keys
  - json/jsonUtils.ts: convertParameterValue / convertToolParameters /
    convertPromptArguments + ParameterSchema
- inspectorClient.ts: replace `../package.json` import (v2 has no
  core/package.json) with a hardcoded identity constant
- remote/node/server.ts: cast hono Context for streamSSE (hono's
  generic typing tightened since v1.5)
- oauth-callback-server.ts: drop unused hostname field
- tsconfig: enable @types/node, add paths for new bare-module deps
  (pino, zustand, hono, atomically) in app + test configs
- vite.config.ts: mirror those module aliases for the unit project
  (which runs from repoRoot)

Tests ported (19 files, ~11K LOC) under clients/web/src/test/core/:
- All core/__tests__/auth/* (7 files)
- inspectorClient.test.ts + 4 OAuth variants
- mcp/oauthManager.test.ts, jsonUtils.test.ts
- transport, remote-transport, remote-server-config, storage-adapters
- helpers/oauth-client-fixtures.ts
Bulk-rewrote `from "../mcp/…"` → `from "@inspector/core/mcp/…"` etc.

Current state:
- typecheck: 0 errors
- build: passes (vite v8, 788 modules)
- unit tests: 1014 / 1034 pass (937 pre-existing + 77 new core tests)
- 20 failures in 13 files; failure modes:
  - 13 file-load failures needing the v1.5 `test-servers/` package
    (@modelcontextprotocol/inspector-test-server) which isn't in v2 yet
    or real fs/network not available in happy-dom
  - 7 assertion failures in discovery.test.ts + state-machine.test.ts
    (SDK 1.29 vs 1.25 API drift — mocks don't match new shape)

Coverage gate not yet checked against new files.

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

* wip(core): port test-servers, more types, partial test integration (#1302)

- Port v1.5 test-servers/ package (12 files, ~5K LOC) under
  repo-root/test-servers/, wire @modelcontextprotocol/inspector-test-server
  alias in both vite.config.ts (regex form) and tsconfig.test.json.
- Add deps: express ^5, yaml ^2, @types/express ^5.
- Re-export InspectorClientOptions/Environment/Transport* from inspectorClient.ts
  so v1.5 tests that import them from that module path keep resolving.
- Switch InspectorClientEventMap to use SamplingCreateMessage /
  ElicitationCreateMessage classes (matches v1.5 event payload contracts)
  while keeping the InspectorPending{Sampling,Elicitation} interfaces in
  the *.ts modules for v2 consumers that still use them.
- Fix verbatim-module-syntax issue in test-servers and drop unused stdio
  config field.
- Adjust inspectorClient.test.ts task types to TaskWithOptionalCreatedAt
  (SDK 1.29 tightened Task shape vs v1.5's 1.25).
- Drop spurious maxMessages/maxFetchRequests/maxStderrLogEvents from
  remote-transport.test.ts (never on InspectorClientOptions).

State:
- typecheck: 0 errors
- build: passes
- unit tests: 1099 / 1270 pass
- 171 failures in 10 test files, almost all integration tests that need
  real HTTP/fs/network (happy-dom can't host them). Next: add a node-env
  vitest project to run these properly.

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

* feat(core): port v1.5 InspectorClient + transports + auth subsystem (#1302)

Bulk-port of the v1.5 core runtime (~7,800 LOC source + ~16K LOC tests +
~5K LOC test-servers/) into v2. Files copied verbatim from origin/v1.5/main
via `git show >`; only minimal adapters added on the v2 side.

Subsystems landed
-----------------
- core/logging/, core/storage/, core/auth/ (browser + node + remote)
- core/mcp/ runtime: inspectorClient.ts (2169 LOC), oauthManager,
  messageTrackingTransport, fetchTracking, config, index
- core/mcp/node/ (stdio transport)
- core/mcp/remote/ + remote/node/ (HTTP/SSE transport + Hono server)
- test-servers/ package (composable MCP test servers, fixtures, harness)

v2 adapter layer
----------------
- types.ts: append CreateTransport*, AppRendererClient,
  InspectorClient{Environment,Options} (v2 had pruned these — v1.5 needs them)
- samplingCreateMessage / elicitationCreateMessage: keep v1.5 classes AND
  v2's Inspector Pending* interfaces in the same files
- inspectorClientEventTarget: add oauth* event keys; switch pending
  sampling/elicitation payloads to the classes (matches v1.5 contracts)
- json/jsonUtils: append convertParameterValue/convertToolParameters/
  convertPromptArguments + ParameterSchema
- inspectorClient.ts: re-export Options/Environment/Transport* so tests
  that import these from `inspectorClient.js` keep resolving; replace
  `../package.json` import with a hardcoded identity (v2 has no core/package.json)
- remote/node/server.ts: cast hono Context for streamSSE (hono generic
  tightened since v1.5)
- oauth-callback-server: drop unused hostname field
- tsconfig.app.json / tsconfig.test.json: add @types/node + paths for
  pino/zustand/hono/@hono/node-server/atomically/express/yaml, disable
  erasableSyntaxOnly (parameter-property syntax from v1.5)
- vite.config.ts: regex-form module aliases (so the package's exports
  field handles subpaths like `hono/streaming`, `zustand/middleware`),
  alias for @modelcontextprotocol/inspector-test-server → test-servers/src

Tests
-----
- 19 v1.5 test files copied under clients/web/src/test/core/,
  imports rewired to @inspector/core/* and @modelcontextprotocol/inspector-test-server
- 1004 unit tests pass; 298 storybook tests pass; coverage gate passes

Known follow-ups (out-of-scope here, tracked in TODOs)
------------------------------------------------------
- 13 integration test files are excluded from the unit project (spawn real
  HTTP/stdio servers; run real OAuth flows; mock SDK auth → happy-dom CORS).
  Needs a node-env vitest project. Files listed under `test.projects[0].test.exclude`.
- Source files exercised only by those integration tests are excluded from
  the coverage gate pending the node-env project. Listed under
  `test.coverage.exclude` with comment.
- Manual smoke tests against real stdio / HTTP / OAuth server per the AC
  on #1302 still need verification locally.

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

* docs/fix: address #1306 review (AGENTS tree, #1307 links, @types/node, .substr)

- AGENTS.md: expand the project-structure tree to include all v1.5-ported
  subsystems (core/auth/{browser,node,remote}, core/storage, core/logging,
  core/mcp/{node,remote/{,node}}, core/mcp/state) plus the new top-level
  test-servers/ directory (with a note about its @modelcontextprotocol/
  inspector-test-server alias).
- vite.config.ts: reference #1307 from both the test exclude block and the
  coverage exclude block so the next person editing either sees the
  marching order for shrinking the lists.
- package.json: restore @types/node to ^24 (an earlier `npm install
  --save-dev @types/node@^22` accidentally pinned it lower than the repo
  was using; nothing here required ^22).
- core/mcp/fetchTracking.ts: replace deprecated .substr(2, 9) with
  .slice(2, 11) to match the convention in core/mcp/inspectorClient.ts.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 15:36:17 -04:00

637 lines
20 KiB
TypeScript

/**
* Hono-based remote server for MCP transports.
* Hosts /api/config, /api/mcp/connect, send, events, disconnect, /api/fetch, /api/log, /api/storage/:storeId.
*/
import { randomBytes, timingSafeEqual } from "node:crypto";
import type pino from "pino";
import {
getDefaultStorageDir,
getStoreFilePath,
validateStoreId,
readStoreFile,
writeStoreFile,
deleteStoreFile,
parseStore,
serializeStore,
} from "../../../storage/store-io.js";
import type { LogEvent } from "pino";
import { Hono } from "hono";
import type { Context, Next } from "hono";
import { streamSSE } from "hono/streaming";
import { createTransportNode } from "../../node/transport.js";
import type { RemoteConnectRequest, RemoteSendRequest } from "../types.js";
import type { MCPServerConfig } from "../../types.js";
import { RemoteSession } from "./remote-session.js";
import type { OAuthClientProvider } from "@modelcontextprotocol/sdk/client/auth.js";
import type { OAuthTokens } from "@modelcontextprotocol/sdk/shared/auth.js";
import { API_SERVER_ENV_VARS } from "../constants.js";
/**
* Shape of the initial config returned by GET /api/config (defaults for client).
*/
export interface InitialConfigPayload {
defaultCommand?: string;
defaultArgs?: string[];
defaultTransport?: string;
defaultServerUrl?: string;
defaultHeaders?: Record<string, string>;
defaultCwd?: string;
defaultEnvironment: Record<string, string>;
}
export interface RemoteServerOptions {
/** Optional auth token. If not provided, uses API_SERVER_ENV_VARS.AUTH_TOKEN env var or generates one. Ignored when dangerouslyOmitAuth is true. */
authToken?: string;
/**
* When true, do not require x-mcp-remote-auth on API routes.
* Origin validation (allowedOrigins) still applies.
* Set via DANGEROUSLY_OMIT_AUTH env var; not recommended for any exposed deployment.
*/
dangerouslyOmitAuth?: boolean;
/** Optional: validate Origin header against allowed origins (for CORS) */
allowedOrigins?: string[];
/** Optional pino file logger. When set, /api/log forwards received events to it. */
logger?: pino.Logger;
/** Optional storage directory for /api/storage/:storeId. Default: ~/.mcp-inspector/storage */
storageDir?: string;
/** Optional sandbox URL for MCP Apps tab. When set, GET /api/config includes sandboxUrl. */
sandboxUrl?: string;
/** Initial config for GET /api/config. Caller must pass this (e.g. from webServerConfigToInitialPayload(config)). */
initialConfig: InitialConfigPayload;
}
export interface CreateRemoteAppResult {
/** The Hono app */
app: Hono;
/** The auth token (from options, env var, or generated). Returned so caller can embed in client. */
authToken: string;
}
/**
* Hono middleware for origin validation (CORS and DNS rebinding protection).
* Validates Origin header against allowedOrigins if provided.
*/
function createOriginMiddleware(allowedOrigins?: string[]) {
return async (c: Context, next: Next) => {
// If no allowedOrigins configured, skip validation (allow all)
if (!allowedOrigins || allowedOrigins.length === 0) {
await next();
return;
}
const origin = c.req.header("origin");
// Handle CORS preflight requests
if (c.req.method === "OPTIONS") {
if (origin && allowedOrigins.includes(origin)) {
c.header("Access-Control-Allow-Origin", origin);
c.header("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
c.header(
"Access-Control-Allow-Headers",
"Content-Type, x-mcp-remote-auth",
);
c.header("Access-Control-Max-Age", "86400"); // 24 hours
return c.body(null, 204);
}
// Invalid origin for preflight - return 403
return c.json(
{
error: "Forbidden",
message:
"Invalid origin. Request blocked to prevent DNS rebinding attacks.",
},
403,
);
}
// For actual requests, validate origin if present
if (origin) {
if (!allowedOrigins.includes(origin)) {
return c.json(
{
error: "Forbidden",
message:
"Invalid origin. Request blocked to prevent DNS rebinding attacks. Configure allowed origins via allowedOrigins option.",
},
403,
);
}
// Set CORS header for allowed origin
c.header("Access-Control-Allow-Origin", origin);
}
// If no origin header (same-origin or non-browser client), allow request
await next();
};
}
/**
* Hono middleware for auth token validation.
* Expects Bearer token format: x-mcp-remote-auth: Bearer <token>
*/
function createAuthMiddleware(authToken: string) {
return async (c: Context, next: Next) => {
const authHeader = c.req.header("x-mcp-remote-auth");
if (!authHeader || !authHeader.startsWith("Bearer ")) {
return c.json(
{
error: "Unauthorized",
message:
"Authentication required. Use the x-mcp-remote-auth header with Bearer token.",
},
401,
);
}
const providedToken = authHeader.substring(7); // Remove 'Bearer ' prefix
const expectedToken = authToken;
// Convert to buffers for timing-safe comparison
const providedBuffer = Buffer.from(providedToken);
const expectedBuffer = Buffer.from(expectedToken);
// Check length first to prevent timing attacks
if (providedBuffer.length !== expectedBuffer.length) {
return c.json(
{
error: "Unauthorized",
message:
"Authentication required. Use the x-mcp-remote-auth header with Bearer token.",
},
401,
);
}
// Perform timing-safe comparison
if (!timingSafeEqual(providedBuffer, expectedBuffer)) {
return c.json(
{
error: "Unauthorized",
message:
"Authentication required. Use the x-mcp-remote-auth header with Bearer token.",
},
401,
);
}
await next();
};
}
/**
* Simple OAuth client provider that just returns tokens.
* Used by remote server to inject Bearer tokens into transport requests.
*/
function createTokenAuthProvider(
tokens: RemoteConnectRequest["oauthTokens"],
): OAuthClientProvider | undefined {
if (!tokens) return undefined;
return {
async tokens(): Promise<OAuthTokens | undefined> {
return tokens as OAuthTokens;
},
// Other methods not needed for transport Bearer token injection
async clientInformation() {
return undefined;
},
async saveTokens() {
// No-op
},
codeVerifier() {
return undefined;
},
async saveCodeVerifier() {
// No-op
},
clear() {
// No-op
},
redirectToAuthorization() {
// No-op
},
state() {
return "";
},
} as unknown as OAuthClientProvider;
}
function forwardLogEvent(
logger: pino.Logger,
logEvent: Partial<LogEvent>,
): void {
const levelLabel = (logEvent?.level?.label ?? "info").toLowerCase();
const method = (logger as unknown as Record<string, unknown>)[levelLabel];
if (typeof method !== "function") return;
const bindings = Object.assign(
{},
...(Array.isArray(logEvent.bindings) ? logEvent.bindings : []),
);
const messages = Array.isArray(logEvent.messages) ? logEvent.messages : [];
if (messages.length === 0) {
(method as (obj: object) => void).call(logger, bindings);
return;
}
const first = messages[0];
if (typeof first === "object" && first !== null && !Array.isArray(first)) {
const obj = { ...bindings, ...(first as Record<string, unknown>) };
const msg = messages[1];
const args = messages.slice(2);
(method as (obj: object, msg?: unknown, ...args: unknown[]) => void).call(
logger,
obj,
msg,
...args,
);
} else {
const msg = messages[0];
const args = messages.slice(1);
(method as (obj: object, msg?: unknown, ...args: unknown[]) => void).call(
logger,
bindings,
msg,
...args,
);
}
}
export function createRemoteApp(
options: RemoteServerOptions,
): CreateRemoteAppResult {
const dangerouslyOmitAuth = !!options.dangerouslyOmitAuth;
// Determine auth token when auth is enabled: options > env var > generate
const authToken = dangerouslyOmitAuth
? ""
: options.authToken ||
process.env[API_SERVER_ENV_VARS.AUTH_TOKEN] ||
randomBytes(32).toString("hex");
const app = new Hono();
const sessions = new Map<string, RemoteSession>();
const { logger: fileLogger, allowedOrigins } = options;
const storageDir = options.storageDir ?? getDefaultStorageDir();
// Apply origin validation middleware first (before auth)
// This prevents DNS rebinding attacks by validating Origin header
app.use("*", createOriginMiddleware(allowedOrigins));
// Apply auth middleware unless dangerously omitted
if (!dangerouslyOmitAuth) {
app.use("*", createAuthMiddleware(authToken));
}
app.get("/api/config", (c) => {
const payload = options.sandboxUrl
? { ...options.initialConfig, sandboxUrl: options.sandboxUrl }
: options.initialConfig;
return c.json(payload);
});
app.post("/api/mcp/connect", async (c) => {
let body: RemoteConnectRequest;
try {
body = (await c.req.json()) as RemoteConnectRequest;
} catch {
return c.json({ error: "Invalid JSON body" }, 400);
}
const config = body.config as MCPServerConfig;
if (!config) {
return c.json({ error: "Missing config" }, 400);
}
const sessionId = crypto.randomUUID();
const session = new RemoteSession(sessionId);
let transport: Awaited<ReturnType<typeof createTransportNode>>["transport"];
try {
// Create authProvider from tokens if provided
const authProvider = createTokenAuthProvider(body.oauthTokens);
const result = createTransportNode(config, {
pipeStderr: true,
onStderr: (entry) => session.onStderr(entry),
onFetchRequest: (entry) => session.onFetchRequest(entry),
authProvider,
});
transport = result.transport;
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
return c.json({ error: `Failed to create transport: ${msg}` }, 500);
}
session.setTransport(transport);
transport.onmessage = (msg) => session.onMessage(msg);
// Track if transport closes/errors during start - this matches local behavior
// If transport.start() throws, we catch it. If it resolves but transport closes immediately,
// we detect that too (process failure after spawn).
let transportFailed = false;
let transportError: string | null = null;
const originalOnclose = transport.onclose;
const originalOnerror = transport.onerror;
// Set up error handlers BEFORE calling start() so we catch failures during start
transport.onerror = (err) => {
transportFailed = true;
transportError = err instanceof Error ? err.message : String(err);
originalOnerror?.(err);
};
transport.onclose = () => {
const session = sessions.get(sessionId);
if (session) {
// Mark transport as dead but don't delete session yet
// We'll notify client via SSE and cleanup when client disconnects
const errorMsg =
transportError || "Transport closed - process may have exited";
session.markTransportDead(errorMsg);
// If no client connected, can cleanup immediately
if (!session.hasEventConsumer()) {
sessions.delete(sessionId);
}
} else {
// Session not created yet - failed during start
transportFailed = true;
transportError =
transportError ||
"Transport closed during start - process may have failed";
}
originalOnclose?.();
};
try {
// transport.start() should throw if process fails to start
// If it resolves, the process should be running
await transport.start();
// Check if transport failed during start (onerror/onclose fired synchronously)
if (transportFailed) {
const errorMsg = transportError || "Transport failed during start";
return c.json({ error: `Failed to start transport: ${errorMsg}` }, 500);
}
} catch (err) {
// transport.start() threw - this is the expected failure path
const msg = err instanceof Error ? err.message : String(err);
// Preserve 401 only when the transport/SDK reports it (no message guessing)
const status =
(err as { code?: number; status?: number }).code ??
(err as { code?: number; status?: number }).status;
const is401 = status === 401;
return c.json(
{ error: `Failed to start transport: ${msg}` },
is401 ? 401 : 500,
);
}
// Transport started successfully - add to sessions
sessions.set(sessionId, session);
return c.json({ sessionId });
});
app.post("/api/mcp/send", async (c) => {
let body: RemoteSendRequest & { sessionId?: string };
try {
body = (await c.req.json()) as RemoteSendRequest & { sessionId?: string };
} catch {
return c.json({ error: "Invalid JSON body" }, 400);
}
const { sessionId, message, relatedRequestId } = body;
if (!sessionId || !message) {
return c.json({ error: "Missing sessionId or message" }, 400);
}
const session = sessions.get(sessionId);
if (!session) {
return c.json({ error: "Session not found" }, 404);
}
// Check if transport is dead - return error immediately (matches local behavior)
if (session.isTransportDead()) {
const errorMsg = session.getTransportError() || "Transport closed";
return c.json({ error: errorMsg }, 500);
}
try {
await session.transport.send(message, {
relatedRequestId: relatedRequestId as string | number | undefined,
});
return c.json({ ok: true });
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
// Preserve 401 only when the transport/SDK reports it (no message guessing)
const status =
(err as { code?: number; status?: number }).code ??
(err as { code?: number; status?: number }).status;
const is401 = status === 401;
return c.json({ error: msg }, is401 ? 401 : 500);
}
});
app.get("/api/mcp/events", async (c) => {
const sessionId = c.req.query("sessionId");
if (!sessionId) {
return c.json({ error: "Missing sessionId query" }, 400);
}
const session = sessions.get(sessionId);
if (!session) {
return c.json({ error: "Session not found" }, 404);
}
// hono's streamSSE generic typing has tightened since v1.5; cast the
// route-typed Context down to the broader Context shape it expects.
return streamSSE(c as unknown as Parameters<typeof streamSSE>[0], async (stream) => {
session.setEventConsumer((event) => {
const data = JSON.stringify(event);
void stream.writeSSE({
event: event.type,
data,
});
});
stream.onAbort(() => {
// Client disconnected - clear event consumer
const shouldCleanup = session.clearEventConsumer();
stream.close();
// If transport is dead and no client connected, cleanup session
if (shouldCleanup || session.isTransportDead()) {
sessions.delete(sessionId);
}
});
// Keep the stream open until the client disconnects. Hono's streamSSE
// closes the stream when this callback returns, so we must not return
// until the connection is aborted.
await new Promise<void>((resolve) => {
stream.onAbort(() => {
// Cleanup happens in onAbort handler above
resolve();
});
});
});
});
app.post("/api/mcp/disconnect", async (c) => {
let body: { sessionId?: string };
try {
body = (await c.req.json()) as { sessionId?: string };
} catch {
return c.json({ error: "Invalid JSON body" }, 400);
}
const sessionId = body.sessionId;
if (!sessionId) {
return c.json({ error: "Missing sessionId" }, 400);
}
const session = sessions.get(sessionId);
if (session) {
session.clearEventConsumer();
await session.transport.close();
sessions.delete(sessionId);
}
return c.json({ ok: true });
});
app.post("/api/fetch", async (c) => {
let body: {
url: string;
method?: string;
headers?: Record<string, string>;
body?: string;
};
try {
body = (await c.req.json()) as typeof body;
} catch {
return c.json({ error: "Invalid JSON body" }, 400);
}
const { url, method = "GET", headers = {}, body: reqBody } = body;
if (!url) {
return c.json({ error: "Missing url" }, 400);
}
try {
const res = await fetch(url, {
method,
headers: new Headers(headers),
body: reqBody,
});
const resHeaders: Record<string, string> = {};
res.headers.forEach((v, k) => {
resHeaders[k] = v;
});
const contentType = res.headers.get("content-type");
const isStream =
contentType?.includes("text/event-stream") ||
contentType?.includes("application/x-ndjson");
let resBody: string | undefined;
if (!isStream && res.body) {
resBody = await res.text();
}
return c.json({
ok: res.ok,
status: res.status,
statusText: res.statusText,
headers: resHeaders,
body: resBody,
});
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
return c.json({ error: msg }, 500);
}
});
app.post("/api/log", async (c) => {
const body = (await c.req.json().catch(() => ({}))) as Partial<LogEvent>;
if (fileLogger) {
forwardLogEvent(fileLogger, body);
}
return c.json({ ok: true });
});
app.get("/api/storage/:storeId", async (c) => {
const storeId = c.req.param("storeId");
if (!storeId || !validateStoreId(storeId)) {
return c.json({ error: "Invalid storeId" }, 400);
}
const filePath = getStoreFilePath(storageDir, storeId);
try {
const raw = await readStoreFile(filePath);
if (raw === null) {
return c.json({}, 200);
}
const store = parseStore(raw);
return c.json(store);
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
return c.json({ error: `Failed to read store: ${msg}` }, 500);
}
});
app.post("/api/storage/:storeId", async (c) => {
const storeId = c.req.param("storeId");
if (!storeId || !validateStoreId(storeId)) {
return c.json({ error: "Invalid storeId" }, 400);
}
let body: unknown;
try {
body = await c.req.json();
} catch {
return c.json({ error: "Invalid JSON body" }, 400);
}
const filePath = getStoreFilePath(storageDir, storeId);
try {
const jsonData = serializeStore(body);
await writeStoreFile(filePath, jsonData);
return c.json({ ok: true });
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
return c.json({ error: `Failed to write store: ${msg}` }, 500);
}
});
app.delete("/api/storage/:storeId", async (c) => {
const storeId = c.req.param("storeId");
if (!storeId || !validateStoreId(storeId)) {
return c.json({ error: "Invalid storeId" }, 400);
}
const filePath = getStoreFilePath(storageDir, storeId);
try {
await deleteStoreFile(filePath);
return c.json({ ok: true });
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
return c.json({ error: `Failed to delete store: ${msg}` }, 500);
}
});
return { app, authToken };
}