"use strict"; /* CyberReport: ядро — справочники, состояние, API, утилиты. */ const CR = window.CR = {}; CR.icon = (name) => ''; /* ---------- Справочники ---------- */ CR.ATTACK_TYPES = [ { id: "phishing", label: "Фишинг" }, { id: "ddos", label: "DDoS" }, { id: "virus", label: "Вирус" }, { id: "hack", label: "Взлом" }, { id: "leak", label: "Утечка данных" }, { id: "other", label: "Другое" } ]; CR.LEVELS = [ { id: "low", label: "Низкий", tone: "ok" }, { id: "medium", label: "Средний", tone: "warn" }, { id: "high", label: "Высокий", tone: "risk" } ]; CR.STATUSES = [ { id: "new", label: "Новый", tone: "info" }, { id: "progress", label: "В работе", tone: "warn" }, { id: "closed", label: "Закрыт", tone: "ok" } ]; CR.typeLabel = (id) => (CR.ATTACK_TYPES.find(t => t.id === id) || {}).label || "—"; CR.levelLabel = (id) => (CR.LEVELS.find(l => l.id === id) || {}).label || "—"; CR.levelTone = (id) => (CR.LEVELS.find(l => l.id === id) || {}).tone || "muted"; CR.statusLabel = (id) => (CR.STATUSES.find(s => s.id === id) || {}).label || "—"; CR.statusTone = (id) => (CR.STATUSES.find(s => s.id === id) || {}).tone || "muted"; /* ---------- Форматирование ---------- */ function pad2(n) { return String(n).padStart(2, "0"); } CR.fmtDate = (iso) => { if (!iso) return "—"; const d = new Date(iso); if (isNaN(d)) return String(iso); return pad2(d.getDate()) + "." + pad2(d.getMonth() + 1) + "." + d.getFullYear(); }; CR.fmtShortDate = (iso) => { if (!iso) return ""; const d = new Date(iso); if (isNaN(d)) return ""; return pad2(d.getDate()) + "." + pad2(d.getMonth() + 1); }; CR.fmtDateTime = (iso) => { if (!iso) return "—"; const d = new Date(iso); if (isNaN(d)) return String(iso); return CR.fmtDate(iso) + " " + pad2(d.getHours()) + ":" + pad2(d.getMinutes()); }; CR.todayIso = () => { const d = new Date(); return d.getFullYear() + "-" + pad2(d.getMonth() + 1) + "-" + pad2(d.getDate()); }; CR.daysAgoIso = (n) => { const d = new Date(); d.setDate(d.getDate() - n); return d.getFullYear() + "-" + pad2(d.getMonth() + 1) + "-" + pad2(d.getDate()); }; CR.esc = (s) => String(s == null ? "" : s) .replace(/&/g, "&").replace(//g, ">") .replace(/"/g, """).replace(/'/g, "'"); CR.pill = (label, tone) => '' + CR.esc(label) + ""; CR.demoPill = () => 'Демо'; /* ---------- Состояние ---------- */ CR.state = { view: "home", attacks: [], online: false, loading: true, filters: { search: "", type: "", level: "", status: "", dateFrom: "", dateTo: "" }, report: { from: CR.daysAgoIso(90), to: CR.todayIso(), generated: null } }; try { const saved = JSON.parse(localStorage.getItem("cr-filters") || "{}"); Object.assign(CR.state.filters, saved); } catch (e) { /* localStorage сломан — фильтры дефолтные */ } CR.setFilter = (key, val) => { CR.state.filters[key] = val; const f = CR.state.filters; const saved = { search: f.search, dateFrom: f.dateFrom, dateTo: f.dateTo }; if (f.search === "" && !f.dateFrom && !f.dateTo) localStorage.removeItem("cr-filters"); else localStorage.setItem("cr-filters", JSON.stringify(saved)); CR.refresh(); }; CR.current = () => CR.state.attacks.find(a => a.id === CR.state.detailId) || null; CR.refresh = () => CR.render(); CR.openDrawer = (html) => { const el = document.getElementById("drawer"); el.innerHTML = html; el.hidden = false; }; CR.closeDrawer = () => { const el = document.getElementById("drawer"); el.hidden = true; el.innerHTML = ""; }; document.addEventListener("keydown", (e) => { if (e.key === "Escape") CR.closeDrawer(); }); CR.toast = function (msg, tone) { const stack = document.getElementById("toasts"); if (!stack) return; const el = document.createElement("div"); el.className = "kt-ai-toast"; el.dataset.tone = tone || "ok"; el.textContent = msg; stack.appendChild(el); setTimeout(() => { el.style.opacity = "0"; el.style.transition = "opacity .3s"; setTimeout(() => el.remove(), 320); }, 4500); }; /* ---------- API ---------- */ CR.api = async (path, opts) => { const res = await fetch("api/" + path, opts); const j = await res.json().catch(() => ({})); if (!res.ok) throw new Error(j.error || ("Ошибка " + res.status)); return j; }; CR.loadAttacks = async () => { CR.state.loading = true; CR.renderView(); try { const d = await CR.api("attacks"); CR.state.attacks = d.attacks || []; CR.state.online = true; } catch (e) { CR.state.online = false; CR.state.attacks = []; } CR.state.loading = false; CR.renderView(); }; CR.saveAttack = async (id, data) => { if (id) { await CR.api("attacks/" + id, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) }); } else { await CR.api("attacks", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) }); } await CR.loadAttacks(); }; /* ---------- Выборка ---------- */ CR.visible = () => { const f = CR.state.filters; return CR.state.attacks .filter(a => { if (f.search) { const q = f.search.toLowerCase(); const hay = (a.title + " " + CR.typeLabel(a.type) + " " + a.description + " " + a.measures).toLowerCase(); if (!hay.includes(q)) return false; } if (f.type && a.type !== f.type) return false; if (f.level && a.level !== f.level) return false; if (f.status && a.status !== f.status) return false; if (f.dateFrom && a.date < f.dateFrom) return false; if (f.dateTo && a.date > f.dateTo) return false; return true; }) .sort((a, b) => b.date.localeCompare(a.date)); }; CR.resetFilters = () => { CR.state.filters = { search: "", type: "", level: "", status: "", dateFrom: "", dateTo: "" }; localStorage.removeItem("cr-filters"); CR.refresh(); }; CR.navigate = (view) => { CR.state.view = view; CR.closeDrawer(); CR.renderView(); }; CR.renderView = () => { const view = document.getElementById("view"); if (!view) return; const s = CR.state; if (s.loading && s.view !== "report") { view.innerHTML = '
Загрузка…
Соединяемся с сервером
'; return; } if (!s.online && s.attacks.length === 0) { view.innerHTML = '
' + CR.icon("warning") + " Сервер данных недоступен: приложение нужно запустить командой «run». Данные не загружены.
"; return; } if (s.view === "reports") CR.Reports.render(view); else CR.Attacks.render(view); }; CR.render = () => { const s = CR.state; document.querySelectorAll("[data-nav]").forEach(b => b.dataset.active = String(b.dataset.nav === s.view)); const title = { home: ["Главная", "сводка по кибератакам"], attacks: ["Кибератаки", "реестр атак: поиск, фильтры, добавление"], reports: ["Отчёты", "отчёт за период и выгрузка"] }[s.view] || ["", ""]; document.getElementById("crumb-title").textContent = title[0]; const crumbSub = document.getElementById("crumb-sub"); if (crumbSub) crumbSub.textContent = title[1]; document.title = "Отчёты по кибератакам — " + title[0]; if (s.view === "attacks") { const el = document.getElementById("top-search"); if (el) { el.style.display = ""; el.value = s.filters.search; } } else { const el = document.getElementById("top-search"); if (el) el.style.display = "none"; } CR.renderView(); };