Spaces:
Running

File size: 4,855 Bytes
6f5f15e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12bb291
 
 
 
 
 
6f5f15e
 
 
 
 
 
 
 
 
 
 
 
e8bfbc2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f5f15e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
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<void> };

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;
}