server.mjs
12.2 KB
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
// ============================================================================
// Server Module - HTTP 服务器和路由
// 职责:HTTP 请求处理、SSE 连接管理、静态文件服务
// ============================================================================
import fs from "node:fs";
import http from "node:http";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { DEFAULT_CONFIG, MODEL_CANDIDATES, PORT, URL_CANDIDATES, VISION_MODEL_CANDIDATES } from "./config.mjs";
import { runPipeline } from "./pipeline.mjs";
import { listBundlePages, listGeneratedFiles, listPreviewProjects } from "./preview-project.mjs";
import { getCurrentProcess, getIsRunning } from "./process-manager.mjs";
import { addClient, getPreviewUrl, removeClient } from "./sse.mjs";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const __publicDir = path.join(__dirname, "..", "public");
/**
* 解析 JSON 请求体
*/
function parseBody(req) {
return new Promise((resolve, reject) => {
let body = "";
req.on("data", (chunk) => { body += chunk; });
req.on("end", () => {
try {
resolve(JSON.parse(body));
} catch {
reject(new Error("Invalid JSON"));
}
});
req.on("error", reject);
});
}
/**
* 发送 JSON 响应
*/
function sendJson(res, data, status = 200) {
res.writeHead(status, {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
});
res.end(JSON.stringify(data));
}
/**
* 发送静态文件
*/
function serveStatic(res, filePath, contentType) {
fs.readFile(filePath, (err, data) => {
if (err) {
res.writeHead(404);
res.end("Not Found");
return;
}
res.writeHead(200, { "Content-Type": contentType });
res.end(data);
});
}
/**
* 获取静态文件 MIME 类型
*/
function getMimeType(filePath) {
const ext = path.extname(filePath).toLowerCase();
const mimeTypes = {
".html": "text/html; charset=utf-8",
".css": "text/css; charset=utf-8",
".js": "application/javascript; charset=utf-8",
".json": "application/json",
".png": "image/png",
".jpg": "image/jpeg",
".gif": "image/gif",
".svg": "image/svg+xml",
".ico": "image/x-icon",
};
return mimeTypes[ext] || "application/octet-stream";
}
/**
* 检查是否为安全的静态文件路径
* 通过解析最终路径并校验是否在 public 目录内,兼容 Windows 路径分隔符
*/
function isSafeStaticPath(requestPath) {
// 拒绝包含 URL 编码或空段的可疑请求
if (requestPath.includes("%") || requestPath.includes("\0")) return false;
// 解析最终绝对路径,path.resolve 会自动处理 ".." 和 "."
const resolved = path.resolve(__publicDir, requestPath);
const safeRoot = path.resolve(__publicDir);
// 必须以 publicDir 为前缀(防止路径遍历)
if (!resolved.startsWith(safeRoot + path.sep) && resolved !== safeRoot) {
return false;
}
// 只允许 css/ 或 js/ 子目录下的文件(使用 path.sep 适配平台)
const relative = path.relative(safeRoot, resolved);
const segments = relative.split(path.sep);
if (segments.length < 2) return false; // 必须至少有两层,例如 css/style.css
return segments[0] === "css" || segments[0] === "js";
}
/**
* 处理 SSE 连接
*/
function handleSSE(req, res) {
res.writeHead(200, {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"Access-Control-Allow-Origin": "*",
});
addClient(res);
res.write(`data: {"type":"connected"}\n\n`);
const previewUrl = getPreviewUrl();
if (previewUrl) {
res.write(`event: preview\ndata: ${JSON.stringify({ url: previewUrl })}\n\n`);
}
if (getIsRunning()) {
res.write(`event: status\ndata: ${JSON.stringify({ running: true, step: "running" })}\n\n`);
}
req.on("close", () => {
removeClient(res);
});
}
/**
* 处理预览代理请求
* 将 /preview-proxy/* 请求转发到预览项目的 dev server
*/
async function handlePreviewProxy(req, res) {
const url = req.url;
const previewUrl = getPreviewUrl();
if (!previewUrl) {
res.writeHead(503, { "Content-Type": "text/html; charset=utf-8" });
res.end("<html><body><p style='color:#8b949e;text-align:center;margin-top:40vh'>预览服务尚未就绪</p></body></html>");
return;
}
// Extract the path after /preview-proxy (e.g., /preview-proxy/foo -> /foo)
const subPath = url.slice("/preview-proxy".length) || "/";
try {
const targetUrl = new URL(subPath, previewUrl);
const proxyReq = http.request(
targetUrl,
{
method: req.method,
headers: {
...req.headers,
host: targetUrl.host,
},
},
(proxyRes) => {
// Copy status and headers
const headers = { ...proxyRes.headers };
// Remove restrictive headers that might break iframe embedding
delete headers["x-frame-options"];
delete headers["content-security-policy"];
res.writeHead(proxyRes.statusCode, headers);
proxyRes.pipe(res);
},
);
proxyReq.on("error", (err) => {
res.writeHead(502, { "Content-Type": "text/html; charset=utf-8" });
res.end(`<html><body><p style='color:#f85149;text-align:center;margin-top:40vh'>无法连接到预览服务: ${err.message}</p></body></html>`);
});
req.pipe(proxyReq);
} catch (error) {
res.writeHead(502, { "Content-Type": "text/html; charset=utf-8" });
res.end(`<html><body><p style='color:#f85149;text-align:center;margin-top:40vh'>预览代理错误: ${error.message}</p></body></html>`);
}
}
/**
* 处理 API 请求
*/
async function handleApi(req, res, repoRoot) {
const url = req.url;
const method = req.method;
// CORS preflight
if (method === "OPTIONS") {
res.writeHead(204, {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type",
});
res.end();
return;
}
// GET /api/status
if (url === "/api/status" && method === "GET") {
sendJson(res, {
running: getIsRunning(),
previewUrl: getPreviewUrl(),
models: MODEL_CANDIDATES,
urlCandidates: URL_CANDIDATES,
defaultConfig: DEFAULT_CONFIG,
});
return;
}
// GET /api/config
if (url === "/api/config" && method === "GET") {
sendJson(res, {
modelCandidates: MODEL_CANDIDATES,
visionModelCandidates: VISION_MODEL_CANDIDATES,
urlCandidates: URL_CANDIDATES,
defaults: DEFAULT_CONFIG,
});
return;
}
// GET /api/preview-url
if (url === "/api/preview-url" && method === "GET") {
sendJson(res, { previewUrl: getPreviewUrl() });
return;
}
// GET /api/projects
if (url === "/api/projects" && method === "GET") {
const projects = listPreviewProjects(repoRoot);
sendJson(res, { previewProjects: projects });
return;
}
// GET /api/bundles
if (url === "/api/bundles" && method === "GET") {
const bundles = listBundlePages(repoRoot);
sendJson(res, { bundles });
return;
}
// GET /api/files?project=xxx
if (url.startsWith("/api/files") && method === "GET") {
const params = new URL(url, `http://${req.headers.host}`).searchParams;
const projectName = params.get("project");
const projects = listPreviewProjects(repoRoot);
const project = projects.find((p) => p.name === projectName);
if (!project) {
sendJson(res, { files: [] }, 404);
return;
}
const files = listGeneratedFiles(project.path);
sendJson(res, { project: project.name, files });
return;
}
// GET /api/file?path=xxx - 读取单个文件内容
if (url.startsWith("/api/file") && method === "GET") {
const params = new URL(url, `http://${req.headers.host}`).searchParams;
const filePath = params.get("path");
if (!filePath) {
res.writeHead(400, { "Content-Type": "text/plain" });
res.end("Missing path parameter");
return;
}
// 安全检查:防止路径遍历
const normalized = path.normalize(filePath);
if (normalized.includes("..")) {
res.writeHead(403, { "Content-Type": "text/plain" });
res.end("Forbidden");
return;
}
// 支持绝对路径和相对路径
let fullPath;
if (path.isAbsolute(filePath)) {
fullPath = filePath;
// 安全检查:绝对路径必须在 ai-previews 目录下
const aiPreviewsDir = path.join(repoRoot, "apps/web/ai-previews");
if (!fullPath.startsWith(aiPreviewsDir)) {
res.writeHead(403, { "Content-Type": "text/plain" });
res.end("Forbidden: path must be within ai-previews directory");
return;
}
} else {
// 相对路径:拼接 ai-previews 目录
fullPath = path.join(repoRoot, "apps/web/ai-previews", filePath);
}
if (!fs.existsSync(fullPath)) {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Not Found");
return;
}
const content = fs.readFileSync(fullPath, "utf8");
res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
res.end(content);
return;
}
// POST /api/generate
if (url === "/api/generate" && method === "POST") {
try {
const config = await parseBody(req);
runPipeline(config, repoRoot);
sendJson(res, { success: true, message: "Pipeline started" });
} catch (error) {
sendJson(res, { success: false, error: error.message }, 400);
}
return;
}
// POST /api/stop
if (url === "/api/stop" && method === "POST") {
const currentProcess = getCurrentProcess();
if (currentProcess) {
currentProcess.kill("SIGTERM");
setTimeout(() => {
if (getCurrentProcess()) {
getCurrentProcess().kill("SIGKILL");
}
}, 3000);
}
sendJson(res, { success: true, message: "Stop signal sent" });
return;
}
// 404
sendJson(res, { error: "Not Found" }, 404);
}
/**
* 创建 HTTP 服务器
*/
export function createServer(repoRoot) {
const server = http.createServer(async (req, res) => {
const url = req.url;
// SSE endpoint
if (url === "/events") {
handleSSE(req, res);
return;
}
// Preview proxy - forwards requests to preview project dev server
if (url.startsWith("/preview-proxy")) {
await handlePreviewProxy(req, res);
return;
}
// API endpoints
if (url.startsWith("/api/")) {
await handleApi(req, res, repoRoot);
return;
}
// Static files
if (url === "/" || url === "/index.html") {
serveStatic(res, path.join(__publicDir, "index.html"), "text/html; charset=utf-8");
return;
}
// 静态资源 (css/, js/)
if (url.startsWith("/css/") || url.startsWith("/js/")) {
const requestPath = url.slice(1); // 移除开头的 /
if (!isSafeStaticPath(requestPath)) {
res.writeHead(403);
res.end("Forbidden");
return;
}
const filePath = path.join(__publicDir, requestPath);
serveStatic(res, filePath, getMimeType(filePath));
return;
}
// 404
res.writeHead(404);
res.end("Not Found");
});
// WebSocket upgrade for Vite HMR in preview proxy
server.on("upgrade", (req, socket, head) => {
const url = req.url || "";
if (url.startsWith("/preview-proxy")) {
const previewUrl = getPreviewUrl();
if (!previewUrl) {
socket.destroy();
return;
}
const subPath = url.slice("/preview-proxy".length) || "/";
const targetUrl = new URL(subPath, previewUrl);
targetUrl.protocol = targetUrl.protocol === "https:" ? "wss:" : "ws:";
const proxyReq = http.request(targetUrl, {
method: "GET",
headers: {
...req.headers,
host: targetUrl.host,
},
});
proxyReq.on("upgrade", (proxyRes, proxySocket, proxyHead) => {
socket.write(`HTTP/1.1 101 Switching Protocols\r\n`);
Object.entries(proxyRes.headers).forEach(([key, value]) => {
if (value) {
const values = Array.isArray(value) ? value : [value];
values.forEach((v) => socket.write(`${key}: ${v}\r\n`));
}
});
socket.write("\r\n");
if (proxyHead.length > 0) socket.write(proxyHead);
proxySocket.pipe(socket);
socket.pipe(proxySocket);
});
proxyReq.on("error", () => socket.destroy());
proxyReq.end();
}
});
return server;
}
/**
* 启动服务器
*/
export function startServer(repoRoot) {
const server = createServer(repoRoot);
server.listen(PORT, () => {
console.log(`\n[ai-direct-server] 服务已启动: http://localhost:${PORT}`);
console.log(`[ai-direct-server] SSE 端点: http://localhost:${PORT}/events`);
console.log(`[ai-direct-server] API 端点: http://localhost:${PORT}/api/status\n`);
});
// 全局错误兜底
process.on("uncaughtException", (err) => {
console.error("[server] uncaughtException:", err.message, err.stack);
});
process.on("unhandledRejection", (err) => {
console.error("[server] unhandledRejection:", err instanceof Error ? err.message : err);
});
}