diff --git a/src/__tests__/api-server.test.ts b/src/__tests__/api-server.test.ts index ee5ce4e..0b6a5a3 100644 --- a/src/__tests__/api-server.test.ts +++ b/src/__tests__/api-server.test.ts @@ -961,6 +961,111 @@ describe("ApiServer", () => { controller.abort(); }); + describe("static file serving", () => { + let uiDir: string; + + beforeEach(() => { + uiDir = path.join(tmpDir, "ui"); + fs.mkdirSync(uiDir, { recursive: true }); + fs.writeFileSync( + path.join(uiDir, "index.html"), + "Dashboard", + ); + fs.mkdirSync(path.join(uiDir, "assets"), { recursive: true }); + fs.writeFileSync( + path.join(uiDir, "assets", "app.js"), + 'console.log("app")', + ); + fs.writeFileSync( + path.join(uiDir, "assets", "style.css"), + "body { color: red }", + ); + }); + + it("serves index.html for root path", async () => { + const { ApiServer } = await import("../core/api-server.js"); + server = new ApiServer( + mockCore as any, + { port: 0, host: "127.0.0.1" }, + portFilePath, + mockTopicManager as any, + uiDir, + ); + await server.start(); + const port = server.getPort(); + + const res = await apiFetch(port, "/"); + expect(res.status).toBe(200); + expect(res.headers.get("content-type")).toContain("text/html"); + const body = await res.text(); + expect(body).toContain("Dashboard"); + }); + + it("serves static assets with correct content-type", async () => { + const { ApiServer } = await import("../core/api-server.js"); + server = new ApiServer( + mockCore as any, + { port: 0, host: "127.0.0.1" }, + portFilePath, + mockTopicManager as any, + uiDir, + ); + await server.start(); + const port = server.getPort(); + + const jsRes = await apiFetch(port, "/assets/app.js"); + expect(jsRes.status).toBe(200); + expect(jsRes.headers.get("content-type")).toContain("javascript"); + + const cssRes = await apiFetch(port, "/assets/style.css"); + expect(cssRes.status).toBe(200); + expect(cssRes.headers.get("content-type")).toContain("text/css"); + }); + + it("falls back to index.html for SPA routes", async () => { + const { ApiServer } = await import("../core/api-server.js"); + server = new ApiServer( + mockCore as any, + { port: 0, host: "127.0.0.1" }, + portFilePath, + mockTopicManager as any, + uiDir, + ); + await server.start(); + const port = server.getPort(); + + const res = await apiFetch(port, "/sessions/abc"); + expect(res.status).toBe(200); + expect(res.headers.get("content-type")).toContain("text/html"); + const body = await res.text(); + expect(body).toContain("Dashboard"); + }); + + it("API routes still work when UI is enabled", async () => { + const { ApiServer } = await import("../core/api-server.js"); + server = new ApiServer( + mockCore as any, + { port: 0, host: "127.0.0.1" }, + portFilePath, + mockTopicManager as any, + uiDir, + ); + await server.start(); + const port = server.getPort(); + + const res = await apiFetch(port, "/api/health"); + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.status).toBe("ok"); + }); + + it("returns 404 for non-API routes when UI not available", async () => { + const port = await startServer(); + const res = await apiFetch(port, "/nonexistent"); + expect(res.status).toBe(404); + }); + }); + describe("token auth", () => { it("rejects requests without token when configured and host is not localhost", async () => { mockCore.configManager.get.mockReturnValue({ diff --git a/src/core/api-server.ts b/src/core/api-server.ts index a83c7bf..6f7ef72 100644 --- a/src/core/api-server.ts +++ b/src/core/api-server.ts @@ -73,13 +73,45 @@ export class ApiServer { private sseCleanupHandlers = new Map void>(); private healthInterval?: ReturnType; + private static MIME_TYPES: Record = { + ".html": "text/html; charset=utf-8", + ".js": "application/javascript; charset=utf-8", + ".css": "text/css; charset=utf-8", + ".json": "application/json; charset=utf-8", + ".png": "image/png", + ".jpg": "image/jpeg", + ".svg": "image/svg+xml", + ".ico": "image/x-icon", + ".woff": "font/woff", + ".woff2": "font/woff2", + }; + constructor( private core: OpenACPCore, private config: ApiConfig, portFilePath?: string, private topicManager?: TopicManager, + private uiDir?: string, ) { this.portFilePath = portFilePath ?? DEFAULT_PORT_FILE; + // Auto-detect UI directory if not provided + if (!this.uiDir) { + const __filename = fileURLToPath(import.meta.url); + const candidate = path.resolve(path.dirname(__filename), "../../ui/dist"); + if (fs.existsSync(path.join(candidate, "index.html"))) { + this.uiDir = candidate; + } + // Also check dist-publish layout + if (!this.uiDir) { + const publishCandidate = path.resolve( + path.dirname(__filename), + "../ui", + ); + if (fs.existsSync(path.join(publishCandidate, "index.html"))) { + this.uiDir = publishCandidate; + } + } + } } async start(): Promise { @@ -259,7 +291,10 @@ export class ApiServer { this.handleSSE(req, res); return; // Don't end the response — SSE keeps it open } else { - this.sendJson(res, 404, { error: "Not found" }); + // Try static file serving (UI dashboard) + if (!this.serveStatic(req, res)) { + this.sendJson(res, 404, { error: "Not found" }); + } } } catch (err) { log.error({ err }, "API request error"); @@ -877,6 +912,39 @@ export class ApiServer { } } + private serveStatic( + req: http.IncomingMessage, + res: http.ServerResponse, + ): boolean { + if (!this.uiDir) return false; + + const urlPath = (req.url || "/").split("?")[0]; + const safePath = path.normalize(urlPath).replace(/^(\.\.[/\\])+/, ""); + + // Try exact file match + const filePath = path.join(this.uiDir, safePath); + if (!filePath.startsWith(this.uiDir)) return false; // path traversal guard + + if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) { + const ext = path.extname(filePath); + const contentType = + ApiServer.MIME_TYPES[ext] ?? "application/octet-stream"; + res.writeHead(200, { "Content-Type": contentType }); + fs.createReadStream(filePath).pipe(res); + return true; + } + + // SPA fallback — serve index.html + const indexPath = path.join(this.uiDir, "index.html"); + if (fs.existsSync(indexPath)) { + res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }); + fs.createReadStream(indexPath).pipe(res); + return true; + } + + return false; + } + private sendJson( res: http.ServerResponse, status: number,