diff --git a/Dockerfile b/Dockerfile index 769a480f..ccee00ec 100644 --- a/Dockerfile +++ b/Dockerfile @@ -91,6 +91,7 @@ ENV NODE_ENV=production ENV HOST=0.0.0.0 ENV PORT=5003 ENV OPENCODE_SERVER_PORT=5551 +ENV DEV_PREVIEW_PORT=3056 ENV DATABASE_PATH=/app/data/opencode.db ENV WORKSPACE_PATH=/workspace ENV XDG_CACHE_HOME=/home/node/.cache @@ -112,7 +113,7 @@ RUN chmod +x /docker-entrypoint.sh RUN mkdir -p /workspace /app/data /home/node/.cache /home/node/.opencode && \ chown -R node:node /workspace /app/data /home/node -EXPOSE 5003 3055 +EXPOSE 5003 3055 3056 HEALTHCHECK --interval=30s --timeout=3s --start-period=40s --retries=3 \ CMD curl -f http://localhost:5003/api/health || exit 1 diff --git a/backend/src/db/queries.ts b/backend/src/db/queries.ts index 623696b2..2a1e85fd 100644 --- a/backend/src/db/queries.ts +++ b/backend/src/db/queries.ts @@ -3,7 +3,6 @@ import type { Repo, CreateRepoInput } from '../types/repo' import { getReposPath } from '@opencode-manager/shared/config/env' import { ASSISTANT_REPO_ID, ASSISTANT_REPO_PATH } from '@opencode-manager/shared/utils' import { getErrorMessage } from '../utils/error-utils' -import type { DevServerConfig } from '@opencode-manager/shared/types' import path from 'path' interface RepoRow { @@ -332,19 +331,6 @@ export function updateRepoBranch(db: Database, id: number, branch: string): void } } -const DEV_SERVER_INJECT_BASE_KEY = 'devServerInjectBase' - -export function getDevServerConfig(db: Database, repoId: number): DevServerConfig { - const injectBase = getRepoSetting(db, repoId, DEV_SERVER_INJECT_BASE_KEY) - return { - injectBase: injectBase === '1', - } -} - -export function setDevServerConfig(db: Database, repoId: number, config: DevServerConfig): void { - setRepoSetting(db, repoId, DEV_SERVER_INJECT_BASE_KEY, config.injectBase ? '1' : null) -} - export function deleteRepo(db: Database, id: number): void { if (id === ASSISTANT_REPO_ID) { return diff --git a/backend/src/index.ts b/backend/src/index.ts index 1423d989..3893ba5c 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -37,9 +37,8 @@ import { createPromptTemplateRoutes } from './routes/prompt-templates' import { createInternalRoutes } from './routes/internal' import { sweepStaleUploadSessions } from './routes/internal/repo-mirror-helpers' import { createOpenCodeProxyRoutes } from './routes/opencode-proxy' -import { createDevProxyRoutes } from './routes/dev-proxy' import { createDevServerRoutes } from './routes/dev-server' -import { createDevProxyUpgradeHandler } from './services/dev-server/upgrade-handler' +import { startPreviewServer } from './services/dev-server/preview-server' import { sseAggregator } from './services/sse-aggregator' import { ensureDirectoryExists, writeFileContent, fileExists, readFileContent } from './services/file-operations' import { SettingsService } from './services/settings' @@ -346,7 +345,6 @@ protectedApi.route('/notifications', createNotificationRoutes(notificationServic protectedApi.route('/prompt-templates', createPromptTemplateRoutes(db)) protectedApi.route('/schedules', createScheduleRoutes(scheduleService)) protectedApi.route('/dev-server', createDevServerRoutes(db)) -protectedApi.route('/dev-proxy', createDevProxyRoutes(db)) app.route('/api', protectedApi) @@ -466,12 +464,13 @@ const shutdown = async (signal: string) => { process.on('SIGTERM', () => shutdown('SIGTERM')) process.on('SIGINT', () => shutdown('SIGINT')) -const server = serve({ +serve({ fetch: app.fetch, port: PORT, hostname: HOST, }) -server.on('upgrade', createDevProxyUpgradeHandler(auth, db)) +startPreviewServer(auth, db) logger.info(`🚀 OpenCode WebUI API running on http://${HOST}:${PORT}`) +logger.info(`🔍 Dev preview proxy running on http://${HOST}:${ENV.DEV_PREVIEW.PORT}`) diff --git a/backend/src/routes/dev-proxy.ts b/backend/src/routes/dev-proxy.ts deleted file mode 100644 index 838b0ae5..00000000 --- a/backend/src/routes/dev-proxy.ts +++ /dev/null @@ -1,152 +0,0 @@ -import { Hono, type Context } from 'hono' -import type { Database } from 'bun:sqlite' -import { getDevServerPort } from '../services/dev-server/manager' -import { - parseDevProxyPath, - buildUpstreamUrl, - filterProxyHeaders, - sanitizeUpstreamResponseHeaders, - prepareTransformedResponseHeaders, - isWebSocketUpgrade, - injectBaseTag, - rewriteDevProxyCssPaths, - rewriteDevProxyHtmlPaths, - rewriteDevProxyJavaScriptPaths, - rewriteViteClientHmrBase, - DEV_PROXY_PREFIX, -} from '../services/dev-server/proxy-utils' -import { getDevServerConfig } from '../db/queries' - -function getNotRunningHtml(port: number): string { - return ` - -Dev Server Not Running - -

Dev Server Not Running

-

No development server responded on localhost:${port}.

-

Go back

- -` -} - -export function createDevProxyRoutes(db: Database): Hono { - const app = new Hono() - - app.all('/:repoId', async (c) => { - return handleProxyRequest(c, db) - }) - - app.all('/:repoId/*', async (c) => { - return handleProxyRequest(c, db) - }) - - return app -} - -async function handleProxyRequest(c: Context, db: Database): Promise { - const repoId = parseInt(c.req.param('repoId'), 10) - if (isNaN(repoId)) { - return c.json({ error: 'Invalid repoId' }, 400) - } - - const port = getDevServerPort(db) - - if (isWebSocketUpgrade((key: string) => c.req.header(key))) { - return c.json({ error: 'WebSocket handled by upgrade listener' }, 426) - } - - const url = new URL(c.req.url) - const parsed = parseDevProxyPath(url.pathname) ?? parseMountedDevProxyPath(url.pathname, repoId) - if (!parsed) { - return c.json({ error: 'Invalid proxy path' }, 400) - } - - const upstreamUrl = buildUpstreamUrl(port, parsed.rest, url.search) - - const filteredHeaders = filterProxyHeaders(c.req.raw.headers) - delete filteredHeaders['if-none-match'] - delete filteredHeaders['if-modified-since'] - - let requestBody: RequestInit['body'] = undefined - if (c.req.method !== 'GET' && c.req.method !== 'HEAD') { - requestBody = c.req.raw.body - } - - let upstreamResponse: Response - try { - upstreamResponse = await fetch(upstreamUrl, { - method: c.req.method, - headers: filteredHeaders, - body: requestBody, - redirect: 'manual', - duplex: 'half', - }) - } catch { - return c.html(getNotRunningHtml(port), 503) - } - - const sanitizedHeaders = sanitizeUpstreamResponseHeaders(upstreamResponse.headers) - - const contentType = upstreamResponse.headers.get('content-type') ?? '' - - if (contentType.includes('text/html')) { - const config = getDevServerConfig(db, repoId) - const text = await upstreamResponse.text() - const basePath = `${DEV_PROXY_PREFIX}/${repoId}/` - const modified = config.injectBase ? injectBaseTag(text, basePath) : rewriteDevProxyHtmlPaths(text, basePath) - return new Response(modified, { - status: upstreamResponse.status, - statusText: upstreamResponse.statusText, - headers: prepareTransformedResponseHeaders(sanitizedHeaders), - }) - } - - if (isJavaScriptContentType(contentType)) { - const text = await upstreamResponse.text() - const basePath = `${DEV_PROXY_PREFIX}/${repoId}/` - const rewrittenPaths = rewriteDevProxyJavaScriptPaths(text, basePath) - const modified = isViteClientRequest(parsed.rest) - ? rewriteViteClientHmrBase(rewrittenPaths, basePath) - : rewrittenPaths - return new Response(modified, { - status: upstreamResponse.status, - statusText: upstreamResponse.statusText, - headers: prepareTransformedResponseHeaders(sanitizedHeaders), - }) - } - - if (isCssContentType(contentType)) { - const text = await upstreamResponse.text() - const modified = rewriteDevProxyCssPaths(text, `${DEV_PROXY_PREFIX}/${repoId}/`) - return new Response(modified, { - status: upstreamResponse.status, - statusText: upstreamResponse.statusText, - headers: prepareTransformedResponseHeaders(sanitizedHeaders), - }) - } - - return new Response(upstreamResponse.body, { - status: upstreamResponse.status, - statusText: upstreamResponse.statusText, - headers: sanitizedHeaders, - }) -} - -function isViteClientRequest(rest: string): boolean { - return rest === '/@vite/client' -} - -function isJavaScriptContentType(contentType: string): boolean { - return contentType.includes('javascript') || contentType.includes('ecmascript') -} - -function isCssContentType(contentType: string): boolean { - return contentType.includes('text/css') -} - -function parseMountedDevProxyPath(pathname: string, repoId: number): { repoId: number; rest: string } | null { - const prefix = `/${repoId}` - if (pathname !== prefix && !pathname.startsWith(`${prefix}/`)) return null - const rest = pathname.slice(prefix.length) - return { repoId, rest: rest || '/' } -} diff --git a/backend/src/routes/dev-server.ts b/backend/src/routes/dev-server.ts index fa2a0f11..6f7965cb 100644 --- a/backend/src/routes/dev-server.ts +++ b/backend/src/routes/dev-server.ts @@ -1,12 +1,8 @@ import { Hono } from 'hono' import type { Database } from 'bun:sqlite' -import { z } from 'zod' -import { getRepoById, getDevServerConfig, setDevServerConfig } from '../db/queries' +import { getRepoById } from '../db/queries' import { getDevServerState } from '../services/dev-server/manager' - -const UpdateConfigSchema = z.object({ - injectBase: z.boolean(), -}) +import { resolveDevPreviewUrl } from '../services/dev-server/proxy-utils' export function createDevServerRoutes(db: Database): Hono { const app = new Hono() @@ -22,43 +18,11 @@ export function createDevServerRoutes(db: Database): Hono { return c.json({ error: 'Repository not found' }, 404) } - const state = await getDevServerState(db, repo.id) + const previewUrl = resolveDevPreviewUrl(c.req.header('host'), c.req.header('x-forwarded-proto')) + const state = await getDevServerState(db, repo.id, previewUrl) return c.json(state) }) - app.get('/:repoId/config', async (c) => { - const repoId = parseInt(c.req.param('repoId'), 10) - if (isNaN(repoId)) { - return c.json({ error: 'Invalid repoId' }, 400) - } - - const config = getDevServerConfig(db, repoId) - return c.json(config) - }) - - app.put('/:repoId/config', async (c) => { - const repoId = parseInt(c.req.param('repoId'), 10) - if (isNaN(repoId)) { - return c.json({ error: 'Invalid repoId' }, 400) - } - - let body: unknown - try { - body = await c.req.json() - } catch { - return c.json({ error: 'Invalid JSON body' }, 400) - } - - const parsed = UpdateConfigSchema.safeParse(body) - if (!parsed.success) { - return c.json({ error: parsed.error.flatten() }, 400) - } - - setDevServerConfig(db, repoId, parsed.data) - const saved = getDevServerConfig(db, repoId) - return c.json(saved) - }) - return app } diff --git a/backend/src/services/dev-server/manager.ts b/backend/src/services/dev-server/manager.ts index 2a0721a3..91445b58 100644 --- a/backend/src/services/dev-server/manager.ts +++ b/backend/src/services/dev-server/manager.ts @@ -8,7 +8,7 @@ export function getDevServerPort(db: Database): number { return port ?? DEFAULT_DEV_SERVER_PORT } -export async function getDevServerState(db: Database, repoId: number): Promise { +export async function getDevServerState(db: Database, repoId: number, previewUrl: string): Promise { const port = getDevServerPort(db) const isRunning = await isPortOpen(port) @@ -17,6 +17,6 @@ export async function getDevServerState(db: Database, repoId: number): Promise + +Sign in required + +

Sign in required

+

Open the preview from an authenticated OpenCode Manager session.

+ +` +} + +function getNotRunningHtml(port: number): string { + return ` + +Dev Server Not Running + +

Dev Server Not Running

+

No development server responded on localhost:${port}.

+ +` +} + +async function hasValidSession(auth: AuthInstance, headers: Headers): Promise { + try { + const session = await auth.api.getSession({ headers }) + return Boolean(session) + } catch { + return false + } +} + +async function handlePreviewRequest(c: Context, auth: AuthInstance, db: Database): Promise { + if (!(await hasValidSession(auth, c.req.raw.headers))) { + return c.html(getUnauthorizedHtml(), 401) + } + + const port = getDevServerPort(db) + const url = new URL(c.req.url) + const upstreamUrl = buildUpstreamUrl(port, url.pathname, url.search) + + const headers = filterProxyHeaders(c.req.raw.headers) + let body: RequestInit['body'] = undefined + if (c.req.method !== 'GET' && c.req.method !== 'HEAD') { + body = c.req.raw.body + } + + let upstreamResponse: Response + try { + upstreamResponse = await fetch(upstreamUrl, { + method: c.req.method, + headers, + body, + redirect: 'manual', + duplex: 'half', + } as RequestInit) + } catch { + return c.html(getNotRunningHtml(port), 503) + } + + return new Response(upstreamResponse.body, { + status: upstreamResponse.status, + statusText: upstreamResponse.statusText, + headers: sanitizeUpstreamResponseHeaders(upstreamResponse.headers), + }) +} + +export function buildPreviewUpgradeRequest(rawHead: string, port: number): string { + const lines = rawHead.split('\r\n') + if (lines.length === 0 || (lines.length === 1 && lines[0] === '')) return rawHead + + const result: string[] = [lines[0]!] + for (let i = 1; i < lines.length; i++) { + const line = lines[i]! + const colonIdx = line.indexOf(':') + if (colonIdx !== -1 && line.slice(0, colonIdx).trim().toLowerCase() === 'host') continue + result.push(line) + } + result.push(`Host: 127.0.0.1:${port}`) + return result.join('\r\n') +} + +function nodeHeadersToWebHeaders(reqHeaders: IncomingMessage['headers']): Headers { + const headers = new Headers() + for (const [key, value] of Object.entries(reqHeaders)) { + if (value === undefined) continue + if (Array.isArray(value)) { + for (const v of value) headers.append(key, v) + } else { + headers.set(key, value) + } + } + return headers +} + +function rawHeadFromRequest(req: IncomingMessage): string { + const lines: string[] = [`${req.method} ${req.url} HTTP/1.1`] + for (const [key, value] of Object.entries(req.headers)) { + if (value === undefined) continue + if (Array.isArray(value)) { + for (const v of value) lines.push(`${key}: ${v}`) + } else { + lines.push(`${key}: ${value}`) + } + } + return lines.join('\r\n') +} + +function createPreviewUpgradeHandler(auth: AuthInstance, db: Database) { + return async (req: IncomingMessage, socket: Duplex, head: Buffer): Promise => { + try { + if (!(await hasValidSession(auth, nodeHeadersToWebHeaders(req.headers)))) { + socket.write('HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n') + socket.destroy() + return + } + + const port = getDevServerPort(db) + const upstreamRequest = buildPreviewUpgradeRequest(rawHeadFromRequest(req), port) + const upstream = net.connect(port, '127.0.0.1') + + upstream.on('connect', () => { + upstream.write(`${upstreamRequest}\r\n\r\n`) + if (head.length > 0) upstream.write(head) + socket.pipe(upstream) + upstream.pipe(socket) + }) + + upstream.on('error', () => socket.destroy()) + socket.on('error', () => upstream.destroy()) + socket.on('close', () => upstream.destroy()) + upstream.on('close', () => socket.destroy()) + } catch (error) { + logger.error('Dev preview upgrade handler error:', error) + socket.destroy() + } + } +} + +export function startPreviewServer(auth: AuthInstance, db: Database): ServerType { + const app = new Hono() + app.all('/*', (c) => handlePreviewRequest(c, auth, db)) + + const server = serve({ + fetch: app.fetch, + port: ENV.DEV_PREVIEW.PORT, + hostname: ENV.SERVER.HOST, + }) + + server.on('upgrade', createPreviewUpgradeHandler(auth, db)) + return server +} diff --git a/backend/src/services/dev-server/proxy-utils.ts b/backend/src/services/dev-server/proxy-utils.ts index a7e4ac97..efe76716 100644 --- a/backend/src/services/dev-server/proxy-utils.ts +++ b/backend/src/services/dev-server/proxy-utils.ts @@ -1,4 +1,4 @@ -export const DEV_PROXY_PREFIX = '/api/dev-proxy' +import { ENV } from '@opencode-manager/shared/config/env' const HOP_BY_HOP_HEADERS = new Set([ 'connection', @@ -14,14 +14,10 @@ const HOP_BY_HOP_HEADERS = new Set([ 'host', ]) -export function parseDevProxyPath(pathname: string): { repoId: number; rest: string } | null { - const match = pathname.match(/^\/api\/dev-proxy\/(\d+)(\/.*)?$/) - if (!match) return null - return { repoId: parseInt(match[1]!, 10), rest: match[2] ?? '/' } -} +const FRAME_BLOCKING_HEADERS = new Set(['x-frame-options', 'content-security-policy']) -export function buildUpstreamUrl(port: number, rest: string, search: string): string { - return `http://127.0.0.1:${port}${rest}${search}` +export function buildUpstreamUrl(port: number, path: string, search: string): string { + return `http://127.0.0.1:${port}${path}${search}` } export function filterProxyHeaders(headers: Headers): Record { @@ -35,11 +31,10 @@ export function filterProxyHeaders(headers: Headers): Record { } export function sanitizeUpstreamResponseHeaders(headers: Headers): Record { - const blocked = new Set(['x-frame-options', 'content-security-policy']) const result: Record = {} headers.forEach((value, key) => { const lower = key.toLowerCase() - if (!HOP_BY_HOP_HEADERS.has(lower) && !blocked.has(lower)) { + if (!HOP_BY_HOP_HEADERS.has(lower) && !FRAME_BLOCKING_HEADERS.has(lower)) { result[key] = value } }) @@ -47,132 +42,28 @@ export function sanitizeUpstreamResponseHeaders(headers: Headers): Record): Record { - const result = { ...headers } - delete result.etag - delete result.ETag - delete result['last-modified'] - delete result['Last-Modified'] - result['cache-control'] = 'no-store' - return result +export function resolveDevPreviewUrl(requestHost: string | undefined, forwardedProto: string | undefined): string { + const publicUrl = ENV.DEV_PREVIEW.PUBLIC_URL.trim() + if (publicUrl) { + return publicUrl.endsWith('/') ? publicUrl : `${publicUrl}/` + } + + const hostname = stripPort(requestHost) || 'localhost' + const protocol = normalizeProtocol(forwardedProto) + return `${protocol}://${hostname}:${ENV.DEV_PREVIEW.PORT}/` } -export function isWebSocketUpgrade(headerGet: (k: string) => string | undefined): boolean { - const connection = headerGet('connection')?.toLowerCase() ?? '' - const upgrade = headerGet('upgrade')?.toLowerCase() ?? '' - return connection.includes('upgrade') && upgrade === 'websocket' +function stripPort(host: string | undefined): string { + if (!host) return '' + const trimmed = host.trim() + if (trimmed.startsWith('[')) { + const closing = trimmed.indexOf(']') + return closing === -1 ? trimmed : trimmed.slice(0, closing + 1) + } + return trimmed.replace(/:\d+$/, '') } -export function injectBaseTag(html: string, basePath: string): string { - const htmlWithRewrittenPaths = rewriteDevProxyHtmlPaths(html, basePath) - if (/]*>/i) - if (!match) return htmlWithRewrittenPaths - - const idx = match.index! + match[0].length - return htmlWithRewrittenPaths.slice(0, idx) + `` + htmlWithRewrittenPaths.slice(idx) +function normalizeProtocol(forwardedProto: string | undefined): string { + const proto = forwardedProto?.split(',')[0]?.trim().toLowerCase() + return proto === 'https' ? 'https' : 'http' } - -export function rewriteDevProxyHtmlPaths(html: string, basePath: string): string { - const rewrittenAttributes = html.replace( - /\b(src|href|action|poster)=(['"])(\/[^/][^'"]*)\2/gi, - (match, attribute: string, quote: string, path: string, offset: number, fullHtml: string) => { - if (isBaseTagAttribute(fullHtml, offset)) return match - const proxiedPath = toDevProxyPath(path, basePath) - if (proxiedPath === path) return match - return `${attribute}=${quote}${proxiedPath}${quote}` - } - ) - - const rewrittenSrcSets = rewrittenAttributes.replace( - /\bsrcset=(['"])([^'"]*)\1/gi, - (_match, quote: string, value: string) => { - const rewrittenValue = value - .split(',') - .map((candidate) => rewriteSrcSetCandidate(candidate, basePath)) - .join(',') - return `srcset=${quote}${rewrittenValue}${quote}` - } - ) - - return rewriteCssUrlReferences(rewrittenSrcSets, basePath) -} - -export function rewriteViteClientHmrBase(js: string, basePath: string): string { - const normalizedBasePath = basePath.endsWith('/') ? basePath : `${basePath}/` - - return js.replace( - /(\$\{\s*hmrPort\s*\|\|\s*importMetaUrl\.port\s*\}\$\{)(['"])([^'"]*)\2(\})/, - (match, prefix: string, quote: string, hmrBase: string, suffix: string) => { - if (hmrBase.startsWith(normalizedBasePath)) return match - const hmrBasePath = hmrBase.startsWith('/') ? hmrBase.slice(1) : hmrBase - const proxiedHmrBase = `${normalizedBasePath}${hmrBasePath}` - return `${prefix}${quote}${proxiedHmrBase}${quote}${suffix}` - } - ) -} - -export function rewriteDevProxyJavaScriptPaths(js: string, basePath: string): string { - const rewrittenStaticImports = js.replace( - /\b((?:import|export)\s+(?:[^'"]*?\s+from\s+)?)(['"])(\/[^/][^'"]*)\2/g, - (match, prefix: string, quote: string, path: string) => { - const proxiedPath = toDevProxyPath(path, basePath) - if (proxiedPath === path) return match - return `${prefix}${quote}${proxiedPath}${quote}` - } - ) - - return rewrittenStaticImports.replace( - /\b(import\(\s*)(['"])(\/[^/][^'"]*)\2(\s*\))/g, - (match, prefix: string, quote: string, path: string, suffix: string) => { - const proxiedPath = toDevProxyPath(path, basePath) - if (proxiedPath === path) return match - return `${prefix}${quote}${proxiedPath}${quote}${suffix}` - } - ) -} - -export function rewriteDevProxyCssPaths(css: string, basePath: string): string { - return rewriteCssUrlReferences(css, basePath) -} - -function rewriteCssUrlReferences(content: string, basePath: string): string { - const rewrittenUrls = content.replace( - /\burl\(\s*(['"]?)(\/(?!\/)[^)'"]*)\1\s*\)/gi, - (match, quote: string, path: string) => { - const proxiedPath = toDevProxyPath(path, basePath) - if (proxiedPath === path) return match - return `url(${quote}${proxiedPath}${quote})` - } - ) - - return rewrittenUrls.replace( - /(@import\s+)(['"])(\/(?!\/)[^'"]*)\2/gi, - (match, prefix: string, quote: string, path: string) => { - const proxiedPath = toDevProxyPath(path, basePath) - if (proxiedPath === path) return match - return `${prefix}${quote}${proxiedPath}${quote}` - } - ) -} - -function rewriteSrcSetCandidate(candidate: string, basePath: string): string { - const match = candidate.match(/^(\s*)(\/\S+)(.*)$/) - if (!match) return candidate - const [, leading = '', path = '', descriptor = ''] = match - return `${leading}${toDevProxyPath(path, basePath)}${descriptor}` -} - -function toDevProxyPath(path: string, basePath: string): string { - const normalizedBasePath = basePath.endsWith('/') ? basePath.slice(0, -1) : basePath - if (path === normalizedBasePath || path.startsWith(`${normalizedBasePath}/`)) return path - return `${normalizedBasePath}${path}` -} - -function isBaseTagAttribute(html: string, attributeOffset: number): boolean { - const tagStart = html.lastIndexOf('<', attributeOffset) - if (tagStart === -1) return false - return /^<\s*base\b/i.test(html.slice(tagStart, attributeOffset)) -} - diff --git a/backend/src/services/dev-server/upgrade-handler.ts b/backend/src/services/dev-server/upgrade-handler.ts deleted file mode 100644 index 68e8eb7f..00000000 --- a/backend/src/services/dev-server/upgrade-handler.ts +++ /dev/null @@ -1,125 +0,0 @@ -import type { IncomingMessage } from 'http' -import type { Duplex } from 'stream' -import type { Database } from 'bun:sqlite' -import net from 'net' -import type { AuthInstance } from '../../auth' -import { getDevServerPort } from './manager' -import { parseDevProxyPath } from './proxy-utils' -import { logger } from '../../utils/logger' - -export function buildUpstreamUpgradeRequest(rawHead: string, rest: string, port: number): string { - const lines = rawHead.split('\r\n') - if (lines.length === 0 || (lines.length === 1 && lines[0] === '')) return rawHead - - const requestLine = lines[0]! - const parts = requestLine.split(' ') - const rewrittenLine = `${parts[0]} ${rest} ${parts.slice(2).join(' ')}` - - const result: string[] = [rewrittenLine] - - for (let i = 1; i < lines.length; i++) { - const line = lines[i]! - const colonIdx = line.indexOf(':') - if (colonIdx !== -1) { - const headerName = line.slice(0, colonIdx).trim().toLowerCase() - if (headerName === 'host') continue - } - result.push(line) - } - - result.push(`Host: 127.0.0.1:${port}`) - - return result.join('\r\n') -} - -function nodeHeadersToWebHeaders(reqHeaders: IncomingMessage['headers']): Headers { - const headers = new Headers() - for (const [key, value] of Object.entries(reqHeaders)) { - if (value !== undefined) { - if (Array.isArray(value)) { - for (const v of value) { - headers.append(key, v) - } - } else { - headers.set(key, value) - } - } - } - return headers -} - -export function createDevProxyUpgradeHandler(auth: AuthInstance, db: Database) { - return async (req: IncomingMessage, socket: Duplex, head: Buffer): Promise => { - try { - const url = req.url ?? '' - const parsed = parseDevProxyPath(url) - if (!parsed) { - socket.destroy() - return - } - - const headers = nodeHeadersToWebHeaders(req.headers) - let session - try { - session = await auth.api.getSession({ headers }) - } catch { - socket.destroy() - return - } - - if (!session) { - socket.write('HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n') - socket.destroy() - return - } - - const port = getDevServerPort(db) - - const rawHeadLines: string[] = [`${req.method} ${req.url} HTTP/1.1`] - for (const [key, value] of Object.entries(req.headers)) { - if (value !== undefined) { - if (Array.isArray(value)) { - for (const v of value) { - rawHeadLines.push(`${key}: ${v}`) - } - } else { - rawHeadLines.push(`${key}: ${value}`) - } - } - } - const rawHead = rawHeadLines.join('\r\n') - - const upstreamRequest = buildUpstreamUpgradeRequest(rawHead, parsed.rest, port) - - const upstream = net.connect(port, '127.0.0.1') - - upstream.on('connect', () => { - upstream.write(upstreamRequest + '\r\n\r\n') - if (head.length > 0) { - upstream.write(head) - } - socket.pipe(upstream) - upstream.pipe(socket) - }) - - upstream.on('error', () => { - socket.destroy() - }) - - socket.on('error', () => { - upstream.destroy() - }) - - socket.on('close', () => { - upstream.destroy() - }) - - upstream.on('close', () => { - socket.destroy() - }) - } catch (error) { - logger.error('Dev proxy upgrade handler error:', error) - socket.destroy() - } - } -} diff --git a/backend/test/routes/dev-server.test.ts b/backend/test/routes/dev-server.test.ts index fb30185e..64d506f2 100644 --- a/backend/test/routes/dev-server.test.ts +++ b/backend/test/routes/dev-server.test.ts @@ -1,4 +1,4 @@ -import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' +import { describe, it, expect, vi, beforeEach } from 'vitest' vi.mock('../../src/services/dev-server/manager', () => ({ getDevServerState: vi.fn(), @@ -7,15 +7,11 @@ vi.mock('../../src/services/dev-server/manager', () => ({ vi.mock('../../src/db/queries', () => ({ getRepoById: vi.fn(), - getDevServerConfig: vi.fn(), - setDevServerConfig: vi.fn(), })) import { getDevServerState } from '../../src/services/dev-server/manager' -import { getRepoById, getDevServerConfig, setDevServerConfig } from '../../src/db/queries' +import { getRepoById } from '../../src/db/queries' import { createDevServerRoutes } from '../../src/routes/dev-server' -import { createDevProxyRoutes } from '../../src/routes/dev-proxy' -import { injectBaseTag, rewriteDevProxyHtmlPaths, rewriteDevProxyJavaScriptPaths, rewriteViteClientHmrBase } from '../../src/services/dev-server/proxy-utils' describe('DevServer Management Routes', () => { let devServerApp: ReturnType @@ -37,229 +33,31 @@ describe('DevServer Management Routes', () => { expect(body.error).toBe('Repository not found') }) - it('returns configured preview port status', async () => { + it('returns 400 for invalid repoId', async () => { + const res = await devServerApp.fetch(new Request('http://localhost/abc/status')) + expect(res.status).toBe(400) + }) + + it('returns status with an absolute preview url derived from the request host', async () => { const mockRepo = { id: 1, fullPath: '/test/repo', repoUrl: null, localPath: '/test/repo' } vi.mocked(getRepoById).mockReturnValue(mockRepo as any) - const mockState = { - repoId: 1, + vi.mocked(getDevServerState).mockImplementation(async (_db, repoId, previewUrl) => ({ + repoId, status: 'running' as const, port: 5100, error: null, - previewPath: '/api/dev-proxy/1/', - } - vi.mocked(getDevServerState).mockResolvedValue(mockState) + previewUrl, + })) - const res = await devServerApp.fetch(new Request('http://localhost/1/status')) + const res = await devServerApp.fetch(new Request('http://manager.example:5003/1/status', { + headers: { host: 'manager.example:5003' }, + })) expect(res.status).toBe(200) const body = await res.json() as Record expect(body.status).toBe('running') expect(body.port).toBe(5100) - expect(body.previewPath).toBe('/api/dev-proxy/1/') - expect(getDevServerState).toHaveBeenCalledWith(mockDb, 1) - }) - }) - - describe('GET /:repoId/config', () => { - it('returns dev server config for repo', async () => { - vi.mocked(getDevServerConfig).mockReturnValue({ injectBase: true }) - - const res = await devServerApp.fetch(new Request('http://localhost/1/config')) - expect(res.status).toBe(200) - const body = await res.json() as Record - expect(body.injectBase).toBe(true) - }) - - it('returns 400 for invalid repoId', async () => { - const res = await devServerApp.fetch(new Request('http://localhost/abc/config')) - expect(res.status).toBe(400) - }) - }) - - describe('PUT /:repoId/config', () => { - it('rejects body missing injectBase', async () => { - const res = await devServerApp.fetch( - new Request('http://localhost/1/config', { - method: 'PUT', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({}), - }) - ) - expect(res.status).toBe(400) - }) - - it('rejects non-boolean injectBase', async () => { - const res = await devServerApp.fetch( - new Request('http://localhost/1/config', { - method: 'PUT', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ injectBase: 'yes' }), - }) - ) - expect(res.status).toBe(400) - }) - - it('persists valid config and returns saved values', async () => { - vi.mocked(setDevServerConfig).mockImplementation(() => {}) - vi.mocked(getDevServerConfig).mockReturnValue({ injectBase: true }) - - const res = await devServerApp.fetch( - new Request('http://localhost/1/config', { - method: 'PUT', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ injectBase: true }), - }) - ) - expect(res.status).toBe(200) - const body = await res.json() as Record - expect(body.injectBase).toBe(true) - expect(setDevServerConfig).toHaveBeenCalledWith(mockDb, 1, { injectBase: true }) + expect(body.previewUrl).toBe('http://manager.example:3056/') + expect(getDevServerState).toHaveBeenCalledWith(mockDb, 1, 'http://manager.example:3056/') }) }) }) - -describe('DevProxy Routes', () => { - let proxyApp: ReturnType - let mockDb: any - - beforeEach(() => { - vi.clearAllMocks() - mockDb = {} as any - proxyApp = createDevProxyRoutes(mockDb) - }) - - afterEach(() => { - vi.unstubAllGlobals() - }) - - describe('GET /:repoId/ and /:repoId/*', () => { - it('returns 503 HTML when dev server is not running', async () => { - vi.mocked(getDevServerConfig).mockReturnValue({ injectBase: false }) - vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('not running'))) - - const res = await proxyApp.fetch(new Request('http://localhost/1/')) - expect(res.status).toBe(503) - const text = await res.text() - expect(text).toContain('localhost:5100') - expect(res.headers.get('content-type')).toContain('text/html') - }) - - it('returns 503 HTML when dev server is not running (sub-path)', async () => { - vi.mocked(getDevServerConfig).mockReturnValue({ injectBase: false }) - vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('not running'))) - - const res = await proxyApp.fetch(new Request('http://localhost/1/some/page')) - expect(res.status).toBe(503) - const text = await res.text() - expect(text).toContain('Dev Server Not Running') - }) - - it('returns 426 for WebSocket upgrade requests', async () => { - vi.mocked(getDevServerConfig).mockReturnValue({ injectBase: false }) - - const res = await proxyApp.fetch(new Request('http://localhost/1/', { - headers: { - Connection: 'Upgrade', - Upgrade: 'websocket', - }, - })) - expect(res.status).toBe(426) - const body = await res.json() as Record - expect(body.error).toContain('WebSocket') - }) - - it('rewrites Vite client HMR websocket base to stay under the dev proxy prefix', async () => { - vi.mocked(getDevServerConfig).mockReturnValue({ injectBase: false }) - vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response( - 'import "/node_modules/vite/dist/client/env.mjs"; const socketHost = `${__HMR_HOSTNAME__ || importMetaUrl.hostname}:${hmrPort || importMetaUrl.port}${"/"}`', - { headers: { 'content-type': 'application/javascript' } } - ))) - - const res = await proxyApp.fetch(new Request('http://localhost/1/@vite/client')) - const text = await res.text() - - expect(text).toContain('${"/api/dev-proxy/1/"}') - expect(text).toContain('import "/api/dev-proxy/1/node_modules/vite/dist/client/env.mjs"') - }) - - it('rewrites root absolute HTML paths even when base injection is disabled', async () => { - vi.mocked(getDevServerConfig).mockReturnValue({ injectBase: false }) - const fetchMock = vi.fn().mockResolvedValue(new Response( - '', - { headers: { 'content-type': 'text/html', etag: 'upstream-etag' } } - )) - vi.stubGlobal('fetch', fetchMock) - - const res = await proxyApp.fetch(new Request('http://localhost/1/', { - headers: { - 'if-none-match': 'cached-etag', - 'if-modified-since': 'Sun, 21 Jun 2026 18:23:30 GMT', - }, - })) - const text = await res.text() - const upstreamRequest = fetchMock.mock.calls[0]?.[1] as RequestInit - const upstreamHeaders = upstreamRequest.headers as Record - - expect(text).toContain('href="/api/dev-proxy/1/src/style.css"') - expect(text).toContain('src="/api/dev-proxy/1/src/tetris.js"') - expect(text).not.toContain(' { - vi.mocked(getDevServerConfig).mockReturnValue({ injectBase: false }) - vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response( - '@import "/reset.css"; .hero{background:url(/assets/hero.png)}', - { headers: { 'content-type': 'text/css', etag: 'css-etag' } } - ))) - - const res = await proxyApp.fetch(new Request('http://localhost/1/assets/app.css')) - const text = await res.text() - - expect(text).toContain('@import "/api/dev-proxy/1/reset.css"') - expect(text).toContain('url(/api/dev-proxy/1/assets/hero.png)') - expect(res.headers.get('etag')).toBeNull() - expect(res.headers.get('cache-control')).toBe('no-store') - }) - }) -}) - -describe('DevProxy HTML rewriting', () => { - it('keeps absolute Vite module paths under the dev proxy prefix', () => { - const html = '' - - const rewritten = injectBaseTag(html, '/api/dev-proxy/1/') - - expect(rewritten).toContain('src="/api/dev-proxy/1/@vite/client"') - expect(rewritten).toContain('src="/api/dev-proxy/1/src/main.tsx"') - }) - - it('rewrites absolute paths without injecting a base tag', () => { - const html = '' - - const rewritten = rewriteDevProxyHtmlPaths(html, '/api/dev-proxy/1/') - - expect(rewritten).toContain('src="/api/dev-proxy/1/src/tetris.js"') - expect(rewritten).not.toContain(' { - const js = 'const socketHost = `${__HMR_HOSTNAME__ || importMetaUrl.hostname}:${hmrPort || importMetaUrl.port}${"/"}`' - - const rewritten = rewriteViteClientHmrBase(js, '/api/dev-proxy/1/') - - expect(rewritten).toContain('${"/api/dev-proxy/1/"}') - }) - - it('keeps JavaScript module paths under the dev proxy prefix', () => { - const js = 'import "/node_modules/vite/dist/client/env.mjs"; export { game } from "/src/game.js"; import("/src/lazy.js")' - - const rewritten = rewriteDevProxyJavaScriptPaths(js, '/api/dev-proxy/1/') - - expect(rewritten).toContain('import "/api/dev-proxy/1/node_modules/vite/dist/client/env.mjs"') - expect(rewritten).toContain('from "/api/dev-proxy/1/src/game.js"') - expect(rewritten).toContain('import("/api/dev-proxy/1/src/lazy.js")') - }) -}) diff --git a/backend/test/services/dev-server/preview-server.test.ts b/backend/test/services/dev-server/preview-server.test.ts new file mode 100644 index 00000000..6bd06bdb --- /dev/null +++ b/backend/test/services/dev-server/preview-server.test.ts @@ -0,0 +1,26 @@ +import { describe, it, expect } from 'vitest' +import { buildPreviewUpgradeRequest } from '../../../src/services/dev-server/preview-server' + +describe('buildPreviewUpgradeRequest', () => { + it('preserves the request line and forces the loopback host', () => { + const rawHead = [ + 'GET /_next/webpack-hmr HTTP/1.1', + 'Host: manager.example:3056', + 'Upgrade: websocket', + 'Connection: Upgrade', + ].join('\r\n') + + const result = buildPreviewUpgradeRequest(rawHead, 3055) + const lines = result.split('\r\n') + + expect(lines[0]).toBe('GET /_next/webpack-hmr HTTP/1.1') + expect(result).toContain('Upgrade: websocket') + expect(result).toContain('Connection: Upgrade') + expect(result).toContain('Host: 127.0.0.1:3055') + expect(result).not.toContain('Host: manager.example:3056') + }) + + it('returns the raw head unchanged when empty', () => { + expect(buildPreviewUpgradeRequest('', 3055)).toBe('') + }) +}) diff --git a/backend/test/services/dev-server/proxy-utils.test.ts b/backend/test/services/dev-server/proxy-utils.test.ts index d84c74fb..ebfcfccd 100644 --- a/backend/test/services/dev-server/proxy-utils.test.ts +++ b/backend/test/services/dev-server/proxy-utils.test.ts @@ -1,337 +1,68 @@ import { describe, it, expect } from 'vitest' import { - DEV_PROXY_PREFIX, - parseDevProxyPath, buildUpstreamUrl, filterProxyHeaders, sanitizeUpstreamResponseHeaders, - isWebSocketUpgrade, - injectBaseTag, - rewriteDevProxyCssPaths, - rewriteDevProxyHtmlPaths, - rewriteDevProxyJavaScriptPaths, + resolveDevPreviewUrl, } from '../../../src/services/dev-server/proxy-utils' -describe('DEV_PROXY_PREFIX', () => { - it('is /api/dev-proxy', () => { - expect(DEV_PROXY_PREFIX).toBe('/api/dev-proxy') - }) -}) - -describe('parseDevProxyPath', () => { - it('parses path with repo id and subpath', () => { - const result = parseDevProxyPath('/api/dev-proxy/12/assets/x.js') - expect(result).toEqual({ repoId: 12, rest: '/assets/x.js' }) - }) - - it('parses path with only repo id', () => { - const result = parseDevProxyPath('/api/dev-proxy/12') - expect(result).toEqual({ repoId: 12, rest: '/' }) - }) - - it('parses path with repo id and trailing slash', () => { - const result = parseDevProxyPath('/api/dev-proxy/12/') - expect(result).toEqual({ repoId: 12, rest: '/' }) - }) - - it('returns null for path without dev-proxy prefix', () => { - expect(parseDevProxyPath('/api/files')).toBeNull() - }) - - it('returns null for path with non-numeric repo id', () => { - expect(parseDevProxyPath('/api/dev-proxy/abc')).toBeNull() - }) - - it('returns null when repo id segment is empty', () => { - expect(parseDevProxyPath('/api/dev-proxy/')).toBeNull() - }) - - it('returns null for unrelated path', () => { - expect(parseDevProxyPath('/api/other/12/file.js')).toBeNull() - }) - - it('parses multi-digit port numbers', () => { - const result = parseDevProxyPath('/api/dev-proxy/12345/assets') - expect(result).toEqual({ repoId: 12345, rest: '/assets' }) - }) - - it('parses path with special characters in rest', () => { - const result = parseDevProxyPath('/api/dev-proxy/1/@fs/src/main.tsx') - expect(result).toEqual({ repoId: 1, rest: '/@fs/src/main.tsx' }) - }) -}) - describe('buildUpstreamUrl', () => { - it('builds url with search params', () => { - const result = buildUpstreamUrl(5173, '/assets/x.js', '?v=1') - expect(result).toBe('http://127.0.0.1:5173/assets/x.js?v=1') - }) - - it('builds url without search params', () => { - const result = buildUpstreamUrl(5173, '/', '') - expect(result).toBe('http://127.0.0.1:5173/') - }) - - it('builds url with query string', () => { - const result = buildUpstreamUrl(3000, '/api/data', '?foo=bar&baz=1') - expect(result).toBe('http://127.0.0.1:3000/api/data?foo=bar&baz=1') - }) - - it('uses 127.0.0.1 as hostname', () => { - const result = buildUpstreamUrl(8080, '/', '') - expect(result).toMatch(/^http:\/\/127\.0\.0\.1:/) + it('targets the loopback dev server with path and search', () => { + expect(buildUpstreamUrl(3055, '/_next/static/chunk.js', '?v=1')).toBe( + 'http://127.0.0.1:3055/_next/static/chunk.js?v=1' + ) }) }) describe('filterProxyHeaders', () => { - it('removes hop-by-hop headers', () => { + it('drops hop-by-hop and host headers', () => { const headers = new Headers({ + host: 'manager.example', + connection: 'keep-alive', 'content-type': 'text/html', - 'connection': 'keep-alive', - 'upgrade': 'websocket', - 'cache-control': 'no-cache', + accept: '*/*', }) - const result = filterProxyHeaders(headers) - expect(result).toHaveProperty('content-type') - expect(result).toHaveProperty('cache-control') - expect(result).not.toHaveProperty('connection') - expect(result).not.toHaveProperty('upgrade') - }) - it('removes all hop-by-hop headers case-insensitively', () => { - const headers = new Headers({ - 'Connection': 'close', - 'Transfer-Encoding': 'chunked', - 'Content-Length': '100', - 'Host': 'example.com', - }) const result = filterProxyHeaders(headers) - expect(Object.keys(result)).toHaveLength(0) - }) - it('preserves non-hop-by-hop headers', () => { - const headers = new Headers({ - 'accept': 'application/json', - 'user-agent': 'test', - 'referer': 'http://example.com', - }) - const result = filterProxyHeaders(headers) - expect(result).toHaveProperty('accept') - expect(result).toHaveProperty('user-agent') - expect(result).toHaveProperty('referer') - }) - - it('returns empty object for empty headers', () => { - const result = filterProxyHeaders(new Headers()) - expect(Object.keys(result)).toHaveLength(0) + expect(result.host).toBeUndefined() + expect(result.connection).toBeUndefined() + expect(result['content-type']).toBe('text/html') + expect(result.accept).toBe('*/*') }) }) describe('sanitizeUpstreamResponseHeaders', () => { - it('strips hop-by-hop headers', () => { - const headers = new Headers({ - 'content-type': 'text/html', - 'connection': 'keep-alive', - 'x-frame-options': 'DENY', - }) - const result = sanitizeUpstreamResponseHeaders(headers) - expect(result).toHaveProperty('content-type') - expect(result).not.toHaveProperty('connection') - }) - - it('removes x-frame-options', () => { + it('strips framing/security headers and forces no-referrer', () => { const headers = new Headers({ 'content-type': 'text/html', 'x-frame-options': 'DENY', + 'content-security-policy': "frame-ancestors 'none'", }) - const result = sanitizeUpstreamResponseHeaders(headers) - expect(result).not.toHaveProperty('x-frame-options') - }) - it('removes content-security-policy', () => { - const headers = new Headers({ - 'content-type': 'text/html', - 'content-security-policy': "default-src 'self'", - }) const result = sanitizeUpstreamResponseHeaders(headers) - expect(result).not.toHaveProperty('content-security-policy') - }) - it('handles case-insensitive blocked header names', () => { - const headers = new Headers({ - 'X-Frame-Options': 'SAMEORIGIN', - 'Content-Security-Policy': "default-src 'self'", - }) - const result = sanitizeUpstreamResponseHeaders(headers) - expect(result).not.toHaveProperty('X-Frame-Options') - expect(result).not.toHaveProperty('Content-Security-Policy') - }) - - it('adds referrer-policy: no-referrer', () => { - const headers = new Headers({ 'content-type': 'text/plain' }) - const result = sanitizeUpstreamResponseHeaders(headers) + expect(result['content-type']).toBe('text/html') + expect(result['x-frame-options']).toBeUndefined() + expect(result['content-security-policy']).toBeUndefined() expect(result['referrer-policy']).toBe('no-referrer') }) - - it('overwrites upstream referrer-policy', () => { - const headers = new Headers({ - 'referrer-policy': 'origin', - }) - const result = sanitizeUpstreamResponseHeaders(headers) - expect(result['referrer-policy']).toBe('no-referrer') - }) - - it('preserves allowed headers', () => { - const headers = new Headers({ - 'content-type': 'application/json', - 'cache-control': 'public', - 'etag': '"abc123"', - }) - const result = sanitizeUpstreamResponseHeaders(headers) - expect(result).toHaveProperty('content-type') - expect(result).toHaveProperty('cache-control') - expect(result).toHaveProperty('etag') - }) }) -describe('isWebSocketUpgrade', () => { - it('returns true for websocket upgrade', () => { - const headerGet = (k: string) => - ({ connection: 'Upgrade', upgrade: 'websocket' })[k] - expect(isWebSocketUpgrade(headerGet)).toBe(true) +describe('resolveDevPreviewUrl', () => { + it('derives the preview origin from the request host and preview port', () => { + expect(resolveDevPreviewUrl('manager.example:5003', undefined)).toBe('http://manager.example:3056/') }) - it('handles case-insensitive connection header', () => { - const headerGet = (k: string) => - ({ connection: 'upgrade', upgrade: 'websocket' })[k] - expect(isWebSocketUpgrade(headerGet)).toBe(true) + it('honours the forwarded protocol', () => { + expect(resolveDevPreviewUrl('manager.example:5003', 'https')).toBe('https://manager.example:3056/') }) - it('returns false when connection does not include upgrade', () => { - const headerGet = (k: string) => - ({ connection: 'keep-alive', upgrade: 'websocket' })[k] - expect(isWebSocketUpgrade(headerGet)).toBe(false) + it('handles bracketed IPv6 hosts', () => { + expect(resolveDevPreviewUrl('[::1]:5003', undefined)).toBe('http://[::1]:3056/') }) - it('returns false when upgrade is not websocket', () => { - const headerGet = (k: string) => - ({ connection: 'Upgrade', upgrade: 'h2c' })[k] - expect(isWebSocketUpgrade(headerGet)).toBe(false) - }) - - it('returns false when both headers are missing', () => { - const headerGet = () => undefined - expect(isWebSocketUpgrade(headerGet)).toBe(false) - }) - - it('returns false when connection header is missing', () => { - const headerGet = (k: string) => - ({ upgrade: 'websocket' })[k] - expect(isWebSocketUpgrade(headerGet)).toBe(false) - }) - - it('returns false when upgrade header is missing', () => { - const headerGet = (k: string) => - ({ connection: 'Upgrade' })[k] - expect(isWebSocketUpgrade(headerGet)).toBe(false) - }) -}) - -describe('injectBaseTag', () => { - it('injects base tag after ', () => { - const html = '' - const result = injectBaseTag(html, '/api/dev-proxy/3/') - expect(result).toBe('') - }) - - it('injects base tag after with attributes', () => { - const html = '' - const result = injectBaseTag(html, '/api/dev-proxy/3/') - expect(result).toBe('') - }) - - it('is no-op when already present', () => { - const html = '' - const result = injectBaseTag(html, '/api/dev-proxy/3/') - expect(result).toBe(html) - }) - - it('is no-op when no tag exists', () => { - const html = 'no head' - const result = injectBaseTag(html, '/api/dev-proxy/3/') - expect(result).toBe(html) - }) - - it('handles uppercase HEAD tag', () => { - const html = '' - const result = injectBaseTag(html, '/proxy/') - expect(result).toBe('') - }) - - it('injects after with newline after', () => { - const html = '\n Test\n' - const result = injectBaseTag(html, '/base/') - expect(result).toBe('\n Test\n') - }) - - it('does not inject when appears in non-head context (e.g. body)', () => { - const html = '' - const result = injectBaseTag(html, '/base/') - expect(result).toBe(html) - }) - - it('handles empty string', () => { - const result = injectBaseTag('', '/base/') - expect(result).toBe('') - }) -}) - -describe('dev proxy path rewriting', () => { - it('rewrites common framework HTML asset paths', () => { - const html = '
' - - const result = rewriteDevProxyHtmlPaths(html, '/api/dev-proxy/7/') - - expect(result).toContain('src="/api/dev-proxy/7/_next/image.png"') - expect(result).toContain('srcset="/api/dev-proxy/7/assets/a.png 1x, /api/dev-proxy/7/static/b.png 2x"') - expect(result).toContain('action="/api/dev-proxy/7/api/action"') - }) - - it('rewrites CSS paths in HTML style content', () => { - const html = '
' - - const result = rewriteDevProxyHtmlPaths(html, '/api/dev-proxy/7/') - - expect(result).toContain('url(/api/dev-proxy/7/assets/bg.png)') - expect(result).toContain('@import "/api/dev-proxy/7/theme.css"') - expect(result).toContain('url("/api/dev-proxy/7/img/bg.svg")') - }) - - it('rewrites CSS response paths', () => { - const css = '@import "/reset.css"; .hero{background:url(/assets/hero.png)} .icon{mask:url("/icons/x.svg")}' - - const result = rewriteDevProxyCssPaths(css, '/api/dev-proxy/7/') - - expect(result).toContain('@import "/api/dev-proxy/7/reset.css"') - expect(result).toContain('url(/api/dev-proxy/7/assets/hero.png)') - expect(result).toContain('url("/api/dev-proxy/7/icons/x.svg")') - }) - - it('rewrites JavaScript module paths', () => { - const js = 'import "/runtime.js"; export { App } from "/src/App.js"; const route = import("/routes/home.js")' - - const result = rewriteDevProxyJavaScriptPaths(js, '/api/dev-proxy/7/') - - expect(result).toContain('import "/api/dev-proxy/7/runtime.js"') - expect(result).toContain('from "/api/dev-proxy/7/src/App.js"') - expect(result).toContain('import("/api/dev-proxy/7/routes/home.js")') - }) - - it('does not rewrite protocol-relative or already proxied paths', () => { - const html = '' - - const result = rewriteDevProxyHtmlPaths(html, '/api/dev-proxy/7/') - - expect(result).toBe(html) + it('falls back to localhost when no host is provided', () => { + expect(resolveDevPreviewUrl(undefined, undefined)).toBe('http://localhost:3056/') }) }) diff --git a/backend/test/services/dev-server/upgrade-handler.test.ts b/backend/test/services/dev-server/upgrade-handler.test.ts deleted file mode 100644 index b9175fea..00000000 --- a/backend/test/services/dev-server/upgrade-handler.test.ts +++ /dev/null @@ -1,259 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest' -import { - buildUpstreamUpgradeRequest, - createDevProxyUpgradeHandler, -} from '../../../src/services/dev-server/upgrade-handler' - -const netConnectMock = vi.hoisted(() => vi.fn()) -vi.mock('net', () => ({ connect: netConnectMock, default: { connect: netConnectMock } })) -vi.mock('../../../src/services/dev-server/manager', () => ({ - getDevServerPort: vi.fn(() => 5173), -})) - -describe('buildUpstreamUpgradeRequest', () => { - it('rewrites request target to rest and sets Host header', () => { - const rawHead = [ - 'GET /api/dev-proxy/1/ws-path HTTP/1.1', - 'Host: localhost:5003', - 'Upgrade: websocket', - 'Connection: Upgrade', - 'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==', - 'Sec-WebSocket-Version: 13', - ].join('\r\n') - - const result = buildUpstreamUpgradeRequest(rawHead, '/ws-path', 5173) - - expect(result).toContain('GET /ws-path HTTP/1.1') - expect(result).toContain('Host: 127.0.0.1:5173') - expect(result).not.toContain('Host: localhost:5003') - }) - - it('preserves Upgrade, Connection, and Sec-WebSocket-* headers', () => { - const rawHead = [ - 'GET /api/dev-proxy/2/socket HTTP/1.1', - 'Host: example.com', - 'Upgrade: websocket', - 'Connection: Upgrade', - 'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==', - 'Sec-WebSocket-Version: 13', - 'Sec-WebSocket-Protocol: json', - ].join('\r\n') - - const result = buildUpstreamUpgradeRequest(rawHead, '/socket', 3000) - - expect(result).toContain('Upgrade: websocket') - expect(result).toContain('Connection: Upgrade') - expect(result).toContain('Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==') - expect(result).toContain('Sec-WebSocket-Version: 13') - expect(result).toContain('Sec-WebSocket-Protocol: json') - }) - - it('handles root path rest', () => { - const rawHead = [ - 'GET /api/dev-proxy/1 HTTP/1.1', - 'Host: localhost:5003', - ].join('\r\n') - - const result = buildUpstreamUpgradeRequest(rawHead, '/', 5173) - - expect(result).toMatch(/^GET \/ HTTP\/1\.1\r\n/m) - }) - - it('preserves non-Host headers in order', () => { - const rawHead = [ - 'GET /api/dev-proxy/1/test HTTP/1.1', - 'Host: localhost:5003', - 'User-Agent: test-agent', - 'Accept: */*', - ].join('\r\n') - - const result = buildUpstreamUpgradeRequest(rawHead, '/test', 8080) - - const userAgentIdx = result.indexOf('User-Agent: test-agent') - const acceptIdx = result.indexOf('Accept: */*') - expect(userAgentIdx).toBeGreaterThan(0) - expect(acceptIdx).toBeGreaterThan(userAgentIdx) - }) - - it('returns empty string when given empty string', () => { - expect(buildUpstreamUpgradeRequest('', '/', 5173)).toBe('') - }) - - it('handles single-line input without headers', () => { - const result = buildUpstreamUpgradeRequest('GET /api/dev-proxy/1/ HTTP/1.1', '/', 5173) - expect(result).toBe('GET / HTTP/1.1\r\nHost: 127.0.0.1:5173') - }) - - it('removes duplicate host headers, keeping only the new one', () => { - const rawHead = [ - 'GET /api/dev-proxy/5/app HTTP/1.1', - 'Host: first.com', - 'Host: second.com', - 'Accept: application/json', - ].join('\r\n') - - const result = buildUpstreamUpgradeRequest(rawHead, '/app', 9999) - - const hostMatches = result.match(/^Host:/gm) - expect(hostMatches).toHaveLength(1) - expect(result).toContain('Host: 127.0.0.1:9999') - }) -}) - -describe('createDevProxyUpgradeHandler', () => { - const mockGetSession = vi.fn() - let auth: { api: { getSession: typeof mockGetSession } } - - beforeEach(() => { - vi.clearAllMocks() - mockGetSession.mockResolvedValue({ session: { userId: 'u1' }, user: { id: 'u1' } }) - netConnectMock.mockReturnValue(createMockSocket()) - auth = { api: { getSession: mockGetSession } } - }) - - function createMockSocket() { - const handlers = new Map void>>() - return { - on: vi.fn((event: string, handler: (...args: unknown[]) => void) => { - if (!handlers.has(event)) handlers.set(event, []) - handlers.get(event)!.push(handler) - }), - destroy: vi.fn(), - write: vi.fn(), - pipe: vi.fn(), - _handlers: handlers, - } - } - - function triggerEvent(obj: { _handlers?: Map void>> }, event: string, ...args: unknown[]) { - const map = obj._handlers - if (!map) return - const handlers = map.get(event) - if (handlers) { - for (const h of handlers) h(...args) - } - } - - describe('URL routing', () => { - it('destroys socket for non-proxy URL', async () => { - const handler = createDevProxyUpgradeHandler(auth as any, {} as any) - const socket = createMockSocket() - const req = { url: '/api/other', method: 'GET', headers: {} } - - await handler(req as any, socket as any, Buffer.alloc(0)) - - expect(socket.destroy).toHaveBeenCalledTimes(1) - expect(mockGetSession).not.toHaveBeenCalled() - }) - - it('destroys socket for URL without repo id', async () => { - const handler = createDevProxyUpgradeHandler(auth as any, {} as any) - const socket = createMockSocket() - const req = { url: '/api/dev-proxy/', method: 'GET', headers: {} } - - await handler(req as any, socket as any, Buffer.alloc(0)) - - expect(socket.destroy).toHaveBeenCalledTimes(1) - }) - }) - - describe('authentication', () => { - it('destroys socket when session lookup throws', async () => { - mockGetSession.mockRejectedValue(new Error('auth error')) - const handler = createDevProxyUpgradeHandler(auth as any, {} as any) - const socket = createMockSocket() - const req = { url: '/api/dev-proxy/1/ws', method: 'GET', headers: { host: 'localhost' } } - - await handler(req as any, socket as any, Buffer.alloc(0)) - - expect(socket.destroy).toHaveBeenCalledTimes(1) - }) - - it('writes 401 and destroys socket when no session', async () => { - mockGetSession.mockResolvedValue(null) - const handler = createDevProxyUpgradeHandler(auth as any, {} as any) - const socket = createMockSocket() - const req = { url: '/api/dev-proxy/1/hmr', method: 'GET', headers: { host: 'localhost' } } - - await handler(req as any, socket as any, Buffer.alloc(0)) - - expect(socket.write).toHaveBeenCalledWith(expect.stringContaining('401 Unauthorized')) - expect(socket.destroy).toHaveBeenCalledTimes(1) - }) - }) - - describe('upstream connection', () => { - it('calls net.connect with active port and 127.0.0.1', async () => { - const handler = createDevProxyUpgradeHandler(auth as any, {} as any) - const socket = createMockSocket() - const req = { url: '/api/dev-proxy/1/hmr', method: 'GET', headers: { host: 'localhost' } } - - await handler(req as any, socket as any, Buffer.alloc(0)) - - expect(netConnectMock).toHaveBeenCalledWith(5173, '127.0.0.1') - }) - - it('writes upstream request on connect', async () => { - const upstreamSocket = createMockSocket() - netConnectMock.mockReturnValue(upstreamSocket) - - const handler = createDevProxyUpgradeHandler(auth as any, {} as any) - const socket = createMockSocket() - const req = { url: '/api/dev-proxy/1/hmr', method: 'GET', headers: { host: 'localhost', upgrade: 'websocket', connection: 'Upgrade' } } - - await handler(req as any, socket as any, Buffer.alloc(0)) - - triggerEvent(upstreamSocket, 'connect') - - expect(upstreamSocket.write).toHaveBeenCalledWith(expect.stringContaining('GET /hmr HTTP/1.1')) - expect(upstreamSocket.write).toHaveBeenCalledWith(expect.stringContaining('Host: 127.0.0.1:5173')) - }) - - it('pipes head buffer after upgrade request', async () => { - const upstreamSocket = createMockSocket() - netConnectMock.mockReturnValue(upstreamSocket) - - const handler = createDevProxyUpgradeHandler(auth as any, {} as any) - const socket = createMockSocket() - const req = { url: '/api/dev-proxy/1/ws', method: 'GET', headers: { host: 'localhost' } } - const head = Buffer.from('extra-data') - - await handler(req as any, socket as any, head) - - triggerEvent(upstreamSocket, 'connect') - - const writeMock = upstreamSocket.write as ReturnType - const secondCallArg = writeMock.mock.calls[1]?.[0] - expect(secondCallArg).toBe(head) - }) - - it('pipes socket and upstream both ways on connect', async () => { - const upstreamSocket = createMockSocket() - netConnectMock.mockReturnValue(upstreamSocket) - - const handler = createDevProxyUpgradeHandler(auth as any, {} as any) - const socket = createMockSocket() - const req = { url: '/api/dev-proxy/1/ws', method: 'GET', headers: { host: 'localhost' } } - - await handler(req as any, socket as any, Buffer.alloc(0)) - triggerEvent(upstreamSocket, 'connect') - - expect(socket.pipe).toHaveBeenCalledWith(upstreamSocket) - expect(upstreamSocket.pipe).toHaveBeenCalledWith(socket) - }) - - it('destroys socket on upstream error', async () => { - const upstreamSocket = createMockSocket() - netConnectMock.mockReturnValue(upstreamSocket) - - const handler = createDevProxyUpgradeHandler(auth as any, {} as any) - const socket = createMockSocket() - const req = { url: '/api/dev-proxy/1/ws', method: 'GET', headers: { host: 'localhost' } } - - await handler(req as any, socket as any, Buffer.alloc(0)) - triggerEvent(upstreamSocket, 'error', new Error('conn refused')) - - expect(socket.destroy).toHaveBeenCalled() - }) - }) -}) diff --git a/docker-compose.yml b/docker-compose.yml index 74340c0f..87614e01 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -9,12 +9,15 @@ services: ports: - "5003:5003" - "3055:3055" + - "3056:3056" environment: - NODE_ENV=${NODE_ENV:-production} - HOST=0.0.0.0 - PORT=5003 - OPENCODE_SERVER_PORT=5551 - OPENCODE_HOST=127.0.0.1 + - DEV_PREVIEW_PORT=3056 + - DEV_PREVIEW_PUBLIC_URL=${DEV_PREVIEW_PUBLIC_URL:-} - DATABASE_PATH=/app/data/opencode.db - WORKSPACE_PATH=/workspace - PROCESS_START_WAIT_MS=2000 diff --git a/docs/configuration/docker.md b/docs/configuration/docker.md index 53a29422..e8f68c34 100644 --- a/docs/configuration/docker.md +++ b/docs/configuration/docker.md @@ -39,12 +39,15 @@ services: ports: - "5003:5003" - "3055:3055" + - "3056:3056" environment: - NODE_ENV=${NODE_ENV:-production} - HOST=0.0.0.0 - PORT=5003 - OPENCODE_SERVER_PORT=5551 - OPENCODE_HOST=127.0.0.1 + - DEV_PREVIEW_PORT=3056 + - DEV_PREVIEW_PUBLIC_URL=${DEV_PREVIEW_PUBLIC_URL:-} - DATABASE_PATH=/app/data/opencode.db - WORKSPACE_PATH=/workspace - PROCESS_START_WAIT_MS=2000 @@ -143,17 +146,21 @@ ports: - "8080:5003" # Access at localhost:8080 ``` -### Dev Server Port +### Dev Server Port & Preview Proxy -The preview proxy reaches a repository's dev server through the main `5003` port at `/api/dev-proxy//`, so the dev server only needs to listen on a single port inside the container. That port defaults to `3055` and is configurable in **Settings** (`devServerPort`); agents receive it as the `$OCM_DEV_SERVER_PORT` environment variable. +A repository's dev server listens on `$OCM_DEV_SERVER_PORT` inside the container. It defaults to `3055`, is configurable in **Settings** (`devServerPort`), and is passed to agents as the `$OCM_DEV_SERVER_PORT` environment variable. -Exposing the port to the host is optional — the preview works entirely through `5003`. Map it only if you also want to hit the dev server directly: +The in-app preview is served by a dedicated **authenticated preview listener** on a separate origin (`DEV_PREVIEW_PORT`, default `3056`). It validates your OpenCode Manager session, then proxies every request and HMR WebSocket to the dev server at the origin root with no path rewriting. Serving at root is what lets framework HMR work transparently across Vite, Next.js, Remix, SvelteKit, etc. + +Because the preview is a separate origin loaded directly by the browser, `3056` must be published to the host: ```yaml ports: - - "3055:3055" + - "3056:3056" ``` +The session cookie is shared with the preview origin because it is the same host on a different port (same site). Behind a reverse proxy that cannot expose `3056` directly, set `DEV_PREVIEW_PUBLIC_URL` to the externally reachable preview origin (e.g. `https://preview.example.com`). + Run your dev server on `$OCM_DEV_SERVER_PORT` and bind to `0.0.0.0`: === "Vite" diff --git a/frontend/src/api/devServer.ts b/frontend/src/api/devServer.ts index 3e666876..60ddea1f 100644 --- a/frontend/src/api/devServer.ts +++ b/frontend/src/api/devServer.ts @@ -5,7 +5,3 @@ import type { DevServerState } from '@opencode-manager/shared/types' export async function getDevServerStatus(repoId: number): Promise { return fetchWrapper(`${API_BASE_URL}/api/dev-server/${repoId}/status`) } - -export function getDevPreviewUrl(repoId: number): string { - return `${API_BASE_URL}/api/dev-proxy/${repoId}/` -} diff --git a/frontend/src/components/dev-server/DevServerPreviewButton.test.tsx b/frontend/src/components/dev-server/DevServerPreviewButton.test.tsx index 80cfb15a..732bc98e 100644 --- a/frontend/src/components/dev-server/DevServerPreviewButton.test.tsx +++ b/frontend/src/components/dev-server/DevServerPreviewButton.test.tsx @@ -9,18 +9,18 @@ vi.mock('@tanstack/react-query', () => ({ vi.mock('@/api/devServer', () => ({ getDevServerStatus: vi.fn(), - getDevPreviewUrl: (repoId: number) => `/api/dev-proxy/${repoId}/`, })) describe('DevServerPreviewButton', () => { it('calls onOpen with devserver input when configured port is running', () => { const onOpen = vi.fn() - let capturedOnSuccess: ((state: { status: 'running'; port: number }) => void) | undefined - vi.mocked(useMutation).mockImplementation(((options: { onSuccess?: (state: { status: 'running'; port: number }) => void }) => { + type RunningState = { status: 'running'; port: number; previewUrl: string } + let capturedOnSuccess: ((state: RunningState) => void) | undefined + vi.mocked(useMutation).mockImplementation(((options: { onSuccess?: (state: RunningState) => void }) => { capturedOnSuccess = options.onSuccess return { - mutate: () => capturedOnSuccess?.({ status: 'running', port: 5100 }), + mutate: () => capturedOnSuccess?.({ status: 'running', port: 5100, previewUrl: 'http://manager.example:3056/' }), isPending: false, } as unknown as ReturnType }) as typeof useMutation) @@ -35,7 +35,7 @@ describe('DevServerPreviewButton', () => { expect(onOpen).toHaveBeenCalledTimes(1) expect(onOpen).toHaveBeenCalledWith({ source: 'devserver', - previewUrl: '/api/dev-proxy/3/', + previewUrl: 'http://manager.example:3056/', title: 'App preview', }) }) diff --git a/frontend/src/components/dev-server/DevServerPreviewButton.tsx b/frontend/src/components/dev-server/DevServerPreviewButton.tsx index b8a32560..b13b2fd6 100644 --- a/frontend/src/components/dev-server/DevServerPreviewButton.tsx +++ b/frontend/src/components/dev-server/DevServerPreviewButton.tsx @@ -1,5 +1,5 @@ import { useMutation } from '@tanstack/react-query' -import { getDevServerStatus, getDevPreviewUrl } from '@/api/devServer' +import { getDevServerStatus } from '@/api/devServer' import { Button } from '@/components/ui/button' import { showToast } from '@/lib/toast' import { Loader2, Play } from 'lucide-react' @@ -14,14 +14,14 @@ export function DevServerPreviewButton({ repoId, onOpen }: DevServerPreviewButto const { mutate, isPending } = useMutation({ mutationFn: () => getDevServerStatus(repoId), onSuccess: (state) => { - if (state.status !== 'running') { + if (state.status !== 'running' || !state.previewUrl) { showToast.error(`No app detected on localhost:${state.port}`) return } onOpen({ source: 'devserver', - previewUrl: getDevPreviewUrl(repoId), + previewUrl: state.previewUrl, title: 'App preview', }) }, diff --git a/frontend/src/components/html-preview/HtmlArtifactPanel.test.tsx b/frontend/src/components/html-preview/HtmlArtifactPanel.test.tsx index 94a9cc87..5bbc15fa 100644 --- a/frontend/src/components/html-preview/HtmlArtifactPanel.test.tsx +++ b/frontend/src/components/html-preview/HtmlArtifactPanel.test.tsx @@ -32,7 +32,7 @@ function createDevServerArtifact(overrides?: Partial): HtmlArtifac id: 'test-3', title: 'App Preview', source: 'devserver', - previewUrl: '/api/dev-proxy/3/', + previewUrl: 'http://manager.example:3056/', ...overrides, } } @@ -219,7 +219,7 @@ describe('HtmlArtifactPanel', () => { const iframe = screen.getByTitle('App Preview') expect(iframe).toBeInTheDocument() - expect(iframe).toHaveAttribute('src', '/api/dev-proxy/3/') + expect(iframe).toHaveAttribute('src', 'http://manager.example:3056/') expect(iframe).toHaveAttribute( 'sandbox', 'allow-scripts allow-same-origin allow-forms allow-popups allow-modals allow-downloads', diff --git a/frontend/src/lib/htmlArtifacts.test.ts b/frontend/src/lib/htmlArtifacts.test.ts index 25d0db09..f371499d 100644 --- a/frontend/src/lib/htmlArtifacts.test.ts +++ b/frontend/src/lib/htmlArtifacts.test.ts @@ -100,9 +100,9 @@ describe('createHtmlArtifact', () => { }) it('creates a devserver artifact with previewUrl', () => { - const artifact = createHtmlArtifact({ source: 'devserver', previewUrl: '/api/dev-proxy/3/' }) + const artifact = createHtmlArtifact({ source: 'devserver', previewUrl: 'http://manager.example:3056/' }) expect(artifact.source).toBe('devserver') - expect(artifact.previewUrl).toBe('/api/dev-proxy/3/') + expect(artifact.previewUrl).toBe('http://manager.example:3056/') expect(artifact.id).toBeTruthy() expect(artifact.title).toBe('App preview') }) diff --git a/shared/src/config/defaults.ts b/shared/src/config/defaults.ts index 478a6472..7822627d 100644 --- a/shared/src/config/defaults.ts +++ b/shared/src/config/defaults.ts @@ -19,6 +19,11 @@ export const DEFAULTS = { HEALTH_FAILURE_THRESHOLD: 2, }, + DEV_PREVIEW: { + PORT: 3056, + PUBLIC_URL: '', // Optional: public origin for the preview iframe behind a reverse proxy (e.g., https://preview.mydomain.com) + }, + DATABASE: { PATH: './data/opencode.db', }, diff --git a/shared/src/config/env.ts b/shared/src/config/env.ts index 0c8b8f3d..a7dbd025 100644 --- a/shared/src/config/env.ts +++ b/shared/src/config/env.ts @@ -63,6 +63,11 @@ export const ENV = { SERVER_USERNAME: getEnvString('OPENCODE_SERVER_USERNAME', 'opencode'), }, + DEV_PREVIEW: { + PORT: getEnvNumber('DEV_PREVIEW_PORT', DEFAULTS.DEV_PREVIEW.PORT), + PUBLIC_URL: getEnvString('DEV_PREVIEW_PUBLIC_URL', DEFAULTS.DEV_PREVIEW.PUBLIC_URL), + }, + DATABASE: { PATH: getEnvString('DATABASE_PATH', DEFAULTS.DATABASE.PATH), }, diff --git a/shared/src/types/dev-server.ts b/shared/src/types/dev-server.ts index dc9666d8..ceec0879 100644 --- a/shared/src/types/dev-server.ts +++ b/shared/src/types/dev-server.ts @@ -7,9 +7,5 @@ export interface DevServerState { status: DevServerStatus port: number error: string | null - previewPath: string | null -} - -export interface DevServerConfig { - injectBase: boolean + previewUrl: string | null } diff --git a/shared/src/types/index.ts b/shared/src/types/index.ts index 2b770c39..1453d647 100644 --- a/shared/src/types/index.ts +++ b/shared/src/types/index.ts @@ -122,7 +122,7 @@ export type { } from '../schemas/schedule' export { DEFAULT_DEV_SERVER_PORT } from './dev-server' -export type { DevServerStatus, DevServerState, DevServerConfig } from './dev-server' +export type { DevServerStatus, DevServerState } from './dev-server' export type { SkillScope,