Files
hobbypj-contents/server/publish.mjs
T
Bkk1234 db7724b237 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
2026-11-20 14:26:54 +07:00

491 lines
20 KiB
JavaScript

#!/usr/bin/env node
/**
* server/publish.mjs — เซิร์ฟเวอร์หลังบ้าน (ไม่มี dependency ภายนอก)
*
* 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 { 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";
import path from "node:path";
import { fileURLToPath } from "node:url";
const execFileAsync = promisify(execFile);
const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, "..");
const DATA_FILE = path.join(ROOT, "data", "projects.json");
const PORT = Number(process.env.PORT || 8090);
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",
".js": "text/javascript; charset=utf-8",
".mjs": "text/javascript; charset=utf-8",
".json": "application/json; charset=utf-8",
".webmanifest": "application/manifest+json; charset=utf-8",
".png": "image/png",
".jpg": "image/jpeg",
".svg": "image/svg+xml",
".ico": "image/x-icon",
".woff2": "font/woff2",
".txt": "text/plain; charset=utf-8",
};
const NO_CACHE = {
"cache-control": "no-cache, no-store, must-revalidate",
"access-control-allow-origin": "*",
};
function sendJson(res, status, body) {
const payload = JSON.stringify(body, null, 2);
res.writeHead(status, {
"content-type": "application/json; charset=utf-8",
"content-length": Buffer.byteLength(payload),
...NO_CACHE,
});
res.end(payload);
}
function isLoopback(req) {
const address = req.socket.remoteAddress || "";
return address === "127.0.0.1" || address === "::1" || address === "::ffff:127.0.0.1";
}
function tokenMatches(provided) {
if (!ADMIN_TOKEN) return false;
const a = Buffer.from(String(provided || ""), "utf8");
const b = Buffer.from(ADMIN_TOKEN, "utf8");
if (a.length !== b.length) return false;
return timingSafeEqual(a, b);
}
function canWrite(req) {
if (!ADMIN_TOKEN) return isLoopback(req);
return tokenMatches(req.headers["x-admin-token"]);
}
function validate(payload) {
const errors = [];
if (!payload || typeof payload !== "object") return ["ข้อมูลที่ส่งมาไม่ใช่ JSON object"];
const site = payload.site;
if (!site || typeof site !== "object") errors.push("ขาดข้อมูล site");
else {
if (typeof site.welcome_message !== "string" || !site.welcome_message.trim())
errors.push("ข้อความต้อนรับว่าง");
}
if (!Array.isArray(payload.projects)) {
errors.push("projects ต้องเป็น array");
return errors;
}
payload.projects.forEach((project, index) => {
const label = `รายการที่ ${index + 1}`;
if (!project || typeof project !== "object") {
errors.push(`${label}: ไม่ใช่ object`);
return;
}
if (!String(project.project_name || "").trim()) errors.push(`${label}: ไม่มีชื่อโปรเจค`);
const url = String(project.project_url || "").trim();
if (!/^https?:\/\/[^\s/?#]+\.[^\s/?#]+/i.test(url))
errors.push(`${label}: ลิงก์ไม่ถูกต้อง (${url || "ว่าง"})`);
if (project.contact_email && !/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(String(project.contact_email).trim()))
errors.push(`${label}: อีเมลไม่ถูกต้อง`);
});
return errors;
}
/** เขียน payload ให้คีย์เรียงคงที่ อ่านง่ายแบบมนุษย์ + ลงท้ายด้วย newline */
function serialize(payload) {
const ordered = {
schema_version: 1,
updated_at: payload.updated_at,
owner_name: payload.owner_name || "",
site: {
site_title: payload.site.site_title || "",
welcome_message: payload.site.welcome_message || "",
},
projects: payload.projects.map((project) => ({
project_id: String(project.project_id || "").trim(),
project_name: String(project.project_name || "").trim(),
project_description: String(project.project_description || "").trim(),
project_url: String(project.project_url || "").trim().replace(/\/$/, ""),
contact_email: String(project.contact_email || "").trim(),
icon: String(project.icon || "folder").trim(),
})),
};
return `${JSON.stringify(ordered, null, 2)}\n`;
}
async function gitPublish() {
const rel = path.relative(ROOT, DATA_FILE);
const result = { committed: false, pushed: false, commit: null, message: "" };
try {
await execFileAsync("git", ["-C", ROOT, "add", rel]);
const changed = await execFileAsync("git", ["-C", ROOT, "status", "--porcelain", "--", rel]);
if (!changed.stdout.trim()) {
result.message = "ไฟล์ไม่เปลี่ยน ไม่มี commit ใหม่";
return result;
}
const commit = await execFileAsync("git", [
"-C",
ROOT,
"-c",
"user.name=" + (process.env.GIT_AUTHOR_NAME || "hobbypj-backoffice"),
"-c",
"user.email=" + (process.env.GIT_AUTHOR_EMAIL || "[email protected]"),
"commit",
"-m",
"content: update project list from backoffice",
]);
result.committed = true;
result.commit = (commit.stdout.match(/\[[^\]]+ ([0-9a-f]{7,})\]/) || [])[1] || null;
if (!SHOULD_PUSH) {
result.message = "commit แล้ว (ข้าม push ตาม PUBLISH_PUSH=0)";
return result;
}
await execFileAsync("git", ["-C", ROOT, "-c", "http.version=HTTP/1.1", "push", "origin", "HEAD"]);
result.pushed = true;
result.message = "commit + push เรียบร้อย";
return result;
} catch (error) {
const detail = (error.stderr || error.stdout || error.message || "").toString().trim();
result.message = `git ผิดพลาด: ${detail.split("\n").slice(0, 3).join(" | ")}`;
return result;
}
}
async function readData() {
const raw = await readFile(DATA_FILE, "utf8");
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();
sendJson(res, 200, { ok: true, writable: canWrite(req) || isLoopback(req), data });
} catch (error) {
sendJson(res, 500, { ok: false, error: `อ่านไฟล์ข้อมูลไม่ได้: ${error.message}` });
}
return;
}
if (pathname === "/api/projects" && req.method === "PUT") {
if (!canWrite(req)) {
sendJson(res, 403, {
ok: false,
error: ADMIN_TOKEN ? "รหัสเผยแพร่ไม่ถูกต้อง" : "อนุญาตเฉพาะเครื่องที่รันเซิร์ฟเวอร์",
});
return;
}
let body = "";
for await (const chunk of req) {
body += chunk;
if (body.length > 1_000_000) {
sendJson(res, 413, { ok: false, error: "ข้อมูลใหญ่เกินไป" });
return;
}
}
let payload;
try {
payload = JSON.parse(body);
} catch {
sendJson(res, 400, { ok: false, error: "JSON ไม่ถูกต้อง" });
return;
}
const errors = validate(payload);
if (errors.length) {
sendJson(res, 422, { ok: false, error: errors.join(" · "), errors });
return;
}
try {
payload.updated_at = new Date().toISOString();
await mkdir(path.dirname(DATA_FILE), { recursive: true });
await writeFile(DATA_FILE, serialize(payload), "utf8");
} catch (error) {
sendJson(res, 500, { ok: false, error: `เขียนไฟล์ไม่ได้: ${error.message}` });
return;
}
const git = await gitPublish();
sendJson(res, 200, {
ok: true,
updated_at: payload.updated_at,
projects: payload.projects.length,
git,
});
return;
}
if (pathname.startsWith("/api/")) {
sendJson(res, 404, { ok: false, error: "ไม่พบ API นี้" });
return;
}
serveStatic(req, res, pathname);
}
async function serveStatic(req, res, pathname) {
let rel = decodeURIComponent(pathname);
if (rel.endsWith("/")) rel += "index.html";
const filePath = path.resolve(ROOT, `.${rel}`);
if (!filePath.startsWith(ROOT) || filePath.includes(`${path.sep}.git${path.sep}`)) {
res.writeHead(403).end("Forbidden");
return;
}
try {
const info = await stat(filePath);
if (info.isDirectory()) {
res.writeHead(301, { location: `${pathname}/` }).end();
return;
}
const ext = path.extname(filePath).toLowerCase();
const headers = { "content-type": MIME[ext] || "application/octet-stream" };
if ([".html", ".css", ".js", ".mjs", ".json"].includes(ext) || ext === "") {
Object.assign(headers, NO_CACHE);
} else {
headers["cache-control"] = "public, max-age=86400";
}
headers["service-worker-allowed"] = "/";
res.writeHead(200, headers);
res.end(await readFile(filePath));
} 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>`,
);
}
}
const server = createServer((req, res) => {
const url = new URL(req.url || "/", `http://${req.headers.host || "localhost"}`);
if (req.method === "OPTIONS") {
res.writeHead(204, {
"access-control-allow-origin": "*",
"access-control-allow-methods": "GET, PUT, OPTIONS",
"access-control-allow-headers": "content-type, x-admin-token",
"access-control-max-age": "600",
});
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 });
});
});
server.listen(PORT, HOST, () => {
const writable = ADMIN_TOKEN ? "เฉพาะผู้มีรหัสเผยแพร่" : "เฉพาะเครื่องนี้ (ยังไม่ตั้ง ADMIN_TOKEN)";
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)`,
);
});