aprf-reader 0.1.1__tar.gz → 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aprf-reader
3
- Version: 0.1.1
3
+ Version: 0.3.0
4
4
  Summary: Summarise APRF (Aggregate Performance Reporting) inbox placement reports.
5
5
  License: MIT
6
6
  Requires-Python: >=3.11
@@ -15,9 +15,16 @@ Dynamic: license-file
15
15
 
16
16
  Reads APRF (Aggregate Performance Reporting) reports and tells you where the
17
17
  mail you signed landed: how much reached the inbox, how much was treated as
18
- unwanted, and how recipients reacted, day by day and per DKIM selector.
18
+ unwanted, and how recipients reacted, day by day and per DKIM selector. It
19
+ points out the days worth a look, such as a jump in unwanted mail.
19
20
 
20
- **Status: 0.1, beta.** Reads reports in the format of draft-ietf-mailmaint-aprf-00.
21
+ Two ways to use it, with the same results:
22
+
23
+ - **In your browser:** [aprf.dns-audit.com](https://aprf.dns-audit.com). Drop
24
+ your reports on the page. They are read on your computer and never uploaded.
25
+ - **On the command line:** `pipx install aprf-reader`.
26
+
27
+ **Status: 0.3, beta.** Reads reports in the format of draft-ietf-mailmaint-aprf-00.
21
28
 
22
29
  ## What APRF is
23
30
 
@@ -39,22 +46,39 @@ environment, or with pip (`pip3` on some systems) inside a virtual environment.
39
46
 
40
47
  ```bash
41
48
  pipx install aprf-reader
42
- aprf-reader reports/ # Markdown summary to the terminal
49
+ aprf-reader reports/ # overview in the terminal
50
+ aprf-reader APRF.mbox # a mail folder exported as mbox
51
+ aprf-reader reports/ --markdown # Markdown with daily tables
43
52
  aprf-reader reports/ --html summary.html # and a page you can open or share
53
+ aprf-reader reports/ --json # the summary as data, for scripts
44
54
  ```
45
55
 
56
+ In a terminal you get an overview: for each stream, each count's latest value,
57
+ its daily range, and a trend line with a gap for each day with no report, then
58
+ the changes worth a look. Piped or written to a file with `--md`, the output
59
+ is Markdown with the full daily tables.
60
+
46
61
  Point it at report files (`.json`, `.json.gz`), saved report emails (`.eml`),
47
- or folders of them. Folders are searched recursively. Files it skips are listed
62
+ mailbox exports (`.mbox`), or folders of them. The easiest way to collect reports
63
+ is a mail filter that moves them into one folder, then an export of that folder:
64
+ Gmail through [Google Takeout](https://takeout.google.com/) (pick Mail and the
65
+ label), Thunderbird with the ImportExportTools NG add-on, or Apple Mail's
66
+ Mailbox > Export Mailbox. Comcast's reports come from
67
+ `aprf-noreply@alerts.xfinity.com` with subjects starting `APRF:`. Folders are searched recursively. Files it skips are listed
48
68
  on stderr and at the end of the summary, each with a reason.
49
69
 
50
70
  Each stream (provider, signing domain, selector) gets a table with one row per
51
71
  day and segment, a trend line per count, and a row for each day with no report.
72
+ A change worth a look is a day when unwanted mail or negative reactions at
73
+ least doubled and grew by 200 or more, or inbox mail fell by half and by 200
74
+ or more, against the report before. Comcast counts in steps of 100, so smaller
75
+ moves are left out as rounding.
52
76
  A change in the report's `version` field is called out, since the draft uses it
53
77
  to mark a change in what a category counts.
54
78
 
55
79
  ## What it does
56
80
 
57
- - Read report files (`.json`, `.json.gz` and `.eml`) or a folder of them, and skip
81
+ - Read report files (`.json`, `.json.gz`, `.eml` and `.mbox`) or a folder of them, and skip
58
82
  duplicates and files it cannot read, with a reason for each.
59
83
  - Summarise placement per signing domain and selector: inbox, unwanted and
60
84
  recipient reactions, by day and as a trend.
@@ -67,6 +91,17 @@ to mark a change in what a category counts.
67
91
  - When the same day arrives twice, keep the first copy and say so. The draft
68
92
  has not yet decided whether a resend replaces the original.
69
93
 
94
+ ## How the web page is built
95
+
96
+ `web/src/aprf.js` is a JavaScript port of the Python reader.
97
+ `tests/test_web_parity.py` runs both on the same files (JSON, gzip, saved
98
+ emails, forwarded emails, mailbox exports, duplicates and hostile text) and
99
+ requires the same JSON, Markdown and HTML output, so the page and the command
100
+ line cannot drift apart. `node web/build.js` inlines everything into one
101
+ `web/dist/index.html` whose Content Security Policy blocks every network
102
+ request, so it also works saved to disk. A merge to main that passes the
103
+ tests deploys it to Cloudflare.
104
+
70
105
  ## Related
71
106
 
72
107
  - [dns-audit.com](https://dns-audit.com) checks a domain for an APRF record and
@@ -2,9 +2,16 @@
2
2
 
3
3
  Reads APRF (Aggregate Performance Reporting) reports and tells you where the
4
4
  mail you signed landed: how much reached the inbox, how much was treated as
5
- unwanted, and how recipients reacted, day by day and per DKIM selector.
5
+ unwanted, and how recipients reacted, day by day and per DKIM selector. It
6
+ points out the days worth a look, such as a jump in unwanted mail.
6
7
 
7
- **Status: 0.1, beta.** Reads reports in the format of draft-ietf-mailmaint-aprf-00.
8
+ Two ways to use it, with the same results:
9
+
10
+ - **In your browser:** [aprf.dns-audit.com](https://aprf.dns-audit.com). Drop
11
+ your reports on the page. They are read on your computer and never uploaded.
12
+ - **On the command line:** `pipx install aprf-reader`.
13
+
14
+ **Status: 0.3, beta.** Reads reports in the format of draft-ietf-mailmaint-aprf-00.
8
15
 
9
16
  ## What APRF is
10
17
 
@@ -26,22 +33,39 @@ environment, or with pip (`pip3` on some systems) inside a virtual environment.
26
33
 
27
34
  ```bash
28
35
  pipx install aprf-reader
29
- aprf-reader reports/ # Markdown summary to the terminal
36
+ aprf-reader reports/ # overview in the terminal
37
+ aprf-reader APRF.mbox # a mail folder exported as mbox
38
+ aprf-reader reports/ --markdown # Markdown with daily tables
30
39
  aprf-reader reports/ --html summary.html # and a page you can open or share
40
+ aprf-reader reports/ --json # the summary as data, for scripts
31
41
  ```
32
42
 
43
+ In a terminal you get an overview: for each stream, each count's latest value,
44
+ its daily range, and a trend line with a gap for each day with no report, then
45
+ the changes worth a look. Piped or written to a file with `--md`, the output
46
+ is Markdown with the full daily tables.
47
+
33
48
  Point it at report files (`.json`, `.json.gz`), saved report emails (`.eml`),
34
- or folders of them. Folders are searched recursively. Files it skips are listed
49
+ mailbox exports (`.mbox`), or folders of them. The easiest way to collect reports
50
+ is a mail filter that moves them into one folder, then an export of that folder:
51
+ Gmail through [Google Takeout](https://takeout.google.com/) (pick Mail and the
52
+ label), Thunderbird with the ImportExportTools NG add-on, or Apple Mail's
53
+ Mailbox > Export Mailbox. Comcast's reports come from
54
+ `aprf-noreply@alerts.xfinity.com` with subjects starting `APRF:`. Folders are searched recursively. Files it skips are listed
35
55
  on stderr and at the end of the summary, each with a reason.
36
56
 
37
57
  Each stream (provider, signing domain, selector) gets a table with one row per
38
58
  day and segment, a trend line per count, and a row for each day with no report.
59
+ A change worth a look is a day when unwanted mail or negative reactions at
60
+ least doubled and grew by 200 or more, or inbox mail fell by half and by 200
61
+ or more, against the report before. Comcast counts in steps of 100, so smaller
62
+ moves are left out as rounding.
39
63
  A change in the report's `version` field is called out, since the draft uses it
40
64
  to mark a change in what a category counts.
41
65
 
42
66
  ## What it does
43
67
 
44
- - Read report files (`.json`, `.json.gz` and `.eml`) or a folder of them, and skip
68
+ - Read report files (`.json`, `.json.gz`, `.eml` and `.mbox`) or a folder of them, and skip
45
69
  duplicates and files it cannot read, with a reason for each.
46
70
  - Summarise placement per signing domain and selector: inbox, unwanted and
47
71
  recipient reactions, by day and as a trend.
@@ -54,6 +78,17 @@ to mark a change in what a category counts.
54
78
  - When the same day arrives twice, keep the first copy and say so. The draft
55
79
  has not yet decided whether a resend replaces the original.
56
80
 
81
+ ## How the web page is built
82
+
83
+ `web/src/aprf.js` is a JavaScript port of the Python reader.
84
+ `tests/test_web_parity.py` runs both on the same files (JSON, gzip, saved
85
+ emails, forwarded emails, mailbox exports, duplicates and hostile text) and
86
+ requires the same JSON, Markdown and HTML output, so the page and the command
87
+ line cannot drift apart. `node web/build.js` inlines everything into one
88
+ `web/dist/index.html` whose Content Security Policy blocks every network
89
+ request, so it also works saved to disk. A merge to main that passes the
90
+ tests deploys it to Cloudflare.
91
+
57
92
  ## Related
58
93
 
59
94
  - [dns-audit.com](https://dns-audit.com) checks a domain for an APRF record and
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "aprf-reader"
7
- version = "0.1.1"
7
+ version = "0.3.0"
8
8
  description = "Summarise APRF (Aggregate Performance Reporting) inbox placement reports."
9
9
  readme = "README.md"
10
10
  license = { text = "MIT" }
@@ -1,3 +1,3 @@
1
1
  """Read APRF aggregate performance reports."""
2
2
 
3
- __version__ = "0.1.1"
3
+ __version__ = "0.3.0"
@@ -3,19 +3,25 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import argparse
6
+ import json
7
+ import os
8
+ import shutil
6
9
  import sys
7
10
  from pathlib import Path
8
11
 
9
12
  from . import __version__
10
13
  from .load import load
11
- from .render import to_html, to_markdown
14
+ from .render import to_html, to_markdown, to_terminal
15
+ from .summary import to_dict
12
16
 
13
17
 
14
18
  def main(argv: list[str] | None = None) -> int:
15
19
  p = argparse.ArgumentParser(prog="aprf-reader", description="Summarise APRF placement reports.")
16
- p.add_argument("paths", nargs="+", type=Path, help="report files (.json, .json.gz, .eml) or folders")
17
- p.add_argument("--md", type=Path, help="write the Markdown summary here instead of printing it")
20
+ p.add_argument("paths", nargs="+", type=Path, help="report files (.json, .json.gz, .eml, .mbox) or folders")
21
+ p.add_argument("--md", type=Path, help="write the summary here instead of printing it")
18
22
  p.add_argument("--html", type=Path, help="also write a self-contained HTML page here")
23
+ p.add_argument("--markdown", action="store_true", help="print Markdown with daily tables, even in a terminal")
24
+ p.add_argument("--json", action="store_true", help="print the summary as JSON")
19
25
  p.add_argument("--version", action="version", version=f"aprf-reader {__version__}")
20
26
  args = p.parse_args(argv)
21
27
 
@@ -29,11 +35,17 @@ def main(argv: list[str] | None = None) -> int:
29
35
  print("no APRF reports found", file=sys.stderr)
30
36
  return 1
31
37
 
32
- md = to_markdown(loaded)
38
+ if args.json:
39
+ text = json.dumps(to_dict(loaded.reports, loaded.skipped), indent=2) + "\n"
40
+ elif args.md or args.markdown or not sys.stdout.isatty():
41
+ text = to_markdown(loaded) # files and pipes get Markdown, which other tools read
42
+ else:
43
+ color = "NO_COLOR" not in os.environ and os.environ.get("TERM") != "dumb"
44
+ text = to_terminal(loaded, color=color, width=shutil.get_terminal_size().columns)
33
45
  if args.md:
34
- args.md.write_text(md, encoding="utf-8")
46
+ args.md.write_text(text, encoding="utf-8")
35
47
  else:
36
- sys.stdout.write(md)
48
+ sys.stdout.write(text)
37
49
  if args.html:
38
50
  args.html.write_text(to_html(loaded), encoding="utf-8")
39
51
  return 0
@@ -0,0 +1,139 @@
1
+ """Find report files, open them, and drop duplicates."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import gzip
6
+ import hashlib
7
+ import io
8
+ import mailbox
9
+ import zlib
10
+ from collections.abc import Iterable, Iterator
11
+ from dataclasses import dataclass, field
12
+ from email import policy
13
+ from email.message import Message
14
+ from email.parser import BytesParser
15
+ from pathlib import Path
16
+
17
+ from .report import Report, ReportError, parse
18
+
19
+ SUFFIXES = (".json", ".json.gz", ".eml", ".mbox")
20
+ # A daily report is a few KB; this stops a stray huge file or gzip bomb
21
+ MAX_BYTES = 10 * 1024 * 1024
22
+
23
+
24
+ @dataclass
25
+ class Loaded:
26
+ reports: list[Report] = field(default_factory=list)
27
+ skipped: list[tuple[str, str]] = field(default_factory=list) # (where, reason)
28
+
29
+
30
+ def _files(paths: Iterable[Path]) -> Iterator[Path]:
31
+ for p in paths:
32
+ if p.is_dir():
33
+ yield from sorted(f for f in p.rglob("*") if f.is_file() and (f.name.lower().endswith(SUFFIXES) or _is_mbox(f)))
34
+ else:
35
+ yield p
36
+
37
+
38
+ def _is_mbox(path: Path) -> bool:
39
+ # Apple Mail exports a folder "Name.mbox" holding a file named just "mbox"
40
+ return path.name.lower() == "mbox" or path.name.lower().endswith(".mbox")
41
+
42
+
43
+ def _gunzip(data: bytes) -> bytes:
44
+ with gzip.GzipFile(fileobj=io.BytesIO(data)) as g:
45
+ out = g.read(MAX_BYTES + 1)
46
+ if len(out) > MAX_BYTES:
47
+ raise ReportError("larger than 10 MB unpacked")
48
+ return out
49
+
50
+
51
+ def _attachments(msg: Message, label: str) -> Iterator[tuple[str, bytes]]:
52
+ """Yield (label, report JSON bytes) for each report attached to one email."""
53
+ for part in msg.walk():
54
+ if part.is_multipart():
55
+ continue
56
+ fname = (part.get_filename() or "").lower()
57
+ ctype = part.get_content_type()
58
+ data = part.get_payload(decode=True) or b""
59
+ where = f"{label} ({fname or ctype})"
60
+ if len(data) > MAX_BYTES:
61
+ raise ReportError(f"{where} is larger than 10 MB")
62
+ if fname.endswith(".gz") or ctype in ("application/gzip", "application/x-gzip") or data[:2] == b"\x1f\x8b":
63
+ yield where, _gunzip(data)
64
+ # By name or type, or an attachment of unhelpful type that is a JSON array or object
65
+ elif fname.endswith(".json") or ctype == "application/json" or (
66
+ part.get_content_disposition() == "attachment" and data.lstrip()[:1] in (b"[", b"{")):
67
+ yield where, data
68
+
69
+
70
+ def _payloads(path: Path) -> Iterator[tuple[str, bytes]]:
71
+ """Yield (label, report JSON bytes) for each report in a file."""
72
+ data = path.read_bytes()
73
+ if len(data) > MAX_BYTES:
74
+ raise ReportError("larger than 10 MB")
75
+ if path.name.lower().endswith(".eml"):
76
+ found = list(_attachments(BytesParser(policy=policy.default).parsebytes(data), str(path)))
77
+ if not found:
78
+ raise ReportError("no report attachment")
79
+ yield from found
80
+ elif data[:2] == b"\x1f\x8b":
81
+ yield str(path), _gunzip(data)
82
+ else:
83
+ yield str(path), data
84
+
85
+
86
+ def _mbox(path: Path, out: Loaded) -> Iterator[tuple[str, bytes]]:
87
+ """Yield reports from a mailbox export; one skip line for all mail with none attached."""
88
+ box = mailbox.mbox(path, factory=lambda f: BytesParser(policy=policy.default).parse(f), create=False)
89
+ without = 0
90
+ try:
91
+ for i, msg in enumerate(box, 1):
92
+ label = f"{path} message {i}"
93
+ try:
94
+ found = list(_attachments(msg, label))
95
+ # OSError covers gzip.BadGzipFile; one bad message must not end the mailbox
96
+ except (OSError, EOFError, zlib.error, ReportError) as e:
97
+ out.skipped.append((label, str(e)))
98
+ continue
99
+ without += not found
100
+ yield from found
101
+ finally:
102
+ box.close()
103
+ if without:
104
+ out.skipped.append((str(path), f"{without} message{'s' if without != 1 else ''} with no report attached"))
105
+
106
+
107
+ def load(paths: Iterable[Path]) -> Loaded:
108
+ out = Loaded()
109
+ seen_bytes: set[str] = set()
110
+ seen_keys: dict[tuple, str] = {}
111
+
112
+ def add(where: str, data: bytes) -> None:
113
+ digest = hashlib.sha256(data).hexdigest()
114
+ if digest in seen_bytes:
115
+ out.skipped.append((where, "duplicate of a file already read"))
116
+ return
117
+ seen_bytes.add(digest)
118
+ try:
119
+ reports = parse(data)
120
+ except ReportError as e:
121
+ out.skipped.append((where, str(e)))
122
+ return
123
+ for r in reports:
124
+ # The draft does not yet say whether a resend replaces the first; keep the first
125
+ if r.key in seen_keys:
126
+ out.skipped.append((where, f"same day already reported in {seen_keys[r.key]}; kept that one"))
127
+ continue
128
+ seen_keys[r.key] = where
129
+ out.reports.append(r)
130
+
131
+ for path in _files(paths):
132
+ try:
133
+ # An mbox can be large, so it is read one message at a time
134
+ payloads = _mbox(path, out) if _is_mbox(path) else list(_payloads(path))
135
+ for where, data in payloads:
136
+ add(where, data)
137
+ except (OSError, EOFError, zlib.error, ReportError) as e:
138
+ out.skipped.append((str(path), str(e)))
139
+ return out
@@ -3,6 +3,8 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import html
6
+ import re
7
+ from datetime import date
6
8
 
7
9
  from . import __version__
8
10
  from .load import Loaded
@@ -56,6 +58,8 @@ def to_markdown(loaded: Loaded) -> str:
56
58
  else:
57
59
  lines.append(f"| {row.day} | {_md(row.segment)} | " + " | ".join(_n(v) for v in row.values) + " |")
58
60
  lines.append("")
61
+ if s.changes:
62
+ lines += ["Changes worth a look:", ""] + [f"- {_md(c)}" for c in s.changes] + [""]
59
63
  if s.notes:
60
64
  lines += [f"- {_md(n)}" for n in s.notes] + [""]
61
65
  if loaded.skipped:
@@ -118,6 +122,8 @@ def to_html(loaded: Loaded) -> str:
118
122
  else:
119
123
  parts.append(f"<tr><td>{row.day}<td>{e(row.segment)}" + "".join(f"<td>{_n(v)}" for v in row.values))
120
124
  parts.append("</tbody></table></div>")
125
+ if s.changes:
126
+ parts.append("<p>Changes worth a look:</p><ul>" + "".join(f"<li>{e(c)}" for c in s.changes) + "</ul>")
121
127
  if s.notes:
122
128
  parts.append("<ul>" + "".join(f"<li>{e(n)}" for n in s.notes) + "</ul>")
123
129
  if loaded.skipped:
@@ -125,3 +131,92 @@ def to_html(loaded: Loaded) -> str:
125
131
  parts.append(f"<p class=muted>Read by aprf-reader {e(__version__)} against {DRAFT}. Nothing left this computer.</p>")
126
132
  parts.append("</body></html>")
127
133
  return "\n".join(parts) + "\n"
134
+
135
+
136
+ # ---- terminal view ----
137
+
138
+ BARS = "▁▂▃▄▅▆▇█"
139
+
140
+
141
+ class _Style:
142
+ def __init__(self, color: bool):
143
+ self.on = color
144
+
145
+ def __call__(self, code: str, text: str) -> str:
146
+ return f"\033[{code}m{text}\033[0m" if self.on else text
147
+
148
+ def bold(self, t: str) -> str: return self("1", t)
149
+ def dim(self, t: str) -> str: return self("2", t)
150
+ def accent(self, t: str) -> str: return self("1;34", t)
151
+ def warn(self, t: str) -> str: return self("33", t)
152
+ def good(self, t: str) -> str: return self("32", t)
153
+
154
+
155
+ def _bars(points: list[tuple[int, int]], width: int) -> str:
156
+ """One character per day, a space for a day with no report; days share a cell when they do not fit."""
157
+ span = points[-1][0] + 1
158
+ cells: list[int | None] = [None] * min(span, width)
159
+ for x, v in points:
160
+ i = x * len(cells) // span
161
+ cells[i] = v if cells[i] is None else max(cells[i], v)
162
+ top = max(v for _, v in points) or 1
163
+ if min(v for _, v in points) == top:
164
+ # A flat line is the same every day; a full bar would read as a peak
165
+ return "".join(" " if v is None else BARS[3] for v in cells)
166
+ return "".join(" " if v is None else BARS[min(7, v * 7 // top)] if v else BARS[0] for v in cells)
167
+
168
+
169
+ def _date(d) -> str:
170
+ return f"{d:%b} {d.day}"
171
+
172
+
173
+ def _range(a, b) -> str:
174
+ if a == b:
175
+ return f"{_date(a)}, {a.year}"
176
+ return (_date(a) if a.year == b.year else f"{_date(a)}, {a.year}") + f" to {_date(b)}, {b.year}"
177
+
178
+
179
+ def _wrap(text: str, width: int, indent: str = "") -> list[str]:
180
+ import textwrap
181
+ return textwrap.wrap(text, width=max(40, width), initial_indent=indent, subsequent_indent=indent) or [indent]
182
+
183
+
184
+ def to_terminal(loaded: Loaded, color: bool = True, width: int = 100) -> str:
185
+ """A readable overview for a terminal: per stream, each count's latest value, range and trend."""
186
+ st = _Style(color)
187
+ ss = streams(loaded.reports)
188
+ out = [st.bold("APRF placement summary") + st.dim(f" {_counts(loaded, ss)}"), ""]
189
+ out += [st.dim(line) for line in _wrap(CAVEAT, min(width, 100))] + [""]
190
+ for s in ss:
191
+ out.append(st.accent(s.domain) + " " + st.bold(f"selector {s.selector}"))
192
+ meta = [s.source, _range(s.first, s.last), _plural(len(s.by_day), "report")]
193
+ line = st.dim(" · ".join(meta))
194
+ if s.missing:
195
+ line += st.dim(" · ") + st.warn(f"{_plural(s.missing, 'day')} with no report")
196
+ out += [line, ""]
197
+ names = [k for _, k in s.columns]
198
+ nw = max([len(n) for n in names] + [5])
199
+ trends = [s.trend(i) for i in range(len(names))]
200
+ latest = [f"{t[-1][1]:,}" for t in trends]
201
+ ranges = [f"{min(v for _, v in t):,} to {max(v for _, v in t):,}" for t in trends]
202
+ lw, rw = max(len(x) for x in latest + ["latest"]), max(len(x) for x in ranges + ["range"])
203
+ bw = max(10, min(60, width - (2 + nw + 2 + lw + 2 + rw + 2)))
204
+ out.append(st.dim(f" {'':<{nw}} {'latest':>{lw}} {'range':<{rw}} trend"))
205
+ for name, t, l, r in zip(names, trends, latest, ranges):
206
+ out.append(f" {name:<{nw}} {st.bold(f'{l:>{lw}}')} {r:<{rw}} {st.accent(_bars(t, bw)) if len(t) > 1 else st.dim('one day')}")
207
+ out.append("")
208
+ if s.changes:
209
+ out.append(st.bold(" Changes worth a look"))
210
+ out += [f" {st.warn('!')} " + re.sub(r"(\d{4})-(\d\d)-(\d\d)", lambda m: _date(date.fromisoformat(m[0])), c)
211
+ for c in s.changes]
212
+ else:
213
+ out.append(f" {st.good('✓')} " + st.dim("No big day-to-day moves in inbox, unwanted, or negative counts."))
214
+ for n in s.notes:
215
+ out += _wrap(n, width - 4, " · ")
216
+ out.append("")
217
+ if loaded.skipped:
218
+ out.append(st.warn(f"Skipped {len(loaded.skipped)}"))
219
+ out += [st.dim(f" {w}: {r}") for w, r in loaded.skipped]
220
+ out.append("")
221
+ out.append(st.dim(f"aprf-reader {__version__}, {DRAFT}. Daily tables: --markdown, or --html for a page."))
222
+ return "\n".join(out) + "\n"
@@ -10,6 +10,11 @@ from functools import cached_property
10
10
  from .report import ENGAGEMENT_NAMES, NO_SDI, PLACEMENT_NAMES, Report
11
11
 
12
12
 
13
+ # Counts where a jump up is bad news, or a drop is
14
+ CHANGES = {"unwanted": "rise", "negative": "rise", "inbox": "fall"}
15
+ MIN_MOVE = 200
16
+
17
+
13
18
  @dataclass(frozen=True)
14
19
  class Row:
15
20
  day: date
@@ -69,6 +74,27 @@ class Stream:
69
74
  return [((d - self.first).days, sum(getattr(s, a).get(k, 0) for s in r.segments))
70
75
  for d, r in sorted(self.by_day.items())]
71
76
 
77
+ @cached_property
78
+ def changes(self) -> list[str]:
79
+ """Day-to-day moves big enough to look at, between one report day and the next."""
80
+ out = []
81
+ for col, (_, k) in enumerate(self.columns):
82
+ rule = CHANGES.get(k)
83
+ if rule is None:
84
+ continue
85
+ pts = self.trend(col)
86
+ for (x0, old), (x1, new) in zip(pts, pts[1:]):
87
+ # Comcast's buckets are 100 wide, so a move under two buckets is noise
88
+ if rule == "rise" and new >= 2 * old and new - old >= MIN_MOVE:
89
+ verb = "rose"
90
+ elif rule == "fall" and 2 * new <= old and old - new >= MIN_MOVE:
91
+ verb = "fell"
92
+ else:
93
+ continue
94
+ d0, d1 = self.first + timedelta(x0), self.first + timedelta(x1)
95
+ out.append(f"{k} {verb} from {old:,} on {d0} to {new:,} on {d1}.")
96
+ return sorted(out, key=lambda t: t.rsplit(" on ", 1)[1])
97
+
72
98
  @cached_property
73
99
  def notes(self) -> list[str]:
74
100
  out = []
@@ -92,3 +118,20 @@ def streams(reports: list[Report]) -> list[Stream]:
92
118
  for r in reports:
93
119
  groups[(r.source, r.dkim_domain.lower(), r.dkim_selector)][r.day] = r
94
120
  return [Stream(src, dom, sel, days) for (src, dom, sel), days in sorted(groups.items())]
121
+
122
+
123
+ def to_dict(reports: list[Report], skipped: list[tuple[str, str]]) -> dict:
124
+ """The summary as plain data, for --json and for checking the web page against."""
125
+ return {
126
+ "reports": len(reports),
127
+ "streams": [{
128
+ "source": s.source, "domain": s.domain, "selector": s.selector,
129
+ "first": str(s.first), "last": str(s.last), "missing_days": s.missing,
130
+ "columns": [k for _, k in s.columns],
131
+ "days": [{"day": str(d), "version": r.version, "segments": [
132
+ {"segment": list(seg.path), "classification": seg.classification, "engagement": seg.engagement}
133
+ for seg in r.segments]} for d, r in sorted(s.by_day.items())],
134
+ "changes": s.changes, "notes": s.notes,
135
+ } for s in streams(reports)],
136
+ "skipped": [{"where": w, "reason": r} for w, r in skipped],
137
+ }
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aprf-reader
3
- Version: 0.1.1
3
+ Version: 0.3.0
4
4
  Summary: Summarise APRF (Aggregate Performance Reporting) inbox placement reports.
5
5
  License: MIT
6
6
  Requires-Python: >=3.11
@@ -15,9 +15,16 @@ Dynamic: license-file
15
15
 
16
16
  Reads APRF (Aggregate Performance Reporting) reports and tells you where the
17
17
  mail you signed landed: how much reached the inbox, how much was treated as
18
- unwanted, and how recipients reacted, day by day and per DKIM selector.
18
+ unwanted, and how recipients reacted, day by day and per DKIM selector. It
19
+ points out the days worth a look, such as a jump in unwanted mail.
19
20
 
20
- **Status: 0.1, beta.** Reads reports in the format of draft-ietf-mailmaint-aprf-00.
21
+ Two ways to use it, with the same results:
22
+
23
+ - **In your browser:** [aprf.dns-audit.com](https://aprf.dns-audit.com). Drop
24
+ your reports on the page. They are read on your computer and never uploaded.
25
+ - **On the command line:** `pipx install aprf-reader`.
26
+
27
+ **Status: 0.3, beta.** Reads reports in the format of draft-ietf-mailmaint-aprf-00.
21
28
 
22
29
  ## What APRF is
23
30
 
@@ -39,22 +46,39 @@ environment, or with pip (`pip3` on some systems) inside a virtual environment.
39
46
 
40
47
  ```bash
41
48
  pipx install aprf-reader
42
- aprf-reader reports/ # Markdown summary to the terminal
49
+ aprf-reader reports/ # overview in the terminal
50
+ aprf-reader APRF.mbox # a mail folder exported as mbox
51
+ aprf-reader reports/ --markdown # Markdown with daily tables
43
52
  aprf-reader reports/ --html summary.html # and a page you can open or share
53
+ aprf-reader reports/ --json # the summary as data, for scripts
44
54
  ```
45
55
 
56
+ In a terminal you get an overview: for each stream, each count's latest value,
57
+ its daily range, and a trend line with a gap for each day with no report, then
58
+ the changes worth a look. Piped or written to a file with `--md`, the output
59
+ is Markdown with the full daily tables.
60
+
46
61
  Point it at report files (`.json`, `.json.gz`), saved report emails (`.eml`),
47
- or folders of them. Folders are searched recursively. Files it skips are listed
62
+ mailbox exports (`.mbox`), or folders of them. The easiest way to collect reports
63
+ is a mail filter that moves them into one folder, then an export of that folder:
64
+ Gmail through [Google Takeout](https://takeout.google.com/) (pick Mail and the
65
+ label), Thunderbird with the ImportExportTools NG add-on, or Apple Mail's
66
+ Mailbox > Export Mailbox. Comcast's reports come from
67
+ `aprf-noreply@alerts.xfinity.com` with subjects starting `APRF:`. Folders are searched recursively. Files it skips are listed
48
68
  on stderr and at the end of the summary, each with a reason.
49
69
 
50
70
  Each stream (provider, signing domain, selector) gets a table with one row per
51
71
  day and segment, a trend line per count, and a row for each day with no report.
72
+ A change worth a look is a day when unwanted mail or negative reactions at
73
+ least doubled and grew by 200 or more, or inbox mail fell by half and by 200
74
+ or more, against the report before. Comcast counts in steps of 100, so smaller
75
+ moves are left out as rounding.
52
76
  A change in the report's `version` field is called out, since the draft uses it
53
77
  to mark a change in what a category counts.
54
78
 
55
79
  ## What it does
56
80
 
57
- - Read report files (`.json`, `.json.gz` and `.eml`) or a folder of them, and skip
81
+ - Read report files (`.json`, `.json.gz`, `.eml` and `.mbox`) or a folder of them, and skip
58
82
  duplicates and files it cannot read, with a reason for each.
59
83
  - Summarise placement per signing domain and selector: inbox, unwanted and
60
84
  recipient reactions, by day and as a trend.
@@ -67,6 +91,17 @@ to mark a change in what a category counts.
67
91
  - When the same day arrives twice, keep the first copy and say so. The draft
68
92
  has not yet decided whether a resend replaces the original.
69
93
 
94
+ ## How the web page is built
95
+
96
+ `web/src/aprf.js` is a JavaScript port of the Python reader.
97
+ `tests/test_web_parity.py` runs both on the same files (JSON, gzip, saved
98
+ emails, forwarded emails, mailbox exports, duplicates and hostile text) and
99
+ requires the same JSON, Markdown and HTML output, so the page and the command
100
+ line cannot drift apart. `node web/build.js` inlines everything into one
101
+ `web/dist/index.html` whose Content Security Policy blocks every network
102
+ request, so it also works saved to disk. A merge to main that passes the
103
+ tests deploys it to Cloudflare.
104
+
70
105
  ## Related
71
106
 
72
107
  - [dns-audit.com](https://dns-audit.com) checks a domain for an APRF record and
@@ -13,4 +13,5 @@ src/aprf_reader.egg-info/dependency_links.txt
13
13
  src/aprf_reader.egg-info/entry_points.txt
14
14
  src/aprf_reader.egg-info/requires.txt
15
15
  src/aprf_reader.egg-info/top_level.txt
16
- tests/test_reader.py
16
+ tests/test_reader.py
17
+ tests/test_web_parity.py
@@ -1,5 +1,7 @@
1
1
  import gzip
2
2
  import json
3
+ import mailbox
4
+ import re
3
5
  from datetime import date
4
6
  from email.message import EmailMessage
5
7
  from pathlib import Path
@@ -91,6 +93,45 @@ def test_load_gz_eml_folder_and_skips(tmp_path):
91
93
  assert "duplicate" in reasons["copy.json"] and "same day" in reasons["resend.json"]
92
94
 
93
95
 
96
+ def report_email(day: int, payload: bytes, subtype: str, filename: str | None) -> EmailMessage:
97
+ msg = EmailMessage()
98
+ msg["From"] = "aprf-noreply@alerts.xfinity.com"
99
+ msg["Subject"] = f"APRF: day {day}"
100
+ msg.set_content("report attached")
101
+ msg.add_attachment(payload, maintype="application", subtype=subtype, filename=filename)
102
+ return msg
103
+
104
+
105
+ def test_attachment_found_by_content(tmp_path):
106
+ # A provider may label the file octet-stream or give it no useful name
107
+ raw = json.dumps(report(0)).encode()
108
+ (tmp_path / "plain.eml").write_bytes(report_email(0, raw, "octet-stream", "20261001_example.com_s1_Comcast").as_bytes())
109
+ gz = gzip.compress(json.dumps(report(1)).encode())
110
+ (tmp_path / "gz.eml").write_bytes(report_email(1, gz, "octet-stream", None).as_bytes())
111
+ loaded = load([tmp_path])
112
+ assert sorted(r.day.day for r in loaded.reports) == [1, 2] and not loaded.skipped
113
+
114
+
115
+ def test_mbox_export(tmp_path):
116
+ (tmp_path / "Reports.mbox").mkdir() # Apple Mail's export layout
117
+ box = mailbox.mbox(tmp_path / "Reports.mbox" / "mbox")
118
+ box.add(report_email(0, gzip.compress(json.dumps(report(0)).encode()), "gzip", "a.json.gz"))
119
+ box.add(report_email(1, json.dumps(report(1)).encode(), "json", "b.json"))
120
+ note = EmailMessage()
121
+ note["Subject"] = "not a report"
122
+ note.set_content("hello")
123
+ box.add(note)
124
+ box.add(note)
125
+ box.add(report_email(2, b"\x1f\x8b broken", "gzip", "c.json.gz"))
126
+ box.add(report_email(3, b"not gzip at all", "gzip", "d.json.gz"))
127
+ box.add(report_email(4, json.dumps(report(4)).encode(), "json", "e.json"))
128
+ box.close()
129
+ loaded = load([tmp_path])
130
+ assert sorted(r.day.day for r in loaded.reports) == [1, 2, 5] # read on past bad messages
131
+ reasons = [r for _, r in loaded.skipped]
132
+ assert len(reasons) == 3 and "2 messages with no report attached" in reasons
133
+
134
+
94
135
  def test_hostile_files_skipped_not_crashed(tmp_path):
95
136
  (tmp_path / "deep.json").write_text("[" * 100_000 + "]" * 100_000)
96
137
  write(tmp_path / "far.json", report(0, report_end=10**20))
@@ -147,3 +188,49 @@ def test_cli(tmp_path, capsys):
147
188
  assert out.read_text().startswith("<!doctype html>")
148
189
  (tmp_path / "empty").mkdir()
149
190
  assert main([str(tmp_path / "empty")]) == 1
191
+
192
+
193
+ def test_changes_flag_big_moves_only():
194
+ (s1, s2) = streams(parse((FIX / "sample_six_weeks.json").read_bytes()))
195
+ assert s1.selector == "news" and s1.changes == [
196
+ "unwanted rose from 300 on 2026-09-24 to 2,500 on 2026-09-25.",
197
+ "negative rose from 100 on 2026-09-24 to 400 on 2026-09-25.",
198
+ "inbox fell from 2,200 on 2026-09-25 to 600 on 2026-09-26.",
199
+ ]
200
+ assert s2.changes == [] # steady stream, nothing flagged
201
+ # 10 to 200 is many times higher but under two buckets of movement
202
+ (s,) = streams([parse(json.dumps(report(0, inbox=100)).encode())[0],
203
+ parse(json.dumps(report(1, inbox=100) | {"body": [{"classification": {"unwanted": 200}}]}).encode())[0]])
204
+ assert not any("unwanted" in c for c in s.changes)
205
+
206
+
207
+ def test_json_output(capsys):
208
+ assert main([str(FIX / "sample_six_weeks.json"), "--json"]) == 0
209
+ doc = json.loads(capsys.readouterr().out)
210
+ assert doc["reports"] == 80 and [s["selector"] for s in doc["streams"]] == ["news", "receipts"]
211
+ news = doc["streams"][0]
212
+ assert news["missing_days"] == 2 and news["columns"] == ["inbox", "unwanted", "positive", "negative"]
213
+ assert news["days"][0]["segments"][0]["segment"] == [] and len(news["changes"]) == 3
214
+
215
+
216
+ def test_terminal_view():
217
+ from aprf_reader.render import to_terminal
218
+ loaded = load([FIX / "sample_six_weeks.json", FIX / "comcast_beta.json"])
219
+ out = to_terminal(loaded, color=False, width=100)
220
+ assert "example.com selector news" in out and "2 days with no report" in out
221
+ assert "! unwanted rose from 300 on Sep 24 to 2,500 on Sep 25." in out
222
+ assert "✓ No big day-to-day moves" in out and "one day" in out
223
+ assert "\033[" not in out and "\033[" in to_terminal(loaded, color=True)
224
+ assert max(len(line) for line in out.splitlines()) <= 100
225
+ inbox = next(line for line in out.splitlines() if line.startswith(" inbox"))
226
+ assert re.search("[▁-█] +[▁-█]", inbox) # the two days with no report show as a break
227
+
228
+
229
+ def test_cli_terminal_when_interactive(monkeypatch, capsys):
230
+ monkeypatch.setattr("sys.stdout.isatty", lambda: True)
231
+ monkeypatch.setenv("NO_COLOR", "1")
232
+ assert main([str(FIX / "sample_six_weeks.json")]) == 0
233
+ out = capsys.readouterr().out
234
+ assert out.startswith("APRF placement summary") and "\033[" not in out
235
+ assert main([str(FIX / "sample_six_weeks.json"), "--markdown"]) == 0
236
+ assert capsys.readouterr().out.startswith("# APRF placement summary")
@@ -0,0 +1,105 @@
1
+ """The web page (web/src/aprf.js) must read files exactly as the command line does."""
2
+
3
+ import gzip
4
+ import json
5
+ import mailbox
6
+ import shutil
7
+ import subprocess
8
+ from email.message import EmailMessage
9
+ from pathlib import Path
10
+
11
+ import pytest
12
+
13
+ from aprf_reader import __version__
14
+ from aprf_reader.load import load
15
+ from aprf_reader.render import to_html, to_markdown
16
+ from aprf_reader.summary import to_dict
17
+
18
+ ROOT = Path(__file__).parent.parent
19
+ FIX = Path(__file__).parent / "fixtures"
20
+ NODE = shutil.which("node")
21
+
22
+ pytestmark = pytest.mark.skipif(NODE is None, reason="node is not installed")
23
+
24
+
25
+ def web(mode: str, paths: list[Path]) -> str:
26
+ return subprocess.run([NODE, str(ROOT / "web/test/run.js"), mode, *map(str, paths)], check=True,
27
+ capture_output=True, text=True, env={"APRF_VERSION": __version__}).stdout
28
+
29
+
30
+ def same(paths: list[Path]) -> None:
31
+ loaded = load(paths)
32
+ assert json.loads(web("--json", paths)) == to_dict(loaded.reports, loaded.skipped)
33
+ assert web("--md", paths) == to_markdown(loaded)
34
+ assert web("--html", paths) == to_html(loaded)
35
+
36
+
37
+ def report(day: int, selector: str = "s1", inbox: int = 100) -> dict:
38
+ start = 1790812800 + day * 86400
39
+ return {"header": {"version": 1, "source": "Comcast/Xfinity", "dkim_domain": "Example.com",
40
+ "dkim_selector": selector, "report_start": start, "report_end": start + 86399,
41
+ "sdi_used": " - N/A - Beta - Not in use"},
42
+ "body": [{"classification": {"inbox": inbox, "unwanted": 0}, "engagement": {"positive": 0}}]}
43
+
44
+
45
+ def email(payload: bytes, subtype: str, filename: str | None, cte: str | None = None) -> EmailMessage:
46
+ msg = EmailMessage()
47
+ msg["From"] = "aprf-noreply@example.net"
48
+ msg["Subject"] = "APRF: test"
49
+ msg.set_content("Report attached.")
50
+ # cte=None would mean raw binary, not the base64 default
51
+ msg.add_attachment(payload, maintype="application", subtype=subtype, filename=filename, **({"cte": cte} if cte else {}))
52
+ return msg
53
+
54
+
55
+ @pytest.mark.parametrize("name", ["draft_sample_1.json", "draft_sample_2.json", "comcast_beta.json", "sample_six_weeks.json"])
56
+ def test_fixtures(name):
57
+ same([FIX / name])
58
+
59
+
60
+ def test_all_fixtures_together():
61
+ same(sorted(FIX.glob("*.json")))
62
+
63
+
64
+ def test_files_emails_and_mailboxes(tmp_path):
65
+ def put(name: str, data: bytes) -> Path:
66
+ (tmp_path / name).write_bytes(data)
67
+ return tmp_path / name
68
+
69
+ raw = lambda day, **kw: json.dumps(report(day, **kw)).encode()
70
+ paths = [
71
+ put("a.json", raw(0)),
72
+ put("b.json.gz", gzip.compress(raw(1))),
73
+ put("c.eml", email(gzip.compress(raw(2)), "gzip", "20261003_example.com_s1_Comcast.json.gz").as_bytes()),
74
+ put("d.eml", email(raw(3), "octet-stream", None).as_bytes()),
75
+ put("e.eml", email(raw(4), "json", "r.json", cte="quoted-printable").as_bytes()),
76
+ put("copy.json", raw(0)),
77
+ put("resend.json", raw(0, inbox=900)),
78
+ put("note.eml", email(b"hello", "pdf", "invoice.pdf").as_bytes()),
79
+ ]
80
+ # A report email forwarded as an attachment
81
+ outer = EmailMessage()
82
+ outer["Subject"] = "Fwd: APRF"
83
+ outer.set_content("See attached.")
84
+ outer.add_attachment(email(raw(5, inbox=3000), "json", "f.json"))
85
+ paths.append(put("fwd.eml", outer.as_bytes()))
86
+ box = mailbox.mbox(tmp_path / "Reports.mbox")
87
+ for day in (6, 7, 9):
88
+ box.add(email(gzip.compress(raw(day, selector="s2")), "gzip", f"{day}.json.gz"))
89
+ box.add(email(raw(8, selector="s2"), "json", "same.json"))
90
+ plain = EmailMessage()
91
+ plain.set_content("From the team: not a report")
92
+ box.add(plain)
93
+ box.close()
94
+ paths.append(tmp_path / "Reports.mbox")
95
+ same(paths)
96
+
97
+
98
+ def test_hostile_text_escaped_the_same(tmp_path):
99
+ obj = report(0)
100
+ hostile = "<script>alert('x')</script>|a\\b \"q\" & é\nnew"
101
+ obj["header"].update(source=hostile, extra_info=hostile, sdi_used=hostile)
102
+ obj["body"][0]["segment"] = [hostile, "two"]
103
+ obj["body"][0]["classification"][hostile] = 7
104
+ (tmp_path / "h.json").write_text(json.dumps(obj))
105
+ same([tmp_path / "h.json"])
@@ -1,98 +0,0 @@
1
- """Find report files, open them, and drop duplicates."""
2
-
3
- from __future__ import annotations
4
-
5
- import gzip
6
- import hashlib
7
- import io
8
- import zlib
9
- from collections.abc import Iterable, Iterator
10
- from dataclasses import dataclass, field
11
- from email import policy
12
- from email.parser import BytesParser
13
- from pathlib import Path
14
-
15
- from .report import Report, ReportError, parse
16
-
17
- SUFFIXES = (".json", ".json.gz", ".eml")
18
- # A daily report is a few KB; this stops a stray huge file or gzip bomb
19
- MAX_BYTES = 10 * 1024 * 1024
20
-
21
-
22
- @dataclass
23
- class Loaded:
24
- reports: list[Report] = field(default_factory=list)
25
- skipped: list[tuple[str, str]] = field(default_factory=list) # (where, reason)
26
-
27
-
28
- def _files(paths: Iterable[Path]) -> Iterator[Path]:
29
- for p in paths:
30
- if p.is_dir():
31
- yield from sorted(f for f in p.rglob("*") if f.is_file() and f.name.lower().endswith(SUFFIXES))
32
- else:
33
- yield p
34
-
35
-
36
- def _gunzip(data: bytes) -> bytes:
37
- with gzip.GzipFile(fileobj=io.BytesIO(data)) as g:
38
- out = g.read(MAX_BYTES + 1)
39
- if len(out) > MAX_BYTES:
40
- raise ReportError("larger than 10 MB unpacked")
41
- return out
42
-
43
-
44
- def _payloads(path: Path) -> Iterator[tuple[str, bytes]]:
45
- """Yield (label, report JSON bytes) for each report in a file."""
46
- data = path.read_bytes()
47
- if len(data) > MAX_BYTES:
48
- raise ReportError("larger than 10 MB")
49
- name = path.name.lower()
50
- if name.endswith(".eml"):
51
- msg = BytesParser(policy=policy.default).parsebytes(data)
52
- found = False
53
- for part in msg.walk():
54
- fname = (part.get_filename() or "").lower()
55
- ctype = part.get_content_type()
56
- if fname.endswith(".json.gz") or ctype == "application/gzip":
57
- found = True
58
- yield f"{path} ({fname or ctype})", _gunzip(part.get_payload(decode=True) or b"")
59
- elif fname.endswith(".json") or ctype == "application/json":
60
- found = True
61
- yield f"{path} ({fname or ctype})", part.get_payload(decode=True) or b""
62
- if not found:
63
- raise ReportError("no .json or .json.gz attachment")
64
- elif data[:2] == b"\x1f\x8b":
65
- yield str(path), _gunzip(data)
66
- else:
67
- yield str(path), data
68
-
69
-
70
- def load(paths: Iterable[Path]) -> Loaded:
71
- out = Loaded()
72
- seen_bytes: set[str] = set()
73
- seen_keys: dict[tuple, str] = {}
74
- for path in _files(paths):
75
- try:
76
- payloads = list(_payloads(path))
77
- except (OSError, EOFError, zlib.error, ReportError) as e:
78
- out.skipped.append((str(path), str(e)))
79
- continue
80
- for where, data in payloads:
81
- digest = hashlib.sha256(data).hexdigest()
82
- if digest in seen_bytes:
83
- out.skipped.append((where, "duplicate of a file already read"))
84
- continue
85
- seen_bytes.add(digest)
86
- try:
87
- reports = parse(data)
88
- except ReportError as e:
89
- out.skipped.append((where, str(e)))
90
- continue
91
- for r in reports:
92
- # The draft does not yet say whether a resend replaces the first; keep the first
93
- if r.key in seen_keys:
94
- out.skipped.append((where, f"same day already reported in {seen_keys[r.key]}; kept that one"))
95
- continue
96
- seen_keys[r.key] = where
97
- out.reports.append(r)
98
- return out
File without changes
File without changes