feat(home): link the homepage of every local project in the workspace

- server: GET /api/local-projects scans sibling folders for index.html
  (title from <title>/<h1>, generic titles fall back to the folder name,
  sorted by newest edit) and GET /projects/<folder>/ serves that folder
- both endpoints are loopback-only; node_modules/.git/.hermes blocked and
  path traversal rejected; WORKSPACE_DIR=none disables the feature
- home: new 'โปรเจคในเครื่อง' list (2 columns >=700px) that hides itself when
  the API is absent, so the live static site never shows fake rows
- SW skips /projects/* so other projects' files are never cached; version 2026.11.19.5
- docs: README/AGENTS/DESIGN cover the endpoints, the loopback rule and the layout
This commit is contained in:
Bkk1234 committed 2026-11-20 14:26:54 +07:00
1 parent b27acd40ee
commit db7724b237
9 files changed
+417 -5

No files matched your search

+191 -1
View File
@@ -4,20 +4,26 @@
*
* GET /api/projects อ่านข้อมูลปัจจุบัน
* PUT /api/projects เขียน data/projects.json แล้ว commit + push ขึ้น Gitea
* GET /api/local-projects รายชื่อโปรเจคในโฟลเดอร์ข้างเคียง (เครื่องตัวเองเท่านั้น)
* GET /projects/<โฟลเดอร์>/… เสิร์ฟหน้า index.html ของโปรเจคใน D:\Git\workspace (เครื่องตัวเองเท่านั้น)
* static เสิร์ฟไฟล์หน้าเว็บจาก root ของโปรเจค
*
* ใช้งาน:
* node server/publish.mjs # http://localhost:8090
* PORT=8090 ADMIN_TOKEN=xxxx node server/publish.mjs
* PUBLISH_PUSH=0 node server/publish.mjs # เขียนไฟล์ + commit แต่ไม่ push
* WORKSPACE_DIR=D:/Git/workspace node server/publish.mjs # เปลี่ยนที่สแกนโปรเจคข้างเคียง
* WORKSPACE_DIR=none node server/publish.mjs # ปิดการเสิร์ฟโฟลเดอร์ข้างเคียง
*
* ความปลอดภัย:
* - ถ้าตั้ง ADMIN_TOKEN ไว้ ต้องส่ง header x-admin-token ให้ตรงทุกครั้งที่เขียน
* - ถ้าไม่ได้ตั้ง อนุญาตเฉพาะ request ที่มาจากเครื่องเดียวกัน (loopback)
* - /api/local-projects และ /projects/* รับเฉพาะ request จากเครื่องเดียวกันเสมอ
* (เปิดเซิร์ฟเวอร์ให้เครื่องอื่นดูเว็บได้ แต่เปิดดูไฟล์ในเครื่องไม่ได้)
*/
import { createServer } from "node:http";
import { readFile, stat, writeFile, mkdir } from "node:fs/promises";
import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { timingSafeEqual } from "node:crypto";
@@ -33,6 +39,26 @@ const HOST = process.env.HOST || "0.0.0.0";
const ADMIN_TOKEN = (process.env.ADMIN_TOKEN || "").trim();
const SHOULD_PUSH = process.env.PUBLISH_PUSH !== "0";
/* โฟลเดอร์โปรเจคข้างเคียง (ค่าเริ่มต้น: โฟลเดอร์แม่ของ repo นี้ = D:\Git\workspace) */
const WORKSPACE_DIR =
process.env.WORKSPACE_DIR === "none"
? null
: path.resolve(process.env.WORKSPACE_DIR || path.join(ROOT, ".."));
const ENTRY_CANDIDATES = [
"index.html",
"public/index.html",
"ui/index.html",
"dist/index.html",
"frontend/dist/index.html",
"frontend/index.html",
];
const SKIP_NAMES = new Set(["node_modules", ".git", ".hermes", "archive", "Library", "Local Settings"]);
/** ชื่อที่ไม่มีข้อมูล (index.html ของบางโปรเจคตั้งไว้ลอย ๆ) → ใช้ชื่อโฟลเดอร์แทน */
const GENERIC_TITLES = new Set(["หน้าแรก", "home", "index", "untitled", "document", "new page", ""]);
const MIME = {
".html": "text/html; charset=utf-8",
".css": "text/css; charset=utf-8",
@@ -175,7 +201,158 @@ async function readData() {
return JSON.parse(raw);
}
/* ------------------------------------------------ โปรเจคในเครื่อง (workspace) */
async function readEntryTitle(file) {
try {
const html = await readFile(file, "utf8");
const head = html.slice(0, 8192);
const title = head.match(/<title[^>]*>([^<]+)<\/title>/i);
if (title) return title[1].trim().replace(/\s+/g, " ");
const h1 = head.match(/<h1[^>]*>([\s\S]{1,160}?)<\/h1>/i);
if (h1) return h1[1].replace(/<[^>]+>/g, "").trim().replace(/\s+/g, " ");
} catch {
/* อ่านไม่ได้ก็ใช้ชื่อโฟลเดอร์แทน */
}
return "";
}
async function findEntry(dir) {
for (const rel of ENTRY_CANDIDATES) {
try {
const info = await stat(path.join(dir, rel));
if (info.isFile()) return { rel, mtime: info.mtimeMs };
} catch {
/* ลองตัวถัดไป */
}
}
return null;
}
async function scanLocalProjects() {
if (!WORKSPACE_DIR) return [];
let dirents = [];
try {
dirents = await readdir(WORKSPACE_DIR, { withFileTypes: true });
} catch {
return [];
}
const items = [];
for (const dirent of dirents) {
if (!dirent.isDirectory()) continue;
const folder = dirent.name;
if (folder.startsWith(".") || folder.startsWith("~") || SKIP_NAMES.has(folder)) continue;
const dir = path.join(WORKSPACE_DIR, folder);
if (dir === ROOT) continue;
const entry = await findEntry(dir);
if (!entry) continue;
const rawTitle = (await readEntryTitle(path.join(dir, entry.rel))).trim();
items.push({
folder,
entry: entry.rel,
url: `/projects/${encodeURIComponent(folder)}/${entry.rel.replace(/index\.html$/, "")}`,
title: GENERIC_TITLES.has(rawTitle.toLowerCase()) ? folder : rawTitle || folder,
updated_at: new Date(entry.mtime).toISOString(),
});
}
items.sort((a, b) => b.updated_at.localeCompare(a.updated_at));
return items;
}
async function sendFile(res, filePath) {
const ext = path.extname(filePath).toLowerCase();
const headers = { "content-type": MIME[ext] || "application/octet-stream" };
if ([".html", ".css", ".js", ".mjs", ".json", ""].includes(ext)) {
Object.assign(headers, NO_CACHE);
} else {
headers["cache-control"] = "public, max-age=300";
}
res.writeHead(200, headers);
res.end(await readFile(filePath));
}
function denyWorkspace(res, reason) {
const payload = `<!doctype html><meta charset="utf-8"><title>เปิดไม่ได้</title>
<div style="font-family:sans-serif;padding:40px"><h1>เปิดไม่ได้</h1><p>${reason}</p></div>`;
res.writeHead(403, { "content-type": "text/html; charset=utf-8" });
res.end(payload);
}
async function serveWorkspace(req, res, pathname) {
if (!WORKSPACE_DIR) {
res.writeHead(404, { "content-type": "text/html; charset=utf-8" });
res.end("<!doctype html><meta charset=utf-8><p>ปิดการเสิร์ฟโฟลเดอร์โปรเจค (WORKSPACE_DIR=none)</p>");
return;
}
if (!isLoopback(req)) {
denyWorkspace(res, "ลิงก์นี้เปิดได้เฉพาะเครื่องที่รันเซิร์ฟเวอร์ (localhost)");
return;
}
const rel = decodeURIComponent(pathname.replace(/^\/projects\/?/, ""));
const target = path.resolve(WORKSPACE_DIR, `./${rel}`);
const withinWorkspace = target === WORKSPACE_DIR || target.startsWith(WORKSPACE_DIR + path.sep);
if (!withinWorkspace || /(^|[\\/])(node_modules|\.git|\.hermes)([\\/]|$)/i.test(target)) {
denyWorkspace(res, "เส้นทางนี้ไม่ได้รับอนุญาต");
return;
}
try {
const info = await stat(target);
if (info.isDirectory()) {
if (!pathname.endsWith("/")) {
res.writeHead(301, { location: `${pathname}/` });
res.end();
return;
}
const indexFile = path.join(target, "index.html");
try {
const indexInfo = await stat(indexFile);
if (!indexInfo.isFile()) throw new Error("not a file");
} catch {
res.writeHead(404, { "content-type": "text/html; charset=utf-8" });
res.end(
`<!doctype html><meta charset="utf-8"><title>ไม่มี index.html</title>
<div style="font-family:sans-serif;padding:40px">
<h1>โฟลเดอร์นี้ไม่มี index.html</h1>
<p>โปรเจคนี้ต้องรัน dev server แยก (เช่น <code>npm run dev</code>)</p>
</div>`,
);
return;
}
await sendFile(res, indexFile);
return;
}
await sendFile(res, target);
} catch {
res.writeHead(404, { "content-type": "text/html; charset=utf-8" });
res.end(
`<!doctype html><meta charset="utf-8"><title>ไม่พบไฟล์</title>
<div style="font-family:sans-serif;padding:40px"><h1>ไม่พบไฟล์นี้</h1>
<p><a href="/">กลับไปหน้ารายชื่อโปรเจค</a></p></div>`,
);
}
}
async function handleApi(req, res, pathname) {
if (pathname === "/api/local-projects" && req.method === "GET") {
if (!canWrite(req)) {
sendJson(res, 403, { ok: false, error: "รายชื่อโปรเจคในเครื่องเปิดได้เฉพาะเครื่องที่รันเซิร์ฟเวอร์" });
return;
}
try {
const projects = await scanLocalProjects();
sendJson(res, 200, {
ok: true,
workspace: WORKSPACE_DIR ? path.basename(WORKSPACE_DIR) : null,
projects,
});
} catch (error) {
sendJson(res, 500, { ok: false, error: `สแกนโฟลเดอร์ไม่สำเร็จ: ${error.message}` });
}
return;
}
if (pathname === "/api/projects" && req.method === "GET") {
try {
const data = await readData();
@@ -287,6 +464,16 @@ const server = createServer((req, res) => {
res.end();
return;
}
// ลิงก์ไปหน้าแรกของแต่ละโปรเจคในโฟลเดอร์ข้างเคียง (เฉพาะเครื่องนี้)
if (url.pathname === "/projects" || url.pathname.startsWith("/projects/")) {
serveWorkspace(req, res, url.pathname).catch((error) => {
res.writeHead(500, { "content-type": "text/plain; charset=utf-8" });
res.end(`อ่านโฟลเดอร์โปรเจคไม่สำเร็จ: ${error.message}`);
});
return;
}
handleApi(req, res, url.pathname).catch((error) => {
sendJson(res, 500, { ok: false, error: error.message });
});
@@ -297,4 +484,7 @@ server.listen(PORT, HOST, () => {
console.log(`[hobbypj] เซิร์ฟเวอร์ทำงานที่ http://localhost:${PORT}`);
console.log(`[hobbypj] เขียนข้อมูลได้: ${writable}`);
console.log(`[hobbypj] ไฟล์ข้อมูล: ${path.relative(ROOT, DATA_FILE)} · push: ${SHOULD_PUSH ? "เปิด" : "ปิด"}`);
console.log(
`[hobbypj] โปรเจคในเครื่อง: ${WORKSPACE_DIR ? `${WORKSPACE_DIR} → /projects/<โฟลเดอร์>/` : "ปิด"} (เฉพาะ localhost)`,
);
});