import { existsSync } from 'node:fs'; import { readFile } from 'node:fs/promises'; import { join } from 'node:path'; import { serveStatic } from '@hono/node-server/serve-static'; import { hostHeaderValidation, localhostOriginValidation, originValidation, } from '@modelcontextprotocol/hono'; import type { McpServerFactory } from '@modelcontextprotocol/server'; import { Hono } from 'hono'; import type { AppConfig } from '../config.js'; import type { RoomRegistryApi } from '../contracts.js'; import { logger } from '../logger.js'; import { createServerFactory } from '../mcp/buildServer.js'; import { PKG_VERSION, UI_DIR } from '../paths.js'; import { mountApiRoutes } from './apiRoutes.js'; import { mountFeedRoute } from './feed.js'; import { mountMcpRoute } from './mcpRoute.js'; export interface AppDeps { rooms: RoomRegistryApi; config: AppConfig; version?: string; uiDir?: string; serverFactory?: McpServerFactory; } const LOCALHOST_BINDS = new Set(['localhost', '127.0.0.1', '::1', '[::1]']); function extractHostname(urlStr: string): string | undefined { try { return new URL(urlStr).hostname; } catch { return undefined; } } function dedupe(items: string[]): string[] { return Array.from(new Set(items.filter((s) => s.length > 0))); } export type WebcamApp = Hono & { close(): Promise }; export function createApp(deps: AppDeps): WebcamApp { const app = new Hono(); const version = deps.version ?? PKG_VERSION; const uiDir = deps.uiDir ?? UI_DIR; const isLocalhostBind = LOCALHOST_BINDS.has(deps.config.host); const mcpHostHostname = deps.config.mcpHostConfigured ? extractHostname(deps.config.mcpHost) : undefined; // 1. Host header validation const shouldValidateHost = isLocalhostBind || deps.config.mcpHostConfigured || deps.config.allowedHosts.length > 0; if (shouldValidateHost) { const allowedHosts = dedupe([ 'localhost', '127.0.0.1', '[::1]', ...(mcpHostHostname ? [mcpHostHostname] : []), ...deps.config.allowedHosts, ]); app.use('*', hostHeaderValidation(allowedHosts)); } else { logger.warn( `Binding to "${deps.config.host}" without MCP_HOST or ALLOWED_HOSTS; Host header validation is disabled.`, ); } // 2. Origin validation on /mcp and non-GET /api/* const hasExplicitOrigins = deps.config.mcpHostConfigured || deps.config.allowedOrigins.length > 0; const originMiddleware = hasExplicitOrigins ? originValidation( dedupe([ 'localhost', '127.0.0.1', '[::1]', ...(mcpHostHostname ? [mcpHostHostname] : []), ...deps.config.allowedOrigins, ]), ) : isLocalhostBind ? localhostOriginValidation() : null; if (originMiddleware) { app.use('/mcp', originMiddleware); app.use('/', async (c, next) => { if (c.req.method === 'GET' || c.req.method === 'HEAD') { return next(); } return originMiddleware(c, next); }); app.use('/api/*', async (c, next) => { if (c.req.method === 'GET' || c.req.method === 'HEAD') { return next(); } return originMiddleware(c, next); }); } // 3. API + Feed + MCP routes mountFeedRoute(app, { rooms: deps.rooms }); mountApiRoutes(app, { rooms: deps.rooms, config: deps.config, version }); const indexPath = join(uiDir, 'index.html'); if (existsSync(uiDir)) { app.get('/mcp', async (c, next) => { const accept = c.req.header('accept') ?? ''; const isBrowserHtml = accept.includes('text/html') && !accept.includes('text/event-stream') && !c.req.header('mcp-protocol-version'); if (isBrowserHtml && existsSync(indexPath)) { const html = await readFile(indexPath, 'utf8'); return c.html(html); } return next(); }); } const serverFactory = deps.serverFactory ?? createServerFactory({ rooms: deps.rooms, config: deps.config, version, }); const mcpRoute = mountMcpRoute(app, { rooms: deps.rooms, serverFactory }); // 4. Static UI assets + SPA fallback if (existsSync(uiDir)) { const staticMiddleware = serveStatic({ root: uiDir }); app.use('*', async (c, next) => { const p = c.req.path; if (p === '/mcp' || p === '/api' || p.startsWith('/api/')) { return next(); } return staticMiddleware(c, next); }); app.get('*', async (c, next) => { const p = c.req.path; if (p === '/mcp' || p === '/api' || p.startsWith('/api/')) { return next(); } if (!existsSync(indexPath)) { return next(); } const html = await readFile(indexPath, 'utf8'); return c.html(html); }); } const webcamApp = app as WebcamApp; webcamApp.close = () => mcpRoute.close(); return webcamApp; }