Skip to content

armgit / posta

Public Imported from GitHub
0

Self-hosted email delivery platform that enables applications to send emails via HTTP APIs while handling SMTP delivery, templates, storage, security, and analytics. Fully self-hostable alternative to services like SendGrid or Mailgun.

feat(messages): harden web forms (#280)

Jonas Kanindae423b8ad0216
diff --git a/cmd/posta/server.go b/cmd/posta/server.go
index e15999b..4aa9f9e 100644
--- a/cmd/posta/server.go
+++ b/cmd/posta/server.go
@@ -37,7 +37,9 @@ import (
"github.com/goposta/posta/internal/services/email"
"github.com/goposta/posta/internal/services/eventbus"
"github.com/goposta/posta/internal/services/inbound"
+ "github.com/goposta/posta/internal/services/messages"
"github.com/goposta/posta/internal/services/notification"
+ "github.com/goposta/posta/internal/services/realtime"
"github.com/goposta/posta/internal/services/retry"
"github.com/goposta/posta/internal/services/seeder"
"github.com/goposta/posta/internal/services/settings"
@@ -299,9 +301,26 @@ func newInboundServiceForWorker(db *gorm.DB,
if bus != nil {
svc.SetEventBus(bus)
}
+ attachThreadRouter(svc, db, cfg, producer)
return svc
}
+// attachThreadRouter routes replies sent to form thread addresses
+// (msg+<token>@POSTA_MESSAGES_INBOUND_DOMAIN) onto their message instead of
+// the generic inbound pipeline. Every inbound service that parses mail needs
+// it; otherwise a reply parsed by that process would be handled as loose mail.
+func attachThreadRouter(svc *inbound.Service, db *gorm.DB, cfg *config.Config, producer *worker.Producer) {
+ if !cfg.MessagesEnabled || cfg.MessagesInboundDomain == "" {
+ return
+ }
+ router := messages.NewThreadRouter(repositories.NewMessageRepository(db), cfg.MessagesInboundDomain)
+ router.SetRealtime(realtime.NewRedis(cfg.Redis.Client))
+ if producer != nil {
+ router.SetEnqueuer(producer)
+ }
+ svc.SetThreadRouter(router)
+}
+
// startInboundSMTPServer configures and launches the built-in SMTP receiver.
// Returns the server so it can be gracefully shut down on exit.
func startInboundSMTPServer(
@@ -525,7 +544,9 @@ func startEmbeddedWorker(db *gorm.DB,
cfg.AppWebURL,
)
messageHandler.OnNotified(metrics.IncrementMessageNotification)
+ messageHandler.SetRealtime(realtime.NewRedis(cfg.Redis.Client))
mux.HandleFunc(worker.TypeMessageProcess, messageHandler.ProcessTask)
+ mux.HandleFunc(worker.TypeMessageReply, messageHandler.ProcessReplyTask)
}
workermon.StartHeartbeat(context.Background(), cfg.Redis.Client, config.Version, config.CommitID)
@@ -599,6 +620,7 @@ func initCronManager(
retentionJob.SetNotificationRepo(repositories.NewNotificationRepository(db))
if cfg.MessagesEnabled {
retentionJob.SetMessageRepo(repositories.NewMessageRepository(db))
+ retentionJob.SetFormRepo(repositories.NewFormRepository(db))
manager.Register(jobs.NewMessageDigestJob(
notifier,
repositories.NewFormRepository(db),
diff --git a/cmd/posta/worker.go b/cmd/posta/worker.go
index 87d9ef5..a1a0325 100644
--- a/cmd/posta/worker.go
+++ b/cmd/posta/worker.go
@@ -32,6 +32,7 @@ import (
"github.com/goposta/posta/internal/services/eventbus"
"github.com/goposta/posta/internal/services/inbound"
"github.com/goposta/posta/internal/services/notification"
+ "github.com/goposta/posta/internal/services/realtime"
"github.com/goposta/posta/internal/services/tracking"
"github.com/goposta/posta/internal/services/workermon"
"github.com/goposta/posta/internal/storage/blob"
@@ -201,6 +202,7 @@ func runWorker() error {
}
parseSvc.SetEnqueuer(parseProducer)
parseSvc.SetEventBus(parseBus)
+ attachThreadRouter(parseSvc, db, cfg, parseProducer)
parseHandler := worker.NewInboundParseHandler(
repositories.NewInboundEmailRepository(db),
parseSvc,
@@ -219,7 +221,9 @@ func runWorker() error {
cfg.AppWebURL,
)
messageHandler.OnNotified(metrics.IncrementMessageNotification)
+ messageHandler.SetRealtime(realtime.NewRedis(cfg.Redis.Client))
mux.HandleFunc(worker.TypeMessageProcess, messageHandler.ProcessTask)
+ mux.HandleFunc(worker.TypeMessageReply, messageHandler.ProcessReplyTask)
}
// Publish worker's build info
diff --git a/docs/docs/messages/replying.md b/docs/docs/messages/replying.md
index c0cb04d..ef86da1 100644
--- a/docs/docs/messages/replying.md
+++ b/docs/docs/messages/replying.md
@@ -50,7 +50,16 @@ Reply-To: msg+<thread_token>@<inbound_domain>
so the sender's email answer routes back onto the same thread instead of into someone's personal mailbox. Without it, replies are one-directional: the visitor's answer goes wherever the `reply_from` mailbox points.
-Replies also set `In-Reply-To` and `References` from the thread's root message id, so mail clients group the conversation.
+The inbound domain must be a verified domain of the same workspace, because the answer arrives through the normal inbound pipeline. When it does:
+
+- it is attached to the thread as a reply marked **Replied by email**, the message moves back to `open` and becomes unread, and the inbound email is marked `forwarded` instead of firing `email.inbound`;
+- the assignee is notified, or the form's usual recipients when nobody is assigned;
+- an answer from an address other than the original sender is still attached, but flagged **Different sender**: it may be a forward, or someone using a leaked thread address;
+- a thread address only routes within its own workspace.
+
+Every reply gets its own `Message-ID` on the sending domain. The first one becomes the thread root, and later replies set `In-Reply-To` to the latest message on the thread and `References` to the root plus the most recent replies, so mail clients group the whole conversation, both directions included.
+
+These headers are set by Posta itself, so they apply whether or not custom headers are enabled on the platform.
## Message state
@@ -72,10 +81,12 @@ Set it with `PUT /workspaces/current/messages/{id}/state`, and assign a message
|-------|------------|
| `message.received` | A submission passes scanning (`received` or `flagged`). |
| `message.spam` | A submission is quarantined or rejected. |
+| `message.replied` | An operator reply is sent from the dashboard or the API. |
+| `message.reply_received` | The sender answers a thread by email (see [Threading](#threading)). |
Subscribe under **Developers → Webhooks**. The payload carries the full submission, the scan verdict, and the reasons behind it — see [event types](../webhooks/event-types.md).
-The dashboard also streams `message.*` events over `GET /workspaces/current/message-stream` (SSE), which is what makes the inbox update live.
+The dashboard also streams `message.*` events over `GET /workspaces/current/message-stream` (SSE), which is what makes the inbox and an open thread update live. Events go through Redis, so they reach the dashboard whichever server replica it is connected to, including events raised by a separate worker process.
## Retention
@@ -84,4 +95,6 @@ The dashboard also streams `message.*` events over `GET /workspaces/current/mess
| `message_retention_days` | `365` | All messages, plus their attachment blobs. |
| `message_spam_retention_days` | `30` | Quarantined and rejected messages. |
-Both are platform settings swept by the `retention` cron job. A form's own `retention_days` can shorten the window for that form.
+Both are platform settings swept by the `retention` cron job. A form's own `retention_days` can shorten the window for that form; it cannot extend it past `message_retention_days`.
+
+To erase one person's messages on request, use **Workspace settings → Data Management (GDPR) → Delete Message Data**, or `POST /workspaces/current/gdpr/delete-messages` with `{"email": "..."}`. It removes every message from that address, its thread replies, the inbound emails those replies arrived as, and all attachments. API keys need the `admin` scope for every `/gdpr/*` route.
diff --git a/docs/docs/webhooks/event-types.md b/docs/docs/webhooks/event-types.md
index 0abd9ee..df588e4 100644
--- a/docs/docs/webhooks/event-types.md
+++ b/docs/docs/webhooks/event-types.md
@@ -22,6 +22,8 @@ description: Available webhook event types
|-------|-------------|
| `message.received` | A web form submission passed scanning (see [Web Form Messages](#web-form-messages)) |
| `message.spam` | A web form submission was quarantined or rejected by scanning |
+| `message.replied` | An operator replied to a web form message |
+| `message.reply_received` | The sender answered a web form thread by email |
## Campaign Events
@@ -175,4 +177,28 @@ For configuring inbound routing and managing received messages, see the Inbound
`sender_phone` is present only when the form submitted one. `status` is `received` or `flagged` for `message.received`, and `quarantined` for `message.spam`. Submissions scored past the reject threshold are stored for audit but never dispatched.
+### `message.replied` and `message.reply_received`
+
+Both carry one thread reply. `kind` is `operator` for `message.replied` and `inbound` for `message.reply_received`:
+
+```json
+{
+ "event": "message.reply_received",
+ "timestamp": "2026-01-02T09:00:01Z",
+ "message_id": "b0b1c2d3-...",
+ "reply_id": "7c1e9a40-...",
+ "form_id": "3f9a7d12-...",
+ "form_name": "Contact form",
+ "kind": "inbound",
+ "from": "[email protected]",
+ "subject": "Re: Question about pricing",
+ "text_body": "Thanks, that answers it.",
+ "sender_mismatch": false,
+ "created_at": "2026-01-02T09:00:00Z"
+}
+```
+
+`message_id` is the thread's original submission. An operator reply also carries `email_id`, the outbound email whose delivery status is in the email log. `sender_mismatch` is `true` when an emailed answer came from an address other than the original submitter.
+
For configuring forms and replying to submissions, see the Forms & Messages section in the sidebar.
diff --git a/internal/cron/jobs/retention.go b/internal/cron/jobs/retention.go
index e42d977..61d34e5 100644
--- a/internal/cron/jobs/retention.go
+++ b/internal/cron/jobs/retention.go
@@ -42,6 +42,7 @@ type RetentionCleanupJob struct {
trackingRepo *repositories.TrackingRepository
inboundEmailRepo *repositories.InboundEmailRepository
messageRepo *repositories.MessageRepository
+ formRepo *repositories.FormRepository
notificationRepo *repositories.NotificationRepository
blobStore blob.Store
settings *settings.Provider
@@ -73,6 +74,11 @@ func (j *RetentionCleanupJob) SetMessageRepo(r *repositories.MessageRepository)
j.messageRepo = r
}
+// SetFormRepo enables per-form message retention (Form.RetentionDays).
+func (j *RetentionCleanupJob) SetFormRepo(r *repositories.FormRepository) {
+ j.formRepo = r
+}
+
// SetNotificationRepo enables pruning of the in-app inbox. Only settled items
// are dropped; an unresolved, undismissed notification is still true however old
// it is, so age alone never removes it.
@@ -381,6 +387,15 @@ func (j *RetentionCleanupJob) cleanupMessages() {
if days := j.settings.MessageSpamRetentionDays(); days > 0 {
before := time.Now().AddDate(0, 0, -days)
+ if j.blobStore != nil {
+ if jsons, err := j.messageRepo.SpamAttachmentKeysOlderThan(before); err == nil {
+ if n := j.deleteInboundAttachmentBlobs(jsons); n > 0 {
+ logger.Info("retention cleanup: deleted spam message attachment blobs", "count", n)
+ }
+ } else {
+ logger.Error("retention cleanup: failed to enumerate spam message attachments", "error", err)
+ }
+ }
if deleted, err := j.messageRepo.DeleteSpamOlderThan(before); err != nil {
logger.Error("retention cleanup: failed to delete spam messages", "error", err)
} else if deleted > 0 {
@@ -389,6 +404,7 @@ func (j *RetentionCleanupJob) cleanupMessages() {
}
days := j.settings.MessageRetentionDays()
+ j.cleanupFormMessages(days)
if days <= 0 {
return
}
@@ -410,3 +426,46 @@ func (j *RetentionCleanupJob) cleanupMessages() {
logger.Info("retention cleanup: deleted old messages", "count", deleted, "older_than_days", days)
}
}
+
+// formRetentionDays is the window that applies to one form's messages. A form
+// can shorten retention below the platform setting but never extend it past
+// that ceiling; 0 means the form sets no window of its own.
+func formRetentionDays(form, platform int) int {
+ if form <= 0 {
+ return 0
+ }
+ return minDays(form, platform)
+}
+
+// cleanupFormMessages applies each form's own retention window before the
+// platform-wide pass.
+func (j *RetentionCleanupJob) cleanupFormMessages(platformDays int) {
+ if j.formRepo == nil {
+ return
+ }
+ forms, err := j.formRepo.FindWithRetention()
+ if err != nil {
+ logger.Error("retention cleanup: failed to list forms with retention", "error", err)
+ return
+ }
+ for _, form := range forms {
+ days := formRetentionDays(form.RetentionDays, platformDays)
+ if days <= 0 {
+ continue
+ }
+ before := time.Now().AddDate(0, 0, -days)
+ if j.blobStore != nil {
+ if jsons, err := j.messageRepo.AttachmentKeysByFormOlderThan(form.ID, before); err == nil {
+ j.deleteInboundAttachmentBlobs(jsons)
+ } else {
+ logger.Error("retention cleanup: failed to enumerate form message attachments", "form_id", form.ID, "error", err)
+ continue
+ }
+ }
+ if deleted, err := j.messageRepo.DeleteByFormOlderThan(form.ID, before); err != nil {
+ logger.Error("retention cleanup: failed to delete form messages", "form_id", form.ID, "error", err)
+ } else if deleted > 0 {
+ logger.Info("retention cleanup: deleted form messages", "form_id", form.ID, "count", deleted, "older_than_days", days)
+ }
+ }
+}
diff --git a/internal/cron/jobs/retention_test.go b/internal/cron/jobs/retention_test.go
index 4548fd8..6341e70 100644
--- a/internal/cron/jobs/retention_test.go
+++ b/internal/cron/jobs/retention_test.go
@@ -60,3 +60,21 @@ func TestMinDays(t *testing.T) {
}
}
}
+
+// formRetentionDays encodes "a form can shorten retention, never extend it".
+func TestFormRetentionDays(t *testing.T) {
+ cases := []struct {
+ form, platform, want int
+ }{
+ {form: 7, platform: 90, want: 7}, // form shorter → form wins
+ {form: 365, platform: 90, want: 90}, // form longer → clamped to the platform ceiling
+ {form: 30, platform: 0, want: 30}, // platform keeps forever → form bounds
+ {form: 0, platform: 90, want: 0}, // form sets nothing → no per-form pass
+ {form: -1, platform: 90, want: 0}, // nonsense → no per-form pass
+ }
+ for _, c := range cases {
+ if got := formRetentionDays(c.form, c.platform); got != c.want {
+ t.Errorf("formRetentionDays(%d, %d) = %d, want %d", c.form, c.platform, got, c.want)
+ }
+ }
+}
diff --git a/internal/dto/webhook_events.go b/internal/dto/webhook_events.go
index 71f9119..0b2d0f7 100644
--- a/internal/dto/webhook_events.go
+++ b/internal/dto/webhook_events.go
@@ -99,6 +99,27 @@ type MessageWebhookEvent struct {
ReceivedAt string `json:"received_at"`
}
+// MessageReplyWebhookEvent is the payload for message.replied (an operator
+// answered from the dashboard) and message.reply_received (the submitter
+// answered the thread by email).
+type MessageReplyWebhookEvent struct {
+ Event string `json:"event"`
+ Timestamp string `json:"timestamp"`
+ MessageID string `json:"message_id"`
+ ReplyID string `json:"reply_id"`
+ FormID string `json:"form_id"`
+ FormName string `json:"form_name"`
+ Kind string `json:"kind" enum:"operator,inbound"`
+ From string `json:"from"`
+ To string `json:"to"`
+ Subject string `json:"subject,omitempty"`
+ TextBody string `json:"text_body,omitempty"`
+ HTMLBody string `json:"html_body,omitempty"`
+ EmailID string `json:"email_id,omitempty" doc:"The outbound email carrying an operator reply, for delivery status."`
+ SenderMismatch bool `json:"sender_mismatch,omitempty" doc:"An inbound reply came from an address other than the original submitter."`
+ CreatedAt string `json:"created_at"`
+}
+
// MessageWebhookField is one submitted form field in a MessageWebhookEvent.
type MessageWebhookField struct {
Key string `json:"key"`
diff --git a/internal/dto/webhook_registry.go b/internal/dto/webhook_registry.go
new file mode 100644
index 0000000..0dfdd6a
--- /dev/null
+++ b/internal/dto/webhook_registry.go
@@ -0,0 +1,58 @@
+// Copyright (c) 2026 Jonas Kaninda.
+//
+// This file is part of Posta.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+//
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package dto
+
+// WebhookEventDef describes one event a webhook can subscribe to.
+type WebhookEventDef struct {
+ Name string
+ Description string
+ Payload any
+}
+
+// WebhookEvents is the single list of subscribable webhook events. The API
+// docs are generated from it, and a test pins the webhook request's enum tag
+// to it, so an event cannot be documented but unsubscribable or the reverse.
+var WebhookEvents = []WebhookEventDef{
+ // Email lifecycle — generic {event, email_id, timestamp} payload.
+ {"email.sent", "Fired when a message is accepted by the destination MTA", WebhookEvent{}},
+ {"email.failed", "Fired when a message permanently fails after retries", WebhookEvent{}},
+ // Inbound mail — full parsed message.
+ {"email.inbound", "Fired when an inbound email is received and parsed", InboundWebhookEvent{}},
+ // Reputation signals — richer recipient-scoped payloads.
+ {"email.unsubscribed", "Fired when a recipient opts out via one-click unsubscribe", UnsubscribeWebhookEvent{}},
+ {"email.complained", "Fired when a recipient marks a message as spam", ComplaintWebhookEvent{}},
+ // Web form messages — full submission plus the scan verdict, and thread replies.
+ {"message.received", "Fired when a web form submission passes scanning", MessageWebhookEvent{}},
+ {"message.spam", "Fired when a web form submission is quarantined or rejected by scanning", MessageWebhookEvent{}},
+ {"message.replied", "Fired when an operator replies to a web form message from the dashboard", MessageReplyWebhookEvent{}},
+ {"message.reply_received", "Fired when the sender answers a web form thread by email", MessageReplyWebhookEvent{}},
+ // Campaign lifecycle — {event, campaign_id, name, timestamp} payload.
+ {"campaign.started", "Fired when a campaign begins sending", CampaignWebhookEvent{}},
+ {"campaign.completed", "Fired when a campaign finishes sending", CampaignWebhookEvent{}},
+}
+
+// WebhookEventNames returns the subscribable event names in registry order.
+func WebhookEventNames() []string {
+ names := make([]string, len(WebhookEvents))
+ for i, e := range WebhookEvents {
+ names[i] = e.Name
+ }
+ return names
+}
diff --git a/internal/handlers/form_handler.go b/internal/handlers/form_handler.go
index 500c90b..af227a0 100644
--- a/internal/handlers/form_handler.go
+++ b/internal/handlers/form_handler.go
@@ -48,6 +48,23 @@ type FormHandler struct {
domainRepo *repositories.DomainRepository
audit *audit.Logger
apiBaseURL string
+ keyCache FormKeyInvalidator
+}
+
+// FormKeyInvalidator drops cached public-key lookups; *messages.Service
+// implements it.
+type FormKeyInvalidator interface {
+ InvalidateFormKey(keys ...string)
+}
+
+// SetKeyCache makes form edits take effect on the public endpoint immediately
+// instead of after the lookup cache expires.
+func (h *FormHandler) SetKeyCache(c FormKeyInvalidator) { h.keyCache = c }
+
+func (h *FormHandler) invalidate(keys ...string) {
+ if h.keyCache != nil {
+ h.keyCache.InvalidateFormKey(keys...)
+ }
}
func NewFormHandler(
@@ -361,6 +378,7 @@ func (h *FormHandler) Update(c *okapi.Context, req *UpdateFormRequest) error {
if err := h.repo.Update(form); err != nil {
return c.AbortInternalServerError("failed to update form")
}
+ h.invalidate(form.PublicKey)
h.log(c, "form.updated", fmt.Sprintf("Form %s updated", form.Name), map[string]any{metaFormID: form.ID})
return ok(c, form)
@@ -377,6 +395,7 @@ func (h *FormHandler) Delete(c *okapi.Context, req *FormIDRequest) error {
if err := h.repo.Delete(form.ID); err != nil {
return c.AbortInternalServerError("failed to delete form")
}
+ h.invalidate(form.PublicKey)
h.log(c, "form.deleted", fmt.Sprintf("Form %s deleted", form.Name), map[string]any{metaFormID: form.ID})
return noContent(c)
}
@@ -394,11 +413,13 @@ func (h *FormHandler) RotateKey(c *okapi.Context, req *FormIDRequest) error {
return c.AbortInternalServerError("failed to generate form key")
}
now := time.Now()
+ oldKey := form.PublicKey
form.PublicKey = key
form.UpdatedAt = &now
if err := h.repo.Update(form); err != nil {
return c.AbortInternalServerError("failed to rotate form key")
}
+ h.invalidate(oldKey, key)
h.log(c, "form.key_rotated", fmt.Sprintf("Form %s key rotated", form.Name), map[string]any{metaFormID: form.ID})
return ok(c, form)
}
diff --git a/internal/handlers/form_ingest_handler.go b/internal/handlers/form_ingest_handler.go
index c48a7ab..4129c09 100644
--- a/internal/handlers/form_ingest_handler.go
+++ b/internal/handlers/form_ingest_handler.go
@@ -96,7 +96,8 @@ func (h *FormIngestHandler) Submit(c *okapi.Context) error {
}
origin := req.Header.Get("Origin")
- if !messages.OriginAllowed(form, origin) {
+ allowlist, strict := form.OriginPolicy()
+ if !messages.OriginAllowed(allowlist, strict, origin) {
return h.respond(c, form, nil, http.StatusForbidden, "origin_not_allowed", "This origin is not allowed to submit to this form.")
}
h.applyCORS(c, form)
@@ -154,7 +155,7 @@ func (h *FormIngestHandler) Submit(c *okapi.Context) error {
return h.respond(c, form, nil, http.StatusInternalServerError, "error", "Submission could not be stored.")
}
- if redirect != "" && messages.RedirectAllowed(form, redirect) {
+ if redirect != "" && messages.RedirectAllowed(form.AllowedOrigins, form.RedirectURL, redirect) {
c.Redirect(http.StatusSeeOther, redirect)
return nil
}
@@ -274,7 +275,8 @@ func (h *FormIngestHandler) parseMultipart(c *okapi.Context, form *models.Form,
func (h *FormIngestHandler) applyCORS(c *okapi.Context, form *models.Form) {
origin := c.Request().Header.Get("Origin")
- if origin == "" || !messages.OriginAllowed(form, origin) {
+ allowlist, strict := form.OriginPolicy()
+ if origin == "" || !messages.OriginAllowed(allowlist, strict, origin) {
return
}
w := c.ResponseWriter()
diff --git a/internal/handlers/gdpr_messages.go b/internal/handlers/gdpr_messages.go
new file mode 100644
index 0000000..ef01a29
--- /dev/null
+++ b/internal/handlers/gdpr_messages.go
@@ -0,0 +1,78 @@
+// Copyright (c) 2026 Jonas Kaninda.
+//
+// This file is part of Posta.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+//
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package handlers
+
+import (
+ "context"
+ "fmt"
+ "strings"
+
+ "github.com/goposta/posta/internal/services/messages"
+ "github.com/goposta/posta/internal/storage/repositories"
+ "github.com/jkaninda/logger"
+ "github.com/jkaninda/okapi"
+)
+
+type GDPRDeleteMessagesRequest struct {
+ Body struct {
+ Email string `json:"email" required:"true" doc:"Sender address whose web form messages, thread replies, and attachments are erased."`
+ } `json:"body"`
+}
+
+// DeleteMessages (GDPR) erases every web form message a person submitted to
+// the workspace, the thread replies on them, the inbound emails those replies
+// came from, and all of their stored attachments.
+func (h *WorkspaceDataHandler) DeleteMessages(c *okapi.Context, req *GDPRDeleteMessagesRequest) error {
+ wsID := uint(c.GetInt("workspace_id"))
+ if wsID == 0 {
+ return c.AbortBadRequest("workspace context required")
+ }
+ email := messages.NormalizeEmail(req.Body.Email)
+ if email == "" || !strings.Contains(email, "@") {
+ return c.AbortBadRequest("a valid email address is required")
+ }
+
+ deleted, blobKeys, err := repositories.EraseMessagesBySender(h.db, wsID, email)
+ if err != nil {
+ return c.AbortInternalServerError("failed to delete messages")
+ }
+
+ // Blobs go after the commit: a failed transaction must leave them in place.
+ if h.blobStore != nil {
+ ctx := context.Background()
+ for _, key := range blobKeys {
+ if err := h.blobStore.Delete(ctx, key); err != nil {
+ logger.Warn("gdpr: failed to delete message blob", "key", key, "error", err)
+ }
+ }
+ }
+
+ if h.audit != nil {
+ // The erased address is deliberately not logged.
+ h.audit.LogCtxScoped(c, wsID, "gdpr.messages_deleted",
+ fmt.Sprintf("Erased %d web form messages for a data subject", deleted),
+ map[string]any{"deleted": deleted})
+ }
+
+ return ok(c, GDPRDeleteResult{
+ Deleted: deleted,
+ Message: fmt.Sprintf("%d messages and their replies deleted", deleted),
+ })
+}
diff --git a/internal/handlers/message_handler.go b/internal/handlers/message_handler.go
index 9fdca5d..ebbcc75 100644
--- a/internal/handlers/message_handler.go
+++ b/internal/handlers/message_handler.go
@@ -31,6 +31,7 @@ import (
"github.com/goposta/posta/internal/services/audit"
"github.com/goposta/posta/internal/services/eventbus"
"github.com/goposta/posta/internal/services/messages"
+ "github.com/goposta/posta/internal/services/realtime"
"github.com/goposta/posta/internal/storage/blob"
"github.com/goposta/posta/internal/storage/repositories"
"github.com/jkaninda/logger"
@@ -50,6 +51,7 @@ type MessageHandler struct {
svc *messages.Service
blobStore blob.Store
bus *eventbus.EventBus
+ realtime realtime.Bus
audit *audit.Logger
}
@@ -66,6 +68,9 @@ func NewMessageHandler(
func (h *MessageHandler) SetBlobStore(bs blob.Store) { h.blobStore = bs }
func (h *MessageHandler) SetEventBus(b *eventbus.EventBus) { h.bus = b }
+// SetRealtime configures the cross-process bus behind the live message stream.
+func (h *MessageHandler) SetRealtime(b realtime.Bus) { h.realtime = b }
+
type MessageListRequest struct {
Page int `query:"page" default:"0"`
Size int `query:"size" default:"20"`
@@ -179,13 +184,14 @@ func (h *MessageHandler) Get(c *okapi.Context, req *MessageIDRequest) error {
if msg.ReadAt == nil {
now := time.Now()
+ if err := h.repo.MarkRead(msg.ID, now); err != nil {
+ return c.AbortInternalServerError("failed to update message")
+ }
msg.ReadAt = &now
if msg.State == models.MessageStateNew {
msg.State = models.MessageStateOpen
}
- if err := h.repo.Update(msg); err != nil {
- return c.AbortInternalServerError("failed to update message")
- }
+ h.publish(c, messages.EventUpdated, msg)
}
return ok(c, msg)
}
@@ -256,7 +262,7 @@ func (h *MessageHandler) Reply(c *okapi.Context, req *ReplyMessageRequest) error
metaMessageID: msg.UUID, metaEmailUUID: reply.EmailUUID,
})
}
- h.publish(c, "message.replied", msg)
+ h.publish(c, messages.EventReplied, msg)
return created(c, reply)
}
@@ -278,19 +284,23 @@ func (h *MessageHandler) UpdateState(c *okapi.Context, req *UpdateMessageStateRe
}
now := time.Now()
+ fields := map[string]any{"state": state, "updated_at": now}
msg.State = state
msg.UpdatedAt = &now
if req.Body.Read != nil {
if *req.Body.Read {
msg.ReadAt = &now
+ fields["read_at"] = now
} else {
msg.ReadAt = nil
+ fields["read_at"] = nil
}
}
- if err := h.repo.Update(msg); err != nil {
+ if err := h.repo.UpdateFields(msg.ID, fields); err != nil {
return c.AbortInternalServerError("failed to update message")
}
hydrate(msg)
+ h.publish(c, messages.EventUpdated, msg)
return ok(c, msg)
}
@@ -305,10 +315,11 @@ func (h *MessageHandler) Assign(c *okapi.Context, req *AssignMessageRequest) err
now := time.Now()
msg.AssignedToID = req.Body.UserID
msg.UpdatedAt = &now
- if err := h.repo.Update(msg); err != nil {
+ if err := h.repo.UpdateFields(msg.ID, map[string]any{"assigned_to_id": req.Body.UserID, "updated_at": now}); err != nil {
return c.AbortInternalServerError("failed to assign message")
}
hydrate(msg)
+ h.publish(c, messages.EventUpdated, msg)
return ok(c, msg)
}
@@ -326,9 +337,12 @@ func (h *MessageHandler) MarkSpam(c *okapi.Context, req *MarkSpamRequest) error
msg.Status = models.MessageStatusQuarantined
msg.State = models.MessageStateSpam
msg.UpdatedAt = &now
- if err := h.repo.Update(msg); err != nil {
+ if err := h.repo.UpdateFields(msg.ID, map[string]any{
+ "status": msg.Status, "state": msg.State, "updated_at": now,
+ }); err != nil {
return c.AbortInternalServerError("failed to update message")
}
+ h.publish(c, messages.EventUpdated, msg)
if req.Body.CreateFilter {
kind := models.FilterKind(req.Body.Kind)
@@ -375,13 +389,18 @@ func (h *MessageHandler) MarkNotSpam(c *okapi.Context, req *MessageIDRequest) er
msg.SpamScore = 0
msg.ScanReasons = nil
msg.UpdatedAt = &now
+ fields := map[string]any{
+ "status": msg.Status, "spam_score": 0, "scan_reasons": nil, "updated_at": now,
+ }
if msg.State == models.MessageStateSpam {
msg.State = models.MessageStateOpen
+ fields["state"] = msg.State
}
- if err := h.repo.Update(msg); err != nil {
+ if err := h.repo.UpdateFields(msg.ID, fields); err != nil {
return c.AbortInternalServerError("failed to update message")
}
hydrate(msg)
+ h.publish(c, messages.EventUpdated, msg)
return ok(c, msg)
}
@@ -444,7 +463,7 @@ func (h *MessageHandler) DownloadAttachment(c *okapi.Context, req *MessageAttach
}
func (h *MessageHandler) Stream(c *okapi.Context) error {
- if h.bus == nil {
+ if h.realtime == nil {
return c.AbortNotFound("message stream not configured")
}
ctx := c.Request().Context()
@@ -454,7 +473,7 @@ func (h *MessageHandler) Stream(c *okapi.Context) error {
}
workspaceID := *scope.WorkspaceID
- ch, unsub := h.bus.Subscribe()
+ ch, unsub := h.realtime.Subscribe(ctx, realtime.WorkspaceTopic(workspaceID))
defer unsub()
msgCh := make(chan okapi.Message, 4)
@@ -479,11 +498,12 @@ func (h *MessageHandler) Stream(c *okapi.Context) error {
if !strings.HasPrefix(evt.Type, "message.") {
continue
}
- if evt.WorkspaceID == nil || *evt.WorkspaceID != workspaceID {
+ // Topics are per workspace already; this is defence in depth.
+ if evt.WorkspaceID != workspaceID {
continue
}
select {
- case msgCh <- okapi.Message{Event: evt.Type, Data: evt}:
+ case msgCh <- okapi.Message{Event: evt.Type, Data: evt.Data}:
case <-ctx.Done():
return
}
@@ -497,8 +517,11 @@ func (h *MessageHandler) Stream(c *okapi.Context) error {
})
}
+// publish sends a message event to the live stream and, for operator actions
+// worth keeping, to the persisted activity log.
func (h *MessageHandler) publish(c *okapi.Context, eventType string, msg *models.Message) {
- if h.bus == nil {
+ messages.PublishEvent(c.Request().Context(), h.realtime, eventType, msg)
+ if h.bus == nil || eventType != messages.EventReplied {
return
}
actor := uint(c.GetInt("user_id"))
diff --git a/internal/handlers/webhook_handler.go b/internal/handlers/webhook_handler.go
index 64608b2..b4691cf 100644
--- a/internal/handlers/webhook_handler.go
+++ b/internal/handlers/webhook_handler.go
@@ -35,8 +35,9 @@ type WebhookHandler struct {
}
type CreateWebhookRequest struct {
Body struct {
- URL string `json:"url" required:"true" format:"url"`
- Events []string `json:"events" required:"true" minItems:"1" enum:"email.sent,email.failed,email.inbound,email.unsubscribed,email.complained,message.received,message.spam,campaign.started,campaign.completed"`
+ URL string `json:"url" required:"true" format:"url"`
+ // The enum must list dto.WebhookEvents in order; TestWebhookEnumMatchesRegistry enforces it.
+ Events []string `json:"events" required:"true" minItems:"1" enum:"email.sent,email.failed,email.inbound,email.unsubscribed,email.complained,message.received,message.spam,message.replied,message.reply_received,campaign.started,campaign.completed"`
Filters []string `json:"filters"`
} `json:"body"`
}
diff --git a/internal/handlers/webhook_registry_test.go b/internal/handlers/webhook_registry_test.go
new file mode 100644
index 0000000..b37c119
--- /dev/null
+++ b/internal/handlers/webhook_registry_test.go
@@ -0,0 +1,59 @@
+// Copyright (c) 2026 Jonas Kaninda.
+//
+// This file is part of Posta.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+//
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package handlers
+
+import (
+ "reflect"
+ "strings"
+ "testing"
+
+ "github.com/goposta/posta/internal/dto"
+)
+
+// TestWebhookEnumMatchesRegistry pins the subscribable events (the enum okapi
+// validates against) to the documented registry. Adding an event to one list
+// but not the other is how message.replied went missing.
+func TestWebhookEnumMatchesRegistry(t *testing.T) {
+ body, ok := reflect.TypeOf(CreateWebhookRequest{}).FieldByName("Body")
+ if !ok {
+ t.Fatal("CreateWebhookRequest has no Body")
+ }
+ events, ok := body.Type.FieldByName("Events")
+ if !ok {
+ t.Fatal("CreateWebhookRequest.Body has no Events")
+ }
+ enum := strings.Split(events.Tag.Get("enum"), ",")
+ if want := dto.WebhookEventNames(); !reflect.DeepEqual(enum, want) {
+ t.Fatalf("enum tag = %v\nregistry = %v", enum, want)
+ }
+}
+
+func TestWebhookRegistryNamesAreUnique(t *testing.T) {
+ seen := map[string]bool{}
+ for _, e := range dto.WebhookEvents {
+ if seen[e.Name] {
+ t.Fatalf("duplicate webhook event %q", e.Name)
+ }
+ seen[e.Name] = true
+ if e.Description == "" || e.Payload == nil {
+ t.Fatalf("event %q needs a description and a payload type", e.Name)
+ }
+ }
+}
diff --git a/internal/handlers/workspace_data_handler.go b/internal/handlers/workspace_data_handler.go
index b67ec0e..1d64006 100644
--- a/internal/handlers/workspace_data_handler.go
+++ b/internal/handlers/workspace_data_handler.go
@@ -25,6 +25,8 @@ import (
"github.com/goposta/posta/internal/config"
"github.com/goposta/posta/internal/models"
+ "github.com/goposta/posta/internal/services/audit"
+ "github.com/goposta/posta/internal/storage/blob"
"github.com/goposta/posta/internal/storage/repositories"
"github.com/jkaninda/okapi"
"gorm.io/gorm"
@@ -46,8 +48,16 @@ type WorkspaceDataHandler struct {
domainRepo *repositories.DomainRepository
subscriberRepo *repositories.SubscriberRepository
subscriberListRepo *repositories.SubscriberListRepository
+ blobStore blob.Store
+ audit *audit.Logger
}
+// SetBlobStore lets GDPR erasure remove stored attachments and raw emails.
+func (h *WorkspaceDataHandler) SetBlobStore(bs blob.Store) { h.blobStore = bs }
+
+// SetAuditLogger records destructive data operations in the audit log.
+func (h *WorkspaceDataHandler) SetAuditLogger(l *audit.Logger) { h.audit = l }
+
func NewWorkspaceDataHandler(
db *gorm.DB,
workspaceRepo *repositories.WorkspaceRepository,
diff --git a/internal/middlewares/message_scope_test.go b/internal/middlewares/message_scope_test.go
index d9a686a..787bfbd 100644
--- a/internal/middlewares/message_scope_test.go
+++ b/internal/middlewares/message_scope_test.go
@@ -69,3 +69,22 @@ func TestReadScopeCannotReachFormConfig(t *testing.T) {
t.Fatal("a read-only key must not be able to enumerate form configuration")
}
}
+
+// GDPR erasure is destructive tenant administration. A workspace-bound key
+// resolves as owner, so without the admin scope a write-only key could erase
+// every contact in the workspace.
+func TestGDPRRoutesRequireAdminScope(t *testing.T) {
+ for _, path := range []string{
+ "/api/v1/workspaces/current/gdpr/delete-contacts",
+ "/api/v1/workspaces/current/gdpr/delete-email-logs",
+ "/api/v1/workspaces/current/gdpr/delete-messages",
+ } {
+ if got := workspaceScopeFor(http.MethodPost, path); got != models.ScopeAdmin {
+ t.Fatalf("workspaceScopeFor(POST %s) = %s, want admin", path, got)
+ }
+ }
+ key := &models.APIKey{Scopes: []string{models.ScopeRead, models.ScopeWrite}}
+ if key.HasScope(workspaceScopeFor(http.MethodPost, "/api/v1/workspaces/current/gdpr/delete-contacts")) {
+ t.Fatal("a read/write key must not reach GDPR erasure")
+ }
+}
diff --git a/internal/middlewares/middleware.go b/internal/middlewares/middleware.go
index d0c69a2..420a72a 100644
--- a/internal/middlewares/middleware.go
+++ b/internal/middlewares/middleware.go
@@ -301,6 +301,7 @@ var tenantAdminPaths = []string{
"/plan",
"/forms",
"/message-filters",
+ "/gdpr/",
}
// workspaceScopeFor returns the scope a workspace-scoped request demands.
diff --git a/internal/models/form.go b/internal/models/form.go
index b9e597e..289c97c 100644
--- a/internal/models/form.go
+++ b/internal/models/form.go
@@ -98,6 +98,38 @@ type Form struct {
func (f *Form) IsActive() bool { return f.Status == FormStatusActive }
+// ScanSource identifies what a submission arrived through, so the scanner can
+// apply that source's filters and count repeat submissions per source.
+type ScanSource struct {
+ Kind string `json:"kind"`
+ ID uint `json:"id"`
+}
+
+// ScanSourceForm is the ScanSource kind of a web form.
+const ScanSourceForm = "form"
+
+// ScanningEnabled, ScanThresholds, and ScanSource make a Form a
+// messagescan.Policy. A nil Form scans with the defaults.
+func (f *Form) ScanningEnabled() bool { return f == nil || f.ScanEnabled }
+
+func (f *Form) ScanThresholds() (flag, quarantine, reject float64) {
+ if f == nil {
+ return 0, 0, 0
+ }
+ return f.FlagThreshold, f.QuarantineThreshold, f.RejectThreshold
+}
+
+func (f *Form) ScanSource() ScanSource {
+ if f == nil {
+ return ScanSource{}
+ }
+ return ScanSource{Kind: ScanSourceForm, ID: f.ID}
+}
+
+// OriginPolicy returns the origin allowlist and whether a missing Origin is
+// refused, for messages.OriginAllowed and RedirectAllowed.
+func (f *Form) OriginPolicy() ([]string, bool) { return f.AllowedOrigins, f.StrictOrigin }
+
func (f *Form) Honeypot() string {
if f.HoneypotField == "" {
return DefaultHoneypotField
diff --git a/internal/models/message.go b/internal/models/message.go
index bf61af5..150dda0 100644
--- a/internal/models/message.go
+++ b/internal/models/message.go
@@ -92,6 +92,11 @@ type Message struct {
RepliedAt *time.Time `json:"replied_at,omitempty"`
ReplyCount int `json:"reply_count" gorm:"default:0;not null"`
+ // WebhookDispatchedAt records that message:process handed the submission to
+ // the webhook dispatcher, so a retried task never fires the webhook twice.
+ // Delivery itself is tracked in webhook_deliveries.
+ WebhookDispatchedAt *time.Time `json:"-"`
+
CreatedAt time.Time `json:"created_at" gorm:"index"`
UpdatedAt *time.Time `json:"updated_at,omitempty"`
DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
@@ -99,9 +104,12 @@ type Message struct {
Fields []MessageField `json:"fields,omitempty" gorm:"-"`
Attachments []InboundAttachmentMeta `json:"attachments,omitempty" gorm:"-"`
- Form *Form `json:"form,omitempty" gorm:"foreignKey:FormID;constraint:false"`
+ // GORM creates these foreign keys whatever the tag (only "constraint:-"
+ // skips one), so declare the cascade the schema relies on: deleting a form
+ // or a message must take its messages or replies with it.
+ Form *Form `json:"form,omitempty" gorm:"foreignKey:FormID;constraint:OnDelete:CASCADE"`
AssignedTo *ActorRef `json:"assigned_to,omitempty" gorm:"->;foreignKey:AssignedToID;references:ID;constraint:false"`
- Replies []MessageReply `json:"replies,omitempty" gorm:"foreignKey:MessageID"`
+ Replies []MessageReply `json:"replies,omitempty" gorm:"foreignKey:MessageID;constraint:OnDelete:CASCADE"`
}
func (m *Message) IsSpam() bool {
@@ -119,7 +127,9 @@ type MessageReply struct {
WorkspaceID *uint `json:"workspace_id,omitempty" gorm:"index;not null"`
Kind MessageReplyKind `json:"kind" gorm:"type:varchar(16);not null"`
- AuthorID uint `json:"author_id" gorm:"index"`
+ // AuthorID is the operator who wrote an outbound reply; nil for an inbound
+ // reply. It must stay nullable: author_id carries a foreign key to users.
+ AuthorID *uint `json:"author_id,omitempty" gorm:"index"`
FromAddr string `json:"from_addr"`
ToAddr string `json:"to_addr"`
Subject string `json:"subject"`
@@ -129,6 +139,13 @@ type MessageReply struct {
EmailUUID string `json:"email_uuid,omitempty" gorm:"index"`
InboundEmailID *uint `json:"inbound_email_id,omitempty" gorm:"index"`
+ // MessageIDHeader is the RFC 5322 Message-ID this reply was sent or received
+ // with. Later replies chain to it through In-Reply-To and References.
+ MessageIDHeader string `json:"-"`
+ // SenderMismatch marks an inbound reply whose sender is not the original
+ // submitter: a forward, or a spoof using a leaked thread address.
+ SenderMismatch bool `json:"sender_mismatch,omitempty" gorm:"default:false;not null"`
+
CreatedAt time.Time `json:"created_at"`
Author *ActorRef `json:"author,omitempty" gorm:"->;foreignKey:AuthorID;references:ID;constraint:false"`
diff --git a/internal/routes/routes.go b/internal/routes/routes.go
index adb1c8f..483ad1a 100644
--- a/internal/routes/routes.go
+++ b/internal/routes/routes.go
@@ -42,6 +42,7 @@ import (
"github.com/goposta/posta/internal/services/passwordreset"
planpkg "github.com/goposta/posta/internal/services/plan"
"github.com/goposta/posta/internal/services/ratelimit"
+ "github.com/goposta/posta/internal/services/realtime"
"github.com/goposta/posta/internal/services/seeder"
sessionpkg "github.com/goposta/posta/internal/services/session"
"github.com/goposta/posta/internal/services/settings"
@@ -409,6 +410,14 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *c
inboundSvc.SetEnqueuer(producer)
}
inboundSvc.SetEventBus(bus)
+ if cfg.MessagesEnabled && cfg.MessagesInboundDomain != "" {
+ router := messages.NewThreadRouter(repositories.NewMessageRepository(db), cfg.MessagesInboundDomain)
+ router.SetRealtime(realtime.NewRedis(redisClient))
+ if producer != nil {
+ router.SetEnqueuer(producer)
+ }
+ inboundSvc.SetThreadRouter(router)
+ }
inboundSvc.OnReceived(func(src models.InboundSource) { metrics.IncrementInboundReceived(string(src)) })
inboundSvc.OnRejected(metrics.IncrementInboundRejected)
inboundSvc.OnBytes(metrics.AddInboundBytes)
@@ -447,7 +456,6 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *c
[]byte(cfg.JWTSecret),
)
messageSvc.SetEmailService(emailService)
- messageSvc.SetEventBus(bus)
if producer != nil {
messageSvc.SetEnqueuer(producer)
}
@@ -459,8 +467,10 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *c
})
r.h.form = handlers.NewFormHandler(formRepo, messageRepo, domainRepo, auditLogger, cfg.ApiBaseURL)
+ r.h.form.SetKeyCache(messageSvc)
r.h.message = handlers.NewMessageHandler(messageRepo, formRepo, messageFilterRepo, messageSvc, auditLogger)
r.h.message.SetEventBus(bus)
+ r.h.message.SetRealtime(realtime.NewRedis(redisClient))
r.h.messageFilter = handlers.NewMessageFilterHandler(messageFilterRepo, messageRepo, formRepo, messageSvc.Scanner())
r.h.formIngest = handlers.NewFormIngestHandler(
messageSvc,
@@ -487,6 +497,10 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *c
webhookRepo, suppressionRepo, smtpRepo, domainRepo,
subscriberRepo, subscriberListRepo,
)
+ r.h.workspaceData.SetAuditLogger(auditLogger)
+ if blobStore != nil {
+ r.h.workspaceData.SetBlobStore(blobStore)
+ }
// Auto-seed Google provider if configured
if cfg.GoogleOAuthClientID != "" {
diff --git a/internal/routes/webhook_docs.go b/internal/routes/webhook_docs.go
index e579f47..5e227c9 100644
--- a/internal/routes/webhook_docs.go
+++ b/internal/routes/webhook_docs.go
@@ -45,22 +45,7 @@ func (r *Router) registerWebhookDocs() {
)
}
- // Email lifecycle — generic {event, email_id, timestamp} payload.
- webhook("email.sent", "Fired when a message is accepted by the destination MTA", dto.WebhookEvent{})
- webhook("email.failed", "Fired when a message permanently fails after retries", dto.WebhookEvent{})
-
- // Reputation signals — richer recipient-scoped payloads.
- webhook("email.complained", "Fired when a recipient marks a message as spam", dto.ComplaintWebhookEvent{})
- webhook("email.unsubscribed", "Fired when a recipient opts out via one-click unsubscribe", dto.UnsubscribeWebhookEvent{})
-
- // Inbound mail — full parsed message.
- webhook("email.inbound", "Fired when an inbound email is received and parsed", dto.InboundWebhookEvent{})
-
- // Web form messages — full submission plus the scan verdict.
- webhook("message.received", "Fired when a web form submission passes scanning", dto.MessageWebhookEvent{})
- webhook("message.spam", "Fired when a web form submission is quarantined or rejected by scanning", dto.MessageWebhookEvent{})
-
- // Campaign lifecycle — {event, campaign_id, name, timestamp} payload.
- webhook("campaign.started", "Fired when a campaign begins sending", dto.CampaignWebhookEvent{})
- webhook("campaign.completed", "Fired when a campaign finishes sending", dto.CampaignWebhookEvent{})
+ for _, e := range dto.WebhookEvents {
+ webhook(e.Name, e.Description, e.Payload)
+ }
}
diff --git a/internal/routes/workspace_routes.go b/internal/routes/workspace_routes.go
index b8fcb1e..7d26610 100644
--- a/internal/routes/workspace_routes.go
+++ b/internal/routes/workspace_routes.go
@@ -319,6 +319,18 @@ func (r *Router) workspaceRoutes() []okapi.RouteDefinition {
Response: &dto.Response[handlers.GDPRDeleteResult]{},
Options: []okapi.RouteOption{workspaceHeaderRequired},
},
+ {
+ Method: http.MethodPost,
+ Path: "/gdpr/delete-messages",
+ Handler: okapi.H(r.h.workspaceData.DeleteMessages),
+ Group: wsGroup,
+ Middlewares: []okapi.Middleware{middlewares.RequireWorkspaceRole(models.WorkspaceRoleAdmin)},
+ Summary: "Delete a person's web form messages (GDPR)",
+ Description: "Erase every web form message submitted from an address, with its thread replies, the inbound emails those replies arrived as, and all stored attachments.",
+ Request: &handlers.GDPRDeleteMessagesRequest{},
+ Response: &dto.Response[handlers.GDPRDeleteResult]{},
+ Options: []okapi.RouteOption{workspaceHeaderRequired},
+ },
}...)
// User-level invitation actions (no workspace context needed)
diff --git a/internal/services/email/headers_test.go b/internal/services/email/headers_test.go
new file mode 100644
index 0000000..cead457
--- /dev/null
+++ b/internal/services/email/headers_test.go
@@ -0,0 +1,83 @@
+// Copyright (c) 2026 Jonas Kaninda.
+//
+// This file is part of Posta.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+//
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package email
+
+import (
+ "encoding/json"
+ "testing"
+)
+
+// System headers carry form-reply threading. They must survive with custom
+// headers disabled (the default), or every queued reply loses its Reply-To.
+func TestOutboundHeadersKeepSystemHeadersWhenCustomDisabled(t *testing.T) {
+ req := &SendRequest{
+ Headers: map[string]string{"X-Custom": "1"},
+ SystemHeaders: map[string]string{"Reply-To": "[email protected]", "Message-ID": "<a@b>"},
+ }
+ got := outboundHeaders(req, false)
+ if got["Reply-To"] != "[email protected]" || got["Message-ID"] != "<a@b>" {
+ t.Fatalf("system headers lost: %v", got)
+ }
+ if _, ok := got["X-Custom"]; ok {
+ t.Fatal("custom headers must not be sent while the platform disables them")
+ }
+}
+
+func TestOutboundHeadersFilterCustomWhenEnabled(t *testing.T) {
+ req := &SendRequest{Headers: map[string]string{"X-Custom": "1", "From": "[email protected]", "X-Posta-Internal": "x"}}
+ got := outboundHeaders(req, true)
+ if got["X-Custom"] != "1" {
+ t.Fatalf("allowed custom header dropped: %v", got)
+ }
+ if _, ok := got["From"]; ok {
+ t.Fatal("a reserved header must be filtered")
+ }
+ if _, ok := got["X-Posta-Internal"]; ok {
+ t.Fatal("a blocked-prefix header must be filtered")
+ }
+}
+
+func TestOutboundHeadersSystemWinsCaseInsensitively(t *testing.T) {
+ req := &SendRequest{
+ Headers: map[string]string{"reply-to": "[email protected]"},
+ SystemHeaders: map[string]string{"Reply-To": "[email protected]"},
+ }
+ got := outboundHeaders(req, true)
+ if len(got) != 1 || got["Reply-To"] != "[email protected]" {
+ t.Fatalf("got %v, want only the system Reply-To", got)
+ }
+}
+
+func TestOutboundHeadersNilWhenNothingToSend(t *testing.T) {
+ if got := outboundHeaders(&SendRequest{Headers: map[string]string{"X-A": "1"}}, false); got != nil {
+ t.Fatalf("got %v, want nil", got)
+ }
+}
+
+// API callers must not be able to set system headers.
+func TestSystemHeadersAreNotDecodedFromJSON(t *testing.T) {
+ var req SendRequest
+ if err := json.Unmarshal([]byte(`{"SystemHeaders":{"Reply-To":"[email protected]"},"system_headers":{"Reply-To":"[email protected]"}}`), &req); err != nil {
+ t.Fatal(err)
+ }
+ if len(req.SystemHeaders) != 0 {
+ t.Fatalf("SystemHeaders decoded from JSON: %v", req.SystemHeaders)
+ }
+}
diff --git a/internal/services/email/service.go b/internal/services/email/service.go
index db7f2fa..6b2cb2a 100644
--- a/internal/services/email/service.go
+++ b/internal/services/email/service.go
@@ -319,7 +319,12 @@ type SendRequest struct {
Text string `json:"text"`
Attachments []models.Attachment `json:"attachments,omitempty" doc:"Optional file attachments. Each must include filename, content_type, and base64-encoded content. Subject to per-attachment and total size limits set by your plan."`
Headers map[string]string `json:"headers,omitempty"`
- Unsubscribe *Unsubscribe `json:"unsubscribe,omitempty"`
+ // SystemHeaders are headers Posta itself sets on internal sends, such as the
+ // Message-ID, In-Reply-To, and Reply-To that thread a form reply. They are
+ // never accepted from API callers and apply whether or not the platform
+ // allows custom headers.
+ SystemHeaders map[string]string `json:"-"`
+ Unsubscribe *Unsubscribe `json:"unsubscribe,omitempty"`
// Deprecated: use Unsubscribe. Kept for one minor release; mapped onto
// Unsubscribe{URL, OneClick} in resolveUnsubscribe.
ListUnsubscribeURL string `json:"list_unsubscribe_url,omitempty" deprecated:"true"`
@@ -734,14 +739,14 @@ func (s *Service) Send(ctx context.Context, userID, apiKeyID uint, workspaceID *
req.Text = HTMLToText(req.HTML)
}
- // Serialize custom headers for storage (only when the setting is enabled)
+ // Resolve the headers once; the async worker reads them back from the row
+ // and the sync path sends them directly, so both paths agree.
+ customEnabled := s.settings != nil && s.settings.CustomHeadersEnabled()
+ req.Headers = outboundHeaders(req, customEnabled)
var headersJSON string
- if len(req.Headers) > 0 && s.settings != nil && s.settings.CustomHeadersEnabled() {
- filtered := filterCustomHeaders(req.Headers)
- if len(filtered) > 0 {
- b, _ := json.Marshal(filtered)
- headersJSON = string(b)
- }
+ if len(req.Headers) > 0 {
+ b, _ := json.Marshal(req.Headers)
+ headersJSON = string(b)
}
var apiKeyPtr *uint
@@ -1340,6 +1345,30 @@ func diffRecipients(original, filtered []string) []string {
return diff
}
+// outboundHeaders returns the headers a message is sent with: the caller's
+// custom headers, filtered, when the platform allows them, plus the system
+// headers Posta set itself, which always apply and win on conflict.
+func outboundHeaders(req *SendRequest, customEnabled bool) map[string]string {
+ out := map[string]string{}
+ if customEnabled {
+ for k, v := range filterCustomHeaders(req.Headers) {
+ out[k] = v
+ }
+ }
+ for k, v := range req.SystemHeaders {
+ for existing := range out {
+ if strings.EqualFold(existing, k) {
+ delete(out, existing)
+ }
+ }
+ out[k] = v
+ }
+ if len(out) == 0 {
+ return nil
+ }
+ return out
+}
+
// filterCustomHeaders removes headers that could conflict with system-set
// headers or be used for spoofing. It returns a sanitized copy.
//
diff --git a/internal/services/inbound/service.go b/internal/services/inbound/service.go
index e9746d1..a47d459 100644
--- a/internal/services/inbound/service.go
+++ b/internal/services/inbound/service.go
@@ -62,6 +62,13 @@ type Enqueuer interface {
EnqueueInboundParse(inboundEmailID uint) error
}
+// ThreadRouter attaches an inbound email to an existing conversation (a web
+// form thread) when one of its recipients is that conversation's reply
+// address. It reports false when no recipient matched.
+type ThreadRouter interface {
+ RouteReply(ctx context.Context, rec *models.InboundEmail, recipients []string) (bool, error)
+}
+
type Service struct {
repo *repositories.InboundEmailRepository
domainRepo *repositories.DomainRepository
@@ -69,6 +76,7 @@ type Service struct {
blobStore blob.Store
producer Enqueuer
bus *eventbus.EventBus
+ threadRouter ThreadRouter
maxMsgSize int64
maxAttachSize int64
onReceived func(source models.InboundSource)
@@ -108,6 +116,49 @@ func (s *Service) SetEnqueuer(eq Enqueuer) { s.producer = eq }
// SetEventBus configures the event bus used to publish inbound.received events.
func (s *Service) SetEventBus(b *eventbus.EventBus) { s.bus = b }
+// SetThreadRouter enables routing replies to thread addresses onto their
+// conversation instead of the generic inbound pipeline.
+func (s *Service) SetThreadRouter(r ThreadRouter) { s.threadRouter = r }
+
+// RouteThread offers rec to the thread router. When the email is attached to a
+// thread it is marked forwarded and the caller must not run the generic
+// email.inbound processing for it. A router failure is logged and the email
+// falls back to ordinary inbound handling, so it is never lost.
+func (s *Service) RouteThread(ctx context.Context, rec *models.InboundEmail, candidates ...[]string) bool {
+ if s.threadRouter == nil || rec == nil {
+ return false
+ }
+ routed, err := s.threadRouter.RouteReply(ctx, rec, uniqueAddresses(candidates...))
+ if err != nil {
+ logger.Error("thread routing failed; handling as ordinary inbound", "inbound_id", rec.UUID, "error", err)
+ return false
+ }
+ if !routed {
+ return false
+ }
+ rec.Status = models.InboundStatusForwarded
+ if err := s.repo.Update(rec); err != nil {
+ logger.Error("failed to mark thread reply forwarded", "inbound_id", rec.UUID, "error", err)
+ }
+ return true
+}
+
+func uniqueAddresses(lists ...[]string) []string {
+ seen := map[string]bool{}
+ var out []string
+ for _, list := range lists {
+ for _, a := range list {
+ key := strings.ToLower(strings.TrimSpace(a))
+ if key == "" || seen[key] {
+ continue
+ }
+ seen[key] = true
+ out = append(out, a)
+ }
+ }
+ return out
+}
+
// OnReceived sets a callback invoked after each successfully ingested inbound message.
func (s *Service) OnReceived(fn func(source models.InboundSource)) { s.onReceived = fn }
@@ -242,7 +293,9 @@ func (s *Service) Ingest(ctx context.Context, p *ParsedEmail, source models.Inbo
}
}
- if s.producer != nil {
+ routed := s.RouteThread(ctx, rec, recipients, p.Cc)
+
+ if s.producer != nil && !routed {
if err := s.producer.EnqueueInboundProcess(rec.ID); err != nil {
logger.Error("failed to enqueue inbound:process", "inbound_id", rec.ID, "error", err)
}
diff --git a/internal/services/messages/events.go b/internal/services/messages/events.go
new file mode 100644
index 0000000..7a3ba32
--- /dev/null
+++ b/internal/services/messages/events.go
@@ -0,0 +1,59 @@
+// Copyright (c) 2026 Jonas Kaninda.
+//
+// This file is part of Posta.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+//
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package messages
+
+import (
+ "context"
+
+ "github.com/goposta/posta/internal/models"
+ "github.com/goposta/posta/internal/services/realtime"
+ "github.com/jkaninda/logger"
+)
+
+// Live event types on a workspace's message stream.
+const (
+ EventReceived = "message.received"
+ EventUpdated = "message.updated"
+ EventReplied = "message.replied"
+ EventReplyReceived = "message.reply_received"
+)
+
+// PublishEvent sends a message.* event to the workspace's live stream. The
+// payload carries identifiers and status only; the dashboard refetches what it
+// shows, so a dropped event costs freshness, never correctness.
+func PublishEvent(ctx context.Context, bus realtime.Bus, eventType string, msg *models.Message) {
+ if bus == nil || msg == nil || msg.WorkspaceID == nil {
+ return
+ }
+ ev := realtime.Event{
+ Type: eventType,
+ WorkspaceID: *msg.WorkspaceID,
+ Topic: realtime.WorkspaceTopic(*msg.WorkspaceID),
+ Data: map[string]any{
+ "message_id": msg.UUID,
+ "form_id": msg.FormID,
+ "status": msg.Status,
+ "state": msg.State,
+ },
+ }
+ if err := bus.Publish(ctx, ev); err != nil {
+ logger.Warn("failed to publish message event", "type", eventType, "message_id", msg.ID, "error", err)
+ }
+}
diff --git a/internal/services/messages/formcache.go b/internal/services/messages/formcache.go
new file mode 100644
index 0000000..8bf59f1
--- /dev/null
+++ b/internal/services/messages/formcache.go
@@ -0,0 +1,97 @@
+// Copyright (c) 2026 Jonas Kaninda.
+//
+// This file is part of Posta.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+//
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package messages
+
+import (
+ "context"
+ "errors"
+ "time"
+
+ "github.com/goposta/posta/internal/models"
+ "gorm.io/gorm"
+)
+
+// Public form lookups are cached because every submission, nonce request, and
+// CORS preflight resolves a form by its public key. A status change therefore
+// takes up to formCacheTTL to apply unless the editor invalidates the key,
+// which the form handler does on every update, rotation, and delete.
+const (
+ formCacheTTL = 60 * time.Second
+ formMissTTL = 30 * time.Second
+ formCachePrefix = "form:pk:"
+)
+
+// formCacheEntry is what is stored per key. Unknown keys are cached too, so a
+// scan of random keys does not reach Postgres on every request.
+type formCacheEntry struct {
+ Missing bool `json:"missing,omitempty"`
+ Form *models.Form `json:"form,omitempty"`
+}
+
+// formKeyCache is satisfied by *cache.Cache.
+type formKeyCache interface {
+ Get(ctx context.Context, key string, dest any) bool
+ Set(ctx context.Context, key string, value any, ttl time.Duration)
+ Delete(ctx context.Context, key string)
+}
+
+// FindFormByKey resolves a form from its public key, through the cache.
+func (s *Service) FindFormByKey(key string) (*models.Form, error) {
+ ctx := context.Background()
+ if s.formCache != nil && key != "" {
+ var entry formCacheEntry
+ if s.formCache.Get(ctx, formCachePrefix+key, &entry) {
+ if entry.Missing || entry.Form == nil {
+ return nil, ErrFormNotFound
+ }
+ return entry.Form, nil
+ }
+ }
+
+ f, err := s.formRepo.FindByPublicKey(key)
+ if err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ if s.formCache != nil && key != "" {
+ s.formCache.Set(ctx, formCachePrefix+key, formCacheEntry{Missing: true}, formMissTTL)
+ }
+ return nil, ErrFormNotFound
+ }
+ return nil, err
+ }
+ if s.formCache != nil {
+ f.LastEditedBy = nil
+ s.formCache.Set(ctx, formCachePrefix+key, formCacheEntry{Form: f}, formCacheTTL)
+ }
+ return f, nil
+}
+
+// InvalidateFormKey drops cached lookups for the given public keys. Call it
+// with both the old and new key when a key rotates.
+func (s *Service) InvalidateFormKey(keys ...string) {
+ if s.formCache == nil {
+ return
+ }
+ ctx := context.Background()
+ for _, k := range keys {
+ if k != "" {
+ s.formCache.Delete(ctx, formCachePrefix+k)
+ }
+ }
+}
diff --git a/internal/services/messages/origin_test.go b/internal/services/messages/origin_test.go
index b10be11..b2307cb 100644
--- a/internal/services/messages/origin_test.go
+++ b/internal/services/messages/origin_test.go
@@ -49,7 +49,8 @@ func TestOriginAllowed(t *testing.T) {
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
form := &models.Form{AllowedOrigins: pq.StringArray(tc.origins), StrictOrigin: tc.strict}
- if got := OriginAllowed(form, tc.origin); got != tc.want {
+ allowlist, strict := form.OriginPolicy()
+ if got := OriginAllowed(allowlist, strict, tc.origin); got != tc.want {
t.Fatalf("OriginAllowed(%q) = %v, want %v", tc.origin, got, tc.want)
}
})
@@ -71,7 +72,7 @@ func TestRedirectAllowedRejectsOpenRedirects(t *testing.T) {
{"", false},
}
for _, tc := range cases {
- if got := RedirectAllowed(form, tc.target); got != tc.want {
+ if got := RedirectAllowed(form.AllowedOrigins, form.RedirectURL, tc.target); got != tc.want {
t.Fatalf("RedirectAllowed(%q) = %v, want %v", tc.target, got, tc.want)
}
}
@@ -79,14 +80,14 @@ func TestRedirectAllowedRejectsOpenRedirects(t *testing.T) {
func TestRedirectAllowedWithoutAllowlistRejects(t *testing.T) {
form := &models.Form{}
- if RedirectAllowed(form, "https://anywhere.test/thanks") {
+ if RedirectAllowed(form.AllowedOrigins, form.RedirectURL, "https://anywhere.test/thanks") {
t.Fatal("a form with no allowlist must not honour an arbitrary redirect target")
}
}
func TestRedirectAllowedMatchesConfiguredRedirectHost(t *testing.T) {
form := &models.Form{RedirectURL: "https://example.com/thanks"}
- if !RedirectAllowed(form, "https://example.com/other") {
+ if !RedirectAllowed(form.AllowedOrigins, form.RedirectURL, "https://example.com/other") {
t.Fatal("a target on the configured redirect host should be allowed")
}
}
diff --git a/internal/services/messages/quota_cache_test.go b/internal/services/messages/quota_cache_test.go
new file mode 100644
index 0000000..8c18288
--- /dev/null
+++ b/internal/services/messages/quota_cache_test.go
@@ -0,0 +1,145 @@
+// Copyright (c) 2026 Jonas Kaninda.
+//
+// This file is part of Posta.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+//
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package messages
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/goposta/posta/internal/models"
+ "github.com/goposta/posta/internal/services/ratelimit"
+)
+
+func quotaKeys(qs []ratelimit.Quota) []string {
+ keys := make([]string, len(qs))
+ for i, q := range qs {
+ keys[i] = q.Key
+ }
+ return keys
+}
+
+func TestSubmissionQuotasChargeEverySharedCounter(t *testing.T) {
+ s := &Service{cfg: Config{PerIPHourly: 20, PerFormHourly: 200, PerEmailHourly: 5, PerWorkspaceDaily: 1000}}
+ keys := quotaKeys(s.submissionQuotas(1, 2, "203.0.113.7", "[email protected]", false))
+ want := []string{"form:q:ip:1:203.0.113.7", "form:q:form:1", "form:q:ws:2", "form:q:email:1:"}
+ if len(keys) != len(want) {
+ t.Fatalf("keys = %v", keys)
+ }
+ for i := range want {
+ if !strings.HasPrefix(keys[i], want[i]) {
+ t.Fatalf("keys = %v, want prefixes %v", keys, want)
+ }
+ }
+}
+
+func TestSubmissionQuotasChargeHoneypotToIPOnly(t *testing.T) {
+ s := &Service{cfg: Config{PerIPHourly: 20, PerFormHourly: 200, PerEmailHourly: 5, PerWorkspaceDaily: 1000}}
+ keys := quotaKeys(s.submissionQuotas(1, 2, "203.0.113.7", "[email protected]", true))
+ if len(keys) != 1 || keys[0] != "form:q:ip:1:203.0.113.7" {
+ t.Fatalf("a honeypot hit must only count against its IP, got %v", keys)
+ }
+}
+
+func TestSubmissionQuotasSkipMissingIPAndEmail(t *testing.T) {
+ s := &Service{cfg: Config{PerIPHourly: 20, PerFormHourly: 200, PerEmailHourly: 5, PerWorkspaceDaily: 1000}}
+ for _, k := range quotaKeys(s.submissionQuotas(1, 2, "", "", false)) {
+ if strings.Contains(k, ":ip:") || strings.Contains(k, ":email:") {
+ t.Fatalf("unexpected quota %q for a request with no IP or email", k)
+ }
+ }
+}
+
+type failingQuotas struct{}
+
+func (failingQuotas) Check(context.Context, []ratelimit.Quota) error {
+ return ratelimit.ErrQuotaUnavailable
+}
+
+func TestCheckQuotasFailsClosed(t *testing.T) {
+ s := &Service{quotas: failingQuotas{}}
+ if err := s.checkQuotas(context.Background(), 1, 2, "ip", "", false); !errors.Is(err, ErrRateLimited) {
+ t.Fatalf("err = %v, want ErrRateLimited when the quota store is down", err)
+ }
+}
+
+// memCache stands in for *cache.Cache, round-tripping through JSON like Redis.
+type memCache struct {
+ data map[string][]byte
+ deleted []string
+}
+
+func (m *memCache) Get(_ context.Context, key string, dest any) bool {
+ raw, ok := m.data[key]
+ return ok && json.Unmarshal(raw, dest) == nil
+}
+
+func (m *memCache) Set(_ context.Context, key string, value any, _ time.Duration) {
+ raw, _ := json.Marshal(value)
+ if m.data == nil {
+ m.data = map[string][]byte{}
+ }
+ m.data[key] = raw
+}
+
+func (m *memCache) Delete(_ context.Context, key string) {
+ delete(m.data, key)
+ m.deleted = append(m.deleted, key)
+}
+
+// The service under test has no formRepo: a cache hit must never reach it.
+func TestFindFormByKeyServesCachedForm(t *testing.T) {
+ ws := uint(4)
+ c := &memCache{}
+ c.Set(context.Background(), formCachePrefix+"pk1", formCacheEntry{Form: &models.Form{
+ ID: 9, WorkspaceID: &ws, PublicKey: "pk1", Status: models.FormStatusActive,
+ AllowedOrigins: []string{"https://example.com"}, HoneypotField: "_hp",
+ }}, time.Minute)
+ s := &Service{formCache: c}
+
+ f, err := s.FindFormByKey("pk1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if f.ID != 9 || *f.WorkspaceID != 4 || f.Honeypot() != "_hp" || len(f.AllowedOrigins) != 1 {
+ t.Fatalf("cached form lost fields: %+v", f)
+ }
+}
+
+func TestFindFormByKeyServesCachedMiss(t *testing.T) {
+ c := &memCache{}
+ c.Set(context.Background(), formCachePrefix+"nope", formCacheEntry{Missing: true}, time.Minute)
+ s := &Service{formCache: c}
+ if _, err := s.FindFormByKey("nope"); !errors.Is(err, ErrFormNotFound) {
+ t.Fatalf("err = %v, want ErrFormNotFound", err)
+ }
+}
+
+func TestInvalidateFormKeyDropsEveryKey(t *testing.T) {
+ c := &memCache{}
+ s := &Service{formCache: c}
+ s.InvalidateFormKey("old", "new", "")
+ if len(c.deleted) != 2 || c.deleted[0] != formCachePrefix+"old" || c.deleted[1] != formCachePrefix+"new" {
+ t.Fatalf("deleted = %v", c.deleted)
+ }
+}
diff --git a/internal/services/messages/ratelimit.go b/internal/services/messages/ratelimit.go
index 0cdcc02..84ad0cc 100644
--- a/internal/services/messages/ratelimit.go
+++ b/internal/services/messages/ratelimit.go
@@ -27,46 +27,49 @@ import (
"fmt"
"strings"
"time"
+
+ "github.com/goposta/posta/internal/services/ratelimit"
)
var ErrRateLimited = errors.New("too many submissions")
-type quota struct {
- key string
- limit int
- window time.Duration
+// quotaChecker is satisfied by *ratelimit.Quotas.
+type quotaChecker interface {
+ Check(ctx context.Context, quotas []ratelimit.Quota) error
}
-func (s *Service) checkQuotas(ctx context.Context, formID, workspaceID uint, ip, email string) error {
- if s.redis == nil {
- return nil
+// submissionQuotas lists the counters one submission is charged to. A
+// honeypot hit is charged to its IP only: bot traffic must not use up the
+// shared per-form, per-workspace, or per-address budget that real visitors
+// draw on, or a botnet spread across IPs could lock a form.
+func (s *Service) submissionQuotas(formID, workspaceID uint, ip, email string, honeypot bool) []ratelimit.Quota {
+ var quotas []ratelimit.Quota
+ if ip != "" {
+ quotas = append(quotas, ratelimit.Quota{
+ Key: fmt.Sprintf("form:q:ip:%d:%s", formID, ip), Limit: s.cfg.PerIPHourly, Window: time.Hour,
+ })
}
-
- quotas := []quota{
- {fmt.Sprintf("form:q:ip:%d:%s", formID, ip), s.cfg.PerIPHourly, time.Hour},
- {fmt.Sprintf("form:q:form:%d", formID), s.cfg.PerFormHourly, time.Hour},
- {fmt.Sprintf("form:q:ws:%d", workspaceID), s.cfg.PerWorkspaceDaily, 24 * time.Hour},
+ if honeypot {
+ return quotas
}
+ quotas = append(quotas,
+ ratelimit.Quota{Key: fmt.Sprintf("form:q:form:%d", formID), Limit: s.cfg.PerFormHourly, Window: time.Hour},
+ ratelimit.Quota{Key: fmt.Sprintf("form:q:ws:%d", workspaceID), Limit: s.cfg.PerWorkspaceDaily, Window: 24 * time.Hour},
+ )
if email != "" {
- quotas = append(quotas, quota{
- fmt.Sprintf("form:q:email:%d:%s", formID, hashKey(email)), s.cfg.PerEmailHourly, time.Hour,
+ quotas = append(quotas, ratelimit.Quota{
+ Key: fmt.Sprintf("form:q:email:%d:%s", formID, hashKey(email)), Limit: s.cfg.PerEmailHourly, Window: time.Hour,
})
}
+ return quotas
+}
- for _, q := range quotas {
- if q.limit <= 0 || strings.HasSuffix(q.key, ":") {
- continue
- }
- count, err := s.redis.Incr(ctx, q.key).Result()
- if err != nil {
- return ErrRateLimited
- }
- if count == 1 {
- s.redis.Expire(ctx, q.key, q.window)
- }
- if count > int64(q.limit) {
- return ErrRateLimited
- }
+func (s *Service) checkQuotas(ctx context.Context, formID, workspaceID uint, ip, email string, honeypot bool) error {
+ if s.quotas == nil {
+ return nil
+ }
+ if err := s.quotas.Check(ctx, s.submissionQuotas(formID, workspaceID, ip, email, honeypot)); err != nil {
+ return ErrRateLimited
}
return nil
}
diff --git a/internal/services/messages/service.go b/internal/services/messages/service.go
index f25b1fc..757071b 100644
--- a/internal/services/messages/service.go
+++ b/internal/services/messages/service.go
@@ -28,19 +28,21 @@ import (
"encoding/json"
"errors"
"fmt"
+ "net/mail"
"net/url"
"strings"
"time"
+ "github.com/google/uuid"
"github.com/goposta/posta/internal/models"
+ "github.com/goposta/posta/internal/services/cache"
"github.com/goposta/posta/internal/services/email"
- "github.com/goposta/posta/internal/services/eventbus"
"github.com/goposta/posta/internal/services/messagescan"
+ "github.com/goposta/posta/internal/services/ratelimit"
"github.com/goposta/posta/internal/storage/blob"
"github.com/goposta/posta/internal/storage/repositories"
"github.com/jkaninda/logger"
"github.com/redis/go-redis/v9"
- "gorm.io/gorm"
)
var (
@@ -68,6 +70,7 @@ type Config struct {
type Enqueuer interface {
EnqueueMessageProcess(messageID uint) error
+ EnqueueMessageReply(replyID uint) error
}
type Service struct {
@@ -78,8 +81,9 @@ type Service struct {
emailService *email.Service
scanner *messagescan.Scanner
redis *redis.Client
+ quotas quotaChecker
+ formCache formKeyCache
blobStore blob.Store
- bus *eventbus.EventBus
enqueuer Enqueuer
cfg Config
hmacKey []byte
@@ -105,6 +109,10 @@ func NewService(
cfg: cfg,
hmacKey: hmacKey,
}
+ if redisClient != nil {
+ s.quotas = ratelimit.NewQuotas(redisClient)
+ s.formCache = cache.New(redisClient)
+ }
s.scanner = messagescan.New(&lookup{
messageRepo: messageRepo,
filterRepo: filterRepo,
@@ -115,32 +123,24 @@ func NewService(
func (s *Service) SetEmailService(es *email.Service) { s.emailService = es }
func (s *Service) SetBlobStore(bs blob.Store) { s.blobStore = bs }
-func (s *Service) SetEventBus(b *eventbus.EventBus) { s.bus = b }
func (s *Service) SetEnqueuer(e Enqueuer) { s.enqueuer = e }
func (s *Service) OnReceived(fn func(models.MessageStatus)) { s.onReceived = fn }
func (s *Service) Scanner() *messagescan.Scanner { return s.scanner }
-func (s *Service) FindFormByKey(key string) (*models.Form, error) {
- f, err := s.formRepo.FindByPublicKey(key)
- if err != nil {
- if errors.Is(err, gorm.ErrRecordNotFound) {
- return nil, ErrFormNotFound
- }
- return nil, err
- }
- return f, nil
-}
-
-func OriginAllowed(form *models.Form, origin string) bool {
+// OriginAllowed reports whether a browser Origin may post to an endpoint with
+// this allowlist. An empty allowlist accepts any origin; "*" does explicitly.
+// A missing Origin (curl, server-to-server, a native app) is accepted unless
+// strict is set. The allowlist slows spam; it is not authentication.
+func OriginAllowed(allowlist []string, strict bool, origin string) bool {
origin = strings.TrimSpace(origin)
if origin == "" {
- return !form.StrictOrigin
+ return !strict
}
- if len(form.AllowedOrigins) == 0 {
+ if len(allowlist) == 0 {
return true
}
- for _, allowed := range form.AllowedOrigins {
+ for _, allowed := range allowlist {
allowed = strings.TrimSpace(allowed)
if allowed == "*" {
return true
@@ -152,7 +152,10 @@ func OriginAllowed(form *models.Form, origin string) bool {
return false
}
-func RedirectAllowed(form *models.Form, target string) bool {
+// RedirectAllowed reports whether target is a safe post-submit redirect: on
+// the host of the endpoint's configured redirect, or on an explicitly allowed
+// origin. Anything else would be an open redirect on a trusted domain.
+func RedirectAllowed(allowlist []string, fixedRedirect, target string) bool {
if target == "" {
return false
}
@@ -164,12 +167,12 @@ func RedirectAllowed(form *models.Form, target string) bool {
return false
}
candidate := u.Scheme + "://" + u.Host
- if form.RedirectURL != "" {
- if ru, err := url.Parse(form.RedirectURL); err == nil && strings.EqualFold(ru.Host, u.Host) {
+ if fixedRedirect != "" {
+ if ru, err := url.Parse(fixedRedirect); err == nil && strings.EqualFold(ru.Host, u.Host) {
return true
}
}
- return OriginAllowed(form, candidate) && len(form.AllowedOrigins) > 0
+ return OriginAllowed(allowlist, false, candidate) && len(allowlist) > 0
}
type SubmitRequest struct {
@@ -218,7 +221,7 @@ func (s *Service) Submit(ctx context.Context, req SubmitRequest) (*SubmitResult,
extracted := Extract(fields)
senderEmail := NormalizeEmail(extracted.Email)
- if err := s.checkQuotas(ctx, form.ID, *form.WorkspaceID, req.ClientIP, senderEmail); err != nil {
+ if err := s.checkQuotas(ctx, form.ID, *form.WorkspaceID, req.ClientIP, senderEmail, req.HoneypotHit); err != nil {
return nil, err
}
@@ -228,7 +231,7 @@ func (s *Service) Submit(ctx context.Context, req SubmitRequest) (*SubmitResult,
}
verdict := s.scanner.Scan(messagescan.Input{
- Form: form,
+ Policy: form,
WorkspaceID: *form.WorkspaceID,
SenderEmail: senderEmail,
SenderName: extracted.Name,
@@ -333,23 +336,29 @@ func (s *Service) Reply(ctx context.Context, actorID, apiKeyID uint, actorEmail
subject = replySubject(msg.Subject)
}
- headers := map[string]string{}
+ messageID := newMessageID(msg.UUID, from)
+ headers := map[string]string{"Message-ID": messageID}
if msg.RootMessageID != "" {
- headers["In-Reply-To"] = msg.RootMessageID
- headers["References"] = msg.RootMessageID
+ prior, err := s.messageRepo.ReplyMessageIDs(msg.ID)
+ if err != nil {
+ logger.Warn("failed to load thread message ids", "message_id", msg.ID, "error", err)
+ }
+ inReplyTo, references := threadHeaders(msg.RootMessageID, prior)
+ headers["In-Reply-To"] = inReplyTo
+ headers["References"] = references
}
if replyTo := s.threadReplyTo(msg); replyTo != "" {
headers["Reply-To"] = replyTo
}
sendReq := &email.SendRequest{
- From: from,
- To: []string{msg.SenderEmail},
- Subject: subject,
- HTML: req.HTML,
- Text: req.Text,
- Attachments: req.Attachments,
- Headers: headers,
+ From: from,
+ To: []string{msg.SenderEmail},
+ Subject: subject,
+ HTML: req.HTML,
+ Text: req.Text,
+ Attachments: req.Attachments,
+ SystemHeaders: headers,
}
resp, err := s.emailService.Send(ctx, actorID, apiKeyID, msg.WorkspaceID, actorEmail, sendReq)
@@ -357,23 +366,44 @@ func (s *Service) Reply(ctx context.Context, actorID, apiKeyID uint, actorEmail
return nil, err
}
+ var authorID *uint
+ if actorID != 0 {
+ authorID = &actorID
+ }
reply := &models.MessageReply{
- MessageID: msg.ID,
- WorkspaceID: msg.WorkspaceID,
- Kind: models.MessageReplyKindOperator,
- AuthorID: actorID,
- FromAddr: from,
- ToAddr: msg.SenderEmail,
- Subject: subject,
- HTMLBody: req.HTML,
- TextBody: req.Text,
- EmailUUID: resp.ID,
+ MessageID: msg.ID,
+ WorkspaceID: msg.WorkspaceID,
+ Kind: models.MessageReplyKindOperator,
+ AuthorID: authorID,
+ FromAddr: from,
+ ToAddr: msg.SenderEmail,
+ Subject: subject,
+ HTMLBody: req.HTML,
+ TextBody: req.Text,
+ EmailUUID: resp.ID,
+ MessageIDHeader: messageID,
}
if err := s.messageRepo.AddReply(reply); err != nil {
return nil, err
}
+ if s.enqueuer != nil {
+ if err := s.enqueuer.EnqueueMessageReply(reply.ID); err != nil {
+ logger.Error("failed to enqueue message reply webhook", "reply_id", reply.ID, "error", err)
+ }
+ }
+
+ if msg.RootMessageID == "" {
+ if err := s.messageRepo.SetRootMessageID(msg.ID, messageID); err != nil {
+ logger.Error("failed to record thread root message id", "message_id", msg.ID, "error", err)
+ } else {
+ msg.RootMessageID = messageID
+ }
+ }
now := time.Now()
+ if err := s.messageRepo.RecordReply(msg.ID, now); err != nil {
+ logger.Error("failed to update message after reply", "message_id", msg.ID, "error", err)
+ }
msg.RepliedAt = &now
msg.UpdatedAt = &now
msg.ReplyCount++
@@ -383,9 +413,6 @@ func (s *Service) Reply(ctx context.Context, actorID, apiKeyID uint, actorEmail
if msg.ReadAt == nil {
msg.ReadAt = &now
}
- if err := s.messageRepo.Update(msg); err != nil {
- logger.Error("failed to update message after reply", "message_id", msg.ID, "error", err)
- }
return reply, nil
}
@@ -399,6 +426,41 @@ func (s *Service) threadReplyTo(msg *models.Message) string {
func (s *Service) ThreadReplyTo(msg *models.Message) string { return s.threadReplyTo(msg) }
+// maxReferences caps the References header at the thread root plus the most
+// recent replies; RFC 5322 §3.6.4 lets a long thread trim the middle.
+const maxReferences = 10
+
+// threadHeaders returns the In-Reply-To and References values for a new reply
+// on a thread whose first reply was root and whose later replies are prior,
+// oldest first.
+func threadHeaders(root string, prior []string) (inReplyTo, references string) {
+ chain := make([]string, 0, maxReferences+1)
+ chain = append(chain, root)
+ recent := make([]string, 0, len(prior))
+ for _, id := range prior {
+ if id != "" && id != root {
+ recent = append(recent, id)
+ }
+ }
+ if len(recent) > maxReferences {
+ recent = recent[len(recent)-maxReferences:]
+ }
+ chain = append(chain, recent...)
+ return chain[len(chain)-1], strings.Join(chain, " ")
+}
+
+// newMessageID builds an RFC 5322 Message-ID on the sending domain, so it is
+// covered by the same DKIM signature as the rest of the message.
+func newMessageID(messageUUID, from string) string {
+ domain := "posta.local"
+ if addr, err := mail.ParseAddress(from); err == nil {
+ if at := strings.LastIndex(addr.Address, "@"); at >= 0 && at+1 < len(addr.Address) {
+ domain = strings.ToLower(addr.Address[at+1:])
+ }
+ }
+ return fmt.Sprintf("<%s.%s@%s>", uuid.NewString(), messageUUID, domain)
+}
+
func defaultSubject(form *models.Form) string {
return fmt.Sprintf("New submission on %s", form.Name)
}
@@ -453,10 +515,19 @@ func (l *lookup) SubmissionsFromIP(ip string, since time.Time) int64 {
return l.messageRepo.CountByIPSince(ip, since)
}
-func (l *lookup) SubmissionsFromSender(formID uint, email string, since time.Time) int64 {
- return l.messageRepo.CountBySenderSince(formID, email, since)
+func (l *lookup) SubmissionsFromSender(src models.ScanSource, email string, since time.Time) int64 {
+ if src.Kind != models.ScanSourceForm {
+ return 0
+ }
+ return l.messageRepo.CountBySenderSince(src.ID, email, since)
}
-func (l *lookup) ActiveFilters(workspaceID uint, formID uint) ([]models.MessageFilter, error) {
+// ActiveFilters returns the workspace-wide filters plus those scoped to the
+// source. Only forms carry source-scoped filters today.
+func (l *lookup) ActiveFilters(workspaceID uint, src models.ScanSource) ([]models.MessageFilter, error) {
+ var formID uint
+ if src.Kind == models.ScanSourceForm {
+ formID = src.ID
+ }
return l.filterRepo.FindActive(workspaceID, formID)
}
diff --git a/internal/services/messages/threads.go b/internal/services/messages/threads.go
new file mode 100644
index 0000000..d24bbe3
--- /dev/null
+++ b/internal/services/messages/threads.go
@@ -0,0 +1,188 @@
+// Copyright (c) 2026 Jonas Kaninda.
+//
+// This file is part of Posta.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+//
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package messages
+
+import (
+ "context"
+ "errors"
+ "net/mail"
+ "strings"
+ "time"
+
+ "github.com/goposta/posta/internal/models"
+ "github.com/goposta/posta/internal/services/realtime"
+ "github.com/jkaninda/logger"
+ "gorm.io/gorm"
+)
+
+// threadLocalPrefix is the local-part prefix of a thread address,
+// msg+<token>@<inbound domain>.
+const threadLocalPrefix = "msg+"
+
+// threadTokenLength is the length of newThreadToken's output: 16 random bytes
+// in unpadded base32.
+const threadTokenLength = 26
+
+// ThreadStore is the slice of MessageRepository the router needs.
+type ThreadStore interface {
+ FindByThreadToken(token string) (*models.Message, error)
+ AddInboundReply(reply *models.MessageReply) (bool, error)
+ UpdateFields(id uint, fields map[string]any) error
+}
+
+// ReplyEnqueuer schedules the follow-up work (webhook, notification) for a
+// reply attached to a thread.
+type ReplyEnqueuer interface {
+ EnqueueMessageReply(replyID uint) error
+}
+
+// ThreadRouter attaches inbound email sent to a thread address onto the form
+// message it belongs to. It implements inbound.ThreadRouter.
+type ThreadRouter struct {
+ store ThreadStore
+ domain string
+ realtime realtime.Bus
+ enqueuer ReplyEnqueuer
+}
+
+// NewThreadRouter returns a router for thread addresses on inboundDomain.
+func NewThreadRouter(store ThreadStore, inboundDomain string) *ThreadRouter {
+ return &ThreadRouter{store: store, domain: strings.ToLower(strings.TrimSpace(inboundDomain))}
+}
+
+func (r *ThreadRouter) SetRealtime(b realtime.Bus) { r.realtime = b }
+func (r *ThreadRouter) SetEnqueuer(e ReplyEnqueuer) { r.enqueuer = e }
+
+// ParseThreadAddress returns the thread token in addr when it is a thread
+// address on domain. It accepts a bare address or a "Name <addr>" form.
+func ParseThreadAddress(addr, domain string) (string, bool) {
+ addr = strings.TrimSpace(addr)
+ if parsed, err := mail.ParseAddress(addr); err == nil {
+ addr = parsed.Address
+ }
+ addr = strings.ToLower(addr)
+ at := strings.LastIndex(addr, "@")
+ if at < 0 || domain == "" || addr[at+1:] != strings.ToLower(domain) {
+ return "", false
+ }
+ local := addr[:at]
+ if !strings.HasPrefix(local, threadLocalPrefix) {
+ return "", false
+ }
+ token := local[len(threadLocalPrefix):]
+ if len(token) != threadTokenLength {
+ return "", false
+ }
+ for _, c := range token {
+ if (c < 'a' || c > 'z') && (c < '2' || c > '7') {
+ return "", false
+ }
+ }
+ return token, true
+}
+
+// RouteReply attaches rec to a thread when one of recipients is a thread
+// address. It reports false, with no side effects, when no recipient names a
+// thread of rec's own workspace; the caller then handles rec as ordinary
+// inbound mail.
+func (r *ThreadRouter) RouteReply(ctx context.Context, rec *models.InboundEmail, recipients []string) (bool, error) {
+ if r == nil || r.domain == "" || rec == nil {
+ return false, nil
+ }
+ for _, rcpt := range recipients {
+ token, ok := ParseThreadAddress(rcpt, r.domain)
+ if !ok {
+ continue
+ }
+ msg, err := r.store.FindByThreadToken(token)
+ if err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ continue
+ }
+ return false, err
+ }
+ // A thread token only routes within its own workspace: mail that reached
+ // workspace A's domain must never write into a workspace B thread.
+ if !sameWorkspace(rec.WorkspaceID, msg.WorkspaceID) {
+ logger.Warn("thread reply rejected: workspace mismatch",
+ "inbound_id", rec.UUID, "message_id", msg.UUID)
+ continue
+ }
+ if err := r.attach(ctx, rec, msg, rcpt); err != nil {
+ return false, err
+ }
+ return true, nil
+ }
+ return false, nil
+}
+
+func (r *ThreadRouter) attach(ctx context.Context, rec *models.InboundEmail, msg *models.Message, rcpt string) error {
+ inboundID := rec.ID
+ reply := &models.MessageReply{
+ MessageID: msg.ID,
+ WorkspaceID: msg.WorkspaceID,
+ Kind: models.MessageReplyKindInbound,
+ FromAddr: rec.Sender,
+ ToAddr: rcpt,
+ Subject: rec.Subject,
+ TextBody: rec.TextBody,
+ HTMLBody: rec.HTMLBody,
+ InboundEmailID: &inboundID,
+ SenderMismatch: !sameAddress(rec.Sender, msg.SenderEmail),
+ }
+ if rec.MessageID != "" {
+ reply.MessageIDHeader = "<" + strings.Trim(rec.MessageID, "<>") + ">"
+ }
+ created, err := r.store.AddInboundReply(reply)
+ if err != nil {
+ return err
+ }
+ if !created {
+ // A retried parse task: this email is already on the thread.
+ return nil
+ }
+
+ now := time.Now()
+ fields := map[string]any{"read_at": nil, "updated_at": now}
+ if msg.State != models.MessageStateSpam {
+ fields["state"] = models.MessageStateOpen
+ msg.State = models.MessageStateOpen
+ }
+ if err := r.store.UpdateFields(msg.ID, fields); err != nil {
+ logger.Error("failed to reopen thread after reply", "message_id", msg.ID, "error", err)
+ }
+
+ PublishEvent(ctx, r.realtime, EventReplyReceived, msg)
+ if r.enqueuer != nil {
+ if err := r.enqueuer.EnqueueMessageReply(reply.ID); err != nil {
+ logger.Error("failed to enqueue message reply processing", "reply_id", reply.ID, "error", err)
+ }
+ }
+ return nil
+}
+
+func sameWorkspace(a, b *uint) bool {
+ return a != nil && b != nil && *a == *b
+}
+
+func sameAddress(a, b string) bool {
+ na := NormalizeEmail(a)
+ return na != "" && na == NormalizeEmail(b)
+}
diff --git a/internal/services/messages/threads_test.go b/internal/services/messages/threads_test.go
new file mode 100644
index 0000000..8716f84
--- /dev/null
+++ b/internal/services/messages/threads_test.go
@@ -0,0 +1,269 @@
+// Copyright (c) 2026 Jonas Kaninda.
+//
+// This file is part of Posta.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+//
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package messages
+
+import (
+ "context"
+ "fmt"
+ "regexp"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/goposta/posta/internal/models"
+ "github.com/goposta/posta/internal/services/realtime"
+ "gorm.io/gorm"
+)
+
+func TestThreadHeadersFirstFollowUp(t *testing.T) {
+ inReplyTo, refs := threadHeaders("<root@x>", nil)
+ if inReplyTo != "<root@x>" || refs != "<root@x>" {
+ t.Fatalf("got %q / %q", inReplyTo, refs)
+ }
+}
+
+func TestThreadHeadersChainsToLatestReply(t *testing.T) {
+ inReplyTo, refs := threadHeaders("<root@x>", []string{"<root@x>", "<a@x>", "<b@x>"})
+ if inReplyTo != "<b@x>" {
+ t.Fatalf("In-Reply-To = %q, want the latest reply", inReplyTo)
+ }
+ if refs != "<root@x> <a@x> <b@x>" {
+ t.Fatalf("References = %q", refs)
+ }
+}
+
+func TestThreadHeadersCapsReferences(t *testing.T) {
+ var prior []string
+ for i := 0; i < 25; i++ {
+ prior = append(prior, fmt.Sprintf("<r%d@x>", i))
+ }
+ _, refs := threadHeaders("<root@x>", prior)
+ ids := strings.Fields(refs)
+ if len(ids) != maxReferences+1 {
+ t.Fatalf("References holds %d ids, want root + %d", len(ids), maxReferences)
+ }
+ if ids[0] != "<root@x>" || ids[len(ids)-1] != "<r24@x>" {
+ t.Fatalf("References must keep the root and the newest replies: %v", ids)
+ }
+}
+
+func TestNewMessageIDUsesSendingDomain(t *testing.T) {
+ id := newMessageID("msg-uuid", "Acme Support <[email protected]>")
+ if !regexp.MustCompile(`^<[0-9a-f-]{36}\.msg-uuid@acme\.example>$`).MatchString(id) {
+ t.Fatalf("Message-ID = %q", id)
+ }
+ first, second := newMessageID("u", "[email protected]"), newMessageID("u", "[email protected]")
+ if first == second {
+ t.Fatal("Message-IDs must be unique per reply")
+ }
+}
+
+func TestParseThreadAddress(t *testing.T) {
+ token := strings.Repeat("a", 22) + "2345"
+ cases := []struct {
+ addr string
+ ok bool
+ }{
+ {"msg+" + token + "@reply.example.com", true},
+ {"Ada <MSG+" + strings.ToUpper(token) + "@Reply.Example.com>", true},
+ {"msg+" + token + "@other.example.com", false}, // wrong domain
+ {"msg+" + token[:20] + "@reply.example.com", false}, // wrong length
+ {"msg+" + strings.Repeat("1", 26) + "@reply.example.com", false}, // not base32
+ {"[email protected]", false},
+ {"msg+" + token + "@reply.example.com.evil.test", false},
+ {"", false},
+ }
+ for _, tc := range cases {
+ got, ok := ParseThreadAddress(tc.addr, "reply.example.com")
+ if ok != tc.ok {
+ t.Fatalf("ParseThreadAddress(%q) ok = %v, want %v", tc.addr, ok, tc.ok)
+ }
+ if ok && got != token {
+ t.Fatalf("ParseThreadAddress(%q) token = %q", tc.addr, got)
+ }
+ }
+}
+
+func TestThreadAddressRoundTrip(t *testing.T) {
+ s := &Service{cfg: Config{InboundDomain: "reply.example.com"}}
+ msg := &models.Message{ThreadToken: newThreadToken()}
+ token, ok := ParseThreadAddress(s.ThreadReplyTo(msg), "reply.example.com")
+ if !ok || token != msg.ThreadToken {
+ t.Fatalf("ThreadReplyTo output does not parse back: %q", s.ThreadReplyTo(msg))
+ }
+}
+
+type fakeThreadStore struct {
+ msgs map[string]*models.Message
+ replies []*models.MessageReply
+ updates []map[string]any
+ dupe bool
+}
+
+func (f *fakeThreadStore) FindByThreadToken(token string) (*models.Message, error) {
+ if m, ok := f.msgs[token]; ok {
+ return m, nil
+ }
+ return nil, gorm.ErrRecordNotFound
+}
+
+func (f *fakeThreadStore) AddInboundReply(r *models.MessageReply) (bool, error) {
+ if f.dupe {
+ return false, nil
+ }
+ f.replies = append(f.replies, r)
+ return true, nil
+}
+
+func (f *fakeThreadStore) UpdateFields(_ uint, fields map[string]any) error {
+ f.updates = append(f.updates, fields)
+ return nil
+}
+
+type fakeReplyEnqueuer struct{ ids []uint }
+
+func (f *fakeReplyEnqueuer) EnqueueMessageReply(id uint) error {
+ f.ids = append(f.ids, id)
+ return nil
+}
+
+// routerFixture builds a router whose one thread belongs to workspace 1.
+func routerFixture() (*ThreadRouter, *fakeThreadStore, *fakeReplyEnqueuer, string) {
+ wsOfMessage := uint(1)
+ token := newThreadToken()
+ store := &fakeThreadStore{msgs: map[string]*models.Message{
+ token: {ID: 7, UUID: "m-7", WorkspaceID: &wsOfMessage, SenderEmail: "[email protected]", State: models.MessageStateReplied},
+ }}
+ enq := &fakeReplyEnqueuer{}
+ r := NewThreadRouter(store, "reply.example.com")
+ r.SetEnqueuer(enq)
+ return r, store, enq, "msg+" + token + "@reply.example.com"
+}
+
+func inboundFrom(ws uint, sender string) *models.InboundEmail {
+ return &models.InboundEmail{ID: 42, UUID: "in-42", WorkspaceID: &ws, Sender: sender,
+ Subject: "Re: hi", TextBody: "thanks", MessageID: "[email protected]"}
+}
+
+func TestRouteReplyIgnoresNonThreadRecipients(t *testing.T) {
+ r, store, _, _ := routerFixture()
+ routed, err := r.RouteReply(context.Background(), inboundFrom(1, "[email protected]"), []string{"[email protected]"})
+ if err != nil || routed || len(store.replies) != 0 {
+ t.Fatalf("routed = %v, err = %v, replies = %d", routed, err, len(store.replies))
+ }
+}
+
+func TestRouteReplyIgnoresUnknownToken(t *testing.T) {
+ r, store, _, _ := routerFixture()
+ unknown := "msg+" + newThreadToken() + "@reply.example.com"
+ routed, err := r.RouteReply(context.Background(), inboundFrom(1, "[email protected]"), []string{unknown})
+ if err != nil || routed || len(store.replies) != 0 {
+ t.Fatalf("routed = %v, err = %v", routed, err)
+ }
+}
+
+func TestRouteReplyRefusesOtherWorkspace(t *testing.T) {
+ r, store, enq, addr := routerFixture()
+ routed, err := r.RouteReply(context.Background(), inboundFrom(2, "[email protected]"), []string{addr})
+ if err != nil || routed {
+ t.Fatalf("routed = %v, err = %v; a token must not cross workspaces", routed, err)
+ }
+ if len(store.replies) != 0 || len(store.updates) != 0 || len(enq.ids) != 0 {
+ t.Fatal("a cross-workspace reply must have no side effects")
+ }
+}
+
+func TestRouteReplyAttachesAndReopens(t *testing.T) {
+ r, store, enq, addr := routerFixture()
+ bus := realtime.NewMemory()
+ r.SetRealtime(bus)
+ ch, unsub := bus.Subscribe(context.Background(), realtime.WorkspaceTopic(1))
+ defer unsub()
+
+ routed, err := r.RouteReply(context.Background(), inboundFrom(1, "Ada <[email protected]>"), []string{"[email protected]", addr})
+ if err != nil || !routed {
+ t.Fatalf("routed = %v, err = %v", routed, err)
+ }
+ if len(store.replies) != 1 {
+ t.Fatalf("replies = %d", len(store.replies))
+ }
+ reply := store.replies[0]
+ if reply.Kind != models.MessageReplyKindInbound || reply.MessageID != 7 || *reply.InboundEmailID != 42 {
+ t.Fatalf("reply = %+v", reply)
+ }
+ if reply.MessageIDHeader != "<[email protected]>" {
+ t.Fatalf("MessageIDHeader = %q", reply.MessageIDHeader)
+ }
+ if reply.SenderMismatch {
+ t.Fatal("the original sender, in any case or display form, is not a mismatch")
+ }
+ if got := store.updates[0]["state"]; got != models.MessageStateOpen {
+ t.Fatalf("state update = %v, want open", got)
+ }
+ if v, ok := store.updates[0]["read_at"]; !ok || v != nil {
+ t.Fatal("a reply must mark the thread unread")
+ }
+ if len(enq.ids) != 1 {
+ t.Fatal("the reply follow-up task was not enqueued")
+ }
+ select {
+ case ev := <-ch:
+ if ev.Type != EventReplyReceived {
+ t.Fatalf("event = %q", ev.Type)
+ }
+ case <-time.After(time.Second):
+ t.Fatal("no realtime event")
+ }
+}
+
+func TestRouteReplyFlagsSenderMismatch(t *testing.T) {
+ r, store, _, addr := routerFixture()
+ if routed, _ := r.RouteReply(context.Background(), inboundFrom(1, "[email protected]"), []string{addr}); !routed {
+ t.Fatal("a mismatched sender is still attached, flagged")
+ }
+ if !store.replies[0].SenderMismatch {
+ t.Fatal("expected SenderMismatch")
+ }
+}
+
+func TestRouteReplyDuplicateIsDoneWithoutSideEffects(t *testing.T) {
+ r, store, enq, addr := routerFixture()
+ store.dupe = true
+ routed, err := r.RouteReply(context.Background(), inboundFrom(1, "[email protected]"), []string{addr})
+ if err != nil || !routed {
+ t.Fatalf("a retried delivery must still count as routed: %v %v", routed, err)
+ }
+ if len(store.updates) != 0 || len(enq.ids) != 0 {
+ t.Fatal("a duplicate must not reopen the thread or re-enqueue")
+ }
+}
+
+func TestRouteReplyKeepsSpamThreadState(t *testing.T) {
+ r, store, _, addr := routerFixture()
+ for _, m := range store.msgs {
+ m.State = models.MessageStateSpam
+ }
+ if routed, _ := r.RouteReply(context.Background(), inboundFrom(1, "[email protected]"), []string{addr}); !routed {
+ t.Fatal("expected routed")
+ }
+ if _, ok := store.updates[0]["state"]; ok {
+ t.Fatal("a reply must not pull a thread out of spam")
+ }
+}
diff --git a/internal/services/messagescan/scanner.go b/internal/services/messagescan/scanner.go
index 1056c35..01a4d95 100644
--- a/internal/services/messagescan/scanner.go
+++ b/internal/services/messagescan/scanner.go
@@ -69,12 +69,23 @@ func (v Verdict) Status() models.MessageStatus {
type Lookup interface {
IsSuppressed(workspaceID uint, email string) bool
SubmissionsFromIP(ip string, since time.Time) int64
- SubmissionsFromSender(formID uint, email string, since time.Time) int64
- ActiveFilters(workspaceID uint, formID uint) ([]models.MessageFilter, error)
+ SubmissionsFromSender(src models.ScanSource, email string, since time.Time) int64
+ ActiveFilters(workspaceID uint, src models.ScanSource) ([]models.MessageFilter, error)
+}
+
+// Policy is the per-endpoint scanning configuration: whether to scan, where
+// the score thresholds sit, and which source's filters apply. *models.Form
+// implements it; a chat widget will too.
+type Policy interface {
+ ScanningEnabled() bool
+ // ScanThresholds returns the flag, quarantine, and reject scores. A
+ // non-positive value means the default for that rung.
+ ScanThresholds() (flag, quarantine, reject float64)
+ ScanSource() models.ScanSource
}
type Input struct {
- Form *models.Form
+ Policy Policy
WorkspaceID uint
SenderEmail string
SenderName string
@@ -114,14 +125,14 @@ func (s *Scanner) Scan(in Input) Verdict {
return v
}
- if in.Form != nil && !in.Form.ScanEnabled {
+ if in.Policy != nil && !in.Policy.ScanningEnabled() {
return v
}
floor := ActionAllow
if s.lookup != nil {
- hits, err := s.lookup.ActiveFilters(in.WorkspaceID, formID(in.Form))
+ hits, err := s.lookup.ActiveFilters(in.WorkspaceID, source(in.Policy))
if err == nil {
for i := range hits {
f := &hits[i]
@@ -157,24 +168,25 @@ func (s *Scanner) Scan(in Input) Verdict {
}
}
- v.Action = resolveAction(in.Form, v.Score)
+ v.Action = resolveAction(in.Policy, v.Score)
if actionRank[floor] > actionRank[v.Action] {
v.Action = floor
}
return v
}
-func resolveAction(form *models.Form, score float64) Action {
+func resolveAction(p Policy, score float64) Action {
flag, quarantine, reject := 3.0, 6.0, 10.0
- if form != nil {
- if form.FlagThreshold > 0 {
- flag = form.FlagThreshold
+ if p != nil {
+ f, q, r := p.ScanThresholds()
+ if f > 0 {
+ flag = f
}
- if form.QuarantineThreshold > 0 {
- quarantine = form.QuarantineThreshold
+ if q > 0 {
+ quarantine = q
}
- if form.RejectThreshold > 0 {
- reject = form.RejectThreshold
+ if r > 0 {
+ reject = r
}
}
switch {
@@ -202,11 +214,11 @@ func filterAction(a models.FilterAction) Action {
}
}
-func formID(f *models.Form) uint {
- if f == nil {
- return 0
+func source(p Policy) models.ScanSource {
+ if p == nil {
+ return models.ScanSource{}
}
- return f.ID
+ return p.ScanSource()
}
func (s *Scanner) matchFilter(f *models.MessageFilter, in Input) (bool, string) {
diff --git a/internal/services/messagescan/scanner_test.go b/internal/services/messagescan/scanner_test.go
index e4c4b87..faba05d 100644
--- a/internal/services/messagescan/scanner_test.go
+++ b/internal/services/messagescan/scanner_test.go
@@ -36,10 +36,12 @@ type stubLookup struct {
filterError error
}
-func (s *stubLookup) IsSuppressed(uint, string) bool { return s.suppressed }
-func (s *stubLookup) SubmissionsFromIP(string, time.Time) int64 { return s.fromIP }
-func (s *stubLookup) SubmissionsFromSender(uint, string, time.Time) int64 { return s.fromSender }
-func (s *stubLookup) ActiveFilters(uint, uint) ([]models.MessageFilter, error) {
+func (s *stubLookup) IsSuppressed(uint, string) bool { return s.suppressed }
+func (s *stubLookup) SubmissionsFromIP(string, time.Time) int64 { return s.fromIP }
+func (s *stubLookup) SubmissionsFromSender(models.ScanSource, string, time.Time) int64 {
+ return s.fromSender
+}
+func (s *stubLookup) ActiveFilters(uint, models.ScanSource) ([]models.MessageFilter, error) {
return s.filters, s.filterError
}
@@ -57,7 +59,7 @@ func testForm() *models.Form {
func TestHoneypotRejectsImmediately(t *testing.T) {
s := New(&stubLookup{})
- v := s.Scan(Input{Form: testForm(), HoneypotHit: true})
+ v := s.Scan(Input{Policy: testForm(), HoneypotHit: true})
if v.Action != ActionReject {
t.Fatalf("Action = %s, want reject", v.Action)
}
@@ -68,7 +70,7 @@ func TestHoneypotRejectsImmediately(t *testing.T) {
func TestNonceFailureRejectsImmediately(t *testing.T) {
s := New(&stubLookup{})
- v := s.Scan(Input{Form: testForm(), NonceFailed: true})
+ v := s.Scan(Input{Policy: testForm(), NonceFailed: true})
if v.Action != ActionReject {
t.Fatalf("Action = %s, want reject", v.Action)
}
@@ -78,7 +80,7 @@ func TestScanDisabledAllows(t *testing.T) {
form := testForm()
form.ScanEnabled = false
s := New(&stubLookup{suppressed: true})
- v := s.Scan(Input{Form: form, SenderEmail: "[email protected]", Body: strings.Repeat("BUY NOW ", 40)})
+ v := s.Scan(Input{Policy: form, SenderEmail: "[email protected]", Body: strings.Repeat("BUY NOW ", 40)})
if v.Action != ActionAllow || v.Score != 0 {
t.Fatalf("Action = %s score = %v, want allow/0", v.Action, v.Score)
}
@@ -113,7 +115,7 @@ func TestAllowlistShortCircuits(t *testing.T) {
},
})
v := s.Scan(Input{
- Form: testForm(),
+ Policy: testForm(),
SenderEmail: "[email protected]",
Body: strings.Repeat("http://spam.test ", 20),
})
@@ -131,7 +133,7 @@ func TestFilterActionSetsFloorRegardlessOfScore(t *testing.T) {
{ID: 1, Kind: models.FilterKindKeyword, Pattern: "casino", Action: models.FilterActionReject, Score: 0},
},
})
- v := s.Scan(Input{Form: testForm(), Body: "come to our casino"})
+ v := s.Scan(Input{Policy: testForm(), Body: "come to our casino"})
if v.Action != ActionReject {
t.Fatalf("Action = %s, want reject", v.Action)
}
@@ -144,7 +146,7 @@ func TestFilterScoreAccumulates(t *testing.T) {
{ID: 2, Kind: models.FilterKindKeyword, Pattern: "ranking", Action: models.FilterActionScore, Score: 2},
},
})
- v := s.Scan(Input{Form: testForm(), Body: "improve your seo and ranking"})
+ v := s.Scan(Input{Policy: testForm(), Body: "improve your seo and ranking"})
if v.Score < 4 {
t.Fatalf("Score = %v, want at least 4", v.Score)
}
@@ -159,10 +161,10 @@ func TestKeywordMatchesWholeWordOnly(t *testing.T) {
{ID: 1, Kind: models.FilterKindKeyword, Pattern: "cat", Action: models.FilterActionScore, Score: 5},
},
})
- if v := s.Scan(Input{Form: testForm(), Body: "concatenate these"}); len(v.FilterHits) != 0 {
+ if v := s.Scan(Input{Policy: testForm(), Body: "concatenate these"}); len(v.FilterHits) != 0 {
t.Fatal("keyword filter must not match inside a longer word")
}
- if v := s.Scan(Input{Form: testForm(), Body: "the cat sat"}); len(v.FilterHits) != 1 {
+ if v := s.Scan(Input{Policy: testForm(), Body: "the cat sat"}); len(v.FilterHits) != 1 {
t.Fatal("keyword filter should match a standalone word")
}
}
@@ -173,7 +175,7 @@ func TestPhraseMatchesSubstring(t *testing.T) {
{ID: 1, Kind: models.FilterKindPhrase, Pattern: "cat", Action: models.FilterActionScore, Score: 5},
},
})
- if v := s.Scan(Input{Form: testForm(), Body: "concatenate these"}); len(v.FilterHits) != 1 {
+ if v := s.Scan(Input{Policy: testForm(), Body: "concatenate these"}); len(v.FilterHits) != 1 {
t.Fatal("phrase filter should match inside a longer word")
}
}
@@ -184,7 +186,7 @@ func TestCaseSensitivity(t *testing.T) {
{ID: 1, Kind: models.FilterKindKeyword, Pattern: "Casino", Action: models.FilterActionScore, Score: 5, CaseSensitive: true},
},
})
- if v := sensitive.Scan(Input{Form: testForm(), Body: "visit our casino"}); len(v.FilterHits) != 0 {
+ if v := sensitive.Scan(Input{Policy: testForm(), Body: "visit our casino"}); len(v.FilterHits) != 0 {
t.Fatal("case-sensitive filter matched a differently-cased word")
}
@@ -193,7 +195,7 @@ func TestCaseSensitivity(t *testing.T) {
{ID: 1, Kind: models.FilterKindKeyword, Pattern: "Casino", Action: models.FilterActionScore, Score: 5},
},
})
- if v := insensitive.Scan(Input{Form: testForm(), Body: "visit our casino"}); len(v.FilterHits) != 1 {
+ if v := insensitive.Scan(Input{Policy: testForm(), Body: "visit our casino"}); len(v.FilterHits) != 1 {
t.Fatal("case-insensitive filter should have matched")
}
}
@@ -204,10 +206,10 @@ func TestDomainFilterMatchesSubdomains(t *testing.T) {
{ID: 1, Kind: models.FilterKindDomain, Pattern: "@spam.test", Action: models.FilterActionScore, Score: 5},
},
})
- if v := s.Scan(Input{Form: testForm(), SenderEmail: "[email protected]"}); len(v.FilterHits) != 1 {
+ if v := s.Scan(Input{Policy: testForm(), SenderEmail: "[email protected]"}); len(v.FilterHits) != 1 {
t.Fatal("domain filter should match a subdomain")
}
- if v := s.Scan(Input{Form: testForm(), SenderEmail: "[email protected]"}); len(v.FilterHits) != 0 {
+ if v := s.Scan(Input{Policy: testForm(), SenderEmail: "[email protected]"}); len(v.FilterHits) != 0 {
t.Fatal("domain filter must not match an unrelated host ending in the same suffix")
}
}
@@ -222,10 +224,10 @@ func TestFilterFieldScoping(t *testing.T) {
},
},
})
- if v := s.Scan(Input{Form: testForm(), Body: "urgent request"}); len(v.FilterHits) != 0 {
+ if v := s.Scan(Input{Policy: testForm(), Body: "urgent request"}); len(v.FilterHits) != 0 {
t.Fatal("subject-scoped filter must not match the body")
}
- if v := s.Scan(Input{Form: testForm(), Subject: "urgent request"}); len(v.FilterHits) != 1 {
+ if v := s.Scan(Input{Policy: testForm(), Subject: "urgent request"}); len(v.FilterHits) != 1 {
t.Fatal("subject-scoped filter should match the subject")
}
}
@@ -253,7 +255,7 @@ func TestBuiltinSignals(t *testing.T) {
t.Run(tc.name, func(t *testing.T) {
s := New(tc.lookup)
in := tc.input
- in.Form = testForm()
+ in.Policy = testForm()
v := s.Scan(in)
for _, r := range v.Reasons {
if r == tc.reason {
@@ -267,7 +269,7 @@ func TestBuiltinSignals(t *testing.T) {
func TestLinkCountScoreIsCapped(t *testing.T) {
s := New(&stubLookup{})
- v := s.Scan(Input{Form: testForm(), Body: strings.Repeat("https://x.test ", 60)})
+ v := s.Scan(Input{Policy: testForm(), Body: strings.Repeat("https://x.test ", 60)})
for _, r := range v.Reasons {
if strings.HasPrefix(r, "links:") {
if v.Score > 20 {
@@ -300,7 +302,7 @@ func TestRegexFilterIgnoresOverlongPattern(t *testing.T) {
{ID: 1, Kind: models.FilterKindRegex, Pattern: strings.Repeat("a", 600), Action: models.FilterActionReject},
},
})
- if v := s.Scan(Input{Form: testForm(), Body: strings.Repeat("a", 600)}); v.Action == ActionReject {
+ if v := s.Scan(Input{Policy: testForm(), Body: strings.Repeat("a", 600)}); v.Action == ActionReject {
t.Fatal("an overlong regex pattern must not be compiled or matched")
}
}
diff --git a/internal/services/messagescan/signals.go b/internal/services/messagescan/signals.go
index 99ef73a..c3ee4f9 100644
--- a/internal/services/messagescan/signals.go
+++ b/internal/services/messagescan/signals.go
@@ -155,10 +155,10 @@ func signalRepeatIP(s *Scanner, in Input) (float64, string) {
}
func signalRepeatSender(s *Scanner, in Input) (float64, string) {
- if s.lookup == nil || in.SenderEmail == "" || in.Form == nil {
+ if s.lookup == nil || in.SenderEmail == "" || in.Policy == nil {
return 0, ""
}
- n := s.lookup.SubmissionsFromSender(in.Form.ID, in.SenderEmail, time.Now().Add(-time.Hour))
+ n := s.lookup.SubmissionsFromSender(in.Policy.ScanSource(), in.SenderEmail, time.Now().Add(-time.Hour))
if n >= 3 {
return 2, fmt.Sprintf("repeat_sender:%d", n)
}
diff --git a/internal/services/notification/templates/new_message.tmpl b/internal/services/notification/templates/new_message.tmpl
index aec789d..405ebac 100644
--- a/internal/services/notification/templates/new_message.tmpl
+++ b/internal/services/notification/templates/new_message.tmpl
@@ -1,8 +1,17 @@
{{ define "content" }}
-<h2 style="color: #111827; font-size: 20px; line-height: 1.3; margin: 0 0 18px; font-weight: 700; letter-spacing: -0.01em;">New message on {{ .FormName }}</h2>
+<h2 style="color: #111827; font-size: 20px; line-height: 1.3; margin: 0 0 18px; font-weight: 700; letter-spacing: -0.01em;">{{ if .Reply }}New reply on {{ .FormName }}{{ else }}New message on {{ .FormName }}{{ end }}</h2>
<p style="margin: 0 0 16px;">Hi {{ .UserName }},</p>
+{{ if .Reply }}
+<p style="margin: 0 0 16px;">The sender answered a <strong>{{ .FormName }}</strong> conversation{{ if .WorkspaceName }} in <strong>{{ .WorkspaceName }}</strong>{{ end }} by email.</p>
+{{ if .SenderMismatch }}
+<div class="alert-box alert-warning" style="padding: 14px 16px; border-radius: 10px; margin: 20px 0; font-size: 14px; line-height: 1.55; background-color: #fffbeb; border: 1px solid #fde68a; color: #92400e;">
+ This reply came from a different address than the original message. It may be a forward, or someone using the thread's reply address.
+</div>
+{{ end }}
+{{ else }}
<p style="margin: 0 0 16px;">{{ if .WorkspaceName }}<strong>{{ .WorkspaceName }}</strong> received{{ else }}You received{{ end }} a new message through the <strong>{{ .FormName }}</strong> form.</p>
+{{ end }}
{{ if .Flagged }}
<div class="alert-box alert-warning" style="padding: 14px 16px; border-radius: 10px; margin: 20px 0; font-size: 14px; line-height: 1.55; background-color: #fffbeb; border: 1px solid #fde68a; color: #92400e;">
diff --git a/internal/services/ratelimit/quota.go b/internal/services/ratelimit/quota.go
new file mode 100644
index 0000000..220b8f7
--- /dev/null
+++ b/internal/services/ratelimit/quota.go
@@ -0,0 +1,100 @@
+// Copyright (c) 2026 Jonas Kaninda.
+//
+// This file is part of Posta.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+//
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package ratelimit
+
+import (
+ "context"
+ "errors"
+ "time"
+
+ "github.com/redis/go-redis/v9"
+)
+
+var (
+ // ErrQuotaExceeded means a counter went over its limit.
+ ErrQuotaExceeded = errors.New("quota exceeded")
+ // ErrQuotaUnavailable means a counter could not be read. Public endpoints
+ // treat it as exceeded: one that stops accepting is better than one that
+ // stops limiting.
+ ErrQuotaUnavailable = errors.New("quota store unavailable")
+)
+
+// Quota is one fixed-window counter: at most Limit hits per Window under Key.
+type Quota struct {
+ Key string
+ Limit int
+ Window time.Duration
+}
+
+// Counter increments a key and guarantees it expires.
+type Counter interface {
+ Incr(ctx context.Context, key string, window time.Duration) (int64, error)
+}
+
+type redisCounter struct {
+ rdb *redis.Client
+}
+
+// Incr runs INCR and EXPIRE NX in one MULTI, so a key can never be left
+// without a TTL; a key stranded without one by older code is given one on its
+// next hit. EXPIRE NX needs Redis 7.0 or later.
+func (c redisCounter) Incr(ctx context.Context, key string, window time.Duration) (int64, error) {
+ pipe := c.rdb.TxPipeline()
+ incr := pipe.Incr(ctx, key)
+ pipe.ExpireNX(ctx, key, window)
+ if _, err := pipe.Exec(ctx); err != nil {
+ return 0, err
+ }
+ return incr.Val(), nil
+}
+
+// Quotas checks a set of counters for one request.
+type Quotas struct {
+ counter Counter
+}
+
+// NewQuotas returns Quotas backed by Redis.
+func NewQuotas(rdb *redis.Client) *Quotas {
+ return &Quotas{counter: redisCounter{rdb: rdb}}
+}
+
+// NewQuotasWithCounter returns Quotas over any Counter, for tests.
+func NewQuotasWithCounter(c Counter) *Quotas {
+ return &Quotas{counter: c}
+}
+
+// Check counts the request against each quota in order and stops at the first
+// one it exceeds, so later counters are not charged for a request that was
+// already refused. A quota with no key or a non-positive limit is skipped.
+func (q *Quotas) Check(ctx context.Context, quotas []Quota) error {
+ for _, quota := range quotas {
+ if quota.Key == "" || quota.Limit <= 0 {
+ continue
+ }
+ n, err := q.counter.Incr(ctx, quota.Key, quota.Window)
+ if err != nil {
+ return ErrQuotaUnavailable
+ }
+ if n > int64(quota.Limit) {
+ return ErrQuotaExceeded
+ }
+ }
+ return nil
+}
diff --git a/internal/services/ratelimit/quota_test.go b/internal/services/ratelimit/quota_test.go
new file mode 100644
index 0000000..dfc2c5b
--- /dev/null
+++ b/internal/services/ratelimit/quota_test.go
@@ -0,0 +1,146 @@
+// Copyright (c) 2026 Jonas Kaninda.
+//
+// This file is part of Posta.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+//
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package ratelimit
+
+import (
+ "context"
+ "errors"
+ "os"
+ "testing"
+ "time"
+
+ "github.com/redis/go-redis/v9"
+)
+
+type fakeCounter struct {
+ counts map[string]int64
+ calls []string
+ err error
+}
+
+func (f *fakeCounter) Incr(_ context.Context, key string, _ time.Duration) (int64, error) {
+ f.calls = append(f.calls, key)
+ if f.err != nil {
+ return 0, f.err
+ }
+ if f.counts == nil {
+ f.counts = map[string]int64{}
+ }
+ f.counts[key]++
+ return f.counts[key], nil
+}
+
+func TestQuotasAllowUpToLimit(t *testing.T) {
+ q := NewQuotasWithCounter(&fakeCounter{})
+ quota := []Quota{{Key: "k", Limit: 2, Window: time.Hour}}
+ for i := 0; i < 2; i++ {
+ if err := q.Check(context.Background(), quota); err != nil {
+ t.Fatalf("hit %d: %v", i+1, err)
+ }
+ }
+ if err := q.Check(context.Background(), quota); !errors.Is(err, ErrQuotaExceeded) {
+ t.Fatalf("third hit = %v, want ErrQuotaExceeded", err)
+ }
+}
+
+func TestQuotasStopAtFirstExceeded(t *testing.T) {
+ counter := &fakeCounter{counts: map[string]int64{"ip": 5}}
+ q := NewQuotasWithCounter(counter)
+ err := q.Check(context.Background(), []Quota{
+ {Key: "ip", Limit: 5, Window: time.Hour},
+ {Key: "form", Limit: 100, Window: time.Hour},
+ })
+ if !errors.Is(err, ErrQuotaExceeded) {
+ t.Fatalf("err = %v", err)
+ }
+ if counter.counts["form"] != 0 {
+ t.Fatal("a refused request must not be charged to later quotas")
+ }
+}
+
+func TestQuotasFailClosed(t *testing.T) {
+ q := NewQuotasWithCounter(&fakeCounter{err: errors.New("redis down")})
+ err := q.Check(context.Background(), []Quota{{Key: "k", Limit: 10, Window: time.Hour}})
+ if !errors.Is(err, ErrQuotaUnavailable) {
+ t.Fatalf("err = %v, want ErrQuotaUnavailable", err)
+ }
+}
+
+func TestQuotasSkipUnsetQuotas(t *testing.T) {
+ counter := &fakeCounter{}
+ q := NewQuotasWithCounter(counter)
+ if err := q.Check(context.Background(), []Quota{
+ {Key: "", Limit: 1, Window: time.Hour},
+ {Key: "disabled", Limit: 0, Window: time.Hour},
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if len(counter.calls) != 0 {
+ t.Fatalf("unexpected counter calls: %v", counter.calls)
+ }
+}
+
+// TestRedisCounterAlwaysSetsTTL runs only against a real Redis 7+, set via
+// POSTA_TEST_REDIS_URL. It covers the bug this counter fixes: a key left
+// without a TTL by a lost EXPIRE stayed over its limit forever.
+func TestRedisCounterAlwaysSetsTTL(t *testing.T) {
+ url := os.Getenv("POSTA_TEST_REDIS_URL")
+ if url == "" {
+ t.Skip("POSTA_TEST_REDIS_URL not set")
+ }
+ opt, err := redis.ParseURL(url)
+ if err != nil {
+ t.Fatal(err)
+ }
+ rdb := redis.NewClient(opt)
+ defer func() { _ = rdb.Close() }()
+ ctx := context.Background()
+ key := "posta:test:quota:" + time.Now().Format("150405.000000")
+ defer rdb.Del(ctx, key)
+
+ // Simulate a key stranded by the old INCR-then-EXPIRE code.
+ if err := rdb.Set(ctx, key, 50, 0).Err(); err != nil {
+ t.Fatal(err)
+ }
+ c := redisCounter{rdb: rdb}
+ n, err := c.Incr(ctx, key, time.Minute)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if n != 51 {
+ t.Fatalf("count = %d, want 51", n)
+ }
+ ttl, err := rdb.TTL(ctx, key).Result()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if ttl <= 0 || ttl > time.Minute {
+ t.Fatalf("ttl = %v, want a TTL within the window", ttl)
+ }
+
+ // A later hit must not push the expiry out (fixed window, not sliding).
+ time.Sleep(1100 * time.Millisecond)
+ if _, err := c.Incr(ctx, key, time.Minute); err != nil {
+ t.Fatal(err)
+ }
+ if ttl2, _ := rdb.TTL(ctx, key).Result(); ttl2 >= ttl {
+ t.Fatalf("ttl grew from %v to %v; EXPIRE NX must not reset it", ttl, ttl2)
+ }
+}
diff --git a/internal/services/realtime/realtime.go b/internal/services/realtime/realtime.go
new file mode 100644
index 0000000..c875401
--- /dev/null
+++ b/internal/services/realtime/realtime.go
@@ -0,0 +1,148 @@
+// Copyright (c) 2026 Jonas Kaninda.
+//
+// This file is part of Posta.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+//
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+// Package realtime fans out live events to SSE subscribers across every Posta
+// process. Unlike eventbus, it does not persist anything and it is not limited
+// to the process that published: the Redis implementation lets the worker
+// publish an event that a dashboard connected to any server replica receives.
+//
+// Delivery is best effort. A subscriber that is not connected when an event is
+// published never sees it, so the database stays the source of truth and an
+// event is only a hint to refetch.
+package realtime
+
+import (
+ "context"
+ "fmt"
+ "sync"
+)
+
+// Event is one live notification.
+type Event struct {
+ Type string `json:"type"`
+ WorkspaceID uint `json:"workspace_id"`
+ Topic string `json:"topic"`
+ Data any `json:"data,omitempty"`
+}
+
+// Bus publishes and subscribes to topics.
+type Bus interface {
+ // Publish sends ev to every current subscriber of ev.Topic, in every process.
+ Publish(ctx context.Context, ev Event) error
+ // Subscribe returns a channel of events on topic and a function that ends
+ // the subscription and closes the channel. The function is safe to call once.
+ Subscribe(ctx context.Context, topic string) (<-chan Event, func())
+}
+
+// WorkspaceTopic is the topic that carries a workspace's dashboard events.
+// Topics are built from database IDs only, never from client input.
+func WorkspaceTopic(workspaceID uint) string {
+ return fmt.Sprintf("ws:%d", workspaceID)
+}
+
+// subscriberBuffer is how many undelivered events a subscriber may hold before
+// further events are dropped for it.
+const subscriberBuffer = 64
+
+// hub is the in-process fan-out shared by both Bus implementations.
+type hub struct {
+ mu sync.RWMutex
+ topics map[string]map[uint64]chan Event
+ nextID uint64
+}
+
+func newHub() *hub {
+ return &hub{topics: make(map[string]map[uint64]chan Event)}
+}
+
+// add registers a subscriber and reports whether it is the topic's first.
+func (h *hub) add(topic string) (uint64, chan Event, bool) {
+ ch := make(chan Event, subscriberBuffer)
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ subs, ok := h.topics[topic]
+ if !ok {
+ subs = make(map[uint64]chan Event)
+ h.topics[topic] = subs
+ }
+ id := h.nextID
+ h.nextID++
+ subs[id] = ch
+ return id, ch, !ok
+}
+
+// remove drops a subscriber and reports whether the topic has none left.
+func (h *hub) remove(topic string, id uint64) bool {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ subs, ok := h.topics[topic]
+ if !ok {
+ return false
+ }
+ if ch, ok := subs[id]; ok {
+ delete(subs, id)
+ close(ch)
+ }
+ if len(subs) == 0 {
+ delete(h.topics, topic)
+ return true
+ }
+ return false
+}
+
+// deliver hands ev to every local subscriber of its topic. A subscriber whose
+// buffer is full misses the event rather than stalling everyone else.
+func (h *hub) deliver(ev Event) {
+ h.mu.RLock()
+ defer h.mu.RUnlock()
+ for _, ch := range h.topics[ev.Topic] {
+ select {
+ case ch <- ev:
+ default:
+ }
+ }
+}
+
+func (h *hub) topicCount() int {
+ h.mu.RLock()
+ defer h.mu.RUnlock()
+ return len(h.topics)
+}
+
+// memoryBus is a single-process Bus, for tests and for deployments that run
+// the worker embedded in the server.
+type memoryBus struct {
+ hub *hub
+}
+
+// NewMemory returns a Bus that only reaches subscribers in this process.
+func NewMemory() Bus {
+ return &memoryBus{hub: newHub()}
+}
+
+func (b *memoryBus) Publish(_ context.Context, ev Event) error {
+ b.hub.deliver(ev)
+ return nil
+}
+
+func (b *memoryBus) Subscribe(_ context.Context, topic string) (<-chan Event, func()) {
+ id, ch, _ := b.hub.add(topic)
+ var once sync.Once
+ return ch, func() { once.Do(func() { b.hub.remove(topic, id) }) }
+}
diff --git a/internal/services/realtime/realtime_test.go b/internal/services/realtime/realtime_test.go
new file mode 100644
index 0000000..b737214
--- /dev/null
+++ b/internal/services/realtime/realtime_test.go
@@ -0,0 +1,166 @@
+// Copyright (c) 2026 Jonas Kaninda.
+//
+// This file is part of Posta.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+//
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package realtime
+
+import (
+ "context"
+ "os"
+ "testing"
+ "time"
+
+ "github.com/redis/go-redis/v9"
+)
+
+func receive(t *testing.T, ch <-chan Event) Event {
+ t.Helper()
+ select {
+ case ev, ok := <-ch:
+ if !ok {
+ t.Fatal("channel closed before an event arrived")
+ }
+ return ev
+ case <-time.After(2 * time.Second):
+ t.Fatal("timed out waiting for an event")
+ }
+ return Event{}
+}
+
+func expectNothing(t *testing.T, ch <-chan Event) {
+ t.Helper()
+ select {
+ case ev, ok := <-ch:
+ if ok {
+ t.Fatalf("unexpected event %+v", ev)
+ }
+ case <-time.After(50 * time.Millisecond):
+ }
+}
+
+func TestMemoryFanOutToEverySubscriberOfATopic(t *testing.T) {
+ bus := NewMemory()
+ ctx := context.Background()
+
+ a, unsubA := bus.Subscribe(ctx, WorkspaceTopic(1))
+ defer unsubA()
+ b, unsubB := bus.Subscribe(ctx, WorkspaceTopic(1))
+ defer unsubB()
+ other, unsubOther := bus.Subscribe(ctx, WorkspaceTopic(2))
+ defer unsubOther()
+
+ if err := bus.Publish(ctx, Event{Type: "message.received", Topic: WorkspaceTopic(1)}); err != nil {
+ t.Fatal(err)
+ }
+
+ if got := receive(t, a); got.Type != "message.received" {
+ t.Fatalf("a got %q", got.Type)
+ }
+ if got := receive(t, b); got.Type != "message.received" {
+ t.Fatalf("b got %q", got.Type)
+ }
+ expectNothing(t, other)
+}
+
+func TestMemoryUnsubscribeClosesChannelAndIsIdempotent(t *testing.T) {
+ bus := NewMemory()
+ ch, unsub := bus.Subscribe(context.Background(), "ws:1")
+ unsub()
+ unsub()
+ if _, ok := <-ch; ok {
+ t.Fatal("channel should be closed after unsubscribe")
+ }
+}
+
+func TestHubTearsDownTopicWithLastSubscriber(t *testing.T) {
+ h := newHub()
+ id1, _, first := h.add("ws:1")
+ if !first {
+ t.Fatal("first subscriber should report first")
+ }
+ id2, _, first := h.add("ws:1")
+ if first {
+ t.Fatal("second subscriber should not report first")
+ }
+ if h.remove("ws:1", id1) {
+ t.Fatal("topic should remain while a subscriber is left")
+ }
+ if !h.remove("ws:1", id2) {
+ t.Fatal("removing the last subscriber should report the topic empty")
+ }
+ if n := h.topicCount(); n != 0 {
+ t.Fatalf("topicCount = %d, want 0", n)
+ }
+}
+
+func TestSlowSubscriberIsDroppedNotBlocking(t *testing.T) {
+ bus := NewMemory()
+ ctx := context.Background()
+ slow, unsubSlow := bus.Subscribe(ctx, "ws:1")
+ defer unsubSlow()
+ fast, unsubFast := bus.Subscribe(ctx, "ws:1")
+ defer unsubFast()
+
+ done := make(chan struct{})
+ go func() {
+ for i := 0; i < subscriberBuffer*3; i++ {
+ _ = bus.Publish(ctx, Event{Type: "tick", Topic: "ws:1"})
+ <-fast
+ }
+ close(done)
+ }()
+
+ select {
+ case <-done:
+ case <-time.After(2 * time.Second):
+ t.Fatal("publishing blocked on a slow subscriber")
+ }
+ if n := len(slow); n != subscriberBuffer {
+ t.Fatalf("slow subscriber holds %d events, want its buffer of %d", n, subscriberBuffer)
+ }
+}
+
+// TestRedisBusAcrossClients runs only against a real Redis, set via
+// POSTA_TEST_REDIS_URL (for example redis://localhost:6379/15). Two buses with
+// separate clients stand in for two processes.
+func TestRedisBusAcrossClients(t *testing.T) {
+ url := os.Getenv("POSTA_TEST_REDIS_URL")
+ if url == "" {
+ t.Skip("POSTA_TEST_REDIS_URL not set")
+ }
+ opt, err := redis.ParseURL(url)
+ if err != nil {
+ t.Fatal(err)
+ }
+ pubClient, subClient := redis.NewClient(opt), redis.NewClient(opt)
+ defer func() { _ = pubClient.Close(); _ = subClient.Close() }()
+
+ publisher, subscriber := NewRedis(pubClient), NewRedis(subClient)
+ ctx := context.Background()
+ ch, unsub := subscriber.Subscribe(ctx, "ws:test")
+ defer unsub()
+ time.Sleep(100 * time.Millisecond) // let SUBSCRIBE reach the server
+
+ if err := publisher.Publish(ctx, Event{Type: "message.received", WorkspaceID: 7, Topic: "ws:test"}); err != nil {
+ t.Fatal(err)
+ }
+ got := receive(t, ch)
+ if got.Type != "message.received" || got.WorkspaceID != 7 || got.Topic != "ws:test" {
+ t.Fatalf("got %+v", got)
+ }
+}
diff --git a/internal/services/realtime/redis.go b/internal/services/realtime/redis.go
new file mode 100644
index 0000000..0b0f820
--- /dev/null
+++ b/internal/services/realtime/redis.go
@@ -0,0 +1,117 @@
+// Copyright (c) 2026 Jonas Kaninda.
+//
+// This file is part of Posta.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+//
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package realtime
+
+import (
+ "context"
+ "encoding/json"
+ "strings"
+ "sync"
+
+ "github.com/jkaninda/logger"
+ "github.com/redis/go-redis/v9"
+)
+
+// channelPrefix namespaces Posta's pub/sub channels on a shared Redis.
+const channelPrefix = "posta:rt:"
+
+// redisBus fans out through Redis pub/sub. Each process holds one pub/sub
+// connection and subscribes to a Redis channel only while it has at least one
+// local subscriber for that topic, so a replica with thousands of open streams
+// on one workspace still holds a single Redis subscription for it.
+type redisBus struct {
+ rdb *redis.Client
+ hub *hub
+
+ mu sync.Mutex
+ ps *redis.PubSub
+ started bool
+}
+
+// NewRedis returns a Bus backed by Redis pub/sub.
+func NewRedis(rdb *redis.Client) Bus {
+ return &redisBus{rdb: rdb, hub: newHub()}
+}
+
+func (b *redisBus) Publish(ctx context.Context, ev Event) error {
+ payload, err := json.Marshal(ev)
+ if err != nil {
+ return err
+ }
+ return b.rdb.Publish(ctx, channelPrefix+ev.Topic, payload).Err()
+}
+
+func (b *redisBus) Subscribe(ctx context.Context, topic string) (<-chan Event, func()) {
+ id, ch, first := b.hub.add(topic)
+ if first {
+ b.redisSubscribe(ctx, topic)
+ }
+ var once sync.Once
+ return ch, func() {
+ once.Do(func() {
+ if b.hub.remove(topic, id) {
+ b.redisUnsubscribe(topic)
+ }
+ })
+ }
+}
+
+// redisSubscribe adds topic to the process-wide pub/sub connection, opening it
+// and starting the reader on first use.
+func (b *redisBus) redisSubscribe(ctx context.Context, topic string) {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ if b.ps == nil {
+ b.ps = b.rdb.Subscribe(context.Background())
+ }
+ if err := b.ps.Subscribe(ctx, channelPrefix+topic); err != nil {
+ logger.Warn("realtime: redis subscribe failed", "topic", topic, "error", err)
+ }
+ if !b.started {
+ b.started = true
+ go b.read(b.ps)
+ }
+}
+
+func (b *redisBus) redisUnsubscribe(topic string) {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ if b.ps == nil {
+ return
+ }
+ if err := b.ps.Unsubscribe(context.Background(), channelPrefix+topic); err != nil {
+ logger.Warn("realtime: redis unsubscribe failed", "topic", topic, "error", err)
+ }
+}
+
+// read relays every Redis message to local subscribers. go-redis reconnects
+// and resubscribes on its own, so this loop only ends if the PubSub is closed.
+func (b *redisBus) read(ps *redis.PubSub) {
+ for msg := range ps.Channel() {
+ var ev Event
+ if err := json.Unmarshal([]byte(msg.Payload), &ev); err != nil {
+ logger.Warn("realtime: dropping malformed event", "channel", msg.Channel, "error", err)
+ continue
+ }
+ // The channel name is authoritative; never trust a topic carried in a payload.
+ ev.Topic = strings.TrimPrefix(msg.Channel, channelPrefix)
+ b.hub.deliver(ev)
+ }
+}
diff --git a/internal/storage/migration/constraints.go b/internal/storage/migration/constraints.go
index 2ef0c3d..d721517 100644
--- a/internal/storage/migration/constraints.go
+++ b/internal/storage/migration/constraints.go
@@ -116,6 +116,31 @@ func runConstraints(db *gorm.DB) {
EXCEPTION WHEN others THEN NULL;
END $$`)
+ // One thread reply per inbound email, so a retried parse task cannot attach
+ // the same answer twice. Its own block: a failure must not skip the others.
+ db.Exec(`DO $$ BEGIN
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_message_replies_inbound ON message_replies (inbound_email_id) WHERE inbound_email_id IS NOT NULL;
+ EXCEPTION WHEN others THEN NULL;
+ END $$`)
+
+ // AutoMigrate used to create fk_messages_form and fk_messages_replies from
+ // the model associations without ON DELETE CASCADE, which made every delete
+ // of a replied message (retention, GDPR erasure) fail. Replace a
+ // non-cascading copy in place; the blocks below then find it present.
+ db.Exec(`DO $$ BEGIN
+ IF EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'fk_messages_replies' AND confdeltype <> 'c') THEN
+ ALTER TABLE message_replies DROP CONSTRAINT fk_messages_replies;
+ ALTER TABLE message_replies ADD CONSTRAINT fk_messages_replies
+ FOREIGN KEY (message_id) REFERENCES messages(id) ON DELETE CASCADE;
+ END IF;
+ IF EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'fk_messages_form' AND confdeltype <> 'c') THEN
+ ALTER TABLE messages DROP CONSTRAINT fk_messages_form;
+ ALTER TABLE messages ADD CONSTRAINT fk_messages_form
+ FOREIGN KEY (form_id) REFERENCES forms(id) ON DELETE CASCADE;
+ END IF;
+ EXCEPTION WHEN others THEN NULL;
+ END $$`)
+
db.Exec(`DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'fk_messages_form') THEN
ALTER TABLE messages ADD CONSTRAINT fk_messages_form
diff --git a/internal/storage/repositories/actor_cascade_test.go b/internal/storage/repositories/actor_cascade_test.go
index 2952cb9..f35d6d5 100644
--- a/internal/storage/repositories/actor_cascade_test.go
+++ b/internal/storage/repositories/actor_cascade_test.go
@@ -115,7 +115,7 @@ func TestMessageUpdateDoesNotCascadeIntoUsers(t *testing.T) {
}
if err := repo.AddReply(&models.MessageReply{
MessageID: msg.ID, WorkspaceID: &wsID, Kind: models.MessageReplyKindOperator,
- AuthorID: userID, FromAddr: "[email protected]", ToAddr: "[email protected]",
+ AuthorID: &userID, FromAddr: "[email protected]", ToAddr: "[email protected]",
}); err != nil {
t.Fatalf("add reply: %v", err)
}
diff --git a/internal/storage/repositories/form_repo.go b/internal/storage/repositories/form_repo.go
index 2812d66..bf328eb 100644
--- a/internal/storage/repositories/form_repo.go
+++ b/internal/storage/repositories/form_repo.go
@@ -120,3 +120,10 @@ func (r *FormRepository) FindActiveWithDigest(mode models.NotifyMode) ([]models.
Find(&items).Error
return items, err
}
+
+// FindWithRetention returns the forms that set their own message retention.
+func (r *FormRepository) FindWithRetention() ([]models.Form, error) {
+ var items []models.Form
+ err := r.db.Where("retention_days > 0").Find(&items).Error
+ return items, err
+}
diff --git a/internal/storage/repositories/message_erase.go b/internal/storage/repositories/message_erase.go
new file mode 100644
index 0000000..d92ab4e
--- /dev/null
+++ b/internal/storage/repositories/message_erase.go
@@ -0,0 +1,119 @@
+// Copyright (c) 2026 Jonas Kaninda.
+//
+// This file is part of Posta.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+//
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package repositories
+
+import (
+ "encoding/json"
+ "strings"
+
+ "github.com/goposta/posta/internal/models"
+ "gorm.io/gorm"
+)
+
+// EraseMessagesBySender hard-deletes, in one transaction, every web form
+// message one address submitted to a workspace, the thread replies on them,
+// and the inbound emails those replies arrived as. Soft-deleted rows are
+// included: an erasure request is not a trash can.
+//
+// It returns the number of messages deleted and the blob keys (attachments,
+// raw .eml files) the caller must remove once the transaction has committed.
+func EraseMessagesBySender(db *gorm.DB, workspaceID uint, email string) (int64, []string, error) {
+ email = strings.ToLower(strings.TrimSpace(email))
+ var blobKeys []string
+ var deleted int64
+ err := db.Transaction(func(tx *gorm.DB) error {
+ var msgs []models.Message
+ if err := tx.Unscoped().
+ Select("id", "attachments_json").
+ Where("workspace_id = ? AND LOWER(sender_email) = ?", workspaceID, email).
+ Find(&msgs).Error; err != nil {
+ return err
+ }
+ if len(msgs) == 0 {
+ return nil
+ }
+ ids := make([]uint, 0, len(msgs))
+ for _, m := range msgs {
+ ids = append(ids, m.ID)
+ blobKeys = append(blobKeys, AttachmentBlobKeys(m.AttachmentsJSON)...)
+ }
+
+ var inboundIDs []uint
+ if err := tx.Model(&models.MessageReply{}).
+ Where("message_id IN ? AND inbound_email_id IS NOT NULL", ids).
+ Pluck("inbound_email_id", &inboundIDs).Error; err != nil {
+ return err
+ }
+ if len(inboundIDs) > 0 {
+ var inbound []models.InboundEmail
+ if err := tx.Unscoped().
+ Select("id", "attachments_json", "raw_storage_key").
+ Where("id IN ? AND workspace_id = ?", inboundIDs, workspaceID).
+ Find(&inbound).Error; err != nil {
+ return err
+ }
+ for _, rec := range inbound {
+ blobKeys = append(blobKeys, AttachmentBlobKeys(rec.AttachmentsJSON)...)
+ if rec.RawStorageKey != "" {
+ blobKeys = append(blobKeys, rec.RawStorageKey)
+ }
+ }
+ if err := tx.Unscoped().Where("id IN ? AND workspace_id = ?", inboundIDs, workspaceID).
+ Delete(&models.InboundEmail{}).Error; err != nil {
+ return err
+ }
+ }
+
+ // Delete replies explicitly rather than relying on the cascade alone, so
+ // erasure holds even where the foreign key was never created.
+ if err := tx.Where("message_id IN ?", ids).Delete(&models.MessageReply{}).Error; err != nil {
+ return err
+ }
+ result := tx.Unscoped().Where("id IN ?", ids).Delete(&models.Message{})
+ if result.Error != nil {
+ return result.Error
+ }
+ deleted = result.RowsAffected
+ return nil
+ })
+ if err != nil {
+ return 0, nil, err
+ }
+ return deleted, blobKeys, nil
+}
+
+// AttachmentBlobKeys returns the blob storage keys in an attachments_json
+// column (a []models.InboundAttachmentMeta).
+func AttachmentBlobKeys(attachmentsJSON string) []string {
+ if attachmentsJSON == "" {
+ return nil
+ }
+ var atts []models.InboundAttachmentMeta
+ if err := json.Unmarshal([]byte(attachmentsJSON), &atts); err != nil {
+ return nil
+ }
+ keys := make([]string, 0, len(atts))
+ for _, a := range atts {
+ if a.StorageKey != "" {
+ keys = append(keys, a.StorageKey)
+ }
+ }
+ return keys
+}
diff --git a/internal/storage/repositories/message_repo.go b/internal/storage/repositories/message_repo.go
index a64e1a0..d06bc8f 100644
--- a/internal/storage/repositories/message_repo.go
+++ b/internal/storage/repositories/message_repo.go
@@ -51,10 +51,65 @@ func (r *MessageRepository) Create(m *models.Message) error {
return r.db.Create(m).Error
}
+// Update writes every column of m. It must not be used after a slow operation
+// (sending mail, calling out): the row may have changed in the meantime, and a
+// full-row save would silently undo those changes. Use UpdateFields instead.
func (r *MessageRepository) Update(m *models.Message) error {
return r.db.Omit(clause.Associations).Save(m).Error
}
+// UpdateFields writes only the given columns, so concurrent changes to other
+// columns of the same message survive.
+func (r *MessageRepository) UpdateFields(id uint, fields map[string]any) error {
+ if len(fields) == 0 {
+ return nil
+ }
+ return r.db.Model(&models.Message{}).Where("id = ?", id).Updates(fields).Error
+}
+
+// RecordReply applies the effects of an operator reply atomically: it bumps the
+// reply count, stamps replied_at, marks the message read if it was not, and
+// moves it to replied unless an operator has already closed it.
+func (r *MessageRepository) RecordReply(id uint, at time.Time) error {
+ return r.db.Model(&models.Message{}).Where("id = ?", id).Updates(map[string]any{
+ "replied_at": at,
+ "updated_at": at,
+ "reply_count": gorm.Expr("reply_count + 1"),
+ "read_at": gorm.Expr("COALESCE(read_at, ?)", at),
+ "state": gorm.Expr("CASE WHEN state = ? THEN state ELSE ? END",
+ models.MessageStateClosed, models.MessageStateReplied),
+ }).Error
+}
+
+// MarkRead stamps read_at if unset and moves a new message to open, without
+// touching any other column.
+func (r *MessageRepository) MarkRead(id uint, at time.Time) error {
+ return r.db.Model(&models.Message{}).Where("id = ? AND read_at IS NULL", id).Updates(map[string]any{
+ "read_at": at,
+ "state": gorm.Expr("CASE WHEN state = ? THEN ? ELSE state END",
+ models.MessageStateNew, models.MessageStateOpen),
+ }).Error
+}
+
+// SetRootMessageID records the Message-ID of a thread's first reply. It only
+// writes when none is set, so two concurrent first replies cannot both claim it.
+func (r *MessageRepository) SetRootMessageID(id uint, messageID string) error {
+ return r.db.Model(&models.Message{}).
+ Where("id = ? AND (root_message_id IS NULL OR root_message_id = '')", id).
+ Update("root_message_id", messageID).Error
+}
+
+// ReplyMessageIDs returns the Message-ID headers of a thread's replies, oldest
+// first, skipping replies recorded before Message-IDs were stored.
+func (r *MessageRepository) ReplyMessageIDs(messageID uint) ([]string, error) {
+ var ids []string
+ err := r.db.Model(&models.MessageReply{}).
+ Where("message_id = ? AND message_id_header <> ''", messageID).
+ Order("created_at ASC, id ASC").
+ Pluck("message_id_header", &ids).Error
+ return ids, err
+}
+
func (r *MessageRepository) FindByID(id uint) (*models.Message, error) {
var m models.Message
if err := r.db.First(&m, id).Error; err != nil {
@@ -199,6 +254,19 @@ func (r *MessageRepository) AddReply(reply *models.MessageReply) error {
return r.db.Create(reply).Error
}
+// AddInboundReply stores an inbound reply unless the same inbound email is
+// already attached (the unique index on inbound_email_id), so a retried parse
+// task cannot add it twice. It reports whether a row was created.
+func (r *MessageRepository) AddInboundReply(reply *models.MessageReply) (bool, error) {
+ if err := r.db.Create(reply).Error; err != nil {
+ if IsDuplicateName(err) {
+ return false, nil
+ }
+ return false, err
+ }
+ return true, nil
+}
+
func (r *MessageRepository) FindReplyByID(id uint) (*models.MessageReply, error) {
var reply models.MessageReply
if err := r.db.First(&reply, id).Error; err != nil {
@@ -226,6 +294,30 @@ func (r *MessageRepository) DeleteSpamOlderThan(before time.Time) (int64, error)
return result.RowsAffected, result.Error
}
+// DeleteByFormOlderThan hard-deletes one form's messages received before the
+// cutoff; replies go with them through the ON DELETE CASCADE foreign key.
+func (r *MessageRepository) DeleteByFormOlderThan(formID uint, before time.Time) (int64, error) {
+ result := r.db.Unscoped().Where("form_id = ? AND created_at < ?", formID, before).Delete(&models.Message{})
+ return result.RowsAffected, result.Error
+}
+
+func (r *MessageRepository) AttachmentKeysByFormOlderThan(formID uint, before time.Time) ([]string, error) {
+ var payloads []string
+ err := r.db.Unscoped().Model(&models.Message{}).
+ Where("form_id = ? AND created_at < ? AND attachments_json <> ''", formID, before).
+ Pluck("attachments_json", &payloads).Error
+ return payloads, err
+}
+
+func (r *MessageRepository) SpamAttachmentKeysOlderThan(before time.Time) ([]string, error) {
+ var payloads []string
+ err := r.db.Unscoped().Model(&models.Message{}).
+ Where("created_at < ? AND attachments_json <> '' AND status IN ?", before,
+ []models.MessageStatus{models.MessageStatusQuarantined, models.MessageStatusRejected}).
+ Pluck("attachments_json", &payloads).Error
+ return payloads, err
+}
+
func (r *MessageRepository) AttachmentKeysOlderThan(before time.Time) ([]string, error) {
var payloads []string
err := r.db.Unscoped().Model(&models.Message{}).
diff --git a/internal/storage/repositories/message_repo_db_test.go b/internal/storage/repositories/message_repo_db_test.go
new file mode 100644
index 0000000..7d85a3e
--- /dev/null
+++ b/internal/storage/repositories/message_repo_db_test.go
@@ -0,0 +1,339 @@
+// Copyright (c) 2026 Jonas Kaninda.
+//
+// This file is part of Posta.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+//
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package repositories_test
+
+import (
+ "fmt"
+ "os"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/goposta/posta/internal/models"
+ "github.com/goposta/posta/internal/storage/migration"
+ "github.com/goposta/posta/internal/storage/repositories"
+ "gorm.io/driver/postgres"
+ "gorm.io/gorm"
+ "gorm.io/gorm/logger"
+)
+
+var (
+ migrateOnce sync.Once
+ migrateErr error
+)
+
+// migratedDB opens TEST_DATABASE_DSN and runs the full migration once, so these
+// tests exercise the real schema, constraints included. Unlike testDB they
+// never fall back to a default DSN: the migration rewrites the schema, so it
+// must only run against a database that was named for it. Each test works in
+// a transaction it rolls back.
+func migratedDB(t *testing.T) *gorm.DB {
+ t.Helper()
+ dsn := os.Getenv("TEST_DATABASE_DSN")
+ if dsn == "" {
+ t.Skip("TEST_DATABASE_DSN not set")
+ }
+ db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
+ if err != nil {
+ t.Skipf("no test database: %v", err)
+ }
+ migrateOnce.Do(func() { migrateErr = migration.Run(db) })
+ if migrateErr != nil {
+ t.Fatalf("migrate: %v", migrateErr)
+ }
+ tx := db.Begin()
+ t.Cleanup(func() { tx.Rollback() })
+ return tx
+}
+
+type fixture struct {
+ user uint
+ ws uint
+ form *models.Form
+}
+
+func newFixture(t *testing.T, tx *gorm.DB, tag string) fixture {
+ t.Helper()
+ user := &models.User{Name: "t", Email: tag + "@test.local", PasswordHash: "x"}
+ if err := tx.Create(user).Error; err != nil {
+ t.Fatalf("user: %v", err)
+ }
+ ws := &models.Workspace{Name: tag, Slug: tag + fmt.Sprint(time.Now().UnixNano()), OwnerID: user.ID}
+ if err := tx.Create(ws).Error; err != nil {
+ t.Fatalf("workspace: %v", err)
+ }
+ form := &models.Form{WorkspaceID: &ws.ID, Name: tag, Slug: tag, PublicKey: tag + fmt.Sprint(time.Now().UnixNano())}
+ if err := tx.Create(form).Error; err != nil {
+ t.Fatalf("form: %v", err)
+ }
+ return fixture{user: user.ID, ws: ws.ID, form: form}
+}
+
+func (f fixture) message(t *testing.T, tx *gorm.DB, mutate func(*models.Message)) *models.Message {
+ t.Helper()
+ m := &models.Message{
+ WorkspaceID: &f.ws, FormID: f.form.ID, SenderEmail: "[email protected]",
+ Status: models.MessageStatusReceived, State: models.MessageStateNew,
+ ThreadToken: fmt.Sprint(time.Now().UnixNano()),
+ }
+ if mutate != nil {
+ mutate(m)
+ }
+ if err := tx.Create(m).Error; err != nil {
+ t.Fatalf("message: %v", err)
+ }
+ return m
+}
+
+func reload(t *testing.T, tx *gorm.DB, id uint) *models.Message {
+ t.Helper()
+ var m models.Message
+ if err := tx.Unscoped().First(&m, id).Error; err != nil {
+ t.Fatalf("reload: %v", err)
+ }
+ return &m
+}
+
+// The bug UpdateFields fixes: the worker loaded a message, spent seconds
+// sending notification mail, then saved its stale copy over an operator's
+// assignment. Column-scoped writes must leave other columns alone.
+func TestUpdateFieldsDoesNotClobberConcurrentChanges(t *testing.T) {
+ tx := migratedDB(t)
+ f := newFixture(t, tx, "clobber")
+ repo := repositories.NewMessageRepository(tx)
+ msg := f.message(t, tx, nil)
+
+ assignee := f.user
+ if err := repo.UpdateFields(msg.ID, map[string]any{"assigned_to_id": assignee, "state": models.MessageStateClosed}); err != nil {
+ t.Fatal(err)
+ }
+ if err := repo.MarkNotified([]uint{msg.ID}, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if err := repo.UpdateFields(msg.ID, map[string]any{"webhook_dispatched_at": time.Now()}); err != nil {
+ t.Fatal(err)
+ }
+
+ got := reload(t, tx, msg.ID)
+ if got.AssignedToID == nil || *got.AssignedToID != assignee || got.State != models.MessageStateClosed {
+ t.Fatalf("operator changes lost: assigned=%v state=%s", got.AssignedToID, got.State)
+ }
+ if got.NotifiedAt == nil || got.WebhookDispatchedAt == nil {
+ t.Fatal("worker stamps not written")
+ }
+}
+
+func TestRecordReplyIsAtomicAndRespectsClosed(t *testing.T) {
+ tx := migratedDB(t)
+ f := newFixture(t, tx, "reply")
+ repo := repositories.NewMessageRepository(tx)
+ open := f.message(t, tx, nil)
+ closed := f.message(t, tx, func(m *models.Message) { m.State = models.MessageStateClosed })
+
+ first := time.Now().Add(-time.Minute).UTC().Truncate(time.Second)
+ if err := repo.RecordReply(open.ID, first); err != nil {
+ t.Fatal(err)
+ }
+ if err := repo.RecordReply(open.ID, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if err := repo.RecordReply(closed.ID, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+
+ got := reload(t, tx, open.ID)
+ if got.ReplyCount != 2 || got.State != models.MessageStateReplied {
+ t.Fatalf("count=%d state=%s, want 2/replied", got.ReplyCount, got.State)
+ }
+ if got.ReadAt == nil || !got.ReadAt.UTC().Equal(first) {
+ t.Fatalf("read_at = %v, want the first reply's time kept", got.ReadAt)
+ }
+ if c := reload(t, tx, closed.ID); c.State != models.MessageStateClosed || c.ReplyCount != 1 {
+ t.Fatalf("closed message: state=%s count=%d", c.State, c.ReplyCount)
+ }
+}
+
+func TestMarkReadOpensNewOnlyOnce(t *testing.T) {
+ tx := migratedDB(t)
+ f := newFixture(t, tx, "read")
+ repo := repositories.NewMessageRepository(tx)
+ fresh := f.message(t, tx, nil)
+ closed := f.message(t, tx, func(m *models.Message) { m.State = models.MessageStateClosed })
+
+ at := time.Now().Add(-time.Hour).UTC().Truncate(time.Second)
+ _ = repo.MarkRead(fresh.ID, at)
+ _ = repo.MarkRead(fresh.ID, time.Now())
+ _ = repo.MarkRead(closed.ID, time.Now())
+
+ got := reload(t, tx, fresh.ID)
+ if got.State != models.MessageStateOpen || got.ReadAt == nil || !got.ReadAt.UTC().Equal(at) {
+ t.Fatalf("state=%s read_at=%v", got.State, got.ReadAt)
+ }
+ if c := reload(t, tx, closed.ID); c.State != models.MessageStateClosed || c.ReadAt == nil {
+ t.Fatalf("closed message: state=%s read_at=%v", c.State, c.ReadAt)
+ }
+}
+
+func TestThreadMessageIDs(t *testing.T) {
+ tx := migratedDB(t)
+ f := newFixture(t, tx, "thread")
+ repo := repositories.NewMessageRepository(tx)
+ msg := f.message(t, tx, nil)
+
+ if err := repo.SetRootMessageID(msg.ID, "<root@x>"); err != nil {
+ t.Fatal(err)
+ }
+ if err := repo.SetRootMessageID(msg.ID, "<second@x>"); err != nil {
+ t.Fatal(err)
+ }
+ if got := reload(t, tx, msg.ID).RootMessageID; got != "<root@x>" {
+ t.Fatalf("root = %q, want the first writer to win", got)
+ }
+
+ base := time.Now().Add(-time.Hour)
+ for i, id := range []string{"<root@x>", "", "<b@x>"} {
+ r := &models.MessageReply{MessageID: msg.ID, WorkspaceID: &f.ws, Kind: models.MessageReplyKindOperator,
+ MessageIDHeader: id, CreatedAt: base.Add(time.Duration(i) * time.Minute)}
+ if err := repo.AddReply(r); err != nil {
+ t.Fatal(err)
+ }
+ }
+ ids, err := repo.ReplyMessageIDs(msg.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(ids) != 2 || ids[0] != "<root@x>" || ids[1] != "<b@x>" {
+ t.Fatalf("ids = %v", ids)
+ }
+}
+
+func TestAddInboundReplyIsIdempotentPerInboundEmail(t *testing.T) {
+ tx := migratedDB(t)
+ f := newFixture(t, tx, "inbound")
+ repo := repositories.NewMessageRepository(tx)
+ msg := f.message(t, tx, nil)
+ inboundID := uint(987654)
+
+ reply := func() *models.MessageReply {
+ return &models.MessageReply{MessageID: msg.ID, WorkspaceID: &f.ws,
+ Kind: models.MessageReplyKindInbound, InboundEmailID: &inboundID}
+ }
+ created, err := repo.AddInboundReply(reply())
+ if err != nil || !created {
+ t.Fatalf("first: created=%v err=%v", created, err)
+ }
+ // The duplicate violates the unique index, which aborts a Postgres
+ // transaction; isolate it in a savepoint as a real retry would be isolated.
+ tx.SavePoint("dupe")
+ created, err = repo.AddInboundReply(reply())
+ tx.RollbackTo("dupe")
+ if err != nil || created {
+ t.Fatalf("duplicate: created=%v err=%v, want false/nil", created, err)
+ }
+}
+
+func TestDeleteByFormOlderThanIsScopedToTheForm(t *testing.T) {
+ tx := migratedDB(t)
+ a := newFixture(t, tx, "reta")
+ b := newFixture(t, tx, "retb")
+ repo := repositories.NewMessageRepository(tx)
+ old := time.Now().AddDate(0, 0, -30)
+
+ oldA := a.message(t, tx, func(m *models.Message) { m.CreatedAt = old })
+ newA := a.message(t, tx, nil)
+ oldB := b.message(t, tx, func(m *models.Message) { m.CreatedAt = old })
+ if err := repo.AddReply(&models.MessageReply{MessageID: oldA.ID, WorkspaceID: &a.ws, Kind: models.MessageReplyKindOperator}); err != nil {
+ t.Fatal(err)
+ }
+
+ n, err := repo.DeleteByFormOlderThan(a.form.ID, time.Now().AddDate(0, 0, -7))
+ if err != nil || n != 1 {
+ t.Fatalf("deleted %d, err %v; want 1", n, err)
+ }
+ var left []uint
+ tx.Unscoped().Model(&models.Message{}).Where("id IN ?", []uint{oldA.ID, newA.ID, oldB.ID}).Pluck("id", &left)
+ if len(left) != 2 {
+ t.Fatalf("remaining = %v, want the recent A and the old B", left)
+ }
+ var replies int64
+ tx.Model(&models.MessageReply{}).Where("message_id = ?", oldA.ID).Count(&replies)
+ if replies != 0 {
+ t.Fatal("replies of a deleted message must cascade")
+ }
+}
+
+func TestEraseMessagesBySender(t *testing.T) {
+ tx := migratedDB(t)
+ f := newFixture(t, tx, "erase")
+ other := newFixture(t, tx, "eraseother")
+
+ domain := &models.Domain{UserID: f.user, WorkspaceID: &f.ws, Domain: "reply.example.com", VerificationToken: "t"}
+ if err := tx.Create(domain).Error; err != nil {
+ t.Fatalf("domain: %v", err)
+ }
+ inbound := &models.InboundEmail{UserID: f.user, WorkspaceID: &f.ws, DomainID: domain.ID, Sender: "[email protected]",
+ Recipients: []string{"[email protected]"}, RawStorageKey: "inbound/x/raw.eml", AttachmentsJSON: `[{"storage_key":"inbound/x/a.pdf"}]`,
+ Status: models.InboundStatusForwarded, Source: models.InboundSourceSMTP}
+ if err := tx.Create(inbound).Error; err != nil {
+ t.Fatalf("inbound: %v", err)
+ }
+
+ target := f.message(t, tx, func(m *models.Message) {
+ m.SenderEmail = "[email protected]"
+ m.AttachmentsJSON = `[{"storage_key":"messages/m/cv.pdf"}]`
+ })
+ softDeleted := f.message(t, tx, nil)
+ tx.Delete(&models.Message{}, softDeleted.ID)
+ keep := f.message(t, tx, func(m *models.Message) { m.SenderEmail = "[email protected]" })
+ otherWS := other.message(t, tx, nil)
+
+ repo := repositories.NewMessageRepository(tx)
+ if err := repo.AddReply(&models.MessageReply{MessageID: target.ID, WorkspaceID: &f.ws,
+ Kind: models.MessageReplyKindInbound, InboundEmailID: &inbound.ID}); err != nil {
+ t.Fatal(err)
+ }
+
+ n, keys, err := repositories.EraseMessagesBySender(tx, f.ws, "[email protected]")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if n != 2 {
+ t.Fatalf("deleted %d, want 2 (including the soft-deleted one)", n)
+ }
+ want := map[string]bool{"messages/m/cv.pdf": true, "inbound/x/a.pdf": true, "inbound/x/raw.eml": true}
+ if len(keys) != len(want) {
+ t.Fatalf("blob keys = %v", keys)
+ }
+ for _, k := range keys {
+ if !want[k] {
+ t.Fatalf("unexpected blob key %q", k)
+ }
+ }
+
+ var count int64
+ tx.Unscoped().Model(&models.Message{}).Where("id IN ?", []uint{keep.ID, otherWS.ID}).Count(&count)
+ if count != 2 {
+ t.Fatal("erasure reached another sender or another workspace")
+ }
+ tx.Unscoped().Model(&models.InboundEmail{}).Where("id = ?", inbound.ID).Count(&count)
+ if count != 0 {
+ t.Fatal("the inbound email behind a thread reply must be erased too")
+ }
+}
diff --git a/internal/worker/inbound_handler.go b/internal/worker/inbound_handler.go
index 1d3aeb1..c938ffd 100644
--- a/internal/worker/inbound_handler.go
+++ b/internal/worker/inbound_handler.go
@@ -112,6 +112,10 @@ func (h *InboundParseHandler) ProcessTask(ctx context.Context, t *asynq.Task) er
return nil
}
+ // ApplyParsed replaces the envelope recipients with the To header; keep them,
+ // since a thread address may only appear in the envelope (Bcc, aliases).
+ envelope := append([]string(nil), rec.Recipients...)
+
if aerr := h.svc.ApplyParsed(ctx, rec, parsed); aerr != nil {
if errors.Is(aerr, inbound.ErrDuplicate) {
return nil
@@ -119,6 +123,13 @@ func (h *InboundParseHandler) ProcessTask(ctx context.Context, t *asynq.Task) er
return fmt.Errorf("apply parsed inbound: %w", aerr)
}
+ if h.svc.RouteThread(ctx, rec, envelope, rec.Recipients, parsed.Cc) {
+ if h.onParsed != nil {
+ h.onParsed()
+ }
+ return nil
+ }
+
if h.producer != nil {
if err := h.producer.EnqueueInboundProcess(rec.ID); err != nil {
logger.Error("failed to enqueue inbound:process", "inbound_id", rec.ID, "error", err)
diff --git a/internal/worker/message_handler.go b/internal/worker/message_handler.go
index f5b7757..aea2a1b 100644
--- a/internal/worker/message_handler.go
+++ b/internal/worker/message_handler.go
@@ -26,9 +26,11 @@ import (
"strings"
"time"
+ "github.com/goposta/posta/internal/dto"
"github.com/goposta/posta/internal/models"
"github.com/goposta/posta/internal/services/messages"
"github.com/goposta/posta/internal/services/notification"
+ "github.com/goposta/posta/internal/services/realtime"
"github.com/goposta/posta/internal/services/webhook"
"github.com/goposta/posta/internal/storage/repositories"
"github.com/hibiken/asynq"
@@ -54,14 +56,46 @@ type MessageWebhookPayload struct {
ReceivedAt string `json:"received_at"`
}
+// messageStore is the slice of MessageRepository the worker needs; an interface
+// so the retry semantics can be tested without a database.
+type messageStore interface {
+ FindByID(id uint) (*models.Message, error)
+ UpdateFields(id uint, fields map[string]any) error
+ MarkNotified(ids []uint, at time.Time) error
+ FindReplyByID(id uint) (*models.MessageReply, error)
+}
+
+type formStore interface {
+ FindByID(id uint) (*models.Form, error)
+}
+
+type jsonDispatcher interface {
+ DispatchJSON(userID uint, workspaceID *uint, event string, body []byte, fromAddr string)
+}
+
+type messageNotifier interface {
+ IsConfigured() bool
+ Send(to, subject, templateName string, data map[string]any) error
+ SendToUser(userID uint, subject, templateName string, data map[string]any) error
+ SendToWorkspaceAdmins(workspaceID uint, subject, templateName string, data map[string]any) error
+}
+
type MessageProcessHandler struct {
- messageRepo *repositories.MessageRepository
- formRepo *repositories.FormRepository
+ messageRepo messageStore
+ formRepo formStore
workspaceRepo *repositories.WorkspaceRepository
- dispatcher *webhook.Dispatcher
- notifier *notification.Service
+ dispatcher jsonDispatcher
+ notifier messageNotifier
+ realtime realtime.Bus
appURL string
onNotified func()
+ // retryCount reports how many times Asynq has already tried this task.
+ retryCount func(ctx context.Context) int
+}
+
+func asynqRetryCount(ctx context.Context) int {
+ n, _ := asynq.GetRetryCount(ctx)
+ return n
}
func NewMessageProcessHandler(
@@ -72,18 +106,32 @@ func NewMessageProcessHandler(
notifier *notification.Service,
appURL string,
) *MessageProcessHandler {
- return &MessageProcessHandler{
+ h := &MessageProcessHandler{
messageRepo: messageRepo,
formRepo: formRepo,
workspaceRepo: workspaceRepo,
- dispatcher: dispatcher,
- notifier: notifier,
appURL: strings.TrimSuffix(appURL, "/"),
+ retryCount: asynqRetryCount,
}
+ // Assign through nil checks so a nil pointer never becomes a non-nil interface.
+ if dispatcher != nil {
+ h.dispatcher = dispatcher
+ }
+ if notifier != nil {
+ h.notifier = notifier
+ }
+ return h
}
func (h *MessageProcessHandler) OnNotified(fn func()) { h.onNotified = fn }
+// SetRealtime enables live dashboard events for processed messages.
+func (h *MessageProcessHandler) SetRealtime(b realtime.Bus) { h.realtime = b }
+
+// ProcessTask fans a stored submission out to webhooks, the live dashboard, and
+// notification email. It is safe to retry: the webhook hand-off and the
+// notification are each recorded once done and skipped on a later attempt, and
+// a failed notification returns an error so Asynq retries it.
func (h *MessageProcessHandler) ProcessTask(ctx context.Context, t *asynq.Task) error {
var payload MessageProcessPayload
if err := json.Unmarshal(t.Payload(), &payload); err != nil {
@@ -103,20 +151,26 @@ func (h *MessageProcessHandler) ProcessTask(ctx context.Context, t *asynq.Task)
return fmt.Errorf("form not found: %w", err)
}
- h.dispatch(msg, form)
+ if msg.WebhookDispatchedAt == nil {
+ h.dispatch(msg, form)
+ now := time.Now().UTC()
+ if err := h.messageRepo.UpdateFields(msg.ID, map[string]any{"webhook_dispatched_at": now}); err != nil {
+ logger.Error("failed to mark message webhook dispatched", "message_id", msg.ID, "error", err)
+ }
+ if !msg.IsSpam() {
+ messages.PublishEvent(ctx, h.realtime, messages.EventReceived, msg)
+ }
+ }
if msg.NotifiedAt == nil && h.shouldNotify(msg, form) {
if err := h.notify(msg, form); err != nil {
- logger.Error("failed to send message notification", "message_id", msg.ID, "error", err)
- } else {
- now := time.Now().UTC()
- msg.NotifiedAt = &now
- if err := h.messageRepo.Update(msg); err != nil {
- logger.Error("failed to mark message notified", "message_id", msg.ID, "error", err)
- }
- if h.onNotified != nil {
- h.onNotified()
- }
+ return fmt.Errorf("notify message %d: %w", msg.ID, err)
+ }
+ if err := h.messageRepo.MarkNotified([]uint{msg.ID}, time.Now().UTC()); err != nil {
+ logger.Error("failed to mark message notified", "message_id", msg.ID, "error", err)
+ }
+ if h.onNotified != nil {
+ h.onNotified()
}
}
@@ -188,13 +242,6 @@ func (h *MessageProcessHandler) notify(msg *models.Message, form *models.Form) e
_ = json.Unmarshal([]byte(msg.FieldsJSON), &fields)
}
- workspaceName := ""
- if msg.WorkspaceID != nil && h.workspaceRepo != nil {
- if ws, err := h.workspaceRepo.FindByID(*msg.WorkspaceID); err == nil {
- workspaceName = ws.Name
- }
- }
-
subject := fmt.Sprintf("New message on %s", form.Name)
if msg.Status == models.MessageStatusFlagged {
subject = fmt.Sprintf("Flagged message on %s", form.Name)
@@ -209,10 +256,22 @@ func (h *MessageProcessHandler) notify(msg *models.Message, form *models.Form) e
"SpamScore": fmt.Sprintf("%.1f", msg.SpamScore),
"MessageURL": h.messageURL(msg.UUID),
}
- if workspaceName != "" {
- data["WorkspaceName"] = workspaceName
- }
+ return h.sendToFormRecipients(msg, form, subject, data)
+}
+
+// sendToFormRecipients delivers to the form's explicit notification list, or
+// to the workspace owners and admins when the list is empty. With several
+// addresses it returns the last error: a retry may then repeat a notification
+// to an address that already got it, which beats one never arriving.
+func (h *MessageProcessHandler) sendToFormRecipients(msg *models.Message, form *models.Form, subject string, data map[string]any) error {
+ if h.workspaceRepo != nil && msg.WorkspaceID != nil {
+ if _, ok := data["WorkspaceName"]; !ok {
+ if ws, err := h.workspaceRepo.FindByID(*msg.WorkspaceID); err == nil && ws.Name != "" {
+ data["WorkspaceName"] = ws.Name
+ }
+ }
+ }
if len(form.NotifyEmails) > 0 {
var lastErr error
for _, to := range form.NotifyEmails {
@@ -291,3 +350,108 @@ func cloneData(in map[string]any) map[string]any {
}
return out
}
+
+// ProcessReplyTask sends the follow-up for one thread reply: the
+// message.replied webhook for an operator reply, or message.reply_received and
+// a notification for the submitter's emailed answer.
+//
+// The webhook goes out on the first attempt only. Dispatch hands off to the
+// dispatcher's own retrying goroutine and cannot fail here, so only the
+// notification can make the task retry, and a retry must not re-fire it.
+func (h *MessageProcessHandler) ProcessReplyTask(ctx context.Context, t *asynq.Task) error {
+ var payload MessageReplyPayload
+ if err := json.Unmarshal(t.Payload(), &payload); err != nil {
+ return fmt.Errorf("unmarshal message reply payload: %w: %w", err, asynq.SkipRetry)
+ }
+ reply, err := h.messageRepo.FindReplyByID(payload.ReplyID)
+ if err != nil {
+ return fmt.Errorf("message reply not found: %w", err)
+ }
+ msg, err := h.messageRepo.FindByID(reply.MessageID)
+ if err != nil {
+ return fmt.Errorf("message not found: %w", err)
+ }
+ form, err := h.formRepo.FindByID(msg.FormID)
+ if err != nil {
+ return fmt.Errorf("form not found: %w", err)
+ }
+
+ if h.retryCount(ctx) == 0 {
+ h.dispatchReply(msg, form, reply)
+ }
+
+ if reply.Kind != models.MessageReplyKindInbound || !h.shouldNotifyReply(msg, form) {
+ return nil
+ }
+ if err := h.notifyReply(msg, form, reply); err != nil {
+ return fmt.Errorf("notify message reply %d: %w", reply.ID, err)
+ }
+ return nil
+}
+
+func replyEvent(kind models.MessageReplyKind) string {
+ if kind == models.MessageReplyKindInbound {
+ return messages.EventReplyReceived
+ }
+ return messages.EventReplied
+}
+
+func (h *MessageProcessHandler) dispatchReply(msg *models.Message, form *models.Form, reply *models.MessageReply) {
+ if h.dispatcher == nil {
+ return
+ }
+ event := replyEvent(reply.Kind)
+ body := dto.MessageReplyWebhookEvent{
+ Event: event,
+ Timestamp: time.Now().UTC().Format(time.RFC3339),
+ MessageID: msg.UUID,
+ ReplyID: reply.UUID,
+ FormID: form.UUID,
+ FormName: form.Name,
+ Kind: string(reply.Kind),
+ From: reply.FromAddr,
+ To: reply.ToAddr,
+ Subject: reply.Subject,
+ TextBody: reply.TextBody,
+ HTMLBody: reply.HTMLBody,
+ EmailID: reply.EmailUUID,
+ SenderMismatch: reply.SenderMismatch,
+ CreatedAt: reply.CreatedAt.UTC().Format(time.RFC3339),
+ }
+ encoded, err := json.Marshal(body)
+ if err != nil {
+ logger.Error("failed to marshal message reply webhook body", "reply_id", reply.ID, "error", err)
+ return
+ }
+ h.dispatcher.DispatchJSON(0, msg.WorkspaceID, event, encoded, reply.FromAddr)
+}
+
+// shouldNotifyReply follows the form's notification switch, but not its digest
+// mode: an answer on a thread someone is working is time-sensitive.
+func (h *MessageProcessHandler) shouldNotifyReply(msg *models.Message, form *models.Form) bool {
+ return form.NotifyEnabled && form.NotifyMode != models.NotifyModeOff && !msg.IsSpam()
+}
+
+// notifyReply tells the assignee, or the form's usual recipients when nobody
+// is assigned, that the submitter answered.
+func (h *MessageProcessHandler) notifyReply(msg *models.Message, form *models.Form, reply *models.MessageReply) error {
+ if h.notifier == nil || !h.notifier.IsConfigured() {
+ return nil
+ }
+ subject := fmt.Sprintf("New reply on %s", form.Name)
+ data := map[string]any{
+ "FormName": form.Name,
+ "Reply": true,
+ "SenderMismatch": reply.SenderMismatch,
+ "Fields": []models.MessageField{
+ {Key: "From", Value: reply.FromAddr},
+ {Key: "Subject", Value: reply.Subject},
+ },
+ "Body": reply.TextBody,
+ "MessageURL": h.messageURL(msg.UUID),
+ }
+ if msg.AssignedToID != nil && *msg.AssignedToID != 0 {
+ return h.notifier.SendToUser(*msg.AssignedToID, subject, notification.TemplateNewMessage, data)
+ }
+ return h.sendToFormRecipients(msg, form, subject, data)
+}
diff --git a/internal/worker/message_process_test.go b/internal/worker/message_process_test.go
new file mode 100644
index 0000000..09ca2f5
--- /dev/null
+++ b/internal/worker/message_process_test.go
@@ -0,0 +1,291 @@
+// Copyright (c) 2026 Jonas Kaninda.
+//
+// This file is part of Posta.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+//
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package worker
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "testing"
+ "time"
+
+ "github.com/goposta/posta/internal/models"
+ "github.com/goposta/posta/internal/services/messages"
+ "github.com/goposta/posta/internal/services/realtime"
+ "github.com/hibiken/asynq"
+)
+
+type fakeMessageStore struct {
+ msg *models.Message
+ reply *models.MessageReply
+ updates []map[string]any
+ notified int
+}
+
+func (f *fakeMessageStore) FindByID(uint) (*models.Message, error) {
+ if f.msg == nil {
+ return nil, errors.New("not found")
+ }
+ cp := *f.msg
+ return &cp, nil
+}
+
+func (f *fakeMessageStore) UpdateFields(_ uint, fields map[string]any) error {
+ f.updates = append(f.updates, fields)
+ if v, ok := fields["webhook_dispatched_at"].(time.Time); ok {
+ f.msg.WebhookDispatchedAt = &v
+ }
+ return nil
+}
+
+func (f *fakeMessageStore) MarkNotified(_ []uint, at time.Time) error {
+ f.notified++
+ f.msg.NotifiedAt = &at
+ return nil
+}
+
+func (f *fakeMessageStore) FindReplyByID(uint) (*models.MessageReply, error) {
+ if f.reply == nil {
+ return nil, errors.New("not found")
+ }
+ return f.reply, nil
+}
+
+type fakeFormStore struct{ form *models.Form }
+
+func (f fakeFormStore) FindByID(uint) (*models.Form, error) { return f.form, nil }
+
+type fakeDispatcher struct{ events []string }
+
+func (f *fakeDispatcher) DispatchJSON(_ uint, _ *uint, event string, _ []byte, _ string) {
+ f.events = append(f.events, event)
+}
+
+type fakeNotifier struct {
+ err error
+ sent []string // "to:<addr>", "user", or "admins"
+}
+
+func (f *fakeNotifier) IsConfigured() bool { return true }
+func (f *fakeNotifier) Send(to, _, _ string, _ map[string]any) error {
+ f.sent = append(f.sent, "to:"+to)
+ return f.err
+}
+func (f *fakeNotifier) SendToUser(userID uint, _, _ string, _ map[string]any) error {
+ f.sent = append(f.sent, "user")
+ return f.err
+}
+func (f *fakeNotifier) SendToWorkspaceAdmins(uint, string, string, map[string]any) error {
+ f.sent = append(f.sent, "admins")
+ return f.err
+}
+
+func newTestHandler(store *fakeMessageStore, form *models.Form) (*MessageProcessHandler, *fakeDispatcher, *fakeNotifier) {
+ d, n := &fakeDispatcher{}, &fakeNotifier{}
+ h := &MessageProcessHandler{
+ messageRepo: store,
+ formRepo: fakeFormStore{form: form},
+ dispatcher: d,
+ notifier: n,
+ retryCount: func(context.Context) int { return 0 },
+ }
+ return h, d, n
+}
+
+// processTask builds the message:process task for message 1, the ID every
+// fakeMessageStore fixture uses.
+func processTask(t *testing.T) *asynq.Task {
+ t.Helper()
+ payload, _ := json.Marshal(MessageProcessPayload{MessageID: 1})
+ return asynq.NewTask(TypeMessageProcess, payload)
+}
+
+func immediateForm() *models.Form {
+ return &models.Form{ID: 1, Name: "Contact", NotifyEnabled: true, NotifyMode: models.NotifyModeImmediate, NotifyOnFlagged: true}
+}
+
+func TestProcessTaskReturnsNotifyErrorSoAsynqRetries(t *testing.T) {
+ ws := uint(3)
+ store := &fakeMessageStore{msg: &models.Message{ID: 1, FormID: 1, WorkspaceID: &ws, Status: models.MessageStatusReceived}}
+ h, _, n := newTestHandler(store, immediateForm())
+ n.err = errors.New("smtp down")
+
+ if err := h.ProcessTask(context.Background(), processTask(t)); err == nil {
+ t.Fatal("a failed notification must fail the task so it is retried")
+ }
+ if store.notified != 0 {
+ t.Fatal("notified_at must not be stamped when the notification failed")
+ }
+}
+
+func TestProcessTaskRetryDoesNotRedispatchWebhook(t *testing.T) {
+ ws := uint(3)
+ store := &fakeMessageStore{msg: &models.Message{ID: 1, FormID: 1, WorkspaceID: &ws, Status: models.MessageStatusReceived}}
+ h, d, n := newTestHandler(store, immediateForm())
+
+ n.err = errors.New("smtp down")
+ _ = h.ProcessTask(context.Background(), processTask(t))
+ n.err = nil
+ if err := h.ProcessTask(context.Background(), processTask(t)); err != nil {
+ t.Fatalf("retry: %v", err)
+ }
+
+ if len(d.events) != 1 || d.events[0] != "message.received" {
+ t.Fatalf("webhook events = %v, want exactly one message.received", d.events)
+ }
+ if store.notified != 1 {
+ t.Fatalf("notified %d times, want 1", store.notified)
+ }
+}
+
+func TestProcessTaskPublishesReceivedToRealtime(t *testing.T) {
+ ws := uint(3)
+ store := &fakeMessageStore{msg: &models.Message{ID: 1, UUID: "m-1", FormID: 1, WorkspaceID: &ws, Status: models.MessageStatusReceived}}
+ h, _, _ := newTestHandler(store, immediateForm())
+ bus := realtime.NewMemory()
+ h.SetRealtime(bus)
+ ch, unsub := bus.Subscribe(context.Background(), realtime.WorkspaceTopic(ws))
+ defer unsub()
+
+ if err := h.ProcessTask(context.Background(), processTask(t)); err != nil {
+ t.Fatal(err)
+ }
+ select {
+ case ev := <-ch:
+ if ev.Type != messages.EventReceived || ev.WorkspaceID != ws {
+ t.Fatalf("event = %+v", ev)
+ }
+ case <-time.After(time.Second):
+ t.Fatal("no message.received event published")
+ }
+}
+
+func TestProcessTaskQuarantinedFiresSpamWebhookWithoutNotifying(t *testing.T) {
+ ws := uint(3)
+ store := &fakeMessageStore{msg: &models.Message{ID: 1, FormID: 1, WorkspaceID: &ws, Status: models.MessageStatusQuarantined}}
+ h, d, n := newTestHandler(store, immediateForm())
+
+ if err := h.ProcessTask(context.Background(), processTask(t)); err != nil {
+ t.Fatal(err)
+ }
+ if len(d.events) != 1 || d.events[0] != "message.spam" {
+ t.Fatalf("webhook events = %v", d.events)
+ }
+ if len(n.sent) != 0 {
+ t.Fatalf("quarantined message notified: %v", n.sent)
+ }
+}
+
+// replyTask builds the message:reply task for reply 5, the ID every reply
+// fixture uses.
+func replyTask(t *testing.T) *asynq.Task {
+ t.Helper()
+ payload, _ := json.Marshal(MessageReplyPayload{ReplyID: 5})
+ return asynq.NewTask(TypeMessageReply, payload)
+}
+
+func TestReplyTaskInboundNotifiesAssignee(t *testing.T) {
+ ws, assignee := uint(3), uint(9)
+ store := &fakeMessageStore{
+ msg: &models.Message{ID: 1, FormID: 1, WorkspaceID: &ws, AssignedToID: &assignee, Status: models.MessageStatusReceived},
+ reply: &models.MessageReply{ID: 5, MessageID: 1, Kind: models.MessageReplyKindInbound, FromAddr: "[email protected]"},
+ }
+ h, d, n := newTestHandler(store, immediateForm())
+
+ if err := h.ProcessReplyTask(context.Background(), replyTask(t)); err != nil {
+ t.Fatal(err)
+ }
+ if len(d.events) != 1 || d.events[0] != messages.EventReplyReceived {
+ t.Fatalf("webhook events = %v", d.events)
+ }
+ if len(n.sent) != 1 || n.sent[0] != "user" {
+ t.Fatalf("notifications = %v, want the assignee", n.sent)
+ }
+}
+
+func TestReplyTaskInboundWithoutAssigneeUsesFormRecipients(t *testing.T) {
+ ws := uint(3)
+ form := immediateForm()
+ form.NotifyEmails = []string{"[email protected]"}
+ store := &fakeMessageStore{
+ msg: &models.Message{ID: 1, FormID: 1, WorkspaceID: &ws, Status: models.MessageStatusReceived},
+ reply: &models.MessageReply{ID: 5, MessageID: 1, Kind: models.MessageReplyKindInbound},
+ }
+ h, _, n := newTestHandler(store, form)
+
+ if err := h.ProcessReplyTask(context.Background(), replyTask(t)); err != nil {
+ t.Fatal(err)
+ }
+ if len(n.sent) != 1 || n.sent[0] != "to:[email protected]" {
+ t.Fatalf("notifications = %v", n.sent)
+ }
+}
+
+func TestReplyTaskOperatorFiresRepliedWithoutNotifying(t *testing.T) {
+ ws := uint(3)
+ store := &fakeMessageStore{
+ msg: &models.Message{ID: 1, FormID: 1, WorkspaceID: &ws, Status: models.MessageStatusReceived},
+ reply: &models.MessageReply{ID: 5, MessageID: 1, Kind: models.MessageReplyKindOperator},
+ }
+ h, d, n := newTestHandler(store, immediateForm())
+
+ if err := h.ProcessReplyTask(context.Background(), replyTask(t)); err != nil {
+ t.Fatal(err)
+ }
+ if len(d.events) != 1 || d.events[0] != messages.EventReplied {
+ t.Fatalf("webhook events = %v", d.events)
+ }
+ if len(n.sent) != 0 {
+ t.Fatalf("operator reply notified: %v", n.sent)
+ }
+}
+
+func TestReplyTaskRetrySkipsWebhook(t *testing.T) {
+ ws := uint(3)
+ store := &fakeMessageStore{
+ msg: &models.Message{ID: 1, FormID: 1, WorkspaceID: &ws, Status: models.MessageStatusReceived},
+ reply: &models.MessageReply{ID: 5, MessageID: 1, Kind: models.MessageReplyKindInbound},
+ }
+ h, d, _ := newTestHandler(store, immediateForm())
+ h.retryCount = func(context.Context) int { return 1 }
+
+ if err := h.ProcessReplyTask(context.Background(), replyTask(t)); err != nil {
+ t.Fatal(err)
+ }
+ if len(d.events) != 0 {
+ t.Fatalf("a retry re-fired the webhook: %v", d.events)
+ }
+}
+
+func TestReplyTaskSkipsSpamThreads(t *testing.T) {
+ ws := uint(3)
+ store := &fakeMessageStore{
+ msg: &models.Message{ID: 1, FormID: 1, WorkspaceID: &ws, Status: models.MessageStatusQuarantined},
+ reply: &models.MessageReply{ID: 5, MessageID: 1, Kind: models.MessageReplyKindInbound},
+ }
+ h, _, n := newTestHandler(store, immediateForm())
+
+ if err := h.ProcessReplyTask(context.Background(), replyTask(t)); err != nil {
+ t.Fatal(err)
+ }
+ if len(n.sent) != 0 {
+ t.Fatalf("a reply on a spam thread notified: %v", n.sent)
+ }
+}
diff --git a/internal/worker/producer.go b/internal/worker/producer.go
index 27be0d1..fc7900a 100644
--- a/internal/worker/producer.go
+++ b/internal/worker/producer.go
@@ -176,6 +176,26 @@ func (p *Producer) EnqueueMessageProcess(messageID uint) error {
return nil
}
+// EnqueueMessageReply schedules the follow-up for a thread reply. The task ID
+// makes a second enqueue of the same reply a no-op.
+func (p *Producer) EnqueueMessageReply(replyID uint) error {
+ task, err := NewMessageReplyTask(replyID,
+ asynq.Queue(QueueTransactional),
+ asynq.MaxRetry(p.maxRetries),
+ asynq.TaskID(fmt.Sprintf("message:reply:%d", replyID)),
+ )
+ if err != nil {
+ return fmt.Errorf("failed to create message reply task: %w", err)
+ }
+ if _, err := p.client.Enqueue(task); err != nil {
+ if errors.Is(err, asynq.ErrTaskIDConflict) {
+ return nil
+ }
+ return fmt.Errorf("failed to enqueue message reply task: %w", err)
+ }
+ return nil
+}
+
// Close closes the underlying Asynq client.
func (p *Producer) Close() error {
return p.client.Close()
diff --git a/internal/worker/tasks.go b/internal/worker/tasks.go
index 3545a62..5e089e6 100644
--- a/internal/worker/tasks.go
+++ b/internal/worker/tasks.go
@@ -33,6 +33,7 @@ const (
TypeInboundParse = "inbound:parse"
TypeInboundProcess = "inbound:process"
TypeMessageProcess = "message:process"
+ TypeMessageReply = "message:reply"
QueueTransactional = queues.Transactional
QueueBulk = queues.Bulk
@@ -111,3 +112,17 @@ func NewMessageProcessTask(id uint, opts ...asynq.Option) (*asynq.Task, error) {
}
return asynq.NewTask(TypeMessageProcess, payload, opts...), nil
}
+
+// MessageReplyPayload names one thread reply, outbound or inbound, whose
+// webhook (and, for inbound replies, notification) is still to be sent.
+type MessageReplyPayload struct {
+ ReplyID uint `json:"reply_id"`
+}
+
+func NewMessageReplyTask(id uint, opts ...asynq.Option) (*asynq.Task, error) {
+ payload, err := json.Marshal(MessageReplyPayload{ReplyID: id})
+ if err != nil {
+ return nil, err
+ }
+ return asynq.NewTask(TypeMessageReply, payload, opts...), nil
+}
diff --git a/web/src/api/types.ts b/web/src/api/types.ts
index 26c386d..59556e6 100644
--- a/web/src/api/types.ts
+++ b/web/src/api/types.ts
@@ -1284,13 +1284,14 @@ export interface MessageReply {
uuid: string
message_id: number
kind: MessageReplyKind
- author_id: number
+ author_id?: number | null
from_addr: string
to_addr: string
subject: string
html_body: string
text_body: string
email_uuid?: string
+ sender_mismatch?: boolean
created_at: string
author?: { id: number; name: string; email: string } | null
}
diff --git a/web/src/api/workspaces.ts b/web/src/api/workspaces.ts
index a8d0c5e..5ccd42e 100644
--- a/web/src/api/workspaces.ts
+++ b/web/src/api/workspaces.ts
@@ -88,4 +88,7 @@ export const workspaceApi = {
deleteEmailLogs(olderThanDays: number) {
return api.post<ApiResponse<GDPRDeleteResult>>('/workspaces/current/gdpr/delete-email-logs', { older_than_days: olderThanDays })
},
+ deleteMessages(email: string) {
+ return api.post<ApiResponse<GDPRDeleteResult>>('/workspaces/current/gdpr/delete-messages', { email })
+ },
}
diff --git a/web/src/views/forms/FormDetail.vue b/web/src/views/forms/FormDetail.vue
index 3040a20..5f5c2eb 100644
--- a/web/src/views/forms/FormDetail.vue
+++ b/web/src/views/forms/FormDetail.vue
@@ -225,8 +225,11 @@ onMounted(load);
<input v-model="form.reply_from_name" class="form-input" placeholder="Acme Support" />
</div>
<div class="form-group">
- <label class="form-label">Retention (days, 0 uses the workspace default)</label>
+ <label class="form-label">Retention (days, 0 uses the platform default)</label>
<input v-model.number="form.retention_days" type="number" class="form-input" min="0" />
+ <p class="muted" style="font-size: 12px; margin: 4px 0 0">
+ Shortens how long this form's messages are kept. It cannot extend retention past the platform setting.
+ </p>
</div>
</div>
</div>
diff --git a/web/src/views/messages/MessageDetail.vue b/web/src/views/messages/MessageDetail.vue
index 476d5b9..27fcb4c 100644
--- a/web/src/views/messages/MessageDetail.vue
+++ b/web/src/views/messages/MessageDetail.vue
@@ -1,5 +1,5 @@
<script setup lang="ts">
-import { computed, onMounted, ref } from "vue";
+import { computed, onBeforeUnmount, onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { messagesApi } from "../../api/messages";
import { useNotificationStore } from "../../stores/notification";
@@ -35,6 +35,36 @@ async function load() {
}
}
+// refresh reloads the thread in place when a live event names this message,
+// keeping whatever the operator has typed in the composer.
+async function refresh() {
+ try {
+ const res = await messagesApi.get(uuid);
+ message.value = res.data.data;
+ } catch {
+ /* the next event or a manual reload will try again */
+ }
+}
+
+let sse: EventSource | null = null;
+function watchThread() {
+ try {
+ sse = new EventSource(messagesApi.streamUrl(), { withCredentials: true });
+ const onEvent = (e: MessageEvent) => {
+ try {
+ if (JSON.parse(e.data)?.message_id === uuid) refresh();
+ } catch {
+ /* ignore malformed events */
+ }
+ };
+ for (const type of ["message.updated", "message.replied", "message.reply_received"]) {
+ sse.addEventListener(type, onEvent as EventListener);
+ }
+ } catch {
+ /* SSE not supported */
+ }
+}
+
function defaultReplySubject(subject: string) {
const trimmed = (subject || "").trim();
if (!trimmed) return "Re: your message";
@@ -252,7 +282,13 @@ function formatBytes(n: number) {
return `${(n / (1024 * 1024)).toFixed(2)} MB`;
}
-onMounted(load);
+onMounted(() => {
+ load();
+ watchThread();
+});
+onBeforeUnmount(() => {
+ if (sse) sse.close();
+});
</script>
<template>
@@ -460,7 +496,15 @@ onMounted(load);
style="border-bottom: 1px solid var(--border); padding: 12px 0"
>
<div style="display: flex; justify-content: space-between; gap: 12px">
- <strong>{{ reply.author?.name || reply.from_addr }}</strong>
+ <span style="display: flex; gap: 8px; align-items: center">
+ <strong>{{ reply.author?.name || reply.from_addr }}</strong>
+ <span v-if="reply.kind === 'inbound'" class="badge">Replied by email</span>
+ <span
+ v-if="reply.sender_mismatch"
+ class="badge badge-warning"
+ title="This reply came from a different address than the original message: a forward, or someone using the thread's reply address."
+ >Different sender</span>
+ </span>
<span class="muted">{{ formatDate(reply.created_at) }}</span>
</div>
<div class="muted" style="font-size: 13px">{{ reply.subject }}</div>
diff --git a/web/src/views/messages/Messages.vue b/web/src/views/messages/Messages.vue
index 0d47380..098a82c 100644
--- a/web/src/views/messages/Messages.vue
+++ b/web/src/views/messages/Messages.vue
@@ -79,10 +79,13 @@ onMounted(async () => {
await loadSidebarData();
try {
sse = new EventSource(messagesApi.streamUrl(), { withCredentials: true });
- sse.addEventListener("message.received", () => {
+ const refresh = () => {
goToPage(pageable.value?.current_page ?? 0);
loadSidebarData();
- });
+ };
+ for (const type of ["message.received", "message.updated", "message.replied", "message.reply_received"]) {
+ sse.addEventListener(type, refresh);
+ }
sse.onerror = () => {
/* reconnects are handled by the browser */
};
diff --git a/web/src/views/webhooks/Webhooks.vue b/web/src/views/webhooks/Webhooks.vue
index bf43e96..4ff8b95 100644
--- a/web/src/views/webhooks/Webhooks.vue
+++ b/web/src/views/webhooks/Webhooks.vue
@@ -29,7 +29,7 @@ const createdWebhook = ref<Webhook | null>(null)
const showSecretModal = ref(false)
const copied = ref(false)
-const availableEvents = ['email.sent', 'email.failed', 'email.inbound', 'email.unsubscribed', 'email.complained', 'campaign.started', 'campaign.completed']
+const availableEvents = ['email.sent', 'email.failed', 'email.inbound', 'email.unsubscribed', 'email.complained', 'message.received', 'message.spam', 'message.replied', 'message.reply_received', 'campaign.started', 'campaign.completed']
const { pageable, goToPage } = usePagination(async (page) => {
loading.value = true
diff --git a/web/src/views/workspaces/WorkspaceSettings.vue b/web/src/views/workspaces/WorkspaceSettings.vue
index 5f49a67..739de16 100644
--- a/web/src/views/workspaces/WorkspaceSettings.vue
+++ b/web/src/views/workspaces/WorkspaceSettings.vue
@@ -81,6 +81,8 @@ const wsSettingsSaving = ref(false)
// Data Management (GDPR) — scoped to this workspace.
const gdprEmail = ref('')
const gdprDays = ref(90)
+const gdprMessagesEmail = ref('')
+const deletingMessages = ref(false)
const deletingContacts = ref(false)
const deletingEmails = ref(false)
@@ -214,6 +216,28 @@ async function deleteWorkspaceEmailLogs() {
}
}
+async function deleteWorkspaceMessages() {
+ const target = gdprMessagesEmail.value.trim()
+ if (!target) return
+ const confirmed = await confirm({
+ title: 'Delete Message Data',
+ message: `Delete every web form message from "${target}", with its thread replies and attachments? This cannot be undone.`,
+ confirmText: 'Delete',
+ variant: 'danger',
+ })
+ if (!confirmed) return
+ deletingMessages.value = true
+ try {
+ const res = await withWorkspace(() => workspaceApi.deleteMessages(target))
+ notify.success(res.data.data.message)
+ gdprMessagesEmail.value = ''
+ } catch (e: any) {
+ notify.error(e.response?.data?.error?.message || 'Failed to delete messages')
+ } finally {
+ deletingMessages.value = false
+ }
+}
+
async function fetchSSO() {
ssoLoading.value = true
try {
@@ -640,7 +664,7 @@ watch(activeTab, (value) => {
<div class="card-header"><span>Data Management (GDPR)</span></div>
<div class="card-body">
<p style="font-size: 13px; color: var(--text-secondary); margin-bottom: 20px;">
- Manage this workspace's data for GDPR compliance. Delete specific contacts or purge old email logs.
+ Manage this workspace's data for GDPR compliance. Delete specific contacts or messages, or purge old email logs.
</p>
<div>
@@ -656,6 +680,19 @@ watch(activeTab, (value) => {
</div>
</div>
+ <div style="margin-top: 24px;">
+ <h4 style="font-size: 14px; font-weight: 600; margin-bottom: 4px;">Delete Message Data</h4>
+ <p style="font-size: 13px; color: var(--text-secondary); margin-bottom: 12px;">
+ Erase every web form message submitted from an address, including thread replies, the emails they arrived as, and attachments.
+ </p>
+ <div style="display: flex; gap: 8px; align-items: center;">
+ <input v-model="gdprMessagesEmail" type="email" class="form-input" placeholder="[email protected]" style="flex: 1" />
+ <button class="btn btn-danger" :disabled="deletingMessages || !gdprMessagesEmail.trim()" @click="deleteWorkspaceMessages">
+ {{ deletingMessages ? 'Deleting...' : 'Delete' }}
+ </button>
+ </div>
+ </div>
+
<div style="margin-top: 24px;">
<h4 style="font-size: 14px; font-weight: 600; margin-bottom: 4px;">Delete Email Logs</h4>
<p style="font-size: 13px; color: var(--text-secondary); margin-bottom: 12px;">