server.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. "use strict";
  2. const http = require("http");
  3. const fs = require("fs");
  4. const fsp = fs.promises;
  5. const path = require("path");
  6. const { URL } = require("url");
  7. const { requireAdmin } = require("./auth");
  8. const { SseHub } = require("./sse");
  9. const { TaskRepository } = require("./data/repository");
  10. const { pruneConversationContext } = require("./data/tree-pruner");
  11. const HOST = process.env.HOST || "127.0.0.1";
  12. const PORT = Number(process.env.PORT) || 3001;
  13. const FRONTEND_DIR = path.join(__dirname, "..", "frontend");
  14. const DATA_FILE = process.env.TASK_BOARD_DATA_FILE || path.join(__dirname, "..", "tasks.json");
  15. const MAX_BODY_SIZE = 2 * 1024 * 1024;
  16. const PUBLIC_RATE_LIMIT = Number.isFinite(Number(process.env.TASK_BOARD_PUBLIC_RATE_LIMIT))
  17. ? Math.max(20, Number(process.env.TASK_BOARD_PUBLIC_RATE_LIMIT))
  18. : 180;
  19. const PUBLIC_RATE_WINDOW_MS = 60 * 1000;
  20. const PUBLIC_ORIGIN_LIST = String(process.env.TASK_BOARD_PUBLIC_ORIGINS || "*")
  21. .split(",")
  22. .map((item) => item.trim())
  23. .filter(Boolean);
  24. const MIME_TYPES = {
  25. ".html": "text/html; charset=utf-8",
  26. ".css": "text/css; charset=utf-8",
  27. ".js": "application/javascript; charset=utf-8",
  28. ".json": "application/json; charset=utf-8",
  29. ".svg": "image/svg+xml",
  30. ".png": "image/png",
  31. ".ico": "image/x-icon",
  32. };
  33. const repository = new TaskRepository({ filePath: DATA_FILE });
  34. const sseHub = new SseHub();
  35. const publicRateMap = new Map();
  36. function nowIso() {
  37. return new Date().toISOString();
  38. }
  39. function sendJson(res, statusCode, payload, extraHeaders = {}) {
  40. res.writeHead(statusCode, {
  41. "Content-Type": "application/json; charset=utf-8",
  42. "Cache-Control": "no-store",
  43. ...extraHeaders,
  44. });
  45. res.end(JSON.stringify(payload));
  46. }
  47. function sendText(res, statusCode, text, extraHeaders = {}) {
  48. res.writeHead(statusCode, {
  49. "Content-Type": "text/plain; charset=utf-8",
  50. ...extraHeaders,
  51. });
  52. res.end(text);
  53. }
  54. function jsonError(res, statusCode, message) {
  55. sendJson(res, statusCode, { error: message });
  56. }
  57. function isOriginAllowed(origin) {
  58. if (!origin) return false;
  59. if (PUBLIC_ORIGIN_LIST.includes("*")) return true;
  60. return PUBLIC_ORIGIN_LIST.includes(origin);
  61. }
  62. function applyCors(req, res) {
  63. const origin = typeof req.headers.origin === "string" ? req.headers.origin : "";
  64. if (origin && isOriginAllowed(origin)) {
  65. res.setHeader("Access-Control-Allow-Origin", origin);
  66. res.setHeader("Vary", "Origin");
  67. } else if (!origin && PUBLIC_ORIGIN_LIST.includes("*")) {
  68. res.setHeader("Access-Control-Allow-Origin", "*");
  69. } else if (PUBLIC_ORIGIN_LIST.includes("*")) {
  70. res.setHeader("Access-Control-Allow-Origin", "*");
  71. }
  72. res.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
  73. res.setHeader("Access-Control-Allow-Headers", "Content-Type,Authorization");
  74. res.setHeader("Access-Control-Expose-Headers", "Content-Type,Cache-Control");
  75. }
  76. function getClientIp(req) {
  77. const forwarded = req.headers["x-forwarded-for"];
  78. if (typeof forwarded === "string" && forwarded.trim()) {
  79. return forwarded.split(",")[0].trim();
  80. }
  81. return req.socket.remoteAddress || "unknown";
  82. }
  83. function checkPublicRateLimit(req, res) {
  84. const ip = getClientIp(req);
  85. const now = Date.now();
  86. const entry = publicRateMap.get(ip);
  87. if (!entry || now >= entry.resetAt) {
  88. publicRateMap.set(ip, {
  89. count: 1,
  90. resetAt: now + PUBLIC_RATE_WINDOW_MS,
  91. });
  92. return true;
  93. }
  94. entry.count += 1;
  95. if (entry.count <= PUBLIC_RATE_LIMIT) {
  96. return true;
  97. }
  98. const retrySec = Math.max(1, Math.ceil((entry.resetAt - now) / 1000));
  99. sendJson(
  100. res,
  101. 429,
  102. {
  103. error: "Too Many Requests",
  104. retryAfterSec: retrySec,
  105. },
  106. { "Retry-After": String(retrySec) },
  107. );
  108. return false;
  109. }
  110. function parseBody(req) {
  111. return new Promise((resolve, reject) => {
  112. let body = "";
  113. let received = 0;
  114. req.on("data", (chunk) => {
  115. received += chunk.length;
  116. if (received > MAX_BODY_SIZE) {
  117. reject(new Error("Body too large"));
  118. req.destroy();
  119. return;
  120. }
  121. body += chunk.toString("utf8");
  122. });
  123. req.on("end", () => {
  124. if (!body.trim()) {
  125. resolve({});
  126. return;
  127. }
  128. try {
  129. const parsed = JSON.parse(body);
  130. resolve(parsed && typeof parsed === "object" ? parsed : {});
  131. } catch {
  132. reject(new Error("Invalid JSON"));
  133. }
  134. });
  135. req.on("error", reject);
  136. });
  137. }
  138. async function resolveStaticPath(urlPath) {
  139. const safePath = path.normalize(urlPath).replace(/^(\.\.[/\\])+/, "");
  140. if (safePath === "/" || safePath === ".") {
  141. return path.join(FRONTEND_DIR, "index.html");
  142. }
  143. const fullPath = path.join(FRONTEND_DIR, safePath);
  144. if (!fullPath.startsWith(FRONTEND_DIR)) return null;
  145. return fullPath;
  146. }
  147. function mapNodeToLegacyTask(node) {
  148. return {
  149. id: node.id,
  150. name: node.name,
  151. parentId: node.parentId,
  152. status: node.status,
  153. createdAt: node.timestamps.created,
  154. updatedAt: node.updatedAt,
  155. startTime: node.timestamps.started,
  156. endTime: node.timestamps.completed,
  157. plannedApproach: node.plannedApproach || "",
  158. bugDetails: node.bugDetails || "",
  159. notes: node.notes || node.content || "",
  160. };
  161. }
  162. async function handlePublicApi(req, res, pathname) {
  163. if (!checkPublicRateLimit(req, res)) return;
  164. if (req.method === "GET" && pathname === "/api/public/conversations") {
  165. const conversations = await repository.listConversations();
  166. sendJson(res, 200, conversations);
  167. return;
  168. }
  169. if (req.method === "GET" && pathname.startsWith("/api/public/tasks/")) {
  170. const conversationId = decodeURIComponent(pathname.replace("/api/public/tasks/", "").trim());
  171. if (!conversationId) {
  172. jsonError(res, 400, "conversationId 不能为空");
  173. return;
  174. }
  175. const graph = await repository.getConversationGraph(conversationId);
  176. sendJson(res, 200, graph);
  177. return;
  178. }
  179. if (req.method === "GET" && pathname.startsWith("/api/public/stream/")) {
  180. const conversationId = decodeURIComponent(pathname.replace("/api/public/stream/", "").trim()) || "*";
  181. sseHub.subscribe(conversationId, req, res);
  182. return;
  183. }
  184. if (req.method === "GET" && pathname.startsWith("/api/public/pruned/")) {
  185. const conversationId = decodeURIComponent(pathname.replace("/api/public/pruned/", "").trim());
  186. const reqUrl = new URL(req.url, `http://${req.headers.host || "localhost"}`);
  187. const focusNodeId = String(reqUrl.searchParams.get("focusNodeId") || "").trim();
  188. if (!conversationId || !focusNodeId) {
  189. jsonError(res, 400, "conversationId 和 focusNodeId 必填");
  190. return;
  191. }
  192. const graph = await repository.getConversationGraph(conversationId);
  193. const pruned = pruneConversationContext(graph, focusNodeId);
  194. sendJson(res, 200, pruned);
  195. return;
  196. }
  197. jsonError(res, 404, "Public API 路径不存在");
  198. }
  199. function resolveConversationIdForNode(node) {
  200. return node && node.conversationId ? node.conversationId : null;
  201. }
  202. async function handleAdminApi(req, res, pathname) {
  203. if (!requireAdmin(req, res)) return;
  204. if (req.method === "POST" && pathname === "/api/admin/nodes") {
  205. const body = await parseBody(req);
  206. const { result } = await repository.upsertNode(body);
  207. sseHub.publishConversation(resolveConversationIdForNode(result), {
  208. reason: "node_upsert",
  209. nodeId: result.id,
  210. });
  211. sendJson(res, 201, result);
  212. return;
  213. }
  214. if (req.method === "PUT" && pathname.startsWith("/api/admin/nodes/")) {
  215. const nodeId = decodeURIComponent(pathname.replace("/api/admin/nodes/", "").trim());
  216. if (!nodeId) {
  217. jsonError(res, 400, "节点 ID 无效");
  218. return;
  219. }
  220. const body = await parseBody(req);
  221. const { result } = await repository.upsertNode({ ...body, id: nodeId });
  222. sseHub.publishConversation(resolveConversationIdForNode(result), {
  223. reason: "node_update",
  224. nodeId: result.id,
  225. });
  226. sendJson(res, 200, result);
  227. return;
  228. }
  229. if (req.method === "DELETE" && pathname.startsWith("/api/admin/nodes/")) {
  230. const nodeId = decodeURIComponent(pathname.replace("/api/admin/nodes/", "").trim());
  231. if (!nodeId) {
  232. jsonError(res, 400, "节点 ID 无效");
  233. return;
  234. }
  235. const current = await repository.getNodeById(nodeId);
  236. const conversationId = resolveConversationIdForNode(current);
  237. const { result } = await repository.deleteNode(nodeId);
  238. sseHub.publishConversation(conversationId, {
  239. reason: "node_delete",
  240. nodeId,
  241. deletedCount: result.deletedCount,
  242. });
  243. sendJson(res, 200, result);
  244. return;
  245. }
  246. if (req.method === "POST" && pathname === "/api/admin/edges") {
  247. const body = await parseBody(req);
  248. const { result } = await repository.upsertEdge(body);
  249. const fromNode = await repository.getNodeById(result.from);
  250. const conversationId = resolveConversationIdForNode(fromNode);
  251. sseHub.publishConversation(conversationId, {
  252. reason: "edge_upsert",
  253. edgeId: result.id,
  254. from: result.from,
  255. to: result.to,
  256. });
  257. sendJson(res, 201, result);
  258. return;
  259. }
  260. if (req.method === "DELETE" && pathname === "/api/admin/edges") {
  261. const reqUrl = new URL(req.url, `http://${req.headers.host || "localhost"}`);
  262. const from = String(reqUrl.searchParams.get("from") || "").trim();
  263. const to = String(reqUrl.searchParams.get("to") || "").trim();
  264. const type = String(reqUrl.searchParams.get("type") || "").trim() || null;
  265. if (!from || !to) {
  266. jsonError(res, 400, "from 和 to 必填");
  267. return;
  268. }
  269. const { result } = await repository.deleteEdge({ from, to, type });
  270. const fromNode = await repository.getNodeById(from);
  271. const conversationId = resolveConversationIdForNode(fromNode);
  272. sseHub.publishConversation(conversationId, {
  273. reason: "edge_delete",
  274. from,
  275. to,
  276. type,
  277. deletedCount: result.deletedCount,
  278. });
  279. sendJson(res, 200, result);
  280. return;
  281. }
  282. if (req.method === "GET" && pathname.startsWith("/api/admin/nodes/")) {
  283. const nodeId = decodeURIComponent(pathname.replace("/api/admin/nodes/", "").trim());
  284. if (!nodeId) {
  285. jsonError(res, 400, "节点 ID 无效");
  286. return;
  287. }
  288. const node = await repository.getNodeById(nodeId);
  289. if (!node) {
  290. jsonError(res, 404, "节点不存在");
  291. return;
  292. }
  293. sendJson(res, 200, node);
  294. return;
  295. }
  296. jsonError(res, 404, "Admin API 路径不存在");
  297. }
  298. async function handleCompatApi(req, res, pathname) {
  299. // Read-only compatibility endpoint for old scripts.
  300. if (req.method === "GET" && pathname === "/api/tasks") {
  301. const conversations = await repository.listConversations();
  302. const allTasks = [];
  303. for (const conv of conversations) {
  304. const graph = await repository.getConversationGraph(conv.conversationId);
  305. allTasks.push(...graph.nodes.map(mapNodeToLegacyTask));
  306. }
  307. sendJson(res, 200, allTasks);
  308. return;
  309. }
  310. if (pathname.startsWith("/api/tasks")) {
  311. jsonError(res, 410, "Legacy write API 已废弃,请改用 /api/admin/*");
  312. return;
  313. }
  314. }
  315. async function serveStatic(req, res, pathname) {
  316. const staticPath = await resolveStaticPath(pathname);
  317. if (!staticPath) {
  318. sendText(res, 403, "Forbidden");
  319. return;
  320. }
  321. let filePath = staticPath;
  322. try {
  323. let stat = await fsp.stat(filePath);
  324. if (stat.isDirectory()) {
  325. filePath = path.join(filePath, "index.html");
  326. stat = await fsp.stat(filePath);
  327. }
  328. const ext = path.extname(filePath).toLowerCase();
  329. const type = MIME_TYPES[ext] || "application/octet-stream";
  330. const stream = fs.createReadStream(filePath);
  331. res.writeHead(200, {
  332. "Content-Type": type,
  333. "Cache-Control": ext === ".html" ? "no-cache" : "public, max-age=60",
  334. "Content-Length": stat.size,
  335. });
  336. stream.pipe(res);
  337. } catch {
  338. try {
  339. const fallback = await fsp.readFile(path.join(FRONTEND_DIR, "index.html"), "utf8");
  340. res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
  341. res.end(fallback);
  342. } catch {
  343. sendText(res, 404, "Not Found");
  344. }
  345. }
  346. }
  347. function isPublicApi(pathname) {
  348. return pathname.startsWith("/api/public/");
  349. }
  350. function isAdminApi(pathname) {
  351. return pathname.startsWith("/api/admin/");
  352. }
  353. function isCompatApi(pathname) {
  354. return pathname.startsWith("/api/tasks");
  355. }
  356. const server = http.createServer(async (req, res) => {
  357. try {
  358. applyCors(req, res);
  359. if (req.method === "OPTIONS") {
  360. res.writeHead(204);
  361. res.end();
  362. return;
  363. }
  364. const reqUrl = new URL(req.url, `http://${req.headers.host || "localhost"}`);
  365. const pathname = reqUrl.pathname;
  366. if (pathname === "/health") {
  367. sendJson(res, 200, { ok: true, now: nowIso() });
  368. return;
  369. }
  370. if (isPublicApi(pathname)) {
  371. await handlePublicApi(req, res, pathname);
  372. return;
  373. }
  374. if (isAdminApi(pathname)) {
  375. await handleAdminApi(req, res, pathname);
  376. return;
  377. }
  378. if (isCompatApi(pathname)) {
  379. await handleCompatApi(req, res, pathname);
  380. return;
  381. }
  382. if (req.method !== "GET" && req.method !== "HEAD") {
  383. sendText(res, 405, "Method Not Allowed");
  384. return;
  385. }
  386. await serveStatic(req, res, pathname);
  387. } catch (error) {
  388. const message = error instanceof Error ? error.message : String(error);
  389. sendJson(res, 500, { error: "服务器内部错误", detail: message });
  390. }
  391. });
  392. async function start() {
  393. await repository.ensureFile();
  394. server.listen(PORT, HOST, () => {
  395. console.log(`[task-board-v2] listening on http://${HOST}:${PORT}`);
  396. console.log(`[task-board-v2] data file: ${DATA_FILE}`);
  397. console.log(`[task-board-v2] public origins: ${PUBLIC_ORIGIN_LIST.join(",") || "*"}`);
  398. });
  399. }
  400. if (require.main === module) {
  401. void start();
  402. }
  403. module.exports = {
  404. start,
  405. server,
  406. };