diff --git a/src/postmaster/mail_url_redaction_v981014.py b/src/postmaster/mail_url_redaction_v981014.py
new file mode 100644
index 00000000..d32e7840
--- /dev/null
+++ b/src/postmaster/mail_url_redaction_v981014.py
@@ -0,0 +1,73 @@
+"""Prevent passive readers and URL-scanning extensions seeing raw bearer URLs.
+
+Redaction happens BEFORE untrusted email content reaches an authenticated
+WebGUI HTML fragment, including escaped diagnostics and cache snippets.
+The actual MIME/URL inventory remains unchanged for explicit, authorized
+on-demand inspection. No DNS, HTTP, tracking click, or file fetch occurs.
+"""
+from __future__ import annotations
+
+import re
+from html import escape
+from html.parser import HTMLParser
+
+URL_HIDDEN = "[URL hidden — reveal explicitly]"
+_URL = re.compile(
+ r"(?i)(?:\b(?:https?|ftps?)://|(?'\"()]*"
+)
+
+
+def hide_url_text(value: str) -> str:
+ """Mask absolute, common schemeless, and relative tracked URLs as text."""
+ return _URL.sub(URL_HIDDEN, str(value or ""))
+
+
+class _SafeHtmlURLMask(HTMLParser):
+ """Accept ONLY already-sanitized Safe Email HTML, never raw email HTML."""
+ def __init__(self) -> None:
+ super().__init__(convert_charrefs=True)
+ self.parts: list[str] = []
+
+ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
+ # Rebuild escaped attributes. safe_email_html() already disallows
+ # active tags, remote assets, event handlers, and navigable href.
+ attr = "".join(
+ ' ' + escape(k, quote=True) + '="' +
+ escape(hide_url_text(v or ""), quote=True) + '"'
+ for k, v in attrs
+ )
+ self.parts.append("<" + tag + attr + ">")
+
+ def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
+ self.handle_starttag(tag, attrs)
+
+ def handle_endtag(self, tag: str) -> None:
+ self.parts.append("" + tag + ">")
+
+ def handle_data(self, data: str) -> None:
+ self.parts.append(escape(hide_url_text(data), quote=False))
+
+ def handle_entityref(self, name: str) -> None:
+ self.parts.append("&" + name + ";")
+
+ def handle_charref(self, name: str) -> None:
+ self.parts.append("" + name + ";")
+
+ def handle_comment(self, value: str) -> None:
+ return
+
+
+def hide_urls_in_safe_html(sanitized_html: str) -> str:
+ """Redact *visible text*, including attribute titles, without breaking tags."""
+ parser = _SafeHtmlURLMask()
+ try:
+ parser.feed(sanitized_html or "")
+ parser.close()
+ except Exception:
+ # Fail closed: never serve unmodified HTML containing opaque tokens.
+ return escape(hide_url_text(re.sub(r"<[^>]*>", "", sanitized_html or "")))
+ return "".join(parser.parts)
+
+
+__all__ = ["URL_HIDDEN", "hide_url_text", "hide_urls_in_safe_html"]
diff --git a/src/postmaster/webgui_links_v984.py b/src/postmaster/webgui_links_v984.py
index f7cd9f07..8b2b689b 100644
--- a/src/postmaster/webgui_links_v984.py
+++ b/src/postmaster/webgui_links_v984.py
@@ -15,6 +15,7 @@
from .webgui_helpers import owner_options, project_options
from .webgui_v962_perf import active_projects, owners
+from .mail_url_redaction_v981014 import hide_url_text
def _e(value: Any) -> str:
@@ -120,7 +121,7 @@ def render_tracked_links_v984(base: Any, core: Any, request: Request, *, target_
status = str(link.get("status") or "unknown")
target = str(link.get("destination_url") or link.get("filename") or link.get("file_id") or "")
kind = "Tracked file" if link.get("target_type") == "stored_file" else "Tracked URL"
- tracked_url = str(link.get("tracked_url") or "")
+ # Tracked URL must not be serialized into the dashboard HTML.
counters = link.get("analytics") or link.get("aggregate") or {}
if not isinstance(counters, dict):
counters = {}
@@ -137,14 +138,21 @@ def render_tracked_links_v984(base: Any, core: Any, request: Request, *, target_
''
''
)
+ reveal = (
+ '
'
+ )
rows.append(
''
- f'| {_e(link.get("label"))} {_e(kind)} · {_e(status)} '
+ f' | {_e(hide_url_text(str(link.get("label") or "")))} {_e(kind)} · {_e(status)} '
f'{_e(link_id)} | '
f'{_e(oid)} / {_e(pid or "owner-wide")} | '
- f'{_e(target)} | '
- f' | '
+ f'{_e(hide_url_text(target))} | '
+ f'{reveal} | '
f'{_e(count)} | {revocation} |
'
)
errors_html = (
@@ -239,9 +247,55 @@ async def revoke(request: Request) -> Response:
)
return RedirectResponse(_redirect(owner, project, "Tracked link revoked"),status_code=303)
+ async def reveal(request: Request) -> Response:
+ """Read-only capability disclosure only after verified explicit POST."""
+ form, error = await base._verified_form(request)
+ if error is not None:
+ return error
+ try:
+ owner, project = _scope(form, base)
+ link_id = str(form.get("tracked_link_id") or "").strip()
+ if not link_id or len(link_id) > 200:
+ raise ValueError("Invalid tracked link")
+ result = core.list_tracked_links(
+ owner_id=owner, project_id=project,
+ active_only=False, limit=500,
+ )
+ if not isinstance(result, dict) or result.get("ok") is not True:
+ raise ValueError("Tracked link lookup failed")
+ item = next(
+ (x for x in result.get("links", [])
+ if isinstance(x, dict) and str(x.get("id") or "") == link_id
+ and str(x.get("owner_id") or "") == owner
+ and str(x.get("project_id") or "") == str(project or "")),
+ None,
+ )
+ if item is None:
+ raise ValueError("Tracked link not found")
+ url = str(item.get("tracked_url") or "")
+ if not url:
+ raise ValueError("Tracked link unavailable")
+ dest = str(item.get("destination_url") or "")
+ except (ValueError, KeyError, TypeError):
+ return PlainTextResponse("Tracked link not available", status_code=404)
+ # No , images, redirects or resource fetches. The browser only sees
+ # the URL after the authorized administrator explicitly presses Reveal.
+ return PlainTextResponse(
+ "Tracked URL (explicit display, not requested):\n" + url
+ + ("\n\nDestination:\n" + dest if dest else "") + "\n",
+ headers={
+ "Cache-Control": "no-store, max-age=0",
+ "Content-Security-Policy": "default-src 'none'; base-uri 'none'; form-action 'none'",
+ "Referrer-Policy": "no-referrer",
+ "X-Content-Type-Options": "nosniff",
+ "X-Robots-Tag": "noindex, nofollow, noarchive",
+ },
+ )
+
index = next(
(i for i, route in enumerate(app.router.routes) if isinstance(route, Mount)),
len(app.router.routes),
)
app.router.routes.insert(index, Route("/dashboard/tracked-links/create", create, methods=["POST"]))
app.router.routes.insert(index+1, Route("/dashboard/tracked-links/revoke", revoke, methods=["POST"]))
+ app.router.routes.insert(index+2, Route("/dashboard/tracked-links/reveal", reveal, methods=["POST"]))
diff --git a/src/postmaster/webgui_tracking_v984.py b/src/postmaster/webgui_tracking_v984.py
index 22ad9694..b8a9df39 100644
--- a/src/postmaster/webgui_tracking_v984.py
+++ b/src/postmaster/webgui_tracking_v984.py
@@ -13,6 +13,7 @@
from starlette.requests import Request
from .tracking_geoip_v984 import global_tracking_network_events
+from .mail_url_redaction_v981014 import hide_url_text
_ZONE = ZoneInfo("Europe/Rome")
_PERIODS = {"24h": timedelta(hours=24), "7d": timedelta(days=7),
@@ -192,7 +193,7 @@ def _event_html(event: dict[str, Any]) -> str:
disclosure; no external resource is fetched or opened while rendering.
"""
def e(k: str) -> str:
- return escape(str(event.get(k) or "—"))
+ return escape(hide_url_text(str(event.get(k) or "—")))
kind = str(event.get("event_kind") or "")
names = {
@@ -202,11 +203,11 @@ def e(k: str) -> str:
"tracked_file_download": "File scaricato",
}
title = names.get(kind, kind)
- subject = str(event.get("email_subject") or "").strip()
+ subject = hide_url_text(str(event.get("email_subject") or "").strip())
recipient = str(event.get("recipient") or "").strip()
original = str(event.get("original_url") or "").strip()
filename = str(event.get("download_filename") or "").strip()
- label = str(event.get("label") or "").strip()
+ label = hide_url_text(str(event.get("label") or "").strip())
href = str(event.get("email_href") or "").strip()
info: list[str] = []
if kind.startswith("email_"):
@@ -216,7 +217,7 @@ def e(k: str) -> str:
if recipient:
info.append("Destinatario: " + escape(recipient) + "")
if kind == "email_click" and original:
- info.append("Destinazione del link: " + escape(original) + "")
+ info.append("Destinazione del link: [URL hidden — reveal explicitly in Mail]")
if href.startswith("/?") and href.endswith("#inbox"):
info.append(
'Etichetta: " + escape(label) + "")
else:
info.append("URL di destinazione:")
- try:
- parts = urlsplit(original)
- clickable = parts.scheme.lower() in {"http", "https"} and bool(parts.netloc)
- except ValueError:
- clickable = False
- if clickable:
- info.append('' +
- escape(original) + "")
- elif original:
- info.append("" + escape(original) + "")
+ if original:
+ info.append("[URL hidden — use Tracked Links to reveal]")
else:
info.append("Destinazione non disponibile")
if label:
diff --git a/src/postmaster/webgui_v963.py b/src/postmaster/webgui_v963.py
index 52cc57d9..bf4bb134 100644
--- a/src/postmaster/webgui_v963.py
+++ b/src/postmaster/webgui_v963.py
@@ -11,7 +11,7 @@
from urllib.parse import urlencode
from starlette.requests import Request
-from starlette.responses import HTMLResponse, RedirectResponse, Response
+from starlette.responses import HTMLResponse, RedirectResponse, Response, PlainTextResponse
from starlette.routing import Route
from . import webgui_v951 as v951
@@ -19,6 +19,7 @@
from . import webgui_v953 as v953
from . import webgui_v960 as v960
from .email_inventory_v963 import inventory_message
+from .mail_url_redaction_v981014 import hide_url_text, hide_urls_in_safe_html
from .email_privacy_v963 import (
attach_cache_state,
fetch_passive_resources,
@@ -174,24 +175,24 @@ def _technical_details(inventory: dict[str, Any], proxy: dict[str, Any]) -> str:
dims = ""
if item.get("width") or item.get("height"):
dims = f"{item.get('width') or '?'} × {item.get('height') or '?'}"
- reasons = "; ".join(str(value) for value in item.get("tracking_reasons") or []) or "—"
- observed = "; ".join(str(value) for value in item.get("observed_evidence") or []) or "—"
+ reasons = hide_url_text("; ".join(str(value) for value in item.get("tracking_reasons") or [])) or "—"
+ observed = hide_url_text("; ".join(str(value) for value in item.get("observed_evidence") or [])) or "—"
redirect = "—"
if item.get("redirect_location"):
- redirect = f"{item.get('redirect_status') or ''} Location: {item.get('redirect_location')}"
+ redirect = f"{item.get('redirect_status') or ''} Location: [URL hidden — reveal explicitly]"
rows.append(
""
- f'{escape(str(item.get("url") or ""))} | '
+ f'[URL hidden — reveal explicitly] | '
f'{escape(str(item.get("domain") or "—"))} | '
f'{escape(str(item.get("source_type") or "—"))} | '
- f'{escape(str(item.get("source_snippet") or "—"))} | '
- f'{escape(str(item.get("anchor_text") or "—"))} | '
+ f'{escape(hide_url_text(str(item.get("source_snippet") or "—")))} | '
+ f'{escape(hide_url_text(str(item.get("anchor_text") or "—")))} | '
f'{escape(str(item.get("classification") or "unknown"))} | '
f'{int(item.get("tracking_score") or 0)}/100 {escape(reasons)} | '
f'{escape(dims or "—")} | '
f'{escape(str(item.get("cache_status") or "not fetched"))} {escape(str(item.get("proxy_status") or "not contacted"))} | '
f'{escape(redirect)} | '
- f'{escape(observed)} Inference: {escape(str(item.get("inference") or "heuristic"))} | '
+ f'{escape(observed)} Inference: {escape(hide_url_text(str(item.get("inference") or "heuristic")))} | '
"
"
)
return f'''
@@ -202,6 +203,22 @@ def _technical_details(inventory: dict[str, Any], proxy: dict[str, Any]) -> str:
'''
+def _url_reveal_form(base: Any, account_id: str, mailbox: str, uid: str) -> str:
+ """The form itself contains no original URL or link capability."""
+ return (
+ ''
+ )
+
+
def _allow_passive(row: dict[str, Any]) -> bool:
source = str(row.get("source_type") or "").casefold()
if source in {"img src", "source src", "video poster", "style url()", "style-block url()"}:
@@ -377,7 +394,8 @@ def _detail(base: Any, params: dict[str, str], account_id: str, mailbox: str, ro
body_text = str(detail.get("body") or "")
inventory = attach_cache_state(inventory_message(body_html, body_text), base.mailbox_cache_store(), account_id=account_id, mailbox=mailbox, uid=uid)
proxy = base.privacy_proxy_store().status()
- safe = safe_email_html(body_html) if body_html else f'{escape(body_text[:100000])}'
+ safe = (hide_urls_in_safe_html(safe_email_html(body_html)) if body_html
+ else f'{escape(hide_url_text(body_text[:100000]))}')
close = _href(params, message_uid=None, compose_mode=None, full_html=None, full_html_intent=None)
action_base = {**params, "message_uid": uid}
buttons = []
@@ -431,7 +449,7 @@ def _detail(base: Any, params: dict[str, str], account_id: str, mailbox: str, ro
if compose_mode in {"reply", "reply_all", "forward"}:
compose = _thread_compose(base, account_id, mailbox, uid, compose_mode, raw, body_text, role=role, body_html=body_html)
counterpart = str(detail.get("to") if role == "sent" else detail.get("from") or "")
- return f'''{escape(str(detail.get('subject') or 'Message'))}
{escape('To' if role == 'sent' else 'From')}: {escape(counterpart)} · {escape(str(detail.get('date') or ''))}
Close{''.join(buttons)}
{mode_label}{warning}{body_view}{_technical_details(inventory, proxy)}{compose}
'''
+ return f'''{escape(hide_url_text(str(detail.get('subject') or 'Message')))}
{escape('To' if role == 'sent' else 'From')}: {escape(counterpart)} · {escape(str(detail.get('date') or ''))}
Close{''.join(buttons)}
{mode_label}{warning}{body_view}{_technical_details(inventory, proxy)}{_url_reveal_form(base, account_id, mailbox, uid)}{compose}
'''
def render_inbox_v963(base: Any, request: Request) -> str:
@@ -536,7 +554,7 @@ def render_inbox_v963(base: Any, request: Request) -> str:
)) if all_accounts else ""
badge = (f'{escape(account_label)}'
if all_accounts and account_label else "")
- rows.append(f'| {dot} | {escape(counterpart)} | {escape(str(row.get("subject") or ""))}{escape(str(row.get("snippet") or "")[:160])}{badge} | {escape(str(row.get("date") or ""))} |
')
+ rows.append(f'| {dot} | {escape(counterpart)} | {escape(hide_url_text(str(row.get("subject") or "")))}{escape(hide_url_text(str(row.get("snippet") or "")[:160]))}{badge} | {escape(str(row.get("date") or ""))} |
')
is_selected = (
uid and row_uid == uid and
(not all_accounts or
@@ -671,6 +689,48 @@ async def delete_saved_draft(base: Any, request: Request):
)
+async def reveal_message_urls(base: Any, request: Request):
+ """Authorized, explicit disclosure of URLs; never fetch or follow them."""
+ form, error = await base._verified_form(request)
+ if error:
+ return error
+ account_id = str(form.get("account_id") or "").strip()
+ mailbox = str(form.get("mailbox") or "").strip()
+ uid = str(form.get("uid") or "").strip()
+ if not account_id or not mailbox or not uid.isdecimal() or int(uid) < 1:
+ return Response(status_code=400)
+ account = base.account_store().get_account(account_id)
+ if not account or account.get("enabled") is False:
+ return Response(status_code=404)
+ store = base.mailbox_cache_store()
+ if not any(str(row.get("name") or "") == mailbox
+ for row in store.list_mailboxes(account_id)):
+ return Response(status_code=404)
+ selected = store.get_message(account_id, mailbox, uid, include_body=True)
+ if not selected or not selected.get("body_cached"):
+ return Response(status_code=404)
+ inventory = inventory_message(
+ str(selected.get("body_html") or ""),
+ str(selected.get("body") or ""),
+ )
+ urls = list(dict.fromkeys(
+ str(row.get("url") or "") for row in inventory.get("urls") or []
+ if str(row.get("url") or "")
+ ))
+ content = (
+ "Explicit URL inspection (no URLs were fetched)\n"
+ + "Original URL count: " + str(len(urls)) + "\n\n"
+ + "\n".join(urls)
+ )
+ return PlainTextResponse(content, headers={
+ "Cache-Control": "no-store, max-age=0",
+ "Content-Security-Policy": "default-src 'none'; base-uri 'none'; form-action 'none'",
+ "X-Content-Type-Options": "nosniff",
+ "Referrer-Policy": "no-referrer",
+ "X-Robots-Tag": "noindex, nofollow, noarchive",
+ })
+
+
async def confirm_full_html(base: Any, request: Request):
form, error = await base._verified_form(request)
if error:
@@ -783,6 +843,7 @@ def install_webgui_v963(app: Any, base: Any) -> None:
v951.render_inbox = v960.render_inbox
routes = [
("/dashboard/inbox/refresh", refresh_inbox, ["POST"], "v963_inbox_refresh"),
+ ("/dashboard/inbox/reveal-urls", reveal_message_urls, ["POST"], "v981014_reveal_urls"),
("/dashboard/inbox/full-html", confirm_full_html, ["POST"], "v963_full_html"),
("/dashboard/inbox/draft", save_thread_draft, ["POST"], "v963_inbox_draft"),
("/dashboard/inbox/draft/delete", delete_saved_draft, ["POST"], "v9810_delete_saved_draft"),
diff --git a/tests/test_safe_mail_url_redaction_v981014.py b/tests/test_safe_mail_url_redaction_v981014.py
new file mode 100644
index 00000000..d1a3f8d3
--- /dev/null
+++ b/tests/test_safe_mail_url_redaction_v981014.py
@@ -0,0 +1,153 @@
+from __future__ import annotations
+
+import asyncio
+import unittest
+from types import SimpleNamespace
+from unittest.mock import Mock
+
+from starlette.requests import Request
+from starlette.responses import PlainTextResponse, Response
+
+from postmaster.email_privacy_v963 import safe_email_html
+from postmaster.mail_url_redaction_v981014 import (
+ URL_HIDDEN, hide_url_text, hide_urls_in_safe_html,
+)
+from postmaster import webgui_v963
+
+
+TRACKED = "https://example.test/t/c/PrivateOpaqueToken123456"
+OTHER = "https://cdn.example.test/file.png"
+
+
+def request() -> Request:
+ return Request({"type": "http", "path": "/dashboard/inbox/reveal-urls",
+ "method": "POST", "query_string": b"", "headers": []})
+
+
+class Base:
+ def __init__(self, form=None, *, csrf_ok=True, account_exists=True,
+ body_cached=True, mailbox_exists=True):
+ self.form = form or {
+ "account_id": "a", "mailbox": "INBOX.Sent", "uid": "331",
+ }
+ self.csrf_ok = csrf_ok
+ self.get_account = Mock(
+ return_value={"id": "a", "enabled": True} if account_exists else None
+ )
+ self.get_message = Mock(return_value={
+ "body_cached": body_cached,
+ "body": "Original link " + TRACKED,
+ "body_html": (
+ 'Asset'
+ '
'
+ ),
+ })
+ self.get_mailboxes = Mock(
+ return_value=[{"name": "INBOX.Sent", "role": "sent"}] if mailbox_exists
+ else [{"name": "INBOX", "role": "received"}]
+ )
+ self.account_store = lambda: SimpleNamespace(get_account=self.get_account)
+ self.mailbox_cache_store = lambda: SimpleNamespace(
+ get_message=self.get_message, list_mailboxes=self.get_mailboxes
+ )
+ self._csrf_value = lambda: "CSRF-protected-value"
+
+ async def _verified_form(self, _request):
+ if not self.csrf_ok:
+ return None, Response(status_code=403)
+ return self.form, None
+
+
+class SafeMailURLRedactionTests(unittest.TestCase):
+ def test_visible_text_masks_full_link_tokens_without_touching_original(self):
+ message = "Open " + TRACKED + " or " + OTHER
+ sanitized = hide_url_text(message)
+ self.assertNotIn("PrivateOpaqueToken123456", sanitized)
+ self.assertNotIn("cdn.example.test", sanitized)
+ self.assertEqual(sanitized.count(URL_HIDDEN), 2)
+ self.assertEqual(message, "Open " + TRACKED + " or " + OTHER)
+ self.assertIn(URL_HIDDEN, hide_url_text("/t/c/Token123"))
+ self.assertIn(URL_HIDDEN, hide_url_text("www.example.test/foo"))
+
+ def test_html_redacts_text_and_titles_and_preserves_safe_markup(self):
+ html = safe_email_html(
+ 'Check '
+ + TRACKED + ' and text & data.
'
+ '
'
+ )
+ self.assertNotIn("href=", html)
+ redacted = hide_urls_in_safe_html(html)
+ self.assertNotIn("PrivateOpaqueToken123456", redacted)
+ self.assertNotIn("https://", redacted)
+ self.assertIn("", redacted)
+ self.assertIn("text & data", redacted)
+ self.assertNotIn("
Asset',
+ "anchor_text": TRACKED, "classification": "analytics link",
+ "tracking_reasons": ["tracking endpoint " + TRACKED],
+ "observed_evidence": ["Request " + OTHER],
+ "redirect_location": OTHER, "redirect_status": 302},
+ ], "url_count": 1}
+ html = webgui_v963._technical_details(inventory, {"enabled": False})
+ self.assertIn("URL hidden", html)
+ self.assertNotIn(TRACKED, html)
+ self.assertNotIn(OTHER, html)
+ self.assertNotIn("PrivateOpaqueToken123456", html)
+ self.assertIn("analytics link", html)
+
+ def test_explicit_reveal_form_contains_only_identifiers_no_public_link(self):
+ html = webgui_v963._url_reveal_form(Base(), "a", "INBOX.Sent", "331")
+ self.assertIn('method="post"', html)
+ self.assertIn('target="_blank"', html)
+ self.assertIn('name="csrf"', html)
+ self.assertIn('name="uid" value="331"', html)
+ self.assertIn("Reveal original URLs (explicit)", html)
+ self.assertNotIn(TRACKED, html)
+
+ def test_reveal_post_is_only_way_original_urls_enter_page(self):
+ base = Base()
+ response = asyncio.run(webgui_v963.reveal_message_urls(base, request()))
+ self.assertIsInstance(response, PlainTextResponse)
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.media_type, "text/plain")
+ text = response.body.decode()
+ self.assertIn(TRACKED, text)
+ self.assertIn(OTHER, text)
+ self.assertNotIn("