-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreply.go
More file actions
185 lines (181 loc) · 5.7 KB
/
Copy pathreply.go
File metadata and controls
185 lines (181 loc) · 5.7 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
package main
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
)
func handleReplyAPI(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
writeJSON(w, 405, map[string]any{"ok": false, "error": "POST only"})
return
}
var req struct {
ID string `json:"id"`
Text string `json:"text"`
From string `json:"from"`
To string `json:"to"`
Subject string `json:"subject"`
// "text" (default), "html", or "markdown" — same as compose (see
// composeReq.Format in compose.go), rendered through the same
// renderBody so both paths produce identical output for the same input.
Format string `json:"format"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.ID == "" || req.Text == "" {
writeJSON(w, 400, map[string]any{"ok": false, "error": "id and text required"})
return
}
// A message id alone must not let one tenant reply as another: without
// this, replyMessage derives its Resend credentials purely from the
// TARGET message's own mailbox, so any signed-in tenant could send mail
// through a different tenant's Resend account just by supplying its
// message id. Same class of gap as handleAttachmentOpen already guards.
if !authIsAdmin(r) {
p := newPocheFromEnv()
doc, err := loadDoc(p, req.ID)
if err != nil {
writeJSON(w, 404, map[string]any{"ok": false, "error": "message not found"})
return
}
mbID := authMailboxID(r)
if mbID == "" || strField(doc, "mailbox_id") != mbID {
writeJSON(w, 403, map[string]any{"ok": false, "error": "forbidden"})
return
}
}
data, err := replyMessage(req.ID, req.Text, req.From, req.To, req.Subject, req.Format)
if err != nil {
writeJSON(w, 500, map[string]any{"ok": false, "error": err.Error()})
return
}
writeJSON(w, 200, map[string]any{"ok": true, "data": data})
}
func replyMessage(localID, text, fromOverride, toOverride, subjOverride, format string) (map[string]any, error) {
p := newPocheFromEnv()
doc, err := loadDoc(p, localID)
if err != nil {
return nil, err
}
from := fromOverride
if from == "" {
from, _ = doc["received_for"].(string)
}
if from == "" {
from, _ = doc["to_addr"].(string)
}
// If the derived from address is missing, disallowed by domain allowlist, or
// does not belong to the mailbox (e.g. stale 'inbox@local' from old payloads),
// fall back to the mailbox primary address so replies can still be sent.
mbID, _ := doc["mailbox_id"].(string)
pForAddr := newPocheFromEnv()
var mb *mailboxRecord
if mbID != "" {
mb, _ = getMailboxByID(pForAddr, mbID)
}
isMailboxAddr := mb != nil && mailboxOwnsAddress(pForAddr, mb, from)
if from == "" || !fromAllowed(from) || (mb != nil && !isMailboxAddr) {
if mb != nil && fromAllowed(mb.Address) {
from = mb.Address
}
}
if from == "" || !fromAllowed(from) {
return nil, fmt.Errorf("from not allowed (set MAIL_FROM_ALLOWLIST): %s", from)
}
if mb != nil && !mailboxOwnsAddress(pForAddr, mb, from) {
return nil, fmt.Errorf("from address %s does not belong to this mailbox", from)
}
to := toOverride
if to == "" {
to = emailOf(fmt.Sprint(doc["from_addr"]))
}
if to == "" {
return nil, fmt.Errorf("no recipient")
}
subj := subjOverride
if subj == "" {
subj = reSubject(fmt.Sprint(doc["subject"]))
}
mid, _ := doc["message_id"].(string)
// Continue the mailbox's own thread_id, not the specific message being
// replied to: if you reply to the 3rd message in a conversation, the
// new message must join the SAME thread everything else is in, not
// start grouping around message #3's own id.
threadID, _ := doc["thread_id"].(string)
if threadID == "" {
threadID = mid
}
textPart, htmlPart, err := renderBody(text, format)
if err != nil {
return nil, fmt.Errorf("render %s body: %w", normalizeFormat(format), err)
}
if strings.TrimSpace(stripTags(htmlPart)) == "" && strings.TrimSpace(textPart) == "" {
return nil, fmt.Errorf("body is empty after rendering")
}
payload := map[string]any{
"from": from,
"to": []string{to},
"subject": subj,
"text": textPart,
}
if htmlPart != "" {
payload["html"] = htmlPart
}
// References carries the whole ancestor chain (RFC 5322), not just the
// direct parent — needed for the recipient's own mail client to thread
// correctly, and for our own findThreadIDByMessageID (sync.go) to find
// a match even when the direct parent was never stored.
existingRefs, _ := doc["references"].(string)
refs := strings.TrimSpace(existingRefs + " " + mid)
if mid != "" {
payload["headers"] = map[string]string{
"In-Reply-To": mid,
"References": refs,
}
}
re := resendForMailbox(mb)
sent, err := re.sendEmail(payload)
if err != nil {
return nil, err
}
sentID, _ := sent["id"].(string)
sentMbID, _ := doc["mailbox_id"].(string)
outDoc := map[string]any{
"mailbox_id": sentMbID,
"from_addr": from,
"to_addr": to,
"subject": subj,
"preview": truncate(textPart, 200),
"body_text": textPart,
"body_html": htmlPart,
"html_sanitized": true,
"search_text": strings.ToLower(subj + " " + from + " " + to + " " + textPart),
"thread_id": threadID,
"unread": false,
"starred": false,
"resend_id": sentID,
"message_id": "",
"received_for": from,
"direction": "out",
"in_reply_to": mid,
"references": refs,
"created_at": time.Now().UnixMilli(),
}
_, err = p.Create("messages", outDoc)
if err == nil {
updateMailboxUsage(p, mbID, 1, messageSizeBytes(outDoc))
}
return map[string]any{
"sent_id": sentID,
"from": from,
"to": to,
"subject": subj,
}, nil
}
func reSubject(subj string) string {
l := strings.ToLower(strings.TrimSpace(subj))
if strings.HasPrefix(l, "re:") {
return subj
}
return "Re: " + subj
}