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): web form messages with manual replies (#214)

Jonas Kaninda1f7abe8da493
diff --git a/.env.example b/.env.example
index fab3ad8..0f77a6e 100644
--- a/.env.example
+++ b/.env.example
@@ -143,6 +143,27 @@ POSTA_INBOUND_SMTP_RATE_LIMIT=60
# Rate-limit window in seconds
POSTA_INBOUND_SMTP_RATE_WINDOW=60
+# Web form messages — receive submissions from a website form, then reply from the dashboard
+# Master toggle — enables the public /api/v1/f/{key} ingest endpoint and the messages routes
+POSTA_MESSAGES_ENABLED=false
+# Max submission body size in bytes (per-form override available in the dashboard)
+POSTA_MESSAGES_MAX_BODY_BYTES=65536
+# Max size of a single uploaded attachment in bytes (attachments are off per form by default)
+POSTA_MESSAGES_MAX_ATTACH_SIZE=5242880
+# Per-IP submissions allowed per window (0 disables — leaves a public endpoint open to flooding)
+POSTA_MESSAGES_IP_RATE_LIMIT=20
+# Rate-limit window in seconds
+POSTA_MESSAGES_IP_RATE_WINDOW=3600
+# Per-form submissions allowed per hour
+POSTA_MESSAGES_PER_FORM_HOURLY=200
+# Per-sender-address submissions allowed per hour, per form
+POSTA_MESSAGES_PER_EMAIL_HOURLY=5
+# Per-workspace submissions allowed per day
+POSTA_MESSAGES_PER_WORKSPACE_DAILY=1000
+# Domain used for msg+<token>@ reply addressing so email answers rejoin the thread.
+# Requires POSTA_INBOUND_ENABLED=true. Leave blank for one-directional replies.
+POSTA_MESSAGES_INBOUND_DOMAIN=
+
# SMTP Relay — lets a workspace issue SMTP credentials for migrating existing senders
# Master toggle — enables the SMTP relay listener and the /workspaces/current/smtp-credentials routes
POSTA_SMTP_RELAY_ENABLED=false
diff --git a/cmd/posta/server.go b/cmd/posta/server.go
index 40a3220..cb88fa3 100644
--- a/cmd/posta/server.go
+++ b/cmd/posta/server.go
@@ -470,6 +470,19 @@ func startEmbeddedWorker(db *gorm.DB,
mux.HandleFunc(worker.TypeInboundParse, parseHandler.ProcessTask)
}
+ if cfg.MessagesEnabled {
+ messageHandler := worker.NewMessageProcessHandler(
+ repositories.NewMessageRepository(db),
+ repositories.NewFormRepository(db),
+ repositories.NewWorkspaceRepository(db),
+ newWebhookDispatcher(db, cfg),
+ notifier,
+ cfg.AppWebURL,
+ )
+ messageHandler.OnNotified(metrics.IncrementMessageNotification)
+ mux.HandleFunc(worker.TypeMessageProcess, messageHandler.ProcessTask)
+ }
+
workermon.StartHeartbeat(context.Background(), cfg.Redis.Client, config.Version, config.CommitID)
go func() {
@@ -538,6 +551,16 @@ func initCronManager(
producer,
))
}
+ if cfg.MessagesEnabled {
+ retentionJob.SetMessageRepo(repositories.NewMessageRepository(db))
+ manager.Register(jobs.NewMessageDigestJob(
+ notifier,
+ repositories.NewFormRepository(db),
+ repositories.NewMessageRepository(db),
+ repositories.NewWorkspaceRepository(db),
+ cfg.AppWebURL,
+ ))
+ }
return manager
}
diff --git a/cmd/posta/worker.go b/cmd/posta/worker.go
index 9b6ffae..4ca1594 100644
--- a/cmd/posta/worker.go
+++ b/cmd/posta/worker.go
@@ -188,6 +188,19 @@ func runWorker() error {
mux.HandleFunc(worker.TypeInboundParse, parseHandler.ProcessTask)
}
+ if cfg.MessagesEnabled {
+ messageHandler := worker.NewMessageProcessHandler(
+ repositories.NewMessageRepository(db),
+ repositories.NewFormRepository(db),
+ repositories.NewWorkspaceRepository(db),
+ newWebhookDispatcher(db, cfg),
+ notifier,
+ cfg.AppWebURL,
+ )
+ messageHandler.OnNotified(metrics.IncrementMessageNotification)
+ mux.HandleFunc(worker.TypeMessageProcess, messageHandler.ProcessTask)
+ }
+
// Publish worker's build info
workermon.StartHeartbeat(context.Background(), cfg.Redis.Client, config.Version, config.CommitID)
diff --git a/docs/docs/getting-started/configuration.md b/docs/docs/getting-started/configuration.md
index 851974d..7b831a8 100644
--- a/docs/docs/getting-started/configuration.md
+++ b/docs/docs/getting-started/configuration.md
@@ -158,6 +158,20 @@ Where email attachments are stored. Leave `POSTA_BLOB_PROVIDER` empty to disable
| `POSTA_INBOUND_SMTP_RATE_LIMIT` | `60` | Per-IP max SMTP sessions per window (`0` disables) |
| `POSTA_INBOUND_SMTP_RATE_WINDOW` | `60` | Rate-limit window in seconds |
+## Web Form Messages
+
+| Variable | Default | Description |
+|----------|---------|-------------|
+| `POSTA_MESSAGES_ENABLED` | `false` | Master toggle — enables the public `/api/v1/f/{key}` ingest endpoint and the messages routes |
+| `POSTA_MESSAGES_MAX_BODY_BYTES` | `65536` | Max submission body size in bytes (each form can lower it) |
+| `POSTA_MESSAGES_MAX_ATTACH_SIZE` | `5242880` | Max per-attachment size in bytes (attachments are off per form by default) |
+| `POSTA_MESSAGES_IP_RATE_LIMIT` | `20` | Per-IP submissions per window (`0` disables — leaves a public endpoint unthrottled) |
+| `POSTA_MESSAGES_IP_RATE_WINDOW` | `3600` | Rate-limit window in seconds |
+| `POSTA_MESSAGES_PER_FORM_HOURLY` | `200` | Submissions allowed per form per hour |
+| `POSTA_MESSAGES_PER_EMAIL_HOURLY` | `5` | Submissions allowed per sender address per hour, per form |
+| `POSTA_MESSAGES_PER_WORKSPACE_DAILY` | `1000` | Submissions allowed per workspace per day |
+| `POSTA_MESSAGES_INBOUND_DOMAIN` | — | Domain for `msg+<token>@` reply addressing so email answers rejoin the thread (requires `POSTA_INBOUND_ENABLED=true`) |
+
## Advanced
| Variable | Default | Description |
diff --git a/docs/docs/messages/creating-a-form.md b/docs/docs/messages/creating-a-form.md
new file mode 100644
index 0000000..1ab699e
--- /dev/null
+++ b/docs/docs/messages/creating-a-form.md
@@ -0,0 +1,85 @@
+---
+sidebar_position: 2
+title: Creating a form
+description: Create and configure a Posta web form endpoint
+---
+
+# Creating a Form
+
+Create a form under **Messages → Forms → New form** in the dashboard, or through the API:
+
+```bash
+curl -X POST https://posta.example.com/api/v1/workspaces/current/forms \
+ -H "Authorization: Bearer $POSTA_API_KEY" \
+ -H "X-Posta-Workspace-Id: 1" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "name": "Contact form",
+ "allowed_origins": ["https://example.com", "https://www.example.com"],
+ "notify_emails": ["[email protected]"],
+ "reply_from": "[email protected]"
+ }'
+```
+
+The response includes `public_key` — the unguessable 22-character string that appears in your embed URL.
+
+:::note
+Form configuration endpoints require the `admin` API-key scope, not `write`. A form row holds notification recipients and the reply sender, so a content-level key has no business changing it. Reading and replying to messages needs only `read`/`write`.
+:::
+
+## Ingest surface
+
+| Field | Default | Notes |
+|-------|---------|-------|
+| `allowed_origins` | _(empty)_ | Blank accepts any origin. Otherwise an exact `scheme://host[:port]` match. |
+| `strict_origin` | `false` | Reject submissions that send no `Origin` header at all (curl, server-to-server). |
+| `redirect_url` | _(empty)_ | Where a no-JS form lands after submitting. |
+| `max_body_bytes` | `65536` | Clamped to 1 KiB–1 MiB. |
+| `max_fields` | `40` | Clamped to 1–200. |
+| `allow_attachments` | `false` | When off, uploaded files in a multipart post are discarded and the text fields still store. |
+
+:::caution
+The origin allowlist is a spam speed bump, not a security boundary. A plain `<form method="post">` with the default encoding is a CORS *simple request*, so the browser sends it without a preflight regardless of the allowlist. Treat the endpoint as public, because it is.
+:::
+
+## Bot controls
+
+| Field | Default | Notes |
+|-------|---------|-------|
+| `honeypot_field` | `_gotcha` | A non-empty value rejects the submission outright. The generated embed code includes it. |
+| `require_nonce` | `false` | Requires a short-lived signed token from `GET /api/v1/f/{key}/nonce`. Single-use, and breaks no-JS forms. |
+| `min_fill_seconds` | `3` | Minimum age of the nonce at submit time. Only applies when `require_nonce` is on. |
+
+## Scanning thresholds
+
+| Field | Default | Effect at or above the score |
+|-------|---------|------------------------------|
+| `flag_threshold` | `3` | Stored and notified, marked for review. |
+| `quarantine_threshold` | `6` | Stored, not notified, not dispatched as `message.received`. |
+| `reject_threshold` | `10` | Stored for audit only. Hidden from the inbox. |
+
+Thresholds must satisfy `flag ≤ quarantine ≤ reject`. Set `scan_enabled: false` to store everything untouched.
+
+## Notifications
+
+| Field | Default | Notes |
+|-------|---------|-------|
+| `notify_enabled` | `true` | Master switch for this form. |
+| `notify_emails` | _(empty)_ | Blank notifies workspace owners and admins, honouring each user's **Web form messages** preference. At most 10 addresses. |
+| `notify_mode` | `immediate` | `immediate`, `hourly`, `daily`, or `off`. Digests are assembled by the `message-digest` cron job. |
+| `notify_on_flagged` | `true` | Whether flagged messages also generate a notification. |
+
+A busy contact form on `immediate` can send a lot of mail. Switching to `hourly` is usually what keeps the feature switched on.
+
+## Replying
+
+| Field | Notes |
+|-------|-------|
+| `reply_from` | Must be an address on an ownership-verified domain in this workspace. Validated when you save, not just when you send. |
+| `reply_from_name` | Display name used on outgoing replies. |
+
+Without `reply_from`, the dashboard shows the message but disables the reply composer.
+
+## Rotating the public key
+
+`POST /workspaces/current/forms/{id}/rotate-key` issues a new key. Existing embeds stop working immediately — update your site first, or expect a gap.
diff --git a/docs/docs/messages/embedding.md b/docs/docs/messages/embedding.md
new file mode 100644
index 0000000..5db6aa4
--- /dev/null
+++ b/docs/docs/messages/embedding.md
@@ -0,0 +1,129 @@
+---
+sidebar_position: 3
+title: Embedding a form
+description: Put a Posta form on your website with plain HTML or JavaScript
+---
+
+# Embedding a Form
+
+The **Embed** tab of a form gives you paste-ready code. Both variants below post to the same endpoint.
+
+## Plain HTML, no JavaScript
+
+```html
+<form action="https://posta.example.com/api/v1/f/YOUR_PUBLIC_KEY" method="POST">
+ <label for="posta-name">Name</label>
+ <input id="posta-name" type="text" name="name" required>
+
+ <label for="posta-email">Email</label>
+ <input id="posta-email" type="email" name="email" required>
+
+ <label for="posta-phone">Phone (optional)</label>
+ <input id="posta-phone" type="tel" name="phone" autocomplete="tel">
+
+ <label for="posta-message">Message</label>
+ <textarea id="posta-message" name="message" required></textarea>
+
+ <div style="position:absolute;left:-9999px" aria-hidden="true">
+ <input type="text" name="_gotcha" tabindex="-1" autocomplete="off">
+ </div>
+
+ <input type="hidden" name="_redirect" value="https://example.com/thanks">
+
+ <button type="submit">Send</button>
+</form>
+```
+
+The honeypot div is off-screen and `aria-hidden`, so it is invisible to sighted users and to screen readers, but a naive bot fills it in and gets rejected.
+
+## JavaScript
+
+```js
+const res = await fetch('https://posta.example.com/api/v1/f/YOUR_PUBLIC_KEY', {
+ method: 'POST',
+ headers: { 'Content-Type': 'text/plain;charset=UTF-8' },
+ body: JSON.stringify({
+ name: form.name.value,
+ email: form.email.value,
+ phone: form.phone.value,
+ message: form.message.value,
+ }),
+})
+const { data } = await res.json()
+```
+
+:::important
+Note the `text/plain;charset=UTF-8` content type. It is deliberate, and the generated snippet uses it.
+
+`Content-Type: application/json` makes the request *preflighted*: the browser sends an `OPTIONS` request first, and Posta answers preflights from the deployment-wide `POSTA_CORS_ORIGINS` allowlist — which will not contain your customers' websites. `text/plain` is a CORS-safelisted content type, so the browser skips the preflight and posts directly. Posta parses a `text/plain` body as JSON.
+
+The same applies to `application/x-www-form-urlencoded` and `multipart/form-data`: both are safelisted and post without a preflight.
+
+`application/json` still works fine for server-to-server calls, where CORS never applies.
+:::
+
+Posta echoes your form's origin back in `Access-Control-Allow-Origin` on the response, so your script can read the result.
+
+## With a nonce
+
+When the form has `require_nonce` enabled, fetch a token first and submit it as `_nonce`:
+
+```js
+const { data: nonce } = await (
+ await fetch('https://posta.example.com/api/v1/f/YOUR_PUBLIC_KEY/nonce')
+).json()
+
+// …later, when the visitor submits
+await fetch('https://posta.example.com/api/v1/f/YOUR_PUBLIC_KEY', {
+ method: 'POST',
+ headers: { 'Content-Type': 'text/plain;charset=UTF-8' },
+ body: JSON.stringify({ ...values, _nonce: nonce.nonce }),
+})
+```
+
+Fetch the nonce when the form is rendered, not when it is submitted — `min_fill_seconds` rejects a token that is younger than the configured age, which is what catches a bot that fills and posts instantly. Each nonce is single-use and expires after 30 minutes.
+
+## Attachments
+
+Set `allow_attachments` on the form and post `multipart/form-data`:
+
+```html
+<form action="https://posta.example.com/api/v1/f/YOUR_PUBLIC_KEY"
+ method="POST" enctype="multipart/form-data">
+ <input type="file" name="resume">
+</form>
+```
+
+At most 5 files per submission, each within `POSTA_MESSAGES_MAX_ATTACH_SIZE`. Files go to blob storage when it is configured, and are base64-encoded on the record otherwise.
+
+## Reserved field names
+
+These are stripped before storage and never appear on the message:
+
+| Field | Purpose |
+|-------|---------|
+| `_gotcha` | Honeypot (or whatever the form's `honeypot_field` is set to). |
+| `_nonce` | Signed anti-bot token. |
+| `_redirect` / `_next` | Post-submit redirect target. |
+| `_subject` | Sets the message subject. |
+| `_captcha`, `_cc` | Reserved for future use. |
+
+`_redirect` is only honoured when the target host is on the form's origin allowlist or matches the configured `redirect_url` host. Anything else is ignored, because an open redirect on a trusted domain is a phishing primitive.
+
+## Field mapping
+
+Posta extracts well-known fields case-insensitively:
+
+| Target | Field names it looks for |
+|--------|--------------------------|
+| Sender email | `email`, `e-mail`, `_replyto`, `reply_to`, `replyto`, `from`, `sender_email`, `your-email` |
+| Sender name | `name`, `full_name`, `fullname`, `your-name`, `sender_name`, or `first_name` + `last_name` |
+| Phone | `phone`, `phone_number`, `phonenumber`, `tel`, `telephone`, `mobile`, `cell`, `your-phone`, `sender_phone` |
+| Subject | `_subject`, `subject`, `topic`, `your-subject` |
+| Body | `message`, `body`, `comments`, `comment`, `content`, `description`, `your-message` |
+
+If nothing matches, Posta falls back to the first value that parses as an email address and the longest value as the body. Every field is stored regardless, in the order it was submitted.
+
+The phone number is optional and has no fallback: if none of those keys are present, `sender_phone` is empty. Submitted values are normalised down to digits and the separators `+ - ( ) . /` — enough to keep `+33 6 12 34 56 78` and `(555) 010-9999` readable, while dropping anything that could reach an email header. A value with no digits at all is discarded.
+
+A message with no usable address is still stored and notified — but it cannot be replied to, and the dashboard says so.
diff --git a/docs/docs/messages/overview.md b/docs/docs/messages/overview.md
new file mode 100644
index 0000000..7dfde39
--- /dev/null
+++ b/docs/docs/messages/overview.md
@@ -0,0 +1,78 @@
+---
+sidebar_position: 1
+title: Overview
+description: Receive website form submissions in Posta and reply to them from the dashboard
+---
+
+# Web Form Messages
+
+Messages let a website contact form post directly to Posta. Each submission is scanned, stored, and pushed to your team — and you reply to the sender from the dashboard, through the same sending pipeline, domains, and suppression list as the rest of your email.
+
+There is no auto-responder. Every reply is written by a person.
+
+## Enabling messages
+
+Messages are off by default.
+
+| Variable | Default | Description |
+|----------|---------|-------------|
+| `POSTA_MESSAGES_ENABLED` | `false` | Master switch for the feature and the public ingest endpoint. |
+| `POSTA_MESSAGES_MAX_BODY_BYTES` | `65536` | Maximum submission body size. Each form can lower it. |
+| `POSTA_MESSAGES_MAX_ATTACH_SIZE` | `5242880` (5 MiB) | Maximum size of a single uploaded file. Attachments are off per form by default. |
+| `POSTA_MESSAGES_IP_RATE_LIMIT` | `20` | Submissions allowed per IP per window. `0` disables the limiter. |
+| `POSTA_MESSAGES_IP_RATE_WINDOW` | `3600` | Rate-limit window in seconds. |
+| `POSTA_MESSAGES_PER_FORM_HOURLY` | `200` | Submissions allowed per form per hour. |
+| `POSTA_MESSAGES_PER_EMAIL_HOURLY` | `5` | Submissions allowed per sender address per hour, per form. |
+| `POSTA_MESSAGES_PER_WORKSPACE_DAILY` | `1000` | Submissions allowed per workspace per day. |
+| `POSTA_MESSAGES_INBOUND_DOMAIN` | _(empty)_ | Domain used for `msg+<token>@` reply addressing. Requires `POSTA_INBOUND_ENABLED=true`. |
+
+:::warning
+`POSTA_MESSAGES_IP_RATE_LIMIT=0` leaves a public, unauthenticated endpoint with no per-IP ceiling. Posta logs a security warning at startup when you do this.
+:::
+
+## Concepts
+
+| Term | Meaning |
+|------|---------|
+| **Form** | The endpoint definition: public key, allowed origins, spam posture, notification recipients, reply sender. |
+| **Message** | One submission, with the fields as submitted and the scan verdict. |
+| **Reply** | One operator answer, linked to the `Email` record that carried it. |
+| **Verdict** | The scanner's output: a score, the reasons behind it, and an action. |
+
+A workspace can have as many forms as it needs — contact, support, careers — each with its own configuration.
+
+## How it works
+
+```
+website form ──► POST /api/v1/f/{public_key} ──► scan ──► stored (Message)
+ │
+ ├─► notification email ──► your team
+ ├─► message.received webhook ──► your endpoint
+ └─► GET /message-stream (SSE) ──► dashboard
+```
+
+1. A visitor submits your form. The browser posts URL-encoded, multipart, or JSON data to the form's public endpoint.
+2. Posta checks the per-IP limiter, the form's origin allowlist, the honeypot, the optional nonce, and the four Redis rate limiters.
+3. The scanner produces a score and an action — `allow`, `flag`, `quarantine`, or `reject`.
+4. The message is stored. Rejected messages are never notified, never dispatched, and hidden from the inbox.
+5. Notification and webhook dispatch happen asynchronously so a slow mailbox never delays the visitor's response.
+6. An operator opens the message in the dashboard and writes a reply. It is sent through the normal email pipeline, so delivery status, opens, and bounces show up in the email log.
+
+## Response contract
+
+The endpoint always answers `202 Accepted` for a submission it stored **or silently rejected**. A spam client gets no signal it can tune against. Only rate limiting (`429`), a disallowed origin (`403`), and malformed payloads (`400`/`413`) produce a different status.
+
+For a JSON request the body is:
+
+```json
+{ "success": true, "data": { "id": "b0b1…", "status": "received", "message": "Thanks — your message has been received." } }
+```
+
+For a plain HTML form post Posta redirects to `_redirect` (when it is on an allowed host) or the form's configured redirect URL, and otherwise renders a small confirmation page.
+
+## Next steps
+
+- [Creating a form](./creating-a-form.md)
+- [Embedding a form](./embedding.md)
+- [Spam filtering](./spam-filtering.md)
+- [Replying to messages](./replying.md)
diff --git a/docs/docs/messages/replying.md b/docs/docs/messages/replying.md
new file mode 100644
index 0000000..c0cb04d
--- /dev/null
+++ b/docs/docs/messages/replying.md
@@ -0,0 +1,87 @@
+---
+sidebar_position: 5
+title: Replying to messages
+description: Answer a form submission from the Posta dashboard
+---
+
+# Replying to Messages
+
+Replies are written by a person. Posta has no auto-responder for web forms, deliberately: a public endpoint that emails an arbitrary attacker-supplied address, from your verified domain, is a spam amplifier and a fast route to a blocklisted sending domain.
+
+## Before you can reply
+
+The form needs a `reply_from` address on an ownership-verified domain in the workspace, and the message needs a usable sender address. The dashboard disables the composer and explains which of the two is missing.
+
+Replying requires the **editor** workspace role or higher. A viewer can read the inbox but cannot speak for the workspace.
+
+## From the dashboard
+
+Open a message and write your reply. Posta sends it through the normal email pipeline, which means:
+
+- the workspace suppression list applies
+- plan rate limits apply
+- delivery status, opens, clicks, and bounces appear in the email log, linked to the reply
+
+The reply is recorded on the thread with its `email_uuid`, so there is no second delivery state machine to keep in sync.
+
+## From the API
+
+```bash
+curl -X POST https://posta.example.com/api/v1/workspaces/current/messages/$MESSAGE_UUID/reply \
+ -H "Authorization: Bearer $POSTA_API_KEY" \
+ -H "X-Posta-Workspace-Id: 1" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "subject": "Re: Question about pricing",
+ "text": "Hi Ada — thanks for reaching out...",
+ "html": "<p>Hi Ada — thanks for reaching out...</p>"
+ }'
+```
+
+Omit `subject` and Posta derives `Re: <original subject>`. At least one of `html` or `text` is required.
+
+## Threading
+
+When `POSTA_MESSAGES_INBOUND_DOMAIN` is set (and inbound email is enabled), replies carry:
+
+```
+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.
+
+## Message state
+
+Separate from the spam status, each message carries a workflow state:
+
+| State | Meaning |
+|-------|---------|
+| `new` | Not yet opened. |
+| `open` | Opened, not yet answered. Set automatically on first read. |
+| `replied` | An operator reply has been sent. |
+| `closed` | Done. |
+| `spam` | Marked as spam. |
+
+Set it with `PUT /workspaces/current/messages/{id}/state`, and assign a message to a teammate with `PUT /workspaces/current/messages/{id}/assign`.
+
+## Events
+
+| Event | Fires when |
+|-------|------------|
+| `message.received` | A submission passes scanning (`received` or `flagged`). |
+| `message.spam` | A submission is quarantined or rejected. |
+
+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.
+
+## Retention
+
+| Setting | Default | Applies to |
+|---------|---------|------------|
+| `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.
diff --git a/docs/docs/messages/spam-filtering.md b/docs/docs/messages/spam-filtering.md
new file mode 100644
index 0000000..a41a1b8
--- /dev/null
+++ b/docs/docs/messages/spam-filtering.md
@@ -0,0 +1,77 @@
+---
+sidebar_position: 4
+title: Spam filtering
+description: How Posta scores web form submissions and how to add your own rules
+---
+
+# Spam Filtering
+
+Every submission runs through a scanner that produces a **score**, a list of **reasons**, and an **action**. The form's thresholds map the score onto the action; a rule with an explicit action sets a floor that the score cannot undo.
+
+| Action | Stored | Notified | Webhook | Visible in inbox |
+|--------|--------|----------|---------|------------------|
+| `allow` | yes | yes | `message.received` | yes |
+| `flag` | yes | if `notify_on_flagged` | `message.received` | yes, marked |
+| `quarantine` | yes | no | `message.spam` | yes, under the spam filter |
+| `reject` | yes | no | no | no |
+
+## Immediate rejections
+
+Three checks bypass scoring entirely and reject outright:
+
+- the honeypot field was filled in
+- a required nonce was missing, expired, replayed, or submitted faster than `min_fill_seconds`
+
+The submitter still receives the normal `202` acknowledgement.
+
+## Built-in signals
+
+| Signal | Score |
+|--------|-------|
+| Sender address is on the workspace suppression list | +5 |
+| Sender address does not parse as an email address | +3 |
+| Sender domain is a known disposable-mail provider | +4 |
+| More than 5 URLs in the subject and body | +1 per extra URL, capped at +6 |
+| A known URL shortener appears in the text | +2 |
+| Body shorter than 10 characters, or longer than 20,000 | +2 |
+| 70% or more uppercase letters over 40+ characters | +2 |
+| Raw `<a href>` or BBCode in a plain-text field | +3 |
+| `<script>` or `javascript:` in the body | +5 |
+| 5 or more submissions from this IP in the last hour | +3 |
+| 3 or more submissions from this address on this form in the last hour | +2 |
+| A scripted user agent (`curl`, `python-requests`, headless browsers) | +2 |
+
+Each signal that fires adds a named reason to the message, which the dashboard renders as a chip so you can see exactly why something was flagged.
+
+## Your own filters
+
+Add filters under **Messages → Spam Filters**, or via `POST /workspaces/current/message-filters`.
+
+| Kind | Matches |
+|------|---------|
+| `keyword` | A whole word. `cat` does not match `concatenate`. |
+| `phrase` | A substring anywhere. |
+| `regex` | A regular expression. Go's `regexp` is RE2 — linear time, no catastrophic backtracking. Patterns are capped at 512 characters and validated when you save. |
+| `email` | The sender address, exactly. |
+| `domain` | The sender domain, including subdomains. `spam.test` matches `mail.spam.test` but not `notspam.test`. |
+| `ip` | The client IP, exactly. |
+
+| Action | Effect |
+|--------|--------|
+| `score` | Adds `score` to the running total. The default. |
+| `flag` / `quarantine` / `reject` | Sets a floor: the message lands at least there, whatever the score. |
+| `allowlist` | Short-circuits the entire scan. The message is allowed with score 0. |
+
+Scope a filter to one form with `form_id`, or leave it null to apply it workspace-wide. Restrict it to specific fields with `fields: ["subject"]`; blank checks every field, plus the sender name and address.
+
+`allowlist` is the escape hatch for the customer whose emails keep tripping the link rule. It is evaluated before everything else.
+
+## Testing a rule before you save it
+
+`POST /workspaces/current/message-filters/test` runs a candidate pattern over your recent messages and reports how many it would have matched, with up to 10 samples. The dashboard exposes this as **Test against recent messages** in the new-filter dialog. Use it before adding anything with a `reject` action.
+
+## Feedback loop
+
+Marking a message as spam in the dashboard quarantines it and offers to create a filter from the sender's domain in the same step. Marking a quarantined message as **Not spam** clears the score and reasons and reopens it.
+
+Each filter tracks its own `hit_count` and `last_hit_at`. A rule that has not fired in months is a rule to delete.
diff --git a/docs/docs/webhooks/event-types.md b/docs/docs/webhooks/event-types.md
index 66a0607..0abd9ee 100644
--- a/docs/docs/webhooks/event-types.md
+++ b/docs/docs/webhooks/event-types.md
@@ -16,6 +16,13 @@ description: Available webhook event types
| `email.complained` | Recipient filed a spam complaint |
| `email.inbound` | An inbound email was received (see [Inbound Email](#inbound-email)) |
+## Web Form Message Events
+
+| Event | Description |
+|-------|-------------|
+| `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 |
+
## Campaign Events
| Event | Description |
@@ -135,3 +142,37 @@ The `email.inbound` event fires when Posta receives an incoming message on a ver
```
For configuring inbound routing and managing received messages, see the Inbound Email section in the sidebar.
+
+## Web Form Messages
+
+`message.received` and `message.spam` share one payload. It carries the full submission plus the scan verdict, so a downstream system can apply its own policy without calling back:
+
+```json
+{
+ "event": "message.received",
+ "timestamp": "2026-01-01T00:00:01Z",
+ "message_id": "b0b1c2d3-...",
+ "form_id": "3f9a7d12-...",
+ "form_name": "Contact form",
+ "sender_email": "[email protected]",
+ "sender_name": "Ada Lovelace",
+ "sender_phone": "+1 555 010 9999",
+ "subject": "Question about pricing",
+ "body": "How does per-seat billing work?",
+ "fields": [
+ { "key": "name", "value": "Ada Lovelace" },
+ { "key": "email", "value": "[email protected]" },
+ { "key": "phone", "value": "+1 555 010 9999" },
+ { "key": "message", "value": "How does per-seat billing work?" }
+ ],
+ "status": "received",
+ "spam_score": 0,
+ "scan_reasons": [],
+ "client_ip": "203.0.113.7",
+ "received_at": "2026-01-01T00:00:00Z"
+}
+```
+
+`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.
+
+For configuring forms and replying to submissions, see the Forms & Messages section in the sidebar.
diff --git a/docs/sidebars.ts b/docs/sidebars.ts
index 349b7f1..5eb4a31 100644
--- a/docs/sidebars.ts
+++ b/docs/sidebars.ts
@@ -120,6 +120,17 @@ const sidebars: SidebarsConfig = {
'inbound/managing',
],
},
+ {
+ type: 'category',
+ label: 'Forms & Messages',
+ items: [
+ 'messages/overview',
+ 'messages/creating-a-form',
+ 'messages/embedding',
+ 'messages/spam-filtering',
+ 'messages/replying',
+ ],
+ },
{
type: 'category',
label: 'Analytics & Monitoring',
diff --git a/internal/config/config.go b/internal/config/config.go
index 6ba6f98..87f43e4 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -115,6 +115,17 @@ type Config struct {
InboundSMTPRateLimit int // per-IP max sessions per window; 0 disables
InboundSMTPRateWindow int // rate-limit window in seconds
+ // Web form message settings
+ MessagesEnabled bool
+ MessagesMaxBodyBytes int64
+ MessagesMaxAttachSize int64
+ MessagesIPRateLimit int
+ MessagesIPRateWindow int
+ MessagesPerFormHourly int
+ MessagesPerEmailHourly int
+ MessagesPerWorkspaceDaily int
+ MessagesInboundDomain string
+
// SMTP Relay settings. No TLS by design.
SMTPRelayEnabled bool
SMTPRelayHost string
@@ -307,6 +318,16 @@ func New() *Config {
InboundSMTPRateLimit: goutils.EnvInt("POSTA_INBOUND_SMTP_RATE_LIMIT", 60),
InboundSMTPRateWindow: goutils.EnvInt("POSTA_INBOUND_SMTP_RATE_WINDOW", 60),
+ MessagesEnabled: goutils.EnvBool("POSTA_MESSAGES_ENABLED", false),
+ MessagesMaxBodyBytes: int64(goutils.EnvInt("POSTA_MESSAGES_MAX_BODY_BYTES", 65536)),
+ MessagesMaxAttachSize: int64(goutils.EnvInt("POSTA_MESSAGES_MAX_ATTACH_SIZE", 5242880)),
+ MessagesIPRateLimit: goutils.EnvInt("POSTA_MESSAGES_IP_RATE_LIMIT", 20),
+ MessagesIPRateWindow: goutils.EnvInt("POSTA_MESSAGES_IP_RATE_WINDOW", 3600),
+ MessagesPerFormHourly: goutils.EnvInt("POSTA_MESSAGES_PER_FORM_HOURLY", 200),
+ MessagesPerEmailHourly: goutils.EnvInt("POSTA_MESSAGES_PER_EMAIL_HOURLY", 5),
+ MessagesPerWorkspaceDaily: goutils.EnvInt("POSTA_MESSAGES_PER_WORKSPACE_DAILY", 1000),
+ MessagesInboundDomain: goutils.Env("POSTA_MESSAGES_INBOUND_DOMAIN", ""),
+
SMTPRelayEnabled: goutils.EnvBool("POSTA_SMTP_RELAY_ENABLED", false),
SMTPRelayHost: goutils.Env("POSTA_SMTP_RELAY_HOST", "0.0.0.0"),
SMTPRelayPort: goutils.EnvInt("POSTA_SMTP_RELAY_PORT", 2526),
@@ -317,6 +338,9 @@ func New() *Config {
}
}
func (c *Config) validate() error {
+ if c.MessagesEnabled && c.MessagesInboundDomain != "" && !c.InboundEnabled {
+ return fmt.Errorf("POSTA_MESSAGES_INBOUND_DOMAIN requires POSTA_INBOUND_ENABLED=true")
+ }
if c.InboundEnabled && c.InboundTLSMode != "" && c.InboundTLSMode != "none" {
if c.InboundTLSMode != "starttls" {
return fmt.Errorf("unsupported POSTA_INBOUND_TLS_MODE %q (use none or starttls)", c.InboundTLSMode)
diff --git a/internal/config/security.go b/internal/config/security.go
index 24b50e1..c61abdc 100644
--- a/internal/config/security.go
+++ b/internal/config/security.go
@@ -119,6 +119,13 @@ func (c *Config) securityProblems() []secretProblem {
false,
})
}
+ if c.MessagesEnabled && c.MessagesIPRateLimit <= 0 {
+ problems = append(problems, secretProblem{
+ "POSTA_MESSAGES_IP_RATE_LIMIT",
+ "is disabled while public form ingest is enabled, leaving the endpoint open to flooding",
+ false,
+ })
+ }
return problems
}
diff --git a/internal/cron/jobs/message_digest.go b/internal/cron/jobs/message_digest.go
new file mode 100644
index 0000000..54654fa
--- /dev/null
+++ b/internal/cron/jobs/message_digest.go
@@ -0,0 +1,178 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package jobs
+
+import (
+ "context"
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/goposta/posta/internal/models"
+ "github.com/goposta/posta/internal/services/notification"
+ "github.com/goposta/posta/internal/storage/repositories"
+ "github.com/hibiken/asynq"
+ "github.com/jkaninda/logger"
+)
+
+type digestItem struct {
+ Sender string
+ Subject string
+ Flagged bool
+}
+
+type MessageDigestJob struct {
+ notifier *notification.Service
+ formRepo *repositories.FormRepository
+ messageRepo *repositories.MessageRepository
+ workspaceRepo *repositories.WorkspaceRepository
+ appURL string
+}
+
+func NewMessageDigestJob(
+ notifier *notification.Service,
+ formRepo *repositories.FormRepository,
+ messageRepo *repositories.MessageRepository,
+ workspaceRepo *repositories.WorkspaceRepository,
+ appURL string,
+) *MessageDigestJob {
+ return &MessageDigestJob{
+ notifier: notifier,
+ formRepo: formRepo,
+ messageRepo: messageRepo,
+ workspaceRepo: workspaceRepo,
+ appURL: strings.TrimSuffix(appURL, "/"),
+ }
+}
+
+func (j *MessageDigestJob) Name() string { return "message-digest" }
+func (j *MessageDigestJob) Schedule() string { return "5 * * * *" }
+
+func (j *MessageDigestJob) Run(_ context.Context, _ *asynq.Client) error {
+ if j.notifier == nil || !j.notifier.IsConfigured() {
+ return nil
+ }
+
+ now := time.Now().UTC()
+ sent := 0
+
+ sent += j.runMode(models.NotifyModeHourly, now.Add(-time.Hour), "Hourly", now)
+ if now.Hour() == 8 {
+ sent += j.runMode(models.NotifyModeDaily, now.Add(-24*time.Hour), "Daily", now)
+ }
+
+ logger.Info("message-digest: digests sent", "count", sent)
+ return nil
+}
+
+func (j *MessageDigestJob) runMode(mode models.NotifyMode, since time.Time, label string, now time.Time) int {
+ forms, err := j.formRepo.FindActiveWithDigest(mode)
+ if err != nil {
+ logger.Error("message-digest: failed to list forms", "mode", mode, "error", err)
+ return 0
+ }
+
+ sent := 0
+ for i := range forms {
+ form := &forms[i]
+ if form.WorkspaceID == nil {
+ continue
+ }
+
+ pending, err := j.messageRepo.FindUnnotified(form.ID, since)
+ if err != nil || len(pending) == 0 {
+ continue
+ }
+
+ items := make([]digestItem, 0, len(pending))
+ ids := make([]uint, 0, len(pending))
+ for k := range pending {
+ m := &pending[k]
+ ids = append(ids, m.ID)
+ if m.Status == models.MessageStatusFlagged && !form.NotifyOnFlagged {
+ continue
+ }
+ if len(items) < 25 {
+ items = append(items, digestItem{
+ Sender: senderLabel(m),
+ Subject: m.Subject,
+ Flagged: m.Status == models.MessageStatusFlagged,
+ })
+ }
+ }
+
+ if len(items) == 0 {
+ _ = j.messageRepo.MarkNotified(ids, now)
+ continue
+ }
+
+ workspaceName := ""
+ if ws, err := j.workspaceRepo.FindByID(*form.WorkspaceID); err == nil {
+ workspaceName = ws.Name
+ }
+
+ data := map[string]any{
+ "Period": label,
+ "FormName": form.Name,
+ "Total": len(items),
+ "Items": items,
+ "InboxURL": j.inboxURL(form.UUID),
+ }
+ if workspaceName != "" {
+ data["WorkspaceName"] = workspaceName
+ }
+ subject := fmt.Sprintf("%s digest: %d new message(s) on %s", label, len(items), form.Name)
+
+ if err := j.deliver(form, subject, data); err != nil {
+ logger.Error("message-digest: failed to send", "form_id", form.ID, "error", err)
+ continue
+ }
+
+ _ = j.messageRepo.MarkNotified(ids, now)
+ sent++
+ }
+ return sent
+}
+
+func (j *MessageDigestJob) deliver(form *models.Form, subject string, data map[string]any) error {
+ if len(form.NotifyEmails) > 0 {
+ var lastErr error
+ for _, to := range form.NotifyEmails {
+ to = strings.TrimSpace(to)
+ if to == "" {
+ continue
+ }
+ payload := make(map[string]any, len(data)+1)
+ for k, v := range data {
+ payload[k] = v
+ }
+ payload["UserName"] = "there"
+ if err := j.notifier.Send(to, subject, notification.TemplateMessageDigest, payload); err != nil {
+ lastErr = err
+ }
+ }
+ return lastErr
+ }
+ return j.notifier.SendToWorkspaceAdmins(*form.WorkspaceID, subject, notification.TemplateMessageDigest, data)
+}
+
+func (j *MessageDigestJob) inboxURL(formUUID string) string {
+ if j.appURL == "" {
+ return ""
+ }
+ return fmt.Sprintf("%s/messages?form=%s", j.appURL, formUUID)
+}
+
+func senderLabel(m *models.Message) string {
+ switch {
+ case m.SenderName != "" && m.SenderEmail != "":
+ return fmt.Sprintf("%s <%s>", m.SenderName, m.SenderEmail)
+ case m.SenderEmail != "":
+ return m.SenderEmail
+ case m.SenderName != "":
+ return m.SenderName
+ default:
+ return "unknown"
+ }
+}
diff --git a/internal/cron/jobs/retention.go b/internal/cron/jobs/retention.go
index dfabaec..799e159 100644
--- a/internal/cron/jobs/retention.go
+++ b/internal/cron/jobs/retention.go
@@ -25,6 +25,7 @@ type RetentionCleanupJob struct {
whDeliveryRepo *repositories.WebhookDeliveryRepository
trackingRepo *repositories.TrackingRepository
inboundEmailRepo *repositories.InboundEmailRepository
+ messageRepo *repositories.MessageRepository
blobStore blob.Store
settings *settings.Provider
}
@@ -51,6 +52,10 @@ func (j *RetentionCleanupJob) SetInboundEmailRepo(r *repositories.InboundEmailRe
j.inboundEmailRepo = r
}
+func (j *RetentionCleanupJob) SetMessageRepo(r *repositories.MessageRepository) {
+ j.messageRepo = r
+}
+
// SetBlobStore configures the blob store so retention cleanup can also purge
// attachment bytes (and raw .eml) before dropping DB rows. Nil disables blob
// cleanup — DB rows are still purged, but blobs will leak.
@@ -214,6 +219,8 @@ func (j *RetentionCleanupJob) Run(_ context.Context, _ *asynq.Client) error {
}
}
+ j.cleanupMessages()
+
// Content windows can never usefully exceed the record window — the row (and
// all its content) is deleted first — so cap them at the email log retention.
bodyRetention := capDays(j.settings.EmailBodyRetentionDays(), emailRetention)
@@ -328,3 +335,40 @@ func (j *RetentionCleanupJob) Run(_ context.Context, _ *asynq.Client) error {
return nil
}
+
+func (j *RetentionCleanupJob) cleanupMessages() {
+ if j.messageRepo == nil {
+ return
+ }
+
+ if days := j.settings.MessageSpamRetentionDays(); days > 0 {
+ before := time.Now().AddDate(0, 0, -days)
+ if deleted, err := j.messageRepo.DeleteSpamOlderThan(before); err != nil {
+ logger.Error("retention cleanup: failed to delete spam messages", "error", err)
+ } else if deleted > 0 {
+ logger.Info("retention cleanup: deleted spam messages", "count", deleted, "older_than_days", days)
+ }
+ }
+
+ days := j.settings.MessageRetentionDays()
+ if days <= 0 {
+ return
+ }
+ before := time.Now().AddDate(0, 0, -days)
+
+ if j.blobStore != nil {
+ if jsons, err := j.messageRepo.AttachmentKeysOlderThan(before); err == nil {
+ if n := j.deleteInboundAttachmentBlobs(jsons); n > 0 {
+ logger.Info("retention cleanup: deleted message attachment blobs", "count", n)
+ }
+ } else {
+ logger.Error("retention cleanup: failed to enumerate message attachments", "error", err)
+ }
+ }
+
+ if deleted, err := j.messageRepo.DeleteOlderThan(before); err != nil {
+ logger.Error("retention cleanup: failed to delete old messages", "error", err)
+ } else if deleted > 0 {
+ logger.Info("retention cleanup: deleted old messages", "count", deleted, "older_than_days", days)
+ }
+}
diff --git a/internal/dto/webhook_events.go b/internal/dto/webhook_events.go
index ec537c8..5fc86f9 100644
--- a/internal/dto/webhook_events.go
+++ b/internal/dto/webhook_events.go
@@ -62,3 +62,29 @@ type InboundWebhookAttachment struct {
Size int64 `json:"size"`
URL string `json:"url,omitempty"`
}
+
+// MessageWebhookEvent is the payload for message.received and message.spam.
+type MessageWebhookEvent struct {
+ Event string `json:"event"`
+ Timestamp string `json:"timestamp"`
+ MessageID string `json:"message_id"`
+ FormID string `json:"form_id"`
+ FormName string `json:"form_name"`
+ SenderEmail string `json:"sender_email,omitempty"`
+ SenderName string `json:"sender_name,omitempty"`
+ SenderPhone string `json:"sender_phone,omitempty"`
+ Subject string `json:"subject,omitempty"`
+ Body string `json:"body,omitempty"`
+ Fields []MessageWebhookField `json:"fields,omitempty"`
+ Status string `json:"status"`
+ SpamScore float64 `json:"spam_score"`
+ ScanReasons []string `json:"scan_reasons,omitempty"`
+ ClientIP string `json:"client_ip,omitempty"`
+ ReceivedAt string `json:"received_at"`
+}
+
+// MessageWebhookField is one submitted form field in a MessageWebhookEvent.
+type MessageWebhookField struct {
+ Key string `json:"key"`
+ Value string `json:"value"`
+}
diff --git a/internal/handlers/enum_tag_test.go b/internal/handlers/enum_tag_test.go
new file mode 100644
index 0000000..690b70c
--- /dev/null
+++ b/internal/handlers/enum_tag_test.go
@@ -0,0 +1,88 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package handlers
+
+import (
+ "reflect"
+ "testing"
+)
+
+func assertEnumTagsAreStrings(t *testing.T, v any) {
+ t.Helper()
+ walkEnumTags(t, reflect.TypeOf(v), "")
+}
+
+func walkEnumTags(t *testing.T, typ reflect.Type, path string) {
+ t.Helper()
+ for typ.Kind() == reflect.Pointer {
+ typ = typ.Elem()
+ }
+ if typ.Kind() != reflect.Struct {
+ return
+ }
+
+ for i := 0; i < typ.NumField(); i++ {
+ field := typ.Field(i)
+ name := field.Name
+ if path != "" {
+ name = path + "." + name
+ }
+
+ if enum, ok := field.Tag.Lookup("enum"); ok {
+ kind := field.Type.Kind()
+ if kind == reflect.Slice {
+ kind = field.Type.Elem().Kind()
+ }
+ if kind != reflect.String {
+ t.Errorf("%s has enum:%q but kind %s; okapi only validates enum on string fields, "+
+ "so every request to this endpoint fails to bind", name, enum, field.Type)
+ }
+ }
+
+ if field.Type.Kind() == reflect.Struct {
+ walkEnumTags(t, field.Type, name)
+ }
+ }
+}
+
+func TestRequestEnumTagsOnlyOnStrings(t *testing.T) {
+ requests := []any{
+ CreateFormRequest{},
+ UpdateFormRequest{},
+ FormIDRequest{},
+ MessageListRequest{},
+ UpdateMessageStateRequest{},
+ AssignMessageRequest{},
+ MarkSpamRequest{},
+ ReplyMessageRequest{},
+ MessageAnalyticsRequest{},
+ CreateMessageFilterRequest{},
+ UpdateMessageFilterRequest{},
+ TestMessageFilterRequest{},
+ }
+ for _, req := range requests {
+ assertEnumTagsAreStrings(t, req)
+ }
+}
+
+func TestParseNotifyMode(t *testing.T) {
+ valid := map[string]string{
+ "immediate": "immediate",
+ "HOURLY": "hourly",
+ " daily ": "daily",
+ "off": "off",
+ }
+ for in, want := range valid {
+ got, ok := parseNotifyMode(in)
+ if !ok || string(got) != want {
+ t.Fatalf("parseNotifyMode(%q) = %q,%v; want %q,true", in, got, ok, want)
+ }
+ }
+
+ for _, in := range []string{"", "weekly", "nonsense"} {
+ if _, ok := parseNotifyMode(in); ok {
+ t.Fatalf("parseNotifyMode(%q) reported valid", in)
+ }
+ }
+}
diff --git a/internal/handlers/form_handler.go b/internal/handlers/form_handler.go
new file mode 100644
index 0000000..1121a6f
--- /dev/null
+++ b/internal/handlers/form_handler.go
@@ -0,0 +1,580 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package handlers
+
+import (
+ "crypto/rand"
+ "fmt"
+ "math/big"
+ "net/mail"
+ "net/url"
+ "regexp"
+ "strings"
+ "time"
+
+ "github.com/goposta/posta/internal/models"
+ "github.com/goposta/posta/internal/services/audit"
+ "github.com/goposta/posta/internal/storage/repositories"
+ "github.com/jkaninda/okapi"
+)
+
+const metaSlug = "slug"
+
+const publicKeyAlphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
+const publicKeyLength = 22
+
+var formSlugPattern = regexp.MustCompile(`[^a-z0-9]+`)
+
+type FormHandler struct {
+ repo *repositories.FormRepository
+ messageRepo *repositories.MessageRepository
+ domainRepo *repositories.DomainRepository
+ audit *audit.Logger
+ apiBaseURL string
+}
+
+func NewFormHandler(
+ repo *repositories.FormRepository,
+ messageRepo *repositories.MessageRepository,
+ domainRepo *repositories.DomainRepository,
+ auditLogger *audit.Logger,
+ apiBaseURL string,
+) *FormHandler {
+ return &FormHandler{
+ repo: repo,
+ messageRepo: messageRepo,
+ domainRepo: domainRepo,
+ audit: auditLogger,
+ apiBaseURL: strings.TrimSuffix(apiBaseURL, "/"),
+ }
+}
+
+type CreateFormRequest struct {
+ Body struct {
+ Name string `json:"name" required:"true"`
+ Slug string `json:"slug"`
+ Description string `json:"description"`
+ AllowedOrigins []string `json:"allowed_origins"`
+ StrictOrigin bool `json:"strict_origin"`
+ RedirectURL string `json:"redirect_url"`
+ AllowAttachments bool `json:"allow_attachments"`
+ RequireNonce bool `json:"require_nonce"`
+ NotifyEmails []string `json:"notify_emails"`
+ NotifyMode string `json:"notify_mode" enum:"immediate,hourly,daily,off"`
+ ReplyFrom string `json:"reply_from"`
+ ReplyFromName string `json:"reply_from_name"`
+ } `json:"body"`
+}
+
+type UpdateFormRequest struct {
+ ID int `param:"id"`
+ Body struct {
+ Name string `json:"name"`
+ Slug string `json:"slug"`
+ Description string `json:"description"`
+ Status string `json:"status" enum:"active,paused,archived"`
+ AllowedOrigins *[]string `json:"allowed_origins"`
+ StrictOrigin *bool `json:"strict_origin"`
+ RedirectURL *string `json:"redirect_url"`
+ MaxBodyBytes *int64 `json:"max_body_bytes"`
+ MaxFields *int `json:"max_fields"`
+ AllowAttachments *bool `json:"allow_attachments"`
+ HoneypotField *string `json:"honeypot_field"`
+ RequireNonce *bool `json:"require_nonce"`
+ MinFillSeconds *int `json:"min_fill_seconds"`
+ ScanEnabled *bool `json:"scan_enabled"`
+ FlagThreshold *float64 `json:"flag_threshold"`
+ QuarantineThreshold *float64 `json:"quarantine_threshold"`
+ RejectThreshold *float64 `json:"reject_threshold"`
+ NotifyEnabled *bool `json:"notify_enabled"`
+ NotifyEmails *[]string `json:"notify_emails"`
+ NotifyMode *string `json:"notify_mode" doc:"One of: immediate, hourly, daily, off"`
+ NotifyOnFlagged *bool `json:"notify_on_flagged"`
+ ReplyFrom *string `json:"reply_from"`
+ ReplyFromName *string `json:"reply_from_name"`
+ RetentionDays *int `json:"retention_days"`
+ } `json:"body"`
+}
+
+type FormIDRequest struct {
+ ID int `param:"id"`
+}
+
+type FormSnippetResponse struct {
+ Endpoint string `json:"endpoint"`
+ PublicKey string `json:"public_key"`
+ HTML string `json:"html"`
+ Fetch string `json:"fetch"`
+}
+
+func (h *FormHandler) Create(c *okapi.Context, req *CreateFormRequest) error {
+ if err := requireEdit(c); err != nil {
+ return c.AbortForbidden("insufficient workspace permissions", err)
+ }
+ scope := getScope(c)
+ if scope.WorkspaceID == nil {
+ return c.AbortBadRequest("a workspace is required to create a form")
+ }
+
+ name := strings.TrimSpace(req.Body.Name)
+ if name == "" {
+ return c.AbortBadRequest("name is required")
+ }
+
+ slug := formSlug(req.Body.Slug)
+ if slug == "" {
+ slug = formSlug(name)
+ }
+ if slug == "" {
+ return c.AbortBadRequest("could not derive a slug from the name")
+ }
+ if h.repo.SlugExists(*scope.WorkspaceID, slug, 0) {
+ return c.AbortConflict("a form with that slug already exists")
+ }
+
+ origins, err := normalizeOrigins(req.Body.AllowedOrigins)
+ if err != nil {
+ return c.AbortBadRequest(err.Error())
+ }
+ notify, err := normalizeEmails(req.Body.NotifyEmails)
+ if err != nil {
+ return c.AbortBadRequest(err.Error())
+ }
+ if req.Body.RedirectURL != "" && !isHTTPURL(req.Body.RedirectURL) {
+ return c.AbortBadRequest("redirect_url must be an absolute http(s) URL")
+ }
+ replyFrom := strings.TrimSpace(req.Body.ReplyFrom)
+ if replyFrom != "" {
+ if err := h.checkSender(scope, replyFrom); err != nil {
+ return c.AbortBadRequest(err.Error())
+ }
+ }
+
+ key, err := generatePublicKey()
+ if err != nil {
+ return c.AbortInternalServerError("failed to generate form key")
+ }
+
+ userID := uint(c.GetInt("user_id"))
+ form := &models.Form{
+ WorkspaceID: scope.WorkspaceID,
+ Name: name,
+ Slug: slug,
+ Description: strings.TrimSpace(req.Body.Description),
+ PublicKey: key,
+ Status: models.FormStatusActive,
+ AllowedOrigins: origins,
+ StrictOrigin: req.Body.StrictOrigin,
+ RedirectURL: strings.TrimSpace(req.Body.RedirectURL),
+ MaxBodyBytes: models.DefaultMaxBodyBytes,
+ MaxFields: models.DefaultMaxFields,
+ AllowAttachments: req.Body.AllowAttachments,
+ HoneypotField: models.DefaultHoneypotField,
+ RequireNonce: req.Body.RequireNonce,
+ MinFillSeconds: 3,
+ ScanEnabled: true,
+ FlagThreshold: 3,
+ QuarantineThreshold: 6,
+ RejectThreshold: 10,
+ NotifyEnabled: true,
+ NotifyEmails: notify,
+ NotifyMode: normalizeNotifyMode(req.Body.NotifyMode),
+ NotifyOnFlagged: true,
+ ReplyFrom: replyFrom,
+ ReplyFromName: strings.TrimSpace(req.Body.ReplyFromName),
+ LastEditedByID: &userID,
+ }
+
+ if err := h.repo.Create(form); err != nil {
+ return c.AbortConflict("failed to create form")
+ }
+
+ h.log(c, "form.created", fmt.Sprintf("Form %s created", form.Name), map[string]any{
+ metaFormID: form.ID, metaSlug: form.Slug,
+ })
+ return created(c, form)
+}
+
+func (h *FormHandler) List(c *okapi.Context, req *ListRequest) error {
+ page, size, offset := normalizePageParams(req.Page, req.Size)
+ forms, total, err := h.repo.FindByScope(getScope(c), size, offset)
+ if err != nil {
+ return c.AbortInternalServerError("failed to list forms")
+ }
+ return paginated(c, forms, total, page, size)
+}
+
+func (h *FormHandler) Get(c *okapi.Context, req *FormIDRequest) error {
+ form, err := h.repo.FindByIDForScope(getScope(c), uint(req.ID))
+ if err != nil {
+ return c.AbortNotFound("form not found")
+ }
+ return ok(c, form)
+}
+
+func (h *FormHandler) Update(c *okapi.Context, req *UpdateFormRequest) error {
+ if err := requireEdit(c); err != nil {
+ return c.AbortForbidden("insufficient workspace permissions", err)
+ }
+ scope := getScope(c)
+ form, err := h.repo.FindByIDForScope(scope, uint(req.ID))
+ if err != nil {
+ return c.AbortNotFound("form not found")
+ }
+
+ b := req.Body
+ if strings.TrimSpace(b.Name) != "" {
+ form.Name = strings.TrimSpace(b.Name)
+ }
+ if strings.TrimSpace(b.Slug) != "" {
+ slug := formSlug(b.Slug)
+ if slug == "" {
+ return c.AbortBadRequest("invalid slug")
+ }
+ if h.repo.SlugExists(*scope.WorkspaceID, slug, form.ID) {
+ return c.AbortConflict("a form with that slug already exists")
+ }
+ form.Slug = slug
+ }
+ if strings.TrimSpace(b.Description) != "" {
+ form.Description = strings.TrimSpace(b.Description)
+ }
+ if b.Status != "" {
+ status := models.FormStatus(b.Status)
+ if status != models.FormStatusActive && status != models.FormStatusPaused && status != models.FormStatusArchived {
+ return c.AbortBadRequest("invalid status")
+ }
+ form.Status = status
+ }
+ if b.AllowedOrigins != nil {
+ origins, err := normalizeOrigins(*b.AllowedOrigins)
+ if err != nil {
+ return c.AbortBadRequest(err.Error())
+ }
+ form.AllowedOrigins = origins
+ }
+ if b.StrictOrigin != nil {
+ form.StrictOrigin = *b.StrictOrigin
+ }
+ if b.RedirectURL != nil {
+ target := strings.TrimSpace(*b.RedirectURL)
+ if target != "" && !isHTTPURL(target) {
+ return c.AbortBadRequest("redirect_url must be an absolute http(s) URL")
+ }
+ form.RedirectURL = target
+ }
+ if b.MaxBodyBytes != nil && *b.MaxBodyBytes > 0 {
+ form.MaxBodyBytes = clampInt64(*b.MaxBodyBytes, 1024, 1048576)
+ }
+ if b.MaxFields != nil && *b.MaxFields > 0 {
+ form.MaxFields = clampInt(*b.MaxFields, 1, 200)
+ }
+ if b.AllowAttachments != nil {
+ form.AllowAttachments = *b.AllowAttachments
+ }
+ if b.HoneypotField != nil {
+ field := strings.TrimSpace(*b.HoneypotField)
+ if field == "" {
+ field = models.DefaultHoneypotField
+ }
+ form.HoneypotField = field
+ }
+ if b.RequireNonce != nil {
+ form.RequireNonce = *b.RequireNonce
+ }
+ if b.MinFillSeconds != nil {
+ form.MinFillSeconds = clampInt(*b.MinFillSeconds, 0, 120)
+ }
+ if b.ScanEnabled != nil {
+ form.ScanEnabled = *b.ScanEnabled
+ }
+ if b.FlagThreshold != nil {
+ form.FlagThreshold = *b.FlagThreshold
+ }
+ if b.QuarantineThreshold != nil {
+ form.QuarantineThreshold = *b.QuarantineThreshold
+ }
+ if b.RejectThreshold != nil {
+ form.RejectThreshold = *b.RejectThreshold
+ }
+ if form.QuarantineThreshold < form.FlagThreshold || form.RejectThreshold < form.QuarantineThreshold {
+ return c.AbortBadRequest("thresholds must satisfy flag <= quarantine <= reject")
+ }
+ if b.NotifyEnabled != nil {
+ form.NotifyEnabled = *b.NotifyEnabled
+ }
+ if b.NotifyEmails != nil {
+ notify, err := normalizeEmails(*b.NotifyEmails)
+ if err != nil {
+ return c.AbortBadRequest(err.Error())
+ }
+ form.NotifyEmails = notify
+ }
+ if b.NotifyMode != nil {
+ mode, valid := parseNotifyMode(*b.NotifyMode)
+ if !valid {
+ return c.AbortBadRequest("notify_mode must be one of: immediate, hourly, daily, off")
+ }
+ form.NotifyMode = mode
+ }
+ if b.NotifyOnFlagged != nil {
+ form.NotifyOnFlagged = *b.NotifyOnFlagged
+ }
+ if b.ReplyFrom != nil {
+ replyFrom := strings.TrimSpace(*b.ReplyFrom)
+ if replyFrom != "" {
+ if err := h.checkSender(scope, replyFrom); err != nil {
+ return c.AbortBadRequest(err.Error())
+ }
+ }
+ form.ReplyFrom = replyFrom
+ }
+ if b.ReplyFromName != nil {
+ form.ReplyFromName = strings.TrimSpace(*b.ReplyFromName)
+ }
+ if b.RetentionDays != nil {
+ form.RetentionDays = clampInt(*b.RetentionDays, 0, 3650)
+ }
+
+ userID := uint(c.GetInt("user_id"))
+ now := time.Now()
+ form.LastEditedByID = &userID
+ form.UpdatedAt = &now
+
+ if err := h.repo.Update(form); err != nil {
+ return c.AbortInternalServerError("failed to update form")
+ }
+
+ h.log(c, "form.updated", fmt.Sprintf("Form %s updated", form.Name), map[string]any{metaFormID: form.ID})
+ return ok(c, form)
+}
+
+func (h *FormHandler) Delete(c *okapi.Context, req *FormIDRequest) error {
+ if err := requireEdit(c); err != nil {
+ return c.AbortForbidden("insufficient workspace permissions", err)
+ }
+ form, err := h.repo.FindByIDForScope(getScope(c), uint(req.ID))
+ if err != nil {
+ return c.AbortNotFound("form not found")
+ }
+ if err := h.repo.Delete(form.ID); err != nil {
+ return c.AbortInternalServerError("failed to delete form")
+ }
+ h.log(c, "form.deleted", fmt.Sprintf("Form %s deleted", form.Name), map[string]any{metaFormID: form.ID})
+ return noContent(c)
+}
+
+func (h *FormHandler) RotateKey(c *okapi.Context, req *FormIDRequest) error {
+ if err := requireEdit(c); err != nil {
+ return c.AbortForbidden("insufficient workspace permissions", err)
+ }
+ form, err := h.repo.FindByIDForScope(getScope(c), uint(req.ID))
+ if err != nil {
+ return c.AbortNotFound("form not found")
+ }
+ key, err := generatePublicKey()
+ if err != nil {
+ return c.AbortInternalServerError("failed to generate form key")
+ }
+ now := time.Now()
+ form.PublicKey = key
+ form.UpdatedAt = &now
+ if err := h.repo.Update(form); err != nil {
+ return c.AbortInternalServerError("failed to rotate form 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)
+}
+
+func (h *FormHandler) Snippet(c *okapi.Context, req *FormIDRequest) error {
+ form, err := h.repo.FindByIDForScope(getScope(c), uint(req.ID))
+ if err != nil {
+ return c.AbortNotFound("form not found")
+ }
+ endpoint := fmt.Sprintf("%s/api/v1/f/%s", h.apiBaseURL, form.PublicKey)
+ return ok(c, FormSnippetResponse{
+ Endpoint: endpoint,
+ PublicKey: form.PublicKey,
+ HTML: buildHTMLSnippet(endpoint, form),
+ Fetch: buildFetchSnippet(endpoint),
+ })
+}
+
+func (h *FormHandler) checkSender(scope repositories.ResourceScope, address string) error {
+ addr, err := mail.ParseAddress(address)
+ if err != nil {
+ return fmt.Errorf("reply_from must be a valid email address")
+ }
+ if h.domainRepo == nil {
+ return nil
+ }
+ at := strings.LastIndex(addr.Address, "@")
+ if at < 0 {
+ return fmt.Errorf("reply_from must be a valid email address")
+ }
+ domain := strings.ToLower(addr.Address[at+1:])
+
+ domains, _, err := h.domainRepo.FindByScope(scope, 200, 0)
+ if err != nil {
+ return nil
+ }
+ for _, d := range domains {
+ if strings.EqualFold(d.Domain, domain) && d.IsOwnershipVerified() {
+ return nil
+ }
+ }
+ return fmt.Errorf("reply_from domain %s is not a verified domain in this workspace", domain)
+}
+
+func (h *FormHandler) log(c *okapi.Context, action, message string, meta map[string]any) {
+ if h.audit == nil {
+ return
+ }
+ h.audit.LogCtx(c, action, message, meta)
+}
+
+func formSlug(v string) string {
+ v = strings.ToLower(strings.TrimSpace(v))
+ v = formSlugPattern.ReplaceAllString(v, "-")
+ v = strings.Trim(v, "-")
+ if len(v) > 60 {
+ v = strings.Trim(v[:60], "-")
+ }
+ return v
+}
+
+func generatePublicKey() (string, error) {
+ out := make([]byte, publicKeyLength)
+ max := big.NewInt(int64(len(publicKeyAlphabet)))
+ for i := range out {
+ n, err := rand.Int(rand.Reader, max)
+ if err != nil {
+ return "", err
+ }
+ out[i] = publicKeyAlphabet[n.Int64()]
+ }
+ return string(out), nil
+}
+
+func normalizeOrigins(in []string) ([]string, error) {
+ out := make([]string, 0, len(in))
+ for _, raw := range in {
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ continue
+ }
+ if raw == "*" {
+ out = append(out, raw)
+ continue
+ }
+ u, err := url.Parse(raw)
+ if err != nil || u.Scheme == "" || u.Host == "" {
+ return nil, fmt.Errorf("allowed origin %q must include a scheme and host, e.g. https://example.com", raw)
+ }
+ out = append(out, strings.ToLower(u.Scheme+"://"+u.Host))
+ }
+ return out, nil
+}
+
+func normalizeEmails(in []string) ([]string, error) {
+ out := make([]string, 0, len(in))
+ for _, raw := range in {
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ continue
+ }
+ addr, err := mail.ParseAddress(raw)
+ if err != nil {
+ return nil, fmt.Errorf("%q is not a valid email address", raw)
+ }
+ out = append(out, addr.Address)
+ }
+ if len(out) > 10 {
+ return nil, fmt.Errorf("at most 10 notification recipients are allowed")
+ }
+ return out, nil
+}
+
+func parseNotifyMode(v string) (models.NotifyMode, bool) {
+ switch models.NotifyMode(strings.ToLower(strings.TrimSpace(v))) {
+ case models.NotifyModeImmediate:
+ return models.NotifyModeImmediate, true
+ case models.NotifyModeHourly:
+ return models.NotifyModeHourly, true
+ case models.NotifyModeDaily:
+ return models.NotifyModeDaily, true
+ case models.NotifyModeOff:
+ return models.NotifyModeOff, true
+ default:
+ return models.NotifyModeImmediate, false
+ }
+}
+
+func normalizeNotifyMode(v string) models.NotifyMode {
+ if strings.TrimSpace(v) == "" {
+ return models.NotifyModeImmediate
+ }
+ mode, _ := parseNotifyMode(v)
+ return mode
+}
+
+func isHTTPURL(v string) bool {
+ u, err := url.Parse(v)
+ return err == nil && (u.Scheme == "http" || u.Scheme == "https") && u.Host != ""
+}
+
+func clampInt(v, lo, hi int) int {
+ if v < lo {
+ return lo
+ }
+ if v > hi {
+ return hi
+ }
+ return v
+}
+
+func clampInt64(v, lo, hi int64) int64 {
+ if v < lo {
+ return lo
+ }
+ if v > hi {
+ return hi
+ }
+ return v
+}
+
+func buildHTMLSnippet(endpoint string, form *models.Form) string {
+ return fmt.Sprintf(`<form action="%s" method="POST">
+ <label for="posta-name">Name</label>
+ <input id="posta-name" type="text" name="name" required>
+
+ <label for="posta-email">Email</label>
+ <input id="posta-email" type="email" name="email" required>
+
+ <label for="posta-phone">Phone (optional)</label>
+ <input id="posta-phone" type="tel" name="phone" autocomplete="tel">
+
+ <label for="posta-message">Message</label>
+ <textarea id="posta-message" name="message" required></textarea>
+
+ <div style="position:absolute;left:-9999px" aria-hidden="true">
+ <input type="text" name="%s" tabindex="-1" autocomplete="off">
+ </div>
+
+ <button type="submit">Send</button>
+</form>`, endpoint, form.Honeypot())
+}
+
+func buildFetchSnippet(endpoint string) string {
+ return fmt.Sprintf(`await fetch(%q, {
+ method: 'POST',
+ headers: { 'Content-Type': 'text/plain;charset=UTF-8' },
+ body: JSON.stringify({
+ name: form.name.value,
+ email: form.email.value,
+ phone: form.phone.value,
+ message: form.message.value,
+ }),
+})`, endpoint)
+}
diff --git a/internal/handlers/form_handler_test.go b/internal/handlers/form_handler_test.go
new file mode 100644
index 0000000..34fc90b
--- /dev/null
+++ b/internal/handlers/form_handler_test.go
@@ -0,0 +1,174 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package handlers
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/goposta/posta/internal/models"
+)
+
+func TestFormSlug(t *testing.T) {
+ cases := map[string]string{
+ "Contact Form": "contact-form",
+ " Support!! ": "support",
+ "Ünïcödé Näme": "n-c-d-n-me",
+ "already-a-slug": "already-a-slug",
+ "!!!": "",
+ "": "",
+ strings.Repeat("a", 100): strings.Repeat("a", 60),
+ }
+ for in, want := range cases {
+ if got := formSlug(in); got != want {
+ t.Fatalf("formSlug(%q) = %q, want %q", in, got, want)
+ }
+ }
+}
+
+func TestGeneratePublicKey(t *testing.T) {
+ seen := map[string]bool{}
+ for i := 0; i < 100; i++ {
+ key, err := generatePublicKey()
+ if err != nil {
+ t.Fatalf("generatePublicKey: %v", err)
+ }
+ if len(key) != publicKeyLength {
+ t.Fatalf("key length = %d, want %d", len(key), publicKeyLength)
+ }
+ if seen[key] {
+ t.Fatalf("duplicate key generated: %s", key)
+ }
+ seen[key] = true
+ for _, r := range key {
+ if !strings.ContainsRune(publicKeyAlphabet, r) {
+ t.Fatalf("key %q contains an out-of-alphabet rune %q", key, r)
+ }
+ }
+ }
+}
+
+func TestNormalizeOrigins(t *testing.T) {
+ got, err := normalizeOrigins([]string{" https://Example.com/ ", "", "*"})
+ if err != nil {
+ t.Fatalf("normalizeOrigins: %v", err)
+ }
+ if len(got) != 2 || got[0] != "https://example.com" || got[1] != "*" {
+ t.Fatalf("got %v", got)
+ }
+
+ if _, err := normalizeOrigins([]string{"example.com"}); err == nil {
+ t.Fatal("a scheme-less origin should be rejected")
+ }
+}
+
+func TestNormalizeEmails(t *testing.T) {
+ got, err := normalizeEmails([]string{"Ada <[email protected]>", " [email protected] "})
+ if err != nil {
+ t.Fatalf("normalizeEmails: %v", err)
+ }
+ if len(got) != 2 || got[0] != "[email protected]" || got[1] != "[email protected]" {
+ t.Fatalf("got %v", got)
+ }
+
+ if _, err := normalizeEmails([]string{"nope"}); err == nil {
+ t.Fatal("an invalid address should be rejected")
+ }
+
+ many := make([]string, 11)
+ for i := range many {
+ many[i] = "[email protected]"
+ }
+ if _, err := normalizeEmails(many); err == nil {
+ t.Fatal("more than 10 recipients should be rejected")
+ }
+}
+
+func TestNormalizeNotifyMode(t *testing.T) {
+ cases := map[string]models.NotifyMode{
+ "hourly": models.NotifyModeHourly,
+ "DAILY": models.NotifyModeDaily,
+ "off": models.NotifyModeOff,
+ "immediate": models.NotifyModeImmediate,
+ "nonsense": models.NotifyModeImmediate,
+ "": models.NotifyModeImmediate,
+ }
+ for in, want := range cases {
+ if got := normalizeNotifyMode(in); got != want {
+ t.Fatalf("normalizeNotifyMode(%q) = %s, want %s", in, got, want)
+ }
+ }
+}
+
+func TestIsHTTPURL(t *testing.T) {
+ cases := map[string]bool{
+ "https://example.com/thanks": true,
+ "http://example.com": true,
+ "javascript:alert(1)": false,
+ "/relative": false,
+ "ftp://example.com": false,
+ }
+ for in, want := range cases {
+ if got := isHTTPURL(in); got != want {
+ t.Fatalf("isHTTPURL(%q) = %v, want %v", in, got, want)
+ }
+ }
+}
+
+func TestBuildHTMLSnippetIncludesHoneypot(t *testing.T) {
+ form := &models.Form{Name: "Contact", HoneypotField: "_trap"}
+ snippet := buildHTMLSnippet("https://posta.test/api/v1/f/abc", form)
+ if !strings.Contains(snippet, `name="_trap"`) {
+ t.Fatalf("snippet is missing the honeypot field:\n%s", snippet)
+ }
+ if !strings.Contains(snippet, `aria-hidden="true"`) {
+ t.Fatal("the honeypot must be hidden from screen readers")
+ }
+ if !strings.Contains(snippet, "https://posta.test/api/v1/f/abc") {
+ t.Fatal("snippet is missing the endpoint")
+ }
+}
+
+func TestFormHelpersOnZeroValueForm(t *testing.T) {
+ form := &models.Form{}
+ if form.Honeypot() != models.DefaultHoneypotField {
+ t.Fatalf("Honeypot() = %q", form.Honeypot())
+ }
+ if form.BodyLimit() != models.DefaultMaxBodyBytes {
+ t.Fatalf("BodyLimit() = %d", form.BodyLimit())
+ }
+ if form.FieldLimit() != models.DefaultMaxFields {
+ t.Fatalf("FieldLimit() = %d", form.FieldLimit())
+ }
+}
+
+func TestMessageCanReply(t *testing.T) {
+ cases := []struct {
+ name string
+ msg models.Message
+ want bool
+ }{
+ {"no sender", models.Message{Status: models.MessageStatusReceived}, false},
+ {"rejected", models.Message{SenderEmail: "[email protected]", Status: models.MessageStatusRejected}, false},
+ {"received", models.Message{SenderEmail: "[email protected]", Status: models.MessageStatusReceived}, true},
+ {"flagged", models.Message{SenderEmail: "[email protected]", Status: models.MessageStatusFlagged}, true},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := tc.msg.CanReply(); got != tc.want {
+ t.Fatalf("CanReply() = %v, want %v", got, tc.want)
+ }
+ })
+ }
+}
+
+func TestTruncateBody(t *testing.T) {
+ if got := truncateBody("hello", 10); got != "hello" {
+ t.Fatalf("got %q", got)
+ }
+ got := truncateBody(strings.Repeat("a", 50), 10)
+ if len([]rune(got)) != 11 || !strings.HasSuffix(got, "…") {
+ t.Fatalf("got %q", got)
+ }
+}
diff --git a/internal/handlers/form_ingest_handler.go b/internal/handlers/form_ingest_handler.go
new file mode 100644
index 0000000..1e4e69c
--- /dev/null
+++ b/internal/handlers/form_ingest_handler.go
@@ -0,0 +1,379 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package handlers
+
+import (
+ "bytes"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "mime"
+ "net/http"
+ "net/url"
+ "strconv"
+ "strings"
+
+ "github.com/goposta/posta/internal/models"
+ "github.com/goposta/posta/internal/services/inbound"
+ "github.com/goposta/posta/internal/services/messages"
+ "github.com/goposta/posta/internal/storage/blob"
+ "github.com/jkaninda/logger"
+ "github.com/jkaninda/okapi"
+)
+
+const genericAcceptMessage = "Thanks — your message has been received."
+
+type FormIngestHandler struct {
+ svc *messages.Service
+ blobStore blob.Store
+ limiter *inbound.IPRateLimiter
+ maxAttach int64
+}
+
+func NewFormIngestHandler(svc *messages.Service, limiter *inbound.IPRateLimiter, maxAttach int64) *FormIngestHandler {
+ return &FormIngestHandler{svc: svc, limiter: limiter, maxAttach: maxAttach}
+}
+
+func (h *FormIngestHandler) SetBlobStore(bs blob.Store) { h.blobStore = bs }
+
+type ingestResponse struct {
+ Success bool `json:"success"`
+ Data ingestRespData `json:"data"`
+}
+
+type ingestRespData struct {
+ ID string `json:"id,omitempty"`
+ Status string `json:"status"`
+ Message string `json:"message"`
+}
+
+func (h *FormIngestHandler) Nonce(c *okapi.Context) error {
+ key := c.Param("key")
+ form, err := h.svc.FindFormByKey(key)
+ if err != nil || !form.IsActive() {
+ return c.AbortNotFound("form not found")
+ }
+ h.applyCORS(c, form)
+
+ nonce, err := h.svc.IssueNonce(c.Request().Context(), key)
+ if err != nil {
+ return c.AbortInternalServerError("failed to issue nonce")
+ }
+ return ok(c, nonce)
+}
+
+func (h *FormIngestHandler) Submit(c *okapi.Context) error {
+ req := c.Request()
+ key := c.Param("key")
+ clientIP := c.RealIP()
+
+ if h.limiter != nil && !h.limiter.Allow(clientIP) {
+ return h.respond(c, nil, nil, http.StatusTooManyRequests, "rate_limited", "Too many submissions. Try again later.")
+ }
+
+ form, err := h.svc.FindFormByKey(key)
+ if err != nil || !form.IsActive() {
+ return h.respond(c, nil, nil, http.StatusAccepted, "received", genericAcceptMessage)
+ }
+
+ origin := req.Header.Get("Origin")
+ if !messages.OriginAllowed(form, 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)
+
+ fields, attachments, redirect, err := h.parseBody(c, form)
+ if err != nil {
+ switch {
+ case errors.Is(err, messages.ErrPayloadTooLarge):
+ return h.respond(c, form, nil, http.StatusRequestEntityTooLarge, "too_large", "Submission is too large.")
+ case errors.Is(err, messages.ErrTooManyFields):
+ return h.respond(c, form, nil, http.StatusBadRequest, "too_many_fields", "Submission has too many fields.")
+ }
+ return h.respond(c, form, nil, http.StatusBadRequest, "invalid_payload", "Submission could not be read.")
+ }
+
+ honeypot := false
+ nonceFailed := false
+ var nonceToken string
+ for _, f := range fields {
+ switch strings.ToLower(f.Key) {
+ case strings.ToLower(form.Honeypot()):
+ if strings.TrimSpace(f.Value) != "" {
+ honeypot = true
+ }
+ case "_nonce":
+ nonceToken = strings.TrimSpace(f.Value)
+ }
+ }
+
+ if form.RequireNonce {
+ if err := h.svc.VerifyNonce(req.Context(), key, nonceToken, form.MinFillSeconds); err != nil {
+ nonceFailed = true
+ }
+ }
+
+ result, err := h.svc.Submit(req.Context(), messages.SubmitRequest{
+ Form: form,
+ Fields: fields,
+ Attachments: attachments,
+ ClientIP: clientIP,
+ UserAgent: req.UserAgent(),
+ Referer: req.Referer(),
+ Origin: origin,
+ HoneypotHit: honeypot,
+ NonceFailed: nonceFailed,
+ })
+ if err != nil {
+ if errors.Is(err, messages.ErrRateLimited) {
+ return h.respond(c, form, nil, http.StatusTooManyRequests, "rate_limited", "Too many submissions. Try again later.")
+ }
+ if errors.Is(err, messages.ErrTooManyFields) {
+ return h.respond(c, form, nil, http.StatusBadRequest, "too_many_fields", "Submission has too many fields.")
+ }
+ logger.Error("form submission failed", "form_id", form.ID, "error", err)
+ return h.respond(c, form, nil, http.StatusInternalServerError, "error", "Submission could not be stored.")
+ }
+
+ if redirect != "" && messages.RedirectAllowed(form, redirect) {
+ c.Redirect(http.StatusSeeOther, redirect)
+ return nil
+ }
+ if redirect == "" && form.RedirectURL != "" && !wantsJSON(req) {
+ c.Redirect(http.StatusSeeOther, form.RedirectURL)
+ return nil
+ }
+
+ return h.respond(c, form, result.Message, http.StatusAccepted, "received", genericAcceptMessage)
+}
+
+func (h *FormIngestHandler) parseBody(c *okapi.Context, form *models.Form) ([]models.MessageField, []models.InboundAttachmentMeta, string, error) {
+ req := c.Request()
+ limit := form.BodyLimit()
+ contentType, _, _ := mime.ParseMediaType(req.Header.Get("Content-Type"))
+
+ switch contentType {
+ case "multipart/form-data":
+ return h.parseMultipart(c, form, limit)
+
+ case "application/json", "text/plain":
+ body, err := io.ReadAll(io.LimitReader(req.Body, limit+1))
+ if err != nil {
+ return nil, nil, "", err
+ }
+ if int64(len(body)) > limit {
+ return nil, nil, "", messages.ErrPayloadTooLarge
+ }
+ var raw map[string]any
+ if err := json.Unmarshal(body, &raw); err != nil {
+ return nil, nil, "", err
+ }
+ fields := make([]models.MessageField, 0, len(raw))
+ for k, v := range raw {
+ fields = append(fields, models.MessageField{Key: k, Value: stringify(v)})
+ }
+ if len(fields) > form.FieldLimit() {
+ return nil, nil, "", messages.ErrTooManyFields
+ }
+ return fields, nil, redirectFrom(raw), nil
+
+ default:
+ if err := h.parseFormValues(c, limit); err != nil {
+ return nil, nil, "", err
+ }
+ fields, redirect := valuesToFields(req.PostForm)
+ if len(fields) > form.FieldLimit() {
+ return nil, nil, "", messages.ErrTooManyFields
+ }
+ return fields, nil, redirect, nil
+ }
+}
+
+func (h *FormIngestHandler) parseFormValues(c *okapi.Context, limit int64) error {
+ req := c.Request()
+ req.Body = http.MaxBytesReader(c.ResponseWriter(), req.Body, limit)
+ if err := req.ParseForm(); err != nil {
+ return messages.ErrPayloadTooLarge
+ }
+ return nil
+}
+
+func (h *FormIngestHandler) parseMultipart(c *okapi.Context, form *models.Form, limit int64) ([]models.MessageField, []models.InboundAttachmentMeta, string, error) {
+ req := c.Request()
+ maxMemory := limit + h.maxAttach
+ req.Body = http.MaxBytesReader(c.ResponseWriter(), req.Body, maxMemory+1024)
+ if err := req.ParseMultipartForm(limit); err != nil {
+ return nil, nil, "", messages.ErrPayloadTooLarge
+ }
+
+ fields, redirect := valuesToFields(req.MultipartForm.Value)
+ if len(fields) > form.FieldLimit() {
+ return nil, nil, "", messages.ErrTooManyFields
+ }
+
+ var attachments []models.InboundAttachmentMeta
+ if !form.AllowAttachments {
+ return fields, nil, redirect, nil
+ }
+ for _, headers := range req.MultipartForm.File {
+ for _, fh := range headers {
+ if len(attachments) >= 5 {
+ break
+ }
+ if fh.Size > h.maxAttach {
+ continue
+ }
+ file, err := fh.Open()
+ if err != nil {
+ continue
+ }
+ data, err := io.ReadAll(io.LimitReader(file, h.maxAttach))
+ _ = file.Close()
+ if err != nil {
+ continue
+ }
+ meta := models.InboundAttachmentMeta{
+ Filename: messages.SanitizeHeaderValue(fh.Filename),
+ ContentType: fh.Header.Get("Content-Type"),
+ Size: int64(len(data)),
+ }
+ if h.blobStore != nil {
+ key := fmt.Sprintf("messages/%s/%d_%s", form.UUID, len(attachments), safeFilename(meta.Filename))
+ if err := h.blobStore.Put(c.Request().Context(), key, bytes.NewReader(data), meta.ContentType); err == nil {
+ meta.StorageKey = key
+ }
+ }
+ if meta.StorageKey == "" {
+ meta.Content = base64.StdEncoding.EncodeToString(data)
+ }
+ attachments = append(attachments, meta)
+ }
+ }
+
+ return fields, attachments, redirect, nil
+}
+
+func (h *FormIngestHandler) applyCORS(c *okapi.Context, form *models.Form) {
+ origin := c.Request().Header.Get("Origin")
+ if origin == "" || !messages.OriginAllowed(form, origin) {
+ return
+ }
+ w := c.ResponseWriter()
+ w.Header().Set("Access-Control-Allow-Origin", origin)
+ w.Header().Set("Vary", "Origin")
+}
+
+func (h *FormIngestHandler) respond(c *okapi.Context, form *models.Form, msg *models.Message, status int, code, message string) error {
+ if form != nil {
+ h.applyCORS(c, form)
+ }
+
+ if !wantsJSON(c.Request()) && status < 400 {
+ return trackingNotice(c, status, "Message sent", message, "success")
+ }
+ if !wantsJSON(c.Request()) {
+ return trackingNotice(c, status, "Message not sent", message, "error")
+ }
+
+ data := ingestRespData{Status: code, Message: message}
+ if msg != nil && status < 400 {
+ data.ID = msg.UUID
+ }
+ return c.JSON(status, ingestResponse{Success: status < 400, Data: data})
+}
+
+func wantsJSON(req *http.Request) bool {
+ contentType := req.Header.Get("Content-Type")
+ if strings.Contains(contentType, "application/json") || strings.Contains(contentType, "text/plain") {
+ return true
+ }
+ accept := req.Header.Get("Accept")
+ if strings.Contains(accept, "application/json") {
+ return true
+ }
+ return !strings.Contains(accept, "text/html") && accept != ""
+}
+
+func valuesToFields(values url.Values) ([]models.MessageField, string) {
+ fields := make([]models.MessageField, 0, len(values))
+ redirect := ""
+ for key, vals := range values {
+ if len(vals) == 0 {
+ continue
+ }
+ value := strings.Join(vals, ", ")
+ if strings.EqualFold(key, "_redirect") || strings.EqualFold(key, "_next") {
+ redirect = value
+ continue
+ }
+ fields = append(fields, models.MessageField{Key: key, Value: value})
+ }
+ return fields, redirect
+}
+
+func redirectFrom(raw map[string]any) string {
+ for _, key := range []string{"_redirect", "_next"} {
+ if v, exists := raw[key]; exists {
+ return stringify(v)
+ }
+ }
+ return ""
+}
+
+func stringify(v any) string {
+ switch t := v.(type) {
+ case nil:
+ return ""
+ case string:
+ return t
+ case bool:
+ if t {
+ return "true"
+ }
+ return "false"
+ case float64:
+ if t == float64(int64(t)) {
+ return strings.TrimSuffix(strings.TrimRight(strings.TrimRight(formatFloat(t), "0"), "."), ".")
+ }
+ return formatFloat(t)
+ case []any:
+ parts := make([]string, 0, len(t))
+ for _, item := range t {
+ parts = append(parts, stringify(item))
+ }
+ return strings.Join(parts, ", ")
+ default:
+ encoded, err := json.Marshal(t)
+ if err != nil {
+ return ""
+ }
+ return string(encoded)
+ }
+}
+
+func formatFloat(f float64) string {
+ return strconv.FormatFloat(f, 'f', -1, 64)
+}
+
+func safeFilename(name string) string {
+ name = strings.Map(func(r rune) rune {
+ switch {
+ case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9':
+ return r
+ case r == '.', r == '-', r == '_':
+ return r
+ default:
+ return '_'
+ }
+ }, name)
+ if name == "" {
+ return "attachment"
+ }
+ if len(name) > 100 {
+ name = name[:100]
+ }
+ return name
+}
diff --git a/internal/handlers/message_filter_handler.go b/internal/handlers/message_filter_handler.go
new file mode 100644
index 0000000..9a0a23a
--- /dev/null
+++ b/internal/handlers/message_filter_handler.go
@@ -0,0 +1,276 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package handlers
+
+import (
+ "strings"
+ "time"
+
+ "github.com/goposta/posta/internal/models"
+ "github.com/goposta/posta/internal/services/messagescan"
+ "github.com/goposta/posta/internal/storage/repositories"
+ "github.com/jkaninda/okapi"
+)
+
+type MessageFilterHandler struct {
+ repo *repositories.MessageFilterRepository
+ messageRepo *repositories.MessageRepository
+ formRepo *repositories.FormRepository
+ scanner *messagescan.Scanner
+}
+
+func NewMessageFilterHandler(
+ repo *repositories.MessageFilterRepository,
+ messageRepo *repositories.MessageRepository,
+ formRepo *repositories.FormRepository,
+ scanner *messagescan.Scanner,
+) *MessageFilterHandler {
+ return &MessageFilterHandler{repo: repo, messageRepo: messageRepo, formRepo: formRepo, scanner: scanner}
+}
+
+type CreateMessageFilterRequest struct {
+ Body struct {
+ FormID *uint `json:"form_id"`
+ Kind string `json:"kind" required:"true" enum:"keyword,phrase,regex,email,domain,ip"`
+ Pattern string `json:"pattern" required:"true"`
+ Action string `json:"action" enum:"score,flag,quarantine,reject,allowlist"`
+ Score *float64 `json:"score"`
+ Fields []string `json:"fields"`
+ CaseSensitive bool `json:"case_sensitive"`
+ Note string `json:"note"`
+ } `json:"body"`
+}
+
+type UpdateMessageFilterRequest struct {
+ ID int `param:"id"`
+ Body struct {
+ Pattern string `json:"pattern"`
+ Action string `json:"action" enum:"score,flag,quarantine,reject,allowlist"`
+ Score *float64 `json:"score"`
+ Fields *[]string `json:"fields"`
+ CaseSensitive *bool `json:"case_sensitive"`
+ Enabled *bool `json:"enabled"`
+ Note *string `json:"note"`
+ } `json:"body"`
+}
+
+type MessageFilterIDRequest struct {
+ ID int `param:"id"`
+}
+
+type TestMessageFilterRequest struct {
+ Body struct {
+ Kind string `json:"kind" required:"true" enum:"keyword,phrase,regex,email,domain,ip"`
+ Pattern string `json:"pattern" required:"true"`
+ CaseSensitive bool `json:"case_sensitive"`
+ Limit int `json:"limit"`
+ } `json:"body"`
+}
+
+type FilterMatch struct {
+ MessageUUID string `json:"message_uuid"`
+ SenderEmail string `json:"sender_email"`
+ Subject string `json:"subject"`
+ Excerpt string `json:"excerpt"`
+}
+
+type TestMessageFilterResponse struct {
+ Scanned int `json:"scanned"`
+ Matched int `json:"matched"`
+ Samples []FilterMatch `json:"samples"`
+}
+
+func (h *MessageFilterHandler) Create(c *okapi.Context, req *CreateMessageFilterRequest) error {
+ if err := requireEdit(c); err != nil {
+ return c.AbortForbidden("insufficient workspace permissions", err)
+ }
+ scope := getScope(c)
+ if scope.WorkspaceID == nil {
+ return c.AbortBadRequest("a workspace is required")
+ }
+
+ kind := models.FilterKind(strings.ToLower(strings.TrimSpace(req.Body.Kind)))
+ if !models.ValidFilterKinds[kind] {
+ return c.AbortBadRequest("invalid filter kind")
+ }
+ pattern := strings.TrimSpace(req.Body.Pattern)
+ if err := messagescan.ValidatePattern(kind, pattern); err != nil {
+ return c.AbortBadRequest(err.Error())
+ }
+
+ action := models.FilterAction(strings.ToLower(strings.TrimSpace(req.Body.Action)))
+ if action == "" {
+ action = models.FilterActionScore
+ }
+ if !models.ValidFilterActions[action] {
+ return c.AbortBadRequest("invalid filter action")
+ }
+
+ if req.Body.FormID != nil {
+ if _, err := h.formRepo.FindByIDForScope(scope, *req.Body.FormID); err != nil {
+ return c.AbortBadRequest("form not found in this workspace")
+ }
+ }
+
+ score := 3.0
+ if req.Body.Score != nil {
+ score = *req.Body.Score
+ }
+
+ filter := &models.MessageFilter{
+ WorkspaceID: scope.WorkspaceID,
+ FormID: req.Body.FormID,
+ Kind: kind,
+ Pattern: pattern,
+ Action: action,
+ Score: score,
+ Fields: normalizeFilterFields(req.Body.Fields),
+ CaseSensitive: req.Body.CaseSensitive,
+ Enabled: true,
+ Note: strings.TrimSpace(req.Body.Note),
+ }
+ if err := h.repo.Create(filter); err != nil {
+ return c.AbortInternalServerError("failed to create filter")
+ }
+ return created(c, filter)
+}
+
+func (h *MessageFilterHandler) List(c *okapi.Context, req *ListRequest) error {
+ page, size, offset := normalizePageParams(req.Page, req.Size)
+ items, total, err := h.repo.FindByScope(getScope(c), size, offset)
+ if err != nil {
+ return c.AbortInternalServerError("failed to list filters")
+ }
+ return paginated(c, items, total, page, size)
+}
+
+func (h *MessageFilterHandler) Update(c *okapi.Context, req *UpdateMessageFilterRequest) error {
+ if err := requireEdit(c); err != nil {
+ return c.AbortForbidden("insufficient workspace permissions", err)
+ }
+ filter, err := h.repo.FindByIDForScope(getScope(c), uint(req.ID))
+ if err != nil {
+ return c.AbortNotFound("filter not found")
+ }
+
+ if p := strings.TrimSpace(req.Body.Pattern); p != "" {
+ if err := messagescan.ValidatePattern(filter.Kind, p); err != nil {
+ return c.AbortBadRequest(err.Error())
+ }
+ filter.Pattern = p
+ }
+ if a := strings.TrimSpace(req.Body.Action); a != "" {
+ action := models.FilterAction(strings.ToLower(a))
+ if !models.ValidFilterActions[action] {
+ return c.AbortBadRequest("invalid filter action")
+ }
+ filter.Action = action
+ }
+ if req.Body.Score != nil {
+ filter.Score = *req.Body.Score
+ }
+ if req.Body.Fields != nil {
+ filter.Fields = normalizeFilterFields(*req.Body.Fields)
+ }
+ if req.Body.CaseSensitive != nil {
+ filter.CaseSensitive = *req.Body.CaseSensitive
+ }
+ if req.Body.Enabled != nil {
+ filter.Enabled = *req.Body.Enabled
+ }
+ if req.Body.Note != nil {
+ filter.Note = strings.TrimSpace(*req.Body.Note)
+ }
+
+ now := time.Now()
+ filter.UpdatedAt = &now
+ if err := h.repo.Update(filter); err != nil {
+ return c.AbortInternalServerError("failed to update filter")
+ }
+ return ok(c, filter)
+}
+
+func (h *MessageFilterHandler) Delete(c *okapi.Context, req *MessageFilterIDRequest) error {
+ if err := requireEdit(c); err != nil {
+ return c.AbortForbidden("insufficient workspace permissions", err)
+ }
+ filter, err := h.repo.FindByIDForScope(getScope(c), uint(req.ID))
+ if err != nil {
+ return c.AbortNotFound("filter not found")
+ }
+ if err := h.repo.Delete(filter.ID); err != nil {
+ return c.AbortInternalServerError("failed to delete filter")
+ }
+ return noContent(c)
+}
+
+func (h *MessageFilterHandler) Test(c *okapi.Context, req *TestMessageFilterRequest) error {
+ scope := getScope(c)
+ if scope.WorkspaceID == nil {
+ return c.AbortBadRequest("a workspace is required")
+ }
+
+ kind := models.FilterKind(strings.ToLower(strings.TrimSpace(req.Body.Kind)))
+ if !models.ValidFilterKinds[kind] {
+ return c.AbortBadRequest("invalid filter kind")
+ }
+ pattern := strings.TrimSpace(req.Body.Pattern)
+ if err := messagescan.ValidatePattern(kind, pattern); err != nil {
+ return c.AbortBadRequest(err.Error())
+ }
+
+ limit := req.Body.Limit
+ if limit <= 0 || limit > 500 {
+ limit = 200
+ }
+
+ candidates, _, err := h.messageRepo.FindByScopeFiltered(scope, repositories.MessageFilterQuery{}, limit, 0)
+ if err != nil {
+ return c.AbortInternalServerError("failed to load messages")
+ }
+
+ probe := &models.MessageFilter{
+ Kind: kind,
+ Pattern: pattern,
+ Action: models.FilterActionScore,
+ CaseSensitive: req.Body.CaseSensitive,
+ }
+
+ resp := TestMessageFilterResponse{Scanned: len(candidates), Samples: []FilterMatch{}}
+ for i := range candidates {
+ m := &candidates[i]
+ hydrate(m)
+ if !h.scanner.MatchesFilter(probe, messagescan.Input{
+ SenderEmail: m.SenderEmail,
+ SenderName: m.SenderName,
+ Subject: m.Subject,
+ Body: m.Body,
+ Fields: m.Fields,
+ ClientIP: m.ClientIP,
+ }) {
+ continue
+ }
+ resp.Matched++
+ if len(resp.Samples) < 10 {
+ resp.Samples = append(resp.Samples, FilterMatch{
+ MessageUUID: m.UUID,
+ SenderEmail: m.SenderEmail,
+ Subject: m.Subject,
+ Excerpt: truncateBody(m.Body, 160),
+ })
+ }
+ }
+ return ok(c, resp)
+}
+
+func normalizeFilterFields(in []string) []string {
+ out := make([]string, 0, len(in))
+ for _, v := range in {
+ v = strings.TrimSpace(v)
+ if v != "" {
+ out = append(out, v)
+ }
+ }
+ return out
+}
diff --git a/internal/handlers/message_handler.go b/internal/handlers/message_handler.go
new file mode 100644
index 0000000..994c624
--- /dev/null
+++ b/internal/handlers/message_handler.go
@@ -0,0 +1,527 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package handlers
+
+import (
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "strings"
+ "time"
+
+ "github.com/goposta/posta/internal/models"
+ "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/storage/blob"
+ "github.com/goposta/posta/internal/storage/repositories"
+ "github.com/jkaninda/logger"
+ "github.com/jkaninda/okapi"
+)
+
+const (
+ metaMessageID = "message_id"
+ metaFormID = "form_id"
+ metaEmailUUID = "email_uuid"
+)
+
+type MessageHandler struct {
+ repo *repositories.MessageRepository
+ formRepo *repositories.FormRepository
+ filterRepo *repositories.MessageFilterRepository
+ svc *messages.Service
+ blobStore blob.Store
+ bus *eventbus.EventBus
+ audit *audit.Logger
+}
+
+func NewMessageHandler(
+ repo *repositories.MessageRepository,
+ formRepo *repositories.FormRepository,
+ filterRepo *repositories.MessageFilterRepository,
+ svc *messages.Service,
+ auditLogger *audit.Logger,
+) *MessageHandler {
+ return &MessageHandler{repo: repo, formRepo: formRepo, filterRepo: filterRepo, svc: svc, audit: auditLogger}
+}
+
+func (h *MessageHandler) SetBlobStore(bs blob.Store) { h.blobStore = bs }
+func (h *MessageHandler) SetEventBus(b *eventbus.EventBus) { h.bus = b }
+
+type MessageListRequest struct {
+ Page int `query:"page" default:"0"`
+ Size int `query:"size" default:"20"`
+ FormID int `query:"form_id"`
+ Status string `query:"status" enum:"received,flagged,quarantined,rejected"`
+ State string `query:"state" enum:"new,open,replied,closed,spam"`
+ Unread bool `query:"unread"`
+ Q string `query:"q"`
+ After string `query:"after" doc:"RFC 3339 lower bound on received time"`
+ Before string `query:"before" doc:"RFC 3339 upper bound on received time"`
+ Assigned int `query:"assigned_to"`
+}
+
+type MessageIDRequest struct {
+ ID string `param:"id"`
+}
+
+type MessageAttachmentRequest struct {
+ ID string `param:"id"`
+ Idx int `param:"idx"`
+}
+
+type ReplyMessageRequest struct {
+ ID string `param:"id"`
+ Body struct {
+ Subject string `json:"subject"`
+ HTML string `json:"html"`
+ Text string `json:"text"`
+ } `json:"body"`
+}
+
+type UpdateMessageStateRequest struct {
+ ID string `param:"id"`
+ Body struct {
+ State string `json:"state" required:"true" enum:"new,open,replied,closed,spam"`
+ Read *bool `json:"read"`
+ } `json:"body"`
+}
+
+type AssignMessageRequest struct {
+ ID string `param:"id"`
+ Body struct {
+ UserID *uint `json:"user_id"`
+ } `json:"body"`
+}
+
+type MarkSpamRequest struct {
+ ID string `param:"id"`
+ Body struct {
+ CreateFilter bool `json:"create_filter"`
+ Pattern string `json:"pattern"`
+ Kind string `json:"kind" enum:"keyword,phrase,email,domain,ip"`
+ } `json:"body"`
+}
+
+type MessageStatsResponse struct {
+ Total int64 `json:"total"`
+ Unread int64 `json:"unread"`
+ Spam int64 `json:"spam"`
+ Forms int64 `json:"forms"`
+}
+
+type MessageAnalyticsRequest struct {
+ Days int `query:"days" default:"30"`
+}
+
+type MessageAnalyticsResponse struct {
+ Daily []repositories.MessageDailyCount `json:"daily"`
+ Total int64 `json:"total"`
+ Spam int64 `json:"spam"`
+}
+
+func (h *MessageHandler) List(c *okapi.Context, req *MessageListRequest) error {
+ page, size, offset := normalizePageParams(req.Page, req.Size)
+
+ filter := repositories.MessageFilterQuery{
+ FormID: uint(req.FormID),
+ Status: req.Status,
+ State: req.State,
+ Unread: req.Unread,
+ Query: strings.TrimSpace(req.Q),
+ }
+ if req.Assigned > 0 {
+ assigned := uint(req.Assigned)
+ filter.Assigned = &assigned
+ }
+ if t, err := time.Parse(time.RFC3339, req.After); err == nil {
+ filter.From = &t
+ }
+ if t, err := time.Parse(time.RFC3339, req.Before); err == nil {
+ filter.To = &t
+ }
+
+ items, total, err := h.repo.FindByScopeFiltered(getScope(c), filter, size, offset)
+ if err != nil {
+ return c.AbortInternalServerError("failed to list messages")
+ }
+ for i := range items {
+ hydrate(&items[i])
+ items[i].Body = truncateBody(items[i].Body, 400)
+ }
+ return paginated(c, items, total, page, size)
+}
+
+func (h *MessageHandler) Get(c *okapi.Context, req *MessageIDRequest) error {
+ msg, err := h.repo.FindByUUIDForScope(getScope(c), req.ID)
+ if err != nil {
+ return c.AbortNotFound("message not found")
+ }
+ hydrate(msg)
+
+ if msg.ReadAt == nil {
+ now := time.Now()
+ 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")
+ }
+ }
+ return ok(c, msg)
+}
+
+func (h *MessageHandler) Delete(c *okapi.Context, req *MessageIDRequest) error {
+ if err := requireEdit(c); err != nil {
+ return c.AbortForbidden("insufficient workspace permissions", err)
+ }
+ msg, err := h.repo.FindByUUIDForScope(getScope(c), req.ID)
+ if err != nil {
+ return c.AbortNotFound("message not found")
+ }
+ if err := h.repo.Delete(msg.ID); err != nil {
+ return c.AbortInternalServerError("failed to delete message")
+ }
+ if h.audit != nil {
+ h.audit.LogCtx(c, "message.deleted", fmt.Sprintf("Message %s deleted", msg.UUID), map[string]any{metaMessageID: msg.UUID})
+ }
+ return noContent(c)
+}
+
+func (h *MessageHandler) Reply(c *okapi.Context, req *ReplyMessageRequest) error {
+ if err := requireEdit(c); err != nil {
+ return c.AbortForbidden("insufficient workspace permissions", err)
+ }
+ if strings.TrimSpace(req.Body.HTML) == "" && strings.TrimSpace(req.Body.Text) == "" {
+ return c.AbortBadRequest("a reply must include html or text content")
+ }
+
+ scope := getScope(c)
+ msg, err := h.repo.FindByUUIDForScope(scope, req.ID)
+ if err != nil {
+ return c.AbortNotFound("message not found")
+ }
+ form, err := h.formRepo.FindByIDForScope(scope, msg.FormID)
+ if err != nil {
+ return c.AbortNotFound("form not found")
+ }
+
+ reply, err := h.svc.Reply(
+ c.Request().Context(),
+ uint(c.GetInt("user_id")),
+ uint(c.GetInt("api_key_id")),
+ c.GetString("user_email"),
+ form, msg,
+ messages.ReplyRequest{
+ Subject: req.Body.Subject,
+ HTML: req.Body.HTML,
+ Text: req.Body.Text,
+ },
+ )
+ if err != nil {
+ switch {
+ case err == messages.ErrSenderNotSet:
+ return c.AbortBadRequest("configure a reply sender address on this form before replying")
+ case err == messages.ErrNoRecipient:
+ return c.AbortBadRequest("this message has no reply address")
+ case isRateLimitError(err):
+ return c.AbortTooManyRequests(err.Error())
+ case isDomainVerificationError(err):
+ return c.AbortForbidden("sender domain is not verified", err)
+ }
+ return c.AbortInternalServerError(err.Error())
+ }
+
+ if h.audit != nil {
+ h.audit.LogCtx(c, "message.replied", fmt.Sprintf("Replied to message %s", msg.UUID), map[string]any{
+ metaMessageID: msg.UUID, metaEmailUUID: reply.EmailUUID,
+ })
+ }
+ h.publish(c, "message.replied", msg)
+ return created(c, reply)
+}
+
+func (h *MessageHandler) UpdateState(c *okapi.Context, req *UpdateMessageStateRequest) error {
+ if err := requireEdit(c); err != nil {
+ return c.AbortForbidden("insufficient workspace permissions", err)
+ }
+ msg, err := h.repo.FindByUUIDForScope(getScope(c), req.ID)
+ if err != nil {
+ return c.AbortNotFound("message not found")
+ }
+
+ state := models.MessageState(req.Body.State)
+ switch state {
+ case models.MessageStateNew, models.MessageStateOpen, models.MessageStateReplied,
+ models.MessageStateClosed, models.MessageStateSpam:
+ default:
+ return c.AbortBadRequest("invalid state")
+ }
+
+ now := time.Now()
+ msg.State = state
+ msg.UpdatedAt = &now
+ if req.Body.Read != nil {
+ if *req.Body.Read {
+ msg.ReadAt = &now
+ } else {
+ msg.ReadAt = nil
+ }
+ }
+ if err := h.repo.Update(msg); err != nil {
+ return c.AbortInternalServerError("failed to update message")
+ }
+ hydrate(msg)
+ return ok(c, msg)
+}
+
+func (h *MessageHandler) Assign(c *okapi.Context, req *AssignMessageRequest) error {
+ if err := requireEdit(c); err != nil {
+ return c.AbortForbidden("insufficient workspace permissions", err)
+ }
+ msg, err := h.repo.FindByUUIDForScope(getScope(c), req.ID)
+ if err != nil {
+ return c.AbortNotFound("message not found")
+ }
+ now := time.Now()
+ msg.AssignedToID = req.Body.UserID
+ msg.UpdatedAt = &now
+ if err := h.repo.Update(msg); err != nil {
+ return c.AbortInternalServerError("failed to assign message")
+ }
+ hydrate(msg)
+ return ok(c, msg)
+}
+
+func (h *MessageHandler) MarkSpam(c *okapi.Context, req *MarkSpamRequest) error {
+ if err := requireEdit(c); err != nil {
+ return c.AbortForbidden("insufficient workspace permissions", err)
+ }
+ scope := getScope(c)
+ msg, err := h.repo.FindByUUIDForScope(scope, req.ID)
+ if err != nil {
+ return c.AbortNotFound("message not found")
+ }
+
+ now := time.Now()
+ msg.Status = models.MessageStatusQuarantined
+ msg.State = models.MessageStateSpam
+ msg.UpdatedAt = &now
+ if err := h.repo.Update(msg); err != nil {
+ return c.AbortInternalServerError("failed to update message")
+ }
+
+ if req.Body.CreateFilter {
+ kind := models.FilterKind(req.Body.Kind)
+ if !models.ValidFilterKinds[kind] {
+ kind = models.FilterKindKeyword
+ }
+ pattern := strings.TrimSpace(req.Body.Pattern)
+ if pattern == "" && kind == models.FilterKindDomain {
+ pattern = senderDomain(msg.SenderEmail)
+ }
+ if pattern == "" && kind == models.FilterKindEmail {
+ pattern = msg.SenderEmail
+ }
+ if pattern != "" {
+ filter := &models.MessageFilter{
+ WorkspaceID: scope.WorkspaceID,
+ Kind: kind,
+ Pattern: pattern,
+ Action: models.FilterActionQuarantine,
+ Score: 6,
+ Enabled: true,
+ Note: fmt.Sprintf("created from message %s", msg.UUID),
+ }
+ if err := h.filterRepo.Create(filter); err != nil {
+ return c.AbortInternalServerError("message marked as spam but the filter could not be created")
+ }
+ }
+ }
+
+ hydrate(msg)
+ return ok(c, msg)
+}
+
+func (h *MessageHandler) MarkNotSpam(c *okapi.Context, req *MessageIDRequest) error {
+ if err := requireEdit(c); err != nil {
+ return c.AbortForbidden("insufficient workspace permissions", err)
+ }
+ msg, err := h.repo.FindByUUIDForScope(getScope(c), req.ID)
+ if err != nil {
+ return c.AbortNotFound("message not found")
+ }
+ now := time.Now()
+ msg.Status = models.MessageStatusReceived
+ msg.SpamScore = 0
+ msg.ScanReasons = nil
+ msg.UpdatedAt = &now
+ if msg.State == models.MessageStateSpam {
+ msg.State = models.MessageStateOpen
+ }
+ if err := h.repo.Update(msg); err != nil {
+ return c.AbortInternalServerError("failed to update message")
+ }
+ hydrate(msg)
+ return ok(c, msg)
+}
+
+func (h *MessageHandler) Stats(c *okapi.Context) error {
+ scope := getScope(c)
+ total, unread, spam := h.repo.CountByScope(scope)
+ forms, _ := h.formRepo.CountByScope(scope)
+ return ok(c, MessageStatsResponse{Total: total, Unread: unread, Spam: spam, Forms: forms})
+}
+
+func (h *MessageHandler) Analytics(c *okapi.Context, req *MessageAnalyticsRequest) error {
+ days := req.Days
+ if days <= 0 || days > 365 {
+ days = 30
+ }
+ scope := getScope(c)
+ rows, err := h.repo.DailyCounts(scope, time.Now().AddDate(0, 0, -days))
+ if err != nil {
+ return c.AbortInternalServerError("failed to load message analytics")
+ }
+ var total, spam int64
+ for _, r := range rows {
+ total += r.Total
+ spam += r.Spam
+ }
+ return ok(c, MessageAnalyticsResponse{Daily: rows, Total: total, Spam: spam})
+}
+
+func (h *MessageHandler) DownloadAttachment(c *okapi.Context, req *MessageAttachmentRequest) error {
+ msg, err := h.repo.FindByUUIDForScope(getScope(c), req.ID)
+ if err != nil {
+ return c.AbortNotFound("message not found")
+ }
+ hydrate(msg)
+ if req.Idx < 0 || req.Idx >= len(msg.Attachments) {
+ return c.AbortNotFound("attachment not found")
+ }
+ att := msg.Attachments[req.Idx]
+ if h.blobStore == nil || att.StorageKey == "" {
+ return c.AbortNotFound("attachment content is unavailable")
+ }
+ rc, err := h.blobStore.Get(c.Request().Context(), att.StorageKey)
+ if err != nil {
+ return c.AbortNotFound("attachment content is unavailable")
+ }
+ defer func() { _ = rc.Close() }()
+
+ contentType := att.ContentType
+ if contentType == "" {
+ contentType = "application/octet-stream"
+ }
+ c.ResponseWriter().Header().Set("Content-Type", contentType)
+ c.ResponseWriter().Header().Set("Content-Disposition", contentDisposition(att.Filename))
+ c.ResponseWriter().Header().Set("X-Content-Type-Options", "nosniff")
+ c.ResponseWriter().WriteHeader(http.StatusOK)
+ if _, err := io.Copy(c.ResponseWriter(), rc); err != nil {
+ logger.Warn("message attachment stream failed", "uuid", msg.UUID, "error", err)
+ }
+ return nil
+}
+
+func (h *MessageHandler) Stream(c *okapi.Context) error {
+ if h.bus == nil {
+ return c.AbortNotFound("message stream not configured")
+ }
+ ctx := c.Request().Context()
+ scope := getScope(c)
+ if scope.WorkspaceID == nil {
+ return c.AbortBadRequest("a workspace is required")
+ }
+ workspaceID := *scope.WorkspaceID
+
+ ch, unsub := h.bus.Subscribe()
+ defer unsub()
+
+ msgCh := make(chan okapi.Message, 4)
+ msgCh <- okapi.Message{
+ Event: "system.info",
+ Data: okapi.M{
+ "workspace_id": workspaceID,
+ "timestamp": time.Now().UTC().Format(time.RFC3339),
+ },
+ }
+
+ go func() {
+ defer close(msgCh)
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case evt, okEvt := <-ch:
+ if !okEvt {
+ return
+ }
+ if !strings.HasPrefix(evt.Type, "message.") {
+ continue
+ }
+ if evt.WorkspaceID == nil || *evt.WorkspaceID != workspaceID {
+ continue
+ }
+ select {
+ case msgCh <- okapi.Message{Event: evt.Type, Data: evt}:
+ case <-ctx.Done():
+ return
+ }
+ }
+ }
+ }()
+
+ return c.SSEStreamWithOptions(ctx, msgCh, &okapi.StreamOptions{
+ Serializer: &okapi.JSONSerializer{},
+ PingInterval: 30 * time.Second,
+ })
+}
+
+func (h *MessageHandler) publish(c *okapi.Context, eventType string, msg *models.Message) {
+ if h.bus == nil {
+ return
+ }
+ actor := uint(c.GetInt("user_id"))
+ h.bus.PublishScoped(msg.WorkspaceID, models.EventCategoryEmail, eventType, &actor,
+ c.GetString("user_email"), c.RealIP(),
+ fmt.Sprintf("Message %s %s", msg.UUID, strings.TrimPrefix(eventType, "message.")),
+ map[string]any{metaMessageID: msg.UUID, metaFormID: msg.FormID})
+}
+
+func hydrate(msg *models.Message) {
+ if msg.FieldsJSON != "" {
+ var fields []models.MessageField
+ if err := json.Unmarshal([]byte(msg.FieldsJSON), &fields); err == nil {
+ msg.Fields = fields
+ }
+ }
+ if msg.AttachmentsJSON != "" {
+ var atts []models.InboundAttachmentMeta
+ if err := json.Unmarshal([]byte(msg.AttachmentsJSON), &atts); err == nil {
+ for i := range atts {
+ atts[i].Content = ""
+ }
+ msg.Attachments = atts
+ }
+ }
+}
+
+func truncateBody(body string, n int) string {
+ runes := []rune(body)
+ if len(runes) <= n {
+ return body
+ }
+ return string(runes[:n]) + "…"
+}
+
+func senderDomain(email string) string {
+ at := strings.LastIndex(email, "@")
+ if at < 0 || at == len(email)-1 {
+ return ""
+ }
+ return strings.ToLower(email[at+1:])
+}
diff --git a/internal/handlers/user_setting_handler.go b/internal/handlers/user_setting_handler.go
index 28c5670..631df19 100644
--- a/internal/handlers/user_setting_handler.go
+++ b/internal/handlers/user_setting_handler.go
@@ -34,6 +34,7 @@ type UpdateUserSettingsRequest struct {
NotifyBounceAlerts *bool `json:"notify_bounce_alerts"`
NotifyAPIKeyExpiry *bool `json:"notify_api_key_expiry"`
NotifyWorkspaceActivity *bool `json:"notify_workspace_activity"`
+ NotifyNewMessage *bool `json:"notify_new_message"`
} `json:"body"`
}
@@ -94,6 +95,9 @@ func (h *UserSettingHandler) UpdateSettings(c *okapi.Context, req *UpdateUserSet
if req.Body.NotifyAPIKeyExpiry != nil {
settings.NotifyAPIKeyExpiry = *req.Body.NotifyAPIKeyExpiry
}
+ if req.Body.NotifyNewMessage != nil {
+ settings.NotifyNewMessage = *req.Body.NotifyNewMessage
+ }
if req.Body.NotifyWorkspaceActivity != nil {
settings.NotifyWorkspaceActivity = *req.Body.NotifyWorkspaceActivity
}
diff --git a/internal/handlers/webhook_handler.go b/internal/handlers/webhook_handler.go
index ec1aa6e..b71d7c5 100644
--- a/internal/handlers/webhook_handler.go
+++ b/internal/handlers/webhook_handler.go
@@ -20,7 +20,7 @@ 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,campaign.started,campaign.completed"`
+ 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"`
Filters []string `json:"filters"`
} `json:"body"`
}
diff --git a/internal/metrics/metrics.go b/internal/metrics/metrics.go
index 2bcef09..cf2315c 100644
--- a/internal/metrics/metrics.go
+++ b/internal/metrics/metrics.go
@@ -98,6 +98,21 @@ var (
[]string{"source"},
)
+ messagesReceivedTotal = prometheus.NewCounterVec(
+ prometheus.CounterOpts{
+ Name: "posta_form_messages_received_total",
+ Help: "Total number of web form messages stored, by scan status",
+ },
+ []string{"status"},
+ )
+
+ messageNotificationsTotal = prometheus.NewCounter(
+ prometheus.CounterOpts{
+ Name: "posta_form_message_notifications_total",
+ Help: "Total number of web form message notifications delivered",
+ },
+ )
+
inboundForwardedTotal = prometheus.NewCounter(
prometheus.CounterOpts{
Name: "posta_inbound_messages_forwarded_total",
@@ -160,6 +175,8 @@ func init() {
prometheus.MustRegister(inboundRejectedTotal)
prometheus.MustRegister(inboundBytesTotal)
prometheus.MustRegister(inboundIngestDuration)
+ prometheus.MustRegister(messagesReceivedTotal)
+ prometheus.MustRegister(messageNotificationsTotal)
prometheus.MustRegister(activeWorkers)
}
@@ -209,6 +226,16 @@ func IncrementSuppression() {
suppressionsTotal.Inc()
}
+// IncrementMessageReceived increments the web form message counter for the given scan status.
+func IncrementMessageReceived(status string) {
+ messagesReceivedTotal.WithLabelValues(status).Inc()
+}
+
+// IncrementMessageNotification increments the web form notification counter.
+func IncrementMessageNotification() {
+ messageNotificationsTotal.Inc()
+}
+
// IncrementInboundReceived increments the inbound received counter for the given source.
func IncrementInboundReceived(source string) {
inboundReceivedTotal.WithLabelValues(source).Inc()
diff --git a/internal/middlewares/message_scope_test.go b/internal/middlewares/message_scope_test.go
new file mode 100644
index 0000000..beb901a
--- /dev/null
+++ b/internal/middlewares/message_scope_test.go
@@ -0,0 +1,55 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package middlewares
+
+import (
+ "net/http"
+ "testing"
+
+ "github.com/goposta/posta/internal/models"
+)
+
+func TestWorkspaceScopeForMessageRoutes(t *testing.T) {
+ cases := []struct {
+ method string
+ path string
+ want string
+ }{
+ {http.MethodGet, "/api/v1/workspaces/current/messages", models.ScopeRead},
+ {http.MethodGet, "/api/v1/workspaces/current/messages/abc", models.ScopeRead},
+ {http.MethodPost, "/api/v1/workspaces/current/messages/abc/reply", models.ScopeWrite},
+ {http.MethodDelete, "/api/v1/workspaces/current/messages/abc", models.ScopeWrite},
+
+ {http.MethodGet, "/api/v1/workspaces/current/forms", models.ScopeAdmin},
+ {http.MethodPost, "/api/v1/workspaces/current/forms", models.ScopeAdmin},
+ {http.MethodPut, "/api/v1/workspaces/current/forms/1", models.ScopeAdmin},
+ {http.MethodPost, "/api/v1/workspaces/current/forms/1/rotate-key", models.ScopeAdmin},
+
+ {http.MethodGet, "/api/v1/workspaces/current/message-filters", models.ScopeAdmin},
+ {http.MethodPost, "/api/v1/workspaces/current/message-filters", models.ScopeAdmin},
+ }
+
+ for _, tc := range cases {
+ if got := workspaceScopeFor(tc.method, tc.path); got != tc.want {
+ t.Fatalf("workspaceScopeFor(%s %s) = %s, want %s", tc.method, tc.path, got, tc.want)
+ }
+ }
+}
+
+func TestSendScopeCannotReachMessages(t *testing.T) {
+ key := &models.APIKey{Scopes: []string{models.ScopeSend}}
+ for _, scope := range []string{models.ScopeRead, models.ScopeWrite, models.ScopeAdmin} {
+ if key.HasScope(scope) {
+ t.Fatalf("a send-only key must not carry %s", scope)
+ }
+ }
+}
+
+func TestReadScopeCannotReachFormConfig(t *testing.T) {
+ key := &models.APIKey{Scopes: []string{models.ScopeRead}}
+ required := workspaceScopeFor(http.MethodGet, "/api/v1/workspaces/current/forms")
+ if key.HasScope(required) {
+ t.Fatal("a read-only key must not be able to enumerate form configuration")
+ }
+}
diff --git a/internal/middlewares/middleware.go b/internal/middlewares/middleware.go
index 4aded20..b98966b 100644
--- a/internal/middlewares/middleware.go
+++ b/internal/middlewares/middleware.go
@@ -283,6 +283,8 @@ var tenantAdminPaths = []string{
"/settings",
"/sso",
"/plan",
+ "/forms",
+ "/message-filters",
}
// workspaceScopeFor returns the scope a workspace-scoped request demands.
diff --git a/internal/models/form.go b/internal/models/form.go
new file mode 100644
index 0000000..b29593e
--- /dev/null
+++ b/internal/models/form.go
@@ -0,0 +1,104 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package models
+
+import (
+ "time"
+
+ "github.com/lib/pq"
+ "gorm.io/gorm"
+)
+
+type FormStatus string
+
+const (
+ FormStatusActive FormStatus = "active"
+ FormStatusPaused FormStatus = "paused"
+ FormStatusArchived FormStatus = "archived"
+)
+
+type NotifyMode string
+
+const (
+ NotifyModeImmediate NotifyMode = "immediate"
+ NotifyModeHourly NotifyMode = "hourly"
+ NotifyModeDaily NotifyMode = "daily"
+ NotifyModeOff NotifyMode = "off"
+)
+
+const (
+ DefaultHoneypotField = "_gotcha"
+ DefaultMaxBodyBytes = 65536
+ DefaultMaxFields = 40
+)
+
+type Form struct {
+ ID uint `json:"id" gorm:"primaryKey"`
+ UUID string `json:"uuid" gorm:"type:uuid;default:gen_random_uuid();uniqueIndex;not null"`
+ WorkspaceID *uint `json:"workspace_id,omitempty" gorm:"index;not null"`
+ Name string `json:"name" gorm:"not null"`
+ Slug string `json:"slug" gorm:"not null"`
+ Description string `json:"description"`
+ PublicKey string `json:"public_key" gorm:"uniqueIndex;not null"`
+ Status FormStatus `json:"status" gorm:"type:varchar(20);default:'active';index;not null"`
+
+ AllowedOrigins pq.StringArray `json:"allowed_origins" gorm:"type:text[]"`
+ StrictOrigin bool `json:"strict_origin" gorm:"default:false;not null"`
+ RedirectURL string `json:"redirect_url"`
+ MaxBodyBytes int64 `json:"max_body_bytes" gorm:"default:65536;not null"`
+ MaxFields int `json:"max_fields" gorm:"default:40;not null"`
+ AllowAttachments bool `json:"allow_attachments" gorm:"default:false;not null"`
+
+ HoneypotField string `json:"honeypot_field" gorm:"default:'_gotcha';not null"`
+ RequireNonce bool `json:"require_nonce" gorm:"default:false;not null"`
+ MinFillSeconds int `json:"min_fill_seconds" gorm:"default:3;not null"`
+
+ ScanEnabled bool `json:"scan_enabled" gorm:"default:true;not null"`
+ FlagThreshold float64 `json:"flag_threshold" gorm:"default:3;not null"`
+ QuarantineThreshold float64 `json:"quarantine_threshold" gorm:"default:6;not null"`
+ RejectThreshold float64 `json:"reject_threshold" gorm:"default:10;not null"`
+
+ NotifyEnabled bool `json:"notify_enabled" gorm:"default:true;not null"`
+ NotifyEmails pq.StringArray `json:"notify_emails" gorm:"type:text[]"`
+ NotifyMode NotifyMode `json:"notify_mode" gorm:"type:varchar(16);default:'immediate';not null"`
+ NotifyOnFlagged bool `json:"notify_on_flagged" gorm:"default:true;not null"`
+
+ ReplyFrom string `json:"reply_from"`
+ ReplyFromName string `json:"reply_from_name"`
+
+ RetentionDays int `json:"retention_days" gorm:"default:0;not null"`
+ LastEditedByID *uint `json:"last_edited_by_id,omitempty" gorm:"index"`
+
+ MessageCount int64 `json:"message_count" gorm:"default:0;not null"`
+ SpamCount int64 `json:"spam_count" gorm:"default:0;not null"`
+ LastMessageAt *time.Time `json:"last_message_at,omitempty"`
+ CreatedAt time.Time `json:"created_at"`
+ UpdatedAt *time.Time `json:"updated_at,omitempty"`
+ DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
+
+ LastEditedBy *ActorRef `json:"last_edited_by,omitempty" gorm:"foreignKey:LastEditedByID;references:ID;constraint:false"`
+}
+
+func (f *Form) IsActive() bool { return f.Status == FormStatusActive }
+
+func (f *Form) Honeypot() string {
+ if f.HoneypotField == "" {
+ return DefaultHoneypotField
+ }
+ return f.HoneypotField
+}
+
+func (f *Form) BodyLimit() int64 {
+ if f.MaxBodyBytes <= 0 {
+ return DefaultMaxBodyBytes
+ }
+ return f.MaxBodyBytes
+}
+
+func (f *Form) FieldLimit() int {
+ if f.MaxFields <= 0 {
+ return DefaultMaxFields
+ }
+ return f.MaxFields
+}
diff --git a/internal/models/message.go b/internal/models/message.go
new file mode 100644
index 0000000..b908036
--- /dev/null
+++ b/internal/models/message.go
@@ -0,0 +1,119 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package models
+
+import (
+ "time"
+
+ "github.com/lib/pq"
+ "gorm.io/gorm"
+)
+
+type MessageStatus string
+
+const (
+ MessageStatusReceived MessageStatus = "received"
+ MessageStatusFlagged MessageStatus = "flagged"
+ MessageStatusQuarantined MessageStatus = "quarantined"
+ MessageStatusRejected MessageStatus = "rejected"
+)
+
+type MessageState string
+
+const (
+ MessageStateNew MessageState = "new"
+ MessageStateOpen MessageState = "open"
+ MessageStateReplied MessageState = "replied"
+ MessageStateClosed MessageState = "closed"
+ MessageStateSpam MessageState = "spam"
+)
+
+type MessageReplyKind string
+
+const (
+ MessageReplyKindOperator MessageReplyKind = "operator"
+ MessageReplyKindInbound MessageReplyKind = "inbound"
+)
+
+type MessageField struct {
+ Key string `json:"key"`
+ Value string `json:"value"`
+}
+
+type Message struct {
+ ID uint `json:"id" gorm:"primaryKey"`
+ UUID string `json:"uuid" gorm:"type:uuid;default:gen_random_uuid();uniqueIndex;not null"`
+ WorkspaceID *uint `json:"workspace_id,omitempty" gorm:"index;not null"`
+ FormID uint `json:"form_id" gorm:"index;not null"`
+
+ SenderEmail string `json:"sender_email" gorm:"index"`
+ SenderName string `json:"sender_name"`
+ SenderPhone string `json:"sender_phone"`
+ Subject string `json:"subject"`
+ Body string `json:"body" gorm:"type:text"`
+
+ FieldsJSON string `json:"-" gorm:"type:text"`
+ AttachmentsJSON string `json:"-" gorm:"type:text"`
+
+ ClientIP string `json:"client_ip,omitempty" gorm:"size:45"`
+ UserAgent string `json:"user_agent,omitempty"`
+ Referer string `json:"referer,omitempty"`
+ Origin string `json:"origin,omitempty"`
+
+ Status MessageStatus `json:"status" gorm:"type:varchar(20);default:'received';index;not null"`
+ State MessageState `json:"state" gorm:"type:varchar(20);default:'new';index;not null"`
+ SpamScore float64 `json:"spam_score" gorm:"default:0;not null"`
+ ScanReasons pq.StringArray `json:"scan_reasons" gorm:"type:text[]"`
+
+ ThreadToken string `json:"-" gorm:"uniqueIndex"`
+ RootMessageID string `json:"-"`
+ DedupHash string `json:"-" gorm:"index"`
+
+ NotifiedAt *time.Time `json:"notified_at,omitempty"`
+ AssignedToID *uint `json:"assigned_to_id,omitempty" gorm:"index"`
+ ReadAt *time.Time `json:"read_at,omitempty"`
+ RepliedAt *time.Time `json:"replied_at,omitempty"`
+ ReplyCount int `json:"reply_count" gorm:"default:0;not null"`
+
+ CreatedAt time.Time `json:"created_at" gorm:"index"`
+ UpdatedAt *time.Time `json:"updated_at,omitempty"`
+ DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
+
+ Fields []MessageField `json:"fields,omitempty" gorm:"-"`
+ Attachments []InboundAttachmentMeta `json:"attachments,omitempty" gorm:"-"`
+
+ Form *Form `json:"form,omitempty" gorm:"foreignKey:FormID;constraint:false"`
+ AssignedTo *ActorRef `json:"assigned_to,omitempty" gorm:"foreignKey:AssignedToID;references:ID;constraint:false"`
+ Replies []MessageReply `json:"replies,omitempty" gorm:"foreignKey:MessageID"`
+}
+
+func (m *Message) IsSpam() bool {
+ return m.Status == MessageStatusQuarantined || m.Status == MessageStatusRejected
+}
+
+func (m *Message) CanReply() bool {
+ return m.SenderEmail != "" && m.Status != MessageStatusRejected
+}
+
+type MessageReply struct {
+ ID uint `json:"id" gorm:"primaryKey"`
+ UUID string `json:"uuid" gorm:"type:uuid;default:gen_random_uuid();uniqueIndex;not null"`
+ MessageID uint `json:"message_id" gorm:"index;not null"`
+ 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"`
+ FromAddr string `json:"from_addr"`
+ ToAddr string `json:"to_addr"`
+ Subject string `json:"subject"`
+ HTMLBody string `json:"html_body" gorm:"type:text"`
+ TextBody string `json:"text_body" gorm:"type:text"`
+
+ EmailUUID string `json:"email_uuid,omitempty" gorm:"index"`
+ InboundEmailID *uint `json:"inbound_email_id,omitempty" gorm:"index"`
+
+ CreatedAt time.Time `json:"created_at"`
+
+ Author *ActorRef `json:"author,omitempty" gorm:"foreignKey:AuthorID;references:ID;constraint:false"`
+}
diff --git a/internal/models/message_filter.go b/internal/models/message_filter.go
new file mode 100644
index 0000000..e7ca58f
--- /dev/null
+++ b/internal/models/message_filter.go
@@ -0,0 +1,71 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package models
+
+import (
+ "time"
+
+ "github.com/lib/pq"
+)
+
+type FilterKind string
+
+const (
+ FilterKindKeyword FilterKind = "keyword"
+ FilterKindPhrase FilterKind = "phrase"
+ FilterKindRegex FilterKind = "regex"
+ FilterKindEmail FilterKind = "email"
+ FilterKindDomain FilterKind = "domain"
+ FilterKindIP FilterKind = "ip"
+)
+
+var ValidFilterKinds = map[FilterKind]bool{
+ FilterKindKeyword: true,
+ FilterKindPhrase: true,
+ FilterKindRegex: true,
+ FilterKindEmail: true,
+ FilterKindDomain: true,
+ FilterKindIP: true,
+}
+
+type FilterAction string
+
+const (
+ FilterActionScore FilterAction = "score"
+ FilterActionFlag FilterAction = "flag"
+ FilterActionQuarantine FilterAction = "quarantine"
+ FilterActionReject FilterAction = "reject"
+ FilterActionAllowlist FilterAction = "allowlist"
+)
+
+var ValidFilterActions = map[FilterAction]bool{
+ FilterActionScore: true,
+ FilterActionFlag: true,
+ FilterActionQuarantine: true,
+ FilterActionReject: true,
+ FilterActionAllowlist: true,
+}
+
+const MaxFilterPatternLength = 512
+
+type MessageFilter struct {
+ ID uint `json:"id" gorm:"primaryKey"`
+ WorkspaceID *uint `json:"workspace_id,omitempty" gorm:"index;not null"`
+ FormID *uint `json:"form_id,omitempty" gorm:"index"`
+
+ Kind FilterKind `json:"kind" gorm:"type:varchar(16);not null"`
+ Pattern string `json:"pattern" gorm:"not null"`
+ Action FilterAction `json:"action" gorm:"type:varchar(16);default:'score';not null"`
+ Score float64 `json:"score" gorm:"default:3;not null"`
+ Fields pq.StringArray `json:"fields" gorm:"type:text[]"`
+ CaseSensitive bool `json:"case_sensitive" gorm:"default:false;not null"`
+ Enabled bool `json:"enabled" gorm:"default:true;index;not null"`
+
+ HitCount int64 `json:"hit_count" gorm:"default:0;not null"`
+ LastHitAt *time.Time `json:"last_hit_at,omitempty"`
+ Note string `json:"note"`
+
+ CreatedAt time.Time `json:"created_at"`
+ UpdatedAt *time.Time `json:"updated_at,omitempty"`
+}
diff --git a/internal/models/user_setting.go b/internal/models/user_setting.go
index 5dc59d5..fd865ba 100644
--- a/internal/models/user_setting.go
+++ b/internal/models/user_setting.go
@@ -24,6 +24,7 @@ type UserSetting struct {
NotifyBounceAlerts bool `json:"notify_bounce_alerts" gorm:"default:true"`
NotifyAPIKeyExpiry bool `json:"notify_api_key_expiry" gorm:"default:true"`
NotifyWorkspaceActivity bool `json:"notify_workspace_activity" gorm:"default:true"`
+ NotifyNewMessage bool `json:"notify_new_message" gorm:"default:true"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
diff --git a/internal/routes/message_routes.go b/internal/routes/message_routes.go
new file mode 100644
index 0000000..a226fcc
--- /dev/null
+++ b/internal/routes/message_routes.go
@@ -0,0 +1,330 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package routes
+
+import (
+ "net/http"
+
+ "github.com/goposta/posta/internal/dto"
+ "github.com/goposta/posta/internal/handlers"
+ "github.com/goposta/posta/internal/models"
+ "github.com/goposta/posta/internal/services/messages"
+ "github.com/jkaninda/okapi"
+)
+
+func (r *Router) formIngestRoutes() []okapi.RouteDefinition {
+ ingestGroup := r.app.Group("/api/v1/f").WithTagInfo(okapi.GroupTag{
+ Name: "Forms",
+ Description: "Public form ingest. A website form posts here with the form's public key; no authentication is used, and access is governed by the form's origin allowlist, honeypot, nonce, and rate limits.",
+ })
+
+ return []okapi.RouteDefinition{
+ {
+ Method: http.MethodPost,
+ Path: "/{key}",
+ Handler: r.h.formIngest.Submit,
+ Group: ingestGroup,
+ Summary: "Submit a web form",
+ Description: "Accepts application/json, text/plain holding JSON, application/x-www-form-urlencoded, and multipart/form-data. Always answers 202 for a stored or silently rejected submission so spam clients learn nothing.",
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("key", "string", "Form public key"),
+ okapi.DocErrorResponse(403, &dto.ErrorResponseBody{}),
+ okapi.DocErrorResponse(429, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/{key}/nonce",
+ Handler: r.h.formIngest.Nonce,
+ Group: ingestGroup,
+ Summary: "Issue a submission nonce",
+ Description: "Returns a short-lived signed nonce for forms that require one. Single-use and bound to a minimum fill time.",
+ Response: &dto.Response[messages.Nonce]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("key", "string", "Form public key"),
+ },
+ },
+ }
+}
+
+func (r *Router) messageWorkspaceRoutes() []okapi.RouteDefinition {
+ opsGroup := r.v1.Group("/workspaces/current", r.mw.auth, r.mw.workspace).WithTagInfo(okapi.GroupTag{
+ Name: "Messages",
+ Description: "Web form definitions, received messages, operator replies, and spam filters for the active workspace. Authenticated with a dashboard session or an API key bound to the workspace.",
+ })
+ opsGroup.WithBearerAuth()
+
+ streamGroup := r.v1.Group("/workspaces/current", r.mw.auth, r.mw.workspaceQuery).WithTagInfo(okapi.GroupTag{
+ Name: "Messages",
+ Description: "Web form definitions, received messages, operator replies, and spam filters for the active workspace.",
+ })
+ streamGroup.WithBearerAuth()
+
+ return []okapi.RouteDefinition{
+ {
+ Method: http.MethodPost,
+ Path: "/forms",
+ Handler: okapi.H(r.h.form.Create),
+ Group: opsGroup,
+ Summary: "Create a form",
+ Description: "Creates a web form endpoint and returns its public key.",
+ Request: &handlers.CreateFormRequest{},
+ Options: []okapi.RouteOption{
+ okapi.DocResponse(201, &dto.Response[models.Form]{}),
+ okapi.DocErrorResponse(409, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/forms",
+ Handler: okapi.H(r.h.form.List),
+ Group: opsGroup,
+ Summary: "List forms",
+ Request: &handlers.ListRequest{},
+ Response: &dto.PageableResponse[models.Form]{},
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/forms/{id:int}",
+ Handler: okapi.H(r.h.form.Get),
+ Group: opsGroup,
+ Summary: "Get a form",
+ Response: &dto.Response[models.Form]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Form ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPut,
+ Path: "/forms/{id:int}",
+ Handler: okapi.H(r.h.form.Update),
+ Group: opsGroup,
+ Summary: "Update a form",
+ Request: &handlers.UpdateFormRequest{},
+ Response: &dto.Response[models.Form]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Form ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodDelete,
+ Path: "/forms/{id:int}",
+ Handler: okapi.H(r.h.form.Delete),
+ Group: opsGroup,
+ Summary: "Delete a form",
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Form ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/forms/{id:int}/rotate-key",
+ Handler: okapi.H(r.h.form.RotateKey),
+ Group: opsGroup,
+ Summary: "Rotate a form public key",
+ Description: "Issues a new public key. Existing embeds stop working immediately.",
+ Response: &dto.Response[models.Form]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Form ID"),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/forms/{id:int}/snippet",
+ Handler: okapi.H(r.h.form.Snippet),
+ Group: opsGroup,
+ Summary: "Get embed code for a form",
+ Description: "Returns paste-ready HTML and fetch() snippets wired to this form's endpoint.",
+ Response: &dto.Response[handlers.FormSnippetResponse]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Form ID"),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/messages",
+ Handler: okapi.H(r.h.message.List),
+ Group: opsGroup,
+ Summary: "List messages",
+ Request: &handlers.MessageListRequest{},
+ Response: &dto.PageableResponse[models.Message]{},
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/messages/stats",
+ Handler: r.h.message.Stats,
+ Group: opsGroup,
+ Summary: "Message counters",
+ Description: "Total, unread, and spam counts plus the number of forms in the workspace.",
+ Response: &dto.Response[handlers.MessageStatsResponse]{},
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/messages/analytics",
+ Handler: okapi.H(r.h.message.Analytics),
+ Group: opsGroup,
+ Summary: "Message volume analytics",
+ Request: &handlers.MessageAnalyticsRequest{},
+ Response: &dto.Response[handlers.MessageAnalyticsResponse]{},
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/messages/{id}",
+ Handler: okapi.H(r.h.message.Get),
+ Group: opsGroup,
+ Summary: "Get a message",
+ Response: &dto.Response[models.Message]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "string", "Message UUID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodDelete,
+ Path: "/messages/{id}",
+ Handler: okapi.H(r.h.message.Delete),
+ Group: opsGroup,
+ Summary: "Delete a message",
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "string", "Message UUID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/messages/{id}/reply",
+ Handler: okapi.H(r.h.message.Reply),
+ Group: opsGroup,
+ Summary: "Reply to a message",
+ Description: "Sends an operator reply to the sender through the workspace's normal email pipeline and records it on the thread.",
+ Request: &handlers.ReplyMessageRequest{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "string", "Message UUID"),
+ okapi.DocResponse(201, &dto.Response[models.MessageReply]{}),
+ okapi.DocErrorResponse(400, &dto.ErrorResponseBody{}),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPut,
+ Path: "/messages/{id}/state",
+ Handler: okapi.H(r.h.message.UpdateState),
+ Group: opsGroup,
+ Summary: "Update message state",
+ Request: &handlers.UpdateMessageStateRequest{},
+ Response: &dto.Response[models.Message]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "string", "Message UUID"),
+ },
+ },
+ {
+ Method: http.MethodPut,
+ Path: "/messages/{id}/assign",
+ Handler: okapi.H(r.h.message.Assign),
+ Group: opsGroup,
+ Summary: "Assign a message",
+ Request: &handlers.AssignMessageRequest{},
+ Response: &dto.Response[models.Message]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "string", "Message UUID"),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/messages/{id}/spam",
+ Handler: okapi.H(r.h.message.MarkSpam),
+ Group: opsGroup,
+ Summary: "Mark a message as spam",
+ Description: "Quarantines the message and optionally creates a filter from it.",
+ Request: &handlers.MarkSpamRequest{},
+ Response: &dto.Response[models.Message]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "string", "Message UUID"),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/messages/{id}/not-spam",
+ Handler: okapi.H(r.h.message.MarkNotSpam),
+ Group: opsGroup,
+ Summary: "Clear the spam verdict on a message",
+ Response: &dto.Response[models.Message]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "string", "Message UUID"),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/messages/{id}/attachments/{idx:int}",
+ Handler: okapi.H(r.h.message.DownloadAttachment),
+ Group: opsGroup,
+ Summary: "Download a message attachment",
+ Request: &handlers.MessageAttachmentRequest{},
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/message-stream",
+ Handler: r.h.message.Stream,
+ Group: streamGroup,
+ Summary: "Server-sent events stream of message events",
+ Options: []okapi.RouteOption{okapi.DocHide()},
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/message-filters",
+ Handler: okapi.H(r.h.messageFilter.Create),
+ Group: opsGroup,
+ Summary: "Create a spam filter",
+ Request: &handlers.CreateMessageFilterRequest{},
+ Options: []okapi.RouteOption{
+ okapi.DocResponse(201, &dto.Response[models.MessageFilter]{}),
+ okapi.DocErrorResponse(400, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/message-filters",
+ Handler: okapi.H(r.h.messageFilter.List),
+ Group: opsGroup,
+ Summary: "List spam filters",
+ Request: &handlers.ListRequest{},
+ Response: &dto.PageableResponse[models.MessageFilter]{},
+ },
+ {
+ Method: http.MethodPut,
+ Path: "/message-filters/{id:int}",
+ Handler: okapi.H(r.h.messageFilter.Update),
+ Group: opsGroup,
+ Summary: "Update a spam filter",
+ Request: &handlers.UpdateMessageFilterRequest{},
+ Response: &dto.Response[models.MessageFilter]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Filter ID"),
+ },
+ },
+ {
+ Method: http.MethodDelete,
+ Path: "/message-filters/{id:int}",
+ Handler: okapi.H(r.h.messageFilter.Delete),
+ Group: opsGroup,
+ Summary: "Delete a spam filter",
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Filter ID"),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/message-filters/test",
+ Handler: okapi.H(r.h.messageFilter.Test),
+ Group: opsGroup,
+ Summary: "Dry-run a spam filter",
+ Description: "Runs a candidate pattern over recent messages and reports how many it would have matched.",
+ Request: &handlers.TestMessageFilterRequest{},
+ Response: &dto.Response[handlers.TestMessageFilterResponse]{},
+ },
+ }
+}
diff --git a/internal/routes/message_routes_test.go b/internal/routes/message_routes_test.go
new file mode 100644
index 0000000..77f1c9d
--- /dev/null
+++ b/internal/routes/message_routes_test.go
@@ -0,0 +1,79 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package routes
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/jkaninda/okapi"
+)
+
+func TestOkapiAutoRegistersOptionsPerPath(t *testing.T) {
+ app := okapi.New()
+ app.WithCORS(okapi.Cors{AllowedOrigins: []string{"https://dashboard.test"}})
+
+ group := app.Group("/api/v1/f")
+ app.Register(okapi.RouteDefinition{
+ Method: http.MethodPost,
+ Path: "/{key}",
+ Handler: func(c *okapi.Context) error { return c.JSON(http.StatusAccepted, okapi.M{"ok": true}) },
+ Group: group,
+ })
+
+ panicked := func() (p bool) {
+ defer func() {
+ if recover() != nil {
+ p = true
+ }
+ }()
+ app.Register(okapi.RouteDefinition{
+ Method: http.MethodOptions,
+ Path: "/{key}",
+ Handler: func(c *okapi.Context) error { return nil },
+ Group: group,
+ })
+ return false
+ }()
+
+ if !panicked {
+ t.Fatal("okapi no longer auto-registers OPTIONS per path; the ingest route may now own its own preflight handler")
+ }
+}
+
+func TestFormIngestPostIsNotAPreflightedRequest(t *testing.T) {
+ app := okapi.New()
+ app.WithCORS(okapi.Cors{AllowedOrigins: []string{"https://dashboard.test"}})
+
+ group := app.Group("/api/v1/f")
+ app.Register(okapi.RouteDefinition{
+ Method: http.MethodPost,
+ Path: "/{key}",
+ Handler: func(c *okapi.Context) error {
+ c.ResponseWriter().Header().Set("Access-Control-Allow-Origin", c.Request().Header.Get("Origin"))
+ return c.JSON(http.StatusAccepted, okapi.M{"ok": true})
+ },
+ Group: group,
+ })
+
+ for _, contentType := range []string{
+ "text/plain;charset=UTF-8",
+ "application/x-www-form-urlencoded",
+ "multipart/form-data; boundary=x",
+ } {
+ req := httptest.NewRequest(http.MethodPost, "/api/v1/f/abc", nil)
+ req.Header.Set("Origin", "https://customer.test")
+ req.Header.Set("Content-Type", contentType)
+ rec := httptest.NewRecorder()
+ app.ServeHTTP(rec, req)
+
+ if rec.Code != http.StatusAccepted {
+ t.Fatalf("content type %q: status = %d, want 202", contentType, rec.Code)
+ }
+ if got := rec.Header().Get("Access-Control-Allow-Origin"); got != "https://customer.test" {
+ t.Fatalf("content type %q: allow-origin = %q", contentType, got)
+ }
+ }
+}
diff --git a/internal/routes/routes.go b/internal/routes/routes.go
index b978b8c..15aa6c7 100644
--- a/internal/routes/routes.go
+++ b/internal/routes/routes.go
@@ -20,6 +20,7 @@ import (
"github.com/goposta/posta/internal/services/emailverify"
"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/passwordreset"
planpkg "github.com/goposta/posta/internal/services/plan"
@@ -113,6 +114,10 @@ type routerHandlers struct {
inbound *handlers.InboundHandler
smtpCredential *handlers.SMTPCredentialHandler
verify *handlers.VerifyHandler
+ form *handlers.FormHandler
+ message *handlers.MessageHandler
+ messageFilter *handlers.MessageFilterHandler
+ formIngest *handlers.FormIngestHandler
}
func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *config.Config, producer *worker.Producer, cronManager *cronpkg.Manager, blobStore blob.Store, ctx context.Context, notifier ...*notification.Service) *email.Service {
@@ -388,6 +393,53 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *c
r.h.inbound.SetEventBus(bus)
}
+ // Web form messages
+ if cfg.MessagesEnabled {
+ formRepo := repositories.NewFormRepository(db)
+ messageRepo := repositories.NewMessageRepository(db)
+ messageFilterRepo := repositories.NewMessageFilterRepository(db)
+
+ messageSvc := messages.NewService(
+ formRepo, messageRepo, messageFilterRepo, suppressionRepo, redisClient,
+ messages.Config{
+ PerIPHourly: cfg.MessagesIPRateLimit,
+ PerFormHourly: cfg.MessagesPerFormHourly,
+ PerEmailHourly: cfg.MessagesPerEmailHourly,
+ PerWorkspaceDaily: cfg.MessagesPerWorkspaceDaily,
+ MaxBodyBytes: cfg.MessagesMaxBodyBytes,
+ MaxAttachmentSize: cfg.MessagesMaxAttachSize,
+ InboundDomain: cfg.MessagesInboundDomain,
+ AppWebURL: cfg.AppWebURL,
+ },
+ []byte(cfg.JWTSecret),
+ )
+ messageSvc.SetEmailService(emailService)
+ messageSvc.SetEventBus(bus)
+ if producer != nil {
+ messageSvc.SetEnqueuer(producer)
+ }
+ if blobStore != nil {
+ messageSvc.SetBlobStore(blobStore)
+ }
+ messageSvc.OnReceived(func(status models.MessageStatus) {
+ metrics.IncrementMessageReceived(string(status))
+ })
+
+ r.h.form = handlers.NewFormHandler(formRepo, messageRepo, domainRepo, auditLogger, cfg.ApiBaseURL)
+ r.h.message = handlers.NewMessageHandler(messageRepo, formRepo, messageFilterRepo, messageSvc, auditLogger)
+ r.h.message.SetEventBus(bus)
+ r.h.messageFilter = handlers.NewMessageFilterHandler(messageFilterRepo, messageRepo, formRepo, messageSvc.Scanner())
+ r.h.formIngest = handlers.NewFormIngestHandler(
+ messageSvc,
+ inbound.NewIPRateLimiter(cfg.MessagesIPRateLimit, time.Duration(cfg.MessagesIPRateWindow)*time.Second),
+ cfg.MessagesMaxAttachSize,
+ )
+ if blobStore != nil {
+ r.h.message.SetBlobStore(blobStore)
+ r.h.formIngest.SetBlobStore(blobStore)
+ }
+ }
+
// SMTP Relay
if cfg.SMTPRelayEnabled {
smtpCredRepo := repositories.NewSMTPCredentialRepository(db)
@@ -479,6 +531,10 @@ func (r *Router) registerRoutes() {
r.app.Register(r.inboundWebhookRoutes()...)
r.app.Register(r.inboundWorkspaceRoutes()...)
}
+ if r.cfg.MessagesEnabled && r.h.formIngest != nil {
+ r.app.Register(r.formIngestRoutes()...)
+ r.app.Register(r.messageWorkspaceRoutes()...)
+ }
r.app.Register(r.adminSSERoutes()...)
r.app.Register(r.adminRoutes()...)
diff --git a/internal/routes/webhook_docs.go b/internal/routes/webhook_docs.go
index 9b78e54..68fe3b7 100644
--- a/internal/routes/webhook_docs.go
+++ b/internal/routes/webhook_docs.go
@@ -40,6 +40,10 @@ func (r *Router) registerWebhookDocs() {
// 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{})
diff --git a/internal/services/messages/nonce.go b/internal/services/messages/nonce.go
new file mode 100644
index 0000000..74558e9
--- /dev/null
+++ b/internal/services/messages/nonce.go
@@ -0,0 +1,84 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package messages
+
+import (
+ "context"
+ "crypto/hmac"
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/base64"
+ "errors"
+ "fmt"
+ "strconv"
+ "strings"
+ "time"
+)
+
+var (
+ ErrNonceInvalid = errors.New("invalid nonce")
+ ErrNonceExpired = errors.New("nonce expired")
+ ErrNonceReplay = errors.New("nonce already used")
+ ErrNonceTooFast = errors.New("submitted too quickly")
+)
+
+const nonceTTL = 30 * time.Minute
+
+type Nonce struct {
+ Value string `json:"nonce"`
+ ExpiresIn int `json:"expires_in"`
+}
+
+func (s *Service) IssueNonce(ctx context.Context, formKey string) (*Nonce, error) {
+ raw := make([]byte, 12)
+ if _, err := rand.Read(raw); err != nil {
+ return nil, err
+ }
+ issued := time.Now().Unix()
+ body := fmt.Sprintf("%s.%d.%s", formKey, issued, base64.RawURLEncoding.EncodeToString(raw))
+ token := body + "." + sign(s.hmacKey, body)
+
+ return &Nonce{Value: token, ExpiresIn: int(nonceTTL.Seconds())}, nil
+}
+
+func (s *Service) VerifyNonce(ctx context.Context, formKey, token string, minFillSeconds int) error {
+ parts := strings.Split(token, ".")
+ if len(parts) != 4 {
+ return ErrNonceInvalid
+ }
+ body := strings.Join(parts[:3], ".")
+ if !hmac.Equal([]byte(sign(s.hmacKey, body)), []byte(parts[3])) {
+ return ErrNonceInvalid
+ }
+ if parts[0] != formKey {
+ return ErrNonceInvalid
+ }
+
+ issued, err := strconv.ParseInt(parts[1], 10, 64)
+ if err != nil {
+ return ErrNonceInvalid
+ }
+ age := time.Since(time.Unix(issued, 0))
+ if age > nonceTTL || age < 0 {
+ return ErrNonceExpired
+ }
+ if minFillSeconds > 0 && age < time.Duration(minFillSeconds)*time.Second {
+ return ErrNonceTooFast
+ }
+
+ if s.redis != nil {
+ key := "form:nonce:" + sign(s.hmacKey, token)
+ set, err := s.redis.SetNX(ctx, key, 1, nonceTTL).Result()
+ if err == nil && !set {
+ return ErrNonceReplay
+ }
+ }
+ return nil
+}
+
+func sign(key []byte, body string) string {
+ mac := hmac.New(sha256.New, key)
+ mac.Write([]byte(body))
+ return base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
+}
diff --git a/internal/services/messages/nonce_test.go b/internal/services/messages/nonce_test.go
new file mode 100644
index 0000000..c321bf7
--- /dev/null
+++ b/internal/services/messages/nonce_test.go
@@ -0,0 +1,156 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package messages
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/goposta/posta/internal/models"
+)
+
+func newTestService() *Service {
+ return &Service{hmacKey: []byte("test-secret")}
+}
+
+func TestNonceRoundTrip(t *testing.T) {
+ s := newTestService()
+ ctx := context.Background()
+
+ nonce, err := s.IssueNonce(ctx, "abc")
+ if err != nil {
+ t.Fatalf("IssueNonce: %v", err)
+ }
+ if err := s.VerifyNonce(ctx, "abc", nonce.Value, 0); err != nil {
+ t.Fatalf("VerifyNonce: %v", err)
+ }
+}
+
+func TestNonceRejectsWrongForm(t *testing.T) {
+ s := newTestService()
+ ctx := context.Background()
+
+ nonce, _ := s.IssueNonce(ctx, "abc")
+ if err := s.VerifyNonce(ctx, "xyz", nonce.Value, 0); !errors.Is(err, ErrNonceInvalid) {
+ t.Fatalf("err = %v, want ErrNonceInvalid", err)
+ }
+}
+
+func TestNonceRejectsTamperedSignature(t *testing.T) {
+ s := newTestService()
+ ctx := context.Background()
+
+ nonce, _ := s.IssueNonce(ctx, "abc")
+ parts := strings.Split(nonce.Value, ".")
+ tampered := strings.Join(parts[:3], ".") + ".deadbeef"
+ if err := s.VerifyNonce(ctx, "abc", tampered, 0); !errors.Is(err, ErrNonceInvalid) {
+ t.Fatalf("err = %v, want ErrNonceInvalid", err)
+ }
+}
+
+func TestNonceRejectsForeignKey(t *testing.T) {
+ issuer := &Service{hmacKey: []byte("secret-a")}
+ verifier := &Service{hmacKey: []byte("secret-b")}
+ ctx := context.Background()
+
+ nonce, _ := issuer.IssueNonce(ctx, "abc")
+ if err := verifier.VerifyNonce(ctx, "abc", nonce.Value, 0); !errors.Is(err, ErrNonceInvalid) {
+ t.Fatalf("err = %v, want ErrNonceInvalid", err)
+ }
+}
+
+func TestNonceRejectsMalformedToken(t *testing.T) {
+ s := newTestService()
+ for _, token := range []string{"", "a", "a.b.c", "a.b.c.d.e"} {
+ if err := s.VerifyNonce(context.Background(), "abc", token, 0); !errors.Is(err, ErrNonceInvalid) {
+ t.Fatalf("token %q: err = %v, want ErrNonceInvalid", token, err)
+ }
+ }
+}
+
+func TestNonceExpires(t *testing.T) {
+ s := newTestService()
+ issued := time.Now().Add(-2 * nonceTTL).Unix()
+ body := fmt.Sprintf("abc.%d.stale", issued)
+ token := body + "." + sign(s.hmacKey, body)
+
+ if err := s.VerifyNonce(context.Background(), "abc", token, 0); !errors.Is(err, ErrNonceExpired) {
+ t.Fatalf("err = %v, want ErrNonceExpired", err)
+ }
+}
+
+func TestNonceEnforcesMinimumFillTime(t *testing.T) {
+ s := newTestService()
+ ctx := context.Background()
+
+ nonce, _ := s.IssueNonce(ctx, "abc")
+ if err := s.VerifyNonce(ctx, "abc", nonce.Value, 30); !errors.Is(err, ErrNonceTooFast) {
+ t.Fatalf("err = %v, want ErrNonceTooFast", err)
+ }
+}
+
+func TestDedupHashIsStable(t *testing.T) {
+ a := dedupHash(1, "[email protected]", "hello")
+ b := dedupHash(1, "[email protected]", "hello")
+ if a != b {
+ t.Fatal("dedup hash should be case-insensitive on the address")
+ }
+ if dedupHash(2, "[email protected]", "hello") == a {
+ t.Fatal("dedup hash should differ per form")
+ }
+ if dedupHash(1, "[email protected]", "hello!") == a {
+ t.Fatal("dedup hash should differ per body")
+ }
+}
+
+func TestNewThreadTokenIsUnique(t *testing.T) {
+ seen := map[string]bool{}
+ for i := 0; i < 50; i++ {
+ token := newThreadToken()
+ if token == "" {
+ t.Fatal("empty thread token")
+ }
+ if seen[token] {
+ t.Fatalf("duplicate thread token %s", token)
+ }
+ seen[token] = true
+ }
+}
+
+func TestReplySubject(t *testing.T) {
+ cases := map[string]string{
+ "": "Re: your message",
+ " ": "Re: your message",
+ "Question": "Re: Question",
+ "Re: Question": "Re: Question",
+ "RE: Question": "RE: Question",
+ }
+ for in, want := range cases {
+ if got := replySubject(in); got != want {
+ t.Fatalf("replySubject(%q) = %q, want %q", in, got, want)
+ }
+ }
+}
+
+func TestThreadReplyToRequiresDomain(t *testing.T) {
+ s := newTestService()
+ msg := testMessage("tok123")
+
+ if got := s.ThreadReplyTo(msg); got != "" {
+ t.Fatalf("without an inbound domain ThreadReplyTo should be empty, got %q", got)
+ }
+
+ s.cfg.InboundDomain = "reply.example.com"
+ if got := s.ThreadReplyTo(msg); got != "[email protected]" {
+ t.Fatalf("ThreadReplyTo = %q", got)
+ }
+}
+
+func testMessage(token string) *models.Message {
+ return &models.Message{ThreadToken: token}
+}
diff --git a/internal/services/messages/origin_test.go b/internal/services/messages/origin_test.go
new file mode 100644
index 0000000..172da9d
--- /dev/null
+++ b/internal/services/messages/origin_test.go
@@ -0,0 +1,76 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package messages
+
+import (
+ "testing"
+
+ "github.com/goposta/posta/internal/models"
+ "github.com/lib/pq"
+)
+
+func TestOriginAllowed(t *testing.T) {
+ cases := []struct {
+ name string
+ origins []string
+ strict bool
+ origin string
+ want bool
+ }{
+ {"no allowlist accepts anything", nil, false, "https://evil.test", true},
+ {"empty origin allowed by default", []string{"https://example.com"}, false, "", true},
+ {"empty origin rejected when strict", []string{"https://example.com"}, true, "", false},
+ {"exact match", []string{"https://example.com"}, false, "https://example.com", true},
+ {"trailing slash tolerated", []string{"https://example.com"}, false, "https://example.com/", true},
+ {"scheme mismatch", []string{"https://example.com"}, false, "http://example.com", false},
+ {"port mismatch", []string{"https://example.com"}, false, "https://example.com:8443", false},
+ {"host mismatch", []string{"https://example.com"}, false, "https://evil.com", false},
+ {"subdomain is not a match", []string{"https://example.com"}, false, "https://www.example.com", false},
+ {"wildcard", []string{"*"}, false, "https://anything.test", true},
+ }
+
+ 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 {
+ t.Fatalf("OriginAllowed(%q) = %v, want %v", tc.origin, got, tc.want)
+ }
+ })
+ }
+}
+
+func TestRedirectAllowedRejectsOpenRedirects(t *testing.T) {
+ form := &models.Form{AllowedOrigins: pq.StringArray{"https://example.com"}}
+
+ cases := []struct {
+ target string
+ want bool
+ }{
+ {"https://example.com/thanks", true},
+ {"https://evil.test/phish", false},
+ {"javascript:alert(1)", false},
+ {"//evil.test", false},
+ {"/thanks", false},
+ {"", false},
+ }
+ for _, tc := range cases {
+ if got := RedirectAllowed(form, tc.target); got != tc.want {
+ t.Fatalf("RedirectAllowed(%q) = %v, want %v", tc.target, got, tc.want)
+ }
+ }
+}
+
+func TestRedirectAllowedWithoutAllowlistRejects(t *testing.T) {
+ form := &models.Form{}
+ if RedirectAllowed(form, "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") {
+ t.Fatal("a target on the configured redirect host should be allowed")
+ }
+}
diff --git a/internal/services/messages/parse.go b/internal/services/messages/parse.go
new file mode 100644
index 0000000..8b76e5f
--- /dev/null
+++ b/internal/services/messages/parse.go
@@ -0,0 +1,210 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package messages
+
+import (
+ "net/mail"
+ "strings"
+ "unicode"
+
+ "golang.org/x/text/unicode/norm"
+
+ "github.com/goposta/posta/internal/models"
+)
+
+const (
+ maxFieldValueBytes = 8192
+ maxHeaderFieldRunes = 200
+)
+
+var reservedFields = map[string]bool{
+ "_gotcha": true,
+ "_nonce": true,
+ "_redirect": true,
+ "_captcha": true,
+ "_cc": true,
+ "_next": true,
+ "_honeypot": true,
+}
+
+var (
+ emailKeys = []string{"email", "e-mail", "_replyto", "reply_to", "replyto", "from", "sender_email", "your-email"}
+ nameKeys = []string{"name", "full_name", "fullname", "your-name", "sender_name"}
+ subjectKeys = []string{"_subject", "subject", "topic", "your-subject"}
+ bodyKeys = []string{"message", "body", "comments", "comment", "content", "description", "your-message"}
+ phoneKeys = []string{"phone", "phone_number", "phonenumber", "tel", "telephone", "mobile", "cell", "your-phone", "sender_phone"}
+)
+
+const (
+ maxPhoneRunes = 40
+ phoneEdgeCutset = " -.,/"
+)
+
+func IsReserved(key string) bool {
+ return reservedFields[strings.ToLower(key)]
+}
+
+func Sanitize(value string) string {
+ value = strings.Map(func(r rune) rune {
+ if r == '\r' || r == 0 {
+ return -1
+ }
+ if r == '\n' || r == '\t' {
+ return r
+ }
+ if unicode.IsControl(r) {
+ return -1
+ }
+ return r
+ }, value)
+ value = norm.NFC.String(value)
+ value = strings.TrimSpace(value)
+ if len(value) > maxFieldValueBytes {
+ value = string([]rune(value)[:maxFieldValueBytes/4])
+ }
+ return value
+}
+
+func SanitizeHeaderValue(value string) string {
+ value = strings.Map(func(r rune) rune {
+ if r == '\r' || r == '\n' || r == 0 || unicode.IsControl(r) {
+ return -1
+ }
+ return r
+ }, value)
+ value = strings.TrimSpace(value)
+ runes := []rune(value)
+ if len(runes) > maxHeaderFieldRunes {
+ value = string(runes[:maxHeaderFieldRunes])
+ }
+ return value
+}
+
+type Extracted struct {
+ Email string
+ Name string
+ Phone string
+ Subject string
+ Body string
+}
+
+func Extract(fields []models.MessageField) Extracted {
+ var out Extracted
+
+ out.Email = SanitizeHeaderValue(pick(fields, emailKeys))
+ out.Name = SanitizeHeaderValue(pick(fields, nameKeys))
+ out.Phone = NormalizePhone(pick(fields, phoneKeys))
+ out.Subject = SanitizeHeaderValue(pick(fields, subjectKeys))
+ out.Body = pick(fields, bodyKeys)
+
+ if out.Email == "" {
+ out.Email = firstAddress(fields)
+ }
+ if out.Name == "" {
+ out.Name = joinNameParts(fields)
+ }
+ if out.Body == "" {
+ out.Body = longestValue(fields)
+ }
+ return out
+}
+
+func pick(fields []models.MessageField, keys []string) string {
+ for _, want := range keys {
+ for _, f := range fields {
+ if strings.EqualFold(strings.TrimSpace(f.Key), want) && strings.TrimSpace(f.Value) != "" {
+ return f.Value
+ }
+ }
+ }
+ return ""
+}
+
+func firstAddress(fields []models.MessageField) string {
+ for _, f := range fields {
+ v := strings.TrimSpace(f.Value)
+ if v == "" || !strings.Contains(v, "@") {
+ continue
+ }
+ if addr, err := mail.ParseAddress(v); err == nil {
+ return addr.Address
+ }
+ }
+ return ""
+}
+
+func joinNameParts(fields []models.MessageField) string {
+ var first, last string
+ for _, f := range fields {
+ switch strings.ToLower(strings.TrimSpace(f.Key)) {
+ case "first_name", "firstname", "given_name":
+ first = f.Value
+ case "last_name", "lastname", "surname", "family_name":
+ last = f.Value
+ }
+ }
+ return SanitizeHeaderValue(strings.TrimSpace(first + " " + last))
+}
+
+func longestValue(fields []models.MessageField) string {
+ var best string
+ for _, f := range fields {
+ if IsReserved(f.Key) {
+ continue
+ }
+ if len(f.Value) > len(best) {
+ best = f.Value
+ }
+ }
+ return best
+}
+
+func NormalizeEmail(email string) string {
+ email = strings.TrimSpace(email)
+ if addr, err := mail.ParseAddress(email); err == nil {
+ return strings.ToLower(addr.Address)
+ }
+ return strings.ToLower(email)
+}
+
+func NormalizePhone(v string) string {
+ v = SanitizeHeaderValue(v)
+ if v == "" {
+ return ""
+ }
+
+ var b strings.Builder
+ for _, r := range v {
+ switch {
+ case r >= '0' && r <= '9':
+ b.WriteRune(r)
+ case r == '+' && b.Len() == 0:
+ b.WriteRune(r)
+ case r == ' ', r == '-', r == '(', r == ')', r == '.', r == '/':
+ b.WriteRune(r)
+ }
+ }
+
+ out := strings.Join(strings.Fields(b.String()), " ")
+ out = strings.TrimLeft(strings.TrimRight(out, phoneEdgeCutset), phoneEdgeCutset)
+ if !strings.ContainsAny(out, "0123456789") {
+ return ""
+ }
+ if runes := []rune(out); len(runes) > maxPhoneRunes {
+ out = strings.TrimSpace(string(runes[:maxPhoneRunes]))
+ }
+ return out
+}
+
+func PhoneAliases() []string { return phoneKeys }
+
+func SummarizedKeys() []string {
+ keys := make([]string, 0, len(emailKeys)+len(nameKeys)+len(subjectKeys)+len(phoneKeys)+4)
+ keys = append(keys, emailKeys...)
+ keys = append(keys, nameKeys...)
+ keys = append(keys, subjectKeys...)
+ keys = append(keys, phoneKeys...)
+ keys = append(keys, "first_name", "firstname", "last_name", "lastname")
+ return keys
+}
diff --git a/internal/services/messages/parse_test.go b/internal/services/messages/parse_test.go
new file mode 100644
index 0000000..95ac6f4
--- /dev/null
+++ b/internal/services/messages/parse_test.go
@@ -0,0 +1,195 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package messages
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/goposta/posta/internal/models"
+)
+
+func TestSanitizeStripsControlCharacters(t *testing.T) {
+ cases := []struct {
+ name string
+ input string
+ want string
+ }{
+ {"carriage return", "hello\rworld", "helloworld"},
+ {"null byte", "hel\x00lo", "hello"},
+ {"keeps newline", "line1\nline2", "line1\nline2"},
+ {"keeps tab", "a\tb", "a\tb"},
+ {"trims", " spaced ", "spaced"},
+ {"bell", "ding\adong", "dingdong"},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := Sanitize(tc.input); got != tc.want {
+ t.Fatalf("Sanitize(%q) = %q, want %q", tc.input, got, tc.want)
+ }
+ })
+ }
+}
+
+func TestSanitizeHeaderValueBlocksInjection(t *testing.T) {
+ got := SanitizeHeaderValue("Jonas\r\nBcc: [email protected]")
+ if strings.ContainsAny(got, "\r\n") {
+ t.Fatalf("header value still contains CR/LF: %q", got)
+ }
+ if got != "JonasBcc: [email protected]" {
+ t.Fatalf("unexpected sanitized value: %q", got)
+ }
+}
+
+func TestSanitizeHeaderValueCapsLength(t *testing.T) {
+ got := SanitizeHeaderValue(strings.Repeat("a", 500))
+ if len([]rune(got)) != maxHeaderFieldRunes {
+ t.Fatalf("got %d runes, want %d", len([]rune(got)), maxHeaderFieldRunes)
+ }
+}
+
+func TestExtractWellKnownFields(t *testing.T) {
+ fields := []models.MessageField{
+ {Key: "Name", Value: "Ada Lovelace"},
+ {Key: "email", Value: "[email protected]"},
+ {Key: "_subject", Value: "Question"},
+ {Key: "message", Value: "How does it work?"},
+ }
+ got := Extract(fields)
+ if got.Name != "Ada Lovelace" || got.Email != "[email protected]" {
+ t.Fatalf("unexpected sender: %+v", got)
+ }
+ if got.Subject != "Question" || got.Body != "How does it work?" {
+ t.Fatalf("unexpected content: %+v", got)
+ }
+}
+
+func TestExtractFallsBackToFirstParseableAddress(t *testing.T) {
+ fields := []models.MessageField{
+ {Key: "contact", Value: "[email protected]"},
+ {Key: "note", Value: "hello there"},
+ }
+ if got := Extract(fields); got.Email != "[email protected]" {
+ t.Fatalf("Email = %q, want [email protected]", got.Email)
+ }
+}
+
+func TestExtractJoinsNameParts(t *testing.T) {
+ fields := []models.MessageField{
+ {Key: "first_name", Value: "Grace"},
+ {Key: "last_name", Value: "Hopper"},
+ }
+ if got := Extract(fields); got.Name != "Grace Hopper" {
+ t.Fatalf("Name = %q, want Grace Hopper", got.Name)
+ }
+}
+
+func TestExtractFallsBackToLongestValueForBody(t *testing.T) {
+ fields := []models.MessageField{
+ {Key: "email", Value: "[email protected]"},
+ {Key: "details", Value: "this is by far the longest submitted value"},
+ }
+ if got := Extract(fields); got.Body != "this is by far the longest submitted value" {
+ t.Fatalf("Body = %q", got.Body)
+ }
+}
+
+func TestExtractWithoutEmailLeavesItEmpty(t *testing.T) {
+ fields := []models.MessageField{{Key: "message", Value: "no address here"}}
+ if got := Extract(fields); got.Email != "" {
+ t.Fatalf("Email = %q, want empty", got.Email)
+ }
+}
+
+func TestIsReserved(t *testing.T) {
+ for _, key := range []string{"_gotcha", "_NONCE", "_redirect", "_captcha"} {
+ if !IsReserved(key) {
+ t.Fatalf("IsReserved(%q) = false, want true", key)
+ }
+ }
+ if IsReserved("email") {
+ t.Fatal("IsReserved(\"email\") = true, want false")
+ }
+}
+
+func TestNormalizeEmail(t *testing.T) {
+ cases := map[string]string{
+ "not-an-address": "not-an-address",
+ }
+ for in, want := range cases {
+ if got := NormalizeEmail(in); got != want {
+ t.Fatalf("NormalizeEmail(%q) = %q, want %q", in, got, want)
+ }
+ }
+}
+
+func TestExtractPhone(t *testing.T) {
+ cases := []struct {
+ name string
+ fields []models.MessageField
+ want string
+ }{
+ {"phone", []models.MessageField{{Key: "phone", Value: "+1 555 010 9999"}}, "+1 555 010 9999"},
+ {"tel alias", []models.MessageField{{Key: "Tel", Value: "0612345678"}}, "0612345678"},
+ {"mobile alias", []models.MessageField{{Key: "mobile", Value: "(555) 010-9999"}}, "(555) 010-9999"},
+ {"phone_number alias", []models.MessageField{{Key: "phone_number", Value: "555.010.9999"}}, "555.010.9999"},
+ {"absent", []models.MessageField{{Key: "email", Value: "[email protected]"}}, ""},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := Extract(tc.fields).Phone; got != tc.want {
+ t.Fatalf("Phone = %q, want %q", got, tc.want)
+ }
+ })
+ }
+}
+
+func TestNormalizePhone(t *testing.T) {
+ cases := map[string]string{
+ "+33 6 12 34 56 78": "+33 6 12 34 56 78",
+ " 0612345678 ": "0612345678",
+ "(555) 010-9999": "(555) 010-9999",
+ "555.010.9999 ext 4": "555.010.9999 4",
+ "call me": "",
+ "": "",
+ "tel:+15550109999": "+15550109999",
+ "+1\r\nBcc: [email protected]": "+1",
+ "12 34": "12 34",
+ }
+ for in, want := range cases {
+ if got := NormalizePhone(in); got != want {
+ t.Fatalf("NormalizePhone(%q) = %q, want %q", in, got, want)
+ }
+ }
+}
+
+func TestNormalizePhoneCapsLength(t *testing.T) {
+ got := NormalizePhone(strings.Repeat("1", 200))
+ if len([]rune(got)) != maxPhoneRunes {
+ t.Fatalf("got %d runes, want %d", len([]rune(got)), maxPhoneRunes)
+ }
+}
+
+func TestNormalizePhoneStripsInjection(t *testing.T) {
+ got := NormalizePhone("555\r\nBcc: [email protected]")
+ if strings.ContainsAny(got, "\r\n") || strings.Contains(got, "@") {
+ t.Fatalf("phone was not sanitized: %q", got)
+ }
+}
+
+func TestSummarizedKeysCoversEveryAlias(t *testing.T) {
+ set := map[string]bool{}
+ for _, k := range SummarizedKeys() {
+ set[k] = true
+ }
+ for _, group := range [][]string{emailKeys, nameKeys, subjectKeys, phoneKeys} {
+ for _, k := range group {
+ if !set[k] {
+ t.Fatalf("SummarizedKeys is missing alias %q", k)
+ }
+ }
+ }
+}
diff --git a/internal/services/messages/ratelimit.go b/internal/services/messages/ratelimit.go
new file mode 100644
index 0000000..0400e72
--- /dev/null
+++ b/internal/services/messages/ratelimit.go
@@ -0,0 +1,61 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package messages
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "strings"
+ "time"
+)
+
+var ErrRateLimited = errors.New("too many submissions")
+
+type quota struct {
+ key string
+ limit int
+ window time.Duration
+}
+
+func (s *Service) checkQuotas(ctx context.Context, formID, workspaceID uint, ip, email string) error {
+ if s.redis == nil {
+ return nil
+ }
+
+ 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 email != "" {
+ quotas = append(quotas, quota{
+ fmt.Sprintf("form:q:email:%d:%s", formID, hashKey(email)), s.cfg.PerEmailHourly, time.Hour,
+ })
+ }
+
+ 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
+ }
+ }
+ return nil
+}
+
+func hashKey(v string) string {
+ sum := sha256.Sum256([]byte(strings.ToLower(v)))
+ return hex.EncodeToString(sum[:8])
+}
diff --git a/internal/services/messages/service.go b/internal/services/messages/service.go
new file mode 100644
index 0000000..0cb83eb
--- /dev/null
+++ b/internal/services/messages/service.go
@@ -0,0 +1,446 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package messages
+
+import (
+ "context"
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/base32"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/url"
+ "strings"
+ "time"
+
+ "github.com/goposta/posta/internal/models"
+ "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/storage/blob"
+ "github.com/goposta/posta/internal/storage/repositories"
+ "github.com/jkaninda/logger"
+ "github.com/redis/go-redis/v9"
+ "gorm.io/gorm"
+)
+
+var (
+ ErrFormNotFound = errors.New("form not found")
+ ErrFormInactive = errors.New("form is not accepting submissions")
+ ErrOriginNotAllowed = errors.New("origin not allowed")
+ ErrPayloadTooLarge = errors.New("payload too large")
+ ErrTooManyFields = errors.New("too many fields")
+ ErrNoRecipient = errors.New("message has no reply address")
+ ErrSenderNotSet = errors.New("no reply sender configured for this form")
+)
+
+const dedupWindow = 5 * time.Minute
+
+type Config struct {
+ PerIPHourly int
+ PerFormHourly int
+ PerEmailHourly int
+ PerWorkspaceDaily int
+ MaxBodyBytes int64
+ MaxAttachmentSize int64
+ InboundDomain string
+ AppWebURL string
+}
+
+type Enqueuer interface {
+ EnqueueMessageProcess(messageID uint) error
+}
+
+type Service struct {
+ formRepo *repositories.FormRepository
+ messageRepo *repositories.MessageRepository
+ filterRepo *repositories.MessageFilterRepository
+ suppressionRepo *repositories.SuppressionRepository
+ emailService *email.Service
+ scanner *messagescan.Scanner
+ redis *redis.Client
+ blobStore blob.Store
+ bus *eventbus.EventBus
+ enqueuer Enqueuer
+ cfg Config
+ hmacKey []byte
+
+ onReceived func(status models.MessageStatus)
+}
+
+func NewService(
+ formRepo *repositories.FormRepository,
+ messageRepo *repositories.MessageRepository,
+ filterRepo *repositories.MessageFilterRepository,
+ suppressionRepo *repositories.SuppressionRepository,
+ redisClient *redis.Client,
+ cfg Config,
+ hmacKey []byte,
+) *Service {
+ s := &Service{
+ formRepo: formRepo,
+ messageRepo: messageRepo,
+ filterRepo: filterRepo,
+ suppressionRepo: suppressionRepo,
+ redis: redisClient,
+ cfg: cfg,
+ hmacKey: hmacKey,
+ }
+ s.scanner = messagescan.New(&lookup{
+ messageRepo: messageRepo,
+ filterRepo: filterRepo,
+ suppressionRepo: suppressionRepo,
+ })
+ return s
+}
+
+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 {
+ origin = strings.TrimSpace(origin)
+ if origin == "" {
+ return !form.StrictOrigin
+ }
+ if len(form.AllowedOrigins) == 0 {
+ return true
+ }
+ for _, allowed := range form.AllowedOrigins {
+ allowed = strings.TrimSpace(allowed)
+ if allowed == "*" {
+ return true
+ }
+ if strings.EqualFold(strings.TrimSuffix(allowed, "/"), strings.TrimSuffix(origin, "/")) {
+ return true
+ }
+ }
+ return false
+}
+
+func RedirectAllowed(form *models.Form, target string) bool {
+ if target == "" {
+ return false
+ }
+ u, err := url.Parse(target)
+ if err != nil || u.Scheme == "" || u.Host == "" {
+ return false
+ }
+ if u.Scheme != "https" && u.Scheme != "http" {
+ 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) {
+ return true
+ }
+ }
+ return OriginAllowed(form, candidate) && len(form.AllowedOrigins) > 0
+}
+
+type SubmitRequest struct {
+ Form *models.Form
+ Fields []models.MessageField
+ Attachments []models.InboundAttachmentMeta
+ ClientIP string
+ UserAgent string
+ Referer string
+ Origin string
+ HoneypotHit bool
+ NonceFailed bool
+}
+
+type SubmitResult struct {
+ Message *models.Message
+ Duplicate bool
+ Stored bool
+}
+
+func (s *Service) Submit(ctx context.Context, req SubmitRequest) (*SubmitResult, error) {
+ form := req.Form
+ if form == nil {
+ return nil, ErrFormNotFound
+ }
+ if !form.IsActive() {
+ return nil, ErrFormInactive
+ }
+ if len(req.Fields) > form.FieldLimit() {
+ return nil, ErrTooManyFields
+ }
+ if form.WorkspaceID == nil {
+ return nil, ErrFormNotFound
+ }
+
+ honeypot := strings.ToLower(form.Honeypot())
+ fields := make([]models.MessageField, 0, len(req.Fields))
+ for _, f := range req.Fields {
+ key := SanitizeHeaderValue(f.Key)
+ if key == "" || IsReserved(key) || strings.ToLower(key) == honeypot {
+ continue
+ }
+ fields = append(fields, models.MessageField{Key: key, Value: Sanitize(f.Value)})
+ }
+
+ extracted := Extract(fields)
+ senderEmail := NormalizeEmail(extracted.Email)
+
+ if err := s.checkQuotas(ctx, form.ID, *form.WorkspaceID, req.ClientIP, senderEmail); err != nil {
+ return nil, err
+ }
+
+ hash := dedupHash(form.ID, senderEmail, extracted.Body)
+ if existing, err := s.messageRepo.FindRecentDuplicate(form.ID, hash, time.Now().Add(-dedupWindow)); err == nil && existing != nil {
+ return &SubmitResult{Message: existing, Duplicate: true, Stored: true}, nil
+ }
+
+ verdict := s.scanner.Scan(messagescan.Input{
+ Form: form,
+ WorkspaceID: *form.WorkspaceID,
+ SenderEmail: senderEmail,
+ SenderName: extracted.Name,
+ Subject: extracted.Subject,
+ Body: extracted.Body,
+ Fields: fields,
+ ClientIP: req.ClientIP,
+ UserAgent: req.UserAgent,
+ HoneypotHit: req.HoneypotHit,
+ NonceFailed: req.NonceFailed,
+ })
+
+ threadToken := newThreadToken()
+ if threadToken == "" {
+ return nil, errors.New("failed to generate a thread token")
+ }
+
+ subject := extracted.Subject
+ if subject == "" {
+ subject = defaultSubject(form)
+ }
+
+ fieldsJSON, _ := json.Marshal(fields)
+ attachmentsJSON := ""
+ if len(req.Attachments) > 0 && form.AllowAttachments {
+ if raw, err := json.Marshal(req.Attachments); err == nil {
+ attachmentsJSON = string(raw)
+ }
+ }
+
+ msg := &models.Message{
+ WorkspaceID: form.WorkspaceID,
+ FormID: form.ID,
+ SenderEmail: senderEmail,
+ SenderName: extracted.Name,
+ SenderPhone: extracted.Phone,
+ Subject: subject,
+ Body: extracted.Body,
+ FieldsJSON: string(fieldsJSON),
+ AttachmentsJSON: attachmentsJSON,
+ ClientIP: req.ClientIP,
+ UserAgent: truncate(req.UserAgent, 400),
+ Referer: truncate(req.Referer, 400),
+ Origin: truncate(req.Origin, 200),
+ Status: verdict.Status(),
+ State: models.MessageStateNew,
+ SpamScore: verdict.Score,
+ ScanReasons: verdict.Reasons,
+ ThreadToken: threadToken,
+ DedupHash: hash,
+ }
+ if msg.IsSpam() {
+ msg.State = models.MessageStateSpam
+ }
+
+ if err := s.messageRepo.Create(msg); err != nil {
+ return nil, err
+ }
+
+ _ = s.formRepo.RecordSubmission(form.ID, msg.IsSpam(), msg.CreatedAt)
+ if len(verdict.FilterHits) > 0 {
+ _ = s.filterRepo.RecordHits(verdict.FilterHits, time.Now())
+ }
+ if s.onReceived != nil {
+ s.onReceived(msg.Status)
+ }
+
+ if msg.Status != models.MessageStatusRejected && s.enqueuer != nil {
+ if err := s.enqueuer.EnqueueMessageProcess(msg.ID); err != nil {
+ logger.Error("failed to enqueue message processing", "message_id", msg.ID, "error", err)
+ }
+ }
+
+ return &SubmitResult{Message: msg, Stored: true}, nil
+}
+
+type ReplyRequest struct {
+ HTML string
+ Text string
+ Subject string
+ Attachments []models.Attachment
+}
+
+func (s *Service) Reply(ctx context.Context, actorID, apiKeyID uint, actorEmail string, form *models.Form, msg *models.Message, req ReplyRequest) (*models.MessageReply, error) {
+ if s.emailService == nil {
+ return nil, errors.New("email service unavailable")
+ }
+ if !msg.CanReply() {
+ return nil, ErrNoRecipient
+ }
+
+ from := strings.TrimSpace(form.ReplyFrom)
+ if from == "" {
+ return nil, ErrSenderNotSet
+ }
+ if form.ReplyFromName != "" {
+ from = fmt.Sprintf("%s <%s>", SanitizeHeaderValue(form.ReplyFromName), from)
+ }
+
+ subject := SanitizeHeaderValue(req.Subject)
+ if subject == "" {
+ subject = replySubject(msg.Subject)
+ }
+
+ headers := map[string]string{}
+ if msg.RootMessageID != "" {
+ headers["In-Reply-To"] = msg.RootMessageID
+ headers["References"] = msg.RootMessageID
+ }
+ 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,
+ }
+
+ resp, err := s.emailService.Send(ctx, actorID, apiKeyID, msg.WorkspaceID, actorEmail, sendReq)
+ if err != nil {
+ return nil, err
+ }
+
+ 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,
+ }
+ if err := s.messageRepo.AddReply(reply); err != nil {
+ return nil, err
+ }
+
+ now := time.Now()
+ msg.RepliedAt = &now
+ msg.UpdatedAt = &now
+ msg.ReplyCount++
+ if msg.State != models.MessageStateClosed {
+ msg.State = models.MessageStateReplied
+ }
+ 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
+}
+
+func (s *Service) threadReplyTo(msg *models.Message) string {
+ if s.cfg.InboundDomain == "" || msg.ThreadToken == "" {
+ return ""
+ }
+ return fmt.Sprintf("msg+%s@%s", msg.ThreadToken, s.cfg.InboundDomain)
+}
+
+func (s *Service) ThreadReplyTo(msg *models.Message) string { return s.threadReplyTo(msg) }
+
+func defaultSubject(form *models.Form) string {
+ return fmt.Sprintf("New submission on %s", form.Name)
+}
+
+func replySubject(subject string) string {
+ subject = strings.TrimSpace(subject)
+ if subject == "" {
+ return "Re: your message"
+ }
+ if strings.HasPrefix(strings.ToLower(subject), "re:") {
+ return subject
+ }
+ return "Re: " + subject
+}
+
+func dedupHash(formID uint, email, body string) string {
+ sum := sha256.Sum256([]byte(fmt.Sprintf("%d|%s|%s", formID, strings.ToLower(email), body)))
+ return hex.EncodeToString(sum[:])
+}
+
+func newThreadToken() string {
+ raw := make([]byte, 16)
+ if _, err := rand.Read(raw); err != nil {
+ return ""
+ }
+ return strings.ToLower(base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(raw))
+}
+
+func truncate(v string, n int) string {
+ if len(v) <= n {
+ return v
+ }
+ return v[:n]
+}
+
+type lookup struct {
+ messageRepo *repositories.MessageRepository
+ filterRepo *repositories.MessageFilterRepository
+ suppressionRepo *repositories.SuppressionRepository
+}
+
+func (l *lookup) IsSuppressed(workspaceID uint, email string) bool {
+ if l.suppressionRepo == nil || email == "" {
+ return false
+ }
+ ws := workspaceID
+ suppressed, err := l.suppressionRepo.IsSuppressed(repositories.ResourceScope{WorkspaceID: &ws}, email)
+ return err == nil && suppressed
+}
+
+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) ActiveFilters(workspaceID uint, formID uint) ([]models.MessageFilter, error) {
+ return l.filterRepo.FindActive(workspaceID, formID)
+}
diff --git a/internal/services/messagescan/scanner.go b/internal/services/messagescan/scanner.go
new file mode 100644
index 0000000..0c5bdb5
--- /dev/null
+++ b/internal/services/messagescan/scanner.go
@@ -0,0 +1,316 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package messagescan
+
+import (
+ "fmt"
+ "regexp"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/goposta/posta/internal/models"
+)
+
+type Action string
+
+const (
+ ActionAllow Action = "allow"
+ ActionFlag Action = "flag"
+ ActionQuarantine Action = "quarantine"
+ ActionReject Action = "reject"
+)
+
+var actionRank = map[Action]int{
+ ActionAllow: 0,
+ ActionFlag: 1,
+ ActionQuarantine: 2,
+ ActionReject: 3,
+}
+
+type Verdict struct {
+ Score float64
+ Reasons []string
+ Action Action
+ Allowlisted bool
+ FilterHits []uint
+}
+
+func (v Verdict) Status() models.MessageStatus {
+ switch v.Action {
+ case ActionReject:
+ return models.MessageStatusRejected
+ case ActionQuarantine:
+ return models.MessageStatusQuarantined
+ case ActionFlag:
+ return models.MessageStatusFlagged
+ default:
+ return models.MessageStatusReceived
+ }
+}
+
+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)
+}
+
+type Input struct {
+ Form *models.Form
+ WorkspaceID uint
+ SenderEmail string
+ SenderName string
+ Subject string
+ Body string
+ Fields []models.MessageField
+ ClientIP string
+ UserAgent string
+ HoneypotHit bool
+ NonceFailed bool
+}
+
+type Scanner struct {
+ lookup Lookup
+
+ mu sync.RWMutex
+ cache map[string]*regexp.Regexp
+}
+
+func New(lookup Lookup) *Scanner {
+ return &Scanner{lookup: lookup, cache: make(map[string]*regexp.Regexp)}
+}
+
+func (s *Scanner) Scan(in Input) Verdict {
+ v := Verdict{Action: ActionAllow}
+
+ if in.HoneypotHit {
+ v.Reasons = append(v.Reasons, "honeypot")
+ v.Action = ActionReject
+ v.Score = 100
+ return v
+ }
+ if in.NonceFailed {
+ v.Reasons = append(v.Reasons, "nonce_invalid")
+ v.Action = ActionReject
+ v.Score = 100
+ return v
+ }
+
+ if in.Form != nil && !in.Form.ScanEnabled {
+ return v
+ }
+
+ floor := ActionAllow
+
+ if s.lookup != nil {
+ hits, err := s.lookup.ActiveFilters(in.WorkspaceID, formID(in.Form))
+ if err == nil {
+ for i := range hits {
+ f := &hits[i]
+ matched, reason := s.matchFilter(f, in)
+ if !matched {
+ continue
+ }
+ v.FilterHits = append(v.FilterHits, f.ID)
+ if f.Action == models.FilterActionAllowlist {
+ v.Reasons = []string{reason}
+ v.Allowlisted = true
+ v.Action = ActionAllow
+ v.Score = 0
+ return v
+ }
+ v.Reasons = append(v.Reasons, reason)
+ v.Score += f.Score
+ if a := filterAction(f.Action); actionRank[a] > actionRank[floor] {
+ floor = a
+ }
+ }
+ }
+ }
+
+ for _, sig := range builtinSignals {
+ score, reason := sig(s, in)
+ if score == 0 && reason == "" {
+ continue
+ }
+ v.Score += score
+ if reason != "" {
+ v.Reasons = append(v.Reasons, reason)
+ }
+ }
+
+ v.Action = resolveAction(in.Form, v.Score)
+ if actionRank[floor] > actionRank[v.Action] {
+ v.Action = floor
+ }
+ return v
+}
+
+func resolveAction(form *models.Form, score float64) Action {
+ flag, quarantine, reject := 3.0, 6.0, 10.0
+ if form != nil {
+ if form.FlagThreshold > 0 {
+ flag = form.FlagThreshold
+ }
+ if form.QuarantineThreshold > 0 {
+ quarantine = form.QuarantineThreshold
+ }
+ if form.RejectThreshold > 0 {
+ reject = form.RejectThreshold
+ }
+ }
+ switch {
+ case score >= reject:
+ return ActionReject
+ case score >= quarantine:
+ return ActionQuarantine
+ case score >= flag:
+ return ActionFlag
+ default:
+ return ActionAllow
+ }
+}
+
+func filterAction(a models.FilterAction) Action {
+ switch a {
+ case models.FilterActionFlag:
+ return ActionFlag
+ case models.FilterActionQuarantine:
+ return ActionQuarantine
+ case models.FilterActionReject:
+ return ActionReject
+ default:
+ return ActionAllow
+ }
+}
+
+func formID(f *models.Form) uint {
+ if f == nil {
+ return 0
+ }
+ return f.ID
+}
+
+func (s *Scanner) matchFilter(f *models.MessageFilter, in Input) (bool, string) {
+ switch f.Kind {
+ case models.FilterKindEmail:
+ return strings.EqualFold(strings.TrimSpace(in.SenderEmail), strings.TrimSpace(f.Pattern)),
+ fmt.Sprintf("filter:email:%s", f.Pattern)
+ case models.FilterKindDomain:
+ domain := emailDomain(in.SenderEmail)
+ pattern := strings.ToLower(strings.TrimPrefix(strings.TrimSpace(f.Pattern), "@"))
+ return domain != "" && (domain == pattern || strings.HasSuffix(domain, "."+pattern)),
+ fmt.Sprintf("filter:domain:%s", f.Pattern)
+ case models.FilterKindIP:
+ return in.ClientIP != "" && in.ClientIP == strings.TrimSpace(f.Pattern),
+ fmt.Sprintf("filter:ip:%s", f.Pattern)
+ case models.FilterKindRegex:
+ re := s.compile(f.Pattern, f.CaseSensitive)
+ if re == nil {
+ return false, ""
+ }
+ for _, text := range filterTargets(f, in) {
+ if re.MatchString(text) {
+ return true, fmt.Sprintf("filter:regex:%d", f.ID)
+ }
+ }
+ return false, ""
+ case models.FilterKindPhrase:
+ needle := f.Pattern
+ for _, text := range filterTargets(f, in) {
+ if containsText(text, needle, f.CaseSensitive) {
+ return true, fmt.Sprintf("filter:phrase:%s", f.Pattern)
+ }
+ }
+ return false, ""
+ default:
+ needle := f.Pattern
+ for _, text := range filterTargets(f, in) {
+ if containsWord(text, needle, f.CaseSensitive) {
+ return true, fmt.Sprintf("filter:keyword:%s", f.Pattern)
+ }
+ }
+ return false, ""
+ }
+}
+
+func filterTargets(f *models.MessageFilter, in Input) []string {
+ if len(f.Fields) == 0 {
+ out := make([]string, 0, 4+len(in.Fields))
+ out = append(out, in.Subject, in.Body, in.SenderName, in.SenderEmail)
+ for _, fld := range in.Fields {
+ out = append(out, fld.Value)
+ }
+ return out
+ }
+ var out []string
+ for _, want := range f.Fields {
+ switch strings.ToLower(want) {
+ case "subject":
+ out = append(out, in.Subject)
+ case "body", "message":
+ out = append(out, in.Body)
+ case "name":
+ out = append(out, in.SenderName)
+ case "email":
+ out = append(out, in.SenderEmail)
+ default:
+ for _, fld := range in.Fields {
+ if strings.EqualFold(fld.Key, want) {
+ out = append(out, fld.Value)
+ }
+ }
+ }
+ }
+ return out
+}
+
+func (s *Scanner) compile(pattern string, caseSensitive bool) *regexp.Regexp {
+ if len(pattern) > models.MaxFilterPatternLength {
+ return nil
+ }
+ key := pattern
+ if !caseSensitive {
+ key = "(?i)" + pattern
+ }
+
+ s.mu.RLock()
+ re, ok := s.cache[key]
+ s.mu.RUnlock()
+ if ok {
+ return re
+ }
+
+ compiled, err := regexp.Compile(key)
+ if err != nil {
+ compiled = nil
+ }
+
+ s.mu.Lock()
+ s.cache[key] = compiled
+ s.mu.Unlock()
+ return compiled
+}
+
+func ValidatePattern(kind models.FilterKind, pattern string) error {
+ pattern = strings.TrimSpace(pattern)
+ if pattern == "" {
+ return fmt.Errorf("pattern is required")
+ }
+ if len(pattern) > models.MaxFilterPatternLength {
+ return fmt.Errorf("pattern exceeds %d characters", models.MaxFilterPatternLength)
+ }
+ if kind == models.FilterKindRegex {
+ if _, err := regexp.Compile(pattern); err != nil {
+ return fmt.Errorf("invalid regular expression: %w", err)
+ }
+ }
+ return nil
+}
+
+func (s *Scanner) MatchesFilter(f *models.MessageFilter, in Input) bool {
+ matched, _ := s.matchFilter(f, in)
+ return matched
+}
diff --git a/internal/services/messagescan/scanner_test.go b/internal/services/messagescan/scanner_test.go
new file mode 100644
index 0000000..2aa0915
--- /dev/null
+++ b/internal/services/messagescan/scanner_test.go
@@ -0,0 +1,304 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package messagescan
+
+import (
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/goposta/posta/internal/models"
+ "github.com/lib/pq"
+)
+
+type stubLookup struct {
+ suppressed bool
+ fromIP int64
+ fromSender int64
+ filters []models.MessageFilter
+ 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) {
+ return s.filters, s.filterError
+}
+
+func testForm() *models.Form {
+ id := uint(1)
+ return &models.Form{
+ ID: 1,
+ WorkspaceID: &id,
+ ScanEnabled: true,
+ FlagThreshold: 3,
+ QuarantineThreshold: 6,
+ RejectThreshold: 10,
+ }
+}
+
+func TestHoneypotRejectsImmediately(t *testing.T) {
+ s := New(&stubLookup{})
+ v := s.Scan(Input{Form: testForm(), HoneypotHit: true})
+ if v.Action != ActionReject {
+ t.Fatalf("Action = %s, want reject", v.Action)
+ }
+ if v.Status() != models.MessageStatusRejected {
+ t.Fatalf("Status = %s, want rejected", v.Status())
+ }
+}
+
+func TestNonceFailureRejectsImmediately(t *testing.T) {
+ s := New(&stubLookup{})
+ v := s.Scan(Input{Form: testForm(), NonceFailed: true})
+ if v.Action != ActionReject {
+ t.Fatalf("Action = %s, want reject", v.Action)
+ }
+}
+
+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)})
+ if v.Action != ActionAllow || v.Score != 0 {
+ t.Fatalf("Action = %s score = %v, want allow/0", v.Action, v.Score)
+ }
+}
+
+func TestThresholdMapping(t *testing.T) {
+ cases := []struct {
+ score float64
+ want Action
+ }{
+ {0, ActionAllow},
+ {2.9, ActionAllow},
+ {3, ActionFlag},
+ {5.9, ActionFlag},
+ {6, ActionQuarantine},
+ {9.9, ActionQuarantine},
+ {10, ActionReject},
+ {50, ActionReject},
+ }
+ for _, tc := range cases {
+ if got := resolveAction(testForm(), tc.score); got != tc.want {
+ t.Fatalf("resolveAction(%v) = %s, want %s", tc.score, got, tc.want)
+ }
+ }
+}
+
+func TestAllowlistShortCircuits(t *testing.T) {
+ s := New(&stubLookup{
+ suppressed: true,
+ filters: []models.MessageFilter{
+ {ID: 7, Kind: models.FilterKindDomain, Pattern: "partner.com", Action: models.FilterActionAllowlist},
+ },
+ })
+ v := s.Scan(Input{
+ Form: testForm(),
+ SenderEmail: "[email protected]",
+ Body: strings.Repeat("http://spam.test ", 20),
+ })
+ if !v.Allowlisted {
+ t.Fatal("expected the message to be allowlisted")
+ }
+ if v.Action != ActionAllow || v.Score != 0 {
+ t.Fatalf("Action = %s score = %v, want allow/0", v.Action, v.Score)
+ }
+}
+
+func TestFilterActionSetsFloorRegardlessOfScore(t *testing.T) {
+ s := New(&stubLookup{
+ filters: []models.MessageFilter{
+ {ID: 1, Kind: models.FilterKindKeyword, Pattern: "casino", Action: models.FilterActionReject, Score: 0},
+ },
+ })
+ v := s.Scan(Input{Form: testForm(), Body: "come to our casino"})
+ if v.Action != ActionReject {
+ t.Fatalf("Action = %s, want reject", v.Action)
+ }
+}
+
+func TestFilterScoreAccumulates(t *testing.T) {
+ s := New(&stubLookup{
+ filters: []models.MessageFilter{
+ {ID: 1, Kind: models.FilterKindKeyword, Pattern: "seo", Action: models.FilterActionScore, Score: 2},
+ {ID: 2, Kind: models.FilterKindKeyword, Pattern: "ranking", Action: models.FilterActionScore, Score: 2},
+ },
+ })
+ v := s.Scan(Input{Form: testForm(), Body: "improve your seo and ranking"})
+ if v.Score < 4 {
+ t.Fatalf("Score = %v, want at least 4", v.Score)
+ }
+ if len(v.FilterHits) != 2 {
+ t.Fatalf("FilterHits = %v, want 2 entries", v.FilterHits)
+ }
+}
+
+func TestKeywordMatchesWholeWordOnly(t *testing.T) {
+ s := New(&stubLookup{
+ filters: []models.MessageFilter{
+ {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 {
+ 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 {
+ t.Fatal("keyword filter should match a standalone word")
+ }
+}
+
+func TestPhraseMatchesSubstring(t *testing.T) {
+ s := New(&stubLookup{
+ filters: []models.MessageFilter{
+ {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 {
+ t.Fatal("phrase filter should match inside a longer word")
+ }
+}
+
+func TestCaseSensitivity(t *testing.T) {
+ sensitive := New(&stubLookup{
+ filters: []models.MessageFilter{
+ {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 {
+ t.Fatal("case-sensitive filter matched a differently-cased word")
+ }
+
+ insensitive := New(&stubLookup{
+ filters: []models.MessageFilter{
+ {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 {
+ t.Fatal("case-insensitive filter should have matched")
+ }
+}
+
+func TestDomainFilterMatchesSubdomains(t *testing.T) {
+ s := New(&stubLookup{
+ filters: []models.MessageFilter{
+ {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 {
+ t.Fatal("domain filter should match a subdomain")
+ }
+ if v := s.Scan(Input{Form: testForm(), SenderEmail: "[email protected]"}); len(v.FilterHits) != 0 {
+ t.Fatal("domain filter must not match an unrelated host ending in the same suffix")
+ }
+}
+
+func TestFilterFieldScoping(t *testing.T) {
+ s := New(&stubLookup{
+ filters: []models.MessageFilter{
+ {
+ ID: 1, Kind: models.FilterKindKeyword, Pattern: "urgent",
+ Action: models.FilterActionScore, Score: 5,
+ Fields: pq.StringArray{"subject"},
+ },
+ },
+ })
+ if v := s.Scan(Input{Form: 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 {
+ t.Fatal("subject-scoped filter should match the subject")
+ }
+}
+
+func TestBuiltinSignals(t *testing.T) {
+ cases := []struct {
+ name string
+ lookup *stubLookup
+ input Input
+ reason string
+ }{
+ {"suppressed sender", &stubLookup{suppressed: true}, Input{SenderEmail: "[email protected]"}, "sender_suppressed"},
+ {"disposable domain", &stubLookup{}, Input{SenderEmail: "[email protected]"}, "disposable_email"},
+ {"unparseable sender", &stubLookup{}, Input{SenderEmail: "not an address"}, "sender_unparseable"},
+ {"shortener", &stubLookup{}, Input{Body: "click https://bit.ly/x"}, "url_shortener"},
+ {"short body", &stubLookup{}, Input{Body: "hi"}, "body_too_short"},
+ {"shouting", &stubLookup{}, Input{Body: strings.Repeat("LOUD NOISES ", 6)}, "excessive_caps"},
+ {"markup", &stubLookup{}, Input{Body: `check <a href="http://x">this</a> out for a while`}, "embedded_markup"},
+ {"script", &stubLookup{}, Input{Body: `<script>alert(1)</script> and some filler text here`}, "embedded_script"},
+ {"repeat ip", &stubLookup{fromIP: 9}, Input{ClientIP: "203.0.113.7"}, "repeat_ip:9"},
+ {"bot agent", &stubLookup{}, Input{UserAgent: "python-requests/2.31"}, "bot_user_agent"},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ s := New(tc.lookup)
+ in := tc.input
+ in.Form = testForm()
+ v := s.Scan(in)
+ for _, r := range v.Reasons {
+ if r == tc.reason {
+ return
+ }
+ }
+ t.Fatalf("reasons %v do not contain %q", v.Reasons, tc.reason)
+ })
+ }
+}
+
+func TestLinkCountScoreIsCapped(t *testing.T) {
+ s := New(&stubLookup{})
+ v := s.Scan(Input{Form: testForm(), Body: strings.Repeat("https://x.test ", 60)})
+ for _, r := range v.Reasons {
+ if strings.HasPrefix(r, "links:") {
+ if v.Score > 20 {
+ t.Fatalf("Score = %v, link scoring should stay bounded", v.Score)
+ }
+ return
+ }
+ }
+ t.Fatal("expected a links: reason")
+}
+
+func TestValidatePattern(t *testing.T) {
+ if err := ValidatePattern(models.FilterKindKeyword, ""); err == nil {
+ t.Fatal("empty pattern should be rejected")
+ }
+ if err := ValidatePattern(models.FilterKindKeyword, strings.Repeat("a", 600)); err == nil {
+ t.Fatal("overlong pattern should be rejected")
+ }
+ if err := ValidatePattern(models.FilterKindRegex, "a(b"); err == nil {
+ t.Fatal("invalid regex should be rejected")
+ }
+ if err := ValidatePattern(models.FilterKindRegex, `^spam\d+$`); err != nil {
+ t.Fatalf("valid regex rejected: %v", err)
+ }
+}
+
+func TestRegexFilterIgnoresOverlongPattern(t *testing.T) {
+ s := New(&stubLookup{
+ filters: []models.MessageFilter{
+ {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 {
+ t.Fatal("an overlong regex pattern must not be compiled or matched")
+ }
+}
+
+func TestVerdictStatusMapping(t *testing.T) {
+ cases := map[Action]models.MessageStatus{
+ ActionAllow: models.MessageStatusReceived,
+ ActionFlag: models.MessageStatusFlagged,
+ ActionQuarantine: models.MessageStatusQuarantined,
+ ActionReject: models.MessageStatusRejected,
+ }
+ for action, want := range cases {
+ if got := (Verdict{Action: action}).Status(); got != want {
+ t.Fatalf("Verdict{%s}.Status() = %s, want %s", action, got, want)
+ }
+ }
+}
diff --git a/internal/services/messagescan/signals.go b/internal/services/messagescan/signals.go
new file mode 100644
index 0000000..860c0b1
--- /dev/null
+++ b/internal/services/messagescan/signals.go
@@ -0,0 +1,239 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package messagescan
+
+import (
+ "fmt"
+ "net/mail"
+ "strings"
+ "time"
+ "unicode"
+)
+
+type signal func(s *Scanner, in Input) (float64, string)
+
+var builtinSignals = []signal{
+ signalSuppressed,
+ signalInvalidSender,
+ signalDisposableDomain,
+ signalLinkCount,
+ signalShortener,
+ signalBodyLength,
+ signalShouting,
+ signalMarkup,
+ signalRepeatIP,
+ signalRepeatSender,
+ signalBotUserAgent,
+}
+
+func signalSuppressed(s *Scanner, in Input) (float64, string) {
+ if s.lookup == nil || in.SenderEmail == "" {
+ return 0, ""
+ }
+ if s.lookup.IsSuppressed(in.WorkspaceID, in.SenderEmail) {
+ return 5, "sender_suppressed"
+ }
+ return 0, ""
+}
+
+func signalInvalidSender(s *Scanner, in Input) (float64, string) {
+ if in.SenderEmail == "" {
+ return 0, ""
+ }
+ if _, err := mail.ParseAddress(in.SenderEmail); err != nil {
+ return 3, "sender_unparseable"
+ }
+ return 0, ""
+}
+
+func signalDisposableDomain(s *Scanner, in Input) (float64, string) {
+ domain := emailDomain(in.SenderEmail)
+ if domain == "" {
+ return 0, ""
+ }
+ if disposableDomains[domain] {
+ return 4, "disposable_email"
+ }
+ return 0, ""
+}
+
+func signalLinkCount(s *Scanner, in Input) (float64, string) {
+ n := countLinks(in.Body) + countLinks(in.Subject)
+ if n <= 5 {
+ return 0, ""
+ }
+ score := float64(n - 5)
+ if score > 6 {
+ score = 6
+ }
+ return score, fmt.Sprintf("links:%d", n)
+}
+
+func signalShortener(s *Scanner, in Input) (float64, string) {
+ lower := strings.ToLower(in.Body + " " + in.Subject)
+ for _, d := range shortenerDomains {
+ if strings.Contains(lower, d) {
+ return 2, "url_shortener"
+ }
+ }
+ return 0, ""
+}
+
+func signalBodyLength(s *Scanner, in Input) (float64, string) {
+ n := len([]rune(strings.TrimSpace(in.Body)))
+ switch {
+ case n == 0:
+ return 0, ""
+ case n < 10:
+ return 2, "body_too_short"
+ case n > 20000:
+ return 2, "body_too_long"
+ }
+ return 0, ""
+}
+
+func signalShouting(s *Scanner, in Input) (float64, string) {
+ text := in.Body
+ if len([]rune(text)) < 40 {
+ return 0, ""
+ }
+ var letters, upper int
+ for _, r := range text {
+ if unicode.IsLetter(r) {
+ letters++
+ if unicode.IsUpper(r) {
+ upper++
+ }
+ }
+ }
+ if letters == 0 {
+ return 0, ""
+ }
+ if float64(upper)/float64(letters) >= 0.7 {
+ return 2, "excessive_caps"
+ }
+ return 0, ""
+}
+
+func signalMarkup(s *Scanner, in Input) (float64, string) {
+ lower := strings.ToLower(in.Body)
+ if strings.Contains(lower, "<a href") || strings.Contains(lower, "[url=") || strings.Contains(lower, "[link=") {
+ return 3, "embedded_markup"
+ }
+ if strings.Contains(lower, "<script") || strings.Contains(lower, "javascript:") {
+ return 5, "embedded_script"
+ }
+ return 0, ""
+}
+
+func signalRepeatIP(s *Scanner, in Input) (float64, string) {
+ if s.lookup == nil || in.ClientIP == "" {
+ return 0, ""
+ }
+ n := s.lookup.SubmissionsFromIP(in.ClientIP, time.Now().Add(-time.Hour))
+ if n >= 5 {
+ return 3, fmt.Sprintf("repeat_ip:%d", n)
+ }
+ return 0, ""
+}
+
+func signalRepeatSender(s *Scanner, in Input) (float64, string) {
+ if s.lookup == nil || in.SenderEmail == "" || in.Form == nil {
+ return 0, ""
+ }
+ n := s.lookup.SubmissionsFromSender(in.Form.ID, in.SenderEmail, time.Now().Add(-time.Hour))
+ if n >= 3 {
+ return 2, fmt.Sprintf("repeat_sender:%d", n)
+ }
+ return 0, ""
+}
+
+func signalBotUserAgent(s *Scanner, in Input) (float64, string) {
+ ua := strings.ToLower(in.UserAgent)
+ if ua == "" {
+ return 0, ""
+ }
+ for _, needle := range botAgents {
+ if strings.Contains(ua, needle) {
+ return 2, "bot_user_agent"
+ }
+ }
+ return 0, ""
+}
+
+func countLinks(text string) int {
+ lower := strings.ToLower(text)
+ return strings.Count(lower, "http://") + strings.Count(lower, "https://") + strings.Count(lower, "www.")
+}
+
+func emailDomain(email string) string {
+ at := strings.LastIndex(email, "@")
+ if at < 0 || at == len(email)-1 {
+ return ""
+ }
+ return strings.ToLower(strings.TrimSpace(email[at+1:]))
+}
+
+func containsText(haystack, needle string, caseSensitive bool) bool {
+ if needle == "" {
+ return false
+ }
+ if caseSensitive {
+ return strings.Contains(haystack, needle)
+ }
+ return strings.Contains(strings.ToLower(haystack), strings.ToLower(needle))
+}
+
+func containsWord(haystack, needle string, caseSensitive bool) bool {
+ if needle == "" {
+ return false
+ }
+ if !caseSensitive {
+ haystack = strings.ToLower(haystack)
+ needle = strings.ToLower(needle)
+ }
+ idx := 0
+ for {
+ found := strings.Index(haystack[idx:], needle)
+ if found < 0 {
+ return false
+ }
+ start := idx + found
+ end := start + len(needle)
+ beforeOK := start == 0 || !isWordRune(rune(haystack[start-1]))
+ afterOK := end == len(haystack) || !isWordRune(rune(haystack[end]))
+ if beforeOK && afterOK {
+ return true
+ }
+ idx = start + 1
+ if idx >= len(haystack) {
+ return false
+ }
+ }
+}
+
+func isWordRune(r rune) bool {
+ return unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_'
+}
+
+var shortenerDomains = []string{
+ "bit.ly", "t.co/", "goo.gl", "tinyurl.com", "ow.ly", "is.gd",
+ "buff.ly", "adf.ly", "cutt.ly", "rebrand.ly", "shorturl.at",
+}
+
+var botAgents = []string{
+ "python-requests", "curl/", "wget/", "go-http-client", "libwww-perl",
+ "scrapy", "httpclient", "okhttp", "phantomjs", "headlesschrome",
+}
+
+var disposableDomains = map[string]bool{
+ "mailinator.com": true, "guerrillamail.com": true, "10minutemail.com": true,
+ "tempmail.com": true, "temp-mail.org": true, "throwawaymail.com": true,
+ "yopmail.com": true, "trashmail.com": true, "sharklasers.com": true,
+ "getnada.com": true, "dispostable.com": true, "maildrop.cc": true,
+ "fakeinbox.com": true, "mailnesia.com": true, "tempinbox.com": true,
+ "spamgourmet.com": true, "mytemp.email": true, "moakt.com": true,
+ "emailondeck.com": true, "mohmal.com": true, "tempr.email": true,
+ "discard.email": true, "grr.la": true, "spam4.me": true,
+}
diff --git a/internal/services/notification/message_templates_test.go b/internal/services/notification/message_templates_test.go
new file mode 100644
index 0000000..4f535e8
--- /dev/null
+++ b/internal/services/notification/message_templates_test.go
@@ -0,0 +1,140 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package notification
+
+import (
+ "html"
+ "html/template"
+ "strings"
+ "testing"
+
+ "github.com/goposta/posta/internal/models"
+)
+
+func renderOnly(t *testing.T, name string, data map[string]any) string {
+ t.Helper()
+ tmpl := template.Must(template.ParseFS(templateFS,
+ "templates/base.tmpl",
+ "templates/"+name+".tmpl",
+ ))
+ var sb strings.Builder
+ if err := tmpl.ExecuteTemplate(&sb, "base", data); err != nil {
+ t.Fatalf("render %s: %v", name, err)
+ }
+ return sb.String()
+}
+
+func renderedText(t *testing.T, name string, data map[string]any) string {
+ t.Helper()
+ return html.UnescapeString(renderOnly(t, name, data))
+}
+
+func TestEveryRegisteredTemplateParses(t *testing.T) {
+ s := &Service{templates: map[string]*template.Template{}}
+ s.loadTemplates()
+
+ for _, name := range []string{TemplateNewMessage, TemplateMessageDigest} {
+ if _, ok := s.templates[name]; !ok {
+ t.Fatalf("template %q is not registered in loadTemplates", name)
+ }
+ }
+}
+
+func TestNewMessageTemplateRenders(t *testing.T) {
+ out := renderedText(t, TemplateNewMessage, map[string]any{
+ "Subject": "New message on Contact form",
+ "UserName": "Ada",
+ "FormName": "Contact form",
+ "WorkspaceName": "Acme",
+ "Fields": []models.MessageField{
+ {Key: "From", Value: "[email protected]"},
+ {Key: "Subject", Value: "Hello"},
+ },
+ "Body": "Plain body text",
+ "Flagged": true,
+ "SpamScore": "4.5",
+ "MessageURL": "https://posta.test/messages/abc",
+ })
+
+ for _, want := range []string{"Contact form", "Acme", "[email protected]", "Plain body text", "4.5", "https://posta.test/messages/abc"} {
+ if !strings.Contains(out, want) {
+ t.Fatalf("rendered template is missing %q", want)
+ }
+ }
+}
+
+func TestNewMessageTemplateEscapesSubmittedContent(t *testing.T) {
+ out := renderOnly(t, TemplateNewMessage, map[string]any{
+ "Subject": "New message",
+ "UserName": "Ada",
+ "FormName": "Contact form",
+ "Fields": []models.MessageField{
+ {Key: "name", Value: `<img src=x onerror=alert(1)>`},
+ },
+ "Body": `<script>alert("xss")</script>`,
+ })
+
+ if strings.Contains(out, "<script>alert") || strings.Contains(out, "<img src=x") {
+ t.Fatalf("submitted content was not escaped:\n%s", out)
+ }
+ if !strings.Contains(out, "&lt;script&gt;") {
+ t.Fatal("expected the body to be HTML-escaped")
+ }
+}
+
+func TestMessageDigestTemplateRenders(t *testing.T) {
+ type item struct {
+ Sender string
+ Subject string
+ Flagged bool
+ }
+ out := renderedText(t, TemplateMessageDigest, map[string]any{
+ "Subject": "Hourly digest",
+ "UserName": "Ada",
+ "Period": "Hourly",
+ "FormName": "Contact form",
+ "Total": 2,
+ "Items": []item{
+ {Sender: "[email protected]", Subject: "One", Flagged: false},
+ {Sender: "[email protected]", Subject: "Two", Flagged: true},
+ },
+ "InboxURL": "https://posta.test/messages",
+ })
+
+ for _, want := range []string{"Hourly", "[email protected]", "[email protected]", "(flagged)", "https://posta.test/messages"} {
+ if !strings.Contains(out, want) {
+ t.Fatalf("rendered digest is missing %q", want)
+ }
+ }
+}
+
+func TestNewMessageTemplateRendersPhone(t *testing.T) {
+ out := renderedText(t, TemplateNewMessage, map[string]any{
+ "Subject": "New message",
+ "UserName": "Ada",
+ "FormName": "Contact form",
+ "SenderPhone": "+1 555 010 9999",
+ "Fields": []models.MessageField{{Key: "From", Value: "[email protected]"}},
+ "Body": "hello",
+ })
+ if !strings.Contains(out, "+1 555 010 9999") {
+ t.Fatal("rendered template is missing the phone number")
+ }
+ if !strings.Contains(out, `href="tel:`) {
+ t.Fatal("the phone number should be a tel: link")
+ }
+}
+
+func TestNewMessageTemplateOmitsPhoneWhenAbsent(t *testing.T) {
+ out := renderedText(t, TemplateNewMessage, map[string]any{
+ "Subject": "New message",
+ "UserName": "Ada",
+ "FormName": "Contact form",
+ "Fields": []models.MessageField{{Key: "From", Value: "[email protected]"}},
+ "Body": "hello",
+ })
+ if strings.Contains(out, "tel:") {
+ t.Fatal("no phone row should render when no phone was submitted")
+ }
+}
diff --git a/internal/services/notification/service.go b/internal/services/notification/service.go
index 39c2985..9a6e6ba 100644
--- a/internal/services/notification/service.go
+++ b/internal/services/notification/service.go
@@ -34,13 +34,17 @@ const (
TemplateLoginAlert = "login_alert"
TemplateTwoFactorChange = "two_factor_changed"
TemplateAccountDeletion = "account_deletion"
+ TemplateNewMessage = "new_message"
+ TemplateMessageDigest = "message_digest"
)
var templatePreference = map[string]func(*models.UserSetting) bool{
- TemplateDailyReport: func(s *models.UserSetting) bool { return s.DailyReport },
- TemplateBounceAlert: func(s *models.UserSetting) bool { return s.NotifyBounceAlerts },
- TemplateAPIKeyExpiry: func(s *models.UserSetting) bool { return s.NotifyAPIKeyExpiry },
- TemplateRoleChanged: func(s *models.UserSetting) bool { return s.NotifyWorkspaceActivity },
+ TemplateDailyReport: func(s *models.UserSetting) bool { return s.DailyReport },
+ TemplateBounceAlert: func(s *models.UserSetting) bool { return s.NotifyBounceAlerts },
+ TemplateAPIKeyExpiry: func(s *models.UserSetting) bool { return s.NotifyAPIKeyExpiry },
+ TemplateRoleChanged: func(s *models.UserSetting) bool { return s.NotifyWorkspaceActivity },
+ TemplateNewMessage: func(s *models.UserSetting) bool { return s.NotifyNewMessage },
+ TemplateMessageDigest: func(s *models.UserSetting) bool { return s.NotifyNewMessage },
}
func templateEnabled(templateName string, settings *models.UserSetting) bool {
@@ -99,6 +103,8 @@ func (s *Service) loadTemplates() {
TemplateLoginAlert,
TemplateTwoFactorChange,
TemplateAccountDeletion,
+ TemplateNewMessage,
+ TemplateMessageDigest,
}
for _, name := range names {
tmpl := template.Must(template.ParseFS(templateFS,
diff --git a/internal/services/notification/templates/message_digest.tmpl b/internal/services/notification/templates/message_digest.tmpl
new file mode 100644
index 0000000..ba7ecc4
--- /dev/null
+++ b/internal/services/notification/templates/message_digest.tmpl
@@ -0,0 +1,27 @@
+{{ define "content" }}
+<h2 style="color: #111827; font-size: 20px; line-height: 1.3; margin: 0 0 18px; font-weight: 700; letter-spacing: -0.01em;">{{ .Period }} message digest</h2>
+<p style="margin: 0 0 16px;">Hi {{ .UserName }},</p>
+
+<p style="margin: 0 0 16px;">{{ if .WorkspaceName }}<strong>{{ .WorkspaceName }}</strong> received{{ else }}You received{{ end }} <strong>{{ .Total }}</strong> new message{{ if ne .Total 1 }}s{{ end }} on <strong>{{ .FormName }}</strong>.</p>
+
+<table class="stats-table" role="presentation" style="width: 100%; border-collapse: separate; border-spacing: 0; margin: 20px 0; border: 1px solid #eceef2; border-radius: 10px; overflow: hidden;">
+ <tr>
+ <th style="padding: 12px 16px; text-align: left; border-bottom: 1px solid #eceef2; background-color: #f9fafb; color: #6b7280; font-weight: 600; font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em;">From</th>
+ <th style="padding: 12px 16px; text-align: left; border-bottom: 1px solid #eceef2; background-color: #f9fafb; color: #6b7280; font-weight: 600; font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em;">Subject</th>
+ </tr>
+ {{ range .Items }}
+ <tr>
+ <td style="padding: 12px 16px; text-align: left; border-bottom: 1px solid #eceef2; font-size: 14px; color: #111827;">{{ .Sender }}{{ if .Flagged }} <span style="color:#d97706; font-weight:600;">(flagged)</span>{{ end }}</td>
+ <td style="padding: 12px 16px; text-align: left; border-bottom: 1px solid #eceef2; font-size: 14px; color: #111827;">{{ .Subject }}</td>
+ </tr>
+ {{ end }}
+</table>
+
+{{ if .InboxURL }}
+<table role="presentation" cellpadding="0" cellspacing="0" border="0" align="center" style="margin: 28px auto;">
+ <tr><td align="center" bgcolor="#7c3aed" style="border-radius: 8px;">
+ <a href="{{ .InboxURL }}" class="btn" style="display: inline-block; padding: 13px 30px; background-color: #7c3aed; color: #ffffff !important; text-decoration: none; border-radius: 8px; font-weight: 600; font-size: 15px; line-height: 1;">Open inbox</a>
+ </td></tr>
+</table>
+{{ end }}
+{{ end }}
diff --git a/internal/services/notification/templates/new_message.tmpl b/internal/services/notification/templates/new_message.tmpl
new file mode 100644
index 0000000..aec789d
--- /dev/null
+++ b/internal/services/notification/templates/new_message.tmpl
@@ -0,0 +1,42 @@
+{{ 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>
+<p style="margin: 0 0 16px;">Hi {{ .UserName }},</p>
+
+<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>
+
+{{ 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;">
+ This message was flagged by spam scanning (score {{ .SpamScore }}). Review it before replying.
+</div>
+{{ end }}
+
+<table class="stats-table" role="presentation" style="width: 100%; border-collapse: separate; border-spacing: 0; margin: 20px 0; border: 1px solid #eceef2; border-radius: 10px; overflow: hidden;">
+ <tr>
+ <th style="padding: 12px 16px; text-align: left; border-bottom: 1px solid #eceef2; background-color: #f9fafb; color: #6b7280; font-weight: 600; font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em;">Field</th>
+ <th style="padding: 12px 16px; text-align: left; border-bottom: 1px solid #eceef2; background-color: #f9fafb; color: #6b7280; font-weight: 600; font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em;">Value</th>
+ </tr>
+ {{ range .Fields }}
+ <tr>
+ <td style="padding: 12px 16px; text-align: left; border-bottom: 1px solid #eceef2; font-size: 14px; color: #6b7280; font-weight: 600;">{{ .Key }}</td>
+ <td style="padding: 12px 16px; text-align: left; border-bottom: 1px solid #eceef2; font-size: 14px; color: #111827;">{{ .Value }}</td>
+ </tr>
+ {{ end }}
+</table>
+
+{{ if .SenderPhone }}
+<p style="margin: 0 0 16px;">Phone: <a href="tel:{{ .SenderPhone }}" style="color: #7c3aed;">{{ .SenderPhone }}</a></p>
+{{ end }}
+
+{{ if .Body }}
+<p style="margin: 0 0 8px; color: #6b7280; font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em; font-weight: 600;">Message</p>
+<div style="padding: 14px 16px; border-radius: 10px; margin: 0 0 20px; font-size: 14px; line-height: 1.6; background-color: #f9fafb; border: 1px solid #eceef2; color: #111827; white-space: pre-wrap;">{{ .Body }}</div>
+{{ end }}
+
+{{ if .MessageURL }}
+<table role="presentation" cellpadding="0" cellspacing="0" border="0" align="center" style="margin: 28px auto;">
+ <tr><td align="center" bgcolor="#7c3aed" style="border-radius: 8px;">
+ <a href="{{ .MessageURL }}" class="btn" style="display: inline-block; padding: 13px 30px; background-color: #7c3aed; color: #ffffff !important; text-decoration: none; border-radius: 8px; font-weight: 600; font-size: 15px; line-height: 1;">Open and reply</a>
+ </td></tr>
+</table>
+{{ end }}
+{{ end }}
diff --git a/internal/services/settings/provider.go b/internal/services/settings/provider.go
index d911a12..bf8a2c5 100644
--- a/internal/services/settings/provider.go
+++ b/internal/services/settings/provider.go
@@ -123,6 +123,12 @@ func (p *Provider) EmailAttachmentRetentionDays() int {
return p.GetInt("email_attachment_retention_days", p.RetentionDays())
}
func (p *Provider) AuditLogRetentionDays() int { return p.GetInt("audit_log_retention_days", 90) }
+func (p *Provider) MessageRetentionDays() int {
+ return p.GetInt("message_retention_days", 365)
+}
+func (p *Provider) MessageSpamRetentionDays() int {
+ return p.GetInt("message_spam_retention_days", 30)
+}
func (p *Provider) WebhookDeliveryRetentionDays() int {
return p.GetInt("webhook_delivery_retention_days", 30)
}
diff --git a/internal/storage/migration/constraints.go b/internal/storage/migration/constraints.go
index 6ff88a1..2d60301 100644
--- a/internal/storage/migration/constraints.go
+++ b/internal/storage/migration/constraints.go
@@ -68,6 +68,38 @@ func runConstraints(db *gorm.DB) {
CREATE UNIQUE INDEX IF NOT EXISTS one_personal_per_user ON workspaces (owner_id) WHERE is_personal;
EXCEPTION WHEN others THEN NULL;
END $$`)
+
+ db.Exec(`DO $$ BEGIN
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_workspace_form_slug ON forms (workspace_id, slug) WHERE workspace_id IS NOT NULL AND deleted_at IS NULL;
+ EXCEPTION WHEN others THEN NULL;
+ END $$`)
+
+ db.Exec(`DO $$ BEGIN
+ CREATE INDEX IF NOT EXISTS idx_messages_ws_created ON messages (workspace_id, created_at DESC) WHERE deleted_at IS NULL;
+ CREATE INDEX IF NOT EXISTS idx_messages_form_status ON messages (form_id, status, created_at DESC) WHERE deleted_at IS NULL;
+ CREATE INDEX IF NOT EXISTS idx_messages_dedup ON messages (form_id, dedup_hash, created_at DESC) WHERE dedup_hash <> '';
+ CREATE INDEX IF NOT EXISTS idx_messages_inbox ON messages (workspace_id, state, created_at DESC) WHERE deleted_at IS NULL AND status IN ('received','flagged');
+ 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
+ FOREIGN KEY (form_id) REFERENCES forms(id) ON DELETE CASCADE;
+ END IF;
+ END $$`)
+
+ db.Exec(`DO $$ BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'fk_message_replies_message') THEN
+ ALTER TABLE message_replies ADD CONSTRAINT fk_message_replies_message
+ FOREIGN KEY (message_id) REFERENCES messages(id) ON DELETE CASCADE;
+ END IF;
+ END $$`)
+
+ db.Exec(`DO $$ BEGIN
+ CREATE INDEX IF NOT EXISTS idx_message_filters_lookup ON message_filters (workspace_id, enabled);
+ EXCEPTION WHEN others THEN NULL;
+ END $$`)
}
// rebuildUniqueIndexes re-scopes the per-tenant uniqueness constraints to
diff --git a/internal/storage/migration/migration.go b/internal/storage/migration/migration.go
index 1d0fbdc..4f68afb 100644
--- a/internal/storage/migration/migration.go
+++ b/internal/storage/migration/migration.go
@@ -57,6 +57,10 @@ func Run(db *gorm.DB) error {
&models.CampaignMessage{},
&models.TrackedLink{},
&models.TrackingEvent{},
+ &models.Form{},
+ &models.Message{},
+ &models.MessageReply{},
+ &models.MessageFilter{},
&models.UpgradeStep{},
&models.UpdateStatus{},
); err != nil {
diff --git a/internal/storage/repositories/form_repo.go b/internal/storage/repositories/form_repo.go
new file mode 100644
index 0000000..bc00c71
--- /dev/null
+++ b/internal/storage/repositories/form_repo.go
@@ -0,0 +1,105 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package repositories
+
+import (
+ "time"
+
+ "github.com/goposta/posta/internal/models"
+ "gorm.io/gorm"
+)
+
+type FormRepository struct {
+ db *gorm.DB
+}
+
+func NewFormRepository(db *gorm.DB) *FormRepository {
+ return &FormRepository{db: db}
+}
+
+func (r *FormRepository) Create(f *models.Form) error {
+ return r.db.Create(f).Error
+}
+
+func (r *FormRepository) Update(f *models.Form) error {
+ return r.db.Save(f).Error
+}
+
+func (r *FormRepository) FindByID(id uint) (*models.Form, error) {
+ var f models.Form
+ if err := r.db.Preload("LastEditedBy").First(&f, id).Error; err != nil {
+ return nil, err
+ }
+ return &f, nil
+}
+
+func (r *FormRepository) FindByIDForScope(scope ResourceScope, id uint) (*models.Form, error) {
+ var f models.Form
+ if err := ApplyWorkspaceScope(r.db, scope).Preload("LastEditedBy").First(&f, id).Error; err != nil {
+ return nil, err
+ }
+ return &f, nil
+}
+
+func (r *FormRepository) FindByPublicKey(key string) (*models.Form, error) {
+ var f models.Form
+ if err := r.db.Where("public_key = ?", key).First(&f).Error; err != nil {
+ return nil, err
+ }
+ return &f, nil
+}
+
+func (r *FormRepository) FindByScope(scope ResourceScope, limit, offset int) ([]models.Form, int64, error) {
+ var items []models.Form
+ var total int64
+
+ ApplyWorkspaceScope(r.db.Model(&models.Form{}), scope).Count(&total)
+
+ if err := ApplyWorkspaceScope(r.db, scope).
+ Preload("LastEditedBy").
+ Order("created_at DESC").
+ Limit(limit).Offset(offset).
+ Find(&items).Error; err != nil {
+ return nil, 0, err
+ }
+ return items, total, nil
+}
+
+func (r *FormRepository) CountByScope(scope ResourceScope) (int64, error) {
+ var total int64
+ err := ApplyWorkspaceScope(r.db.Model(&models.Form{}), scope).Count(&total).Error
+ return total, err
+}
+
+func (r *FormRepository) Delete(id uint) error {
+ return r.db.Delete(&models.Form{}, id).Error
+}
+
+func (r *FormRepository) SlugExists(workspaceID uint, slug string, excludeID uint) bool {
+ var count int64
+ q := r.db.Model(&models.Form{}).Where("workspace_id = ? AND slug = ?", workspaceID, slug)
+ if excludeID > 0 {
+ q = q.Where("id <> ?", excludeID)
+ }
+ q.Count(&count)
+ return count > 0
+}
+
+func (r *FormRepository) RecordSubmission(id uint, spam bool, at time.Time) error {
+ updates := map[string]any{
+ "message_count": gorm.Expr("message_count + 1"),
+ "last_message_at": at,
+ }
+ if spam {
+ updates["spam_count"] = gorm.Expr("spam_count + 1")
+ }
+ return r.db.Model(&models.Form{}).Where("id = ?", id).Updates(updates).Error
+}
+
+func (r *FormRepository) FindActiveWithDigest(mode models.NotifyMode) ([]models.Form, error) {
+ var items []models.Form
+ err := r.db.Where("status = ? AND notify_enabled = true AND notify_mode = ?", models.FormStatusActive, mode).
+ Find(&items).Error
+ return items, err
+}
diff --git a/internal/storage/repositories/message_filter_repo.go b/internal/storage/repositories/message_filter_repo.go
new file mode 100644
index 0000000..2f0eac6
--- /dev/null
+++ b/internal/storage/repositories/message_filter_repo.go
@@ -0,0 +1,78 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package repositories
+
+import (
+ "time"
+
+ "github.com/goposta/posta/internal/models"
+ "gorm.io/gorm"
+)
+
+type MessageFilterRepository struct {
+ db *gorm.DB
+}
+
+func NewMessageFilterRepository(db *gorm.DB) *MessageFilterRepository {
+ return &MessageFilterRepository{db: db}
+}
+
+func (r *MessageFilterRepository) Create(f *models.MessageFilter) error {
+ return r.db.Create(f).Error
+}
+
+func (r *MessageFilterRepository) Update(f *models.MessageFilter) error {
+ return r.db.Save(f).Error
+}
+
+func (r *MessageFilterRepository) FindByIDForScope(scope ResourceScope, id uint) (*models.MessageFilter, error) {
+ var f models.MessageFilter
+ if err := ApplyWorkspaceScope(r.db, scope).First(&f, id).Error; err != nil {
+ return nil, err
+ }
+ return &f, nil
+}
+
+func (r *MessageFilterRepository) FindByScope(scope ResourceScope, limit, offset int) ([]models.MessageFilter, int64, error) {
+ var items []models.MessageFilter
+ var total int64
+
+ ApplyWorkspaceScope(r.db.Model(&models.MessageFilter{}), scope).Count(&total)
+
+ if err := ApplyWorkspaceScope(r.db, scope).
+ Order("created_at DESC").
+ Limit(limit).Offset(offset).
+ Find(&items).Error; err != nil {
+ return nil, 0, err
+ }
+ return items, total, nil
+}
+
+func (r *MessageFilterRepository) FindActive(workspaceID uint, formID uint) ([]models.MessageFilter, error) {
+ var items []models.MessageFilter
+ err := r.db.Where("workspace_id = ? AND enabled = true AND (form_id IS NULL OR form_id = ?)", workspaceID, formID).
+ Order("action DESC, id ASC").
+ Find(&items).Error
+ return items, err
+}
+
+func (r *MessageFilterRepository) Delete(id uint) error {
+ return r.db.Delete(&models.MessageFilter{}, id).Error
+}
+
+func (r *MessageFilterRepository) RecordHits(ids []uint, at time.Time) error {
+ if len(ids) == 0 {
+ return nil
+ }
+ return r.db.Model(&models.MessageFilter{}).Where("id IN ?", ids).Updates(map[string]any{
+ "hit_count": gorm.Expr("hit_count + 1"),
+ "last_hit_at": at,
+ }).Error
+}
+
+func (r *MessageFilterRepository) CountByWorkspace(workspaceID uint) int64 {
+ var count int64
+ r.db.Model(&models.MessageFilter{}).Where("workspace_id = ?", workspaceID).Count(&count)
+ return count
+}
diff --git a/internal/storage/repositories/message_repo.go b/internal/storage/repositories/message_repo.go
new file mode 100644
index 0000000..d34c413
--- /dev/null
+++ b/internal/storage/repositories/message_repo.go
@@ -0,0 +1,235 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package repositories
+
+import (
+ "strings"
+ "time"
+
+ "github.com/goposta/posta/internal/models"
+ "gorm.io/gorm"
+)
+
+type MessageFilterQuery struct {
+ FormID uint
+ Status string
+ State string
+ Assigned *uint
+ Unread bool
+ Query string
+ From *time.Time
+ To *time.Time
+}
+
+type MessageRepository struct {
+ db *gorm.DB
+}
+
+func NewMessageRepository(db *gorm.DB) *MessageRepository {
+ return &MessageRepository{db: db}
+}
+
+func (r *MessageRepository) Create(m *models.Message) error {
+ return r.db.Create(m).Error
+}
+
+func (r *MessageRepository) Update(m *models.Message) error {
+ return r.db.Save(m).Error
+}
+
+func (r *MessageRepository) FindByID(id uint) (*models.Message, error) {
+ var m models.Message
+ if err := r.db.First(&m, id).Error; err != nil {
+ return nil, err
+ }
+ return &m, nil
+}
+
+func (r *MessageRepository) FindByUUIDForScope(scope ResourceScope, uuid string) (*models.Message, error) {
+ var m models.Message
+ err := ApplyWorkspaceScope(r.db, scope).
+ Preload("Form").
+ Preload("AssignedTo").
+ Preload("Replies", func(db *gorm.DB) *gorm.DB {
+ return db.Order("created_at ASC").Preload("Author")
+ }).
+ Where("uuid = ?", uuid).First(&m).Error
+ if err != nil {
+ return nil, err
+ }
+ return &m, nil
+}
+
+func (r *MessageRepository) FindByThreadToken(token string) (*models.Message, error) {
+ var m models.Message
+ if err := r.db.Where("thread_token = ?", token).First(&m).Error; err != nil {
+ return nil, err
+ }
+ return &m, nil
+}
+
+func (r *MessageRepository) FindByScopeFiltered(scope ResourceScope, f MessageFilterQuery, limit, offset int) ([]models.Message, int64, error) {
+ var items []models.Message
+ var total int64
+
+ apply := func(q *gorm.DB) *gorm.DB {
+ q = ApplyWorkspaceScope(q, scope)
+ if f.FormID > 0 {
+ q = q.Where("form_id = ?", f.FormID)
+ }
+ if f.Status != "" {
+ q = q.Where("status = ?", f.Status)
+ } else {
+ q = q.Where("status <> ?", models.MessageStatusRejected)
+ }
+ if f.State != "" {
+ q = q.Where("state = ?", f.State)
+ }
+ if f.Assigned != nil {
+ q = q.Where("assigned_to_id = ?", *f.Assigned)
+ }
+ if f.Unread {
+ q = q.Where("read_at IS NULL")
+ }
+ if f.Query != "" {
+ like := "%" + strings.ToLower(f.Query) + "%"
+ q = q.Where(
+ "LOWER(subject) LIKE ? OR LOWER(body) LIKE ? OR LOWER(sender_email) LIKE ? OR LOWER(sender_name) LIKE ? OR sender_phone LIKE ?",
+ like, like, like, like, like)
+ }
+ if f.From != nil {
+ q = q.Where("created_at >= ?", *f.From)
+ }
+ if f.To != nil {
+ q = q.Where("created_at <= ?", *f.To)
+ }
+ return q
+ }
+
+ apply(r.db.Model(&models.Message{})).Count(&total)
+
+ if err := apply(r.db).
+ Preload("Form").
+ Preload("AssignedTo").
+ Order("created_at DESC").
+ Limit(limit).Offset(offset).
+ Find(&items).Error; err != nil {
+ return nil, 0, err
+ }
+ return items, total, nil
+}
+
+func (r *MessageRepository) FindRecentDuplicate(formID uint, hash string, since time.Time) (*models.Message, error) {
+ var m models.Message
+ err := r.db.Where("form_id = ? AND dedup_hash = ? AND created_at >= ?", formID, hash, since).
+ Order("created_at DESC").First(&m).Error
+ if err != nil {
+ return nil, err
+ }
+ return &m, nil
+}
+
+func (r *MessageRepository) Delete(id uint) error {
+ return r.db.Delete(&models.Message{}, id).Error
+}
+
+func (r *MessageRepository) CountByScope(scope ResourceScope) (total, unread, spam int64) {
+ ApplyWorkspaceScope(r.db.Model(&models.Message{}), scope).
+ Where("status <> ?", models.MessageStatusRejected).Count(&total)
+ ApplyWorkspaceScope(r.db.Model(&models.Message{}), scope).
+ Where("read_at IS NULL AND status IN ?", []models.MessageStatus{models.MessageStatusReceived, models.MessageStatusFlagged}).Count(&unread)
+ ApplyWorkspaceScope(r.db.Model(&models.Message{}), scope).
+ Where("status IN ?", []models.MessageStatus{models.MessageStatusQuarantined, models.MessageStatusRejected}).Count(&spam)
+ return
+}
+
+func (r *MessageRepository) CountBySenderSince(formID uint, email string, since time.Time) int64 {
+ var count int64
+ r.db.Model(&models.Message{}).
+ Where("form_id = ? AND LOWER(sender_email) = ? AND created_at >= ?", formID, strings.ToLower(email), since).
+ Count(&count)
+ return count
+}
+
+func (r *MessageRepository) CountByIPSince(ip string, since time.Time) int64 {
+ var count int64
+ if ip == "" {
+ return 0
+ }
+ r.db.Model(&models.Message{}).
+ Where("client_ip = ? AND created_at >= ?", ip, since).
+ Count(&count)
+ return count
+}
+
+func (r *MessageRepository) FindUnnotified(formID uint, since time.Time) ([]models.Message, error) {
+ var items []models.Message
+ err := r.db.Where("form_id = ? AND notified_at IS NULL AND created_at >= ? AND status IN ?",
+ formID, since, []models.MessageStatus{models.MessageStatusReceived, models.MessageStatusFlagged}).
+ Order("created_at ASC").Find(&items).Error
+ return items, err
+}
+
+func (r *MessageRepository) MarkNotified(ids []uint, at time.Time) error {
+ if len(ids) == 0 {
+ return nil
+ }
+ return r.db.Model(&models.Message{}).Where("id IN ?", ids).Update("notified_at", at).Error
+}
+
+func (r *MessageRepository) AddReply(reply *models.MessageReply) error {
+ return r.db.Create(reply).Error
+}
+
+func (r *MessageRepository) FindReplyByID(id uint) (*models.MessageReply, error) {
+ var reply models.MessageReply
+ if err := r.db.First(&reply, id).Error; err != nil {
+ return nil, err
+ }
+ return &reply, nil
+}
+
+func (r *MessageRepository) ListReplies(messageID uint) ([]models.MessageReply, error) {
+ var items []models.MessageReply
+ err := r.db.Where("message_id = ?", messageID).Preload("Author").Order("created_at ASC").Find(&items).Error
+ return items, err
+}
+
+func (r *MessageRepository) DeleteOlderThan(before time.Time) (int64, error) {
+ result := r.db.Unscoped().Where("created_at < ?", before).Delete(&models.Message{})
+ return result.RowsAffected, result.Error
+}
+
+func (r *MessageRepository) DeleteSpamOlderThan(before time.Time) (int64, error) {
+ result := r.db.Unscoped().
+ Where("created_at < ? AND status IN ?", before,
+ []models.MessageStatus{models.MessageStatusQuarantined, models.MessageStatusRejected}).
+ Delete(&models.Message{})
+ return result.RowsAffected, result.Error
+}
+
+func (r *MessageRepository) AttachmentKeysOlderThan(before time.Time) ([]string, error) {
+ var payloads []string
+ err := r.db.Unscoped().Model(&models.Message{}).
+ Where("created_at < ? AND attachments_json <> ''", before).
+ Pluck("attachments_json", &payloads).Error
+ return payloads, err
+}
+
+func (r *MessageRepository) DailyCounts(scope ResourceScope, since time.Time) ([]MessageDailyCount, error) {
+ var rows []MessageDailyCount
+ err := ApplyWorkspaceScope(r.db.Model(&models.Message{}), scope).
+ Select("DATE(created_at) AS day, COUNT(*) AS total, COUNT(*) FILTER (WHERE status IN ('quarantined','rejected')) AS spam").
+ Where("created_at >= ?", since).
+ Group("DATE(created_at)").
+ Order("day ASC").
+ Scan(&rows).Error
+ return rows, err
+}
+
+type MessageDailyCount struct {
+ Day time.Time `json:"day"`
+ Total int64 `json:"total"`
+ Spam int64 `json:"spam"`
+}
diff --git a/internal/storage/repositories/scope.go b/internal/storage/repositories/scope.go
index 17e2ee4..8f031c0 100644
--- a/internal/storage/repositories/scope.go
+++ b/internal/storage/repositories/scope.go
@@ -36,3 +36,15 @@ func OwnsResource(scope ResourceScope, resourceUserID uint, resourceWorkspaceID
}
return resourceUserID == scope.UserID && resourceWorkspaceID == nil
}
+
+func ApplyWorkspaceScope(db *gorm.DB, scope ResourceScope) *gorm.DB {
+ if scope.WorkspaceID == nil {
+ logger.Warn("ApplyWorkspaceScope: workspace-only resource requested without a workspace", "user_id", scope.UserID)
+ return db.Where("1 = 0")
+ }
+ return db.Where("workspace_id = ?", *scope.WorkspaceID)
+}
+
+func OwnsWorkspaceResource(scope ResourceScope, resourceWorkspaceID *uint) bool {
+ return scope.WorkspaceID != nil && resourceWorkspaceID != nil && *scope.WorkspaceID == *resourceWorkspaceID
+}
diff --git a/internal/worker/message_handler.go b/internal/worker/message_handler.go
new file mode 100644
index 0000000..3827856
--- /dev/null
+++ b/internal/worker/message_handler.go
@@ -0,0 +1,277 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package worker
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "strings"
+ "time"
+
+ "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/webhook"
+ "github.com/goposta/posta/internal/storage/repositories"
+ "github.com/hibiken/asynq"
+ "github.com/jkaninda/logger"
+)
+
+type MessageWebhookPayload struct {
+ Event string `json:"event"`
+ Timestamp string `json:"timestamp"`
+ MessageID string `json:"message_id"`
+ FormID string `json:"form_id"`
+ FormName string `json:"form_name"`
+ SenderEmail string `json:"sender_email,omitempty"`
+ SenderName string `json:"sender_name,omitempty"`
+ SenderPhone string `json:"sender_phone,omitempty"`
+ Subject string `json:"subject,omitempty"`
+ Body string `json:"body,omitempty"`
+ Fields []models.MessageField `json:"fields,omitempty"`
+ Status string `json:"status"`
+ SpamScore float64 `json:"spam_score"`
+ ScanReasons []string `json:"scan_reasons,omitempty"`
+ ClientIP string `json:"client_ip,omitempty"`
+ ReceivedAt string `json:"received_at"`
+}
+
+type MessageProcessHandler struct {
+ messageRepo *repositories.MessageRepository
+ formRepo *repositories.FormRepository
+ workspaceRepo *repositories.WorkspaceRepository
+ dispatcher *webhook.Dispatcher
+ notifier *notification.Service
+ appURL string
+ onNotified func()
+}
+
+func NewMessageProcessHandler(
+ messageRepo *repositories.MessageRepository,
+ formRepo *repositories.FormRepository,
+ workspaceRepo *repositories.WorkspaceRepository,
+ dispatcher *webhook.Dispatcher,
+ notifier *notification.Service,
+ appURL string,
+) *MessageProcessHandler {
+ return &MessageProcessHandler{
+ messageRepo: messageRepo,
+ formRepo: formRepo,
+ workspaceRepo: workspaceRepo,
+ dispatcher: dispatcher,
+ notifier: notifier,
+ appURL: strings.TrimSuffix(appURL, "/"),
+ }
+}
+
+func (h *MessageProcessHandler) OnNotified(fn func()) { h.onNotified = fn }
+
+func (h *MessageProcessHandler) ProcessTask(ctx context.Context, t *asynq.Task) error {
+ var payload MessageProcessPayload
+ if err := json.Unmarshal(t.Payload(), &payload); err != nil {
+ return fmt.Errorf("unmarshal message payload: %w: %w", err, asynq.SkipRetry)
+ }
+
+ msg, err := h.messageRepo.FindByID(payload.MessageID)
+ if err != nil {
+ return fmt.Errorf("message not found: %w", err)
+ }
+ if msg.Status == models.MessageStatusRejected {
+ return nil
+ }
+
+ form, err := h.formRepo.FindByID(msg.FormID)
+ if err != nil {
+ return fmt.Errorf("form not found: %w", err)
+ }
+
+ h.dispatch(msg, form)
+
+ 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 nil
+}
+
+func (h *MessageProcessHandler) shouldNotify(msg *models.Message, form *models.Form) bool {
+ if !form.NotifyEnabled || form.NotifyMode != models.NotifyModeImmediate {
+ return false
+ }
+ if msg.Status == models.MessageStatusQuarantined {
+ return false
+ }
+ if msg.Status == models.MessageStatusFlagged && !form.NotifyOnFlagged {
+ return false
+ }
+ return true
+}
+
+func (h *MessageProcessHandler) dispatch(msg *models.Message, form *models.Form) {
+ if h.dispatcher == nil {
+ return
+ }
+
+ event := "message.received"
+ if msg.IsSpam() {
+ event = "message.spam"
+ }
+
+ var fields []models.MessageField
+ if msg.FieldsJSON != "" {
+ _ = json.Unmarshal([]byte(msg.FieldsJSON), &fields)
+ }
+
+ body := MessageWebhookPayload{
+ Event: event,
+ Timestamp: time.Now().UTC().Format(time.RFC3339),
+ MessageID: msg.UUID,
+ FormID: form.UUID,
+ FormName: form.Name,
+ SenderEmail: msg.SenderEmail,
+ SenderName: msg.SenderName,
+ SenderPhone: msg.SenderPhone,
+ Subject: msg.Subject,
+ Body: msg.Body,
+ Fields: fields,
+ Status: string(msg.Status),
+ SpamScore: msg.SpamScore,
+ ScanReasons: []string(msg.ScanReasons),
+ ClientIP: msg.ClientIP,
+ ReceivedAt: msg.CreatedAt.UTC().Format(time.RFC3339),
+ }
+
+ encoded, err := json.Marshal(body)
+ if err != nil {
+ logger.Error("failed to marshal message webhook body", "message_id", msg.ID, "error", err)
+ return
+ }
+ h.dispatcher.DispatchJSON(0, msg.WorkspaceID, event, encoded, msg.SenderEmail)
+}
+
+func (h *MessageProcessHandler) notify(msg *models.Message, form *models.Form) error {
+ if h.notifier == nil || !h.notifier.IsConfigured() {
+ return nil
+ }
+
+ var fields []models.MessageField
+ if msg.FieldsJSON != "" {
+ _ = 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)
+ }
+
+ data := map[string]any{
+ "FormName": form.Name,
+ "SenderPhone": msg.SenderPhone,
+ "Fields": notifiableFields(msg, fields),
+ "Body": msg.Body,
+ "Flagged": msg.Status == models.MessageStatusFlagged,
+ "SpamScore": fmt.Sprintf("%.1f", msg.SpamScore),
+ "MessageURL": h.messageURL(msg.UUID),
+ }
+ if workspaceName != "" {
+ data["WorkspaceName"] = workspaceName
+ }
+
+ if len(form.NotifyEmails) > 0 {
+ var lastErr error
+ for _, to := range form.NotifyEmails {
+ to = strings.TrimSpace(to)
+ if to == "" {
+ continue
+ }
+ payload := cloneData(data)
+ payload["UserName"] = "there"
+ if err := h.notifier.Send(to, subject, notification.TemplateNewMessage, payload); err != nil {
+ lastErr = err
+ }
+ }
+ return lastErr
+ }
+
+ if msg.WorkspaceID == nil {
+ return nil
+ }
+ return h.notifier.SendToWorkspaceAdmins(*msg.WorkspaceID, subject, notification.TemplateNewMessage, data)
+}
+
+func (h *MessageProcessHandler) messageURL(uuid string) string {
+ if h.appURL == "" {
+ return ""
+ }
+ return fmt.Sprintf("%s/messages/%s", h.appURL, uuid)
+}
+
+var summarizedFieldKeys = func() map[string]bool {
+ set := map[string]bool{"message": true, "body": true}
+ for _, k := range messages.SummarizedKeys() {
+ set[strings.ToLower(k)] = true
+ }
+ return set
+}()
+
+func notifiableFields(msg *models.Message, fields []models.MessageField) []models.MessageField {
+ out := []models.MessageField{
+ {Key: "From", Value: displaySender(msg)},
+ }
+ if msg.SenderPhone != "" {
+ out = append(out, models.MessageField{Key: "Phone", Value: msg.SenderPhone})
+ }
+ out = append(out, models.MessageField{Key: "Subject", Value: msg.Subject})
+
+ for _, f := range fields {
+ if summarizedFieldKeys[strings.ToLower(strings.TrimSpace(f.Key))] {
+ continue
+ }
+ if len(out) >= 12 {
+ break
+ }
+ out = append(out, f)
+ }
+ return out
+}
+
+func displaySender(msg *models.Message) string {
+ switch {
+ case msg.SenderName != "" && msg.SenderEmail != "":
+ return fmt.Sprintf("%s <%s>", msg.SenderName, msg.SenderEmail)
+ case msg.SenderEmail != "":
+ return msg.SenderEmail
+ case msg.SenderName != "":
+ return msg.SenderName
+ default:
+ return "unknown sender"
+ }
+}
+
+func cloneData(in map[string]any) map[string]any {
+ out := make(map[string]any, len(in))
+ for k, v := range in {
+ out[k] = v
+ }
+ return out
+}
diff --git a/internal/worker/message_handler_test.go b/internal/worker/message_handler_test.go
new file mode 100644
index 0000000..64af13d
--- /dev/null
+++ b/internal/worker/message_handler_test.go
@@ -0,0 +1,160 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package worker
+
+import (
+ "testing"
+
+ "github.com/goposta/posta/internal/models"
+)
+
+func TestShouldNotify(t *testing.T) {
+ cases := []struct {
+ name string
+ form models.Form
+ status models.MessageStatus
+ want bool
+ }{
+ {
+ "received with immediate notify",
+ models.Form{NotifyEnabled: true, NotifyMode: models.NotifyModeImmediate, NotifyOnFlagged: true},
+ models.MessageStatusReceived, true,
+ },
+ {
+ "notify disabled",
+ models.Form{NotifyEnabled: false, NotifyMode: models.NotifyModeImmediate},
+ models.MessageStatusReceived, false,
+ },
+ {
+ "digest mode defers to the cron job",
+ models.Form{NotifyEnabled: true, NotifyMode: models.NotifyModeHourly},
+ models.MessageStatusReceived, false,
+ },
+ {
+ "quarantined never notifies",
+ models.Form{NotifyEnabled: true, NotifyMode: models.NotifyModeImmediate, NotifyOnFlagged: true},
+ models.MessageStatusQuarantined, false,
+ },
+ {
+ "flagged notifies when opted in",
+ models.Form{NotifyEnabled: true, NotifyMode: models.NotifyModeImmediate, NotifyOnFlagged: true},
+ models.MessageStatusFlagged, true,
+ },
+ {
+ "flagged skipped when opted out",
+ models.Form{NotifyEnabled: true, NotifyMode: models.NotifyModeImmediate, NotifyOnFlagged: false},
+ models.MessageStatusFlagged, false,
+ },
+ }
+
+ h := &MessageProcessHandler{}
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ msg := &models.Message{Status: tc.status}
+ form := tc.form
+ if got := h.shouldNotify(msg, &form); got != tc.want {
+ t.Fatalf("shouldNotify = %v, want %v", got, tc.want)
+ }
+ })
+ }
+}
+
+func TestDisplaySender(t *testing.T) {
+ cases := []struct {
+ msg models.Message
+ want string
+ }{
+ {models.Message{SenderName: "Ada", SenderEmail: "[email protected]"}, "Ada <[email protected]>"},
+ {models.Message{SenderEmail: "[email protected]"}, "[email protected]"},
+ {models.Message{SenderName: "Ada"}, "Ada"},
+ {models.Message{}, "unknown sender"},
+ }
+ for _, tc := range cases {
+ msg := tc.msg
+ if got := displaySender(&msg); got != tc.want {
+ t.Fatalf("displaySender(%+v) = %q, want %q", tc.msg, got, tc.want)
+ }
+ }
+}
+
+func TestNotifiableFieldsDropsBodyAndCaps(t *testing.T) {
+ msg := &models.Message{SenderEmail: "[email protected]", Subject: "Hi"}
+ fields := []models.MessageField{{Key: "message", Value: "long body"}, {Key: "company", Value: "Acme"}}
+ for i := 0; i < 20; i++ {
+ fields = append(fields, models.MessageField{Key: "extra", Value: "x"})
+ }
+
+ got := notifiableFields(msg, fields)
+ if len(got) > 12 {
+ t.Fatalf("got %d fields, want at most 12", len(got))
+ }
+ for _, f := range got {
+ if f.Key == "message" {
+ t.Fatal("the body field must not be duplicated into the field table")
+ }
+ }
+ if got[0].Key != "From" || got[1].Key != "Subject" {
+ t.Fatalf("unexpected leading fields: %+v", got[:2])
+ }
+}
+
+func TestMessageIsSpam(t *testing.T) {
+ cases := map[models.MessageStatus]bool{
+ models.MessageStatusReceived: false,
+ models.MessageStatusFlagged: false,
+ models.MessageStatusQuarantined: true,
+ models.MessageStatusRejected: true,
+ }
+ for status, want := range cases {
+ msg := models.Message{Status: status}
+ if got := msg.IsSpam(); got != want {
+ t.Fatalf("IsSpam(%s) = %v, want %v", status, got, want)
+ }
+ }
+}
+
+func TestNotifiableFieldsIncludesPhoneAndDropsSummarizedAliases(t *testing.T) {
+ msg := &models.Message{
+ SenderName: "Ada",
+ SenderEmail: "[email protected]",
+ SenderPhone: "+1 555 010 9999",
+ Subject: "Hi",
+ }
+ fields := []models.MessageField{
+ {Key: "name", Value: "Ada"},
+ {Key: "email", Value: "[email protected]"},
+ {Key: "phone", Value: "+1 555 010 9999"},
+ {Key: "subject", Value: "Hi"},
+ {Key: "message", Value: "long body"},
+ {Key: "company", Value: "Acme"},
+ }
+
+ got := notifiableFields(msg, fields)
+
+ keys := make([]string, 0, len(got))
+ for _, f := range got {
+ keys = append(keys, f.Key)
+ }
+ want := []string{"From", "Phone", "Subject", "company"}
+ if len(keys) != len(want) {
+ t.Fatalf("keys = %v, want %v", keys, want)
+ }
+ for i := range want {
+ if keys[i] != want[i] {
+ t.Fatalf("keys = %v, want %v", keys, want)
+ }
+ }
+ if got[1].Value != "+1 555 010 9999" {
+ t.Fatalf("phone value = %q", got[1].Value)
+ }
+}
+
+func TestNotifiableFieldsOmitsPhoneRowWhenAbsent(t *testing.T) {
+ msg := &models.Message{SenderEmail: "[email protected]", Subject: "Hi"}
+ for _, f := range notifiableFields(msg, nil) {
+ if f.Key == "Phone" {
+ t.Fatal("a Phone row should not appear when no phone was submitted")
+ }
+ }
+}
diff --git a/internal/worker/producer.go b/internal/worker/producer.go
index c9c6177..d8ea31b 100644
--- a/internal/worker/producer.go
+++ b/internal/worker/producer.go
@@ -142,6 +142,24 @@ func (p *Producer) EnqueueInboundParse(inboundEmailID uint) error {
return nil
}
+func (p *Producer) EnqueueMessageProcess(messageID uint) error {
+ task, err := NewMessageProcessTask(messageID,
+ asynq.Queue(QueueTransactional),
+ asynq.MaxRetry(p.maxRetries),
+ asynq.TaskID(fmt.Sprintf("message:process:%d", messageID)),
+ )
+ if err != nil {
+ return fmt.Errorf("failed to create message 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 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 cf56285..de370a1 100644
--- a/internal/worker/tasks.go
+++ b/internal/worker/tasks.go
@@ -15,6 +15,7 @@ const (
TypeCampaignBatch = "campaign:batch"
TypeInboundParse = "inbound:parse"
TypeInboundProcess = "inbound:process"
+ TypeMessageProcess = "message:process"
QueueTransactional = "transactional"
QueueBulk = "bulk"
@@ -81,3 +82,15 @@ func NewInboundParseTask(id uint, opts ...asynq.Option) (*asynq.Task, error) {
}
return asynq.NewTask(TypeInboundParse, payload, opts...), nil
}
+
+type MessageProcessPayload struct {
+ MessageID uint `json:"message_id"`
+}
+
+func NewMessageProcessTask(id uint, opts ...asynq.Option) (*asynq.Task, error) {
+ payload, err := json.Marshal(MessageProcessPayload{MessageID: id})
+ if err != nil {
+ return nil, err
+ }
+ return asynq.NewTask(TypeMessageProcess, payload, opts...), nil
+}
diff --git a/web/src/api/messages.ts b/web/src/api/messages.ts
new file mode 100644
index 0000000..2458387
--- /dev/null
+++ b/web/src/api/messages.ts
@@ -0,0 +1,179 @@
+import api from './client'
+import type {
+ ApiResponse,
+ PaginatedResponse,
+ Form,
+ FormSnippet,
+ Message,
+ MessageFilterRule,
+ MessageReply,
+ MessageStats,
+} from './types'
+
+const WORKSPACE_KEY = 'posta_workspace_id'
+
+function workspaceParam(): string {
+ const ws = localStorage.getItem(WORKSPACE_KEY)
+ return ws ? `workspace_id=${encodeURIComponent(ws)}` : ''
+}
+
+export interface FormPayload {
+ name?: string
+ slug?: string
+ description?: string
+ status?: string
+ allowed_origins?: string[]
+ strict_origin?: boolean
+ redirect_url?: string
+ max_body_bytes?: number
+ max_fields?: number
+ allow_attachments?: boolean
+ honeypot_field?: string
+ require_nonce?: boolean
+ min_fill_seconds?: number
+ scan_enabled?: boolean
+ flag_threshold?: number
+ quarantine_threshold?: number
+ reject_threshold?: number
+ notify_enabled?: boolean
+ notify_emails?: string[]
+ notify_mode?: string
+ notify_on_flagged?: boolean
+ reply_from?: string
+ reply_from_name?: string
+ retention_days?: number
+}
+
+export interface MessageListParams {
+ page?: number
+ size?: number
+ form_id?: number
+ status?: string
+ state?: string
+ unread?: boolean
+ q?: string
+ after?: string
+ before?: string
+}
+
+export interface FilterPayload {
+ form_id?: number | null
+ kind?: string
+ pattern?: string
+ action?: string
+ score?: number
+ fields?: string[]
+ case_sensitive?: boolean
+ enabled?: boolean
+ note?: string
+}
+
+export interface FilterTestResult {
+ scanned: number
+ matched: number
+ samples: Array<{
+ message_uuid: string
+ sender_email: string
+ subject: string
+ excerpt: string
+ }>
+}
+
+export interface MessageAnalytics {
+ daily: Array<{ day: string; total: number; spam: number }>
+ total: number
+ spam: number
+}
+
+export const formsApi = {
+ list(params: { page?: number; size?: number } = {}) {
+ return api.get<PaginatedResponse<Form>>('/workspaces/current/forms', {
+ params: { page: 0, size: 20, ...params },
+ })
+ },
+ get(id: number) {
+ return api.get<ApiResponse<Form>>(`/workspaces/current/forms/${id}`)
+ },
+ create(payload: FormPayload) {
+ return api.post<ApiResponse<Form>>('/workspaces/current/forms', payload)
+ },
+ update(id: number, payload: FormPayload) {
+ return api.put<ApiResponse<Form>>(`/workspaces/current/forms/${id}`, payload)
+ },
+ delete(id: number) {
+ return api.delete<ApiResponse<void>>(`/workspaces/current/forms/${id}`)
+ },
+ rotateKey(id: number) {
+ return api.post<ApiResponse<Form>>(`/workspaces/current/forms/${id}/rotate-key`)
+ },
+ snippet(id: number) {
+ return api.get<ApiResponse<FormSnippet>>(`/workspaces/current/forms/${id}/snippet`)
+ },
+}
+
+export const messagesApi = {
+ list(params: MessageListParams = {}) {
+ return api.get<PaginatedResponse<Message>>('/workspaces/current/messages', {
+ params: { page: 0, size: 20, ...params },
+ })
+ },
+ get(uuid: string) {
+ return api.get<ApiResponse<Message>>(`/workspaces/current/messages/${uuid}`)
+ },
+ delete(uuid: string) {
+ return api.delete<ApiResponse<void>>(`/workspaces/current/messages/${uuid}`)
+ },
+ reply(uuid: string, payload: { subject?: string; html?: string; text?: string }) {
+ return api.post<ApiResponse<MessageReply>>(`/workspaces/current/messages/${uuid}/reply`, payload)
+ },
+ setState(uuid: string, payload: { state: string; read?: boolean }) {
+ return api.put<ApiResponse<Message>>(`/workspaces/current/messages/${uuid}/state`, payload)
+ },
+ assign(uuid: string, userId: number | null) {
+ return api.put<ApiResponse<Message>>(`/workspaces/current/messages/${uuid}/assign`, {
+ user_id: userId,
+ })
+ },
+ markSpam(uuid: string, payload: { create_filter?: boolean; pattern?: string; kind?: string } = {}) {
+ return api.post<ApiResponse<Message>>(`/workspaces/current/messages/${uuid}/spam`, payload)
+ },
+ markNotSpam(uuid: string) {
+ return api.post<ApiResponse<Message>>(`/workspaces/current/messages/${uuid}/not-spam`)
+ },
+ stats() {
+ return api.get<ApiResponse<MessageStats>>('/workspaces/current/messages/stats')
+ },
+ analytics(days = 30) {
+ return api.get<ApiResponse<MessageAnalytics>>('/workspaces/current/messages/analytics', {
+ params: { days },
+ })
+ },
+ attachmentUrl(uuid: string, idx: number) {
+ const ws = workspaceParam()
+ return `/api/v1/workspaces/current/messages/${uuid}/attachments/${idx}${ws ? `?${ws}` : ''}`
+ },
+ streamUrl() {
+ const ws = workspaceParam()
+ return `/api/v1/workspaces/current/message-stream${ws ? `?${ws}` : ''}`
+ },
+}
+
+export const messageFiltersApi = {
+ list(params: { page?: number; size?: number } = {}) {
+ return api.get<PaginatedResponse<MessageFilterRule>>('/workspaces/current/message-filters', {
+ params: { page: 0, size: 50, ...params },
+ })
+ },
+ create(payload: FilterPayload) {
+ return api.post<ApiResponse<MessageFilterRule>>('/workspaces/current/message-filters', payload)
+ },
+ update(id: number, payload: FilterPayload) {
+ return api.put<ApiResponse<MessageFilterRule>>(`/workspaces/current/message-filters/${id}`, payload)
+ },
+ delete(id: number) {
+ return api.delete<ApiResponse<void>>(`/workspaces/current/message-filters/${id}`)
+ },
+ test(payload: { kind: string; pattern: string; case_sensitive?: boolean; limit?: number }) {
+ return api.post<ApiResponse<FilterTestResult>>('/workspaces/current/message-filters/test', payload)
+ },
+}
diff --git a/web/src/api/types.ts b/web/src/api/types.ts
index 52a8edb..8675898 100644
--- a/web/src/api/types.ts
+++ b/web/src/api/types.ts
@@ -696,6 +696,7 @@ export interface UserSettings {
notify_bounce_alerts: boolean
notify_api_key_expiry: boolean
notify_workspace_activity: boolean
+ notify_new_message: boolean
created_at: string
updated_at: string
}
@@ -1113,3 +1114,132 @@ export interface CampaignAnalyticsData {
open_series: Array<{ time: string; count: number }>
click_series: Array<{ time: string; count: number }>
}
+
+export type FormStatus = 'active' | 'paused' | 'archived'
+export type NotifyMode = 'immediate' | 'hourly' | 'daily' | 'off'
+export type MessageStatus = 'received' | 'flagged' | 'quarantined' | 'rejected'
+export type MessageState = 'new' | 'open' | 'replied' | 'closed' | 'spam'
+export type MessageReplyKind = 'operator' | 'inbound'
+export type FilterKind = 'keyword' | 'phrase' | 'regex' | 'email' | 'domain' | 'ip'
+export type FilterAction = 'score' | 'flag' | 'quarantine' | 'reject' | 'allowlist'
+
+export interface Form {
+ id: number
+ uuid: string
+ workspace_id?: number | null
+ name: string
+ slug: string
+ description: string
+ public_key: string
+ status: FormStatus
+ allowed_origins: string[]
+ strict_origin: boolean
+ redirect_url: string
+ max_body_bytes: number
+ max_fields: number
+ allow_attachments: boolean
+ honeypot_field: string
+ require_nonce: boolean
+ min_fill_seconds: number
+ scan_enabled: boolean
+ flag_threshold: number
+ quarantine_threshold: number
+ reject_threshold: number
+ notify_enabled: boolean
+ notify_emails: string[]
+ notify_mode: NotifyMode
+ notify_on_flagged: boolean
+ reply_from: string
+ reply_from_name: string
+ retention_days: number
+ message_count: number
+ spam_count: number
+ last_message_at?: string | null
+ created_at: string
+ updated_at?: string | null
+}
+
+export interface MessageField {
+ key: string
+ value: string
+}
+
+export interface MessageReply {
+ id: number
+ uuid: string
+ message_id: number
+ kind: MessageReplyKind
+ author_id: number
+ from_addr: string
+ to_addr: string
+ subject: string
+ html_body: string
+ text_body: string
+ email_uuid?: string
+ created_at: string
+ author?: { id: number; name: string; email: string } | null
+}
+
+export interface Message {
+ id: number
+ uuid: string
+ workspace_id?: number | null
+ form_id: number
+ sender_email: string
+ sender_name: string
+ sender_phone: string
+ subject: string
+ body: string
+ client_ip?: string
+ user_agent?: string
+ referer?: string
+ origin?: string
+ status: MessageStatus
+ state: MessageState
+ spam_score: number
+ scan_reasons: string[] | null
+ notified_at?: string | null
+ assigned_to_id?: number | null
+ read_at?: string | null
+ replied_at?: string | null
+ reply_count: number
+ created_at: string
+ updated_at?: string | null
+ fields?: MessageField[]
+ attachments?: InboundAttachmentMeta[]
+ form?: Form | null
+ assigned_to?: { id: number; name: string; email: string } | null
+ replies?: MessageReply[]
+}
+
+export interface MessageFilterRule {
+ id: number
+ workspace_id?: number | null
+ form_id?: number | null
+ kind: FilterKind
+ pattern: string
+ action: FilterAction
+ score: number
+ fields: string[] | null
+ case_sensitive: boolean
+ enabled: boolean
+ hit_count: number
+ last_hit_at?: string | null
+ note: string
+ created_at: string
+ updated_at?: string | null
+}
+
+export interface MessageStats {
+ total: number
+ unread: number
+ spam: number
+ forms: number
+}
+
+export interface FormSnippet {
+ endpoint: string
+ public_key: string
+ html: string
+ fetch: string
+}
diff --git a/web/src/composables/apiError.ts b/web/src/composables/apiError.ts
new file mode 100644
index 0000000..d2c3ce8
--- /dev/null
+++ b/web/src/composables/apiError.ts
@@ -0,0 +1,5 @@
+export function apiMessage(e: any, fallback: string): string {
+ const data = e?.response?.data
+ const message = data?.error?.message || data?.error?.error || data?.message
+ return typeof message === 'string' && message.trim() ? message : fallback
+}
diff --git a/web/src/layouts/DashboardLayout.vue b/web/src/layouts/DashboardLayout.vue
index 11daee6..abfb9c0 100644
--- a/web/src/layouts/DashboardLayout.vue
+++ b/web/src/layouts/DashboardLayout.vue
@@ -166,6 +166,15 @@ const navSections: NavSection[] = [
title: 'Inbound',
items: [
{ name: 'Inbound Emails', path: '/inbound-emails', icon: 'inbox' },
+ {
+ name: 'Messages',
+ path: '/messages',
+ icon: 'message-square',
+ children: [
+ { name: 'Forms', path: '/forms', icon: 'edit-3' },
+ { name: 'Spam Filters', path: '/message-filters', icon: 'shield' },
+ ],
+ },
],
},
{
@@ -368,6 +377,7 @@ function getIcon(name: string): string {
'pie-chart': '<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M16.5 11.4A7.5 7.5 0 116.6 1.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M16.5 9A7.5 7.5 0 009 1.5V9h7.5z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',
'zap': '<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M9.75 1.5L3 10.5h5.25L8.25 16.5 15 7.5H9.75l0-6z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',
'code': '<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M12 4.5L16.5 9 12 13.5M6 4.5L1.5 9 6 13.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',
+ 'message-square': '<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M15.75 11.25a1.5 1.5 0 01-1.5 1.5H5.25L2.25 15.75V3.75a1.5 1.5 0 011.5-1.5h10.5a1.5 1.5 0 011.5 1.5v7.5z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',
}
return icons[name] || ''
}
diff --git a/web/src/router/index.ts b/web/src/router/index.ts
index b3d510d..bc11c3b 100644
--- a/web/src/router/index.ts
+++ b/web/src/router/index.ts
@@ -61,6 +61,11 @@ const routes = [
{ path: 'emails/:id', name: 'email-detail', component: () => import('../views/emails/EmailDetail.vue'), meta: { title: 'Email' } },
{ path: 'inbound-emails', name: 'inbound-emails', component: () => import('../views/inbound/InboundEmails.vue'), meta: { title: 'Inbound Emails' } },
{ path: 'inbound-emails/:id', name: 'inbound-email-detail', component: () => import('../views/inbound/InboundEmailDetail.vue'), meta: { title: 'Inbound Email' } },
+ { path: 'messages', name: 'messages', component: () => import('../views/messages/Messages.vue'), meta: { title: 'Messages' } },
+ { path: 'messages/:id', name: 'message-detail', component: () => import('../views/messages/MessageDetail.vue'), meta: { title: 'Message' } },
+ { path: 'message-filters', name: 'message-filters', component: () => import('../views/messages/MessageFilters.vue'), meta: { title: 'Spam Filters' } },
+ { path: 'forms', name: 'forms', component: () => import('../views/forms/Forms.vue'), meta: { title: 'Forms' } },
+ { path: 'forms/:id', name: 'form-detail', component: () => import('../views/forms/FormDetail.vue'), meta: { title: 'Form' } },
{ path: 'templates', name: 'templates', component: () => import('../views/templates/Templates.vue'), meta: { title: 'Templates' } },
{ path: 'templates/preview', name: 'template-preview-general', component: () => import('../views/emails/EmailPreview.vue'), meta: { title: 'Template Preview' } },
{ path: 'templates/:id/preview', name: 'template-preview', component: () => import('../views/templates/TemplatePreview.vue'), meta: { title: 'Template Preview' } },
diff --git a/web/src/views/forms/FormDetail.vue b/web/src/views/forms/FormDetail.vue
new file mode 100644
index 0000000..3040a20
--- /dev/null
+++ b/web/src/views/forms/FormDetail.vue
@@ -0,0 +1,334 @@
+<script setup lang="ts">
+import { computed, onMounted, ref } from "vue";
+import { useRoute, useRouter } from "vue-router";
+import { formsApi } from "../../api/messages";
+import { useNotificationStore } from "../../stores/notification";
+import { apiMessage } from "../../composables/apiError";
+import type { Form, FormSnippet } from "../../api/types";
+
+const route = useRoute();
+const router = useRouter();
+const notify = useNotificationStore();
+const id = Number(route.params.id);
+
+const loading = ref(true);
+const saving = ref(false);
+const form = ref<Form | null>(null);
+const snippet = ref<FormSnippet | null>(null);
+const loadFailed = ref(false);
+const tab = ref<"setup" | "spam" | "notifications" | "embed">("setup");
+
+const originsText = ref("");
+const notifyText = ref("");
+
+async function load() {
+ loading.value = true;
+ try {
+ const [formRes, snippetRes] = await Promise.all([formsApi.get(id), formsApi.snippet(id)]);
+ form.value = formRes.data.data;
+ snippet.value = snippetRes.data.data;
+ originsText.value = (formRes.data.data.allowed_origins || []).join(", ");
+ notifyText.value = (formRes.data.data.notify_emails || []).join(", ");
+ } catch (e: any) {
+ loadFailed.value = true;
+ notify.error(apiMessage(e, "Failed to load form"));
+ } finally {
+ loading.value = false;
+ }
+}
+
+function splitList(value: string) {
+ return value
+ .split(/[\s,]+/)
+ .map((v) => v.trim())
+ .filter(Boolean);
+}
+
+async function save() {
+ if (!form.value) return;
+ saving.value = true;
+ try {
+ const res = await formsApi.update(id, {
+ name: form.value.name,
+ description: form.value.description,
+ status: form.value.status,
+ allowed_origins: splitList(originsText.value),
+ strict_origin: form.value.strict_origin,
+ redirect_url: form.value.redirect_url,
+ allow_attachments: form.value.allow_attachments,
+ honeypot_field: form.value.honeypot_field,
+ require_nonce: form.value.require_nonce,
+ min_fill_seconds: form.value.min_fill_seconds,
+ scan_enabled: form.value.scan_enabled,
+ flag_threshold: form.value.flag_threshold,
+ quarantine_threshold: form.value.quarantine_threshold,
+ reject_threshold: form.value.reject_threshold,
+ notify_enabled: form.value.notify_enabled,
+ notify_emails: splitList(notifyText.value),
+ notify_mode: form.value.notify_mode,
+ notify_on_flagged: form.value.notify_on_flagged,
+ reply_from: form.value.reply_from,
+ reply_from_name: form.value.reply_from_name,
+ retention_days: form.value.retention_days,
+ });
+ form.value = res.data.data;
+ notify.success("Form saved.");
+ } catch (e: any) {
+ notify.error(apiMessage(e, "Failed to save form"));
+ } finally {
+ saving.value = false;
+ }
+}
+
+async function rotateKey() {
+ if (!confirm("Rotate the public key? Existing embeds stop working immediately.")) return;
+ saving.value = true;
+ try {
+ const res = await formsApi.rotateKey(id);
+ form.value = res.data.data;
+ const snippetRes = await formsApi.snippet(id);
+ snippet.value = snippetRes.data.data;
+ notify.success("Public key rotated. Update your embed code.");
+ } catch (e: any) {
+ notify.error(apiMessage(e, "Failed to rotate key"));
+ } finally {
+ saving.value = false;
+ }
+}
+
+async function remove() {
+ if (!confirm("Delete this form? Its messages are deleted too.")) return;
+ try {
+ await formsApi.delete(id);
+ router.push("/forms");
+ } catch (e: any) {
+ notify.error(apiMessage(e, "Failed to delete form"));
+ }
+}
+
+function copy(text: string) {
+ navigator.clipboard?.writeText(text);
+ notify.success("Copied to clipboard.");
+}
+
+const endpoint = computed(() => snippet.value?.endpoint || "");
+
+onMounted(load);
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <h1>{{ form?.name || "Form" }}</h1>
+ <div style="display: flex; gap: 8px">
+ <router-link
+ v-if="form"
+ :to="`/messages?form_id=${form.id}`"
+ class="btn btn-secondary"
+ >View messages</router-link>
+ <button class="btn btn-danger" @click="remove">Delete</button>
+ <button class="btn btn-secondary" @click="router.push('/forms')">Back</button>
+ </div>
+ </div>
+
+ <div v-if="loading" class="loading-page">
+ <div class="spinner"></div>
+ </div>
+
+ <div v-else-if="loadFailed" class="card">
+ <div class="empty-state">
+ <h3>Could not load this form</h3>
+ <p>It may have been deleted, or it belongs to another workspace.</p>
+ <button class="btn btn-secondary" @click="router.push('/forms')">Back to forms</button>
+ </div>
+ </div>
+
+ <template v-else-if="form">
+ <div class="card" style="margin-bottom: 20px">
+ <div class="card-body" style="display: flex; gap: 8px; flex-wrap: wrap">
+ <button
+ v-for="t in (['setup', 'spam', 'notifications', 'embed'] as const)"
+ :key="t"
+ class="btn"
+ :class="tab === t ? 'btn-primary' : 'btn-secondary'"
+ @click="tab = t"
+ >
+ {{ t }}
+ </button>
+ </div>
+ </div>
+
+ <div v-show="tab === 'setup'" class="card" style="margin-bottom: 20px">
+ <div class="card-header"><h2>Setup</h2></div>
+ <div class="card-body">
+ <div class="form-group">
+ <label class="form-label">Name</label>
+ <input v-model="form.name" class="form-input" />
+ </div>
+ <div class="form-group">
+ <label class="form-label">Description</label>
+ <input v-model="form.description" class="form-input" />
+ </div>
+ <div class="form-group">
+ <label class="form-label">Status</label>
+ <select v-model="form.status" class="form-select">
+ <option value="active">Active</option>
+ <option value="paused">Paused</option>
+ <option value="archived">Archived</option>
+ </select>
+ </div>
+ <div class="form-group">
+ <label class="form-label">Allowed origins</label>
+ <input v-model="originsText" class="form-input" placeholder="https://example.com" />
+ <small class="muted">
+ Comma separated. Blank accepts any origin. A plain HTML form post is a CORS
+ simple request, so this is a spam speed bump, not authentication.
+ </small>
+ </div>
+ <div class="form-group">
+ <label class="checkbox-label">
+ <input v-model="form.strict_origin" type="checkbox" />
+ Reject submissions with no Origin header
+ </label>
+ </div>
+ <div class="form-group">
+ <label class="form-label">Redirect after submit</label>
+ <input v-model="form.redirect_url" class="form-input" placeholder="https://example.com/thanks" />
+ </div>
+ <div class="form-group">
+ <label class="form-label">Honeypot field name</label>
+ <input v-model="form.honeypot_field" class="form-input" />
+ </div>
+ <div class="form-group">
+ <label class="checkbox-label">
+ <input v-model="form.require_nonce" type="checkbox" />
+ Require a signed nonce (blocks scripted posts, needs the JS snippet)
+ </label>
+ </div>
+ <div class="form-group">
+ <label class="form-label">Minimum fill time (seconds)</label>
+ <input v-model.number="form.min_fill_seconds" type="number" class="form-input" min="0" max="120" />
+ </div>
+ <div class="form-group">
+ <label class="checkbox-label">
+ <input v-model="form.allow_attachments" type="checkbox" />
+ Accept file attachments
+ </label>
+ </div>
+ <div class="form-group">
+ <label class="form-label">Reply sender</label>
+ <input v-model="form.reply_from" class="form-input" placeholder="[email protected]" />
+ <small class="muted">Must be on a verified domain in this workspace.</small>
+ </div>
+ <div class="form-group">
+ <label class="form-label">Reply sender name</label>
+ <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>
+ <input v-model.number="form.retention_days" type="number" class="form-input" min="0" />
+ </div>
+ </div>
+ </div>
+
+ <div v-show="tab === 'spam'" class="card" style="margin-bottom: 20px">
+ <div class="card-header">
+ <h2>Spam scanning</h2>
+ <router-link to="/message-filters" class="btn btn-secondary">Manage filters</router-link>
+ </div>
+ <div class="card-body">
+ <div class="form-group">
+ <label class="checkbox-label">
+ <input v-model="form.scan_enabled" type="checkbox" />
+ Scan submissions
+ </label>
+ </div>
+ <div class="form-group">
+ <label class="form-label">Flag at score</label>
+ <input v-model.number="form.flag_threshold" type="number" step="0.5" class="form-input" />
+ <small class="muted">Stored and notified, marked for review.</small>
+ </div>
+ <div class="form-group">
+ <label class="form-label">Quarantine at score</label>
+ <input v-model.number="form.quarantine_threshold" type="number" step="0.5" class="form-input" />
+ <small class="muted">Stored, no notification.</small>
+ </div>
+ <div class="form-group">
+ <label class="form-label">Reject at score</label>
+ <input v-model.number="form.reject_threshold" type="number" step="0.5" class="form-input" />
+ <small class="muted">
+ Stored for audit but never notified, never dispatched, and hidden from the
+ inbox. The submitter still receives a normal acknowledgement.
+ </small>
+ </div>
+ </div>
+ </div>
+
+ <div v-show="tab === 'notifications'" class="card" style="margin-bottom: 20px">
+ <div class="card-header"><h2>Notifications</h2></div>
+ <div class="card-body">
+ <div class="form-group">
+ <label class="checkbox-label">
+ <input v-model="form.notify_enabled" type="checkbox" />
+ Notify on new messages
+ </label>
+ </div>
+ <div class="form-group">
+ <label class="form-label">Recipients</label>
+ <input v-model="notifyText" class="form-input" placeholder="[email protected]" />
+ <small class="muted">Blank notifies workspace owners and admins.</small>
+ </div>
+ <div class="form-group">
+ <label class="form-label">Delivery</label>
+ <select v-model="form.notify_mode" class="form-select">
+ <option value="immediate">Immediate</option>
+ <option value="hourly">Hourly digest</option>
+ <option value="daily">Daily digest</option>
+ <option value="off">Off</option>
+ </select>
+ </div>
+ <div class="form-group">
+ <label class="checkbox-label">
+ <input v-model="form.notify_on_flagged" type="checkbox" />
+ Also notify for flagged messages
+ </label>
+ </div>
+ </div>
+ </div>
+
+ <div v-show="tab === 'embed'" class="card" style="margin-bottom: 20px">
+ <div class="card-header">
+ <h2>Embed</h2>
+ <button class="btn btn-secondary" @click="rotateKey">Rotate key</button>
+ </div>
+ <div class="card-body">
+ <div class="form-group">
+ <label class="form-label">Endpoint</label>
+ <div style="display: flex; gap: 8px">
+ <input class="form-input" :value="endpoint" readonly />
+ <button class="btn btn-secondary" @click="copy(endpoint)">Copy</button>
+ </div>
+ </div>
+ <div class="form-group">
+ <label class="form-label">HTML form</label>
+ <pre style="overflow-x: auto; padding: 12px; border-radius: 8px; background: var(--bg-subtle)">{{ snippet?.html }}</pre>
+ <button class="btn btn-secondary" @click="copy(snippet?.html || '')">Copy HTML</button>
+ </div>
+ <div class="form-group">
+ <label class="form-label">fetch()</label>
+ <pre style="overflow-x: auto; padding: 12px; border-radius: 8px; background: var(--bg-subtle)">{{ snippet?.fetch }}</pre>
+ <button class="btn btn-secondary" @click="copy(snippet?.fetch || '')">Copy JS</button>
+ </div>
+ </div>
+ </div>
+
+ <div class="card">
+ <div class="card-body">
+ <button class="btn btn-primary" :disabled="saving" @click="save">
+ {{ saving ? "Saving..." : "Save changes" }}
+ </button>
+ </div>
+ </div>
+ </template>
+ </div>
+</template>
diff --git a/web/src/views/forms/Forms.vue b/web/src/views/forms/Forms.vue
new file mode 100644
index 0000000..87f630c
--- /dev/null
+++ b/web/src/views/forms/Forms.vue
@@ -0,0 +1,196 @@
+<script setup lang="ts">
+import { ref } from "vue";
+import { useRouter } from "vue-router";
+import { formsApi } from "../../api/messages";
+import { useNotificationStore } from "../../stores/notification";
+import { apiMessage } from "../../composables/apiError";
+import type { Form } from "../../api/types";
+import Pagination from "../../components/Pagination.vue";
+import { usePagination } from "../../composables/usePagination";
+
+const router = useRouter();
+const notify = useNotificationStore();
+const loading = ref(true);
+const featureDisabled = ref(false);
+const forms = ref<Form[]>([]);
+
+const showCreate = ref(false);
+const creating = ref(false);
+const newName = ref("");
+const newOrigins = ref("");
+const newNotify = ref("");
+
+const { pageable, goToPage } = usePagination(async (page) => {
+ loading.value = true;
+ try {
+ const res = await formsApi.list({ page });
+ forms.value = res.data.data;
+ pageable.value = res.data.pageable;
+ featureDisabled.value = false;
+ } catch (e: any) {
+ if (e?.response?.status === 404) {
+ featureDisabled.value = true;
+ } else {
+ notify.error(apiMessage(e, "Failed to load forms"));
+ }
+ } finally {
+ loading.value = false;
+ }
+});
+
+function openCreate() {
+ newName.value = "";
+ newOrigins.value = "";
+ newNotify.value = "";
+ showCreate.value = true;
+}
+
+async function createForm() {
+ if (!newName.value.trim()) return;
+ creating.value = true;
+ try {
+ const res = await formsApi.create({
+ name: newName.value.trim(),
+ allowed_origins: splitList(newOrigins.value),
+ notify_emails: splitList(newNotify.value),
+ });
+ showCreate.value = false;
+ router.push(`/forms/${res.data.data.id}`);
+ } catch (e: any) {
+ notify.error(apiMessage(e, "Failed to create form"));
+ } finally {
+ creating.value = false;
+ }
+}
+
+function splitList(value: string) {
+ return value
+ .split(/[\s,]+/)
+ .map((v) => v.trim())
+ .filter(Boolean);
+}
+
+function statusBadgeClass(status: string) {
+ switch (status) {
+ case "active":
+ return "badge badge-success";
+ case "paused":
+ return "badge badge-warning";
+ default:
+ return "badge badge-secondary";
+ }
+}
+
+function formatDate(date: string | null | undefined) {
+ if (!date) return "-";
+ return new Date(date).toLocaleString();
+}
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <h1>Forms</h1>
+ <div style="display: flex; gap: 8px">
+ <router-link to="/messages" class="btn btn-secondary">Messages</router-link>
+ <button class="btn btn-primary" @click="openCreate">New form</button>
+ </div>
+ </div>
+
+ <div v-if="loading" class="loading-page">
+ <div class="spinner"></div>
+ </div>
+
+ <div v-else-if="featureDisabled" class="card">
+ <div class="empty-state">
+ <h3>Web form messages are disabled</h3>
+ <p>
+ Ask your administrator to enable them by setting
+ <code>POSTA_MESSAGES_ENABLED=true</code>.
+ </p>
+ </div>
+ </div>
+
+ <div v-else class="card">
+ <div v-if="forms.length === 0" class="empty-state">
+ <h3>No forms yet</h3>
+ <p>Create a form to get an endpoint you can post your website's contact form to.</p>
+ <button class="btn btn-primary" @click="openCreate">New form</button>
+ </div>
+
+ <template v-else>
+ <div class="table-wrapper">
+ <table>
+ <thead>
+ <tr>
+ <th>Name</th>
+ <th>Public key</th>
+ <th>Status</th>
+ <th>Messages</th>
+ <th>Spam</th>
+ <th>Last message</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr
+ v-for="form in forms"
+ :key="form.id"
+ style="cursor: pointer"
+ @click="router.push(`/forms/${form.id}`)"
+ >
+ <td>{{ form.name }}</td>
+ <td><code style="font-size: 12px">{{ form.public_key }}</code></td>
+ <td><span :class="statusBadgeClass(form.status)">{{ form.status }}</span></td>
+ <td>{{ form.message_count }}</td>
+ <td>{{ form.spam_count }}</td>
+ <td>{{ formatDate(form.last_message_at) }}</td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ <Pagination :pageable="pageable" @page="goToPage" />
+ </template>
+ </div>
+
+ <div v-if="showCreate" class="modal-overlay" @click.self="showCreate = false">
+ <div class="modal">
+ <div class="modal-header">
+ <h3>New form</h3>
+ </div>
+ <div class="modal-body">
+ <div class="form-group">
+ <label class="form-label">Name</label>
+ <input v-model="newName" class="form-input" placeholder="Contact form" />
+ </div>
+ <div class="form-group">
+ <label class="form-label">Allowed origins</label>
+ <input
+ v-model="newOrigins"
+ class="form-input"
+ placeholder="https://example.com, https://www.example.com"
+ />
+ <small class="muted">
+ Leave blank to accept any origin. Browsers only enforce this for scripted
+ requests, so treat it as a spam speed bump rather than authentication.
+ </small>
+ </div>
+ <div class="form-group">
+ <label class="form-label">Notification recipients</label>
+ <input
+ v-model="newNotify"
+ class="form-input"
+ placeholder="[email protected]"
+ />
+ <small class="muted">Leave blank to notify workspace owners and admins.</small>
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button class="btn btn-secondary" @click="showCreate = false">Cancel</button>
+ <button class="btn btn-primary" :disabled="creating || !newName.trim()" @click="createForm">
+ {{ creating ? "Creating..." : "Create form" }}
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+</template>
diff --git a/web/src/views/messages/MessageDetail.vue b/web/src/views/messages/MessageDetail.vue
new file mode 100644
index 0000000..476d5b9
--- /dev/null
+++ b/web/src/views/messages/MessageDetail.vue
@@ -0,0 +1,655 @@
+<script setup lang="ts">
+import { computed, onMounted, ref } from "vue";
+import { useRoute, useRouter } from "vue-router";
+import { messagesApi } from "../../api/messages";
+import { useNotificationStore } from "../../stores/notification";
+import { apiMessage } from "../../composables/apiError";
+import type { Message } from "../../api/types";
+
+const route = useRoute();
+const router = useRouter();
+const notify = useNotificationStore();
+
+const loading = ref(true);
+const message = ref<Message | null>(null);
+const loadFailed = ref(false);
+
+const replySubject = ref("");
+const replyText = ref("");
+const sending = ref(false);
+const busy = ref(false);
+
+const uuid = String(route.params.id);
+
+async function load() {
+ loading.value = true;
+ try {
+ const res = await messagesApi.get(uuid);
+ message.value = res.data.data;
+ replySubject.value = defaultReplySubject(res.data.data.subject);
+ } catch (e: any) {
+ loadFailed.value = true;
+ notify.error(apiMessage(e, "Failed to load message"));
+ } finally {
+ loading.value = false;
+ }
+}
+
+function defaultReplySubject(subject: string) {
+ const trimmed = (subject || "").trim();
+ if (!trimmed) return "Re: your message";
+ return /^re:/i.test(trimmed) ? trimmed : `Re: ${trimmed}`;
+}
+
+async function sendReply() {
+ if (!message.value || !replyText.value.trim()) return;
+ sending.value = true;
+ try {
+ await messagesApi.reply(uuid, {
+ subject: replySubject.value,
+ text: replyText.value,
+ html: textToHtml(replyText.value),
+ });
+ replyText.value = "";
+ notify.success("Reply sent.");
+ await load();
+ } catch (e: any) {
+ notify.error(apiMessage(e, "Failed to send reply"));
+ } finally {
+ sending.value = false;
+ }
+}
+
+function textToHtml(text: string) {
+ const escaped = text
+ .replace(/&/g, "&amp;")
+ .replace(/</g, "&lt;")
+ .replace(/>/g, "&gt;");
+ return `<div style="white-space:pre-wrap">${escaped}</div>`;
+}
+
+async function setState(state: string) {
+ busy.value = true;
+ try {
+ const res = await messagesApi.setState(uuid, { state });
+ message.value = res.data.data;
+ } catch (e: any) {
+ notify.error(apiMessage(e, "Failed to update message"));
+ } finally {
+ busy.value = false;
+ }
+}
+
+async function markSpam(createFilter: boolean, kind = "domain") {
+ busy.value = true;
+ try {
+ const res = await messagesApi.markSpam(uuid, { create_filter: createFilter, kind });
+ message.value = res.data.data;
+ notify.success(createFilter ? "Marked as spam and filter created." : "Marked as spam.");
+ } catch (e: any) {
+ notify.error(apiMessage(e, "Failed to mark as spam"));
+ } finally {
+ busy.value = false;
+ }
+}
+
+async function markNotSpam() {
+ busy.value = true;
+ try {
+ const res = await messagesApi.markNotSpam(uuid);
+ message.value = res.data.data;
+ notify.success("Spam verdict cleared.");
+ } catch (e: any) {
+ notify.error(apiMessage(e, "Failed to clear the spam verdict"));
+ } finally {
+ busy.value = false;
+ }
+}
+
+async function remove() {
+ if (!confirm("Delete this message permanently?")) return;
+ busy.value = true;
+ try {
+ await messagesApi.delete(uuid);
+ router.push("/messages");
+ } catch (e: any) {
+ notify.error(apiMessage(e, "Failed to delete message"));
+ busy.value = false;
+ }
+}
+
+const BODY_KEYS = [
+ "message",
+ "body",
+ "comments",
+ "comment",
+ "content",
+ "description",
+ "your-message",
+];
+
+const SCAN_REASON_LABELS: Record<string, string> = {
+ honeypot: "Honeypot field was filled in",
+ nonce_invalid: "Anti-bot token missing, expired, or reused",
+ sender_suppressed: "Sender is on the suppression list",
+ sender_unparseable: "Sender address does not parse",
+ disposable_email: "Disposable email domain",
+ url_shortener: "Contains a URL shortener",
+ body_too_short: "Body is unusually short",
+ body_too_long: "Body is unusually long",
+ excessive_caps: "Mostly uppercase",
+ embedded_markup: "Contains HTML or BBCode markup",
+ embedded_script: "Contains a script tag or javascript: URL",
+ bot_user_agent: "Submitted by a scripted client",
+};
+
+const showRaw = ref(false);
+
+const bodyField = computed(() => {
+ const fields = message.value?.fields ?? [];
+ return fields.find((f) => BODY_KEYS.includes(f.key.trim().toLowerCase())) ?? null;
+});
+
+const detailFields = computed(() =>
+ (message.value?.fields ?? []).filter((f) => f !== bodyField.value)
+);
+
+const bodyText = computed(() => bodyField.value?.value || message.value?.body || "");
+
+const bodyLabel = computed(() =>
+ bodyField.value ? humanizeKey(bodyField.value.key) : "Message"
+);
+
+const fieldCount = computed(() => message.value?.fields?.length ?? 0);
+
+const rawFields = computed(() =>
+ JSON.stringify(
+ Object.fromEntries((message.value?.fields ?? []).map((f) => [f.key, f.value])),
+ null,
+ 2
+ )
+);
+
+function humanizeKey(key: string) {
+ const cleaned = key
+ .replace(/^_+/, "")
+ .replace(/^your[-_\s]+/i, "")
+ .replace(/[_-]+/g, " ")
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
+ .trim();
+ if (!cleaned) return key;
+ return cleaned.charAt(0).toUpperCase() + cleaned.slice(1);
+}
+
+function valueKind(value: string): "email" | "url" | "phone" | "text" {
+ const v = value.trim();
+ if (/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)) return "email";
+ if (/^https?:\/\/\S+$/i.test(v)) return "url";
+ if (/^\+?\d[\d\s().\/-]{5,}$/.test(v)) return "phone";
+ return "text";
+}
+
+function scanReasonLabel(reason: string) {
+ if (SCAN_REASON_LABELS[reason]) return SCAN_REASON_LABELS[reason];
+ const [head, ...rest] = reason.split(":");
+ const tail = rest.join(":");
+ switch (head) {
+ case "links":
+ return `${tail} links in the message`;
+ case "repeat_ip":
+ return `${tail} submissions from this IP in the last hour`;
+ case "repeat_sender":
+ return `${tail} submissions from this sender in the last hour`;
+ case "filter":
+ return rest.length > 1
+ ? `Matched a ${rest[0]} filter: ${rest.slice(1).join(":")}`
+ : `Matched a ${tail} filter`;
+ default:
+ return reason;
+ }
+}
+
+async function copyValue(value: string) {
+ try {
+ await navigator.clipboard.writeText(value);
+ notify.success("Copied to clipboard.");
+ } catch {
+ notify.error("Could not copy to clipboard.");
+ }
+}
+
+const canReply = computed(
+ () => !!message.value?.sender_email && message.value?.status !== "rejected"
+);
+const replyFromConfigured = computed(() => !!message.value?.form?.reply_from);
+const scanReasons = computed(() => message.value?.scan_reasons || []);
+
+function statusBadgeClass(value: string) {
+ switch (value) {
+ case "received":
+ return "badge badge-success";
+ case "flagged":
+ return "badge badge-warning";
+ default:
+ return "badge badge-danger";
+ }
+}
+
+function senderLabel(m: Message) {
+ if (m.sender_name && m.sender_email) return `${m.sender_name} <${m.sender_email}>`;
+ return m.sender_email || m.sender_name || "unknown sender";
+}
+
+function formatDate(date: string | null | undefined) {
+ if (!date) return "-";
+ return new Date(date).toLocaleString();
+}
+
+function formatBytes(n: number) {
+ if (!n) return "0 B";
+ if (n < 1024) return `${n} B`;
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
+ return `${(n / (1024 * 1024)).toFixed(2)} MB`;
+}
+
+onMounted(load);
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <h1>Message</h1>
+ <div style="display: flex; gap: 8px">
+ <button v-if="message" class="btn btn-secondary" :disabled="busy" @click="setState('closed')">
+ Close
+ </button>
+ <button
+ v-if="message && message.status !== 'quarantined'"
+ class="btn btn-secondary"
+ :disabled="busy"
+ @click="markSpam(false)"
+ >
+ Mark spam
+ </button>
+ <button
+ v-if="message && message.status === 'quarantined'"
+ class="btn btn-secondary"
+ :disabled="busy"
+ @click="markNotSpam"
+ >
+ Not spam
+ </button>
+ <button class="btn btn-danger" :disabled="busy" @click="remove">Delete</button>
+ <button class="btn btn-secondary" @click="router.push('/messages')">Back</button>
+ </div>
+ </div>
+
+ <div v-if="loading" class="loading-page">
+ <div class="spinner"></div>
+ </div>
+
+ <div v-else-if="loadFailed" class="card">
+ <div class="empty-state">
+ <h3>Could not load this message</h3>
+ <p>It may have been deleted, or it belongs to another workspace.</p>
+ <button class="btn btn-secondary" @click="router.push('/messages')">Back to messages</button>
+ </div>
+ </div>
+
+ <template v-else-if="message">
+ <div class="card" style="margin-bottom: 24px">
+ <div class="card-header">
+ <h2>{{ message.subject || "(no subject)" }}</h2>
+ <div style="display: flex; gap: 8px">
+ <span :class="statusBadgeClass(message.status)">{{ message.status }}</span>
+ <span class="badge badge-secondary">{{ message.state }}</span>
+ </div>
+ </div>
+ <div class="card-body">
+ <table>
+ <tbody>
+ <tr>
+ <td style="font-weight: 600; width: 160px">From</td>
+ <td>{{ senderLabel(message) }}</td>
+ </tr>
+ <tr v-if="message.sender_phone">
+ <td style="font-weight: 600">Phone</td>
+ <td><a :href="`tel:${message.sender_phone}`">{{ message.sender_phone }}</a></td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600">Form</td>
+ <td>
+ <router-link v-if="message.form" :to="`/forms/${message.form.id}`">
+ {{ message.form.name }}
+ </router-link>
+ <span v-else>-</span>
+ </td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600">Received</td>
+ <td>{{ formatDate(message.created_at) }}</td>
+ </tr>
+ <tr v-if="message.origin">
+ <td style="font-weight: 600">Origin</td>
+ <td><code style="font-size: 12px">{{ message.origin }}</code></td>
+ </tr>
+ <tr v-if="message.client_ip">
+ <td style="font-weight: 600">Client IP</td>
+ <td><code style="font-size: 12px">{{ message.client_ip }}</code></td>
+ </tr>
+ <tr v-if="message.spam_score">
+ <td style="font-weight: 600">Spam score</td>
+ <td>{{ message.spam_score.toFixed(1) }}</td>
+ </tr>
+ <tr v-if="scanReasons.length">
+ <td style="font-weight: 600">Scan reasons</td>
+ <td class="scan-reasons">
+ <span
+ v-for="reason in scanReasons"
+ :key="reason"
+ class="badge badge-warning"
+ :title="reason"
+ >{{ scanReasonLabel(reason) }}</span>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ </div>
+
+ <div class="card" style="margin-bottom: 24px">
+ <div class="card-header">
+ <h2>Submission</h2>
+ <div class="submission-actions">
+ <span v-if="fieldCount" class="badge badge-neutral">
+ {{ fieldCount }} field{{ fieldCount === 1 ? "" : "s" }}
+ </span>
+ <button
+ v-if="fieldCount"
+ class="btn btn-secondary btn-sm"
+ @click="showRaw = !showRaw"
+ >
+ {{ showRaw ? "Formatted" : "Raw" }}
+ </button>
+ </div>
+ </div>
+
+ <div class="card-body">
+ <pre v-if="showRaw" class="raw-fields">{{ rawFields }}</pre>
+
+ <template v-else>
+ <div v-if="bodyText" class="submission-body">
+ <div class="submission-label">{{ bodyLabel }}</div>
+ <div class="submission-body-text">{{ bodyText }}</div>
+ </div>
+
+ <dl v-if="detailFields.length" class="field-grid">
+ <template v-for="(field, idx) in detailFields" :key="`${idx}-${field.key}`">
+ <dt :title="field.key">{{ humanizeKey(field.key) }}</dt>
+ <dd>
+ <span v-if="!field.value.trim()" class="field-empty">—</span>
+
+ <span v-else class="field-value">
+ <a
+ v-if="valueKind(field.value) === 'email'"
+ :href="`mailto:${field.value.trim()}`"
+ >{{ field.value }}</a>
+ <a
+ v-else-if="valueKind(field.value) === 'phone'"
+ :href="`tel:${field.value.trim()}`"
+ >{{ field.value }}</a>
+ <a
+ v-else-if="valueKind(field.value) === 'url'"
+ :href="field.value.trim()"
+ target="_blank"
+ rel="noopener noreferrer nofollow"
+ >{{ field.value }}</a>
+ <span v-else>{{ field.value }}</span>
+
+ <button
+ class="field-copy"
+ type="button"
+ :title="`Copy ${humanizeKey(field.key)}`"
+ @click="copyValue(field.value)"
+ >Copy</button>
+ </span>
+ </dd>
+ </template>
+ </dl>
+
+ <div v-if="!bodyText && !detailFields.length" class="empty-state">
+ <h3>Nothing was submitted</h3>
+ <p>This submission arrived with no readable fields.</p>
+ </div>
+ </template>
+ </div>
+ </div>
+
+ <div
+ v-if="message.attachments && message.attachments.length"
+ class="card"
+ style="margin-bottom: 24px"
+ >
+ <div class="card-header"><h2>Attachments</h2></div>
+ <div class="card-body">
+ <ul style="list-style: none; padding: 0; margin: 0">
+ <li
+ v-for="(attachment, idx) in message.attachments"
+ :key="idx"
+ style="padding: 6px 0"
+ >
+ <a
+ :href="messagesApi.attachmentUrl(message.uuid, idx)"
+ target="_blank"
+ rel="noopener"
+ >{{ attachment.filename }}</a>
+ <span class="muted" style="margin-left: 8px">
+ {{ attachment.content_type }} · {{ formatBytes(attachment.size) }}
+ </span>
+ </li>
+ </ul>
+ </div>
+ </div>
+
+ <div v-if="message.replies && message.replies.length" class="card" style="margin-bottom: 24px">
+ <div class="card-header"><h2>Thread</h2></div>
+ <div class="card-body">
+ <div
+ v-for="reply in message.replies"
+ :key="reply.uuid"
+ 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 class="muted">{{ formatDate(reply.created_at) }}</span>
+ </div>
+ <div class="muted" style="font-size: 13px">{{ reply.subject }}</div>
+ <p style="white-space: pre-wrap; margin: 8px 0 0">{{ reply.text_body }}</p>
+ </div>
+ </div>
+ </div>
+
+ <div class="card">
+ <div class="card-header"><h2>Reply</h2></div>
+ <div class="card-body">
+ <div v-if="!canReply" class="empty-state">
+ <p>This message has no reply address, so it cannot be answered from here.</p>
+ </div>
+ <div v-else-if="!replyFromConfigured" class="alert alert-warning">
+ Set a reply sender address on
+ <router-link v-if="message.form" :to="`/forms/${message.form.id}`">this form</router-link>
+ <span v-else>this form</span>
+ before replying. It must use a verified domain in this workspace.
+ </div>
+ <template v-else>
+ <div class="form-group">
+ <label class="form-label">To</label>
+ <input class="form-input" :value="message.sender_email" disabled />
+ </div>
+ <div class="form-group">
+ <label class="form-label">Subject</label>
+ <input v-model="replySubject" class="form-input" />
+ </div>
+ <div class="form-group">
+ <label class="form-label">Message</label>
+ <textarea
+ v-model="replyText"
+ class="form-input"
+ rows="8"
+ placeholder="Write your reply..."
+ ></textarea>
+ </div>
+ <button
+ class="btn btn-primary"
+ :disabled="sending || !replyText.trim()"
+ @click="sendReply"
+ >
+ {{ sending ? "Sending..." : "Send reply" }}
+ </button>
+ </template>
+ </div>
+ </div>
+ </template>
+ </div>
+</template>
+
+<style scoped>
+.submission-actions {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+
+.btn-sm {
+ padding: 4px 10px;
+ font-size: 12px;
+}
+
+.submission-body {
+ margin-bottom: 20px;
+}
+
+.submission-label,
+.field-grid dt {
+ font-size: 11px;
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ font-weight: 600;
+ color: var(--text-tertiary);
+}
+
+.submission-label {
+ margin-bottom: 8px;
+}
+
+.submission-body-text {
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+ padding: 14px 16px;
+ border-radius: 8px;
+ background: var(--bg-secondary);
+ border: 1px solid var(--border-primary);
+ line-height: 1.65;
+ font-size: 14px;
+ color: var(--text-primary);
+}
+
+.field-grid {
+ display: grid;
+ grid-template-columns: minmax(140px, 220px) 1fr;
+ margin: 0;
+ border: 1px solid var(--border-primary);
+ border-radius: 8px;
+ overflow: hidden;
+}
+
+.field-grid dt {
+ padding: 11px 14px;
+ background: var(--bg-secondary);
+ border-bottom: 1px solid var(--border-secondary);
+ overflow-wrap: anywhere;
+}
+
+.field-grid dd {
+ margin: 0;
+ padding: 11px 14px;
+ font-size: 14px;
+ color: var(--text-primary);
+ border-bottom: 1px solid var(--border-secondary);
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+}
+
+.field-grid dt:last-of-type,
+.field-grid dd:last-of-type {
+ border-bottom: 0;
+}
+
+.field-value {
+ display: inline-flex;
+ align-items: baseline;
+ gap: 8px;
+ max-width: 100%;
+}
+
+.field-empty {
+ color: var(--text-muted);
+}
+
+.field-copy {
+ flex: none;
+ border: 0;
+ background: none;
+ padding: 0;
+ font: inherit;
+ font-size: 12px;
+ color: var(--text-muted);
+ cursor: pointer;
+ opacity: 0;
+ transition: opacity 0.12s ease, color 0.12s ease;
+}
+
+.field-grid dd:hover .field-copy,
+.field-copy:focus-visible {
+ opacity: 1;
+}
+
+.field-copy:hover {
+ color: var(--primary-600);
+ text-decoration: underline;
+}
+
+.raw-fields {
+ margin: 0;
+ padding: 16px;
+ border-radius: 8px;
+ background: var(--bg-secondary);
+ border: 1px solid var(--border-primary);
+ font-size: 13px;
+ line-height: 1.6;
+ color: var(--text-primary);
+ overflow-x: auto;
+}
+
+.scan-reasons {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+}
+
+@media (max-width: 640px) {
+ .field-grid {
+ grid-template-columns: 1fr;
+ }
+
+ .field-grid dt {
+ background: transparent;
+ border-bottom: 0;
+ padding-bottom: 0;
+ }
+
+ .field-copy {
+ opacity: 1;
+ }
+}
+</style>
diff --git a/web/src/views/messages/MessageFilters.vue b/web/src/views/messages/MessageFilters.vue
new file mode 100644
index 0000000..ac77255
--- /dev/null
+++ b/web/src/views/messages/MessageFilters.vue
@@ -0,0 +1,302 @@
+<script setup lang="ts">
+import { ref } from "vue";
+import { formsApi, messageFiltersApi, type FilterTestResult } from "../../api/messages";
+import { useNotificationStore } from "../../stores/notification";
+import { apiMessage } from "../../composables/apiError";
+import type { Form, MessageFilterRule } from "../../api/types";
+
+const notify = useNotificationStore();
+const loading = ref(true);
+const featureDisabled = ref(false);
+const filters = ref<MessageFilterRule[]>([]);
+const forms = ref<Form[]>([]);
+const saving = ref(false);
+
+const showModal = ref(false);
+const draft = ref({
+ form_id: 0,
+ kind: "keyword",
+ pattern: "",
+ action: "score",
+ score: 3,
+ case_sensitive: false,
+ note: "",
+});
+
+const testing = ref(false);
+const testResult = ref<FilterTestResult | null>(null);
+
+async function load() {
+ loading.value = true;
+ try {
+ const [filtersRes, formsRes] = await Promise.all([
+ messageFiltersApi.list(),
+ formsApi.list({ size: 100 }),
+ ]);
+ filters.value = filtersRes.data.data;
+ forms.value = formsRes.data.data;
+ featureDisabled.value = false;
+ } catch (e: any) {
+ if (e?.response?.status === 404) {
+ featureDisabled.value = true;
+ } else {
+ notify.error(apiMessage(e, "Failed to load filters"));
+ }
+ } finally {
+ loading.value = false;
+ }
+}
+
+function openCreate() {
+ draft.value = {
+ form_id: 0,
+ kind: "keyword",
+ pattern: "",
+ action: "score",
+ score: 3,
+ case_sensitive: false,
+ note: "",
+ };
+ testResult.value = null;
+ showModal.value = true;
+}
+
+async function create() {
+ if (!draft.value.pattern.trim()) return;
+ saving.value = true;
+ try {
+ await messageFiltersApi.create({
+ form_id: draft.value.form_id || null,
+ kind: draft.value.kind,
+ pattern: draft.value.pattern.trim(),
+ action: draft.value.action,
+ score: draft.value.score,
+ case_sensitive: draft.value.case_sensitive,
+ note: draft.value.note,
+ });
+ showModal.value = false;
+ notify.success("Filter created.");
+ await load();
+ } catch (e: any) {
+ notify.error(apiMessage(e, "Failed to create filter"));
+ } finally {
+ saving.value = false;
+ }
+}
+
+async function runTest() {
+ if (!draft.value.pattern.trim()) return;
+ testing.value = true;
+ testResult.value = null;
+ try {
+ const res = await messageFiltersApi.test({
+ kind: draft.value.kind,
+ pattern: draft.value.pattern.trim(),
+ case_sensitive: draft.value.case_sensitive,
+ });
+ testResult.value = res.data.data;
+ } catch (e: any) {
+ notify.error(apiMessage(e, "Test failed"));
+ } finally {
+ testing.value = false;
+ }
+}
+
+async function toggle(filter: MessageFilterRule) {
+ try {
+ const res = await messageFiltersApi.update(filter.id, { enabled: !filter.enabled });
+ Object.assign(filter, res.data.data);
+ } catch (e: any) {
+ notify.error(apiMessage(e, "Failed to update filter"));
+ }
+}
+
+async function remove(filter: MessageFilterRule) {
+ if (!confirm(`Delete the filter "${filter.pattern}"?`)) return;
+ try {
+ await messageFiltersApi.delete(filter.id);
+ filters.value = filters.value.filter((f) => f.id !== filter.id);
+ } catch (e: any) {
+ notify.error(apiMessage(e, "Failed to delete filter"));
+ }
+}
+
+function formName(formId: number | null | undefined) {
+ if (!formId) return "All forms";
+ return forms.value.find((f) => f.id === formId)?.name || `Form ${formId}`;
+}
+
+function actionBadgeClass(action: string) {
+ switch (action) {
+ case "reject":
+ return "badge badge-danger";
+ case "quarantine":
+ return "badge badge-danger";
+ case "flag":
+ return "badge badge-warning";
+ case "allowlist":
+ return "badge badge-success";
+ default:
+ return "badge badge-secondary";
+ }
+}
+
+function formatDate(date: string | null | undefined) {
+ if (!date) return "never";
+ return new Date(date).toLocaleString();
+}
+
+load();
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <h1>Spam Filters</h1>
+ <div style="display: flex; gap: 8px">
+ <router-link to="/messages" class="btn btn-secondary">Messages</router-link>
+ <button class="btn btn-primary" @click="openCreate">New filter</button>
+ </div>
+ </div>
+
+ <div v-if="loading" class="loading-page">
+ <div class="spinner"></div>
+ </div>
+
+ <div v-else-if="featureDisabled" class="card">
+ <div class="empty-state">
+ <h3>Web form messages are disabled</h3>
+ <p>
+ Ask your administrator to enable them by setting
+ <code>POSTA_MESSAGES_ENABLED=true</code>.
+ </p>
+ </div>
+ </div>
+
+ <div v-else class="card">
+ <div v-if="filters.length === 0" class="empty-state">
+ <h3>No filters</h3>
+ <p>
+ Built-in signals still run. Add a filter to score, quarantine, or reject
+ submissions containing specific words, senders, or domains.
+ </p>
+ <button class="btn btn-primary" @click="openCreate">New filter</button>
+ </div>
+
+ <div v-else class="table-wrapper">
+ <table>
+ <thead>
+ <tr>
+ <th>Pattern</th>
+ <th>Kind</th>
+ <th>Action</th>
+ <th>Score</th>
+ <th>Scope</th>
+ <th>Hits</th>
+ <th>Last hit</th>
+ <th></th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="filter in filters" :key="filter.id">
+ <td>
+ <code style="font-size: 12px">{{ filter.pattern }}</code>
+ <div v-if="filter.note" class="muted" style="font-size: 12px">{{ filter.note }}</div>
+ </td>
+ <td>{{ filter.kind }}</td>
+ <td><span :class="actionBadgeClass(filter.action)">{{ filter.action }}</span></td>
+ <td>{{ filter.action === "score" ? filter.score : "-" }}</td>
+ <td>{{ formName(filter.form_id) }}</td>
+ <td>{{ filter.hit_count }}</td>
+ <td>{{ formatDate(filter.last_hit_at) }}</td>
+ <td style="text-align: right; white-space: nowrap">
+ <button class="btn btn-secondary" @click="toggle(filter)">
+ {{ filter.enabled ? "Disable" : "Enable" }}
+ </button>
+ <button class="btn btn-danger" style="margin-left: 6px" @click="remove(filter)">
+ Delete
+ </button>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ </div>
+
+ <div v-if="showModal" class="modal-overlay" @click.self="showModal = false">
+ <div class="modal">
+ <div class="modal-header">
+ <h3>New filter</h3>
+ </div>
+ <div class="modal-body">
+ <div class="form-group">
+ <label class="form-label">Applies to</label>
+ <select v-model.number="draft.form_id" class="form-select">
+ <option :value="0">All forms</option>
+ <option v-for="f in forms" :key="f.id" :value="f.id">{{ f.name }}</option>
+ </select>
+ </div>
+ <div class="form-group">
+ <label class="form-label">Kind</label>
+ <select v-model="draft.kind" class="form-select">
+ <option value="keyword">Keyword (whole word)</option>
+ <option value="phrase">Phrase (substring)</option>
+ <option value="regex">Regular expression</option>
+ <option value="email">Sender email</option>
+ <option value="domain">Sender domain</option>
+ <option value="ip">Client IP</option>
+ </select>
+ </div>
+ <div class="form-group">
+ <label class="form-label">Pattern</label>
+ <input v-model="draft.pattern" class="form-input" placeholder="casino" />
+ </div>
+ <div class="form-group">
+ <label class="form-label">Action</label>
+ <select v-model="draft.action" class="form-select">
+ <option value="score">Add to spam score</option>
+ <option value="flag">Flag</option>
+ <option value="quarantine">Quarantine</option>
+ <option value="reject">Reject</option>
+ <option value="allowlist">Allowlist (skip scanning)</option>
+ </select>
+ </div>
+ <div v-if="draft.action === 'score'" class="form-group">
+ <label class="form-label">Score</label>
+ <input v-model.number="draft.score" type="number" step="0.5" class="form-input" />
+ </div>
+ <div class="form-group">
+ <label class="checkbox-label">
+ <input v-model="draft.case_sensitive" type="checkbox" />
+ Case sensitive
+ </label>
+ </div>
+ <div class="form-group">
+ <label class="form-label">Note</label>
+ <input v-model="draft.note" class="form-input" placeholder="Why this rule exists" />
+ </div>
+
+ <div class="form-group">
+ <button class="btn btn-secondary" :disabled="testing || !draft.pattern.trim()" @click="runTest">
+ {{ testing ? "Testing..." : "Test against recent messages" }}
+ </button>
+ </div>
+ <div v-if="testResult" class="alert alert-info">
+ Matched {{ testResult.matched }} of {{ testResult.scanned }} recent messages.
+ <ul v-if="testResult.samples.length" style="margin: 8px 0 0; padding-left: 18px">
+ <li v-for="sample in testResult.samples" :key="sample.message_uuid">
+ {{ sample.sender_email || "unknown" }} — {{ sample.subject || "(no subject)" }}
+ </li>
+ </ul>
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button class="btn btn-secondary" @click="showModal = false">Cancel</button>
+ <button class="btn btn-primary" :disabled="saving || !draft.pattern.trim()" @click="create">
+ {{ saving ? "Creating..." : "Create filter" }}
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+</template>
diff --git a/web/src/views/messages/Messages.vue b/web/src/views/messages/Messages.vue
new file mode 100644
index 0000000..0d47380
--- /dev/null
+++ b/web/src/views/messages/Messages.vue
@@ -0,0 +1,289 @@
+<script setup lang="ts">
+import { computed, onBeforeUnmount, onMounted, ref } from "vue";
+import { useRoute, useRouter } from "vue-router";
+import { formsApi, messagesApi } from "../../api/messages";
+import { useNotificationStore } from "../../stores/notification";
+import { apiMessage } from "../../composables/apiError";
+import type { Form, Message, MessageStats } from "../../api/types";
+import Pagination from "../../components/Pagination.vue";
+import { usePagination } from "../../composables/usePagination";
+
+const router = useRouter();
+const route = useRoute();
+const notify = useNotificationStore();
+const loading = ref(true);
+const featureDisabled = ref(false);
+const messages = ref<Message[]>([]);
+const forms = ref<Form[]>([]);
+const stats = ref<MessageStats | null>(null);
+
+const formId = ref<number>(Number(route.query.form_id) || 0);
+const status = ref("");
+const state = ref("");
+const unread = ref(false);
+const q = ref("");
+
+const { pageable, goToPage } = usePagination(async (page) => {
+ loading.value = true;
+ try {
+ const res = await messagesApi.list({
+ page,
+ form_id: formId.value || undefined,
+ status: status.value || undefined,
+ state: state.value || undefined,
+ unread: unread.value || undefined,
+ q: q.value || undefined,
+ });
+ messages.value = res.data.data;
+ pageable.value = res.data.pageable;
+ featureDisabled.value = false;
+ } catch (e: any) {
+ if (e?.response?.status === 404) {
+ featureDisabled.value = true;
+ } else {
+ notify.error(apiMessage(e, "Failed to load messages"));
+ }
+ } finally {
+ loading.value = false;
+ }
+});
+
+async function loadSidebarData() {
+ try {
+ const [formsRes, statsRes] = await Promise.all([
+ formsApi.list({ size: 100 }),
+ messagesApi.stats(),
+ ]);
+ forms.value = formsRes.data.data;
+ stats.value = statsRes.data.data;
+ } catch {
+ /* the list view already reports a disabled feature */
+ }
+}
+
+function applyFilters() {
+ goToPage(0);
+}
+
+function resetFilters() {
+ formId.value = 0;
+ status.value = "";
+ state.value = "";
+ unread.value = false;
+ q.value = "";
+ goToPage(0);
+}
+
+let sse: EventSource | null = null;
+onMounted(async () => {
+ await loadSidebarData();
+ try {
+ sse = new EventSource(messagesApi.streamUrl(), { withCredentials: true });
+ sse.addEventListener("message.received", () => {
+ goToPage(pageable.value?.current_page ?? 0);
+ loadSidebarData();
+ });
+ sse.onerror = () => {
+ /* reconnects are handled by the browser */
+ };
+ } catch {
+ /* SSE not supported */
+ }
+});
+onBeforeUnmount(() => {
+ if (sse) sse.close();
+});
+
+const hasForms = computed(() => forms.value.length > 0);
+
+function statusBadgeClass(value: string) {
+ switch (value) {
+ case "received":
+ return "badge badge-success";
+ case "flagged":
+ return "badge badge-warning";
+ case "quarantined":
+ return "badge badge-danger";
+ case "rejected":
+ return "badge badge-danger";
+ default:
+ return "badge";
+ }
+}
+
+function stateBadgeClass(value: string) {
+ switch (value) {
+ case "new":
+ return "badge badge-info";
+ case "replied":
+ return "badge badge-success";
+ case "closed":
+ return "badge badge-secondary";
+ case "spam":
+ return "badge badge-danger";
+ default:
+ return "badge";
+ }
+}
+
+function senderLabel(message: Message) {
+ if (message.sender_name && message.sender_email)
+ return `${message.sender_name} <${message.sender_email}>`;
+ return message.sender_email || message.sender_name || "unknown sender";
+}
+
+function formatDate(date: string | null | undefined) {
+ if (!date) return "-";
+ return new Date(date).toLocaleString();
+}
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <h1>Messages</h1>
+ <router-link to="/forms" class="btn btn-secondary">Manage forms</router-link>
+ </div>
+
+ <div v-if="loading && !messages.length" class="loading-page">
+ <div class="spinner"></div>
+ </div>
+
+ <div v-else-if="featureDisabled" class="card">
+ <div class="empty-state">
+ <h3>Web form messages are disabled</h3>
+ <p>
+ Ask your administrator to enable them by setting
+ <code>POSTA_MESSAGES_ENABLED=true</code>.
+ </p>
+ </div>
+ </div>
+
+ <template v-else>
+ <div v-if="stats" class="stats-grid" style="margin-bottom: 20px">
+ <div class="stat-card">
+ <div class="stat-label">Messages</div>
+ <div class="stat-value">{{ stats.total }}</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-label">Unread</div>
+ <div class="stat-value">{{ stats.unread }}</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-label">Spam</div>
+ <div class="stat-value">{{ stats.spam }}</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-label">Forms</div>
+ <div class="stat-value">{{ stats.forms }}</div>
+ </div>
+ </div>
+
+ <div class="card">
+ <div
+ class="card-body"
+ style="display: flex; gap: 12px; flex-wrap: wrap; align-items: flex-end"
+ >
+ <div style="flex: 1 1 160px">
+ <label class="form-label">Form</label>
+ <select v-model.number="formId" class="form-select" @change="applyFilters">
+ <option :value="0">All forms</option>
+ <option v-for="f in forms" :key="f.id" :value="f.id">{{ f.name }}</option>
+ </select>
+ </div>
+
+ <div style="flex: 1 1 140px">
+ <label class="form-label">Status</label>
+ <select v-model="status" class="form-select" @change="applyFilters">
+ <option value="">Any</option>
+ <option value="received">Received</option>
+ <option value="flagged">Flagged</option>
+ <option value="quarantined">Quarantined</option>
+ </select>
+ </div>
+
+ <div style="flex: 1 1 140px">
+ <label class="form-label">State</label>
+ <select v-model="state" class="form-select" @change="applyFilters">
+ <option value="">Any</option>
+ <option value="new">New</option>
+ <option value="open">Open</option>
+ <option value="replied">Replied</option>
+ <option value="closed">Closed</option>
+ <option value="spam">Spam</option>
+ </select>
+ </div>
+
+ <div style="flex: 2 1 200px">
+ <label class="form-label">Search</label>
+ <input
+ v-model="q"
+ class="form-input"
+ placeholder="Sender, subject, or body..."
+ @keyup.enter="applyFilters"
+ />
+ </div>
+
+ <div style="display: flex; gap: 8px; align-items: center">
+ <label class="form-label" style="display: flex; gap: 6px; align-items: center; margin: 0">
+ <input v-model="unread" type="checkbox" @change="applyFilters" />
+ Unread only
+ </label>
+ <button class="btn btn-primary" @click="applyFilters">Apply</button>
+ <button class="btn btn-secondary" @click="resetFilters">Reset</button>
+ </div>
+ </div>
+
+ <div v-if="messages.length === 0" class="empty-state">
+ <h3>No messages yet</h3>
+ <p v-if="hasForms">
+ Submissions to your forms will appear here as soon as they arrive.
+ </p>
+ <p v-else>
+ Create a form first, then embed it on your website.
+ <router-link to="/forms">Create a form</router-link>
+ </p>
+ </div>
+
+ <template v-else>
+ <div class="table-wrapper">
+ <table>
+ <thead>
+ <tr>
+ <th>From</th>
+ <th>Subject</th>
+ <th>Form</th>
+ <th>Status</th>
+ <th>State</th>
+ <th>Received</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr
+ v-for="message in messages"
+ :key="message.uuid"
+ style="cursor: pointer"
+ @click="router.push(`/messages/${message.uuid}`)"
+ >
+ <td :style="{ fontWeight: message.read_at ? '400' : '600' }">
+ {{ senderLabel(message) }}
+ </td>
+ <td>{{ message.subject || "(no subject)" }}</td>
+ <td>{{ message.form?.name || "-" }}</td>
+ <td>
+ <span :class="statusBadgeClass(message.status)">{{ message.status }}</span>
+ </td>
+ <td>
+ <span :class="stateBadgeClass(message.state)">{{ message.state }}</span>
+ </td>
+ <td>{{ formatDate(message.created_at) }}</td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ <Pagination :pageable="pageable" @page="goToPage" />
+ </template>
+ </div>
+ </template>
+ </div>
+</template>
diff --git a/web/src/views/settings/Settings.vue b/web/src/views/settings/Settings.vue
index 1fc8cec..db1a0b1 100644
--- a/web/src/views/settings/Settings.vue
+++ b/web/src/views/settings/Settings.vue
@@ -31,19 +31,21 @@ const form = ref<Partial<UserSettings>>({
notify_bounce_alerts: true,
notify_api_key_expiry: true,
notify_workspace_activity: true,
+ notify_new_message: true,
})
// Per-type notification toggles rendered under the master switch. Security
// alerts (sign-in, 2FA, password, account deletion) are always on and shown
// separately as informational.
const notificationTypes: {
- key: 'daily_report' | 'notify_bounce_alerts' | 'notify_api_key_expiry' | 'notify_workspace_activity'
+ key: 'daily_report' | 'notify_bounce_alerts' | 'notify_api_key_expiry' | 'notify_workspace_activity' | 'notify_new_message'
label: string
hint: string
}[] = [
{ key: 'notify_bounce_alerts', label: 'Bounce & deliverability alerts', hint: 'Warn me when my bounce rate crosses the safe threshold.' },
{ key: 'notify_api_key_expiry', label: 'API key expiry reminders', hint: 'Remind me before an API key expires.' },
{ key: 'notify_workspace_activity', label: 'Workspace updates', hint: 'Notify me about role changes and workspace activity.' },
+ { key: 'notify_new_message', label: 'Web form messages', hint: 'Notify me when a website form receives a new message.' },
{ key: 'daily_report', label: 'Daily report', hint: 'Receive a daily email summary of send statistics.' },
]
@@ -69,6 +71,7 @@ onMounted(async () => {
notify_bounce_alerts: u.notify_bounce_alerts,
notify_api_key_expiry: u.notify_api_key_expiry,
notify_workspace_activity: u.notify_workspace_activity,
+ notify_new_message: u.notify_new_message,
}
} catch {
notify.error('Failed to load settings')