diff --git a/README.md b/README.md index fe0e117..d23bdab 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,8 @@ Use an app-specific password for [iCloud](https://support.apple.com/en-us/102525 Want to try it first? Run `hane demo` for a sample inbox that never connects or sends mail. +To try the image button, open **A few photos from the coast** in the demo and click **Always show images**. The sample is local, and demo settings reset when you quit. + ## Everyday use Use these keys to navigate Hane's TUI: @@ -59,6 +61,7 @@ Use these keys to navigate Hane's TUI: | `Space n t` | Show or hide the account explorer | | `/` | Search downloaded mail | | `r` / `c` | Reply / compose a new message | +| `I` / `S` | Always show remote images / reading settings | | `u` / `s` | Toggle unread / starred | | `dd` | Move a conversation to Trash after confirmation | | `R` / `L` | Sync now / load older messages | @@ -70,6 +73,8 @@ In the editor, press **i** to type and **Esc** to return to Normal mode. Use **` Mail syncs in the background every minute. Opening a conversation marks it read; previews do not. Use `hane --offline` to read cached mail and write drafts without connecting. +Embedded and attached images appear inline when you open a conversation. When remote images are hidden, click the **Always show images** button above the message or press **I** once. Hane remembers the choice for all messages, including after restarting. Press **S** for reading settings to turn them off. Image hosts can see those requests. PNG, JPEG, GIF (first frame), and WebP previews use terminal colour cells; the pixels are cached only for the current session. + For the complete keymap, account setup, and delivery recovery instructions, see the [usage guide](docs/usage.md). ## Update @@ -110,6 +115,6 @@ hane help passwords The previous `--demo`, `--version`, `--sync-once`, `--check-connection`, and `--password-setup` flags remain supported as command aliases. -Connection checks and `hane sync` do not send outgoing messages. Search covers downloaded mail; use **L** to load more. Attachments are listed but cannot yet be downloaded or attached, and composition is plain text. Drafts are stored locally rather than in the server's Drafts folder. +Connection checks and `hane sync` do not send outgoing messages. Search covers downloaded mail; use **L** to load more. Image attachments can be previewed; general file downloads and uploads are not available yet, and composition is plain text. Drafts are stored locally rather than in the server's Drafts folder. See [development](docs/development.md) for the source layout, tests, and release builds. diff --git a/docs/development.md b/docs/development.md index 551de81..535558c 100644 --- a/docs/development.md +++ b/docs/development.md @@ -8,6 +8,7 @@ internal/app/ Terminal UI, accounts, mail, and credential handling internal/app/assets/ Embedded terminal logo internal/buildinfo/ Shared application version internal/cli/ Command parsing, option validation, and help +internal/mailimage/ Bounded raster decoding, public HTTP fetching, terminal previews internal/update/ Release discovery, verified downloads, atomic installation scripts/ Release packaging and screenshot rendering docs/ Usage guide and screenshots @@ -65,3 +66,15 @@ Open a pull request for every change to `main`, including administrator changes. David (`@dmillzilla`) owns all files through `.github/CODEOWNERS`. Non-admins need one approving code-owner review; new reviewable commits dismiss stale approvals. Repository admins can explicitly bypass the review requirement when merging a PR, including their own PRs. That exception does not bypass the PR requirement, CI checks, or conversation resolution. GitHub applies bypass permission to the person merging, rather than to the PR author. Admins should approve contributor PRs before merging; the review bypass exists so admin-authored PRs do not need self-approval. + +## Message images + +Normal IMAP reads index image MIME parts and an HTML alternative without fetching separate image parts or remote image URLs. The plaintext body is preserved, and a separate sanitized body retains image placeholders by message ID. Legacy mail cache entries gain this metadata when synced; the storage schema remains compatible. + +Opening a conversation schedules bounded local/attached image jobs. Remote jobs are allowed only by the saved app-wide reading preference (off by default) or an explicit one-conversation command. The reader notice enables the remembered preference; Settings disables it and cancels pending work. `preferences.json` uses the existing private, atomic config writer. Invalid preferences stay blocked and are preserved rather than overwritten. + +Remote HTTP requests use a dedicated client with no environment proxy, cookies, mail credentials, or Referer. Every DNS answer is checked before dialing a pinned public address, including on public redirects. Private destinations, HTTPS downgrades, redirect loops, oversized responses, and unsupported raster types are rejected. MIME image fetches use read-only selection, UIDVALIDITY validation, and BODY.PEEK. + +The demo includes an embedded picture in its first conversation and a simulated remote picture in **A few photos from the coast**. The simulated source goes through the regular consent UI, but the demo loader supplies a local raster and rejects other network/attachment requests. Demo reading preferences are session-only and do not read or overwrite the real preference file. + +Decoded dimensions are checked before full pixel allocation, then pixels are reduced for a bounded in-memory cache. Truecolor half-block previews use the regular TUI layout so scrolling, resizing, and redraws work without graphics-protocol support. Background jobs carry generations; hiding images or leaving a conversation cancels work and stale completions cannot reopen previews or populate another message. The reducer schedules automatic loading after both navigation and live sync, without repeatedly retrying failures. diff --git a/docs/usage.md b/docs/usage.md index a50931d..e7352a0 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -11,7 +11,30 @@ - Opening a conversation searches all server folders for its Message-ID, References, and In-Reply-To relationships, including older parents beyond the inbox page. Copies with the same Message-ID display once in the conversation. Unrelated messages are not merged merely because they share a subject. - Opening a thread marks its messages read. **u** toggles read/unread; **s** toggles starred. Changes are saved locally before being queued for the server. Temporary disconnections retain the queue. UIDVALIDITY checks prevent writes from targeting a different message after the server rebuilds a mailbox. - Explorer and inbox unread counts come from server message counts, so they cover older, unloaded pages too. Pending local changes update those counts immediately. -- Mail is fetched with **BODY.PEEK**. Background downloads and previews do not mark messages read. HTML is converted to readable terminal text; scripts, styles, remote images, and tracking pixels are not loaded. Attachments are listed by name. +- Mail is fetched with **BODY.PEEK**. Background downloads and previews do not mark messages read. HTML is converted to readable terminal text; scripts and styles are not executed. Embedded and attached image previews load when you open a conversation; remote images follow your reading preference. Other attachments are listed by name. + +### Images + +Embedded CID images, data images, and image attachments load inline when you open a conversation. Remote images are blocked by default. The first time you encounter them, a notice above the message offers a distinct **Always show images** button. Click the button, or press **I** / **`:images`**, to load images and remember the choice for all accounts and future launches. The button stays visible as you scroll until you enable images; the explanation and surrounding text are not click targets. + +Press **S** or **`:settings`** to open reading settings. **Space/Enter** toggles **Always show remote images**; **h/l** turns it off/on, and **Esc** returns. Turning it off cancels pending image loads and hides remote previews, including cached ones. Image hosts can see when you open mail after enabling it. Known hidden and tracking-sized HTML images are skipped. + +PNG, JPEG, GIF (first frame), and WebP are supported. Previews use terminal colour cells and resize with the reader; a truecolor terminal is recommended. + +To try both image flows locally, run `./hane demo --no-splash`: + +1. Open the first conversation to see an embedded image load automatically. +2. Go back and open **A few photos from the coast** in **Personal / Inbox** (the fifth conversation). +3. Click **Always show images** above the message. The sample photo appears inline. +4. Press **S**, turn the setting off with **h**, and press **Esc**. The photo is hidden and the button returns. + +The demo uses local pictures and never contacts an image host. It starts with remote-image samples hidden each time; changes to demo settings last only for that session and do not affect your mailbox preferences. + +Only public HTTP(S) sources are fetched, with DNS validation on every connection and redirect. Local/private-network sources, active formats such as SVG, and oversized images are refused. + +Previews are cached in memory for the current session. Offline mode displays already loaded previews and embedded data images without fetching remote or attached images. Conversations preview up to 32 images, with an 8 MiB limit per image, a 32 MiB download budget, and a 45-second loading timeout. Failed images do not retry automatically; **I** retries while enabling the saved remote-image preference. Advanced commands **`:loadimages`** and **`:hideimages`** show/retry or hide only the current conversation without changing the saved preference. Normal navigation and scrolling continue while images load. Older cached messages discover image metadata on the next sync, which fetches text and MIME metadata only. + +The preference is stored privately in `preferences.json` in Hane's existing config directory (`~/.config/sorakyaku` on Linux, `~/Library/Application Support/sorakyaku` on macOS). Rendered previews are kept in memory. ![Live mailbox layout using fictional preview data](live-mail.png) @@ -83,6 +106,8 @@ SMTP acceptance confirms submission to the server, not final delivery to the rec | `L` / `:older` | Fetch 100 older messages in the folder | | `/` | Search downloaded mail; Esc clears | | `u`; `s` | Toggle unread; toggle starred | +| `I` / `:images` | Always show remote images; retry failed previews | +| `S` / `:settings` | Reading settings, including remote images on/off | | `dd` / Delete / `:delete` | Confirm move to Trash, or delete a saved local draft | | `Q` / `:queue` | Open pending Trash moves and their status | | `r`; `c` / `:new` | Reply/resume draft; new message | @@ -136,7 +161,7 @@ Corrupt or unsupported mail storage is preserved and blocks startup instead of b ## Current limits -- Plain-text replies and new messages; no attachment downloads/uploads, HTML composition, Bcc, OAuth, permanent deletion, or general folder moves yet. +- Plain-text replies and new messages; image attachments can be previewed, but general attachment downloads/uploads, HTML composition, Bcc, OAuth, permanent deletion, and general folder moves are not available yet. - Drafts are local to this device. The server Drafts folder can be read, but server draft editing/upload is not implemented. - Search covers downloaded mail. Load older pages with L to expand it. - Message text downloads are limited to 1 MiB of encoded input shared across up to 16 text parts, and 2 MiB of decoded text. The reader labels truncated text. Very large or deeply malformed conversations stop at 500 referenced IDs / 12 lookup rounds with an incomplete-thread notice. diff --git a/go.mod b/go.mod index a2307f5..0396621 100644 --- a/go.mod +++ b/go.mod @@ -12,6 +12,7 @@ require ( github.com/godbus/dbus/v5 v5.2.2 github.com/gofrs/flock v0.13.1 github.com/zalando/go-keyring v0.2.8 + golang.org/x/image v0.46.0 golang.org/x/net v0.59.0 golang.org/x/term v0.46.0 ) diff --git a/go.sum b/go.sum index b03f748..a51f910 100644 --- a/go.sum +++ b/go.sum @@ -61,6 +61,8 @@ golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACk golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI= golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo= +golang.org/x/image v0.46.0 h1:b1+oYj0Jbp6K5MDT4i4/eZpYlk3V8SJhhDKh6LBHAyQ= +golang.org/x/image v0.46.0/go.mod h1:3B3W05VGVQyuXucLINLjXKrqISASfi4Xj+iCVkLMwew= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= diff --git a/internal/app/image_content.go b/internal/app/image_content.go new file mode 100644 index 0000000..28d8687 --- /dev/null +++ b/internal/app/image_content.go @@ -0,0 +1,281 @@ +package app + +import ( + "crypto/sha256" + "fmt" + "net/url" + "strconv" + "strings" + + "github.com/dmillzilla/hane/internal/mailimage" + "github.com/emersion/go-imap" + "golang.org/x/net/html" +) + +const maxMessageImages = 32 + +// Only image references are persisted with mail. Downloaded pixels stay in the +// bounded session cache and cannot be fetched by the text renderer itself. +type messageImage struct { + ID, Name, Source, MIMEType, Encoding, CID string + Part []int + Size uint32 + Attachment bool +} + +type messageImages struct { + Text string + Images []messageImage + Ref mailRef +} + +func (i messageImage) token() string { return "[[hane-image:" + i.ID + "]]" } + +func imageID(source string) string { + sum := sha256.Sum256([]byte(source)) + return fmt.Sprintf("%x", sum[:8]) +} + +func imageName(s string) string { + s = strings.Join(strings.Fields(safeMailText(s)), " ") + r := []rune(s) + if len(r) > 80 { + s = string(r[:80]) + "…" + } + if s == "" { + return "Image" + } + return s +} + +func supportedImage(kind string) bool { + switch strings.ToLower(kind) { + case "image/png", "image/jpeg", "image/jpg", "image/gif", "image/webp": + return true + } + return false +} + +// imageMIMEParts also finds an HTML alternative even when the default reader +// prefers plain text. Walking is bounded independently of sender MIME nesting. +func imageMIMEParts(bs *imap.BodyStructure) ([]messageImage, *textPart) { + var images []messageImage + var htmlPart *textPart + visited := 0 + var walk func(*imap.BodyStructure, []int, int) + walk = func(p *imap.BodyStructure, path []int, depth int) { + if p == nil || depth > 24 || visited >= 256 { + return + } + visited++ + attached := strings.EqualFold(p.Disposition, "attachment") + if strings.EqualFold(p.MIMEType, "multipart") { + if attached { + return + } + for j, child := range p.Parts { + walk(child, append(append([]int(nil), path...), j+1), depth+1) + } + return + } + if len(path) == 0 { + path = []int{1} + } + kind := strings.ToLower(p.MIMEType + "/" + p.MIMESubType) + if kind == "text/html" && !attached && htmlPart == nil { + htmlPart = &textPart{Path: path, Type: kind, Encoding: p.Encoding, Params: p.Params, Size: p.Size} + } + if !supportedImage(kind) || len(images) >= maxMessageImages { + return + } + name := p.DispositionParams["filename"] + if name == "" { + name = p.Params["name"] + } + if name == "" { + name = kind + } + images = append(images, messageImage{ + ID: imageID(fmt.Sprint(path)), Name: imageName(name), Part: path, + MIMEType: kind, Encoding: p.Encoding, Size: p.Size, + CID: strings.Trim(strings.TrimSpace(p.Id), "<>"), Attachment: attached, + }) + } + walk(bs, nil, 0) + return images, htmlPart +} + +func imageHidden(n *html.Node) bool { + for _, a := range n.Attr { + value := strings.ToLower(strings.Join(strings.Fields(a.Val), "")) + switch a.Key { + case "hidden": + return true + case "aria-hidden": + if value == "true" { + return true + } + case "style": + for _, declaration := range strings.Split(value, ";") { + property, setting, _ := strings.Cut(declaration, ":") + setting = strings.TrimSuffix(setting, "!important") + if property == "display" && setting == "none" || property == "visibility" && setting == "hidden" { + return true + } + if property == "opacity" { + if opacity, err := strconv.ParseFloat(setting, 64); err == nil && opacity == 0 { + return true + } + } + if n.Data == "img" && (property == "width" || property == "height") { + if pixels, err := strconv.ParseFloat(strings.TrimSuffix(setting, "px"), 64); err == nil && pixels >= 0 && pixels <= 2 { + return true + } + } + } + case "width", "height": + if n.Data == "img" { + pixels, err := strconv.Atoi(strings.TrimSuffix(value, "px")) + if err == nil && pixels >= 0 && pixels <= 2 { + return true + } + } + } + } + return false +} + +func htmlImages(source string, parts []messageImage) (string, []messageImage) { + root, err := html.Parse(strings.NewReader(source)) + if err != nil { + return "", nil + } + cids := map[string]messageImage{} + for _, part := range parts { + if part.CID != "" { + cids[part.CID] = part + } + } + var text strings.Builder + var images []messageImage + seen := map[string]bool{} + var walk func(*html.Node, int) + walk = func(n *html.Node, depth int) { + if depth > 128 { + return + } + if n.Type == html.ElementNode { + if imageHidden(n) { + return + } + switch n.Data { + case "script", "style", "head", "svg", "noscript", "iframe", "object", "embed": + return + case "p", "div", "br", "tr", "li", "blockquote", "h1", "h2", "h3": + text.WriteByte('\n') + case "img": + if len(images) >= maxMessageImages { + return + } + var src, alt string + for _, a := range n.Attr { + if a.Key == "src" { + src = strings.TrimSpace(a.Val) + if strings.HasPrefix(src, "//") { + src = "https:" + src + } + } else if a.Key == "alt" { + alt = imageName(a.Val) + } + } + img := messageImage{ID: imageID(src), Name: imageName(alt), Source: src} + switch { + case strings.HasPrefix(strings.ToLower(src), "cid:"): + cid, _ := url.PathUnescape(src[4:]) + part, ok := cids[strings.Trim(cid, "<>")] + if !ok { + return + } + img = part + if alt != "" { + img.Name = alt + } + case mailimage.PublicURL(src): + case strings.HasPrefix(strings.ToLower(src), "data:image/"): + if _, _, err := mailimage.Data(src); err != nil { + return + } + default: + return + } + if !seen[img.ID] { + images = append(images, img) + seen[img.ID] = true + } + text.WriteString("\n" + img.token() + "\n") + return + } + } + if n.Type == html.TextNode { + text.WriteString(n.Data) + } + for child := n.FirstChild; child != nil; child = child.NextSibling { + walk(child, depth+1) + } + if n.Type == html.ElementNode && n.Data == "a" { + for _, a := range n.Attr { + if a.Key == "href" && (strings.HasPrefix(a.Val, "https://") || strings.HasPrefix(a.Val, "http://")) { + text.WriteString(" (" + a.Val + ")") + } + } + } + } + walk(root, 0) + var lines []string + for _, line := range strings.Split(safeMailText(text.String()), "\n") { + if line = strings.Join(strings.Fields(line), " "); line != "" { + lines = append(lines, line) + } + } + return strings.Join(lines, "\n"), images +} + +func indexMailImages(r *remoteMail, parts []messageImage, htmlSource string) { + r.Images, r.ImageBody = nil, "" + seen := map[string]bool{} + if htmlSource != "" { + body, images := htmlImages(htmlSource, parts) + if len(images) > 0 { + r.Images, r.ImageBody = images, body + for _, img := range images { + seen[img.ID] = true + } + } + } + for _, img := range parts { + // A hidden/unreferenced inline CID image must not reappear as an + // attachment preview. Explicit attachments remain available to load. + if seen[img.ID] || len(r.Images) >= maxMessageImages || (htmlSource != "" && img.CID != "" && !img.Attachment) { + continue + } + if r.ImageBody == "" { + r.ImageBody = r.Body + } + r.Images = append(r.Images, img) + r.ImageBody += "\n" + img.token() + } + if r.ImageBody != "" && htmlSource != "" && len(r.Attachments) > 0 { + r.ImageBody += "\n\nAttachments: " + strings.Join(r.Attachments, ", ") + } + if len(r.ImageBody) > 2<<20 { + r.ImageBody = safeMailText(r.ImageBody[:2<<20]) + "\n[Image view text truncated at 2 MiB.]" + } + visible := r.Images[:0] + for _, img := range r.Images { + if strings.Contains(r.ImageBody, img.token()) { + visible = append(visible, img) + } + } + r.Images = visible + r.ImagesIndexed = true +} diff --git a/internal/app/image_content_test.go b/internal/app/image_content_test.go new file mode 100644 index 0000000..8b728fd --- /dev/null +++ b/internal/app/image_content_test.go @@ -0,0 +1,80 @@ +package app + +import ( + "strings" + "testing" + + "github.com/emersion/go-imap" +) + +func TestHTMLImagePositionsCIDAndTrackingFilters(t *testing.T) { + part := messageImage{ID: imageID("cid-part"), CID: "postcard@example.com", Name: "postcard.png", Part: []int{2}, MIMEType: "image/png"} + source := `

Before photo

Postcard

After photo

+Remote photo + +
+ + + +` + body, images := htmlImages(source, []messageImage{part}) + if len(images) != 2 || images[0].Source != "" || len(images[0].Part) != 1 || images[1].Source != "https://images.example/photo.png" { + t.Fatalf("unexpected image metadata: %+v", images) + } + before, photo, after := strings.Index(body, "Before photo"), strings.Index(body, images[0].token()), strings.Index(body, "After photo") + if before < 0 || photo <= before || after <= photo { + t.Fatalf("image position was lost: %q", body) + } + for _, forbidden := range []string{"pixel", "hidden", "transparent", "private", "passwd", "script"} { + if strings.Contains(body, forbidden) { + t.Fatalf("hidden/unsafe content retained: %q", body) + } + } +} + +func TestImageMIMEStructureAndAttachmentFallback(t *testing.T) { + bs := &imap.BodyStructure{MIMEType: "multipart", MIMESubType: "related", Parts: []*imap.BodyStructure{ + {MIMEType: "multipart", MIMESubType: "alternative", Parts: []*imap.BodyStructure{ + {MIMEType: "text", MIMESubType: "plain"}, + {MIMEType: "text", MIMESubType: "html", Encoding: "quoted-printable"}, + }}, + {MIMEType: "image", MIMESubType: "png", Id: "", Encoding: "base64"}, + {MIMEType: "image", MIMESubType: "jpeg", Disposition: "attachment", DispositionParams: map[string]string{"filename": "photo.jpg"}}, + {MIMEType: "image", MIMESubType: "svg+xml", Disposition: "attachment"}, + }} + parts, html := imageMIMEParts(bs) + if html == nil || len(html.Path) != 2 || html.Path[0] != 1 || html.Path[1] != 2 || len(parts) != 2 { + t.Fatalf("MIME indexing failed: %+v, %+v", parts, html) + } + r := remoteMail{Body: "Plain body", Attachments: []string{"photo.jpg"}} + indexMailImages(&r, parts, `

HTML body

`) + if !r.ImagesIndexed || len(r.Images) != 1 || r.Images[0].Name != "photo.jpg" || !strings.Contains(r.ImageBody, "Plain body") || !strings.Contains(r.ImageBody, r.Images[0].token()) { + t.Fatalf("hidden CID reappeared or attachment was lost: %+v", r) + } +} + +func TestImageLabelsAreSanitizedAndSourcesDeduplicated(t *testing.T) { + body, images := htmlImages(`hello world`, nil) + if len(images) != 1 || strings.ContainsRune(images[0].Name, '\x1b') || images[0].Source != "https://images.example/photo.png" || strings.Count(body, images[0].token()) != 2 { + t.Fatal("source deduplication or label sanitization failed") + } + var source strings.Builder + for i := 0; i < 100; i++ { + source.WriteString(``) + } + _, images = htmlImages(source.String(), nil) + if len(images) > maxMessageImages { + t.Fatal("HTML image count was not bounded") + } +} + +func TestAttachedMultipartDoesNotReplaceMainHTMLBody(t *testing.T) { + bs := &imap.BodyStructure{MIMEType: "multipart", MIMESubType: "mixed", Disposition: "attachment", Parts: []*imap.BodyStructure{ + {MIMEType: "text", MIMESubType: "html"}, + {MIMEType: "image", MIMESubType: "png"}, + }} + images, html := imageMIMEParts(bs) + if len(images) != 0 || html != nil { + t.Fatal("an attached multipart document was treated as the main mail body") + } +} diff --git a/internal/app/image_transport.go b/internal/app/image_transport.go new file mode 100644 index 0000000..d9bafab --- /dev/null +++ b/internal/app/image_transport.go @@ -0,0 +1,75 @@ +package app + +import ( + "bytes" + "context" + "errors" + "io" + "strings" + + "github.com/emersion/go-imap" + message "github.com/emersion/go-message" +) + +// Image fetches just one selected MIME part, using BODY.PEEK in a read-only +// mailbox. The source UIDVALIDITY is checked before touching any message UID. +func (b imapTransport) Image(ctx context.Context, c AccountConfig, password string, ref mailRef, part messageImage, limit int64) ([]byte, string, error) { + if len(part.Part) == 0 || len(part.Part) > 24 || !supportedImage(part.MIMEType) || ref.UID == 0 || ref.Validity == 0 || limit <= 0 { + return nil, "", errors.New("invalid image attachment reference") + } + for _, number := range part.Part { + if number < 1 { + return nil, "", errors.New("invalid image MIME path") + } + } + encodedLimit := limit*4/3 + 4096 + if int64(part.Size) > encodedLimit { + return nil, "", errors.New("image attachment exceeds the download limit") + } + im, close, err := b.connect(ctx, c, password) + if err != nil { + return nil, "", err + } + defer close() + box, err := im.Select(ref.Folder, true) + if err != nil { + return nil, "", errors.New("could not open the image's mailbox") + } + if box.UidValidity != ref.Validity { + return nil, "", errors.New("mailbox changed; sync before loading this image") + } + section := &imap.BodySectionName{BodyPartName: imap.BodyPartName{Path: part.Part}, Peek: true, Partial: []int{0, int(encodedLimit + 1)}} + ch := make(chan *imap.Message, 1) + done := make(chan error, 1) + go func() { + done <- im.UidFetch(uidSet([]uint32{ref.UID}), []imap.FetchItem{imap.FetchUid, section.FetchItem()}, ch) + }() + var encoded []byte + var readErr error + for msg := range ch { + if msg.Uid != ref.UID { + continue + } + if literal := msg.GetBody(section); literal != nil { + encoded, readErr = io.ReadAll(io.LimitReader(literal, encodedLimit+1)) + } + } + if err := <-done; err != nil || readErr != nil || len(encoded) == 0 { + return nil, "", errors.New("could not download the image attachment") + } + if int64(len(encoded)) > encodedLimit { + return nil, "", errors.New("image attachment exceeds the download limit") + } + var header message.Header + header.Set("Content-Type", part.MIMEType) + header.Set("Content-Transfer-Encoding", strings.ToLower(part.Encoding)) + entity, err := message.New(header, bytes.NewReader(encoded)) + if err != nil || entity == nil { + return nil, "", errors.New("unsupported image attachment encoding") + } + data, err := io.ReadAll(io.LimitReader(entity.Body, limit+1)) + if err != nil || int64(len(data)) > limit { + return nil, "", errors.New("image attachment is incomplete or too large") + } + return data, part.MIMEType, nil +} diff --git a/internal/app/image_transport_test.go b/internal/app/image_transport_test.go new file mode 100644 index 0000000..ea7f288 --- /dev/null +++ b/internal/app/image_transport_test.go @@ -0,0 +1,95 @@ +package app + +import ( + "bytes" + "context" + "encoding/base64" + "image" + "image/png" + "strings" + "testing" + "time" + + "github.com/dmillzilla/hane/internal/mailimage" +) + +func imagePNG(t *testing.T) []byte { + t.Helper() + var data bytes.Buffer + if err := png.Encode(&data, image.NewRGBA(image.Rect(0, 0, 16, 12))); err != nil { + t.Fatal(err) + } + return data.Bytes() +} + +func TestIMAPIndexesHTMLImagesAndFetchesCIDWithPeek(t *testing.T) { + b, c := liveIMAPFixture(t) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + imageBytes := imagePNG(t) + raw := "From: Photos \r\nTo: reader@example.com\r\nSubject: Photos\r\nMessage-ID: \r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=outer\r\n\r\n" + + "--outer\r\nContent-Type: multipart/alternative; boundary=alt\r\n\r\n" + + "--alt\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nPlain text stays available\r\n" + + "--alt\r\nContent-Type: text/html; charset=utf-8\r\n\r\n

Before photo

\"Coast\"

After photo

\"Remote\"\r\n--alt--\r\n" + + "--outer\r\nContent-Type: image/png; name=coast.png\r\nContent-ID: \r\nContent-Disposition: inline; filename=coast.png\r\nContent-Transfer-Encoding: base64\r\n\r\n" + base64.StdEncoding.EncodeToString(imageBytes) + "\r\n" + + "--outer\r\nContent-Type: image/png; name=attachment.png\r\nContent-Disposition: attachment; filename=attachment.png\r\nContent-Transfer-Encoding: base64\r\n\r\n" + base64.StdEncoding.EncodeToString(imageBytes) + "\r\n--outer--\r\n" + im, close, err := b.connect(ctx, c, "password") + if err != nil { + t.Fatal(err) + } + if err := im.Append("INBOX", nil, time.Now(), bytes.NewReader([]byte(raw))); err != nil { + close() + t.Fatal(err) + } + close() + result := b.Sync(ctx, c, "password", accountMail{}, syncRequest{Folder: "INBOX"}) + if result.Err != nil { + t.Fatal(result.Err) + } + var message remoteMail + for _, r := range result.Data.Messages { + if r.MessageID == "" { + message = r + } + } + if !message.ImagesIndexed || len(message.Images) != 3 || message.Seen || !strings.Contains(message.Body, "Plain text stays available") || strings.Contains(message.Body, "Before photo") { + t.Fatalf("plain text, image metadata, or read status was lost: %+v", message) + } + if !strings.Contains(message.ImageBody, "Before photo") || !strings.Contains(message.ImageBody, "After photo") || strings.Contains(message.ImageBody, "pixel") { + t.Fatal("HTML image placement or tracking-image suppression failed") + } + var cid messageImage + for _, img := range message.Images { + if img.CID == "coast@example.com" { + cid = img + } + } + data, kind, err := b.Image(ctx, c, "password", message.Ref, cid, mailimage.MaxBytes) + if err != nil || kind != "image/png" || !bytes.Equal(data, imageBytes) { + t.Fatalf("image MIME part did not decode: %v", err) + } + if _, err := mailimage.Decode(data, kind); err != nil { + t.Fatal(err) + } + stale := message.Ref + stale.Validity++ + if _, _, err := b.Image(ctx, c, "password", stale, cid, mailimage.MaxBytes); err == nil || !strings.Contains(err.Error(), "mailbox changed") { + t.Fatal("image fetch did not reject stale UIDVALIDITY") + } + for i := range result.Data.Messages { + if result.Data.Messages[i].MessageID == message.MessageID { + result.Data.Messages[i].ImagesIndexed = false + result.Data.Messages[i].Images = nil + result.Data.Messages[i].ImageBody = "" + } + } + refreshed := b.Sync(ctx, c, "password", result.Data, syncRequest{Folder: "INBOX"}) + if refreshed.Err != nil { + t.Fatal(refreshed.Err) + } + for _, r := range refreshed.Data.Messages { + if r.MessageID == message.MessageID && (r.Seen || !r.ImagesIndexed || len(r.Images) != 3) { + t.Fatalf("BODY.PEEK/cache refresh: seen=%v indexed=%v images=%d", r.Seen, r.ImagesIndexed, len(r.Images)) + } + } +} diff --git a/internal/app/images.go b/internal/app/images.go new file mode 100644 index 0000000..f104d18 --- /dev/null +++ b/internal/app/images.go @@ -0,0 +1,550 @@ +package app + +import ( + "context" + "errors" + "fmt" + "image" + "image/color" + "strings" + "time" + + tea "charm.land/bubbletea/v2" + "github.com/charmbracelet/x/ansi" + "github.com/dmillzilla/hane/internal/mailimage" +) + +const maxThreadImages = 32 +const imageDownloadBudget = 32 << 20 + +// This sample follows the remote-image consent policy, but the demo loader +// supplies its picture locally. Demo mode never contacts this address. +const demoRemoteImageSource = "https://images.example/hane-demo-postcard.png" + +type imageJob struct { + Key string + Image messageImage + Ref mailRef + Config AccountConfig + Password string + Demo bool + Limit int64 +} + +type imageLoader func(context.Context, imageJob) (image.Image, int64, error) +type imagePreview struct { + raster image.Image + lines map[string][]string +} +type imageState struct { + visible map[string]bool + hidden map[string]bool + loaded map[string]*imagePreview + failed map[string]string + busy map[string]bool + order []string + queue []imageJob + generation uint64 + thread string + lastThread string + remaining int64 + ctx context.Context + cancel context.CancelFunc + load imageLoader + // Tests supply a local loader; production constructs a fresh loader for + // each request, so its private credential cache belongs to one worker. + testLoader imageLoader +} +type imageLoadedMsg struct { + key string + generation uint64 + raster image.Image + used int64 + err error +} + +func newImageState() *imageState { + return &imageState{visible: map[string]bool{}, hidden: map[string]bool{}, loaded: map[string]*imagePreview{}, failed: map[string]string{}, busy: map[string]bool{}} +} + +type imagePartFetcher interface { + Image(context.Context, AccountConfig, string, mailRef, messageImage, int64) ([]byte, string, error) +} + +func newImageLoader(store credentialStore, backend mailTransport) imageLoader { + passwords := map[string]string{} + return func(ctx context.Context, job imageJob) (image.Image, int64, error) { + var data []byte + var kind string + var err error + switch { + case job.Demo && (job.Image.Source == "demo:postcard" || job.Image.Source == demoRemoteImageSource): + return demoPostcard(), 0, nil + case strings.HasPrefix(strings.ToLower(job.Image.Source), "data:"): + data, kind, err = mailimage.Data(job.Image.Source) + case job.Demo: + return nil, 0, errors.New("this image is not part of the offline demo") + case job.Image.Source != "": + data, kind, err = mailimage.Fetch(ctx, job.Image.Source, job.Limit) + case len(job.Image.Part) > 0: + fetcher, ok := backend.(imagePartFetcher) + if !ok || store == nil { + return nil, 0, errors.New("image attachment loading is unavailable") + } + key := credentialKey(job.Config) + password := job.Password + if password == "" { + password = passwords[key] + } + if password == "" { + password, err = store.Get(ctx, job.Config) + if err != nil { + return nil, 0, errors.New("unlock the local keyring to load attached images") + } + passwords[key] = password + } + data, kind, err = fetcher.Image(ctx, job.Config, password, job.Ref, job.Image, job.Limit) + default: + err = errors.New("image source is unavailable") + } + if err != nil { + return nil, job.Limit, err + } + if err := ctx.Err(); err != nil { + return nil, int64(len(data)), err + } + if int64(len(data)) > job.Limit { + return nil, int64(len(data)), errors.New("image exceeds the download limit") + } + raster, err := mailimage.Decode(data, kind) + return raster, int64(len(data)), err + } +} + +func (m model) imageThreadKey(t *Thread) string { + if t == nil { + return "" + } + return fmt.Sprintf("%s/%d/%d", m.liveKey(t.Account), t.Account, t.ID) +} + +func (m model) imageKey(t *Thread, id string, meta messageImages, img messageImage) string { + return imageID(fmt.Sprintf("%s/%s/%s/%s", m.imageThreadKey(t), id, meta.Ref.key(), img.ID)) +} + +func (m *model) cancelImages() { + if m.images == nil { + return + } + if m.images.cancel != nil { + m.images.cancel() + } + m.images.generation++ + m.images.cancel, m.images.queue, m.images.thread = nil, nil, "" + m.images.busy = map[string]bool{} +} + +func (m *model) cancelImagesIfNeeded() { + if m.images != nil && m.images.thread != "" && (!m.reading || m.imageThreadKey(m.current()) != m.images.thread) { + m.cancelImages() + } +} + +func (m *model) hideImages() { + if m.images == nil { + return + } + m.images.visible[m.imageThreadKey(m.current())] = false + m.images.hidden[m.imageThreadKey(m.current())] = true + m.cancelImages() + m.notice = "Images hidden for this conversation. I shows them again; S opens settings." + m.clampScroll() +} + +func remoteImage(img messageImage) bool { + source := strings.ToLower(img.Source) + return source != "" && !strings.HasPrefix(source, "data:") && !strings.HasPrefix(source, "demo:") +} + +func (m model) imageVisible(t *Thread, img messageImage) bool { + if m.images != nil && m.images.hidden[m.imageThreadKey(t)] { + return false + } + return !remoteImage(img) || m.preferences.RemoteImages || m.images != nil && m.images.visible[m.imageThreadKey(t)] +} + +func (m model) blockedRemoteImages() bool { + return m.blockedRemoteImageCount() > 0 +} + +func (m model) blockedRemoteImageCount() int { + t := m.current() + if t == nil || t.QueueID != "" || isDraftThread(t) { + return 0 + } + count := 0 + for _, meta := range t.ImageBodies { + for _, img := range meta.Images { + if remoteImage(img) && !m.imageVisible(t, img) { + count++ + } + } + } + return count +} + +type readerImageNotice struct { + lines []string + buttonRow int + buttonWidth int +} + +// The rendered button and its mouse target share one layout. The notice sits +// above the scrolling body, so the action stays available beside hidden images. +func (m model) imageNotice() readerImageNotice { + count := m.blockedRemoteImageCount() + if !m.reading || count == 0 { + return readerImageNotice{} + } + noun := "images" + if count == 1 { + noun = "image" + } + notice := readerImageNotice{} + compact := m.bodyHeight() < 16 + if !compact { + text := fmt.Sprintf("%d remote %s hidden. Loading can tell the sender you opened this mail.", count, noun) + for _, line := range strings.Split(ansi.Wrap(text, m.readerWidth(), ""), "\n") { + notice.lines = append(notice.lines, styled(line, muted)) + } + } + const button = "[ Always show images ]" + notice.buttonRow, notice.buttonWidth = len(notice.lines), ansi.StringWidth(button) + notice.lines = append(notice.lines, imageNoticeButton(button)+styled(" click or press I", muted)) + if compact { + caption := "All mail · senders may see opens · S off" + if m.demo { + caption = "Demo · no network · S to turn off" + } + notice.lines = append(notice.lines, styled(caption, muted)) + } else { + caption := "All mail · remembered · S to turn off" + if m.demo { + caption = "Demo · no network · session only · S off" + } + notice.lines = append(notice.lines, styled(caption, muted), "") + } + return notice +} + +func (m model) imageNoticeLines() []string { + return m.imageNotice().lines +} + +func (m model) imageNoticeClicked(x, y int) bool { + tw, lw, rw := m.layout() + if m.width < 48 || m.height < 16 || rw == 0 || m.loading || m.help || m.compose != nil || m.settingsOpen || m.setup != nil || m.quitOpen || m.deletion != nil { + return false + } + notice := m.imageNotice() + left := tw + lw + 2 // pane margin, then the reader's content indent + return notice.buttonWidth > 0 && x >= left && x < left+notice.buttonWidth && y == 7+notice.buttonRow +} + +// This is a persistent app-wide choice, made by the reader notice or I. Merely +// opening mail never changes the remote image preference. +func (m *model) alwaysShowImages() tea.Cmd { + if err := m.setRemoteImages(true); err != nil { + m.notice = err.Error() + return nil + } + if m.images == nil { + m.images = newImageState() + } + delete(m.images.hidden, m.imageThreadKey(m.current())) + if !m.reading { + m.openThread() + } + m.cancelImages() + m.notice = "Remote images will always show. S opens reading settings." + if m.demo { + m.notice = "Demo images will show for this session. S opens reading settings." + } + return m.queueImages(true) +} + +func (m *model) loadImages() tea.Cmd { + t := m.current() + if t == nil || t.QueueID != "" || isDraftThread(t) { + m.notice = "Open a conversation to load images." + return nil + } + if !m.reading { + m.openThread() + } + if m.images == nil { + m.images = newImageState() + } + m.cancelImages() + state := m.images + thread := m.imageThreadKey(t) + state.visible[thread] = true + delete(state.hidden, thread) + return m.queueImages(true) +} + +func (m *model) automaticImages() tea.Cmd { + if !m.reading || m.loading || m.compose != nil || m.help || m.settingsOpen || m.setup != nil || m.quitOpen || m.deletion != nil { + return nil + } + return m.queueImages(false) +} + +// Local images load as a conversation opens. Remote images join the same queue +// only after an explicit saved preference (or the one-conversation command). +func (m *model) queueImages(retry bool) tea.Cmd { + t := m.current() + if t == nil || t.QueueID != "" || isDraftThread(t) { + return nil + } + if m.images == nil { + m.images = newImageState() + } + state := m.images + if state.thread != "" { + return nil + } + thread := m.imageThreadKey(t) + if state.lastThread != thread { + if len(state.failed) >= 128 { + state.failed = map[string]string{} + } + state.lastThread = thread + } + var jobs []imageJob + seen := map[string]bool{} + total := 0 + for _, msg := range t.Messages { + id := msg.ID + meta := t.ImageBodies[id] + for _, img := range meta.Images { + if !m.imageVisible(t, img) { + continue + } + key := m.imageKey(t, id, meta, img) + if seen[key] { + continue + } + seen[key] = true + total++ + if state.loaded[key] != nil || !retry && state.failed[key] != "" { + continue + } + if total > maxThreadImages { + state.failed[key] = "Conversation preview limit reached" + continue + } + if len(img.Part) > 0 && int64(img.Size) > mailimage.MaxBytes*4/3+4096 { + state.failed[key] = "Image exceeds the 8 MiB preview limit" + continue + } + if m.live != nil && m.live.offline && !strings.HasPrefix(strings.ToLower(img.Source), "data:") { + state.failed[key] = "Offline: reconnect to load this image" + continue + } + job := imageJob{Key: key, Image: img, Ref: meta.Ref, Demo: !t.Remote} + if m.realAccount(t.Account) && len(img.Part) > 0 { + job.Config = *m.accounts[t.Account].Config + job.Password = m.live.passwords[m.liveKey(t.Account)] + } + delete(state.failed, key) + state.busy[key] = true + jobs = append(jobs, job) + } + } + if total == 0 { + if retry { + m.notice = "No displayable images in this conversation. Older cached mail may need R to refresh." + } + return nil + } + if len(jobs) == 0 { + return nil + } + parent := m.background + if parent == nil { + parent = context.Background() + } + state.ctx, state.cancel = context.WithTimeout(parent, 45*time.Second) + state.queue, state.thread, state.remaining = jobs, thread, imageDownloadBudget + var backend mailTransport + if m.live != nil { + backend = m.live.backend + } + state.load = state.testLoader + if state.load == nil { + state.load = newImageLoader(m.credentials, backend) + } + m.notice = fmt.Sprintf("Loading %d image(s) · S reading settings", len(jobs)) + return m.nextImage() +} + +func (m *model) nextImage() tea.Cmd { + s := m.images + if s == nil || len(s.queue) == 0 { + return nil + } + if s.remaining <= 0 || s.ctx.Err() != nil { + for _, job := range s.queue { + s.failed[job.Key] = "Image loading limit reached; I retries" + delete(s.busy, job.Key) + } + m.cancelImages() + m.notice = "Image loading stopped at its time or download limit." + return nil + } + job := s.queue[0] + s.queue = s.queue[1:] + job.Limit = min(s.remaining, mailimage.MaxBytes) + ctx, load, generation := s.ctx, s.load, s.generation + return func() tea.Msg { + raster, used, err := load(ctx, job) + return imageLoadedMsg{key: job.Key, generation: generation, raster: raster, used: used, err: err} + } +} + +func (m model) finishImage(msg imageLoadedMsg) (tea.Model, tea.Cmd) { + s := m.images + if s == nil || msg.generation != s.generation || !s.busy[msg.key] { + return m, nil + } + delete(s.busy, msg.key) + s.remaining -= max(0, msg.used) + if msg.err != nil || msg.raster == nil { + text := "Image could not be loaded" + if msg.err != nil { + text = imageName(msg.err.Error()) + } + s.failed[msg.key] = text + } else { + if len(s.order) >= 32 { + delete(s.loaded, s.order[0]) + s.order = s.order[1:] + } + s.loaded[msg.key] = &imagePreview{raster: msg.raster, lines: map[string][]string{}} + s.order = append(s.order, msg.key) + } + if len(s.queue) > 0 { + m.notice = fmt.Sprintf("Loading images · %d remaining", len(s.queue)) + cmd := m.nextImage() + return m, cmd + } + if s.cancel != nil { + s.cancel() + } + s.cancel, s.thread = nil, "" + m.notice = "Images loaded where available · I retries · S reading settings" + m.clampScroll() + return m, nil +} + +func (m model) imageBodyLines(t *Thread, index int, msg Message, width int) []string { + var meta messageImages + id := msg.ID + meta = t.ImageBodies[id] + text := msg.Body + if len(meta.Images) > 0 && meta.Text != "" { + text = meta.Text + } + byToken := map[string]messageImage{} + for _, img := range meta.Images { + byToken[img.token()] = img + } + var out []string + for _, line := range strings.Split(text, "\n") { + if img, ok := byToken[line]; ok { + key := m.imageKey(t, id, meta, img) + label := "[Image: " + imageName(img.Name) + "]" + if m.images != nil && m.imageVisible(t, img) { + if preview := m.images.loaded[key]; preview != nil { + out = append(out, styled(ansi.Truncate("[Image: "+imageName(img.Name)+"]", width, "…"), muted)) + rows := max(4, min(24, m.height-14)) + variant := fmt.Sprintf("%d/%d", width, rows) + lines, ok := preview.lines[variant] + if !ok { + if len(preview.lines) >= 4 { + preview.lines = map[string][]string{} + } + lines = mailimage.Lines(preview.raster, width, rows, violetPane) + preview.lines[variant] = lines + } + out = append(out, lines...) + continue + } else if m.images.busy[key] { + label = "[Image: " + imageName(img.Name) + " · loading…]" + } else if failure := m.images.failed[key]; failure != "" { + label = "[Image: " + imageName(img.Name) + " · " + failure + "]" + } + } + for _, wrapped := range strings.Split(ansi.Wrap(label, width, ""), "\n") { + out = append(out, styled(wrapped, muted)) + } + continue + } + for _, wrapped := range strings.Split(ansi.Wrap(line, width, ""), "\n") { + out = append(out, styled(wrapped, readerText)) + } + } + return out +} + +func demoPostcard() image.Image { + img := image.NewRGBA(image.Rect(0, 0, 96, 54)) + for y := 0; y < 54; y++ { + for x := 0; x < 96; x++ { + c := color.RGBA{uint8(60 + y*2), uint8(120 + y), uint8(200 - y), 255} + if (x-68)*(x-68)+(y-15)*(y-15) < 64 { + c = color.RGBA{255, 214, 134, 255} + } + if y > 31-abs(x-22)/2 && x < 65 { + c = color.RGBA{44, 76, 106, 255} + } + if y > 35 { + c = color.RGBA{uint8(20 + y/2), uint8(110 + y), uint8(160 + (x+y)%12), 255} + } + img.SetRGBA(x, y, c) + } + } + return img +} + +func addDemoImage(threads []Thread) { + embedded := false + for i := range threads { + t := &threads[i] + if t.Account != 0 || t.Folder != "Inbox" || len(t.Messages) == 0 { + continue + } + if t.Subject == "A few photos from the coast" { + img := messageImage{ID: imageID(demoRemoteImageSource), Source: demoRemoteImageSource, Name: "A photo from the coast (demo)"} + t.Messages[0].ID = "demo-remote-postcard" + intro := "Try the image button above this message. This photo behaves like a remote image, but the demo works without a network connection.\n\n" + t.ImageBodies = map[string]messageImages{"demo-remote-postcard": {Text: intro + img.token() + "\n\n" + t.Messages[0].Body, Images: []messageImage{img}}} + continue + } + if embedded { + continue + } + img := messageImage{ID: imageID("demo:postcard"), Source: "demo:postcard", Name: "A postcard from the coast"} + t.Messages[0].ID = "demo-postcard" + t.ImageBodies = map[string]messageImages{"demo-postcard": {Text: img.token() + "\n" + t.Messages[0].Body, Images: []messageImage{img}}} + embedded = true + } +} + +func abs(n int) int { + if n < 0 { + return -n + } + return n +} diff --git a/internal/app/images_test.go b/internal/app/images_test.go new file mode 100644 index 0000000..e471313 --- /dev/null +++ b/internal/app/images_test.go @@ -0,0 +1,447 @@ +package app + +import ( + "context" + "encoding/base64" + "errors" + "fmt" + "image" + "path/filepath" + "strings" + "testing" + "time" + + tea "charm.land/bubbletea/v2" + "github.com/charmbracelet/x/ansi" + "github.com/dmillzilla/hane/internal/mailimage" +) + +func imageModel(t *testing.T) model { + t.Helper() + m := newModel(time.Now()) + m.openThread() + return m +} + +func runImageKey(m model) (model, tea.Cmd) { + next, cmd := m.Update(tea.KeyPressMsg{Code: 'I', Text: "I"}) + return next.(model), cmd +} + +func remoteImageModel(t *testing.T) model { + m := imageModel(t) + target := m.current() + for id, meta := range target.ImageBodies { + for i := range meta.Images { + meta.Images[i].Source = "https://images.example/photo.png" + } + target.ImageBodies[id] = meta + } + return m +} + +func TestRemoteImagesAskOnceAndStayInline(t *testing.T) { + m := remoteImageModel(t) + calls := 0 + m.images.testLoader = func(context.Context, imageJob) (image.Image, int64, error) { + calls++ + return demoPostcard(), 100, nil + } + next, cmd := m.Update(tea.WindowSizeMsg{Width: 120, Height: 36}) + m = next.(model) + before := ansi.Strip(m.View().Content) + if cmd != nil || calls != 0 || strings.Count(before, "Always show") != 1 || strings.Contains(before, "▀") { + t.Fatal("opening mail fetched remote images without consent or repeated the notice") + } + m, cmd = runImageKey(m) + if cmd == nil || !m.preferences.RemoteImages || !strings.Contains(m.notice, "Loading") || calls != 0 { + t.Fatal("load action did not schedule the preview separately from rendering") + } + next, cmd = m.Update(cmd()) + m = next.(model) + loaded := strings.Join(m.readerLines(), "\n") + if cmd != nil || calls != 1 || !strings.Contains(loaded, "▀") || strings.Contains(loaded, "[[hane-image:") || strings.Contains(m.View().Content, "Always show images") { + t.Fatal("loaded image did not render inline") + } + m = press(m, "Sh") // turn the saved preference off in Settings + if strings.Contains(strings.Join(m.readerLines(), "\n"), "▀") { + t.Fatal("turning off remote images kept the cached preview visible") + } + m = special(m, tea.KeyEscape) + m, cmd = runImageKey(m) + if cmd != nil || calls != 1 || !strings.Contains(strings.Join(m.readerLines(), "\n"), "▀") { + t.Fatal("showing a cached image fetched it again") + } +} + +func TestImageLoadingCancellationAndStaleResults(t *testing.T) { + m := remoteImageModel(t) + m.images.testLoader = func(context.Context, imageJob) (image.Image, int64, error) { return demoPostcard(), 100, nil } + m, cmd := runImageKey(m) + result := cmd() + m = press(m, "Sh") // disable remote images before the completion is delivered + next, nextCmd := m.Update(result) + m = next.(model) + if nextCmd != nil || len(m.images.loaded) != 0 || strings.Contains(strings.Join(m.readerLines(), "\n"), "▀") { + t.Fatal("a stale image completion reopened a hidden preview") + } + m = special(m, tea.KeyEscape) + m, cmd = runImageKey(m) + result = cmd() + m = press(m, "h") + next, _ = m.Update(result) + m = next.(model) + if m.reading || len(m.images.loaded) != 0 { + t.Fatal("leaving the conversation accepted a stale image") + } +} + +func TestImageFailureIsInlineAndDoesNotReplaceMessageText(t *testing.T) { + m := imageModel(t) + m.images.testLoader = func(context.Context, imageJob) (image.Image, int64, error) { + return nil, 0, errors.New("Image host unavailable") + } + before := m.current().newest().Body + m, cmd := runImageKey(m) + next, again := m.Update(cmd()) + m = next.(model) + if again != nil || m.current().newest().Body != before || !strings.Contains(ansi.Strip(strings.Join(m.readerLines(), "\n")), "Image host unavailable") { + t.Fatal("image failure damaged the body or was not shown inline") + } + next, again = m.Update(tea.WindowSizeMsg{Width: 100, Height: 30}) + if again != nil { + t.Fatal("a failed image retried on a redraw") + } +} + +func TestLoadedImageViewsFitResizedTerminals(t *testing.T) { + m := imageModel(t) + m, cmd := runImageKey(m) + next, _ := m.Update(cmd()) + m = next.(model) + for _, size := range [][2]int{{160, 44}, {120, 36}, {90, 24}, {48, 16}} { + next, _ := m.Update(tea.WindowSizeMsg{Width: size[0], Height: size[1]}) + m = next.(model) + lines := strings.Split(m.View().Content, "\n") + if len(lines) != size[1] { + t.Fatal("image view exceeded terminal height") + } + for _, line := range lines { + if ansi.StringWidth(line) != size[0] { + t.Fatal("image view exceeded terminal width") + } + } + } +} + +func TestMessageImageIdentitySurvivesReordering(t *testing.T) { + m := imageModel(t) + target := m.current() + img := target.ImageBodies[target.Messages[0].ID] + if len(img.Images) == 0 { + t.Fatal("missing demo image") + } + target.Messages = append([]Message{{Sender: "New reply", Address: "friend@example.com", Body: "A newer reply without an image", Received: time.Now().Add(time.Hour), ID: "new-id"}}, target.Messages...) + first := m.imageBodyLines(target, 0, target.Messages[0], 60) + second := m.imageBodyLines(target, 1, target.Messages[1], 60) + if strings.Contains(strings.Join(first, "\n"), "Image:") || !strings.Contains(strings.Join(second, "\n"), "Image:") { + t.Fatal("an image was associated with a different message after reordering") + } +} + +func TestOfflineModeDoesNotScheduleRemoteOrAttachedImages(t *testing.T) { + m := liveTestModel(t) + m.live.offline = true + key := m.liveKey(0) + a := m.live.disk.Accounts[key] + remote := messageImage{ID: "remote", Name: "Remote", Source: "https://images.example/photo.png"} + attachment := messageImage{ID: "attached", Name: "Attached", Part: []int{2}, MIMEType: "image/png"} + a.Messages[0].Images = []messageImage{remote, attachment} + a.Messages[0].ImageBody = remote.token() + "\n" + attachment.token() + m.live.disk.Accounts[key] = a + m.rebuildLive() + m.openThread() + calls := 0 + m.images.testLoader = func(context.Context, imageJob) (image.Image, int64, error) { + calls++ + return nil, 0, errors.New("must not load") + } + m, cmd := runImageKey(m) + if cmd != nil || calls != 0 || !strings.Contains(ansi.Strip(strings.Join(m.readerLines(), "\n")), "Offline") { + t.Fatal("offline image loading scheduled a remote or IMAP fetch") + } +} + +func TestEmbeddedImagesCanLoadOffline(t *testing.T) { + m := liveTestModel(t) + m.live.offline = true + key := m.liveKey(0) + a := m.live.disk.Accounts[key] + data := imagePNG(t) + img := messageImage{ID: "embedded", Name: "Embedded", Source: "data:image/png;base64," + base64.StdEncoding.EncodeToString(data)} + a.Messages[0].Images, a.Messages[0].ImageBody = []messageImage{img}, img.token() + m.live.disk.Accounts[key] = a + m.rebuildLive() + m.openThread() + next, cmd := m.Update(tea.WindowSizeMsg{Width: 120, Height: 36}) + m = next.(model) + if cmd == nil { + t.Fatal("offline embedded image did not schedule local decoding") + } + next, _ = m.Update(cmd()) + m = next.(model) + if !strings.Contains(strings.Join(m.readerLines(), "\n"), "▀") { + t.Fatal("embedded image was not displayed offline") + } +} + +func TestEmbeddedImageLoadsOnOpeningWithoutEnablingRemoteImages(t *testing.T) { + m := newModel(time.Now()) + next, cmd := m.Update(tea.KeyPressMsg{Code: tea.KeyEnter}) + m = next.(model) + if cmd == nil || m.preferences.RemoteImages { + t.Fatal("opening embedded image did not schedule it independently of the remote preference") + } + next, cmd = m.Update(cmd()) + m = next.(model) + if cmd != nil || !strings.Contains(strings.Join(m.readerLines(), "\n"), "▀") || m.preferences.RemoteImages { + t.Fatal("embedded preview was not loaded automatically") + } +} + +func TestDemoRemoteImageCanBeClickedAndHiddenWithoutNetwork(t *testing.T) { + m := newModel(time.Now()) + m.demo = true + found := false + for i, thread := range m.folderThreads() { + if thread.Subject == "A few photos from the coast" { + m.selected, found = i, true + break + } + } + if !found { + t.Fatal("missing image-button demo conversation") + } + next, cmd := m.Update(tea.KeyPressMsg{Code: tea.KeyEnter}) + m = next.(model) + if cmd != nil || !m.blockedRemoteImages() || strings.Contains(strings.Join(m.readerLines(), "\n"), "▀") { + t.Fatal("demo remote sample did not start behind the consent action") + } + x, y := imageButtonPosition(t, m) + next, cmd = m.Update(tea.MouseClickMsg{Button: tea.MouseLeft, X: x + 4, Y: y}) + m = next.(model) + if cmd == nil || !m.preferences.RemoteImages || m.preferencesPath != "" { + t.Fatal("demo click did not schedule a session-only preview") + } + // Use the real loader, with no credentials, backend, or injected image data. + next, again := m.Update(cmd()) + m = next.(model) + if again != nil || !strings.Contains(strings.Join(m.readerLines(), "\n"), "▀") || m.blockedRemoteImages() { + t.Fatal("demo click failed to display its local picture") + } + m = special(press(m, "Sh"), tea.KeyEscape) + if !m.blockedRemoteImages() || strings.Contains(strings.Join(m.readerLines(), "\n"), "▀") { + t.Fatal("turning demo images off did not restore the button") + } + imageButtonPosition(t, m) +} + +func TestDemoLoaderRejectsNetworkAndMailboxRequests(t *testing.T) { + load := newImageLoader(nil, nil) + for _, img := range []messageImage{ + {Source: "https://images.example/not-a-demo-image.png"}, + {Part: []int{2}, MIMEType: "image/png"}, + } { + raster, _, err := load(context.Background(), imageJob{Demo: true, Image: img, Limit: mailimage.MaxBytes}) + if raster != nil || err == nil || err.Error() != "this image is not part of the offline demo" { + t.Fatal("demo job reached the HTTP or IMAP loading path") + } + } +} + +func TestRememberedChoiceLoadsOtherConversations(t *testing.T) { + m := remoteImageModel(t) + first := *m.current() + second := first + second.ID++ + second.Subject = "A different conversation" + second.Messages = append([]Message(nil), first.Messages...) + second.Messages[0].Received = first.newest().Received.Add(-time.Second) + m.threads = []Thread{first, second} + calls := 0 + m.images.testLoader = func(context.Context, imageJob) (image.Image, int64, error) { + calls++ + return demoPostcard(), 100, nil + } + m, cmd := runImageKey(m) + next, _ := m.Update(cmd()) + m = press(next.(model), "hj") + next, cmd = m.Update(tea.KeyPressMsg{Code: tea.KeyEnter}) + m = next.(model) + if cmd == nil || m.current().ID != second.ID || !m.preferences.RemoteImages || m.blockedRemoteImages() { + t.Fatal("saved choice was not applied to the next conversation") + } + next, _ = m.Update(cmd()) + if calls != 2 || !strings.Contains(strings.Join(next.(model).readerLines(), "\n"), "▀") { + t.Fatal("the next conversation required another load action") + } +} + +func imageButtonPosition(t *testing.T, m model) (int, int) { + t.Helper() + for y, line := range strings.Split(ansi.Strip(m.View().Content), "\n") { + if pos := strings.Index(line, "[ Always show images ]"); pos >= 0 { + return ansi.StringWidth(line[:pos]), y + } + } + t.Fatal("no visible image button") + return 0, 0 +} + +func TestClickingImageButtonLoadsAndRemembersAcrossLayouts(t *testing.T) { + for _, size := range [][2]int{{160, 44}, {125, 36}, {120, 36}, {90, 24}, {48, 16}} { + t.Run(fmt.Sprint(size), func(t *testing.T) { + m := remoteImageModel(t) + m.width, m.height = size[0], size[1] + m.preferencesPath = filepath.Join(t.TempDir(), "preferences.json") + calls := 0 + m.images.testLoader = func(context.Context, imageJob) (image.Image, int64, error) { + calls++ + return demoPostcard(), 1, nil + } + x, y := imageButtonPosition(t, m) + m = press(m, "G") + if m.scroll == 0 { + t.Fatal("fixture must have scrolling content") + } + if sx, sy := imageButtonPosition(t, m); sx != x || sy != y { + t.Fatal("image action scrolled away from the visible message") + } + next, cmd := m.Update(tea.MouseClickMsg{Button: tea.MouseLeft, X: x + 5, Y: y}) + m = next.(model) + if cmd == nil || calls != 0 || !m.preferences.RemoteImages || m.focus != threadPane { + t.Fatal("click did not schedule the image and enable the preference") + } + p, err := readPreferences(m.preferencesPath) + if err != nil || !p.RemoteImages { + t.Fatal("mouse action did not save the preference") + } + next, again := m.Update(cmd()) + m = next.(model) + if again != nil || calls != 1 || strings.Contains(m.View().Content, "Always show images") || !strings.Contains(strings.Join(m.readerLines(), "\n"), "▀") { + t.Fatal("click did not load the preview and dismiss the notice") + } + }) + } +} + +func TestClicksOutsideImageButtonDoNotEnableRemoteImages(t *testing.T) { + for _, click := range []struct { + name string + dx, dy int + button tea.MouseButton + }{ + {"left margin", -1, 0, tea.MouseLeft}, + {"explanation", 0, -1, tea.MouseLeft}, + {"preference caption", 0, 1, tea.MouseLeft}, + {"right padding", 22, 0, tea.MouseLeft}, + {"right mouse button", 0, 0, tea.MouseRight}, + } { + t.Run(click.name, func(t *testing.T) { + m := remoteImageModel(t) + x, y := imageButtonPosition(t, m) + next, cmd := m.Update(tea.MouseClickMsg{Button: click.button, X: x + click.dx, Y: y + click.dy}) + if cmd != nil || next.(model).preferences.RemoteImages { + t.Fatal("click outside the button enabled remote images") + } + }) + } +} + +func TestImageMetadataArrivingFromSyncLoadsWithoutAnotherAction(t *testing.T) { + for _, remote := range []bool{false, true} { + t.Run(fmt.Sprintf("remote=%v", remote), func(t *testing.T) { + m := liveTestModel(t) + m.openThread() + m.live.pending = nil // the thread lookup is represented by the result below + m.live.queued = map[string]syncRequest{} + m.preferences.RemoteImages = remote + key := m.liveKey(0) + data := copyAccount(m.live.disk.Accounts[key]) + var applied []string + for _, op := range data.Flags { + applied = append(applied, op.ID) + } + img := messageImage{ID: "sync-image", Name: "Photo", Part: []int{2}, MIMEType: "image/png"} + if remote { + img.Source, img.Part = "https://images.example/photo.png", nil + } + data.Messages[0].Images, data.Messages[0].ImageBody = []messageImage{img}, img.token() + data.Messages[0].ImagesIndexed = true + calls := 0 + m.images.testLoader = func(_ context.Context, job imageJob) (image.Image, int64, error) { + calls++ + if !remote && (len(job.Image.Part) != 1 || job.Password != "test-password" || job.Ref.UID != 41) { + t.Fatal("attached preview lost its mail identity or connection details") + } + return demoPostcard(), 100, nil + } + next, cmd := m.Update(liveSyncMsg{Key: key, Request: syncRequest{Folder: "INBOX"}, Result: syncResult{Data: data, Applied: applied}}) + m = next.(model) + if cmd == nil { + t.Fatal("sync delivered image metadata but no preview was scheduled") + } + next, again := m.Update(cmd()) + m = next.(model) + if again != nil || calls != 1 || !strings.Contains(strings.Join(m.readerLines(), "\n"), "▀") { + t.Fatal("image required a manual action after the message synced") + } + }) + } +} + +func TestConversationImageCommandsDoNotChangeGlobalPreference(t *testing.T) { + m := remoteImageModel(t) + m.images.testLoader = func(context.Context, imageJob) (image.Image, int64, error) { return demoPostcard(), 1, nil } + m = press(m, ":loadimages") + next, cmd := m.Update(tea.KeyPressMsg{Code: tea.KeyEnter}) + m = next.(model) + if cmd == nil || m.preferences.RemoteImages { + t.Fatal("one-conversation load changed the saved preference") + } + next, _ = m.Update(cmd()) + m = press(next.(model), ":hideimages") + m = special(m, tea.KeyEnter) + if m.preferences.RemoteImages || strings.Contains(strings.Join(m.readerLines(), "\n"), "▀") || m.images.thread != "" { + t.Fatal("one-conversation hide did not hide and cancel previews") + } +} + +func TestImageQueueHasDownloadAndConcurrencyBounds(t *testing.T) { + m := imageModel(t) + target := m.current() + id := target.Messages[0].ID + var meta messageImages + for i := 0; i < 40; i++ { + img := messageImage{ID: fmt.Sprint(i), Name: "Image", Source: fmt.Sprintf("https://images.example/%d.png", i)} + meta.Images = append(meta.Images, img) + meta.Text += img.token() + "\n" + } + target.ImageBodies[id] = meta + calls := 0 + m.images.testLoader = func(context.Context, imageJob) (image.Image, int64, error) { + calls++ + return demoPostcard(), mailimage.MaxBytes, nil + } + m, cmd := runImageKey(m) + if len(m.images.busy) != maxThreadImages { + t.Fatal("image work was not bounded by the per-action limit") + } + for cmd != nil { + next, nextCmd := m.Update(cmd()) + m, cmd = next.(model), nextCmd + } + if calls != imageDownloadBudget/mailimage.MaxBytes || len(m.images.busy) != 0 || !strings.Contains(m.notice, "limit") { + t.Fatalf("image queue exceeded the download budget or kept running: calls=%d notice=%s", calls, m.notice) + } +} diff --git a/internal/app/live_model.go b/internal/app/live_model.go index e1ff1aa..7c4e063 100644 --- a/internal/app/live_model.go +++ b/internal/app/live_model.go @@ -526,7 +526,7 @@ func (m *model) rebuildLive() { } } } - threads = append(threads, Thread{ID: d.ID, Account: index, Folder: localDraftFolder, Subject: d.Subject, LocalDraft: true, Remote: true, ReplyTo: parent, ReplyID: d.ReplyID, References: d.References, Recipient: d.To, Messages: []Message{{"You", m.accounts[index].Address, d.Body, d.Updated}}}) + threads = append(threads, Thread{ID: d.ID, Account: index, Folder: localDraftFolder, Subject: d.Subject, LocalDraft: true, Remote: true, ReplyTo: parent, ReplyID: d.ReplyID, References: d.References, Recipient: d.To, Messages: []Message{{"You", m.accounts[index].Address, d.Body, d.Updated, ""}}}) } out = append(out, threads...) } @@ -603,7 +603,7 @@ func buildMailThreads(index int, key string, records []remoteMail, old []Thread) folders[r.Ref.Folder] = true } for folder := range folders { - t := Thread{ID: stableMailID(key + folder + group), Account: index, Folder: folder, Subject: rs[0].Subject, Remote: true} + t := Thread{ID: stableMailID(key + folder + group), Account: index, Folder: folder, Subject: rs[0].Subject, Remote: true, ImageBodies: map[string]messageImages{}} seen := map[string]bool{} for _, r := range rs { t.Refs = append(t.Refs, r.Ref) @@ -612,8 +612,11 @@ func buildMailThreads(index int, key string, records []remoteMail, old []Thread) t.Starred = t.Starred || r.Starred } if !seen[r.MessageID] { - t.Messages = append(t.Messages, Message{r.Sender, r.From, r.Body, r.Received}) + t.Messages = append(t.Messages, Message{Sender: r.Sender, Address: r.From, Body: r.Body, Received: r.Received, ID: r.MessageID}) t.RemoteIDs = append(t.RemoteIDs, r.MessageID) + if len(r.Images) > 0 { + t.ImageBodies[r.MessageID] = messageImages{Text: r.ImageBody, Images: r.Images, Ref: r.Ref} + } seen[r.MessageID] = true } } @@ -887,7 +890,19 @@ func (m *model) finishLiveSend(msg liveSendMsg) { // Wrap the existing UI reducer so every navigation route (including mouse and // Vim prefixes) schedules the same live operations and draft autosave. -func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { +func (m model) Update(msg tea.Msg) (nextModel tea.Model, nextCmd tea.Cmd) { + defer func() { + if next, ok := nextModel.(model); ok { + next.cancelImagesIfNeeded() + if auto := next.automaticImages(); auto != nil { + nextCmd = tea.Batch(nextCmd, auto) + } + nextModel = next + } + }() + if result, ok := msg.(imageLoadedMsg); ok { + return m.finishImage(result) + } if m.live == nil { return m.updateUI(msg) } diff --git a/internal/app/live_store.go b/internal/app/live_store.go index 95a780f..7e52d2e 100644 --- a/internal/app/live_store.go +++ b/internal/app/live_store.go @@ -31,6 +31,9 @@ type remoteMail struct { Received time.Time Seen, Starred, BodyLoaded bool Attachments []string + Images []messageImage + ImageBody string + ImagesIndexed bool } type folderInfo struct { Name, Role string diff --git a/internal/app/mail.go b/internal/app/mail.go index 2e44bbc..ccf729b 100644 --- a/internal/app/mail.go +++ b/internal/app/mail.go @@ -19,6 +19,7 @@ type Account struct { type Message struct { Sender, Address, Body string Received time.Time + ID string } type Thread struct { QueueID string @@ -33,6 +34,7 @@ type Thread struct { Messages []Message ReplyTo int Recipient string + ImageBodies map[string]messageImages } func (t *Thread) newest() Message { @@ -107,12 +109,12 @@ func seed(now time.Time) ([]Account, []Thread) { if a == 1 && f == 0 && i == 0 { subject = "Prototype review / navigation and rhythm" } - msg := Message{item.sender, strings.ToLower(strings.ReplaceAll(item.sender, " ", ".")) + "@example.com", item.body, received} + msg := Message{item.sender, strings.ToLower(strings.ReplaceAll(item.sender, " ", ".")) + "@example.com", item.body, received, ""} messages := []Message{msg} if i%2 == 0 { messages = append(messages, - Message{"You", accounts[a].Address, "Thanks for putting this together. I like the direction, especially the small details.\n\nCould you share the updated plan when you have a moment? I'd love to make sure we leave enough time to enjoy it.\n\nDaniel", received.Add(-3 * time.Hour)}, - Message{item.sender, msg.Address, "Hey Daniel,\n\nI've been thinking about our conversation and started gathering a few ideas. There is something nice about giving ourselves a little more space to explore.\n\nI'll send a more detailed update tomorrow. In the meantime, tell me if there's anything you'd like to include.\n\nTalk soon,\n" + strings.Fields(item.sender)[0], received.Add(-26 * time.Hour)}) + Message{"You", accounts[a].Address, "Thanks for putting this together. I like the direction, especially the small details.\n\nCould you share the updated plan when you have a moment? I'd love to make sure we leave enough time to enjoy it.\n\nDaniel", received.Add(-3 * time.Hour), ""}, + Message{item.sender, msg.Address, "Hey Daniel,\n\nI've been thinking about our conversation and started gathering a few ideas. There is something nice about giving ourselves a little more space to explore.\n\nI'll send a more detailed update tomorrow. In the meantime, tell me if there's anything you'd like to include.\n\nTalk soon,\n" + strings.Fields(item.sender)[0], received.Add(-26 * time.Hour), ""}) } if folder == "Sent" { messages[0].Sender = "You" diff --git a/internal/app/mail_content.go b/internal/app/mail_content.go index 275a073..12ab7f5 100644 --- a/internal/app/mail_content.go +++ b/internal/app/mail_content.go @@ -191,6 +191,23 @@ func decodeTextPart(p textPart, data []byte) string { } return body } + +// decodeTextSource preserves HTML structure for image placement. It only +// decodes an already fetched MIME text part; it never follows image sources. +func decodeTextSource(p textPart, data []byte) string { + var h message.Header + h.Set("Content-Type", mime.FormatMediaType(p.Type, p.Params)) + h.Set("Content-Transfer-Encoding", p.Encoding) + e, _ := message.New(h, bytes.NewReader(data)) + if e == nil { + return "" + } + content, err := io.ReadAll(io.LimitReader(e.Body, 2<<20)) + if err != nil { + return "" + } + return string(content) +} func makeWire(c AccountConfig, o outgoingMail) ([]byte, []string, error) { if strings.ContainsAny(o.To+o.Subject, "\r\n\x00") { return nil, nil, fmt.Errorf("Recipients and subject must each be a single line.") diff --git a/internal/app/mail_transport.go b/internal/app/mail_transport.go index 6cbc787..83ba4c5 100644 --- a/internal/app/mail_transport.go +++ b/internal/app/mail_transport.go @@ -193,13 +193,21 @@ func fetchLiveMail(im *client.Client, folder string, validity uint32, uids []uin var out []remoteMail for _, f := range result { r := f.r - if !r.BodyLoaded { + if !r.BodyLoaded || !r.ImagesIndexed { parts, attachments := readableParts(f.bs) + imageParts, htmlPart := imageMIMEParts(f.bs) tooManyParts := len(parts) > 16 r.Attachments = attachments if len(parts) > 16 { parts = parts[:16] } + bodyParts := map[string]bool{} + for _, part := range parts { + bodyParts[fmt.Sprint(part.Path)] = true + } + if htmlPart != nil && !bodyParts[fmt.Sprint(htmlPart.Path)] && len(parts) < 16 { + parts = append(parts, *htmlPart) + } partLimit := (1 << 20) / max(1, len(parts)) var sections []*imap.BodySectionName items := []imap.FetchItem{imap.FetchUid} @@ -209,6 +217,7 @@ func fetchLiveMail(im *client.Client, folder string, validity uint32, uids []uin items = append(items, s.FetchItem()) } var body []string + var htmlSource string if len(parts) > 0 { bodyCh := make(chan *imap.Message, 1) bodyDone := make(chan error, 1) @@ -220,10 +229,15 @@ func fetchLiveMail(im *client.Client, folder string, validity uint32, uids []uin if lit := m.GetBody(s); lit != nil { data, _ := io.ReadAll(io.LimitReader(lit, int64(partLimit))) text := decodeTextPart(parts[i], data) + if parts[i].Type == "text/html" && htmlSource == "" { + htmlSource = decodeTextSource(parts[i], data) + } if parts[i].Size > uint32(partLimit) { text += "\n[Text part truncated to keep this message within its 1 MiB download limit.]" } - body = append(body, text) + if bodyParts[fmt.Sprint(parts[i].Path)] { + body = append(body, text) + } } } } @@ -245,8 +259,14 @@ func fetchLiveMail(im *client.Client, folder string, validity uint32, uids []uin r.Body = "[No readable text in this message.]" } if len(attachments) > 0 { - r.Body += "\n\nAttachments: " + strings.Join(attachments, ", ") + "\n[Attachment downloads are not supported yet.]" + r.Body += "\n\nAttachments: " + strings.Join(attachments, ", ") + if len(imageParts) > 0 { + r.Body += "\n[Image attachments appear inline in the reader. Other downloads are not supported yet.]" + } else { + r.Body += "\n[Attachment downloads are not supported yet.]" + } } + indexMailImages(&r, imageParts, htmlSource) r.BodyLoaded = true } out = append(out, r) @@ -449,7 +469,7 @@ func (b imapTransport) Sync(ctx context.Context, c AccountConfig, password strin old := recordMap(res.Data) var need []uint32 for _, id := range all { - if r, ok := old[(mailRef{req.Folder, box.UidValidity, id}).key()]; !ok || !r.BodyLoaded { + if r, ok := old[(mailRef{req.Folder, box.UidValidity, id}).key()]; !ok || !r.BodyLoaded || !r.ImagesIndexed { need = append(need, id) } } @@ -552,7 +572,7 @@ func expandRemoteThread(im *client.Client, a *accountMail, seed string) error { var need []uint32 for _, id := range found { ref := mailRef{folder.Name, box.UidValidity, id} - if r, ok := old[ref.key()]; !ok || !r.BodyLoaded { + if r, ok := old[ref.key()]; !ok || !r.BodyLoaded || !r.ImagesIndexed { need = append(need, id) } else { frontier = append(frontier, r.MessageID) diff --git a/internal/app/main.go b/internal/app/main.go index 20e5a80..96ce05f 100644 --- a/internal/app/main.go +++ b/internal/app/main.go @@ -29,6 +29,10 @@ type Options struct { // Run opens the terminal client with already validated options. func Run(options Options) error { m := newModel(time.Now()) + m.demo = options.Demo + if !options.Demo { + m.loadPreferences() + } ctx, cancel := context.WithCancel(context.Background()) defer cancel() m.background = ctx diff --git a/internal/app/model.go b/internal/app/model.go index d9c3464..18d97c3 100644 --- a/internal/app/model.go +++ b/internal/app/model.go @@ -62,11 +62,17 @@ type model struct { configPath, configError string credentials credentialStore background context.Context + images *imageState + preferences readerPreferences + preferencesPath, preferencesReadError, settingsError string + settingsOpen bool + demo bool } func newModel(now time.Time) model { a, t := seed(now) - return model{accounts: a, threads: t, now: now, width: 120, height: 36, folder: "Inbox", expanded: []bool{true, true}, treeOpen: true, treeCursor: 1, notice: "Welcome aboard. Press ? for the keymap."} + addDemoImage(t) + return model{accounts: a, threads: t, images: newImageState(), preferences: readerPreferences{Version: 1}, now: now, width: 120, height: 36, folder: "Inbox", expanded: []bool{true, true}, treeOpen: true, treeCursor: 1, notice: "Welcome aboard. Press ? for the keymap."} } func tick() tea.Cmd { return tea.Tick(70*time.Millisecond, func(t time.Time) tea.Msg { return tickMsg(t) }) @@ -206,6 +212,11 @@ func (m model) updateUI(msg tea.Msg) (tea.Model, tea.Cmd) { if result, ok := msg.(accountCheckMsg); ok { return m.finishAccountCheck(result) } + if m.settingsOpen { + if _, resizing := msg.(tea.WindowSizeMsg); !resizing { + return m.handleSettings(msg) + } + } if m.setup != nil { return m.handleAccountSetup(msg) } @@ -267,6 +278,11 @@ func (m model) updateUI(msg tea.Msg) (tea.Model, tea.Cmd) { return m, nil } if msg.Button == tea.MouseLeft { + if m.imageNoticeClicked(msg.X, msg.Y) { + m.focus = threadPane + cmd := m.alwaysShowImages() + return m, cmd + } m.click(msg.X, msg.Y) } case tea.MouseWheelMsg: @@ -357,6 +373,11 @@ func (m model) updateUI(msg tea.Msg) (tea.Model, tea.Cmd) { return m, nil } switch key { + case "I": + cmd := m.alwaysShowImages() + return m, cmd + case "S": + m.openSettings() case "Q": m.openSyncQueue() case "R", "f5": @@ -545,6 +566,18 @@ func (m model) handlePrompt(key tea.KeyPressMsg) (tea.Model, tea.Cmd) { m.focus = listPane } else { switch strings.TrimSpace(m.input) { + case "images": + m.prompt, m.input = "", "" + cmd := m.alwaysShowImages() + return m, cmd + case "settings": + m.openSettings() + case "loadimages": + m.prompt, m.input = "", "" + cmd := m.loadImages() + return m, cmd + case "hideimages": + m.hideImages() case "queue": m.openSyncQueue() case "delete", "trash": @@ -664,7 +697,7 @@ func (m *model) saveDraft() bool { id = m.nextID() } m.removeSavedDraft(d.savedID) - m.threads = append(m.threads, Thread{ID: id, Account: d.account, Folder: "Drafts", Subject: d.subject, ReplyTo: d.threadID, Recipient: d.to, Messages: []Message{{"You", m.accounts[d.account].Address, d.body, time.Now()}}}) + m.threads = append(m.threads, Thread{ID: id, Account: d.account, Folder: "Drafts", Subject: d.subject, ReplyTo: d.threadID, Recipient: d.to, Messages: []Message{{"You", m.accounts[d.account].Address, d.body, time.Now(), ""}}}) normalize(m.threads) d.savedID = id d.savedBody = d.body @@ -704,7 +737,7 @@ func (m *model) sendDemo() { m.notice = "Add a message before sending." return } - msg := Message{"You", m.accounts[d.account].Address, d.body, time.Now()} + msg := Message{"You", m.accounts[d.account].Address, d.body, time.Now(), ""} m.removeSavedDraft(d.savedID) for i := range m.threads { if m.threads[i].ID == d.threadID { diff --git a/internal/app/preferences.go b/internal/app/preferences.go new file mode 100644 index 0000000..70598f0 --- /dev/null +++ b/internal/app/preferences.go @@ -0,0 +1,167 @@ +package app + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "strings" + + tea "charm.land/bubbletea/v2" + "github.com/charmbracelet/x/ansi" +) + +type readerPreferences struct { + Version int `json:"version"` + RemoteImages bool `json:"remote_images"` +} + +func preferencesPath() (string, error) { + root, err := os.UserConfigDir() + if err != nil { + return "", err + } + return filepath.Join(root, storageNamespace, "preferences.json"), nil +} + +func readPreferences(path string) (readerPreferences, error) { + p := readerPreferences{Version: 1} + f, err := os.Open(path) + if errors.Is(err, os.ErrNotExist) { + return p, nil + } + if err != nil { + return p, err + } + defer f.Close() + info, err := f.Stat() + if err != nil || info.Size() > 64<<10 { + return readerPreferences{Version: 1}, errors.New("preferences.json exceeds its size limit or could not be read") + } + d := json.NewDecoder(io.LimitReader(f, 64<<10)) + if err := d.Decode(&p); err != nil { + return readerPreferences{Version: 1}, errors.New("could not read preferences.json") + } + var suffix any + if err := d.Decode(&suffix); err != io.EOF || p.Version != 1 { + return readerPreferences{Version: 1}, errors.New("unsupported or invalid preferences.json") + } + return p, nil +} + +func (m *model) loadPreferences() { + path, err := preferencesPath() + if err == nil { + m.preferencesPath = path + m.preferences, err = readPreferences(path) + } + if err != nil { + m.preferences = readerPreferences{Version: 1} + m.preferencesReadError = "Reader preferences could not be loaded. Fix preferences.json before changing settings." + } +} + +func (m *model) setRemoteImages(enabled bool) error { + if m.preferencesReadError != "" { + return errors.New(m.preferencesReadError) + } + p := m.preferences + p.Version, p.RemoteImages = 1, enabled + if !m.demo && m.preferencesPath != "" { + if err := atomicPrivateJSON(m.preferencesPath, p); err != nil { + return errors.New("Could not save reading preferences. Check the config directory permissions.") + } + } + m.preferences = p + m.settingsError = "" + if !enabled && m.images != nil { + m.cancelImages() + m.images.visible = map[string]bool{} + } + m.clampScroll() + return nil +} + +func (m *model) openSettings() { + m.settingsOpen, m.settingsError, m.prompt, m.input = true, "", "", "" +} + +func (m model) handleSettings(msg tea.Msg) (tea.Model, tea.Cmd) { + enabled, change := m.preferences.RemoteImages, false + switch key := msg.(type) { + case tea.KeyPressMsg: + switch key.String() { + case "q", "esc", "ctrl+c": + m.settingsOpen = false + return m, nil + case "enter", " ": + enabled, change = !enabled, true + case "h", "left": + enabled, change = false, true + case "l", "right": + enabled, change = true, true + } + case tea.MouseClickMsg: + if key.Button == tea.MouseLeft && key.Y == 6 { + enabled, change = !enabled, true + } + } + if change { + if err := m.setRemoteImages(enabled); err != nil { + m.settingsError = err.Error() + m.notice = err.Error() + } else { + m.notice = "Reading preferences saved." + if m.demo { + m.notice = "Demo reading preference changed for this session." + } + } + } + return m, nil +} + +func (m model) settingsView() string { + check := " " + if m.preferences.RemoteImages { + check = "x" + } + lines := []string{ + bold(" Reading", cyan), "", + bold(fmt.Sprintf(" [%s] Always show remote images", check), teal), "", + } + if m.preferencesReadError != "" { + lines = append(lines, wrappedSetting(m.preferencesReadError, max(1, m.width-4))...) + } + if m.settingsError != "" { + lines = append(lines, wrappedSetting(m.settingsError, max(1, m.width-4))...) + } + details := []string{ + "Images load automatically as you read after this is enabled.", + "This applies to all accounts and is remembered between launches.", + "Image hosts can see when you open a message. Known hidden and tracking-sized images are skipped.", + "Embedded and attached image previews load when you open a message.", + } + if m.demo { + details = []string{ + "Try the image button in 'A few photos from the coast' in Personal / Inbox.", + "Demo images come from local samples. No image host is contacted.", + "This setting applies to this demo session only. Your mailbox preference stays unchanged.", + "Each demo launch starts with remote image samples hidden. Embedded images still load automatically.", + } + } + for _, text := range details { + lines = append(lines, wrappedSetting(text, max(1, m.width-4))...) + lines = append(lines, "") + } + return paneLines(lines, m.width, m.bodyHeight(), false, bluePane) +} + +func wrappedSetting(text string, width int) []string { + var out []string + for _, line := range strings.Split(ansi.Wrap(text, width, ""), "\n") { + out = append(out, styled(" "+line, muted)) + } + return out +} diff --git a/internal/app/preferences_test.go b/internal/app/preferences_test.go new file mode 100644 index 0000000..996e1a6 --- /dev/null +++ b/internal/app/preferences_test.go @@ -0,0 +1,131 @@ +package app + +import ( + "context" + "image" + "os" + "path/filepath" + "strings" + "testing" + "time" + + tea "charm.land/bubbletea/v2" + "github.com/charmbracelet/x/ansi" +) + +func TestRemoteImagePreferencePersistsAcrossLaunches(t *testing.T) { + root := t.TempDir() + t.Setenv("HOME", root) + t.Setenv("XDG_CONFIG_HOME", root) + m := remoteImageModel(t) + m.loadPreferences() + if m.preferences.RemoteImages { + t.Fatal("remote images must be off without a saved preference") + } + m.images.testLoader = func(context.Context, imageJob) (image.Image, int64, error) { return demoPostcard(), 100, nil } + m, cmd := runImageKey(m) + if cmd == nil { + t.Fatal("Always show did not schedule the image") + } + info, err := os.Stat(m.preferencesPath) + if err != nil || info.Mode().Perm() != 0600 { + t.Fatalf("preference was not saved privately: %v", err) + } + if dir, err := os.Stat(filepath.Dir(m.preferencesPath)); err != nil || dir.Mode().Perm() != 0700 { + t.Fatalf("preference directory was not private: %v", err) + } + restarted := remoteImageModel(t) + restarted.loadPreferences() + restarted.images.testLoader = m.images.testLoader + next, cmd := restarted.Update(tea.WindowSizeMsg{Width: 120, Height: 36}) + restarted = next.(model) + if !restarted.preferences.RemoteImages || cmd == nil || restarted.blockedRemoteImages() { + t.Fatal("next launch forgot the preference or required another action") + } + restarted = press(restarted, "Sh") + saved, err := readPreferences(restarted.preferencesPath) + if err != nil || saved.RemoteImages { + t.Fatal("Settings did not save the disabled preference") + } +} + +func TestPreferenceSaveFailureDoesNotEnableRemoteRequests(t *testing.T) { + m := remoteImageModel(t) + parent := filepath.Join(t.TempDir(), "not-a-directory") + if err := os.WriteFile(parent, []byte("preserve"), 0600); err != nil { + t.Fatal(err) + } + m.preferencesPath = filepath.Join(parent, "preferences.json") + m, cmd := runImageKey(m) + if cmd != nil || m.preferences.RemoteImages || !m.blockedRemoteImages() || !strings.Contains(m.notice, "Could not save") { + t.Fatal("save failure enabled remote images or was not explained") + } +} + +func TestDemoPreferenceDoesNotOverwriteMailboxPreference(t *testing.T) { + path := filepath.Join(t.TempDir(), "preferences.json") + const saved = `{"version":1,"remote_images":false}` + if err := os.WriteFile(path, []byte(saved), 0600); err != nil { + t.Fatal(err) + } + m := newModel(time.Now()) + m.demo, m.preferencesPath = true, path + if err := m.setRemoteImages(true); err != nil || !m.preferences.RemoteImages { + t.Fatalf("demo setting did not change for this session: %v", err) + } + got, err := os.ReadFile(path) + if err != nil || string(got) != saved { + t.Fatal("demo setting modified the saved mailbox preference") + } +} + +func TestInvalidPreferencesRemainBlockedAndPreserved(t *testing.T) { + for _, input := range []string{ + `{"version":1,"remote_images":true} trailing`, + `{"version":2,"remote_images":true}`, + `{"version":1,"remote_images":"true"}`, + `{"version":1,"remote_images":true}` + strings.Repeat(" ", 64<<10), + } { + t.Run(input[:min(40, len(input))], func(t *testing.T) { + path := filepath.Join(t.TempDir(), "preferences.json") + if err := os.WriteFile(path, []byte(input), 0600); err != nil { + t.Fatal(err) + } + p, err := readPreferences(path) + if err == nil || p.RemoteImages { + t.Fatal("invalid preferences enabled remote images") + } + m := newModel(time.Now()) + m.preferences, m.preferencesPath, m.preferencesReadError = p, path, "Invalid preferences preserved" + if err := m.setRemoteImages(true); err == nil || m.preferences.RemoteImages { + t.Fatal("unreadable preferences were silently replaced") + } + got, err := os.ReadFile(path) + if err != nil || string(got) != input { + t.Fatal("invalid preferences were not preserved") + } + }) + } +} + +func TestReadingSettingsLayoutAndCommand(t *testing.T) { + m := newModel(time.Now()) + m = press(m, ":settings") + m = special(m, tea.KeyEnter) + if !m.settingsOpen || !strings.Contains(ansi.Strip(m.View().Content), "Always show remote images") { + t.Fatal("reading settings command did not open the preference") + } + for _, size := range [][2]int{{120, 36}, {90, 24}, {48, 16}} { + next, _ := m.Update(tea.WindowSizeMsg{Width: size[0], Height: size[1]}) + m = next.(model) + lines := strings.Split(m.View().Content, "\n") + if len(lines) != size[1] { + t.Fatal("settings exceeded terminal height") + } + for _, line := range lines { + if ansi.StringWidth(line) != size[0] { + t.Fatal("settings exceeded terminal width") + } + } + } +} diff --git a/internal/app/reply.go b/internal/app/reply.go index 0116b1d..dfb2c60 100644 --- a/internal/app/reply.go +++ b/internal/app/reply.go @@ -38,7 +38,7 @@ func (m model) replyThreadLines() []string { if left == 0 { left = m.width } - return threadLines(m.replyThread(), max(8, left-4)) + return m.threadImageLines(m.replyThread(), max(8, left-4)) } func (m model) replyThreadVisible() int { return max(1, m.bodyHeight()-4) } diff --git a/internal/app/view.go b/internal/app/view.go index ebf23c1..386eb9c 100644 --- a/internal/app/view.go +++ b/internal/app/view.go @@ -35,6 +35,10 @@ func bold(s string, c color.Color) string { return lip.NewStyle().Bold(true).Foreground(c).Render(s) } +func imageNoticeButton(s string) string { + return lip.NewStyle().Bold(true).Foreground(ink).Background(teal).Render(s) +} + // Nested text styles reset their background. Restore the containing surface // after those resets so colors fill the pane, including its empty space. func onSurface(s string, bg color.Color) string { @@ -103,9 +107,15 @@ func (m model) readerLines() []string { if t := m.current(); t != nil && t.QueueID != "" { return m.queueReaderLines(t, m.readerWidth()) } - return threadLines(m.current(), m.readerWidth()) + return m.threadImageLines(m.current(), m.readerWidth()) } func threadLines(t *Thread, w int) []string { + return formattedThreadLines(t, w, nil) +} +func (m model) threadImageLines(t *Thread, w int) []string { + return formattedThreadLines(t, w, func(i int, msg Message) []string { return m.imageBodyLines(t, i, msg, w) }) +} +func formattedThreadLines(t *Thread, w int, render func(int, Message) []string) []string { if t == nil { return nil } @@ -117,15 +127,23 @@ func threadLines(t *Thread, w int) []string { } out = append(out, joinSides(bold(msg.Sender, cyan), styled(msg.Received.Local().Format("Jan 02 · 15:04"), muted), w)) out = append(out, styled(msg.Address, muted), styled(fmt.Sprintf("%s / %02d", label, i+1), violet), "") - for _, line := range strings.Split(ansi.Wrap(msg.Body, w, ""), "\n") { - out = append(out, styled(line, readerText)) + if render != nil { + out = append(out, render(i, msg)...) + } else { + for _, line := range strings.Split(ansi.Wrap(msg.Body, w, ""), "\n") { + out = append(out, styled(line, readerText)) + } } out = append(out, "", gradient(strings.Repeat("─", w), 0), "") } return out } func (m *model) clampScroll() { - m.scroll = max(0, min(m.scroll, max(0, len(m.readerLines())-(m.bodyHeight()-4)))) + m.scroll = max(0, min(m.scroll, max(0, len(m.readerLines())-m.readerVisibleLines()))) +} + +func (m model) readerVisibleLines() int { + return max(1, m.bodyHeight()-4-len(m.imageNoticeLines())) } func paneLines(lines []string, w, h int, separator bool, surface ...color.Color) string { @@ -368,9 +386,12 @@ func (m model) readerView(w int) string { if op, ok := m.queueOperation(t); ok { lines[1] = styled(m.trashStatus(t.Account, op), cyan) } + for _, line := range m.imageNoticeLines() { + lines = append(lines, " "+line) + } content := m.readerLines() start := min(m.scroll, len(content)) - end := min(len(content), start+m.bodyHeight()-4) + end := min(len(content), start+m.readerVisibleLines()) for _, line := range content[start:end] { lines = append(lines, " "+line) } @@ -378,10 +399,10 @@ func (m model) readerView(w int) string { lines = append(lines, "") } percent := 100 - if maxScroll := len(content) - (m.bodyHeight() - 4); maxScroll > 0 { + if maxScroll := len(content) - m.readerVisibleLines(); maxScroll > 0 { percent = min(100, m.scroll*100/maxScroll) } - lines = append(lines, styled(fmt.Sprintf(" r reply h inbox %d%%", percent), dim)) + lines = append(lines, styled(fmt.Sprintf(" r reply S settings h inbox %d%%", percent), dim)) if t.QueueID != "" { lines[len(lines)-1] = styled(" R retry h back to queue", dim) } @@ -402,8 +423,13 @@ func (m model) View() tea.View { if m.compose != nil { header[3] = joinSides(styled(" Writing · "+m.accounts[m.account].Name, muted), styled(m.notice, oceanText), m.width) } + if m.settingsOpen { + header[3] = styled(" Settings / Reading", muted) + } body := "" - if m.help { + if m.settingsOpen { + body = m.settingsView() + } else if m.help { body = m.helpView() } else if m.compose != nil { body = m.composeView() @@ -431,6 +457,9 @@ func (m model) View() tea.View { if m.prompt == ":" { mode = "Command" } + if m.settingsOpen { + mode = "Settings" + } badge := lip.NewStyle().Foreground(ink).Background(teal).Bold(true).Render(" " + mode + " ") status := onSurface(joinSides(badge+styled(" "+m.notice, oceanText), styled(fmt.Sprintf(" %d/%d ", min(m.selected+1, len(m.folderThreads())), len(m.folderThreads())), cyan), m.width), statusPane) hint := styled(" dd trash r reply / search \\nt tree h j k l navigate ? help :q quit", muted) @@ -455,12 +484,18 @@ func (m model) View() tea.View { hint = styled(" Enter details :canceldelete show originals h back \\nt tree", cyan) } } + if m.reading && m.compose == nil && m.focus == threadPane && m.folder != syncQueueFolder { + hint = styled(" S settings I show/retry images j/k scroll r reply h back", muted) + } if m.prompt != "" { hint = styled(" "+m.prompt+m.input+"▏", cyan) } if m.compose != nil { status, hint = m.editorFooter() } + if m.settingsOpen { + hint = styled(" Space/Enter toggle h off l on Esc back", muted) + } content = strings.Join(header, "\n") + "\n" + body + "\n" + fit(status, m.width) + "\n" + fit(hint, m.width) } // Fill the entire alternate screen, including sparse and narrow layouts. @@ -561,6 +596,8 @@ func (m model) helpView() string { {"dd / Delete / :delete", "Move cached mail in this folder to Trash; delete local draft"}, {"Q / :queue", "View pending Trash moves, failures, and recovery details"}, {"r", "Reply or re-open a saved draft"}, + {"I / :images", "Always show remote images; retry failed previews"}, + {"S / :settings", "Reading settings; turn remote images on or off"}, {"A / :addaccount", "Add account; also at the bottom of Explorer"}, {"e on account", "Edit settings and check sign-in again"}, {"Normal: :w", "Save draft; configured accounts also autosave"}, diff --git a/internal/mailimage/http.go b/internal/mailimage/http.go new file mode 100644 index 0000000..1687fbf --- /dev/null +++ b/internal/mailimage/http.go @@ -0,0 +1,165 @@ +package mailimage + +import ( + "context" + "errors" + "fmt" + "image/color" + "io" + "net" + "net/http" + "net/netip" + "net/url" + "strings" + "time" +) + +type lookupFunc func(context.Context, string, string) ([]netip.Addr, error) +type dialFunc func(context.Context, string, string) (net.Conn, error) + +// PublicURL performs syntactic checks only. No DNS query is made until Fetch. +func PublicURL(source string) bool { + if len(source) > 16<<10 { + return false + } + u, err := url.Parse(source) + if err != nil || (strings.ToLower(u.Scheme) != "https" && strings.ToLower(u.Scheme) != "http") || u.User != nil || u.Hostname() == "" { + return false + } + host := strings.ToLower(strings.TrimSuffix(u.Hostname(), ".")) + if ip, err := netip.ParseAddr(host); err == nil { + return publicAddress(ip) + } + return strings.Contains(host, ".") && host != "localhost" && !strings.HasSuffix(host, ".localhost") && !strings.HasSuffix(host, ".local") && !strings.HasSuffix(host, ".internal") && !strings.HasSuffix(host, ".localdomain") +} + +var reserved = []netip.Prefix{ + netip.MustParsePrefix("0.0.0.0/8"), netip.MustParsePrefix("100.64.0.0/10"), + netip.MustParsePrefix("192.0.0.0/24"), netip.MustParsePrefix("192.0.2.0/24"), + netip.MustParsePrefix("192.88.99.0/24"), + netip.MustParsePrefix("198.18.0.0/15"), netip.MustParsePrefix("198.51.100.0/24"), + netip.MustParsePrefix("203.0.113.0/24"), netip.MustParsePrefix("240.0.0.0/4"), + netip.MustParsePrefix("64:ff9b::/96"), netip.MustParsePrefix("64:ff9b:1::/48"), + netip.MustParsePrefix("::/96"), netip.MustParsePrefix("fec0::/10"), + netip.MustParsePrefix("2001::/23"), netip.MustParsePrefix("2001:db8::/32"), netip.MustParsePrefix("2002::/16"), +} + +func publicAddress(ip netip.Addr) bool { + ip = ip.Unmap() + if !ip.IsValid() || ip.Zone() != "" || !ip.IsGlobalUnicast() || ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast() { + return false + } + for _, prefix := range reserved { + if prefix.Contains(ip) { + return false + } + } + return true +} + +func client(parent context.Context, lookup lookupFunc, dial dialFunc) (*http.Client, *http.Transport) { + transport := &http.Transport{ + // Do not inherit proxies, cookies, auth, or credentials from mail or the + // environment. Resolve and validate every answer, then pin the dial. + Proxy: nil, DisableKeepAlives: true, MaxResponseHeaderBytes: 64 << 10, + TLSHandshakeTimeout: 8 * time.Second, ResponseHeaderTimeout: 10 * time.Second, + DialContext: func(transportContext context.Context, network, address string) (net.Conn, error) { + // Transport may detach its dial context to reuse connections. Bind + // DNS and dialing to this explicit image request as well, so hiding + // images cancels resolution before it can start another connection. + ctx, cancel := context.WithTimeout(parent, 8*time.Second) + stop := context.AfterFunc(transportContext, cancel) + defer stop() + defer cancel() + host, port, err := net.SplitHostPort(address) + if err != nil { + return nil, errors.New("invalid image host") + } + addresses, err := lookup(ctx, "ip", host) + if err != nil || len(addresses) == 0 { + return nil, errors.New("could not resolve image host") + } + for _, ip := range addresses { + if !publicAddress(ip) { + return nil, errors.New("image host resolves to a non-public address") + } + } + for _, ip := range addresses { + conn, err := dial(ctx, "tcp", net.JoinHostPort(ip.String(), port)) + if err == nil { + return conn, nil + } + } + return nil, errors.New("could not connect to image host") + }, + } + return &http.Client{ + Transport: transport, Timeout: 15 * time.Second, + CheckRedirect: imageRedirect, + }, transport +} + +func imageRedirect(req *http.Request, via []*http.Request) error { + if len(via) > 3 || !PublicURL(req.URL.String()) { + return errors.New("image redirect is not a public HTTP(S) source") + } + req.URL.Scheme = strings.ToLower(req.URL.Scheme) + if len(via) > 0 && via[len(via)-1].URL.Scheme == "https" && req.URL.Scheme != "https" { + return errors.New("image redirect would downgrade HTTPS") + } + // A redirect must not disclose the original image URL (which may contain + // a signed query or per-recipient token) in a Referer header. + req.Header.Del("Referer") + req.Header.Del("Authorization") + req.Header.Del("Cookie") + return nil +} + +// Fetch contacts a public image host after the reader permits remote images. DNS, +// connection, redirects, and body reads share a deadline. Every redirect is +// revalidated and every connection is pinned to approved public DNS answers. +func Fetch(ctx context.Context, source string, limit int64) ([]byte, string, error) { + if !PublicURL(source) { + return nil, "", errors.New("only public HTTP(S) image sources can be loaded") + } + ctx, cancel := context.WithTimeout(ctx, 15*time.Second) + defer cancel() + u, _ := url.Parse(source) + u.Scheme = strings.ToLower(u.Scheme) + resolver := &net.Resolver{PreferGo: true} + httpClient, transport := client(ctx, resolver.LookupNetIP, (&net.Dialer{Timeout: 8 * time.Second}).DialContext) + defer transport.CloseIdleConnections() + return fetch(ctx, httpClient, u.String(), min(limit, MaxBytes)) +} + +func fetch(ctx context.Context, httpClient *http.Client, source string, limit int64) ([]byte, string, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, source, nil) + if err != nil { + return nil, "", errors.New("invalid image request") + } + req.Header.Set("User-Agent", "Hane image viewer") + req.Header.Set("Accept", "image/png,image/jpeg,image/gif,image/webp") + resp, err := httpClient.Do(req) + if err != nil { + return nil, "", errors.New("image request failed or timed out") + } + defer resp.Body.Close() + if resp.StatusCode >= 300 && resp.StatusCode < 400 { + return nil, "", errors.New("image redirects are blocked") + } + if resp.StatusCode != http.StatusOK { + return nil, "", fmt.Errorf("image host returned HTTP %d", resp.StatusCode) + } + if limit <= 0 || resp.ContentLength > limit { + return nil, "", errors.New("image exceeds the download limit") + } + data, err := io.ReadAll(io.LimitReader(resp.Body, limit+1)) + if err != nil || int64(len(data)) > limit { + return nil, "", errors.New("image download was incomplete or too large") + } + return data, resp.Header.Get("Content-Type"), nil +} + +func escapeColor(top, bottom color.RGBA) string { + return fmt.Sprintf("\x1b[38;2;%d;%d;%dm\x1b[48;2;%d;%d;%dm", top.R, top.G, top.B, bottom.R, bottom.G, bottom.B) +} diff --git a/internal/mailimage/http_test.go b/internal/mailimage/http_test.go new file mode 100644 index 0000000..04bc3f7 --- /dev/null +++ b/internal/mailimage/http_test.go @@ -0,0 +1,188 @@ +package mailimage + +import ( + "context" + "net" + "net/http" + "net/http/httptest" + "net/netip" + "net/url" + "strings" + "sync/atomic" + "testing" + "time" +) + +func TestImageURLRejectsLocalCredentialsAndUnsupportedSchemes(t *testing.T) { + for _, source := range []string{ + "file:///etc/passwd", "ftp://images.example/image.png", "javascript:alert(1)", + "http://localhost/image", "http://device.local/image", "http://internal/image", + "http://127.0.0.1/image", "http://10.0.0.1/image", "http://169.254.169.254/latest", + "http://100.64.0.1/image", "http://192.168.1.1/image", "http://[::1]/image", + "http://[::ffff:127.0.0.1]/image", "http://[fec0::1]/image", "http://[::127.0.0.1]/image", + "http://user:password@images.example/image.png", "http://device.local./image", + } { + if PublicURL(source) { + t.Fatalf("unsafe image URL allowed: %s", source) + } + } + for _, source := range []string{"https://images.example/photo.png", "http://8.8.8.8/photo.png", "https://[2606:4700:4700::1111]/image"} { + if !PublicURL(source) { + t.Fatalf("public URL rejected: %s", source) + } + } +} + +func TestPrivateDNSAnswersNeverDialEvenWithPublicAnswer(t *testing.T) { + for _, ips := range [][]netip.Addr{ + {netip.MustParseAddr("127.0.0.1")}, + {netip.MustParseAddr("169.254.169.254")}, + {netip.MustParseAddr("93.184.216.34"), netip.MustParseAddr("192.168.1.1")}, + {netip.MustParseAddr("::ffff:10.0.0.1")}, + } { + var dials atomic.Int32 + lookup := func(context.Context, string, string) ([]netip.Addr, error) { return ips, nil } + client, transport := client(context.Background(), lookup, func(context.Context, string, string) (net.Conn, error) { + dials.Add(1) + return nil, nil + }) + _, _, err := fetch(context.Background(), client, "http://images.example/photo.png", MaxBytes) + transport.CloseIdleConnections() + if err == nil || dials.Load() != 0 { + t.Fatal("a private or mixed DNS answer reached the dialer") + } + } +} + +func TestPublicFetchPinsAddressAndSendsNoMailCredentials(t *testing.T) { + t.Setenv("HTTP_PROXY", "http://127.0.0.1:1") + t.Setenv("HTTPS_PROXY", "http://127.0.0.1:1") + raw := pngFixture(t) + var requests atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + if r.Header.Get("Authorization") != "" || r.Header.Get("Cookie") != "" || r.Header.Get("Referer") != "" || r.Method != http.MethodGet { + t.Error("image request carried credentials or mail context") + } + if !strings.HasPrefix(r.Host, "images.example:") { + t.Error("pinned dial did not preserve the image host") + } + w.Header().Set("Content-Type", "image/png") + _, _ = w.Write(raw) + })) + defer server.Close() + serverURL, _ := url.Parse(server.URL) + var dials atomic.Int32 + lookup := func(context.Context, string, string) ([]netip.Addr, error) { + return []netip.Addr{netip.MustParseAddr("93.184.216.34")}, nil + } + client, transport := client(context.Background(), lookup, func(ctx context.Context, network, address string) (net.Conn, error) { + dials.Add(1) + if address != net.JoinHostPort("93.184.216.34", serverURL.Port()) { + t.Error("connection was not pinned to the approved address") + } + return (&net.Dialer{}).DialContext(ctx, network, serverURL.Host) + }) + defer transport.CloseIdleConnections() + data, kind, err := fetch(context.Background(), client, "http://images.example:"+serverURL.Port()+"/photo.png", MaxBytes) + if err != nil || kind != "image/png" || len(data) != len(raw) || requests.Load() != 1 || dials.Load() != 1 { + t.Fatalf("pinned request failed: %v", err) + } +} + +func TestRedirectAndOversizedDownloadsAreRefused(t *testing.T) { + var requests atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + if r.URL.Path == "/redirect" { + http.Redirect(w, r, "http://127.0.0.1/private", http.StatusFound) + return + } + _, _ = w.Write([]byte(strings.Repeat("x", 100))) + })) + defer server.Close() + client := server.Client() + client.CheckRedirect = imageRedirect + if _, _, err := fetch(context.Background(), client, server.URL+"/redirect", MaxBytes); err == nil || requests.Load() != 1 { + t.Fatal("redirect was followed or accepted") + } + if _, _, err := fetch(context.Background(), client, server.URL+"/large", 10); err == nil { + t.Fatal("oversized image accepted") + } +} + +func TestCanceledImageRequestStopsDNS(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) + defer cancel() + stopped := make(chan struct{}) + lookup := func(ctx context.Context, _, _ string) ([]netip.Addr, error) { + <-ctx.Done() + close(stopped) + return nil, ctx.Err() + } + client, transport := client(ctx, lookup, (&net.Dialer{}).DialContext) + defer transport.CloseIdleConnections() + started := time.Now() + if _, _, err := fetch(ctx, client, "http://images.example/photo", MaxBytes); err == nil || time.Since(started) > time.Second { + t.Fatal("canceled request did not stop promptly") + } + select { + case <-stopped: + case <-time.After(time.Second): + t.Fatal("canceled HTTP request left DNS resolution running") + } +} + +func TestPublicRedirectsAreRevalidatedAndDoNotSendReferer(t *testing.T) { + var requests, resolutions atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + if r.URL.Path == "/start" { + _, port, _ := net.SplitHostPort(r.Host) + http.Redirect(w, r, "http://cdn.example:"+port+"/final", http.StatusFound) + return + } + if r.Header.Get("Referer") != "" { + t.Error("redirect disclosed the original image URL") + } + w.Header().Set("Content-Type", "image/png") + _, _ = w.Write(pngFixture(t)) + })) + defer server.Close() + u, _ := url.Parse(server.URL) + lookup := func(context.Context, string, string) ([]netip.Addr, error) { + resolutions.Add(1) + return []netip.Addr{netip.MustParseAddr("93.184.216.34")}, nil + } + client, transport := client(context.Background(), lookup, func(ctx context.Context, network, _ string) (net.Conn, error) { + return (&net.Dialer{}).DialContext(ctx, network, u.Host) + }) + defer transport.CloseIdleConnections() + if _, _, err := fetch(context.Background(), client, "http://images.example:"+u.Port()+"/start?recipient=private-token", MaxBytes); err != nil || requests.Load() != 2 || resolutions.Load() != 2 { + t.Fatalf("public redirect was not fetched through revalidated DNS: %v", err) + } +} + +func TestRedirectDNSRebindingCannotReachPrivateAddress(t *testing.T) { + var dials, lookups atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, port, _ := net.SplitHostPort(r.Host) + http.Redirect(w, r, "http://cdn.example:"+port+"/image", http.StatusFound) + })) + defer server.Close() + u, _ := url.Parse(server.URL) + lookup := func(context.Context, string, string) ([]netip.Addr, error) { + if lookups.Add(1) == 1 { + return []netip.Addr{netip.MustParseAddr("93.184.216.34")}, nil + } + return []netip.Addr{netip.MustParseAddr("10.0.0.1")}, nil + } + client, transport := client(context.Background(), lookup, func(ctx context.Context, network, _ string) (net.Conn, error) { + dials.Add(1) + return (&net.Dialer{}).DialContext(ctx, network, u.Host) + }) + defer transport.CloseIdleConnections() + if _, _, err := fetch(context.Background(), client, "http://images.example:"+u.Port()+"/start", MaxBytes); err == nil || dials.Load() != 1 { + t.Fatal("redirect reached a private address after DNS changed") + } +} diff --git a/internal/mailimage/image.go b/internal/mailimage/image.go new file mode 100644 index 0000000..03dcf18 --- /dev/null +++ b/internal/mailimage/image.go @@ -0,0 +1,129 @@ +// Package mailimage loads bounded raster images and renders terminal previews. +package mailimage + +import ( + "bytes" + "encoding/base64" + "errors" + "image" + "image/color" + _ "image/gif" + _ "image/jpeg" + _ "image/png" + "mime" + "strings" + + "golang.org/x/image/draw" + _ "golang.org/x/image/webp" +) + +const MaxBytes = 8 << 20 +const maxPixels = 16_000_000 +const previewSize = 512 + +// Decode checks dimensions before allocating the full image. GIF previews use +// the first frame. The returned raster is reduced to bound session-cache memory. +func Decode(data []byte, declared string) (image.Image, error) { + if len(data) == 0 || len(data) > MaxBytes { + return nil, errors.New("image is empty or larger than 8 MiB") + } + config, format, err := image.DecodeConfig(bytes.NewReader(data)) + if err != nil || config.Width <= 0 || config.Height <= 0 || config.Width > maxPixels/config.Height { + return nil, errors.New("image is invalid, unsupported, or larger than 16 megapixels") + } + types := map[string]string{"png": "image/png", "jpeg": "image/jpeg", "gif": "image/gif", "webp": "image/webp"} + want, ok := types[format] + if !ok { + return nil, errors.New("only PNG, JPEG, GIF, and WebP images can be displayed") + } + if declared != "" { + kind, _, err := mime.ParseMediaType(declared) + if err != nil { + return nil, errors.New("invalid image content type") + } + if kind == "image/jpg" { + kind = "image/jpeg" + } + if kind != want && kind != "application/octet-stream" { + return nil, errors.New("image content does not match its declared type") + } + } + if config.Width <= 2 || config.Height <= 2 { + return nil, errors.New("tiny tracking-sized images are not displayed") + } + source, _, err := image.Decode(bytes.NewReader(data)) + if err != nil { + return nil, errors.New("could not decode image") + } + w, h := fitSize(config.Width, config.Height, previewSize, previewSize) + preview := image.NewRGBA(image.Rect(0, 0, w, h)) + draw.ApproxBiLinear.Scale(preview, preview.Bounds(), source, source.Bounds(), draw.Src, nil) + return preview, nil +} + +// Data decodes only explicit base64 raster data URIs, never SVG or HTML. +func Data(source string) ([]byte, string, error) { + header, encoded, ok := strings.Cut(source, ",") + if !ok || !strings.HasPrefix(strings.ToLower(header), "data:image/") || !strings.HasSuffix(strings.ToLower(header), ";base64") || len(encoded) > base64.StdEncoding.EncodedLen(MaxBytes) { + return nil, "", errors.New("unsupported embedded image") + } + kind := strings.TrimSuffix(strings.TrimPrefix(strings.ToLower(header), "data:"), ";base64") + switch kind { + case "image/png", "image/jpeg", "image/gif", "image/webp": + default: + return nil, "", errors.New("unsupported embedded image type") + } + data, err := base64.StdEncoding.DecodeString(encoded) + if err != nil { + return nil, "", errors.New("invalid embedded image") + } + return data, kind, nil +} + +func fitSize(w, h, maxW, maxH int) (int, int) { + if w > maxW { + h, w = max(1, h*maxW/w), maxW + } + if h > maxH { + w, h = max(1, w*maxH/h), maxH + } + return max(1, w), max(1, h) +} + +// Lines uses truecolor half-block cells. It participates in the TUI's normal +// clipping and redraws, so images scroll correctly without terminal extensions. +func Lines(source image.Image, width, maxRows int, background color.Color) []string { + if source == nil || width < 1 || maxRows < 1 { + return nil + } + bounds := source.Bounds() + if bounds.Empty() { + return nil + } + w, h := fitSize(bounds.Dx(), bounds.Dy(), min(width, 100), maxRows*2) + scaled := image.NewRGBA(image.Rect(0, 0, w, h)) + draw.ApproxBiLinear.Scale(scaled, scaled.Bounds(), source, bounds, draw.Src, nil) + var lines []string + for y := 0; y < h; y += 2 { + var line strings.Builder + for x := 0; x < w; x++ { + top := over(scaled.At(x, y), background) + bottom := over(color.Transparent, background) + if y+1 < h { + bottom = over(scaled.At(x, y+1), background) + } + // Only application-generated colour escapes enter the output. + line.WriteString(escapeColor(top, bottom)) + line.WriteRune('▀') + } + line.WriteString("\x1b[0m") + lines = append(lines, line.String()) + } + return lines +} + +func over(fg, bg color.Color) color.RGBA { + r, g, b, a := fg.RGBA() + br, bgc, bb, _ := bg.RGBA() + return color.RGBA{uint8((r + br*(65535-a)/65535) >> 8), uint8((g + bgc*(65535-a)/65535) >> 8), uint8((b + bb*(65535-a)/65535) >> 8), 255} +} diff --git a/internal/mailimage/image_test.go b/internal/mailimage/image_test.go new file mode 100644 index 0000000..bb1817f --- /dev/null +++ b/internal/mailimage/image_test.go @@ -0,0 +1,135 @@ +package mailimage + +import ( + "bytes" + "encoding/base64" + "encoding/binary" + "hash/crc32" + "image" + "image/color" + "image/gif" + "image/jpeg" + "image/png" + "strings" + "testing" + + "github.com/charmbracelet/x/ansi" +) + +func pngFixture(t *testing.T) []byte { + t.Helper() + img := image.NewRGBA(image.Rect(0, 0, 12, 8)) + for y := 0; y < 8; y++ { + for x := 0; x < 12; x++ { + img.SetRGBA(x, y, color.RGBA{uint8(x * 20), uint8(y * 30), 170, 255}) + } + } + var b bytes.Buffer + if err := png.Encode(&b, img); err != nil { + t.Fatal(err) + } + return b.Bytes() +} + +func TestDecodeSupportedRasterAndBoundedPreview(t *testing.T) { + source, _, err := image.Decode(bytes.NewReader(pngFixture(t))) + if err != nil { + t.Fatal(err) + } + for _, kind := range []string{"png", "jpeg", "gif"} { + t.Run(kind, func(t *testing.T) { + var data bytes.Buffer + switch kind { + case "png": + err = png.Encode(&data, source) + case "jpeg": + err = jpeg.Encode(&data, source, nil) + case "gif": + err = gif.Encode(&data, source, nil) + } + if err != nil { + t.Fatal(err) + } + img, err := Decode(data.Bytes(), "image/"+kind) + if err != nil || img.Bounds().Dx() != 12 || img.Bounds().Dy() != 8 { + t.Fatalf("decode %s: %v", kind, err) + } + for _, size := range [][2]int{{1, 1}, {8, 2}, {40, 20}} { + lines := Lines(img, size[0], size[1], color.RGBA{11, 22, 43, 255}) + if len(lines) == 0 || len(lines) > size[1] { + t.Fatal("image exceeded row budget") + } + for _, line := range lines { + if ansi.StringWidth(line) > size[0] || !strings.Contains(line, "▀") { + t.Fatal("image exceeded column budget or did not render pixels") + } + } + } + }) + } +} + +func TestRefuseInvalidSpoofedTinyAndHugeImages(t *testing.T) { + // A valid IHDR is enough to read dimensions; no large pixel allocation is + // needed to verify that a malicious decompression size is rejected. + var large bytes.Buffer + large.WriteString("\x89PNG\r\n\x1a\n") + header := make([]byte, 13) + binary.BigEndian.PutUint32(header, 5000) + binary.BigEndian.PutUint32(header[4:], 5000) + header[8], header[9] = 8, 2 + _ = binary.Write(&large, binary.BigEndian, uint32(len(header))) + large.WriteString("IHDR") + large.Write(header) + _ = binary.Write(&large, binary.BigEndian, crc32.ChecksumIEEE(append([]byte("IHDR"), header...))) + var tiny bytes.Buffer + _ = png.Encode(&tiny, image.NewRGBA(image.Rect(0, 0, 1, 1))) + for _, tc := range []struct { + data []byte + kind string + }{ + {[]byte(``), "image/png"}, + {pngFixture(t), "image/svg+xml"}, + {pngFixture(t), "image/jpeg"}, + {large.Bytes(), "image/png"}, + {tiny.Bytes(), "image/png"}, + {nil, "image/png"}, + } { + if _, err := Decode(tc.data, tc.kind); err == nil { + t.Fatal("unsafe or invalid image was accepted") + } + } +} + +func TestEmbeddedRasterDataIsValidated(t *testing.T) { + raw := pngFixture(t) + source := "data:image/png;base64," + base64.StdEncoding.EncodeToString(raw) + decoded, kind, err := Data(source) + if err != nil || kind != "image/png" || !bytes.Equal(raw, decoded) { + t.Fatal("valid embedded PNG was not decoded") + } + for _, source := range []string{"data:text/html;base64,AAAA", "data:image/svg+xml;base64,AAAA", "data:image/png;base64,not base64", "file:///tmp/image.png"} { + if _, _, err := Data(source); err == nil { + t.Fatal("invalid data URI accepted") + } + } +} + +func TestTransparentPixelsUseReaderBackground(t *testing.T) { + got := over(color.Transparent, color.RGBA{11, 22, 43, 255}) + if got != (color.RGBA{11, 22, 43, 255}) { + t.Fatal("transparent pixels did not use the reader background") + } +} + +func TestWebPPreview(t *testing.T) { + // A locally generated 16x12 solid-colour lossless WebP fixture. + data, err := base64.StdEncoding.DecodeString("UklGRh4AAABXRUJQVlA4TBEAAAAvD8ACAAdQ2lIUuf+BiOh/AAA=") + if err != nil { + t.Fatal(err) + } + img, err := Decode(data, "image/webp") + if err != nil || img.Bounds().Dx() != 16 || img.Bounds().Dy() != 12 { + t.Fatalf("WebP decode failed: %v", err) + } +} diff --git a/scripts/render_capture.py b/scripts/render_capture.py index f9aec1e..d7b125b 100644 --- a/scripts/render_capture.py +++ b/scripts/render_capture.py @@ -13,6 +13,19 @@ '', ''] fg, bg, weight = "#b5d5ff", "#0b162b", "normal" + +def palette_color(index): + basic = ["#000000", "#800000", "#008000", "#808000", "#000080", "#800080", "#008080", "#c0c0c0", + "#808080", "#ff0000", "#00ff00", "#ffff00", "#0000ff", "#ff00ff", "#00ffff", "#ffffff"] + if index < 16: + return basic[max(0, index)] + if index >= 232: + level = min(255, 8 + 10 * (index - 232)) + return "#%02x%02x%02x" % (level, level, level) + value = index - 16 + levels = [0, 95, 135, 175, 215, 255] + return "#%02x%02x%02x" % (levels[value // 36], levels[value // 6 % 6], levels[value % 6]) + for y, line in enumerate(lines): x, pos = 0, 0 for match in list(escape.finditer(line)) + [None]: @@ -39,6 +52,13 @@ fg = "#b5d5ff" elif code == 49: bg = "#0b162b" + elif code in (38, 48) and codes[i+1:i+2] == [5] and i+2 < len(codes): + color = palette_color(codes[i+2]) + if code == 38: + fg = color + else: + bg = color + i += 2 elif code in (38, 48) and codes[i+1:i+2] == [2] and i+4 < len(codes): color = "#%02x%02x%02x" % tuple(codes[i+2:i+5]) if code == 38: