- server/db.mjs: schema (site + projects), transactional replace, WAL, VACUUM INTO backups (keep 10), JSON export, first-run seed from data/projects.json - publish.mjs: read/write through the database, export mirror JSON for git/static/offline, validate duplicate project_id - ui/data.js: read live data from /api/projects first, fall back to data/projects.json - Dockerfile/compose/.env.example: DB_PATH, drop experimental sqlite warning flag - docs: AGENTS.md + README describe the database layer and traps
306 lines
12 KiB
JavaScript
306 lines
12 KiB
JavaScript
#!/usr/bin/env node
|
|
/**
|
|
* server/publish.mjs — เซิร์ฟเวอร์หลังบ้าน (ไม่มี dependency ภายนอก)
|
|
*
|
|
* GET /api/projects อ่านข้อมูลปัจจุบันจาก SQLite
|
|
* PUT /api/projects เขียนลง SQLite → export data/projects.json → commit + push ขึ้น Gitea
|
|
* static เสิร์ฟไฟล์หน้าเว็บจาก root ของโปรเจค
|
|
*
|
|
* ข้อมูลจริงอยู่ใน `data/hobbypj.sqlite` (SQLite ผ่าน node:sqlite, override ด้วย DB_PATH)
|
|
* `data/projects.json` เป็นสำเนาที่ export ออกมาทุกครั้งที่บันทึก
|
|
*
|
|
* ใช้งาน:
|
|
* 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 } 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";
|
|
import {
|
|
backupDatabase,
|
|
countProjects,
|
|
exportJson,
|
|
openDatabase,
|
|
readData,
|
|
resolveDbPath,
|
|
saveData,
|
|
seedFromJson,
|
|
} from "./db.mjs";
|
|
|
|
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 DB_FILE = resolveDbPath(ROOT);
|
|
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;
|
|
}
|
|
const seen = new Set();
|
|
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}: อีเมลไม่ถูกต้อง`);
|
|
const id = String(project.project_id || "").trim();
|
|
if (!id) errors.push(`${label}: ไม่มีรหัสโปรเจค (project_id)`);
|
|
else if (seen.has(id)) errors.push(`${label}: รหัสโปรเจคซ้ำ (${id})`);
|
|
else seen.add(id);
|
|
});
|
|
return errors;
|
|
}
|
|
|
|
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 handleApi(req, res, pathname) {
|
|
if (pathname === "/api/projects" && req.method === "GET") {
|
|
try {
|
|
sendJson(res, 200, { ok: true, writable: canWrite(req) || isLoopback(req), data: readData(db) });
|
|
} 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 {
|
|
// สำรองสภาพก่อนแก้ (ถ้ามีข้อมูลอยู่) แล้วค่อยเขียนทับในทรานแซกชันเดียว
|
|
const backup = countProjects(db) > 0 ? await backupDatabase(db, DB_FILE).catch(() => null) : null;
|
|
payload.updated_at = saveData(db, payload);
|
|
await exportJson(DATA_FILE, { ...payload, updated_at: payload.updated_at });
|
|
payload.backup = backup ? path.relative(ROOT, backup) : null;
|
|
} 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,
|
|
database: path.relative(ROOT, DB_FILE),
|
|
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>`,
|
|
);
|
|
}
|
|
}
|
|
|
|
// เปิดฐานข้อมูล + ย้ายข้อมูลจาก data/projects.json ครั้งแรก (ถ้าตารางว่าง)
|
|
const db = await openDatabase(DB_FILE);
|
|
const seed = await seedFromJson(db, DATA_FILE);
|
|
|
|
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, DB_FILE)} (SQLite) · สำเนา JSON: ${path.relative(ROOT, DATA_FILE)} · push: ${SHOULD_PUSH ? "เปิด" : "ปิด"}`,
|
|
);
|
|
console.log(
|
|
seed.seeded
|
|
? `[hobbypj] ย้ายข้อมูลจาก projects.json เข้าฐานข้อมูลแล้ว ${seed.count} รายการ`
|
|
: `[hobbypj] ฐานข้อมูลพร้อมใช้ (${seed.reason})`,
|
|
);
|
|
});
|