Debian Codegraph @

public/js/summary.js

raw symbols SCIP
1 /**
2 * dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
3 * Copyright (C) 2022-2025 Aleksey Andreev (liuch)
4 *
5 * Available at:
6 * https://github.com/liuch/dmarc-srg
7 *
8 * This program is free software: you can redistribute it and/or modify it
9 * under the terms of the GNU General Public License as published by the Free
10 * Software Foundation, either version 3 of the License.
11 *
12 * This program is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
15 * more details.
16 *
17 * You should have received a copy of the GNU General Public License along with
18 * this program. If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 class Summary {
22 constructor(id) {
23 this._element = document.getElementById("main-block");
24 this._container = null;
25 this._options_data = null;
26 this._options_block = { main: null, domains: null, period: null, button1: null, button2: null };
27 this._report_block = null;
28 }
29
30 display() {
31 this._create_container();
32 this._element.appendChild(this._container);
33 this._create_options_block();
34 this._create_report_block();
35 this._container.appendChild(this._options_block.main);
36 this._container.appendChild(document.createElement("hr"));
37 this._container.appendChild(this._report_block);
38 }
39
40 update() {
41 this._handle_url_params();
42 this._update_options_block();
43 this._fetch_report();
44 }
45
46 title() {
47 return "Summary Reports";
48 }
49
50 _handle_url_params() {
51 let url_params = new URL(document.location.href).searchParams;
52 let domain = url_params.get("domain");
53 let period = url_params.get("period");
54 let format = url_params.get("format");
55 if (domain && period) {
56 this._options_data = { domains: domain, period: period, format: format || "text" };
57 if (period.startsWith("range:")) {
58 this._options_data.range = period.substring(6).split("-").map(v => {
59 return v.replace(/^(\d{4})(\d{2})(\d{2})$/, "$1-$2-$3");
60 });
61 this._options_data.period = "range";
62 }
63 } else {
64 this._options_data = null;
65 }
66 }
67
68 _create_container() {
69 this._container = document.createElement("div");
70 this._container.setAttribute("class", "panel-container round-border");
71 }
72
73 _create_options_block() {
74 const main = document.createElement("div");
75 main.classList.add("options-block");
76
77 main.appendChild(document.createElement("h2")).textContent = "Report options:";
78
79 const list = main.appendChild(document.createElement("ul"));
80 [ [ "period" ], [ "format" ], [ "domains", "fqdn" ] ].forEach(it => {
81 const name = it[0];
82 const li = list.appendChild(document.createElement("li"));
83 li.appendChild(document.createElement("span")).textContent = `${name}: `;
84 const val = document.createElement("span");
85 li.appendChild(val).textContent = "none";
86 if (it[1]) val.classList.add(it[1]);
87 this._options_block[name] = val;
88 });
89
90 const bb = main.appendChild(document.createElement("div"));
91 bb.classList.add("buttons-block");
92
93 const btn1 = bb.appendChild(document.createElement("button"));
94 btn1.classList.add("options-button");
95 btn1.textContent = "Change the options";
96 btn1.addEventListener("click", event => this._display_dialog());
97 this._options_block.button1 = btn1;
98
99 const btn2 = bb.appendChild(document.createElement("button"));
100 btn2.classList.add("options-button", "hidden");
101 btn2.textContent = "Save CSV data to a file";
102 btn2.addEventListener("click", event => {
103 const data = Array.from(this._report_block.querySelectorAll("pre")).map(el => el.textContent);
104 const blob = new Blob(data, { type: "text/csv" });
105 const a = document.createElement("a");
106 a.href = URL.createObjectURL(blob);
107 a.download = "DMARC summary report.csv";
108 a.click();
109 setTimeout(() => URL.revokeObjectURL(a.href), 0);
110 });
111 this._options_block.button2 = btn2;
112
113 this._options_block.main = main;
114 }
115
116 _update_options_block() {
117 [ "period", "format" ].forEach(id => {
118 this._options_block[id].textContent = this._options_data && this._options_data[id] || "none";
119 });
120 if (this._options_data && this._options_data.period === "range") {
121 this._options_block.period.append(` [ ${this._options_data.range.join(" - ")} ]`);
122 }
123 const de = this._options_block.domains;
124 const dl = this._options_data && this._options_data.domains && this._options_data.domains.split(",") || [ "none" ];
125 de.replaceChildren(dl.slice(0, 3).join(", "));
126 if (dl.length > 3) {
127 const dm = document.createElement("a");
128 dm.href = "#";
129 dm.textContent = `and ${dl.length - 3} more`;
130 dm.addEventListener("click", event => {
131 event.preventDefault();
132 de.replaceChildren(dl.join(", "));
133 });
134 de.append(" ", dm);
135 }
136 }
137
138 _create_report_block() {
139 this._report_block = document.createElement("div");
140 this._report_block.setAttribute("class", "summary-report");
141 }
142
143 _display_dialog() {
144 let dlg = new OptionsDialog(this._options_data);
145 dlg.element().classList.add("report-dialog");
146 document.getElementById("main-block").appendChild(dlg.element());
147 dlg.show().then(d => {
148 if (!d) return;
149 const url = new URL(document.location.href);
150 url.searchParams.set("domain", d.domain);
151 let period = d.period;
152 if (period === "lastndays") {
153 period += ":" + d.days;
154 } else if (period === "range") {
155 period += ":" + d.range.map(val => val.replaceAll("-", "")).join("-");
156 }
157 url.searchParams.set("period", period);
158 url.searchParams.set("format", d.format);
159 window.history.replaceState(null, "", url.toString());
160 this._element.replaceChildren();
161 this.display();
162 this.update();
163 }).finally(() => {
164 dlg.element().remove();
165 this._options_block.button1.focus();
166 });
167 }
168
169 _fetch_report() {
170 this._report_block.replaceChildren();
171 if (!this._options_data) {
172 this._report_block.appendChild(document.createTextNode("Report options are not selected"));
173 return;
174 }
175 this._report_block.appendChild(set_wait_status());
176 const url = new URL("summary.php", document.location);
177 url.searchParams.set("mode", "report");
178 url.searchParams.set("domain", this._options_data.domains);
179 let period = this._options_data.period;
180 if (period === "range") {
181 period += ":" + this._options_data.range.map(r => r.replaceAll("-", "")).join("-");
182 }
183 url.searchParams.set("period", period);
184 let format = null;
185 switch (this._options_data.format) {
186 case "html":
187 format = "raw";
188 break;
189 case "csv":
190 format = "csv";
191 break;
192 default:
193 format = "text";
194 break;
195 }
196 url.searchParams.set("format", format);
197 window.fetch(url, {
198 method: "GET",
199 cache: "no-store",
200 headers: HTTP_HEADERS,
201 credentials: "same-origin"
202 }).then(resp => {
203 if (!resp.ok) throw new Error("Failed to fetch the report");
204 return resp.json();
205 }).then(data => {
206 Common.checkResult(data);
207 const overall = data.overall && (new OverallReport(data.overall)) || null;
208 this._display_report(data.reports.map(rep => new SummaryReport(format, rep)), overall);
209 }).catch(err => {
210 Common.displayError(err);
211 set_error_status(this._report_block, 'Error: ' + err.message);
212 }).finally(() => {
213 let wm = this._report_block.querySelector(".wait-message");
214 if (wm) wm.remove();
215 });
216 }
217
218 _display_report(reports, overall) {
219 function noDataElement() {
220 const el = document.createElement("p");
221 el.append("No data");
222 return el;
223 }
224 function appendText(el, text) {
225 el.appendChild(document.createElement("pre")).textContent = text;
226 }
227 function appendSeparator(el, html) {
228 if (html) {
229 el.append(document.createElement("hr"));
230 } else {
231 appendText(el, "==========\n");
232 }
233 }
234
235 let el = null;
236 if (reports.length) {
237 el = document.createDocumentFragment();
238 reports.forEach((report, index) => {
239 switch (report.format) {
240 case "raw":
241 if (!index) {
242 if (overall) {
243 el.append(overall.html());
244 appendSeparator(el, true);
245 }
246 } else {
247 appendSeparator(el, true);
248 }
249 el.append(report.html() || noDataElement());
250 break;
251 case "text":
252 {
253 if (!index) {
254 if (overall) {
255 appendText(el, overall.text());
256 appendSeparator(el, false);
257 }
258 } else {
259 appendSeparator(el, false);
260 }
261 const text = report.text();
262 if (text) {
263 appendText(el, text);
264 } else {
265 el.append(noDataElement());
266 }
267 }
268 break;
269 case "csv":
270 if (!index && overall) appendText(el, overall.csv());
271 appendText(el, report.csv());
272 break;
273 }
274 });
275 } else {
276 el = noDataElement();
277 }
278 this._report_block.appendChild(el);
279 if (this._options_data && this._options_data.format === "csv") {
280 this._options_block.button2.classList.remove("hidden");
281 } else {
282 this._options_block.button2.classList.add("hidden");
283 }
284 }
285 }
286
287 class OptionsDialog extends VerticalDialog {
288 constructor(params) {
289 super({ title: "Report options", buttons: [ "apply", "reset" ] });
290 this._data = params || {};
291 this._content = null;
292 this._domains = null;
293 this._ui_data = [
294 { name: "domains", title: "Domains", type: "multi-select" },
295 { name: "period", title: "Period" },
296 { name: "days", title: "Days", type: "input" },
297 { name: "range", title: "Range", type: "div" },
298 { name: "format", title: "Format" }
299 ];
300 }
301
302 _gen_content() {
303 this._ui_data.forEach(row => {
304 const i_el = this._insert_input_row(row.title, row.name, row.type);
305 const name = row.name;
306 if (name === "domains") {
307 i_el.setLabel("Domains");
308 } else if (name === "days") {
309 i_el.setAttribute("type", "number");
310 i_el.setAttribute("min", "1");
311 i_el.setAttribute("max", "9999");
312 i_el.setAttribute("value", "");
313 } else if (name === "range") {
314 const r1 = i_el.appendChild(document.createElement("input"));
315 r1.type = "date";
316 r1.name = "date1";
317 i_el.append(" - ");
318 const r2 = i_el.appendChild(document.createElement("input"));
319 r2.type = "date";
320 r2.name = "date2";
321 }
322 row.element = i_el;
323 });
324 this._ui_data[0].element.setAttribute("placeholder", "Pick domains");
325 this._ui_data[0].element.addEventListener("change", event => {
326 this._buttons[1].disabled = this._ui_data[0].element.isEmpty();
327 });
328 this._ui_data[1].element.addEventListener("change", event => {
329 const day_el = this._ui_data[2].element;
330 const per_el = this._ui_data[3].element;
331 const period = event.target.value;
332 if (period === "range") {
333 day_el.parentElement.classList.add("hidden");
334 per_el.parentElement.classList.remove("hidden");
335 per_el.querySelectorAll("input").forEach(inp => inp.required = true);
336 } else {
337 per_el.parentElement.classList.add("hidden");
338 day_el.parentElement.classList.remove("hidden");
339 per_el.querySelectorAll("input").forEach(inp => inp.required = false);
340 }
341 if (period === "lastndays") {
342 day_el.disabled = false;
343 delete day_el.dataset.disabled;
344 day_el.value = day_el.dataset.value || "1";
345 } else {
346 day_el.disabled = true;
347 day_el.dataset.value = day_el.value || "1";
348 day_el.dataset.disabled = true;
349 day_el.value = "";
350 }
351 });
352 this._update_period_element();
353 this._update_format_element();
354
355 if (!this._domains) {
356 this._fetch_data();
357 }
358 }
359
360 _insert_input_row(text, name, type) {
361 let el = document.createElement(type || "select");
362 el.setAttribute("name", name);
363 super._insert_input_row(text, el);
364 return el;
365 }
366
367 _submit() {
368 let res = {
369 domain: this._ui_data[0].element.getValues().join(","),
370 period: this._ui_data[1].element.value,
371 format: this._ui_data[4].element.value
372 };
373 switch (res.period) {
374 case "lastndays":
375 res.days = parseInt(this._ui_data[2].element.value) || 1;
376 break;
377 case "range":
378 res.range = Array.from(this._ui_data[3].element.querySelectorAll("input")).map(inp => inp.value);
379 if (Date.UTC(...res.range[0].split("-")) > Date.UTC(...res.range[1].split("-"))) {
380 Notification.add({ text: "Incorrect date range", type: "error" });
381 this._ui_data[3].element.querySelector("input").focus();
382 return;
383 }
384 break;
385 }
386 this._result = res;
387 this.hide();
388 }
389
390 _reset() {
391 this._ui_data[0].element.setValues(this._data.domains && this._data.domains.split(",") || []);
392 window.setTimeout(() => this._ui_data[1].element.dispatchEvent(new Event("change")), 0);
393 }
394
395 _update_domain_element() {
396 let el = this._ui_data[0].element;
397 el.clear();
398 if (this._domains) {
399 this._domains.forEach(name => el.appendItem(name));
400 }
401 if (this._data.domains) el.setValues(this._data.domains.split(","));
402 }
403
404 _update_period_element() {
405 let el = this._ui_data[1].element;
406 let c_val = this._data.period && this._data.period.split(":") || [ "lastweek" ];
407 [
408 [ "lastweek", "Last week"],
409 [ "lastmonth", "Last month" ],
410 [ "lastndays", "Last N days" ],
411 [ "range", "Date range"]
412 ].forEach(it => {
413 let opt = document.createElement("option");
414 opt.setAttribute("value", it[0]);
415 if (it[0] === c_val[0]) {
416 opt.setAttribute("selected", "");
417 }
418 el.appendChild(opt).textContent = it[1];
419 });
420 if (c_val[1]) {
421 let val = parseInt(c_val[1]);
422 let i_el = this._ui_data[2].element;
423 i_el.setAttribute("value", val);
424 i_el.dataset.value = val;
425 }
426 if (this._data.range) {
427 this._ui_data[3].element.querySelectorAll("input").forEach((el, idx) => {
428 let rv = this._data.range[idx];
429 if (rv) el.setAttribute("value", rv);
430 });
431 }
432 el.dispatchEvent(new Event("change"));
433 }
434
435 _update_format_element() {
436 let el = this._ui_data[4].element;
437 let cv = this._data.format || "text";
438 [
439 [ "text", "Plain text" ],
440 [ "html", "HTML" ],
441 [ "csv", "CSV data" ]
442 ].forEach(it => {
443 let opt = document.createElement("option");
444 opt.setAttribute("value", it[0]);
445 if (it[0] === cv) {
446 opt.setAttribute("selected", "");
447 }
448 el.appendChild(opt).textContent = it[1];
449 });
450 }
451
452 _enable_ui(enable) {
453 const dom_el = this._ui_data[0].element;
454 const controls = Array.from(this._element.querySelector("form").elements);
455 controls.push(dom_el);
456 for (const el of controls) {
457 if (el.type === "submit") {
458 el.disabled = !enable || dom_el.isEmpty();
459 } else {
460 el.disabled = !enable || el.dataset.disabled;
461 }
462 }
463 this.focus();
464 }
465
466 _fetch_data() {
467 this._enable_ui(false);
468 this.display_status("wait", "Getting data...");
469 window.fetch("summary.php?mode=options", {
470 method: "GET",
471 cache: "no-store",
472 headers: HTTP_HEADERS,
473 credentials: "same-origin"
474 }).then(resp => {
475 if (!resp.ok) throw new Error("Failed to fetch the report options list");
476 return resp.json();
477 }).then(data => {
478 Common.checkResult(data);
479 this._domains = data.domains;
480 this._update_domain_element();
481 this._enable_ui(true);
482 }).catch(err => {
483 Common.displayError(err);
484 this.display_status("error", err.message);
485 }).finally(() => {
486 this.display_status("wait", null);
487 });
488 }
489 }
490
491 class SummaryReport {
492 constructor(format, data) {
493 this.format = format;
494 this._report = data;
495 }
496
497 text() {
498 let lines = this._report.text || [];
499 if (lines.length > 0) {
500 return lines.join("\n");
501 }
502 }
503
504 csv() {
505 return this._report.csv || "";
506 }
507
508 html() {
509 const data = this._report.data;
510 const html = document.createDocumentFragment();
511
512 html.appendChild(document.createElement("h2")).textContent = "Domain: " + this._report.domain;
513 html.appendChild(document.createElement("div")).append(
514 "Range: ", (new Date(data.date_range.begin)).toUIDateString(true),
515 " - ", (new Date(data.date_range.end)).toUIDateString(true)
516 );
517
518 {
519 html.appendChild(document.createElement("h3")).textContent = "Summary";
520 const cont = html.appendChild(document.createElement("div"));
521 cont.classList.add("left-titled");
522 const emails = data.summary.emails;
523 const total = emails.total;
524 cont.append(SummaryReport.makeSummaryRow("Total", total, null, null));
525 const f_aligned = emails.dkim_spf_aligned;
526 const p_aligned = emails.dkim_aligned + emails.spf_aligned;
527 const n_aligned = total - f_aligned - p_aligned;
528 const rejected = emails.rejected;
529 const quarantined = emails.quarantined;
530 [
531 [ "Fully aligned", f_aligned, "pass" ], [ "Partial aligned", p_aligned, null ],
532 [ "Not aligned", n_aligned, "fail" ], [ "Quarantined", quarantined, "fail" ],
533 [ "Rejected", rejected, "fail" ]
534 ].forEach(it => cont.append(SummaryReport.makeSummaryRow(it[0], it[1], total, it[2])));
535 }
536 if (data.sources && data.sources.length) {
537 html.appendChild(document.createElement("h3")).textContent = "Sources";
538 const table = html.appendChild(document.createElement("table"));
539 table.classList.add("report-table");
540 table.appendChild(document.createElement("caption")).textContent = "Total records: " + data.sources.length;
541 const thead = document.createElement("thead");
542 table.appendChild(thead);
543 thead.append(SummaryReport.makeHeaderRow([
544 [ "IP address", 0, 2 ], [ "Email volume", 0, 2 ], [ "Partial aligned", 2, 0 ],
545 [ "Not aligned", 0, 2 ], [ "Disposition", 2, 0 ]
546 ]));
547 thead.append(SummaryReport.makeHeaderRow(
548 [ [ "SPF only" ], [ "DKIM only" ], [ "quar+rej" ], [ "fail rate" ] ]
549 ));
550 const tbody = table.appendChild(document.createElement("tbody"));
551 data.sources.forEach(sou => {
552 const tr = tbody.appendChild(document.createElement("tr"));
553 [ Common.makeIpElement(sou.ip), sou.emails, sou.spf_aligned, sou.dkim_aligned ].forEach(
554 v => tr.append(SummaryReport.makeResultElement("td", v, null))
555 );
556 const dq = sou.quarantined;
557 const dr = sou.rejected;
558 const ds = dq || dr ? `${dq.toLocaleString()}+${dr.toLocaleString()}` : 0;
559 [
560 sou.emails - sou.dkim_aligned - sou.spf_aligned - sou.dkim_spf_aligned, ds
561 ].forEach(v => tr.append(SummaryReport.makeResultElement("td", v, "fail")));
562 tr.append(SummaryReport.makeResultElement("td", SummaryReport.num2percent(dq + dr, sou.emails, false)));
563 });
564 }
565 if (data.organizations && data.organizations.length) {
566 html.appendChild(document.createElement("h3")).textContent = "Reporting organizations";
567 const table = html.appendChild(document.createElement("table"));
568 table.classList.add("report-table");
569
570 table.appendChild(document.createElement("caption")).textContent = "Total records: " + data.organizations.length;
571 const thead = table.appendChild(document.createElement("thead"));
572 thead.append(SummaryReport.makeHeaderRow([
573 [ "Name", 0, 2 ], [ "Volume", 2, 0 ], [ "Partial aligned", 2, 0 ],
574 [ "Not aligned", 0, 2 ], [ "Disposition", 2, 0 ]
575 ]));
576 thead.append(SummaryReport.makeHeaderRow([
577 [ "reports" ], [ "emails" ], [ "SPF only" ], [ "DKIM only" ], [ "quar+rej" ], [ "fail rate" ]
578 ]));
579 const tbody = table.appendChild(document.createElement("tbody"));
580 data.organizations.forEach(org => {
581 const tr = tbody.appendChild(document.createElement("tr"));
582 [
583 org.name, org.reports, org.emails, org.spf_aligned, org.dkim_aligned
584 ].forEach(v => tr.append(SummaryReport.makeResultElement("td", v)));
585 const dq = org.quarantined;
586 const dr = org.rejected;
587 const ds = dq || dr ? `${dq.toLocaleString()}+${dr.toLocaleString()}` : 0;
588 [
589 org.emails - org.dkim_aligned - org.spf_aligned - org.dkim_spf_aligned, ds
590 ].forEach(v => tr.append(SummaryReport.makeResultElement("td", v, "fail")));
591 tr.append(SummaryReport.makeResultElement("td", SummaryReport.num2percent(dq + dr, org.emails, false)));
592 });
593 }
594 return html;
595 }
596
597 static num2percent(per, cent, with_num) {
598 if (!per) return 0;
599 let res = "" + Math.round(per / cent * 100) + "%";
600 if (with_num) res += " (" + per + ")";
601 return res;
602 }
603
604 static makeSummaryRow(title, value, total, type) {
605 const re = document.createDocumentFragment();
606 const te = re.appendChild(document.createElement("span"));
607 te.textContent = title + ": ";
608 if (total) {
609 re.append(SummaryReport.makeResultElement("span", SummaryReport.num2percent(value, total, true), type));
610 } else {
611 re.append(value);
612 }
613 return re;
614 }
615
616 static makeHeaderRow(data) {
617 const tr = document.createElement("tr");
618 data.forEach(row => {
619 const td = tr.appendChild(document.createElement("th"));
620 if (row[1]) td.colSpan = row[1];
621 if (row[2]) td.rowSpan = row[2];
622 td.textContent = row[0];
623 });
624 return tr;
625 }
626
627 static makeResultElement(name, value, type) {
628 const el = document.createElement(name);
629 if (value && type) el.classList.add("report-result-" + type);
630 el.append(typeof(value) === "number" ? value.toLocaleString() : value);
631 return el;
632 }
633 }
634
635 class OverallReport extends SummaryReport {
636 constructor(data) {
637 super("overall", data);
638 }
639
640 html() {
641 const html = document.createDocumentFragment();
642 html.appendChild(document.createElement("h2")).textContent = "Overall by domains";
643 const table = html.appendChild(document.createElement("table"));
644 table.classList.add("report-table");
645 table.appendChild(document.createElement("caption")).textContent = "Total records: " + this._report.data.length;
646 const thead = table.appendChild(document.createElement("thead"));
647 thead.append(SummaryReport.makeHeaderRow([
648 [ "Name", 0, 2 ], [ "Emails", 0, 2 ], [ "Partial aligned", 2, 0 ],
649 [ "Not aligned", 0, 2 ], [ "Disposition", 2, 0 ]
650 ]));
651 thead.append(SummaryReport.makeHeaderRow([
652 [ "SPF only" ], [ "DKIM only" ], [ "quar+rej" ], [ "fail rate" ]
653 ]));
654 const tbody = table.appendChild(document.createElement("tbody"));
655 this._report.data.forEach(d => {
656 const tr = tbody.appendChild(document.createElement("tr"));
657 [
658 d.fqdn, d.total, d.spf_aligned, d.dkim_aligned
659 ].forEach(v => tr.append(SummaryReport.makeResultElement("td", v)));
660 const dq = d.quarantined;
661 const dr = d.rejected;
662 const ds = (dq || dr) ? `${dq.toLocaleString()}+${dr.toLocaleString()}` : 0;
663 [
664 d.total - d.dkim_aligned - d.spf_aligned - d.dkim_spf_aligned, ds
665 ].forEach(v => tr.append(SummaryReport.makeResultElement("td", v, "fail")));
666 tr.append(SummaryReport.makeResultElement("td", SummaryReport.num2percent(dq + dr, d.total, false)));
667 });
668 return html;
669 }
670 }