Debian Codegraph @

public/js/report.js

raw symbols SCIP
1 /**
2 * dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
3 * Copyright (C) 2020-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 ReportWidget {
22 constructor() {
23 this._rep_id = null;
24 this._element = null;
25 this._close_btn = null;
26 this._id_element = null;
27 this._cn_element = null;
28 this._onclose_act = null;
29 }
30
31 display() {
32 if (!this._element || !document.contains(this._element)) {
33 let cn = document.getElementById("main-block");
34 cn.appendChild(this.element());
35 }
36 }
37
38 update() {
39 this.show_report().catch(function(err) {
40 Common.displayError(err);
41 });
42 }
43
44 onpopstate() {
45 this.display();
46 this.update();
47 }
48
49 oncleardata() {
50 if (!this._element || !document.contains(this._element)) {
51 document.getElementById("main-block").replaceChildren();
52 document.getElementById("detail-block").replaceChildren();
53 }
54 }
55
56 show_report(domain, report_time, org, report_id, filter) {
57 this.element();
58 let that = this;
59 return new Promise(function(resolve, reject) {
60 if (!domain || !report_time || !org || !report_id) {
61 let sp = (new URL(document.location)).searchParams;
62 domain = sp.get("domain");
63 report_time = sp.get("time");
64 org = sp.get("org");
65 report_id = sp.get("report_id");
66 if (!domain || !report_time || !org || !report_id) {
67 let err_msg = "Domain, report time, reporting organization, report ID must be specified";
68 set_error_status(that._cn_element, err_msg);
69 reject(new Error(err_msg));
70 }
71 }
72 that._id_element.childNodes[0].nodeValue = report_id;
73 set_wait_status(that._cn_element);
74 that._rep_id = report_id + report_time;
75 that._element.classList.remove("report-hidden");
76 that._close_btn.classList.add("active");
77 let rep = new Report(domain, report_time, org, report_id, filter);
78 rep.fetch().then(function() {
79 if (that._rep_id === report_id + report_time) {
80 that._cn_element.replaceChildren(rep.element());
81 rep.set_value("seen", true);
82 }
83 resolve();
84 }).catch(function(err) {
85 let err_str = rep.error_message() || "Failed to get the report data";
86 set_error_status(that._cn_element, err_str);
87 reject(err);
88 });
89 });
90 }
91
92 element() {
93 if (!this._element) {
94 this._gen_element();
95 }
96 return this._element;
97 }
98
99 title() {
100 return "Report Detail";
101 }
102
103 focus() {
104 let el = this._element;
105 if (el)
106 el.focus();
107 }
108
109 hide() {
110 if (this._element && !this._element.classList.contains("report-hidden")) {
111 this._element.classList.add("report-hidden");
112 this._close_btn.classList.remove("active");
113 return true;
114 }
115 return false;
116 }
117
118 close() {
119 if (this.hide() && this._onclose_act)
120 this._onclose_act();
121 }
122
123 onclose(fn) {
124 this._onclose_act = typeof(fn) == "function" && fn || null;
125 }
126
127 _gen_element() {
128 let el = document.createElement("div");
129 el.setAttribute("class", "report-modal report-hidden");
130 el.setAttribute("tabindex", -1);
131 el.addEventListener("click", function(event) {
132 if (event.target.classList.contains("close-btn") || event.target.classList.contains("report-header")) {
133 if (window.history.state && window.history.state.from === "list")
134 this.close();
135 else
136 window.history.go(-1);
137 }
138 }.bind(this));
139
140 let hd = document.createElement("div");
141 hd.setAttribute("class", "report-header");
142 {
143 let ht = document.createElement("span");
144 ht.setAttribute("class", "header-text");
145 ht.appendChild(document.createTextNode("DMARC Report (Id: "));
146
147 let id = document.createElement("span");
148 id.setAttribute("id", "report-modal-id");
149 id.appendChild(document.createTextNode("?"));
150 this._id_element = id;
151 ht.appendChild(id);
152
153 ht.appendChild(document.createTextNode(")"));
154 hd.appendChild(ht);
155 }
156 el.appendChild(hd);
157
158 let bd = document.createElement("div");
159 bd.setAttribute("class", "body");
160
161 let cn = document.createElement("div");
162 cn.setAttribute("class", "content");
163 this._cn_element = cn;
164 bd.appendChild(cn);
165
166 let cb = document.createElement("button");
167 cb.setAttribute("class", "btn close-btn");
168 cb.appendChild(document.createTextNode("Close"));
169 this._close_btn = cb;
170 bd.appendChild(cb);
171
172 el.appendChild(bd);
173
174 this._element = el;
175 }
176 }
177
178 ReportWidget.instance = function() {
179 if (!ReportWidget._instance) {
180 ReportWidget._instance = new ReportWidget();
181 ReportWidget._instance.onclose(function() {
182 window.history.go(-1);
183 });
184 }
185 return ReportWidget._instance;
186 }
187
188 class Report {
189 constructor(domain, report_time, org, report_id, filter) {
190 this._data = null;
191 this._error = false;
192 this._filter_btn = null;
193 this._records_el = null;
194 this._error_message = null;
195 this._org = org;
196 this._domain = domain;
197 this._report_id = report_id;
198 this._report_time = report_time;
199 if (Common.rv_filter === "from-list")
200 this._filter = filter;
201 else
202 this._filter = this._filter_storage();
203 this._filter ||= {};
204 }
205
206 id() {
207 return this._report_id;
208 }
209
210 error() {
211 return this._error;
212 }
213
214 error_message() {
215 return this._error_message;
216 }
217
218 fetch() {
219 let url = new URL("report.php", document.location);
220 let u_params = url.searchParams;
221 u_params.set("org", this._org);
222 u_params.set("time", this._report_time);
223 u_params.set("domain", this._domain);
224 u_params.set("report_id", this._report_id);
225
226 let that = this;
227 return window.fetch(url, {
228 method: "GET",
229 cache: "no-store",
230 headers: HTTP_HEADERS,
231 credentials: "same-origin"
232 }).then(function(resp) {
233 if (!resp.ok)
234 throw new Error("Failed to fetch report data");
235 return resp.json();
236 }).then(function(data) {
237 Common.checkResult(data);
238 that._data = data.report;
239 that._error = false;
240 that._error_message = null;
241 }).catch(function(err) {
242 that._data = null;
243 that._error = true;
244 that._error_message = err.message;
245 throw err;
246 });
247 }
248
249 element() {
250 let el = this._create_element();
251 this._apply_filter();
252 this._update_filter_button();
253 return el;
254 }
255
256 set_value(name, value) {
257 let definitions = {
258 "seen": "boolean"
259 };
260
261 if (value === undefined || definitions[name] !== typeof(value)) {
262 console.warn("Set report value: Incorrect value");
263 return Promise.resolve({});
264 }
265
266 let url = new URL("report.php", document.location);
267 let url_params = url.searchParams;
268 url_params.set("action", "set");
269 url_params.set("org", this._org);
270 url_params.set("time", this._report_time);
271 url_params.set("domain", this._domain);
272 url_params.set("report_id", this._report_id);
273 return window.fetch(url, {
274 method: "POST",
275 cache: "no-store",
276 headers: Object.assign(HTTP_HEADERS, HTTP_HEADERS_POST),
277 credentials: "same-origin",
278 body: JSON.stringify({ name: name, value: value })
279 }).then(function(resp) {
280 if (!resp.ok)
281 throw new Error("Failed to set report value");
282 return resp.json();
283 }).catch(function(err) {
284 Common.displayError(err);
285 });
286 }
287
288 _create_element() {
289 let el = document.createDocumentFragment();
290 let md = document.createElement("div");
291 md.setAttribute("class", "report-metadata");
292 md.appendChild(this._create_data_item("Report Id", this._data.report_id));
293 md.appendChild(this._create_data_item("Reporting organization", this._data.org_name));
294 md.appendChild(this._create_data_item("Domain", this._data.domain, "fqdn"));
295 let d1 = new Date(this._data.date.begin);
296 let d2 = new Date(this._data.date.end);
297 md.appendChild(this._create_data_item("Date range", d1.toUIString(true) + " - " + d2.toUIString(true)));
298 md.appendChild(this._create_data_item("Email", this._data.email || "n/a", "fqdn"));
299 if (this._data.extra_contact_info)
300 md.appendChild(this._create_data_item("Extra contact info", this._data.extra_contact_info));
301 md.appendChild(this._create_data_item("Published policy", this._create_pub_policy_fragment(this._data.policy)));
302 if (this._data.error_string)
303 md.appendChild(this._create_data_item("Error string", "???"));
304 md.appendChild(this._create_data_item("Loaded time", (new Date(this._data.loaded_time)).toUIString()));
305 el.appendChild(md);
306 // Records
307 let rs = document.createElement("div");
308 rs.setAttribute("class", "report-records");
309 rs.appendChild(this._get_filter_button());
310 let hd = document.createElement("h5");
311 hd.id = "records-title";
312 hd.appendChild(document.createTextNode("Records"));
313 hd.appendChild(document.createElement("span"));
314 rs.appendChild(hd);
315 this._data.records.forEach(rec => {
316 const tl = rs.appendChild(document.createElement("div"));
317 tl.classList.add("report-record", "round-border");
318 const hd = tl.appendChild(document.createElement("div"));
319 hd.classList.add("header");
320 hd.append(
321 this._create_data_fragment("IP-address", rec.ip),
322 (new HintButton({ data: rec.ip, content: this._make_ip_info_element.bind(this) })).element()
323 );
324 tl.append(
325 this._create_data_item("Message count", rec.count),
326 this._create_data_item("Policy evaluated", this._create_ev_policy_fragment(rec))
327 );
328 if (rec.reason)
329 tl.append(this._create_data_item("Evaluated reason", this._create_reason_fragment(rec.reason)));
330 tl.append(
331 this._create_data_item("Identifiers", this._create_identifiers_fragment(rec)),
332 this._create_data_item("DKIM auth", this._create_dkim_auth_fragment(rec.dkim_auth)),
333 this._create_data_item("SPF auth", this._create_spf_auth_fragment(rec.spf_auth))
334 );
335
336 });
337 let nd = document.createElement("div");
338 nd.classList.add("nodata", "hidden");
339 nd.textContent = "There are no records to display. Try changing the filter options.";
340 rs.appendChild(nd);
341 el.appendChild(rs);
342 this._records_el = rs;
343 return el;
344 }
345
346 _get_row_container(ctn, data) {
347 if (data.length < 2)
348 return ctn;
349 let div = document.createElement("div")
350 ctn.appendChild(div);
351 return div;
352 }
353
354 _create_data_item(title, data, cname) {
355 let el = document.createElement("div");
356 el.setAttribute("class", "report-item");
357 el.appendChild(this._create_data_fragment(title, data, cname));
358 return el;
359 }
360
361 _create_data_fragment(title, data, cname) {
362 let fr = document.createDocumentFragment();
363 let tl = document.createElement("span");
364 tl.appendChild(document.createTextNode(title + ": "));
365 tl.setAttribute("class", "title");
366 fr.appendChild(tl);
367 if (typeof(data) !== "object")
368 data = document.createTextNode(data);
369 let dt = document.createElement(data.childNodes.length > 1 ? "div" : "span");
370 dt.setAttribute("class", "value");
371 dt.appendChild(data);
372 if (Array.from(dt.children).find(function(ch) {
373 return ch.tagName === "DIV";
374 })) dt.classList.add("rows");
375 if (cname) dt.classList.add(cname);
376 fr.appendChild(dt);
377 return fr;
378 }
379
380 _create_values_fragment(values, keys, clist) {
381 if (!Array.isArray(values)) values = [ values ];
382 const params = keys.map(key => {
383 let r = false;
384 if (key.at(0) === "!") {
385 r = true;
386 key = key.substring(1);
387 }
388 const a = key.split(":");
389 return { name: a[0], title: a[1] || a[0], result: r };
390
391 });
392 const fr = document.createDocumentFragment();
393 const ca = Array.isArray(clist);
394 const lcnt = values.length;
395 values.forEach(val => {
396 const elist = params.reduce((res, param, idx) => {
397 let v = val[param.name];
398 if (v) {
399 const r = param.result && v || null;
400 const el = Common.createReportResultElement(param.title, r, v);
401 const cl = ca ? clist[idx] : clist;
402 if (cl) el.classList.add(cl);
403 res.push(el);
404 }
405 return res;
406 }, []);
407 (lcnt < 2 ? fr : fr.appendChild(document.createElement("div"))).append(...elist);
408 });
409 return fr;
410 }
411
412 _create_pub_policy_fragment(data) {
413 if (!data) return "n/a";
414 return this._create_values_fragment(data, [ "adkim", "aspf", "p", "sp", "np", "pct", "fo" ]);
415 }
416
417 _create_ev_policy_fragment(data) {
418 return this._create_values_fragment(data, [ "!dkim_align:DKIM", "!spf_align:SPF", "disposition" ]);
419 }
420
421 _create_reason_fragment(data) {
422 return this._create_values_fragment(data, [ "type", "comment" ]);
423 }
424
425 _create_identifiers_fragment(data) {
426 return this._create_values_fragment(data, [ "header_from", "envelope_from", "envelope_to" ], "fqdn");
427 }
428
429 _create_dkim_auth_fragment(data) {
430 if (!data) return "n/a";
431 return this._create_values_fragment(data, [ "domain", "selector", "!result" ], [ "fqdn" ]);
432 }
433
434 _create_spf_auth_fragment(data) {
435 if (!data) return "n/a";
436 return this._create_values_fragment(data, [ "domain", "!result" ], [ "fqdn" ]);
437 }
438
439 _get_filter_button() {
440 let btn = document.createElement("button");
441 btn.classList.add("toolbar-btn");
442 btn.textContent = "filter: ";
443 btn.appendChild(document.createElement("span"));
444 btn.addEventListener("click", function(event) {
445 btn.disabled = true;
446 let dlg = new ReportViewFilterDialog({ filter: this._filter });
447 document.getElementById("main-block").prepend(dlg.element());
448 dlg.show().then(function(res) {
449 if (res && (res.dkim !== this._filter.dkim || res.spf !== this._filter.spf ||
450 res.disposition !== this._filter.disposition)
451 ) {
452 this._filter = res;
453 this._apply_filter();
454 this._update_filter_button();
455 this._filter_storage(res);
456 }
457 }.bind(this)).finally(function() {
458 dlg.element().remove();
459 btn.disabled = false;
460 btn.focus();
461 });
462 }.bind(this));
463 this._filter_btn = btn;
464 return btn;
465 }
466
467 _apply_filter() {
468 if (!this._records_el)
469 return;
470 let rtitle = this._records_el.querySelector("#records-title");
471 if (!rtitle)
472 return;
473 let total = this._data.records.length;
474 let displ = 0;
475 let filter = this._filter;
476 let e_list = this._records_el.querySelectorAll(".report-record");
477 for (let i = 0; i < total; ++i) {
478 let rec = this._data.records[i];
479 if ((!filter.dkim || filter.dkim === rec.dkim_align) && (!filter.spf || filter.spf === rec.spf_align) &&
480 (!filter.disposition || filter.disposition === rec.disposition)
481 ) {
482 e_list[i].classList.remove("hidden");
483 ++displ;
484 }
485 else {
486 e_list[i].classList.add("hidden");
487 }
488 }
489 let tstr = null;
490 if (total === displ)
491 tstr = total;
492 else
493 tstr = displ + "/" + total;
494 rtitle.childNodes[1].textContent = " (" + tstr + ")";
495 let nd = this._records_el.querySelector(".nodata");
496 if (displ > 0)
497 nd.classList.add("hidden");
498 else
499 nd.classList.remove("hidden");
500 }
501
502 _update_filter_button() {
503 let ea = [ [ "dkim", this._filter.dkim ], [ "spf", this._filter.spf ] ].reduce(function(res, it) {
504 if (it[1]) {
505 let el = document.createElement("span");
506 el.classList.add("report-result-" + it[1]);
507 el.textContent = it[0];
508 res.push(el);
509 }
510 return res;
511 }, []);
512 if (this._filter.disposition) {
513 let el = document.createElement("span");
514 el.textContent = "disp=" + this._filter.disposition.substring(0, 1);
515 ea.push(el);
516 }
517 let bt = this._filter_btn.childNodes[1];
518 bt.replaceChildren();
519 if (ea.length > 0) {
520 for (let i = 0; i < ea.length; ++i) {
521 if (i) bt.append(", ");
522 bt.append(ea[i]);
523 }
524 } else {
525 bt.textContent = "none";
526 }
527 }
528
529 _filter_storage(data) {
530 let storage = null;
531 switch (Common.rv_filter) {
532 case "last-value":
533 storage = "localStorage";
534 break;
535 case "last-value-tab":
536 storage = "sessionStorage";
537 break;
538 default:
539 return;
540 }
541 let res = {};
542 if (window[storage]) {
543 let prefix = "ReportView.filter.";
544 [ "dkim", "spf", "disposition" ].forEach(function(name) {
545 if (data)
546 window[storage].setItem(prefix + name, data[name] || "");
547 else
548 res[name] = window[storage].getItem(prefix + name);
549 });
550 }
551 return res;
552 }
553
554 _make_ip_info_element(ip) {
555 const el = document.createElement("div");
556 el.appendChild(document.createElement("h4")).textContent = "Host information";
557 this._make_ip_info_items(el, { id: "main" }, [ { title: "IP address", value: Common.makeIpElement(ip) } ]);
558 this._update_ip_info(ip, el);
559 return el;
560 }
561
562 _make_ip_info_items(el, group, items) {
563 let ul = Array.from(el.querySelectorAll("ul[data-group]")).find(e => {
564 return e.dataset.group === group.id;
565 });
566 if (!ul) {
567 if (group.id !== "main") {
568 el.appendChild(document.createElement("h5")).textContent = group.title;
569 }
570 ul = el.appendChild(document.createElement("ul"));
571 ul.dataset.group = group.id;
572 }
573 items.forEach(item => {
574 const li = ul.appendChild(document.createElement("li"));
575 li.appendChild(document.createElement("span")).textContent = item.title + ": ";
576 const val = li.appendChild(document.createElement("span"));
577 val.append(item.value);
578 if (item.tvalue) val.title = item.tvalue;
579 if (item.cvalue) val.classList.add(item.cvalue);
580 });
581 }
582
583 _update_ip_info(ip, el) {
584 const cache_keys = [ "main.rdns", "main.rip" ];
585 const dict = {
586 "main.ip": "IP address", "main.rdns": "rDNS name", "main.rip": "Reverse IP",
587 "stats": "Statistics", "stats.reports": "Total reports", "stats.messages": "Total messages",
588 "stats.last_report": "Last report"
589 };
590
591 const that = this;
592
593 function convertItem(name, item) {
594 switch (name) {
595 case "main.rip":
596 if (typeof(item.value) == "boolean") {
597 if (item.value) {
598 item.value = "match";
599 item.cvalue = "report-result-pass";
600 } else {
601 item.value = "not match";
602 item.cvalue = "report-result-fail";
603 }
604 }
605 break;
606 case "stats.last_report":
607 if (Array.isArray(item.value)) {
608 try {
609 if (item.value[0]) {
610 const rt = new Date(that._data.date.begin);
611 let lt = new Date(item.value[0]);
612 if (lt.getTime() === rt.getTime() && item.value[1]) {
613 lt = new Date(item.value[1]);
614 }
615 item.value = lt.toUIDateString(true);
616 }
617 } catch (err) {
618 }
619 }
620 break;
621 }
622 switch (typeof(item.value)) {
623 case "number":
624 item.value = item.value.toLocaleString();
625 break;
626 default:
627 try {
628 item.value = "" + item.value;
629 } catch (err) {
630 item.value = "";
631 }
632 //break is not needed
633 case "string":
634 if (item.value.length >= 15) item.tvalue = item.value;
635 break;
636 }
637 }
638
639 function setData(result, el) {
640 const m = new Map();
641 const groups = [];
642 for (const d of result.data) {
643 if (!Array.isArray(d) || typeof(d[0]) != "string") continue;
644 const nm = d[0].split(".");
645 if (nm.length != 2) continue;
646 let gr_data = m.get(nm[0]);
647 if (!gr_data) {
648 gr_data = [];
649 m.set(nm[0], gr_data);
650 groups.push(nm[0]);
651 }
652 const item = { title: dict[d[0]] || nm[1], value: d[1] };
653 convertItem(d[0], item);
654 gr_data.push(item);
655 }
656 for (let gr of groups) {
657 gr = { id: gr, title: dict[gr] || gr };
658 that._make_ip_info_items(el, gr, m.get(gr.id));
659 }
660 }
661
662 const we = el.appendChild(document.createElement("div"));
663 we.ariaLabel = "Wait please";
664 we.classList.add("spinner");
665 we.innerHTML = "<div></div><div></div><div></div><div></div><div></div>";
666
667 const excl_fields = {};
668 const cache_data = [];
669 try {
670 const s = window.sessionStorage && window.sessionStorage.getItem("ReportView.Cache.ip-" + ip);
671 if (s) {
672 const jdata = JSON.parse(s);
673 const expire = jdata.expire || 0;
674 if (Date.now() < expire) {
675 const edata = [];
676 cache_keys.forEach(n => {
677 excl_fields[n] = true;
678 cache_data.push([ n, jdata[n] ]);
679 });
680 }
681 }
682 } catch (err) {
683 }
684
685 const url = new URL("hosts.php", document.location);
686 url.searchParams.set("host", ip);
687 url.searchParams.set(
688 "fields",
689 Object.keys(dict).filter(it => (it.includes(".") && it !== "main.ip" && !excl_fields[it])).join(",")
690 );
691 return window.fetch(url, {
692 method: "GET",
693 cache: "no-store",
694 headers: HTTP_HEADERS,
695 credentials: "same-origin"
696 }).then(resp => {
697 if (!resp.ok) throw new Error("Failed to fetch host information");
698 return resp.json();
699 }).then(result => {
700 Common.checkResult(result);
701 // Extracting data for caching
702 let cc = 0;
703 const cache = {};
704 for (const it of result.data) {
705 if (cache_keys.includes(it[0])) {
706 cache[it[0]] = it[1];
707 ++cc;
708 }
709 }
710 // Merging the received data with the local cache
711 for (const it of cache_data) {
712 if (cache[it[0]] === undefined) result.data.push(it);
713 }
714 // Updating the local cache
715 if (cc) {
716 const expire = new Date();
717 expire.setHours(expire.getHours() + 24);
718 cache.expire = expire.valueOf();
719 window.sessionStorage && window.sessionStorage.setItem("ReportView.Cache.ip-" + ip, JSON.stringify(cache));
720 }
721 // Merge dictionaries
722 if (result.dictionary) Object.assign(dict, result.dictionary);
723 // Set data
724 setData(result, el);
725 }).catch(err => {
726 Common.displayError(err);
727 Notification.add({ type: "error", text: err.message });
728 }).finally(() => {
729 we.remove();
730 });
731 }
732 }
733
734 class ReportViewFilterDialog extends ReportFilterDialog {
735 constructor(params) {
736 params.title = "Records filtering";
737 params.item_list = [ "dkim", "spf", "disposition" ];
738 let pfa = [ "pass", "fail" ];
739 params.loaded_filters = { dkim: pfa, spf: pfa, disposition: [ "none", "reject", "quarantine" ] };
740 super(params);
741 }
742 }