feat: Render HTML inline in Archive with sanitization and plain/HTML toggle

This MR implements Hyperkitty archive display support for HTML email parts, as discussed in !702. As per Stephen's feedback, this MR tackles display support first before expanding the editor.

Relates to issue #476 and #540

Note:- This MR is intended to merge before !702 (feature/rich-text-compose). The editor MR will be rebased on top of this one once it lands.

cc @stephenjturnbull @danil-smirnov @msapiro

What this does

When an archived email contains a text/html MIME part, it now renders inline within the archive instead of just showing a download link. A "View HTML / View Plain Text" toggle appears above the message body, defaulting to the HTML view. Emails without HTML parts remain unchanged.

Implementation Details

  • views/message.py: Added a new html_attachment view that decodes and sanitizes HTML using nh3. It uses a strict tag/attribute allowlist before serving. It also explicitly sets X-Frame-Options: SAMEORIGIN to allow our own iframe embedding while blocking external sites.
  • urls.py: Added a new URL pattern for attachment/<counter>/html.
  • models/email.py: Introduced two new properties (html_attachment and file_attachments) so the templates can cleanly distinguish the HTML body from typical downloadable files that might have been attached.
  • messages/message.html: Updated the template to show the HTML part as the main body alongside the new toggle button. The attachments section at the bottom now exclusively lists non-HTML attachments.
  • hyperkitty/static/hyperkitty/js/hyperkitty-thread.js: Added logic to automatically resize iframes to content height and handle the toggle button clicks.
  • pyproject.toml: Added the nh3>=0.2 dependency.

Security Measures

  • HTML is sanitized server-side with nh3 - scripts, event handlers, and all non-allowlisted tags/attributes are aggressively stripped.
  • The iframe utilizes sandbox="allow-same-origin" and referrerpolicy="no-referrer".
  • X-Frame-Options: SAMEORIGIN is explicitly set on the response, ensuring external sites cannot embed the endpoint.
  • Sanitization happens entirely at serve time. The raw, original content is preserved perfectly in the database archive.

Testing

Added three new tests to test_message.py:

  • test_html_attachment_renders_inline: Verifies the HTML content is served correctly.
  • test_html_attachment_strips_scripts: Verifies <script> tags and onclick handlers are successfully stripped.
  • test_html_attachment_wrong_type_returns_404: Verifies that attempting to hit this endpoint for non-HTML attachments correctly returns a 404.

Licensing

Sample Screenshots:

image.png

image.png

Merge request reports

Loading
Loading