Files
LambdaMail/services/protocols/internal/application/usecase/message_render.go
T
Lucas RayanandClaude Opus 5 48fe3c68f3 #21: serve the webmail mail API from the protocols service
The mail screens had no backend at all: they rendered a hardcoded array,
and the storage service that ADR-001 assigned this to is still a health
stub. The API lands here instead, because the folder, UID, MODSEQ, flag
and blob logic already exists and is tested in this service for IMAP.
Reimplementing it in TypeScript would mean two implementations of the
same semantics and two chances to disagree about what a UID means.

Reads use a projected read model rather than hydrated aggregates, which
is the CQRS exception PLAN.md section 2 carves out for webmail queries.
Every query is scoped to the mailbox resolved from the verified session,
never to an identifier taken from the request, so one account cannot read
another's mail by guessing a UID - covered by a test that tries exactly
that and expects 404.

Sending reuses ProcessOutboundEmailUseCase, so mail written in the browser
gets the same treatment as mail submitted over 587: send limits, DKIM
signing, and the durable queue. The From address comes from the session
and never from the request body; letting the body choose it is how a
webmail becomes a relay for spoofed mail.

MIME is parsed server-side because this service already depends on a MIME
library. A message that will not parse still returns its raw text - an
unreadable message beats an inbox that refuses to open one.

Marking a message read updates the flag and the folder counter in one
transaction, and only on a real transition, so re-opening a message cannot
drive unread_count negative.

Verified against the running stack: a message delivered over port 25
appears in the list with its decoded subject and sender, opens, marks
itself read, is found by search, and a message composed in the webmail
reaches outbound_jobs with the session's address as the envelope sender.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-02 10:03:25 -03:00

113 lines
3.4 KiB
Go

package usecase
import (
"bytes"
"io"
"strings"
"github.com/emersion/go-message"
"github.com/emersion/go-message/mail"
)
// maxRenderedPartBytes bounds how much of one part is returned to the browser.
// A message can legitimately be tens of megabytes; the reader pane cannot use
// that, and holding it in memory per request is how a few open tabs turn into
// an out-of-memory kill.
const maxRenderedPartBytes = 2 << 20 // 2 MiB
// RenderedMessage is a message prepared for display: headers the reader shows
// and the two body flavours, already decoded from their transfer encoding.
type RenderedMessage struct {
UID uint32 `json:"uid"`
Subject string `json:"subject"`
From string `json:"from"`
To []string `json:"to"`
Cc []string `json:"cc"`
Date string `json:"date"`
Text string `json:"text"`
HTML string `json:"html"`
Attachments []string `json:"attachments"`
}
// RenderMessage turns raw RFC 5322 bytes into what the reader pane needs.
//
// Parsing happens here rather than in the browser because this service already
// depends on a MIME library, and a second implementation in TypeScript would
// be a second set of edge cases to get wrong. A message that cannot be parsed
// still yields its raw text rather than an error - unreadable formatting beats
// an inbox that refuses to open a message.
func RenderMessage(raw []byte, uid uint32) RenderedMessage {
out := RenderedMessage{UID: uid, To: []string{}, Cc: []string{}, Attachments: []string{}}
entity, err := message.Read(bytes.NewReader(raw))
if err != nil {
out.Text = string(raw)
return out
}
header := mail.Header{Header: entity.Header}
out.Subject, _ = header.Subject()
if addrs, err := header.AddressList("From"); err == nil && len(addrs) > 0 {
out.From = addrs[0].String()
}
for _, field := range []struct {
name string
dst *[]string
}{{"To", &out.To}, {"Cc", &out.Cc}} {
if addrs, err := header.AddressList(field.name); err == nil {
for _, a := range addrs {
*field.dst = append(*field.dst, a.String())
}
}
}
// A missing Date header parses without error into the zero time, which
// would render as the year 0001 in the reader. Left empty, the UI falls
// back to the received timestamp it already has.
if date, err := header.Date(); err == nil && !date.IsZero() {
out.Date = date.UTC().Format("2006-01-02T15:04:05Z")
}
collectParts(entity, &out)
return out
}
// collectParts walks the MIME tree, keeping the first text and HTML bodies and
// naming everything else as an attachment.
func collectParts(entity *message.Entity, out *RenderedMessage) {
if multipart := entity.MultipartReader(); multipart != nil {
for {
part, err := multipart.NextPart()
if err != nil {
return
}
collectParts(part, out)
}
}
mediaType, _, err := entity.Header.ContentType()
if err != nil {
mediaType = "text/plain"
}
if disposition, params, err := entity.Header.ContentDisposition(); err == nil && disposition == "attachment" {
name := params["filename"]
if name == "" {
name = "attachment"
}
out.Attachments = append(out.Attachments, name)
return
}
body, err := io.ReadAll(io.LimitReader(entity.Body, maxRenderedPartBytes))
if err != nil {
return
}
switch {
case strings.EqualFold(mediaType, "text/plain") && out.Text == "":
out.Text = string(body)
case strings.EqualFold(mediaType, "text/html") && out.HTML == "":
out.HTML = string(body)
}
}