sozday-veb-prilozhenie-cyber/server.js

144 lines
7.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"use strict";
/* CyberReport: сервер на node:http без зависимостей. Данные — data.json. */
const http = require("http");
const fs = require("fs");
const path = require("path");
const crypto = require("crypto");
const PORT = process.env.PORT || 3000;
const DATA = path.join(__dirname, "data.json");
const TYPES = ["phishing", "ddos", "virus", "hack", "leak", "other"];
const LEVELS = ["low", "medium", "high"];
const STATUSES = ["new", "progress", "closed"];
const FIELDS = ["title", "date", "type", "level", "status", "description", "measures"];
function daysAgoIso(n) {
const d = new Date();
d.setDate(d.getDate() - n);
return d.getFullYear() + "-" + String(d.getMonth() + 1).padStart(2, "0") + "-" + String(d.getDate()).padStart(2, "0");
}
function demoData() {
return [
{ id: "demo-1", title: "Фишинговые письма от имени банка", date: daysAgoIso(46), type: "phishing", level: "medium", status: "closed",
description: "Сотрудникам отдела продаж пришли письма с просьбой срочно обновить данные карты. Ссылка вела на поддельную страницу банка.",
measures: "Письма заблокированы на шлюзе, домен отправителя добавлен в чёрный список, проведён инструктаж по распознаванию фишинга.", demo: true },
{ id: "demo-2", title: "DDoS-атака на сайт компании", date: daysAgoIso(34), type: "ddos", level: "high", status: "closed",
description: "Резкий рост трафика на публичном сайте, пиковая нагрузка втрое выше нормы, сервис отвечал с задержкой.",
measures: "Включена фильтрация на балансировщике, подключён внешний сервис противодействия DDoS.", demo: true },
{ id: "demo-3", title: "Вирус на рабочем месте бухгалтера", date: daysAgoIso(25), type: "virus", level: "medium", status: "progress",
description: "Антивирус обнаружил троян, загруженный вместе с макросом из Excel-файла, открытого из личного почтового ящика.",
measures: "Рабочее место изолировано, угроза удалена, пароль сотрудника изменён. Ожидается проверка связанных систем у банка.", demo: true },
{ id: "demo-4", title: "Подрыв учётных записей администратора", date: daysAgoIso(11), type: "hack", level: "high", status: "progress",
description: "Зафиксирован вход в админ-панель с нового IP-адреса. Администратор подтвердил, что входил сам, но с рабочего устройства.",
measures: "Учётная запись заблокирована, включена двухфакторная аутентификация, ведётся аудит действий за 30 дней.", demo: true },
{ id: "demo-5", title: "Подозрение на утечку клиентской базы", date: daysAgoIso(4), type: "leak", level: "medium", status: "new",
description: "Внешний сервис сообщил о файле с контактными данными клиентов, загруженном сотрудником в личное облако.",
measures: "Хранилище заблокировано, файл удалён, проводится проверка, кто и когда имел доступ к базе.", demo: true }
];
}
function readDb() {
if (fs.existsSync(DATA)) {
try {
const d = JSON.parse(fs.readFileSync(DATA, "utf8"));
if (Array.isArray(d.attacks)) return d;
} catch (e) { /* сломанное data.json — пересоздаём на демо */ }
}
const d = { attacks: demoData() };
writeDb(d);
return d;
}
function writeDb(d) {
fs.writeFileSync(DATA, JSON.stringify(d, null, 2));
}
function cleanInput(b) {
const o = {};
o.title = String(b.title || "").trim().slice(0, 300);
o.date = /^\d{4}-\d{2}-\d{2}$/.test(String(b.date || "")) ? b.date : daysAgoIso(0);
o.type = TYPES.includes(b.type) ? b.type : "other";
o.level = LEVELS.includes(b.level) ? b.level : "medium";
o.status = STATUSES.includes(b.status) ? b.status : "new";
o.description = String(b.description || "").trim().slice(0, 4000);
o.measures = String(b.measures || "").trim().slice(0, 4000);
return o;
}
function sendJson(res, code, obj) {
res.writeHead(code, { "Content-Type": "application/json; charset=utf-8" });
res.end(JSON.stringify(obj));
}
function readBody(req) {
return new Promise((resolve) => {
let s = "";
req.on("data", (c) => { s += c; if (s.length > 100000) req.destroy(); });
req.on("end", () => { try { resolve(JSON.parse(s || "{}")); } catch (e) { resolve({}); } });
});
}
const MIME = { ".html": "text/html", ".css": "text/css", ".js": "application/javascript", ".json": "application/json", ".svg": "image/svg+xml", ".png": "image/png", ".ico": "image/x-icon" };
http.createServer(async (req, res) => {
const url = req.url.split("?")[0];
const isApi = url.startsWith("/api/");
if (isApi) {
try {
if (req.method === "GET" && url === "/api/attacks") {
const db = readDb();
return sendJson(res, 200, { ok: true, attacks: db.attacks });
}
if (req.method === "POST" && url === "/api/attacks") {
const db = readDb();
const it = cleanInput(await readBody(req));
it.id = "a-" + crypto.randomBytes(6).toString("hex");
it.createdAt = new Date().toISOString();
it.updatedAt = it.createdAt;
db.attacks.push(it);
writeDb(db);
return sendJson(res, 200, { ok: true, attack: it });
}
const m = url.match(/^\/api\/attacks\/([\w-]+)$/);
if (m && req.method === "PUT") {
const db = readDb();
const it = db.attacks.find(a => a.id === m[1]);
if (!it) return sendJson(res, 404, { ok: false, error: "Атака не найдена" });
const patch = cleanInput(await readBody(req));
Object.assign(it, patch, { updatedAt: new Date().toISOString() });
writeDb(db);
return sendJson(res, 200, { ok: true, attack: it });
}
if (m && req.method === "DELETE") {
const db = readDb();
const i = db.attacks.findIndex(a => a.id === m[1]);
if (i === -1) return sendJson(res, 404, { ok: false, error: "Атака не найдена" });
db.attacks.splice(i, 1);
writeDb(db);
return sendJson(res, 200, { ok: true });
}
return sendJson(res, 404, { ok: false, error: "Не найдено" });
} catch (e) {
return sendJson(res, 500, { ok: false, error: "Ошибка сервера" });
}
}
let file = url === "/" ? "/index.html" : url;
const full = path.normalize(path.join(__dirname, file));
if (!full.startsWith(__dirname)) { res.writeHead(403); return res.end("Forbidden"); }
if (fs.existsSync(full) && fs.statSync(full).isFile()) {
const ext = path.extname(full).toLowerCase();
res.writeHead(200, { "Content-Type": (MIME[ext] || "application/octet-stream") + "; charset=utf-8" });
return res.end(fs.readFileSync(full));
}
// SPA-фолбэк: любая непустая страница отдаёт index.html
if (!/\.[a-z0-9]+$/i.test(file)) {
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
return res.end(fs.readFileSync(path.join(__dirname, "index.html")));
}
res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
res.end("Not found");
}).listen(PORT, () => console.log("CyberReport работает на порту " + PORT));