142 lines
4.7 KiB
JavaScript
142 lines
4.7 KiB
JavaScript
"use strict";
|
|
const http = require("http");
|
|
const fs = require("fs");
|
|
const path = require("path");
|
|
const fsp = fs.promises;
|
|
|
|
const PORT = process.env.PORT ? Number(process.env.PORT) : 3000;
|
|
const DATA_FILE = path.join(__dirname, "data.json");
|
|
const STATIC_DIR = __dirname;
|
|
|
|
const MIME = {
|
|
".html": "text/html; charset=utf-8",
|
|
".css": "text/css; charset=utf-8",
|
|
".js": "text/javascript; charset=utf-8",
|
|
".json": "application/json; charset=utf-8",
|
|
".png": "image/png",
|
|
".svg": "image/svg+xml",
|
|
".ico": "image/x-icon",
|
|
".woff": "font/woff",
|
|
".woff2": "font/woff2"
|
|
};
|
|
|
|
function load() {
|
|
try {
|
|
const raw = fsp.readFileSync(DATA_FILE, "utf8");
|
|
const d = JSON.parse(raw);
|
|
if (Array.isArray(d.items)) d.items = d.items.filter(i => i && i.ip !== undefined);
|
|
if (!Array.isArray(d.log)) d.log = [];
|
|
return d;
|
|
} catch (_) {
|
|
return { items: [], log: [] };
|
|
}
|
|
}
|
|
|
|
function save(d) {
|
|
fsp.writeFile(DATA_FILE, JSON.stringify(d, null, 2), "utf8").catch(e => console.error("Сохранение data.json:", e.message));
|
|
}
|
|
|
|
function readBody(req) {
|
|
return new Promise((resolve, reject) => {
|
|
let b = "";
|
|
req.on("data", c => {
|
|
b += c;
|
|
if (b.length > 2e6) {
|
|
reject(new Error("payload too large"));
|
|
req.destroy();
|
|
}
|
|
});
|
|
req.on("end", () => {
|
|
if (!b) return resolve({});
|
|
try { resolve(JSON.parse(b)); }
|
|
catch (_) { reject(new Error("bad json")); }
|
|
});
|
|
req.on("error", reject);
|
|
});
|
|
}
|
|
|
|
function send(res, code, obj, head) {
|
|
const body = JSON.stringify(obj);
|
|
const h = Object.assign({ "Content-Type": "application/json; charset=utf-8", "Content-Length": Buffer.byteLength(body) }, head || {});
|
|
res.writeHead(code, h);
|
|
res.end(body);
|
|
}
|
|
|
|
async function serveFile(req, res, pathname) {
|
|
if (pathname === "/") pathname = "/index.html";
|
|
const fp = path.normalize(path.join(STATIC_DIR, pathname));
|
|
if (!fp.startsWith(STATIC_DIR)) { res.writeHead(403); return res.end("403"); }
|
|
try {
|
|
const s = await fsp.stat(fp);
|
|
if (s.isDirectory()) {
|
|
const idx = path.join(fp, "index.html");
|
|
const st = await fsp.stat(idx);
|
|
if (!st.isFile()) { res.writeHead(404); return res.end("404"); }
|
|
return serveFile(req, res, pathname + "index.html");
|
|
}
|
|
const b = await fsp.readFile(fp);
|
|
const t = path.extname(fp).toLowerCase() in MIME ? MIME[path.extname(fp).toLowerCase()] : "application/octet-stream";
|
|
res.writeHead(200, { "Content-Type": t, "Content-Length": b.byteLength });
|
|
res.end(b);
|
|
} catch (_) {
|
|
res.writeHead(404);
|
|
res.end("404 Not Found");
|
|
}
|
|
}
|
|
|
|
const server = http.createServer(async (req, res) => {
|
|
res.setHeader("Access-Control-Allow-Origin", "*");
|
|
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
|
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
|
|
const u = req.url || "/";
|
|
const pathname = u.split("?")[0];
|
|
|
|
if (req.method === "OPTIONS") {
|
|
res.writeHead(204);
|
|
return res.end();
|
|
}
|
|
|
|
if (pathname.startsWith("/api/")) {
|
|
try {
|
|
if (pathname === "/api/items" && req.method === "GET") {
|
|
const d = load();
|
|
return send(res, 200, d, { "Access-Control-Allow-Origin": "*" });
|
|
}
|
|
if (pathname === "/api/items" && req.method === "POST") {
|
|
const body = await readBody(req);
|
|
const items = Array.isArray(body.items) ? body.items : body.items ? [body.items] : [];
|
|
const log = Array.isArray(body.log) ? body.log : null;
|
|
const d = load();
|
|
const next = { items: items, log: log || d.log };
|
|
if (log === null) next.log = d.log;
|
|
save(next);
|
|
return send(res, 200, { ok: true, count: next.items.length }, { "Access-Control-Allow-Origin": "*" });
|
|
}
|
|
if (pathname === "/api/items" && req.method === "OPTIONS") {
|
|
return send(res, 204, {}, {
|
|
"Access-Control-Allow-Origin": "*",
|
|
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
|
|
"Access-Control-Allow-Headers": "Content-Type"
|
|
});
|
|
}
|
|
if (pathname === "/api/health" && req.method === "GET") {
|
|
return send(res, 200, { ok: true }, { "Access-Control-Allow-Origin": "*" });
|
|
}
|
|
return send(res, 404, { error: "not found" }, { "Access-Control-Allow-Origin": "*" });
|
|
} catch (e) {
|
|
return send(res, e.message === "bad json" ? 400 : 500, { error: e.message }, { "Access-Control-Allow-Origin": "*" });
|
|
}
|
|
}
|
|
|
|
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
res.writeHead(405);
|
|
return res.end("405 Method Not Allowed");
|
|
}
|
|
await serveFile(req, res, pathname);
|
|
});
|
|
|
|
server.listen(PORT, () => {
|
|
const d = load();
|
|
console.log("[ip-registry] сервер запущен на порту " + PORT + " · записей: " + d.items.length + " · " + DATA_FILE);
|
|
});
|