301 lines
12 KiB
JavaScript
301 lines
12 KiB
JavaScript
#!/usr/bin/env node
|
|
/**
|
|
* server/publish.mjs — เซิร์ฟเวอร์หลังบ้าน (ไม่มี dependency ภายนอก)
|
|
*
|
|
* GET /api/projects อ่านข้อมูลปัจจุบัน
|
|
* PUT /api/projects เขียน data/projects.json แล้ว commit + push ขึ้น Gitea
|
|
* 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
|
|
*
|
|
* ความปลอดภัย:
|
|
* - ถ้าตั้ง ADMIN_TOKEN ไว้ ต้องส่ง header x-admin-token ให้ตรงทุกครั้งที่เขียน
|
|
* - ถ้าไม่ได้ตั้ง อนุญาตเฉพาะ request ที่มาจากเครื่องเดียวกัน (loopback)
|
|
*/
|
|
|
|
import { createServer } from "node:http";
|
|
import { readFile, stat, writeFile, mkdir } 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";
|
|
|
|
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);
|
|
}
|
|
|
|
async function handleApi(req, res, pathname) {
|
|
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;
|
|
}
|
|
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 ? "เปิด" : "ปิด"}`);
|
|
});
|