feat(api): serve embedded UI dashboard as static files
Add static file serving to ApiServer so the React SPA can be served from the same HTTP server. Accepts optional uiDir as 5th constructor parameter with auto-detection fallback for dev and publish layouts. Includes path traversal guard and SPA fallback to index.html. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> Entire-Checkpoint: 1fe28d47aa9b
This commit is contained in:
parent
b027d0189b
commit
16f366b9b0
@ -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"),
|
||||
"<html><body>Dashboard</body></html>",
|
||||
);
|
||||
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({
|
||||
|
||||
@ -73,13 +73,45 @@ export class ApiServer {
|
||||
private sseCleanupHandlers = new Map<http.ServerResponse, () => void>();
|
||||
private healthInterval?: ReturnType<typeof setInterval>;
|
||||
|
||||
private static MIME_TYPES: Record<string, string> = {
|
||||
".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<void> {
|
||||
@ -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,
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user