-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmessage.go
More file actions
376 lines (319 loc) · 10.4 KB
/
Copy pathmessage.go
File metadata and controls
376 lines (319 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
package handlers
import (
"encoding/json"
"fmt"
"html/template"
"log"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"gomail/config"
"gomail/delivery"
"gomail/mdn"
"gomail/security"
"gomail/store"
"gomail/templates"
)
// MessageHandler handles viewing individual messages.
type MessageHandler struct {
db *store.DB
cfg *config.Config
queue *delivery.Queue
sessionMgr *security.SessionManager
templates *template.Template
}
// NewMessageHandler creates a message handler.
func NewMessageHandler(cfg *config.Config, db *store.DB, queue *delivery.Queue, sm *security.SessionManager) *MessageHandler {
funcMap := template.FuncMap{
"safeHTML": func(s string) template.HTML {
return template.HTML(sanitizeHTML(s))
},
"formatSize": func(size int64) string {
switch {
case size >= 1048576:
return fmt.Sprintf("%.1f MB", float64(size)/1048576)
case size >= 1024:
return fmt.Sprintf("%.1f KB", float64(size)/1024)
default:
return fmt.Sprintf("%d B", size)
}
},
"formatAuth": func(result string) string {
switch result {
case "pass":
return "✓ Pass"
case "fail":
return "✗ Fail"
default:
return "— " + result
}
},
"authClass": func(result string) string {
switch result {
case "pass":
return "auth-pass"
case "fail":
return "auth-fail"
default:
return "auth-neutral"
}
},
}
tmpl := templates.LoadTemplate(funcMap, "base", "message", "welcome")
return &MessageHandler{
db: db,
cfg: cfg,
queue: queue,
sessionMgr: sm,
templates: tmpl,
}
}
// View shows a single message.
func (h *MessageHandler) View(w http.ResponseWriter, r *http.Request) {
account := getSessionAccount(h.db, h.sessionMgr, r)
if account == nil {
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
idStr := strings.TrimPrefix(r.URL.Path, "/message/")
id, err := strconv.ParseInt(idStr, 10, 64)
if err != nil {
http.NotFound(w, r)
return
}
msg, err := h.db.GetMessage(id, account.ID)
if err != nil || msg == nil {
http.NotFound(w, r)
return
}
log.Printf("[web] View message: id=%d, subject=%q, textLen=%d, htmlLen=%d",
id, msg.Subject, len(msg.TextBody), len(msg.HTMLBody))
log.Printf("[web] View message: id=%d, MDNRequested=%v, MDNAddress=%s, MDNSent=%v, Config.MDN.Enabled=%s, Config.MDN.Mode=%s",
id, msg.MDNRequested, msg.MDNAddress, msg.MDNSent, h.cfg.MDN.Enabled, h.cfg.MDN.Mode)
// Mark as read
if !msg.IsRead {
h.db.MarkRead(id)
msg.IsRead = true
// Update folder counts since message is now read
if msg.FolderID != nil {
h.db.UpdateFolderCounts(*msg.FolderID)
}
// Handle MDN (Message Disposition Notification) if requested
if msg.MDNRequested && !msg.MDNSent && h.cfg.MDN.Enabled == "yes" {
log.Printf("[web] MDN handling - mode=%s, address=%s", h.cfg.MDN.Mode, msg.MDNAddress)
h.handleMDN(msg, account)
}
}
// Get attachments
attachments, _ := h.db.GetAttachments(id)
unread, _ := h.db.CountUnread(account.ID)
folders, _ := h.db.ListFolders(account.ID)
data := map[string]interface{}{
"Title": msg.Subject,
"Message": msg,
"Attachments": attachments,
"Unread": unread,
"CSRFToken": h.sessionMgr.GenerateCSRFToken(r),
"Section": msg.Direction,
"Account": account,
"Folders": folders,
"MDNMode": h.cfg.MDN.Mode,
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := h.templates.ExecuteTemplate(w, "base.html", data); err != nil {
log.Printf("[web] template error: %v", err)
}
}
// Delete soft-deletes a message.
func (h *MessageHandler) Delete(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
if !h.sessionMgr.ValidateCSRF(r) {
http.Error(w, "Invalid CSRF token", http.StatusForbidden)
return
}
idStr := strings.TrimPrefix(r.URL.Path, "/message/delete/")
id, err := strconv.ParseInt(idStr, 10, 64)
if err != nil {
http.NotFound(w, r)
return
}
h.db.DeleteMessage(id)
http.Redirect(w, r, "/inbox", http.StatusSeeOther)
}
// ToggleStar toggles the starred status.
func (h *MessageHandler) ToggleStar(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
account := getSessionAccount(h.db, h.sessionMgr, r)
if account == nil {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
idStr := strings.TrimPrefix(r.URL.Path, "/message/star/")
id, err := strconv.ParseInt(idStr, 10, 64)
if err != nil {
http.NotFound(w, r)
return
}
msg, err := h.db.GetMessage(id, account.ID)
if err != nil || msg == nil {
http.NotFound(w, r)
return
}
h.db.MarkStarred(id, !msg.IsStarred)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]bool{"starred": !msg.IsStarred})
}
// MarkRead marks a message as read (AJAX).
func (h *MessageHandler) MarkRead(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
idStr := strings.TrimPrefix(r.URL.Path, "/api/mark-read/")
id, err := strconv.ParseInt(idStr, 10, 64)
if err != nil {
http.NotFound(w, r)
return
}
h.db.MarkRead(id)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]bool{"ok": true})
}
// handleMDN handles Message Disposition Notification based on config mode
func (h *MessageHandler) handleMDN(msg *store.Message, account *store.Account) {
if msg.MDNAddress == "" {
log.Printf("[web] handleMDN: no MDN address")
return
}
log.Printf("[web] handleMDN: mode=%s, checking auto mode", h.cfg.MDN.Mode)
// In auto mode, send MDN immediately
if h.cfg.MDN.Mode == "auto" {
log.Printf("[web] handleMDN: sending MDN in auto mode")
h.sendMDN(msg, account)
} else {
log.Printf("[web] handleMDN: manual mode, no auto-send")
}
// In manual mode, MDN will be shown in template and user can send/deny via API
}
// sendMDN generates and sends an MDN response
func (h *MessageHandler) sendMDN(msg *store.Message, account *store.Account) {
log.Printf("[web] sendMDN: starting for msg=%d, recipient=%s", msg.ID, msg.MDNAddress)
// Generate MDN message using multipart/report format per RFC 3798
mdnBody := mdn.GenerateMDNMultipart(
msg.MessageID,
msg.Subject,
account.Email,
msg.MDNAddress,
h.cfg.Server.Hostname,
)
log.Printf("[web] sendMDN: MDN body generated, enqueueing for delivery")
// Enqueue MDN for delivery
if err := h.queue.Enqueue(account.Email, []string{msg.MDNAddress}, []byte(mdnBody), account.ID); err != nil {
log.Printf("[web] MDN enqueue error: %v", err)
return
}
// Mark MDN as sent
h.db.MarkMDNSent(msg.ID)
log.Printf("[web] MDN sent for message %d to %s", msg.ID, msg.MDNAddress)
}
// SendMDN handles the API endpoint for manually sending MDN
func (h *MessageHandler) SendMDN(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
if !h.sessionMgr.ValidateCSRF(r) {
http.Error(w, "Invalid CSRF token", http.StatusForbidden)
return
}
account := getSessionAccount(h.db, h.sessionMgr, r)
if account == nil {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
idStr := strings.TrimPrefix(r.URL.Path, "/api/send-mdn/")
id, err := strconv.ParseInt(idStr, 10, 64)
if err != nil {
http.Error(w, "Invalid message ID", http.StatusBadRequest)
return
}
msg, err := h.db.GetMessage(id, account.ID)
if err != nil || msg == nil {
http.Error(w, "Message not found", http.StatusNotFound)
return
}
if !msg.MDNRequested {
http.Error(w, "No MDN requested for this message", http.StatusBadRequest)
return
}
if msg.MDNSent {
http.Error(w, "MDN already sent", http.StatusBadRequest)
return
}
log.Printf("[web] SendMDN API: sending MDN for message %d", id)
h.sendMDN(msg, account)
// Redirect back to the message
http.Redirect(w, r, "/message/"+idStr, http.StatusSeeOther)
}
// DownloadAttachment serves an attachment file.
func (h *MessageHandler) DownloadAttachment(w http.ResponseWriter, r *http.Request) {
idStr := strings.TrimPrefix(r.URL.Path, "/attachment/")
id, err := strconv.ParseInt(idStr, 10, 64)
if err != nil {
http.NotFound(w, r)
return
}
// Find the attachment
// We need to look it up — for simplicity, query by attachment ID
var att store.Attachment
err = h.db.QueryRow(`
SELECT id, message_id, filename, content_type, size, storage_path
FROM attachments WHERE id = ?`, id).Scan(
&att.ID, &att.MessageID, &att.Filename, &att.ContentType, &att.Size, &att.StoragePath,
)
if err != nil {
http.NotFound(w, r)
return
}
fullPath := filepath.Join(h.db.AttachmentsPath(), att.StoragePath)
// Check file exists
if _, err := os.Stat(fullPath); os.IsNotExist(err) {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", att.ContentType)
w.Header().Set("Content-Disposition", "attachment; filename=\""+att.Filename+"\"")
http.ServeFile(w, r, fullPath)
}
// sanitizeHTML removes potentially dangerous content from HTML emails
func sanitizeHTML(html string) string {
// Remove script tags and content
html = regexp.MustCompile(`(?i)<script[^>]*>.*?</script>`).ReplaceAllString(html, "")
// Remove iframes
html = regexp.MustCompile(`(?i)<iframe[^>]*>.*?</iframe>`).ReplaceAllString(html, "")
// Remove event handlers (onclick, onerror, onload, etc.)
// Match: on<word>= followed by quoted or unquoted value
html = regexp.MustCompile(`(?i)\s+on\w+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]*)`).ReplaceAllString(html, " ")
// Remove form submissions
html = regexp.MustCompile(`(?i)<form[^>]*>`).ReplaceAllString(html, "<div>")
html = regexp.MustCompile(`(?i)</form>`).ReplaceAllString(html, "</div>")
html = regexp.MustCompile(`(?i)<input[^>]*>`).ReplaceAllString(html, "")
html = regexp.MustCompile(`(?i)<button[^>]*>.*?</button>`).ReplaceAllString(html, "")
// Remove meta refresh (can be used to redirect)
html = regexp.MustCompile(`(?i)<meta\s+http-equiv\s*=\s*['"]?refresh['"]?[^>]*>`).ReplaceAllString(html, "")
// Remove base tag (can be used to change relative URLs)
html = regexp.MustCompile(`(?i)<base[^>]*>`).ReplaceAllString(html, "")
// Allow safe tags and attributes
// Keep: a, img, table, tr, td, div, span, p, br, strong, em, etc.
// This is a basic whitelist - emails should mostly work
return strings.TrimSpace(html)
}