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: add inbound email processing, SSO auth, and email verification

Jonas Kaninda6b379bb04cb9
diff --git a/.env.example b/.env.example
index 2483bf5..e96fba1 100644
--- a/.env.example
+++ b/.env.example
@@ -95,4 +95,30 @@ [email protected]
POSTA_SYSTEM_SMTP_PASSWORD=secret
# Encryption mode: none, ssl, starttls
-POSTA_SYSTEM_SMTP_ENCRYPTION=starttls
\ No newline at end of file
+POSTA_SYSTEM_SMTP_ENCRYPTION=starttls
+
+# Inbound email processing
+# Master toggle — enables the SMTP receiver and the /api/v1/inbound/* routes
+POSTA_INBOUND_ENABLED=false
+# Bind address for the built-in SMTP receiver
+POSTA_INBOUND_SMTP_HOST=0.0.0.0
+# SMTP listener port (use 25 publicly)
+POSTA_INBOUND_SMTP_PORT=2525
+# Hostname announced in EHLO / used as TLS SNI — should match the MX record
+POSTA_INBOUND_HOSTNAME=posta.example.com
+# Max raw message size in bytes (default 25 MiB)
+POSTA_INBOUND_MAX_MESSAGE_SIZE=26214400
+# Max per-attachment size in bytes (default 10 MiB)
+POSTA_INBOUND_MAX_ATTACH_SIZE=10485760
+# Shared secret for the generic MX-provider webhook at POST /api/v1/inbound/webhook
+# Clients must send it via the X-Posta-Inbound-Secret header
+# POSTA_INBOUND_WEBHOOK_SECRET=
+# SMTP TLS mode: none | starttls
+POSTA_INBOUND_TLS_MODE=none
+# PEM cert/key paths (required when POSTA_INBOUND_TLS_MODE=starttls)
+# POSTA_INBOUND_TLS_CERT_FILE=/etc/posta/tls/fullchain.pem
+# POSTA_INBOUND_TLS_KEY_FILE=/etc/posta/tls/privkey.pem
+# Per-IP SMTP rate limit: max sessions per window (0 disables)
+POSTA_INBOUND_SMTP_RATE_LIMIT=60
+# Rate-limit window in seconds
+POSTA_INBOUND_SMTP_RATE_WINDOW=60
\ No newline at end of file
diff --git a/Posta Observability Dashboard.json b/Posta Observability Dashboard.json
deleted file mode 100644
index e1fa51e..0000000
--- a/Posta Observability Dashboard.json
+++ /dev/null
@@ -1,1108 +0,0 @@
-{
- "__inputs": [
- {
- "name": "DS_PROMETHEUS",
- "label": "Prometheus",
- "description": "",
- "type": "datasource",
- "pluginId": "prometheus",
- "pluginName": "Prometheus"
- }
- ],
- "__elements": {},
- "__requires": [
- {
- "type": "panel",
- "id": "gauge",
- "name": "Gauge",
- "version": ""
- },
- {
- "type": "grafana",
- "id": "grafana",
- "name": "Grafana",
- "version": "12.1.0"
- },
- {
- "type": "datasource",
- "id": "prometheus",
- "name": "Prometheus",
- "version": "1.0.0"
- },
- {
- "type": "panel",
- "id": "stat",
- "name": "Stat",
- "version": ""
- },
- {
- "type": "panel",
- "id": "timeseries",
- "name": "Time series",
- "version": ""
- }
- ],
- "annotations": {
- "list": [
- {
- "builtIn": 1,
- "datasource": {
- "type": "grafana",
- "uid": "-- Grafana --"
- },
- "enable": true,
- "hide": true,
- "iconColor": "rgba(0, 211, 255, 1)",
- "name": "Annotations & Alerts",
- "type": "dashboard"
- }
- ]
- },
- "description": "Visualize Posta email delivery platform metrics",
- "editable": true,
- "fiscalYearStartMonth": 0,
- "graphTooltip": 0,
- "id": null,
- "links": [],
- "panels": [
- {
- "collapsed": false,
- "gridPos": { "h": 1, "w": 24, "x": 0, "y": 0 },
- "id": 100,
- "panels": [],
- "title": "Email Delivery",
- "type": "row"
- },
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "description": "Total emails successfully sent",
- "fieldConfig": {
- "defaults": {
- "color": { "mode": "thresholds" },
- "decimals": 0,
- "mappings": [],
- "thresholds": {
- "mode": "absolute",
- "steps": [
- { "color": "green", "value": 0 },
- { "color": "dark-green", "value": 1000 }
- ]
- },
- "unit": "short"
- },
- "overrides": []
- },
- "gridPos": { "h": 4, "w": 6, "x": 0, "y": 1 },
- "id": 1,
- "options": {
- "colorMode": "value",
- "graphMode": "area",
- "justifyMode": "auto",
- "orientation": "auto",
- "percentChangeColorMode": "standard",
- "reduceOptions": { "calcs": ["lastNotNull"], "fields": "", "values": false },
- "showPercentChange": false,
- "textMode": "auto",
- "wideLayout": true
- },
- "pluginVersion": "12.1.0",
- "targets": [
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "editorMode": "code",
- "expr": "sum(posta_emails_sent_total{instance=~\"$instance\"})",
- "legendFormat": "Emails Sent",
- "range": true,
- "refId": "A"
- }
- ],
- "title": "Emails Sent",
- "type": "stat"
- },
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "description": "Total emails that failed to send",
- "fieldConfig": {
- "defaults": {
- "color": { "mode": "thresholds" },
- "decimals": 0,
- "mappings": [],
- "thresholds": {
- "mode": "absolute",
- "steps": [
- { "color": "green", "value": 0 },
- { "color": "dark-orange", "value": 10 },
- { "color": "dark-red", "value": 100 }
- ]
- },
- "unit": "short"
- },
- "overrides": []
- },
- "gridPos": { "h": 4, "w": 6, "x": 6, "y": 1 },
- "id": 2,
- "options": {
- "colorMode": "value",
- "graphMode": "area",
- "justifyMode": "auto",
- "orientation": "auto",
- "percentChangeColorMode": "standard",
- "reduceOptions": { "calcs": ["lastNotNull"], "fields": "", "values": false },
- "showPercentChange": false,
- "textMode": "auto",
- "wideLayout": true
- },
- "pluginVersion": "12.1.0",
- "targets": [
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "editorMode": "code",
- "expr": "sum(posta_emails_failed_total{instance=~\"$instance\"})",
- "legendFormat": "Emails Failed",
- "range": true,
- "refId": "A"
- }
- ],
- "title": "Emails Failed",
- "type": "stat"
- },
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "description": "Total emails enqueued for delivery",
- "fieldConfig": {
- "defaults": {
- "color": { "mode": "thresholds" },
- "decimals": 0,
- "mappings": [],
- "thresholds": {
- "mode": "absolute",
- "steps": [
- { "color": "blue", "value": 0 },
- { "color": "dark-blue", "value": 1000 }
- ]
- },
- "unit": "short"
- },
- "overrides": []
- },
- "gridPos": { "h": 4, "w": 6, "x": 12, "y": 1 },
- "id": 3,
- "options": {
- "colorMode": "value",
- "graphMode": "area",
- "justifyMode": "auto",
- "orientation": "auto",
- "percentChangeColorMode": "standard",
- "reduceOptions": { "calcs": ["lastNotNull"], "fields": "", "values": false },
- "showPercentChange": false,
- "textMode": "auto",
- "wideLayout": true
- },
- "pluginVersion": "12.1.0",
- "targets": [
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "editorMode": "code",
- "expr": "sum(posta_emails_queued_total{instance=~\"$instance\"})",
- "legendFormat": "Emails Queued",
- "range": true,
- "refId": "A"
- }
- ],
- "title": "Emails Queued",
- "type": "stat"
- },
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "description": "Total email retry attempts",
- "fieldConfig": {
- "defaults": {
- "color": { "mode": "thresholds" },
- "decimals": 0,
- "mappings": [],
- "thresholds": {
- "mode": "absolute",
- "steps": [
- { "color": "dark-yellow", "value": 0 },
- { "color": "dark-orange", "value": 50 }
- ]
- },
- "unit": "short"
- },
- "overrides": []
- },
- "gridPos": { "h": 4, "w": 6, "x": 18, "y": 1 },
- "id": 4,
- "options": {
- "colorMode": "value",
- "graphMode": "area",
- "justifyMode": "auto",
- "orientation": "auto",
- "percentChangeColorMode": "standard",
- "reduceOptions": { "calcs": ["lastNotNull"], "fields": "", "values": false },
- "showPercentChange": false,
- "textMode": "auto",
- "wideLayout": true
- },
- "pluginVersion": "12.1.0",
- "targets": [
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "editorMode": "code",
- "expr": "sum(posta_email_retries_total{instance=~\"$instance\"})",
- "legendFormat": "Email Retries",
- "range": true,
- "refId": "A"
- }
- ],
- "title": "Email Retries",
- "type": "stat"
- },
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "description": "Email delivery success rate",
- "fieldConfig": {
- "defaults": {
- "color": { "mode": "thresholds" },
- "mappings": [],
- "thresholds": {
- "mode": "absolute",
- "steps": [
- { "color": "dark-red", "value": 0 },
- { "color": "dark-orange", "value": 90 },
- { "color": "semi-dark-green", "value": 98 }
- ]
- },
- "unit": "percent"
- },
- "overrides": []
- },
- "gridPos": { "h": 8, "w": 6, "x": 0, "y": 5 },
- "id": 5,
- "options": {
- "minVizHeight": 75,
- "minVizWidth": 75,
- "orientation": "auto",
- "reduceOptions": { "calcs": ["lastNotNull"], "fields": "", "values": false },
- "showThresholdLabels": false,
- "showThresholdMarkers": true,
- "sizing": "auto"
- },
- "pluginVersion": "12.1.0",
- "targets": [
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "editorMode": "code",
- "expr": "sum(posta_emails_sent_total{instance=~\"$instance\"}) / (sum(posta_emails_sent_total{instance=~\"$instance\"}) + sum(posta_emails_failed_total{instance=~\"$instance\"})) * 100",
- "legendFormat": "Delivery Rate",
- "range": true,
- "refId": "A"
- }
- ],
- "title": "Delivery Rate",
- "type": "gauge"
- },
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "description": "Webhook delivery success vs failure",
- "fieldConfig": {
- "defaults": {
- "color": { "mode": "thresholds" },
- "decimals": 0,
- "mappings": [],
- "thresholds": {
- "mode": "absolute",
- "steps": [
- { "color": "green", "value": 0 },
- { "color": "dark-green", "value": 100 }
- ]
- },
- "unit": "short"
- },
- "overrides": []
- },
- "gridPos": { "h": 4, "w": 6, "x": 6, "y": 5 },
- "id": 6,
- "options": {
- "colorMode": "value",
- "graphMode": "none",
- "justifyMode": "auto",
- "orientation": "auto",
- "percentChangeColorMode": "standard",
- "reduceOptions": { "calcs": ["lastNotNull"], "fields": "", "values": false },
- "showPercentChange": false,
- "textMode": "auto",
- "wideLayout": true
- },
- "pluginVersion": "12.1.0",
- "targets": [
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "editorMode": "code",
- "expr": "sum(posta_webhook_deliveries_total{instance=~\"$instance\",status=\"success\"})",
- "legendFormat": "Webhook Success",
- "range": true,
- "refId": "A"
- }
- ],
- "title": "Webhook Deliveries (Success)",
- "type": "stat"
- },
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "description": "Failed webhook delivery attempts",
- "fieldConfig": {
- "defaults": {
- "color": { "mode": "thresholds" },
- "decimals": 0,
- "mappings": [],
- "thresholds": {
- "mode": "absolute",
- "steps": [
- { "color": "dark-orange", "value": 0 },
- { "color": "dark-red", "value": 50 }
- ]
- },
- "unit": "short"
- },
- "overrides": []
- },
- "gridPos": { "h": 4, "w": 6, "x": 6, "y": 9 },
- "id": 7,
- "options": {
- "colorMode": "value",
- "graphMode": "none",
- "justifyMode": "auto",
- "orientation": "auto",
- "percentChangeColorMode": "standard",
- "reduceOptions": { "calcs": ["lastNotNull"], "fields": "", "values": false },
- "showPercentChange": false,
- "textMode": "auto",
- "wideLayout": true
- },
- "pluginVersion": "12.1.0",
- "targets": [
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "editorMode": "code",
- "expr": "sum(posta_webhook_deliveries_total{instance=~\"$instance\",status=\"failed\"})",
- "legendFormat": "Webhook Failed",
- "range": true,
- "refId": "A"
- }
- ],
- "title": "Webhook Deliveries (Failed)",
- "type": "stat"
- },
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "description": "Bounces by type",
- "fieldConfig": {
- "defaults": {
- "color": { "mode": "thresholds" },
- "decimals": 0,
- "mappings": [],
- "thresholds": {
- "mode": "absolute",
- "steps": [
- { "color": "dark-red", "value": 0 }
- ]
- },
- "unit": "short"
- },
- "overrides": []
- },
- "gridPos": { "h": 4, "w": 6, "x": 12, "y": 5 },
- "id": 8,
- "options": {
- "colorMode": "value",
- "graphMode": "none",
- "justifyMode": "auto",
- "orientation": "auto",
- "percentChangeColorMode": "standard",
- "reduceOptions": { "calcs": ["lastNotNull"], "fields": "", "values": false },
- "showPercentChange": false,
- "textMode": "auto",
- "wideLayout": true
- },
- "pluginVersion": "12.1.0",
- "targets": [
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "editorMode": "code",
- "expr": "sum(posta_bounces_total{instance=~\"$instance\"}) by (type)",
- "legendFormat": "{{type}}",
- "range": true,
- "refId": "A"
- }
- ],
- "title": "Bounces by Type",
- "type": "stat"
- },
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "description": "Total email suppressions",
- "fieldConfig": {
- "defaults": {
- "color": { "mode": "thresholds" },
- "decimals": 0,
- "mappings": [],
- "thresholds": {
- "mode": "absolute",
- "steps": [
- { "color": "dark-purple", "value": 0 }
- ]
- },
- "unit": "short"
- },
- "overrides": []
- },
- "gridPos": { "h": 4, "w": 6, "x": 18, "y": 5 },
- "id": 9,
- "options": {
- "colorMode": "value",
- "graphMode": "area",
- "justifyMode": "auto",
- "orientation": "auto",
- "percentChangeColorMode": "standard",
- "reduceOptions": { "calcs": ["lastNotNull"], "fields": "", "values": false },
- "showPercentChange": false,
- "textMode": "auto",
- "wideLayout": true
- },
- "pluginVersion": "12.1.0",
- "targets": [
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "editorMode": "code",
- "expr": "sum(posta_suppressions_total{instance=~\"$instance\"})",
- "legendFormat": "Suppressions",
- "range": true,
- "refId": "A"
- }
- ],
- "title": "Suppressions",
- "type": "stat"
- },
- {
- "collapsed": false,
- "gridPos": { "h": 1, "w": 24, "x": 0, "y": 13 },
- "id": 200,
- "panels": [],
- "title": "Email Throughput & Trends",
- "type": "row"
- },
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "description": "Email send/fail rate over time",
- "fieldConfig": {
- "defaults": {
- "color": { "mode": "palette-classic" },
- "custom": {
- "axisBorderShow": false, "axisCenteredZero": false, "axisColorMode": "text",
- "axisLabel": "", "axisPlacement": "auto", "barAlignment": 0, "barWidthFactor": 0.6,
- "drawStyle": "line", "fillOpacity": 10, "gradientMode": "none",
- "hideFrom": { "legend": false, "tooltip": false, "viz": false },
- "insertNulls": false, "lineInterpolation": "linear", "lineWidth": 1, "pointSize": 5,
- "scaleDistribution": { "type": "linear" }, "showPoints": "never", "spanNulls": false,
- "stacking": { "group": "A", "mode": "none" },
- "thresholdsStyle": { "mode": "off" }
- },
- "mappings": [],
- "thresholds": { "mode": "absolute", "steps": [{ "color": "green", "value": 0 }] },
- "unit": "short"
- },
- "overrides": []
- },
- "gridPos": { "h": 10, "w": 24, "x": 0, "y": 14 },
- "id": 10,
- "options": {
- "legend": { "calcs": ["mean", "lastNotNull", "max"], "displayMode": "table", "placement": "right", "showLegend": true },
- "tooltip": { "hideZeros": false, "maxHeight": 600, "mode": "multi", "sort": "none" }
- },
- "pluginVersion": "12.1.0",
- "targets": [
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "editorMode": "code",
- "expr": "rate(posta_emails_sent_total{instance=~\"$instance\"}[5m])",
- "legendFormat": "Sent/s",
- "range": true,
- "refId": "A"
- },
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "editorMode": "code",
- "expr": "rate(posta_emails_failed_total{instance=~\"$instance\"}[5m])",
- "legendFormat": "Failed/s",
- "range": true,
- "refId": "B"
- },
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "editorMode": "code",
- "expr": "rate(posta_emails_queued_total{instance=~\"$instance\"}[5m])",
- "legendFormat": "Queued/s",
- "range": true,
- "refId": "C"
- },
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "editorMode": "code",
- "expr": "rate(posta_email_retries_total{instance=~\"$instance\"}[5m])",
- "legendFormat": "Retries/s",
- "range": true,
- "refId": "D"
- }
- ],
- "title": "Email Throughput Rate",
- "type": "timeseries"
- },
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "description": "Webhook delivery rate and duration",
- "fieldConfig": {
- "defaults": {
- "color": { "mode": "palette-classic" },
- "custom": {
- "axisBorderShow": false, "axisCenteredZero": false, "axisColorMode": "text",
- "axisLabel": "", "axisPlacement": "auto", "barAlignment": 0, "barWidthFactor": 0.6,
- "drawStyle": "line", "fillOpacity": 10, "gradientMode": "none",
- "hideFrom": { "legend": false, "tooltip": false, "viz": false },
- "insertNulls": false, "lineInterpolation": "linear", "lineWidth": 1, "pointSize": 5,
- "scaleDistribution": { "type": "linear" }, "showPoints": "never", "spanNulls": false,
- "stacking": { "group": "A", "mode": "none" },
- "thresholdsStyle": { "mode": "off" }
- },
- "mappings": [],
- "thresholds": { "mode": "absolute", "steps": [{ "color": "green", "value": 0 }] },
- "unit": "short"
- },
- "overrides": []
- },
- "gridPos": { "h": 8, "w": 12, "x": 0, "y": 24 },
- "id": 11,
- "options": {
- "legend": { "calcs": [], "displayMode": "list", "placement": "bottom", "showLegend": true },
- "tooltip": { "hideZeros": false, "mode": "multi", "sort": "none" }
- },
- "pluginVersion": "12.1.0",
- "targets": [
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "editorMode": "code",
- "expr": "rate(posta_webhook_deliveries_total{instance=~\"$instance\",status=\"success\"}[5m])",
- "legendFormat": "Success/s",
- "range": true,
- "refId": "A"
- },
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "editorMode": "code",
- "expr": "rate(posta_webhook_deliveries_total{instance=~\"$instance\",status=\"failed\"}[5m])",
- "legendFormat": "Failed/s",
- "range": true,
- "refId": "B"
- }
- ],
- "title": "Webhook Delivery Rate",
- "type": "timeseries"
- },
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "description": "Webhook delivery latency percentiles",
- "fieldConfig": {
- "defaults": {
- "color": { "mode": "palette-classic" },
- "custom": {
- "axisBorderShow": false, "axisCenteredZero": false, "axisColorMode": "text",
- "axisLabel": "", "axisPlacement": "auto", "barAlignment": 0, "barWidthFactor": 0.6,
- "drawStyle": "line", "fillOpacity": 10, "gradientMode": "none",
- "hideFrom": { "legend": false, "tooltip": false, "viz": false },
- "insertNulls": false, "lineInterpolation": "linear", "lineWidth": 1, "pointSize": 5,
- "scaleDistribution": { "type": "linear" }, "showPoints": "never", "spanNulls": false,
- "stacking": { "group": "A", "mode": "none" },
- "thresholdsStyle": { "mode": "off" }
- },
- "mappings": [],
- "thresholds": { "mode": "absolute", "steps": [{ "color": "green", "value": 0 }] },
- "unit": "s"
- },
- "overrides": []
- },
- "gridPos": { "h": 8, "w": 12, "x": 12, "y": 24 },
- "id": 12,
- "options": {
- "legend": { "calcs": ["mean", "lastNotNull"], "displayMode": "table", "placement": "bottom", "showLegend": true },
- "tooltip": { "hideZeros": false, "mode": "multi", "sort": "none" }
- },
- "pluginVersion": "12.1.0",
- "targets": [
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "editorMode": "code",
- "expr": "histogram_quantile(0.50, sum(rate(posta_webhook_delivery_duration_seconds_bucket{instance=~\"$instance\"}[5m])) by (le))",
- "legendFormat": "p50",
- "range": true,
- "refId": "A"
- },
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "editorMode": "code",
- "expr": "histogram_quantile(0.95, sum(rate(posta_webhook_delivery_duration_seconds_bucket{instance=~\"$instance\"}[5m])) by (le))",
- "legendFormat": "p95",
- "range": true,
- "refId": "B"
- },
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "editorMode": "code",
- "expr": "histogram_quantile(0.99, sum(rate(posta_webhook_delivery_duration_seconds_bucket{instance=~\"$instance\"}[5m])) by (le))",
- "legendFormat": "p99",
- "range": true,
- "refId": "C"
- }
- ],
- "title": "Webhook Delivery Latency (p50 / p95 / p99)",
- "type": "timeseries"
- },
- {
- "collapsed": false,
- "gridPos": { "h": 1, "w": 24, "x": 0, "y": 32 },
- "id": 300,
- "panels": [],
- "title": "HTTP API & Performance",
- "type": "row"
- },
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "description": "Total HTTP requests by status code",
- "fieldConfig": {
- "defaults": {
- "color": { "mode": "palette-classic" },
- "custom": {
- "axisBorderShow": false, "axisCenteredZero": false, "axisColorMode": "text",
- "axisLabel": "", "axisPlacement": "auto", "barAlignment": 0, "barWidthFactor": 0.6,
- "drawStyle": "line", "fillOpacity": 0, "gradientMode": "none",
- "hideFrom": { "legend": false, "tooltip": false, "viz": false },
- "insertNulls": false, "lineInterpolation": "linear", "lineWidth": 1, "pointSize": 5,
- "scaleDistribution": { "type": "linear" }, "showPoints": "auto", "spanNulls": false,
- "stacking": { "group": "A", "mode": "none" },
- "thresholdsStyle": { "mode": "off" }
- },
- "mappings": [],
- "thresholds": { "mode": "absolute", "steps": [{ "color": "green", "value": 0 }] },
- "unit": "reqps"
- },
- "overrides": []
- },
- "gridPos": { "h": 10, "w": 24, "x": 0, "y": 33 },
- "id": 13,
- "options": {
- "legend": { "calcs": ["mean", "lastNotNull", "max"], "displayMode": "table", "placement": "right", "showLegend": true },
- "tooltip": { "hideZeros": false, "maxHeight": 600, "mode": "multi", "sort": "none" }
- },
- "pluginVersion": "12.1.0",
- "targets": [
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "editorMode": "code",
- "expr": "sum(rate(posta_http_requests_total{instance=~\"$instance\"}[5m])) by (status)",
- "legendFormat": "HTTP {{status}}",
- "range": true,
- "refId": "A"
- }
- ],
- "title": "HTTP Request Rate by Status Code",
- "type": "timeseries"
- },
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "description": "HTTP request latency by endpoint",
- "fieldConfig": {
- "defaults": {
- "color": { "mode": "palette-classic" },
- "custom": {
- "axisBorderShow": false, "axisCenteredZero": false, "axisColorMode": "text",
- "axisLabel": "", "axisPlacement": "auto", "barAlignment": 0, "barWidthFactor": 0.6,
- "drawStyle": "line", "fillOpacity": 10, "gradientMode": "none",
- "hideFrom": { "legend": false, "tooltip": false, "viz": false },
- "insertNulls": false, "lineInterpolation": "linear", "lineWidth": 1, "pointSize": 5,
- "scaleDistribution": { "type": "linear" }, "showPoints": "never", "spanNulls": false,
- "stacking": { "group": "A", "mode": "none" },
- "thresholdsStyle": { "mode": "off" }
- },
- "mappings": [],
- "thresholds": { "mode": "absolute", "steps": [{ "color": "green", "value": 0 }] },
- "unit": "s"
- },
- "overrides": []
- },
- "gridPos": { "h": 10, "w": 24, "x": 0, "y": 43 },
- "id": 14,
- "options": {
- "legend": { "calcs": ["mean", "lastNotNull"], "displayMode": "table", "placement": "right", "showLegend": true },
- "tooltip": { "hideZeros": false, "maxHeight": 600, "mode": "multi", "sort": "none" }
- },
- "pluginVersion": "12.1.0",
- "targets": [
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "editorMode": "code",
- "expr": "histogram_quantile(0.50, sum(rate(posta_http_request_duration_seconds_bucket{instance=~\"$instance\"}[5m])) by (le, path))",
- "legendFormat": "{{path}} (p50)",
- "range": true,
- "refId": "A"
- },
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "editorMode": "code",
- "expr": "histogram_quantile(0.95, sum(rate(posta_http_request_duration_seconds_bucket{instance=~\"$instance\"}[5m])) by (le, path))",
- "legendFormat": "{{path}} (p95)",
- "range": true,
- "refId": "B"
- },
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "editorMode": "code",
- "expr": "histogram_quantile(0.99, sum(rate(posta_http_request_duration_seconds_bucket{instance=~\"$instance\"}[5m])) by (le, path))",
- "legendFormat": "{{path}} (p99)",
- "range": true,
- "refId": "C"
- }
- ],
- "title": "API Request Latency Percentiles by Endpoint (p50 / p95 / p99)",
- "type": "timeseries"
- },
- {
- "collapsed": false,
- "gridPos": { "h": 1, "w": 24, "x": 0, "y": 53 },
- "id": 400,
- "panels": [],
- "title": "Go Runtime",
- "type": "row"
- },
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "fieldConfig": {
- "defaults": {
- "color": { "mode": "thresholds" },
- "mappings": [],
- "thresholds": {
- "mode": "absolute",
- "steps": [
- { "color": "green", "value": 0 },
- { "color": "orange", "value": 500000000 },
- { "color": "semi-dark-red", "value": 1500000000 }
- ]
- },
- "unit": "decbytes"
- },
- "overrides": []
- },
- "gridPos": { "h": 8, "w": 6, "x": 0, "y": 54 },
- "id": 15,
- "options": {
- "minVizHeight": 75, "minVizWidth": 75, "orientation": "auto",
- "reduceOptions": { "calcs": ["lastNotNull"], "fields": "", "values": false },
- "showThresholdLabels": false, "showThresholdMarkers": true, "sizing": "auto"
- },
- "pluginVersion": "12.1.0",
- "targets": [
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "editorMode": "code",
- "expr": "sum(go_memstats_heap_inuse_bytes{instance=~\"$instance\"})",
- "legendFormat": "{{job}}",
- "range": true,
- "refId": "A"
- }
- ],
- "title": "Heap In Use",
- "type": "gauge"
- },
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "fieldConfig": {
- "defaults": {
- "color": { "mode": "thresholds" },
- "mappings": [],
- "thresholds": {
- "mode": "absolute",
- "steps": [
- { "color": "semi-dark-green", "value": 0 },
- { "color": "semi-dark-orange", "value": 50 },
- { "color": "dark-red", "value": 75 }
- ]
- },
- "unit": "percent"
- },
- "overrides": []
- },
- "gridPos": { "h": 8, "w": 6, "x": 6, "y": 54 },
- "id": 16,
- "options": {
- "minVizHeight": 75, "minVizWidth": 75, "orientation": "auto",
- "reduceOptions": { "calcs": ["lastNotNull"], "fields": "", "values": false },
- "showThresholdLabels": false, "showThresholdMarkers": true, "sizing": "auto"
- },
- "pluginVersion": "12.1.0",
- "targets": [
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "editorMode": "code",
- "expr": "rate(process_cpu_seconds_total{instance=~\"$instance\"}[5m]) * 100",
- "legendFormat": "{{job}}",
- "range": true,
- "refId": "A"
- }
- ],
- "title": "CPU Usage",
- "type": "gauge"
- },
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "fieldConfig": {
- "defaults": {
- "color": { "mode": "palette-classic" },
- "custom": {
- "axisBorderShow": false, "axisCenteredZero": false, "axisColorMode": "text",
- "axisLabel": "", "axisPlacement": "auto", "barAlignment": 0, "barWidthFactor": 0.6,
- "drawStyle": "line", "fillOpacity": 10, "gradientMode": "none",
- "hideFrom": { "legend": false, "tooltip": false, "viz": false },
- "insertNulls": false, "lineInterpolation": "linear", "lineWidth": 1, "pointSize": 5,
- "scaleDistribution": { "type": "linear" }, "showPoints": "never", "spanNulls": false,
- "stacking": { "group": "A", "mode": "none" },
- "thresholdsStyle": { "mode": "off" }
- },
- "mappings": [],
- "thresholds": { "mode": "absolute", "steps": [{ "color": "green", "value": 0 }, { "color": "red", "value": 80 }] },
- "unit": "bytes"
- },
- "overrides": []
- },
- "gridPos": { "h": 8, "w": 12, "x": 0, "y": 62 },
- "id": 17,
- "options": {
- "legend": { "calcs": [], "displayMode": "list", "placement": "bottom", "showLegend": true },
- "tooltip": { "hideZeros": false, "maxHeight": 600, "mode": "multi", "sort": "none" }
- },
- "pluginVersion": "12.1.0",
- "targets": [
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "editorMode": "code",
- "expr": "go_memstats_heap_alloc_bytes{instance=~\"$instance\"}",
- "legendFormat": "Heap Allocated",
- "range": true,
- "refId": "A"
- },
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "editorMode": "code",
- "expr": "go_memstats_heap_inuse_bytes{instance=~\"$instance\"}",
- "legendFormat": "Heap In Use",
- "range": true,
- "refId": "B"
- },
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "editorMode": "code",
- "expr": "go_memstats_heap_idle_bytes{instance=~\"$instance\"}",
- "legendFormat": "Heap Idle",
- "range": true,
- "refId": "C"
- }
- ],
- "title": "Go Heap Memory Usage",
- "type": "timeseries"
- },
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "fieldConfig": {
- "defaults": {
- "color": { "mode": "palette-classic" },
- "custom": {
- "axisBorderShow": false, "axisCenteredZero": false, "axisColorMode": "text",
- "axisLabel": "", "axisPlacement": "auto", "barAlignment": 0, "barWidthFactor": 0.6,
- "drawStyle": "line", "fillOpacity": 10, "gradientMode": "none",
- "hideFrom": { "legend": false, "tooltip": false, "viz": false },
- "insertNulls": false, "lineInterpolation": "linear", "lineWidth": 1, "pointSize": 5,
- "scaleDistribution": { "type": "linear" }, "showPoints": "never", "spanNulls": false,
- "stacking": { "group": "A", "mode": "none" },
- "thresholdsStyle": { "mode": "off" }
- },
- "mappings": [],
- "thresholds": { "mode": "absolute", "steps": [{ "color": "green", "value": 0 }, { "color": "red", "value": 80 }] },
- "unit": "short"
- },
- "overrides": []
- },
- "gridPos": { "h": 8, "w": 12, "x": 12, "y": 62 },
- "id": 18,
- "options": {
- "legend": { "calcs": [], "displayMode": "list", "placement": "bottom", "showLegend": true },
- "tooltip": { "hideZeros": false, "maxHeight": 600, "mode": "multi", "sort": "none" }
- },
- "pluginVersion": "12.1.0",
- "targets": [
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "editorMode": "code",
- "expr": "go_goroutines{instance=~\"$instance\"}",
- "legendFormat": "Goroutines",
- "range": true,
- "refId": "A"
- },
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "editorMode": "code",
- "expr": "go_threads{instance=~\"$instance\"}",
- "legendFormat": "OS Threads",
- "range": true,
- "refId": "B"
- }
- ],
- "title": "Go Goroutine & Thread Count",
- "type": "timeseries"
- },
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "fieldConfig": {
- "defaults": {
- "color": { "mode": "palette-classic" },
- "custom": {
- "axisBorderShow": false, "axisCenteredZero": false, "axisColorMode": "text",
- "axisLabel": "", "axisPlacement": "auto", "barAlignment": 0, "barWidthFactor": 0.6,
- "drawStyle": "line", "fillOpacity": 10, "gradientMode": "none",
- "hideFrom": { "legend": false, "tooltip": false, "viz": false },
- "insertNulls": false, "lineInterpolation": "linear", "lineWidth": 1, "pointSize": 5,
- "scaleDistribution": { "type": "linear" }, "showPoints": "never", "spanNulls": false,
- "stacking": { "group": "A", "mode": "none" },
- "thresholdsStyle": { "mode": "off" }
- },
- "mappings": [],
- "thresholds": { "mode": "absolute", "steps": [{ "color": "green", "value": 0 }, { "color": "red", "value": 75 }] },
- "unit": "percent"
- },
- "overrides": []
- },
- "gridPos": { "h": 8, "w": 12, "x": 0, "y": 70 },
- "id": 19,
- "options": {
- "legend": { "calcs": [], "displayMode": "list", "placement": "bottom", "showLegend": true },
- "tooltip": { "hideZeros": false, "maxHeight": 600, "mode": "multi", "sort": "none" }
- },
- "pluginVersion": "12.1.0",
- "targets": [
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "editorMode": "code",
- "expr": "rate(process_cpu_seconds_total{instance=~\"$instance\"}[$__rate_interval]) * 100",
- "legendFormat": "CPU Usage",
- "range": true,
- "refId": "A"
- }
- ],
- "title": "CPU Usage (%)",
- "type": "timeseries"
- },
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "fieldConfig": {
- "defaults": {
- "color": { "mode": "palette-classic" },
- "custom": {
- "axisBorderShow": false, "axisCenteredZero": false, "axisColorMode": "text",
- "axisLabel": "", "axisPlacement": "auto", "barAlignment": 0, "barWidthFactor": 0.6,
- "drawStyle": "line", "fillOpacity": 10, "gradientMode": "none",
- "hideFrom": { "legend": false, "tooltip": false, "viz": false },
- "insertNulls": false, "lineInterpolation": "linear", "lineWidth": 1, "pointSize": 5,
- "scaleDistribution": { "type": "linear" }, "showPoints": "never", "spanNulls": false,
- "stacking": { "group": "A", "mode": "none" },
- "thresholdsStyle": { "mode": "off" }
- },
- "mappings": [],
- "thresholds": { "mode": "absolute", "steps": [{ "color": "green", "value": 0 }, { "color": "red", "value": 80 }] },
- "unit": "s"
- },
- "overrides": []
- },
- "gridPos": { "h": 8, "w": 12, "x": 12, "y": 70 },
- "id": 20,
- "options": {
- "legend": { "calcs": [], "displayMode": "list", "placement": "bottom", "showLegend": true },
- "tooltip": { "hideZeros": false, "maxHeight": 600, "mode": "multi", "sort": "none" }
- },
- "pluginVersion": "12.1.0",
- "targets": [
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "editorMode": "code",
- "expr": "go_gc_duration_seconds{instance=~\"$instance\",quantile=\"0.5\"}",
- "legendFormat": "GC p50",
- "range": true,
- "refId": "A"
- },
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "editorMode": "code",
- "expr": "go_gc_duration_seconds{instance=~\"$instance\",quantile=\"0.95\"}",
- "legendFormat": "GC p95",
- "range": true,
- "refId": "B"
- },
- {
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "editorMode": "code",
- "expr": "rate(go_gc_duration_seconds_count{instance=~\"$instance\"}[5m])",
- "legendFormat": "GC Frequency",
- "range": true,
- "refId": "C"
- }
- ],
- "title": "Go GC Pause Duration",
- "type": "timeseries"
- }
- ],
- "refresh": "30s",
- "schemaVersion": 41,
- "tags": [
- "posta",
- "email",
- "go",
- "smtp"
- ],
- "templating": {
- "list": [
- {
- "current": {},
- "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
- "definition": "label_values(posta_emails_sent_total,instance)",
- "includeAll": true,
- "multi": true,
- "name": "instance",
- "options": [],
- "query": {
- "qryType": 1,
- "query": "label_values(posta_emails_sent_total,instance)",
- "refId": "PrometheusVariableQueryEditor-VariableQuery"
- },
- "refresh": 1,
- "regex": "",
- "sort": 1,
- "type": "query"
- }
- ]
- },
- "time": {
- "from": "now-1h",
- "to": "now"
- },
- "timepicker": {},
- "timezone": "",
- "title": "Posta Observability Dashboard",
- "uid": "posta-observability",
- "version": 1,
- "weekStart": ""
-}
diff --git a/README.md b/README.md
index 0a0653b..efb4c7e 100644
--- a/README.md
+++ b/README.md
@@ -68,12 +68,28 @@ Response:
* Async processing with Redis and Asynq
* Automatic retries and priority queues
+### Inbound Email
+
+* Built-in SMTP receiver for incoming messages (default port `2525`, STARTTLS supported)
+* HTTP ingestion endpoint for third-party providers (SendGrid, Mailgun, etc.) with HMAC-signed webhooks
+* Full RFC 5322 parsing with attachment extraction and blob storage (S3 or filesystem)
+* Domain verification enforcement — only verified/owned domains accept mail (SMTP 550 otherwise)
+* Suppression list checks, Message-ID deduplication, and per-IP rate limiting
+* `email.inbound` webhook dispatch with retries and delivery tracking
+* Real-time SSE stream for inbound notifications and `.eml` / attachment downloads
+
### Templates
* Versioned and multi-language templates
* Variable substitution and stylesheet inlining
* Import/export and preview support
+### Campaigns
+
+* Bulk email campaigns with scheduling and subscriber targeting
+* Draft, scheduled, sending, paused, and cancelled lifecycle states
+* A/B testing with multi-variant splits and per-variant performance metrics
+
### SMTP & Domains
* Multiple SMTP providers with TLS support
@@ -89,12 +105,19 @@ Response:
* OAuth / SSO login (Google, Keycloak, authentik, and more)
* Rate limiting and session management
-### Contacts & Suppression
+### Contacts & Subscribers
-* Contact tracking and segmentation
-* Bounce and complaint handling
+* Contact tracking, lists, and segmentation
+* Subscriber lifecycle (active, bounced, unsubscribed)
+* Hard/soft bounce and complaint handling
* Automatic suppression lists
+### Tracking
+
+* Pixel-based open tracking
+* Click tracking with link rewriting
+* Per-email engagement metrics
+
### Workspaces
* Multi-tenant architecture with isolated workspaces
@@ -109,7 +132,7 @@ Response:
### Analytics & Monitoring
-* Email delivery metrics and trends
+* Email delivery, open, and click metrics
* Prometheus integration
* Health endpoints and daily reports
@@ -123,7 +146,7 @@ Response:
### Dashboard
* Vue-based UI for managing all resources
-* Analytics, templates, SMTP, contacts, and logs
+* Analytics, templates, SMTP, domains, contacts, campaigns, and logs
* Dark/light mode and user preferences
---
diff --git a/cmd/posta/server.go b/cmd/posta/server.go
index 1647c43..0a15f7d 100644
--- a/cmd/posta/server.go
+++ b/cmd/posta/server.go
@@ -19,14 +19,22 @@ package main
import (
"context"
+ "errors"
+ "net"
"time"
+ "github.com/emersion/go-smtp"
+
"github.com/goposta/posta/internal/config"
cronpkg "github.com/goposta/posta/internal/cron"
"github.com/goposta/posta/internal/cron/jobs"
"github.com/goposta/posta/internal/metrics"
+ "github.com/goposta/posta/internal/models"
"github.com/goposta/posta/internal/routes"
"github.com/goposta/posta/internal/services/crypto"
+ "github.com/goposta/posta/internal/services/email"
+ "github.com/goposta/posta/internal/services/eventbus"
+ "github.com/goposta/posta/internal/services/inbound"
"github.com/goposta/posta/internal/services/notification"
"github.com/goposta/posta/internal/services/retry"
"github.com/goposta/posta/internal/services/seeder"
@@ -51,6 +59,7 @@ type serverResources struct {
blobStore blob.Store
db *gorm.DB
redis *redis.Client
+ smtpInbound *smtp.Server
}
func runServer(cli *okapicli.CLI) {
@@ -109,13 +118,25 @@ func runServer(cli *okapicli.CLI) {
logger.Info("system notification service enabled")
}
- if cfg.EmbeddedWorker && !cfg.DevMode {
+ if !cfg.DevMode {
res.producer = worker.NewProducer(cfg.Redis.Addr, cfg.Redis.Password, cfg.WorkerMaxRetries)
- startEmbeddedWorker(res.db, cfg, res.blobStore, notifier)
+ if cfg.EmbeddedWorker {
+ startEmbeddedWorker(res.db, cfg, res.blobStore, notifier)
+ }
+ }
+
+ if cfg.InboundEnabled && !cfg.DevMode {
+ eventRepo := repositories.NewEventRepository(res.db)
+ inboundBus := eventbus.New(eventRepo)
+ if srv, err := startInboundSMTPServer(res.db, cfg, res.blobStore, res.producer, inboundBus); err != nil {
+ logger.Error("failed to start inbound SMTP server", "error", err)
+ } else {
+ res.smtpInbound = srv
+ }
}
if !cfg.DevMode {
- res.cronManager = initCronManager(res.db, cfg, notifier)
+ res.cronManager = initCronManager(res.db, cfg, notifier, res.blobStore, res.producer)
}
routes.InitRoutes(app, res.db,
@@ -179,6 +200,68 @@ func newWebhookDispatcher(db *gorm.DB, cfg *config.Config) *webhook.Dispatcher {
return dispatcher
}
+// startInboundSMTPServer configures and launches the built-in SMTP receiver.
+// Returns the server so it can be gracefully shut down on exit.
+func startInboundSMTPServer(
+ db *gorm.DB,
+ cfg *config.Config,
+ blobStore blob.Store,
+ producer *worker.Producer,
+ bus *eventbus.EventBus,
+) (*smtp.Server, error) {
+ inboundRepo := repositories.NewInboundEmailRepository(db)
+ domainRepo := repositories.NewDomainRepository(db)
+ suppressionRepo := repositories.NewSuppressionRepository(db)
+
+ svc := inbound.NewService(
+ inboundRepo,
+ domainRepo,
+ suppressionRepo,
+ inbound.Config{
+ MaxMessageSize: cfg.InboundMaxMessageSize,
+ MaxAttachmentSize: cfg.InboundMaxAttachSize,
+ },
+ )
+ if blobStore != nil {
+ svc.SetBlobStore(blobStore)
+ }
+ if producer != nil {
+ svc.SetEnqueuer(producer)
+ }
+ svc.SetEventBus(bus)
+ svc.OnReceived(func(src models.InboundSource) { metrics.IncrementInboundReceived(string(src)) })
+ svc.OnRejected(metrics.IncrementInboundRejected)
+ svc.OnBytes(metrics.AddInboundBytes)
+ svc.OnIngestDuration(metrics.ObserveInboundIngestDuration)
+
+ backend := inbound.NewBackend(svc, domainRepo, cfg.InboundMaxMessageSize)
+ if cfg.InboundSMTPRateLimit > 0 {
+ window := time.Duration(cfg.InboundSMTPRateWindow) * time.Second
+ backend.SetRateLimiter(inbound.NewIPRateLimiter(cfg.InboundSMTPRateLimit, window))
+ }
+ srv, err := inbound.NewSMTPServer(backend, inbound.SMTPConfig{
+ Host: cfg.InboundSMTPHost,
+ Port: cfg.InboundSMTPPort,
+ Hostname: cfg.InboundHostname,
+ MaxMessageSize: cfg.InboundMaxMessageSize,
+ TLSMode: cfg.InboundTLSMode,
+ TLSCertFile: cfg.InboundTLSCertFile,
+ TLSKeyFile: cfg.InboundTLSKeyFile,
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ go func() {
+ logger.Info("inbound SMTP server listening", "addr", srv.Addr, "tls_mode", cfg.InboundTLSMode)
+ err := srv.ListenAndServe()
+ if err != nil && !errors.Is(err, net.ErrClosed) && !errors.Is(err, smtp.ErrServerClosed) {
+ logger.Error("inbound SMTP server error", "error", err)
+ }
+ }()
+ return srv, nil
+}
+
// startEmbeddedWorker starts an in-process asynq worker for email delivery.
func startEmbeddedWorker(db *gorm.DB, cfg *config.Config, blobStore blob.Store, notifier *notification.Service) {
dispatcher := newWebhookDispatcher(db, cfg)
@@ -195,13 +278,32 @@ func startEmbeddedWorker(db *gorm.DB, cfg *config.Config, blobStore blob.Store,
handler.SetBlobStore(blobStore)
}
handler.SetCampaignMessageRepo(repositories.NewCampaignMessageRepository(db))
- handler.OnSent(metrics.IncrementEmailSent)
- handler.OnFailed(metrics.IncrementEmailFailed)
+ handler.SetCampaignRepo(repositories.NewCampaignRepository(db))
+ handler.SetStamper(email.NewStamper("Posta", config.Version, []byte(cfg.JWTSecret)))
+ handler.OnSent(func() {
+ metrics.IncrementEmailSent()
+ metrics.DecrementEmailQueued()
+ })
+ handler.OnFailed(func() {
+ metrics.IncrementEmailFailed()
+ metrics.DecrementEmailQueued()
+ })
exhaustedHandler := worker.NewExhaustedErrorHandler(
- repositories.NewEmailRepository(db), dispatcher, metrics.IncrementEmailFailed,
+ repositories.NewEmailRepository(db), dispatcher, func() {
+ metrics.IncrementEmailFailed()
+ metrics.DecrementEmailQueued()
+ },
)
+ errorHandlers := []asynq.ErrorHandler{exhaustedHandler}
+ if cfg.InboundEnabled {
+ inboundExhausted := worker.NewInboundExhaustedErrorHandler(
+ repositories.NewInboundEmailRepository(db), metrics.IncrementInboundFailed,
+ )
+ errorHandlers = append(errorHandlers, inboundExhausted)
+ }
+
srv := asynq.NewServer(
asynq.RedisClientOpt{Addr: cfg.Redis.Addr, Password: cfg.Redis.Password},
asynq.Config{
@@ -211,7 +313,7 @@ func startEmbeddedWorker(db *gorm.DB, cfg *config.Config, blobStore blob.Store,
worker.QueueBulk: 3,
worker.QueueLow: 1,
},
- ErrorHandler: exhaustedHandler,
+ ErrorHandler: worker.ChainErrorHandlers(errorHandlers...),
},
)
@@ -247,6 +349,18 @@ func startEmbeddedWorker(db *gorm.DB, cfg *config.Config, blobStore blob.Store,
mux.HandleFunc(worker.TypeCampaignBatch, campaignProcessor.HandleCampaignBatch)
mux.HandleFunc(jobs.TypeDailyReport, dailyReportHandler.ProcessTask)
+ if cfg.InboundEnabled {
+ inboundHandler := worker.NewInboundProcessHandler(
+ repositories.NewInboundEmailRepository(db),
+ newWebhookDispatcher(db, cfg),
+ cfg.ApiBaseURL,
+ []byte(cfg.JWTSecret),
+ )
+ inboundHandler.OnForwarded(metrics.IncrementInboundForwarded)
+ inboundHandler.OnFailed(metrics.IncrementInboundFailed)
+ mux.HandleFunc(worker.TypeInboundProcess, inboundHandler.ProcessTask)
+ }
+
go func() {
if err := srv.Run(mux); err != nil {
logger.Error("embedded worker error", "error", err)
@@ -257,7 +371,13 @@ func startEmbeddedWorker(db *gorm.DB, cfg *config.Config, blobStore blob.Store,
}
// initCronManager creates and registers scheduled jobs.
-func initCronManager(db *gorm.DB, cfg *config.Config, notifier *notification.Service) *cronpkg.Manager {
+func initCronManager(
+ db *gorm.DB,
+ cfg *config.Config,
+ notifier *notification.Service,
+ blobStore blob.Store,
+ producer *worker.Producer,
+) *cronpkg.Manager {
cronClient := asynq.NewClient(asynq.RedisClientOpt{
Addr: cfg.Redis.Addr,
Password: cfg.Redis.Password,
@@ -265,13 +385,20 @@ func initCronManager(db *gorm.DB, cfg *config.Config, notifier *notification.Ser
settingsProvider := settings.NewProvider(repositories.NewSettingRepository(db))
manager := cronpkg.NewManager(cronClient)
- manager.Register(jobs.NewRetentionCleanupJob(
+ retentionJob := jobs.NewRetentionCleanupJob(
repositories.NewEmailRepository(db),
repositories.NewEventRepository(db),
repositories.NewWebhookDeliveryRepository(db),
repositories.NewTrackingRepository(db),
settingsProvider,
- ))
+ )
+ if cfg.InboundEnabled {
+ retentionJob.SetInboundEmailRepo(repositories.NewInboundEmailRepository(db))
+ }
+ if blobStore != nil {
+ retentionJob.SetBlobStore(blobStore)
+ }
+ manager.Register(retentionJob)
manager.Register(jobs.NewDailyReportJob(repositories.NewUserSettingRepository(db)))
manager.Register(jobs.NewAccountCleanupJob(repositories.NewUserRepository(db)))
manager.Register(jobs.NewAPIKeyExpiryJob(db, notifier))
@@ -280,6 +407,13 @@ func initCronManager(db *gorm.DB, cfg *config.Config, notifier *notification.Ser
repositories.NewBounceRepository(db),
repositories.NewSuppressionRepository(db),
))
+ if producer != nil {
+ manager.Register(jobs.NewCampaignRestartJob(
+ repositories.NewCampaignRepository(db),
+ repositories.NewCampaignMessageRepository(db),
+ producer,
+ ))
+ }
return manager
}
@@ -305,6 +439,13 @@ func startRetryWorker(db *gorm.DB, cfg *config.Config, producer *worker.Producer
func shutdownServer(res *serverResources) {
logger.Info("Posta Server shutting down gracefully...")
+ if res.smtpInbound != nil {
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ if err := res.smtpInbound.Shutdown(ctx); err != nil {
+ logger.Error("failed to shut down inbound SMTP server", "error", err)
+ }
+ cancel()
+ }
if res.cronManager != nil {
res.cronManager.Stop()
}
diff --git a/cmd/posta/worker.go b/cmd/posta/worker.go
index 264df01..ff9a1f7 100644
--- a/cmd/posta/worker.go
+++ b/cmd/posta/worker.go
@@ -22,6 +22,7 @@ import (
"github.com/goposta/posta/internal/cron/jobs"
"github.com/goposta/posta/internal/metrics"
"github.com/goposta/posta/internal/services/crypto"
+ "github.com/goposta/posta/internal/services/email"
"github.com/goposta/posta/internal/services/notification"
"github.com/goposta/posta/internal/services/tracking"
"github.com/goposta/posta/internal/storage/blob"
@@ -81,13 +82,32 @@ func runWorker() error {
handler.SetBlobStore(blobStore)
}
handler.SetCampaignMessageRepo(repositories.NewCampaignMessageRepository(db))
- handler.OnSent(metrics.IncrementEmailSent)
- handler.OnFailed(metrics.IncrementEmailFailed)
+ handler.SetCampaignRepo(repositories.NewCampaignRepository(db))
+ handler.SetStamper(email.NewStamper("Posta", config.Version, []byte(cfg.JWTSecret)))
+ handler.OnSent(func() {
+ metrics.IncrementEmailSent()
+ metrics.DecrementEmailQueued()
+ })
+ handler.OnFailed(func() {
+ metrics.IncrementEmailFailed()
+ metrics.DecrementEmailQueued()
+ })
exhaustedHandler := worker.NewExhaustedErrorHandler(
- repositories.NewEmailRepository(db), dispatcher, metrics.IncrementEmailFailed,
+ repositories.NewEmailRepository(db), dispatcher, func() {
+ metrics.IncrementEmailFailed()
+ metrics.DecrementEmailQueued()
+ },
)
+ errorHandlers := []asynq.ErrorHandler{exhaustedHandler}
+ if cfg.InboundEnabled {
+ inboundExhausted := worker.NewInboundExhaustedErrorHandler(
+ repositories.NewInboundEmailRepository(db), metrics.IncrementInboundFailed,
+ )
+ errorHandlers = append(errorHandlers, inboundExhausted)
+ }
+
srv := asynq.NewServer(
asynq.RedisClientOpt{Addr: cfg.Redis.Addr, Password: cfg.Redis.Password},
asynq.Config{
@@ -97,7 +117,7 @@ func runWorker() error {
worker.QueueBulk: 3,
worker.QueueLow: 1,
},
- ErrorHandler: exhaustedHandler,
+ ErrorHandler: worker.ChainErrorHandlers(errorHandlers...),
},
)
@@ -138,6 +158,18 @@ func runWorker() error {
mux.HandleFunc(worker.TypeCampaignBatch, campaignProcessor.HandleCampaignBatch)
mux.HandleFunc(jobs.TypeDailyReport, dailyReportHandler.ProcessTask)
+ if cfg.InboundEnabled {
+ inboundHandler := worker.NewInboundProcessHandler(
+ repositories.NewInboundEmailRepository(db),
+ newWebhookDispatcher(db, cfg),
+ cfg.ApiBaseURL,
+ []byte(cfg.JWTSecret),
+ )
+ inboundHandler.OnForwarded(metrics.IncrementInboundForwarded)
+ inboundHandler.OnFailed(metrics.IncrementInboundFailed)
+ mux.HandleFunc(worker.TypeInboundProcess, inboundHandler.ProcessTask)
+ }
+
logger.Info("Posta worker started",
"version", config.Version,
"concurrency", cfg.WorkerConcurrency,
diff --git a/go.mod b/go.mod
index fb6d67d..83ecfe1 100644
--- a/go.mod
+++ b/go.mod
@@ -5,14 +5,15 @@ go 1.26.1
require (
github.com/aws/aws-sdk-go-v2 v1.41.6
github.com/aws/aws-sdk-go-v2/credentials v1.19.15
- github.com/aws/aws-sdk-go-v2/service/s3 v1.99.1
+ github.com/aws/aws-sdk-go-v2/service/s3 v1.100.0
github.com/coreos/go-oidc/v3 v3.18.0
+ github.com/emersion/go-smtp v0.24.0
github.com/golang-jwt/jwt/v5 v5.3.1
github.com/google/uuid v1.6.0
github.com/hibiken/asynq v0.26.0
github.com/jkaninda/go-utils v0.1.4
github.com/jkaninda/logger v0.0.5
- github.com/jkaninda/okapi v0.5.2
+ github.com/jkaninda/okapi v0.5.3
github.com/joho/godotenv v1.5.1
github.com/lib/pq v1.12.3
github.com/pquerna/otp v1.5.0
@@ -46,8 +47,9 @@ require (
github.com/clipperhouse/displaywidth v0.11.0 // indirect
github.com/clipperhouse/uax29/v2 v2.7.0 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
+ github.com/emersion/go-sasl v0.0.0-20241020182733-b788ff22d5a6 // indirect
github.com/fatih/color v1.19.0 // indirect
- github.com/getkin/kin-openapi v0.134.0 // indirect
+ github.com/getkin/kin-openapi v0.135.0 // indirect
github.com/go-jose/go-jose/v4 v4.1.4 // indirect
github.com/go-openapi/jsonpointer v0.22.5 // indirect
github.com/go-openapi/swag/jsonname v0.25.5 // indirect
@@ -68,8 +70,8 @@ require (
github.com/mattn/go-runewidth v0.0.22 // indirect
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
- github.com/oasdiff/yaml v0.0.7 // indirect
- github.com/oasdiff/yaml3 v0.0.6 // indirect
+ github.com/oasdiff/yaml v0.0.9 // indirect
+ github.com/oasdiff/yaml3 v0.0.9 // indirect
github.com/olekukonko/cat v0.0.0-20250911104152-50322a0618f6 // indirect
github.com/olekukonko/errors v1.2.0 // indirect
github.com/olekukonko/ll v0.1.8 // indirect
diff --git a/go.sum b/go.sum
index 6a3898a..34c1ca7 100644
--- a/go.sum
+++ b/go.sum
@@ -24,8 +24,8 @@ github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.22 h1:PUmZeJU6
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.22/go.mod h1:nO6egFBoAaoXze24a2C0NjQCvdpk8OueRoYimvEB9jo=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.22 h1:SE+aQ4DEqG53RRCAIHlCf//B2ycxGH7jFkpnAh/kKPM=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.22/go.mod h1:ES3ynECd7fYeJIL6+oax+uIEljmfps0S70BaQzbMd/o=
-github.com/aws/aws-sdk-go-v2/service/s3 v1.99.1 h1:kU/eBN5+MWNo/LcbNa4hWDdN76hdcd7hocU5kvu7IsU=
-github.com/aws/aws-sdk-go-v2/service/s3 v1.99.1/go.mod h1:Fw9aqhJicIVee1VytBBjH+l+5ov6/PhbtIK/u3rt/ls=
+github.com/aws/aws-sdk-go-v2/service/s3 v1.100.0 h1:7G26Sae6PMKn4kMcU5JzNfrm1YrKwyOhowXPYR2WiWY=
+github.com/aws/aws-sdk-go-v2/service/s3 v1.100.0/go.mod h1:Fw9aqhJicIVee1VytBBjH+l+5ov6/PhbtIK/u3rt/ls=
github.com/aws/smithy-go v1.25.0 h1:Sz/XJ64rwuiKtB6j98nDIPyYrV1nVNJ4YU74gttcl5U=
github.com/aws/smithy-go v1.25.0/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
@@ -50,12 +50,16 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
+github.com/emersion/go-sasl v0.0.0-20241020182733-b788ff22d5a6 h1:oP4q0fw+fOSWn3DfFi4EXdT+B+gTtzx8GC9xsc26Znk=
+github.com/emersion/go-sasl v0.0.0-20241020182733-b788ff22d5a6/go.mod h1:iL2twTeMvZnrg54ZoPDNfJaJaqy0xIQFuBdrLsmspwQ=
+github.com/emersion/go-smtp v0.24.0 h1:g6AfoF140mvW0vLNPD/LuCBLEAdlxOjIXqbIkJIS6Wk=
+github.com/emersion/go-smtp v0.24.0/go.mod h1:ZtRRkbTyp2XTHCA+BmyTFTrj8xY4I+b4McvHxCU2gsQ=
github.com/fatih/color v1.19.0 h1:Zp3PiM21/9Ld6FzSKyL5c/BULoe/ONr9KlbYVOfG8+w=
github.com/fatih/color v1.19.0/go.mod h1:zNk67I0ZUT1bEGsSGyCZYZNrHuTkJJB+r6Q9VuMi0LE=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
-github.com/getkin/kin-openapi v0.134.0 h1:/L5+1+kfe6dXh8Ot/wqiTgUkjOIEJiC0bbYVziHB8rU=
-github.com/getkin/kin-openapi v0.134.0/go.mod h1:wK6ZLG/VgoETO9pcLJ/VmAtIcl/DNlMayNTb716EUxE=
+github.com/getkin/kin-openapi v0.135.0 h1:751SjYfbiwqukYuVjwYEIKNfrSwS5YpA7DZnKSwQgtg=
+github.com/getkin/kin-openapi v0.135.0/go.mod h1:6dd5FJl6RdX4usBtFBaQhk9q62Yb2J0Mk5IhUO/QqFI=
github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA=
github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
github.com/go-openapi/jsonpointer v0.22.5 h1:8on/0Yp4uTb9f4XvTrM2+1CPrV05QPZXu+rvu2o9jcA=
@@ -99,8 +103,8 @@ github.com/jkaninda/go-utils v0.1.4 h1:ZdNlI+yLWc4/S0qKcCNQIPj+6lHSdJcGaxtRADAif
github.com/jkaninda/go-utils v0.1.4/go.mod h1:Aa54jEAcDykc3CnOdreqZG80UfSZOvrYecyusu+oPb4=
github.com/jkaninda/logger v0.0.5 h1:fTHKgDsHtuN8rkSBvwe6QStfi8yIdm8O3r0g99dRDTY=
github.com/jkaninda/logger v0.0.5/go.mod h1:ZUXJ2BdxDPG6e8t6mbKhc2ZFaFi2Iuy/4ukquFrPkFE=
-github.com/jkaninda/okapi v0.5.2 h1:V6YgBBTo8vv0qxHNrDlohg1ss1ZxDXDtoVh48geDLQE=
-github.com/jkaninda/okapi v0.5.2/go.mod h1:sakNPl65ouUMDl1GL8yaNPkLNAF+VTcuPCFQ/v16By4=
+github.com/jkaninda/okapi v0.5.3 h1:8Q+zyg34B+5OquaXGd7phWXN4iZD3vBi0gtVet/2F9E=
+github.com/jkaninda/okapi v0.5.3/go.mod h1:aZcCEWBUQy+tOwvJshSMX0nJq48LEwaYFYwQQ+xhXHQ=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
@@ -129,10 +133,10 @@ github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 h1:RWengNIwukTxcDr9
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826/go.mod h1:TaXosZuwdSHYgviHp1DAtfrULt5eUgsSMsZf+YrPgl8=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
-github.com/oasdiff/yaml v0.0.7 h1:r/BR4tqb+W/5fSV6RknYrfBa+PSZnRRvZ/nUnDdepFQ=
-github.com/oasdiff/yaml v0.0.7/go.mod h1:EaJ6/lcrRLK+syawtvtrHdbrrln4/SUmQw6aBTIlaMs=
-github.com/oasdiff/yaml3 v0.0.6 h1:459QJwIK3pqFs91pIbH/XxCld0ugHd4/F8xHkFjaJPo=
-github.com/oasdiff/yaml3 v0.0.6/go.mod h1:y5+oSEHCPT/DGrS++Wc/479ERge0zTFxaF8PbGKcg2o=
+github.com/oasdiff/yaml v0.0.9 h1:zQOvd2UKoozsSsAknnWoDJlSK4lC0mpmjfDsfqNwX48=
+github.com/oasdiff/yaml v0.0.9/go.mod h1:8lvhgJG4xiKPj3HN5lDow4jZHPlx1i7dIwzkdAo6oAM=
+github.com/oasdiff/yaml3 v0.0.9 h1:rWPrKccrdUm8J0F3sGuU+fuh9+1K/RdJlWF7O/9yw2g=
+github.com/oasdiff/yaml3 v0.0.9/go.mod h1:y5+oSEHCPT/DGrS++Wc/479ERge0zTFxaF8PbGKcg2o=
github.com/olekukonko/cat v0.0.0-20250911104152-50322a0618f6 h1:zrbMGy9YXpIeTnGj4EljqMiZsIcE09mmF8XsD5AYOJc=
github.com/olekukonko/cat v0.0.0-20250911104152-50322a0618f6/go.mod h1:rEKTHC9roVVicUIfZK7DYrdIoM0EOr8mK1Hj5s3JjH0=
github.com/olekukonko/errors v1.2.0 h1:10Zcn4GeV59t/EGqJc8fUjtFT/FuUh5bTMzZ1XwmCRo=
diff --git a/internal/config/config.go b/internal/config/config.go
index 9c383ea..3800a7a 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -44,11 +44,13 @@ type Config struct {
AdminEmail string
AdminPassword string
OpenAPIDocs bool
- MetricsEnabled bool
- WebDir string
- AppWebURL string
- ApiBaseURL string
- CORSOrigins string
+ securitySchemes okapi.SecuritySchemes
+
+ MetricsEnabled bool
+ WebDir string
+ AppWebURL string
+ ApiBaseURL string
+ CORSOrigins string
// Worker settings
EmbeddedWorker bool
@@ -68,6 +70,8 @@ type Config struct {
// System SMTP for platform notifications (daily reports, invitations, etc.)
SystemSMTP SystemSMTPConfig
+ EmailVerificationRequired bool
+
// Encryption key for SMTP password encryption (if empty, base64 encoding is used)
EncryptionKey string
@@ -81,6 +85,20 @@ type Config struct {
BlobS3UseSSL bool
BlobS3PathStyle bool
BlobFSPath string
+
+ // Inbound email settings
+ InboundEnabled bool
+ InboundSMTPHost string
+ InboundSMTPPort int
+ InboundMaxMessageSize int64
+ InboundMaxAttachSize int64
+ InboundWebhookSecret string
+ InboundHostname string
+ InboundTLSMode string
+ InboundTLSCertFile string
+ InboundTLSKeyFile string
+ InboundSMTPRateLimit int // per-IP max sessions per window; 0 disables
+ InboundSMTPRateWindow int // rate-limit window in seconds
}
type SystemSMTPConfig struct {
Host string
@@ -148,10 +166,12 @@ func New() *Config {
AdminEmail: goutils.Env("POSTA_ADMIN_EMAIL", "[email protected]"),
AdminPassword: goutils.Env("POSTA_ADMIN_PASSWORD", "admin1234"),
OpenAPIDocs: goutils.EnvBool("POSTA_OPENAPI_DOCS", true),
- MetricsEnabled: goutils.EnvBool("POSTA_METRICS_ENABLED", false),
- WebDir: goutils.Env("POSTA_WEB_DIR", "web/dist"),
- AppWebURL: goutils.Env("POSTA_WEB_URL", ""),
- ApiBaseURL: goutils.Env("POSTA_API_URL", ""),
+ securitySchemes: okapi.SecuritySchemes{},
+
+ MetricsEnabled: goutils.EnvBool("POSTA_METRICS_ENABLED", false),
+ WebDir: goutils.Env("POSTA_WEB_DIR", "web/dist"),
+ AppWebURL: goutils.Env("POSTA_WEB_URL", ""),
+ ApiBaseURL: goutils.Env("POSTA_API_URL", ""),
CORSOrigins: goutils.Env("POSTA_CORS_ORIGINS", "*"),
@@ -176,6 +196,8 @@ func New() *Config {
Encryption: goutils.Env("POSTA_SYSTEM_SMTP_ENCRYPTION", "starttls"),
},
+ EmailVerificationRequired: goutils.EnvBool("POSTA_EMAIL_VERIFICATION_REQUIRED", true),
+
EncryptionKey: goutils.Env("POSTA_ENCRYPTION_KEY", ""),
BlobProvider: goutils.Env("POSTA_BLOB_PROVIDER", ""),
@@ -187,10 +209,30 @@ func New() *Config {
BlobS3UseSSL: goutils.EnvBool("POSTA_BLOB_S3_USE_SSL", true),
BlobS3PathStyle: goutils.EnvBool("POSTA_BLOB_S3_PATH_STYLE", false),
BlobFSPath: goutils.Env("POSTA_BLOB_FS_PATH", "data/attachments"),
+
+ InboundEnabled: goutils.EnvBool("POSTA_INBOUND_ENABLED", false),
+ InboundSMTPHost: goutils.Env("POSTA_INBOUND_SMTP_HOST", "0.0.0.0"),
+ InboundSMTPPort: goutils.EnvInt("POSTA_INBOUND_SMTP_PORT", 2525),
+ InboundMaxMessageSize: int64(goutils.EnvInt("POSTA_INBOUND_MAX_MESSAGE_SIZE", 26214400)),
+ InboundMaxAttachSize: int64(goutils.EnvInt("POSTA_INBOUND_MAX_ATTACH_SIZE", 10485760)),
+ InboundWebhookSecret: goutils.Env("POSTA_INBOUND_WEBHOOK_SECRET", ""),
+ InboundHostname: goutils.Env("POSTA_INBOUND_HOSTNAME", "posta.local"),
+ InboundTLSMode: goutils.Env("POSTA_INBOUND_TLS_MODE", "none"),
+ InboundTLSCertFile: goutils.Env("POSTA_INBOUND_TLS_CERT_FILE", ""),
+ InboundTLSKeyFile: goutils.Env("POSTA_INBOUND_TLS_KEY_FILE", ""),
+ InboundSMTPRateLimit: goutils.EnvInt("POSTA_INBOUND_SMTP_RATE_LIMIT", 60),
+ InboundSMTPRateWindow: goutils.EnvInt("POSTA_INBOUND_SMTP_RATE_WINDOW", 60),
}
}
func (c *Config) validate() error {
-
+ 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)
+ }
+ if c.InboundTLSCertFile == "" || c.InboundTLSKeyFile == "" {
+ return fmt.Errorf("POSTA_INBOUND_TLS_MODE=%s requires POSTA_INBOUND_TLS_CERT_FILE and POSTA_INBOUND_TLS_KEY_FILE", c.InboundTLSMode)
+ }
+ }
return nil
}
func (c *Config) validateWorker() error {
@@ -228,15 +270,38 @@ func (c *Config) Initialize(app *okapi.Okapi) error {
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowCredentials: true,
})
+
if c.OpenAPIDocs {
+ // Dashboard / JWT-authenticated endpoints.
+ c.securitySchemes = append(c.securitySchemes, okapi.SecurityScheme{
+ Name: "BearerAuth",
+ Description: "Bearer token issued by /auth/login. Send as: `Authorization: Bearer <JWT>`.",
+ Type: "http",
+ Scheme: "bearer",
+ BearerFormat: "JWT",
+ })
+ // API-key authenticated endpoints.
+ c.securitySchemes = append(c.securitySchemes, okapi.SecurityScheme{
+ Name: "ApiKeyAuth",
+ Description: "Long-lived API key. Send as: `Authorization: Bearer <API_KEY>`. Manage keys under Settings → API Keys.",
+ Type: "http",
+ Scheme: "bearer",
+ BearerFormat: "Posta API Key",
+ })
app.WithOpenAPIDocs(okapi.OpenAPI{
Title: "Posta API",
Version: "v1",
License: okapi.License{
- Name: "Apache",
+ Name: "Apache-2.0",
URL: "http://www.apache.org/licenses/LICENSE-2.0",
},
- Servers: apiServers,
+ Contact: okapi.Contact{
+ Name: "Posta",
+ URL: "https://github.com/goposta/posta",
+ Email: "[email protected]",
+ },
+ Servers: apiServers,
+ SecuritySchemes: c.securitySchemes,
})
}
app.WithErrorHandler(errorhandlers.CustomErrorHandler())
diff --git a/internal/cron/jobs/campaign_restart.go b/internal/cron/jobs/campaign_restart.go
new file mode 100644
index 0000000..2d7f63a
--- /dev/null
+++ b/internal/cron/jobs/campaign_restart.go
@@ -0,0 +1,80 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package jobs
+
+import (
+ "context"
+ "time"
+
+ "github.com/goposta/posta/internal/storage/repositories"
+ "github.com/hibiken/asynq"
+ "github.com/jkaninda/logger"
+)
+
+type CampaignBatchEnqueuer interface {
+ EnqueueCampaignBatch(campaignID uint, delay time.Duration) error
+}
+
+type CampaignRestartJob struct {
+ campaignRepo *repositories.CampaignRepository
+ messageRepo *repositories.CampaignMessageRepository
+ producer CampaignBatchEnqueuer
+}
+
+func NewCampaignRestartJob(
+ campaignRepo *repositories.CampaignRepository,
+ messageRepo *repositories.CampaignMessageRepository,
+ producer CampaignBatchEnqueuer,
+) *CampaignRestartJob {
+ return &CampaignRestartJob{
+ campaignRepo: campaignRepo,
+ messageRepo: messageRepo,
+ producer: producer,
+ }
+}
+
+func (j *CampaignRestartJob) Name() string { return "campaign-restart" }
+func (j *CampaignRestartJob) Schedule() string { return "*/5 * * * *" }
+
+const stuckFor = 10 * time.Minute
+
+func (j *CampaignRestartJob) Run(_ context.Context, _ *asynq.Client) error {
+ if j.producer == nil {
+ return nil
+ }
+ stuck, err := j.campaignRepo.FindStuckSending(stuckFor)
+ if err != nil {
+ return err
+ }
+ for _, c := range stuck {
+ pending, err := j.messageRepo.CountPending(c.ID)
+ if err != nil {
+ logger.Warn("campaign-restart: failed to count pending", "campaign_id", c.ID, "error", err)
+ continue
+ }
+ if pending == 0 {
+ continue
+ }
+ if err := j.producer.EnqueueCampaignBatch(c.ID, 0); err != nil {
+ logger.Warn("campaign-restart: failed to re-enqueue batch", "campaign_id", c.ID, "error", err)
+ continue
+ }
+ logger.Info("campaign-restart: re-enqueued stuck campaign", "campaign_id", c.ID, "pending", pending)
+ }
+ return nil
+}
diff --git a/internal/cron/jobs/retention.go b/internal/cron/jobs/retention.go
index dbbc8ea..e9af828 100644
--- a/internal/cron/jobs/retention.go
+++ b/internal/cron/jobs/retention.go
@@ -19,9 +19,12 @@ package jobs
import (
"context"
+ "encoding/json"
"time"
+ "github.com/goposta/posta/internal/models"
"github.com/goposta/posta/internal/services/settings"
+ "github.com/goposta/posta/internal/storage/blob"
"github.com/goposta/posta/internal/storage/repositories"
"github.com/hibiken/asynq"
"github.com/jkaninda/logger"
@@ -30,11 +33,13 @@ import (
// RetentionCleanupJob purges old email logs, audit events, and webhook
// delivery records based on platform retention settings.
type RetentionCleanupJob struct {
- emailRepo *repositories.EmailRepository
- eventRepo *repositories.EventRepository
- whDeliveryRepo *repositories.WebhookDeliveryRepository
- trackingRepo *repositories.TrackingRepository
- settings *settings.Provider
+ emailRepo *repositories.EmailRepository
+ eventRepo *repositories.EventRepository
+ whDeliveryRepo *repositories.WebhookDeliveryRepository
+ trackingRepo *repositories.TrackingRepository
+ inboundEmailRepo *repositories.InboundEmailRepository
+ blobStore blob.Store
+ settings *settings.Provider
}
func NewRetentionCleanupJob(
@@ -53,20 +58,147 @@ func NewRetentionCleanupJob(
}
}
+// SetInboundEmailRepo configures the inbound email repository for cleanup.
+// When nil, inbound emails are not subject to retention cleanup.
+func (j *RetentionCleanupJob) SetInboundEmailRepo(r *repositories.InboundEmailRepository) {
+ j.inboundEmailRepo = 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.
+func (j *RetentionCleanupJob) SetBlobStore(bs blob.Store) {
+ j.blobStore = bs
+}
+
+// deleteOutboundAttachmentBlobs enumerates StorageKeys inside each attachments_json
+// payload and deletes them from blob storage. Returns the number of keys deleted.
+func (j *RetentionCleanupJob) deleteOutboundAttachmentBlobs(jsons []string) int {
+ if j.blobStore == nil {
+ return 0
+ }
+ ctx := context.Background()
+ deleted := 0
+ for _, js := range jsons {
+ if js == "" {
+ continue
+ }
+ var atts []models.Attachment
+ if err := json.Unmarshal([]byte(js), &atts); err != nil {
+ continue
+ }
+ for _, a := range atts {
+ if a.StorageKey == "" {
+ continue
+ }
+ if err := j.blobStore.Delete(ctx, a.StorageKey); err != nil {
+ logger.Warn("retention cleanup: failed to delete attachment blob", "key", a.StorageKey, "error", err)
+ continue
+ }
+ deleted++
+ }
+ }
+ return deleted
+}
+
+// deleteInboundAttachmentBlobs does the same for inbound attachment metadata.
+func (j *RetentionCleanupJob) deleteInboundAttachmentBlobs(jsons []string) int {
+ if j.blobStore == nil {
+ return 0
+ }
+ ctx := context.Background()
+ deleted := 0
+ for _, js := range jsons {
+ if js == "" {
+ continue
+ }
+ var atts []models.InboundAttachmentMeta
+ if err := json.Unmarshal([]byte(js), &atts); err != nil {
+ continue
+ }
+ for _, a := range atts {
+ if a.StorageKey == "" {
+ continue
+ }
+ if err := j.blobStore.Delete(ctx, a.StorageKey); err != nil {
+ logger.Warn("retention cleanup: failed to delete inbound attachment blob", "key", a.StorageKey, "error", err)
+ continue
+ }
+ deleted++
+ }
+ }
+ return deleted
+}
+
+// deleteRawKeys removes each raw .eml blob for the given storage keys.
+func (j *RetentionCleanupJob) deleteRawKeys(keys []string) int {
+ if j.blobStore == nil {
+ return 0
+ }
+ ctx := context.Background()
+ deleted := 0
+ for _, k := range keys {
+ if k == "" {
+ continue
+ }
+ if err := j.blobStore.Delete(ctx, k); err != nil {
+ logger.Warn("retention cleanup: failed to delete raw eml blob", "key", k, "error", err)
+ continue
+ }
+ deleted++
+ }
+ return deleted
+}
+
func (j *RetentionCleanupJob) Name() string { return "retention-cleanup" }
func (j *RetentionCleanupJob) Schedule() string { return "0 3 * * *" } // daily at 03:00 UTC
func (j *RetentionCleanupJob) Run(_ context.Context, _ *asynq.Client) error {
- // Clean up email logs
+ // Clean up email logs (and any blob-stored attachments).
emailRetention := j.settings.RetentionDays()
if emailRetention > 0 {
before := time.Now().AddDate(0, 0, -emailRetention)
+
+ // Outbound attachments
+ if j.blobStore != nil {
+ if jsons, err := j.emailRepo.AttachmentsJSONOlderThan(before); err == nil {
+ n := j.deleteOutboundAttachmentBlobs(jsons)
+ if n > 0 {
+ logger.Info("retention cleanup: deleted outbound attachment blobs", "count", n)
+ }
+ } else {
+ logger.Error("retention cleanup: failed to enumerate outbound attachments", "error", err)
+ }
+ }
+
deleted, err := j.emailRepo.DeleteOlderThan(before)
if err != nil {
logger.Error("retention cleanup: failed to delete old emails", "error", err)
} else if deleted > 0 {
logger.Info("retention cleanup: deleted old emails", "count", deleted, "older_than_days", emailRetention)
}
+
+ if j.inboundEmailRepo != nil {
+ // Inbound attachments + raw .eml
+ if j.blobStore != nil {
+ if jsons, rawKeys, err := j.inboundEmailRepo.InboundBlobKeysOlderThan(before); err == nil {
+ n := j.deleteInboundAttachmentBlobs(jsons)
+ r := j.deleteRawKeys(rawKeys)
+ if n+r > 0 {
+ logger.Info("retention cleanup: deleted inbound blobs", "attachments", n, "raw_eml", r)
+ }
+ } else {
+ logger.Error("retention cleanup: failed to enumerate inbound blobs", "error", err)
+ }
+ }
+
+ deleted, err := j.inboundEmailRepo.DeleteOlderThan(before)
+ if err != nil {
+ logger.Error("retention cleanup: failed to delete old inbound emails", "error", err)
+ } else if deleted > 0 {
+ logger.Info("retention cleanup: deleted old inbound emails", "count", deleted, "older_than_days", emailRetention)
+ }
+ }
}
// Clean up audit/event logs
diff --git a/internal/handlers/admin_handler.go b/internal/handlers/admin_handler.go
index 284f649..618e5bd 100644
--- a/internal/handlers/admin_handler.go
+++ b/internal/handlers/admin_handler.go
@@ -64,8 +64,9 @@ type AdminCreateUserRequest struct {
type AdminUpdateUserRequest struct {
ID int `param:"id"`
Body struct {
- Role string `json:"role" enum:"admin,user"`
- Active *bool `json:"active"`
+ Role string `json:"role" enum:"admin,user"`
+ Active *bool `json:"active"`
+ EmailVerified *bool `json:"email_verified"`
} `json:"body"`
}
type AdminDeleteUserRequest struct {
@@ -90,6 +91,11 @@ type PlatformMetrics struct {
SharedSmtpServers int64 `json:"shared_smtp_servers"`
TotalDomains int64 `json:"total_domains"`
TotalWorkspaces int64 `json:"total_workspaces"`
+ TotalInbound int64 `json:"total_inbound"`
+ ForwardedInbound int64 `json:"forwarded_inbound"`
+ FailedInbound int64 `json:"failed_inbound"`
+ ReceivedInbound int64 `json:"received_inbound"`
+ RejectedInbound int64 `json:"rejected_inbound"`
WebhookDeliveries *repositories.WebhookDeliveryStats `json:"webhook_deliveries"`
ServerUptime float64 `json:"server_uptime_seconds"`
CurrentGoroutines int `json:"current_goroutines"`
@@ -128,6 +134,9 @@ type UserDetailMetrics struct {
TotalSuppressions int64 `json:"total_suppressions"`
TotalDomains int64 `json:"total_domains"`
TotalSmtpServers int64 `json:"total_smtp_servers"`
+ TotalInbound int64 `json:"total_inbound"`
+ ForwardedInbound int64 `json:"forwarded_inbound"`
+ FailedInbound int64 `json:"failed_inbound"`
WebhookDeliveries *repositories.WebhookDeliveryStats `json:"webhook_deliveries"`
}
@@ -216,6 +225,16 @@ func (h *AdminHandler) UpdateUser(c *okapi.Context, req *AdminUpdateUserRequest)
}
user.Active = *req.Body.Active
}
+ if req.Body.EmailVerified != nil {
+ if *req.Body.EmailVerified {
+ if user.EmailVerifiedAt == nil {
+ now := time.Now()
+ user.EmailVerifiedAt = &now
+ }
+ } else {
+ user.EmailVerifiedAt = nil
+ }
+ }
if err := h.userRepo.Update(user); err != nil {
return c.AbortInternalServerError("failed to update user")
}
@@ -358,6 +377,13 @@ func (h *AdminHandler) Metrics(c *okapi.Context) error {
h.db.Model(&models.Domain{}).Count(&m.TotalDomains)
h.db.Model(&models.Workspace{}).Count(&m.TotalWorkspaces)
+ // Inbound email counts (platform-wide)
+ h.db.Model(&models.InboundEmail{}).Count(&m.TotalInbound)
+ h.db.Model(&models.InboundEmail{}).Where("status = ?", models.InboundStatusForwarded).Count(&m.ForwardedInbound)
+ h.db.Model(&models.InboundEmail{}).Where("status = ?", models.InboundStatusFailed).Count(&m.FailedInbound)
+ h.db.Model(&models.InboundEmail{}).Where("status = ?", models.InboundStatusReceived).Count(&m.ReceivedInbound)
+ h.db.Model(&models.InboundEmail{}).Where("status = ?", models.InboundStatusRejected).Count(&m.RejectedInbound)
+
if m.TotalEmails > 0 {
m.FailureRate = float64(m.FailedEmails) / float64(m.TotalEmails) * 100
}
@@ -426,6 +452,9 @@ func (h *AdminHandler) UserMetrics(c *okapi.Context, req *AdminGetUserRequest) e
h.db.Model(&models.Suppression{}).Where("user_id = ?", req.ID).Count(&m.TotalSuppressions)
h.db.Model(&models.Domain{}).Where("user_id = ?", req.ID).Count(&m.TotalDomains)
h.db.Model(&models.SMTPServer{}).Where("user_id = ?", req.ID).Count(&m.TotalSmtpServers)
+ h.db.Model(&models.InboundEmail{}).Where("user_id = ?", req.ID).Count(&m.TotalInbound)
+ h.db.Model(&models.InboundEmail{}).Where("user_id = ? AND status = ?", req.ID, models.InboundStatusForwarded).Count(&m.ForwardedInbound)
+ h.db.Model(&models.InboundEmail{}).Where("user_id = ? AND status = ?", req.ID, models.InboundStatusFailed).Count(&m.FailedInbound)
if m.TotalEmails > 0 {
m.FailureRate = float64(m.FailedEmails) / float64(m.TotalEmails) * 100
diff --git a/internal/handlers/analytics_handler.go b/internal/handlers/analytics_handler.go
index 6ad40a0..6c6ac34 100644
--- a/internal/handlers/analytics_handler.go
+++ b/internal/handlers/analytics_handler.go
@@ -191,6 +191,70 @@ func (h *AnalyticsHandler) UserDashboardAnalytics(c *okapi.Context, req *Dashboa
return ok(c, resp)
}
+type ProviderBreakdownRequest struct {
+ From string `query:"from"`
+ To string `query:"to"`
+}
+
+type ProviderBreakdownResponse struct {
+ Providers []repositories.ProviderBreakdownPoint `json:"providers"`
+}
+
+// UserProviderBreakdown returns delivery counts grouped by recipient mailbox
+// provider (Gmail, Outlook, Yahoo, ...) for the authenticated scope.
+func (h *AnalyticsHandler) UserProviderBreakdown(c *okapi.Context, req *ProviderBreakdownRequest) error {
+ scope := getScope(c)
+ ctx := c.Request().Context()
+
+ scopeKey := int(scope.UserID)
+ if scope.WorkspaceID != nil {
+ scopeKey = int(*scope.WorkspaceID) + 1000000
+ }
+ cacheKey := cache.UserProviderBreakdownKey(scopeKey, req.From, req.To)
+ var resp ProviderBreakdownResponse
+ if h.cache.Get(ctx, cacheKey, &resp) {
+ return ok(c, resp)
+ }
+
+ from, to := parseTimeRange(req.From, req.To)
+
+ var rows []repositories.ProviderBreakdownPoint
+ var err error
+ if scope.WorkspaceID != nil {
+ rows, err = h.repo.WorkspaceProviderBreakdown(*scope.WorkspaceID, from, to)
+ } else {
+ rows, err = h.repo.ProviderBreakdown(scope.UserID, from, to)
+ }
+ if err != nil {
+ return c.AbortInternalServerError("failed to fetch provider breakdown")
+ }
+
+ resp = ProviderBreakdownResponse{Providers: rows}
+ h.cache.Set(ctx, cacheKey, resp, cache.AnalyticsTTL)
+ return ok(c, resp)
+}
+
+// AdminProviderBreakdown returns provider breakdown across all users.
+func (h *AnalyticsHandler) AdminProviderBreakdown(c *okapi.Context, req *ProviderBreakdownRequest) error {
+ ctx := c.Request().Context()
+
+ cacheKey := cache.AdminProviderBreakdownKey(req.From, req.To)
+ var resp ProviderBreakdownResponse
+ if h.cache.Get(ctx, cacheKey, &resp) {
+ return ok(c, resp)
+ }
+
+ from, to := parseTimeRange(req.From, req.To)
+ rows, err := h.repo.AdminProviderBreakdown(from, to)
+ if err != nil {
+ return c.AbortInternalServerError("failed to fetch provider breakdown")
+ }
+
+ resp = ProviderBreakdownResponse{Providers: rows}
+ h.cache.Set(ctx, cacheKey, resp, cache.AnalyticsTTL)
+ return ok(c, resp)
+}
+
func (h *AnalyticsHandler) AdminDashboardAnalytics(c *okapi.Context, req *DashboardAnalyticsRequest) error {
ctx := c.Request().Context()
diff --git a/internal/handlers/campaign_handler.go b/internal/handlers/campaign_handler.go
index 53ff269..0227711 100644
--- a/internal/handlers/campaign_handler.go
+++ b/internal/handlers/campaign_handler.go
@@ -18,11 +18,14 @@
package handlers
import (
+ "errors"
+ "strings"
"time"
"github.com/goposta/posta/internal/models"
"github.com/goposta/posta/internal/storage/repositories"
"github.com/goposta/posta/internal/worker"
+ "github.com/jkaninda/logger"
"github.com/jkaninda/okapi"
)
@@ -32,6 +35,7 @@ type CampaignHandler struct {
listRepo *repositories.SubscriberListRepository
subscriberRepo *repositories.SubscriberRepository
templateRepo *repositories.TemplateRepository
+ domainRepo *repositories.DomainRepository
producer *worker.Producer
}
@@ -41,6 +45,7 @@ func NewCampaignHandler(
listRepo *repositories.SubscriberListRepository,
subscriberRepo *repositories.SubscriberRepository,
templateRepo *repositories.TemplateRepository,
+ domainRepo *repositories.DomainRepository,
producer *worker.Producer,
) *CampaignHandler {
return &CampaignHandler{
@@ -49,6 +54,7 @@ func NewCampaignHandler(
listRepo: listRepo,
subscriberRepo: subscriberRepo,
templateRepo: templateRepo,
+ domainRepo: domainRepo,
producer: producer,
}
}
@@ -187,17 +193,27 @@ func (h *CampaignHandler) List(c *okapi.Context, req *ListCampaignsRequest) erro
return c.AbortInternalServerError("failed to list campaigns")
}
+ // Single grouped query instead of N per-campaign stats calls.
+ ids := make([]uint, len(items))
+ for i, it := range items {
+ ids[i] = it.ID
+ }
+ countsByID, cerr := h.messageRepo.CountByStatusForCampaigns(ids)
+ if cerr != nil {
+ // Stats are best-effort; still return the list.
+ countsByID = nil
+ }
+
result := make([]CampaignWithStats, len(items))
for i, item := range items {
- stats := h.buildStats(item.ID)
- result[i] = CampaignWithStats{Campaign: item, Stats: stats}
+ result[i] = CampaignWithStats{Campaign: item, Stats: statsFromCounts(countsByID[item.ID])}
}
return paginated(c, result, total, page, size)
}
func (h *CampaignHandler) Get(c *okapi.Context, req *CampaignActionRequest) error {
- campaign, err := h.campaignRepo.FindByID(uint(req.ID))
- if err != nil || !ownsResource(c, campaign.UserID, campaign.WorkspaceID) {
+ campaign, err := h.findScoped(c, uint(req.ID))
+ if err != nil {
return c.AbortNotFound("campaign not found")
}
stats := h.buildStats(campaign.ID)
@@ -208,8 +224,8 @@ func (h *CampaignHandler) Update(c *okapi.Context, req *UpdateCampaignRequest) e
if err := requireEdit(c); err != nil {
return c.AbortForbidden("insufficient workspace permissions", err)
}
- campaign, err := h.campaignRepo.FindByID(uint(req.ID))
- if err != nil || !ownsResource(c, campaign.UserID, campaign.WorkspaceID) {
+ campaign, err := h.findScoped(c, uint(req.ID))
+ if err != nil {
return c.AbortNotFound("campaign not found")
}
if campaign.Status != models.CampaignStatusDraft {
@@ -271,14 +287,18 @@ func (h *CampaignHandler) Delete(c *okapi.Context, req *CampaignActionRequest) e
if err := requireEdit(c); err != nil {
return c.AbortForbidden("insufficient workspace permissions", err)
}
- campaign, err := h.campaignRepo.FindByID(uint(req.ID))
- if err != nil || !ownsResource(c, campaign.UserID, campaign.WorkspaceID) {
+ campaign, err := h.findScoped(c, uint(req.ID))
+ if err != nil {
return c.AbortNotFound("campaign not found")
}
- if campaign.Status != models.CampaignStatusDraft && campaign.Status != models.CampaignStatusCancelled {
- return c.AbortBadRequest("can only delete draft or cancelled campaigns")
+ // Block deletion mid-flight so the worker doesn't race against row removal.
+ // Callers should Cancel first, then Delete.
+ if campaign.Status == models.CampaignStatusSending {
+ return c.AbortBadRequest("cancel the campaign before deleting it")
}
- if err := h.campaignRepo.Delete(campaign.ID); err != nil {
+ // Snapshot stats so post-deletion analytics survive.
+ snapshot := h.snapshotFor(campaign)
+ if err := h.campaignRepo.Delete(campaign.ID, snapshot); err != nil {
return c.AbortInternalServerError("failed to delete campaign")
}
return noContent(c)
@@ -288,28 +308,54 @@ func (h *CampaignHandler) Send(c *okapi.Context, req *CampaignActionRequest) err
if err := requireEdit(c); err != nil {
return c.AbortForbidden("insufficient workspace permissions", err)
}
- campaign, err := h.campaignRepo.FindByID(uint(req.ID))
- if err != nil || !ownsResource(c, campaign.UserID, campaign.WorkspaceID) {
+ campaign, err := h.findScoped(c, uint(req.ID))
+ if err != nil {
return c.AbortNotFound("campaign not found")
}
if campaign.Status != models.CampaignStatusDraft {
return c.AbortBadRequest("can only send draft campaigns")
}
+ // Deliverability check: surface unverified sender domains as a warning in
+ // logs rather than blocking, since the SMTP-server/shared-server layer has
+ // its own policy and legitimate setups exist where ownership isn't yet
+ // proven (DNS propagation, shared-server tenants, etc.).
+ h.warnSenderDeliverable(campaign)
+
if campaign.ScheduledAt != nil && campaign.ScheduledAt.After(time.Now()) {
- // Schedule for later
- if err := h.campaignRepo.UpdateStatus(campaign.ID, models.CampaignStatusScheduled); err != nil {
- return c.AbortInternalServerError("failed to schedule campaign")
+ if err := h.campaignRepo.TransitionStatus(
+ campaign.ID,
+ []models.CampaignStatus{models.CampaignStatusDraft},
+ models.CampaignStatusScheduled,
+ ); err != nil {
+ return translateTransitionErr(c, err, "failed to schedule campaign")
}
campaign.Status = models.CampaignStatusScheduled
return ok(c, campaign)
}
- // Send immediately
- if err := h.campaignRepo.UpdateStatus(campaign.ID, models.CampaignStatusSending); err != nil {
- return c.AbortInternalServerError("failed to update campaign status")
+ if h.producer == nil {
+ return c.AbortInternalServerError("background worker is not configured; cannot send campaigns")
}
+
+ // Atomically claim the draft -> sending transition. Losing the race returns 409
+ // so a double-click or concurrent Send doesn't double-enqueue.
+ if err := h.campaignRepo.TransitionStatus(
+ campaign.ID,
+ []models.CampaignStatus{models.CampaignStatusDraft},
+ models.CampaignStatusSending,
+ ); err != nil {
+ return translateTransitionErr(c, err, "failed to update campaign status")
+ }
+
+ // Idempotent enqueue: TaskID dedupes retries of the same campaign start.
if err := h.producer.EnqueueCampaignStart(campaign.ID); err != nil {
+ // Roll back so the campaign is retryable, not stuck.
+ _ = h.campaignRepo.TransitionStatus(
+ campaign.ID,
+ []models.CampaignStatus{models.CampaignStatusSending},
+ models.CampaignStatusDraft,
+ )
return c.AbortInternalServerError("failed to enqueue campaign")
}
campaign.Status = models.CampaignStatusSending
@@ -320,15 +366,16 @@ func (h *CampaignHandler) Pause(c *okapi.Context, req *CampaignActionRequest) er
if err := requireEdit(c); err != nil {
return c.AbortForbidden("insufficient workspace permissions", err)
}
- campaign, err := h.campaignRepo.FindByID(uint(req.ID))
- if err != nil || !ownsResource(c, campaign.UserID, campaign.WorkspaceID) {
+ campaign, err := h.findScoped(c, uint(req.ID))
+ if err != nil {
return c.AbortNotFound("campaign not found")
}
- if campaign.Status != models.CampaignStatusSending {
- return c.AbortBadRequest("can only pause sending campaigns")
- }
- if err := h.campaignRepo.UpdateStatus(campaign.ID, models.CampaignStatusPaused); err != nil {
- return c.AbortInternalServerError("failed to pause campaign")
+ if err := h.campaignRepo.TransitionStatus(
+ campaign.ID,
+ []models.CampaignStatus{models.CampaignStatusSending},
+ models.CampaignStatusPaused,
+ ); err != nil {
+ return translateTransitionErr(c, err, "failed to pause campaign")
}
campaign.Status = models.CampaignStatusPaused
return ok(c, campaign)
@@ -338,17 +385,26 @@ func (h *CampaignHandler) Resume(c *okapi.Context, req *CampaignActionRequest) e
if err := requireEdit(c); err != nil {
return c.AbortForbidden("insufficient workspace permissions", err)
}
- campaign, err := h.campaignRepo.FindByID(uint(req.ID))
- if err != nil || !ownsResource(c, campaign.UserID, campaign.WorkspaceID) {
+ campaign, err := h.findScoped(c, uint(req.ID))
+ if err != nil {
return c.AbortNotFound("campaign not found")
}
- if campaign.Status != models.CampaignStatusPaused {
- return c.AbortBadRequest("can only resume paused campaigns")
+ if h.producer == nil {
+ return c.AbortInternalServerError("background worker is not configured; cannot resume campaigns")
}
- if err := h.campaignRepo.UpdateStatus(campaign.ID, models.CampaignStatusSending); err != nil {
- return c.AbortInternalServerError("failed to resume campaign")
+ if err := h.campaignRepo.TransitionStatus(
+ campaign.ID,
+ []models.CampaignStatus{models.CampaignStatusPaused},
+ models.CampaignStatusSending,
+ ); err != nil {
+ return translateTransitionErr(c, err, "failed to resume campaign")
}
if err := h.producer.EnqueueCampaignBatch(campaign.ID, 0); err != nil {
+ _ = h.campaignRepo.TransitionStatus(
+ campaign.ID,
+ []models.CampaignStatus{models.CampaignStatusSending},
+ models.CampaignStatusPaused,
+ )
return c.AbortInternalServerError("failed to enqueue campaign batch")
}
campaign.Status = models.CampaignStatusSending
@@ -359,18 +415,24 @@ func (h *CampaignHandler) Cancel(c *okapi.Context, req *CampaignActionRequest) e
if err := requireEdit(c); err != nil {
return c.AbortForbidden("insufficient workspace permissions", err)
}
- campaign, err := h.campaignRepo.FindByID(uint(req.ID))
- if err != nil || !ownsResource(c, campaign.UserID, campaign.WorkspaceID) {
+ campaign, err := h.findScoped(c, uint(req.ID))
+ if err != nil {
return c.AbortNotFound("campaign not found")
}
- if campaign.Status != models.CampaignStatusSending &&
- campaign.Status != models.CampaignStatusPaused &&
- campaign.Status != models.CampaignStatusScheduled {
- return c.AbortBadRequest("can only cancel sending, paused, or scheduled campaigns")
- }
- if err := h.campaignRepo.UpdateStatus(campaign.ID, models.CampaignStatusCancelled); err != nil {
- return c.AbortInternalServerError("failed to cancel campaign")
- }
+ if err := h.campaignRepo.TransitionStatus(
+ campaign.ID,
+ []models.CampaignStatus{
+ models.CampaignStatusSending,
+ models.CampaignStatusPaused,
+ models.CampaignStatusScheduled,
+ },
+ models.CampaignStatusCancelled,
+ ); err != nil {
+ return translateTransitionErr(c, err, "failed to cancel campaign")
+ }
+ // Drain: mark still-pending messages as skipped. Already-queued emails are
+ // filtered at dispatch time by EmailSendHandler checking the campaign status.
+ _, _ = h.messageRepo.SkipPendingForCampaign(campaign.ID, "campaign cancelled")
campaign.Status = models.CampaignStatusCancelled
return ok(c, campaign)
}
@@ -379,8 +441,8 @@ func (h *CampaignHandler) Duplicate(c *okapi.Context, req *CampaignActionRequest
if err := requireEdit(c); err != nil {
return c.AbortForbidden("insufficient workspace permissions", err)
}
- campaign, err := h.campaignRepo.FindByID(uint(req.ID))
- if err != nil || !ownsResource(c, campaign.UserID, campaign.WorkspaceID) {
+ campaign, err := h.findScoped(c, uint(req.ID))
+ if err != nil {
return c.AbortNotFound("campaign not found")
}
scope := getScope(c)
@@ -395,13 +457,13 @@ func (h *CampaignHandler) Duplicate(c *okapi.Context, req *CampaignActionRequest
TemplateID: campaign.TemplateID,
TemplateVersionID: campaign.TemplateVersionID,
Language: campaign.Language,
- TemplateData: campaign.TemplateData,
+ TemplateData: cloneTemplateData(campaign.TemplateData),
Status: models.CampaignStatusDraft,
ListID: campaign.ListID,
SendRate: campaign.SendRate,
SendAtLocalTime: campaign.SendAtLocalTime,
ABTestEnabled: campaign.ABTestEnabled,
- ABTestVariants: campaign.ABTestVariants,
+ ABTestVariants: append(models.ABTestVariants(nil), campaign.ABTestVariants...),
}
if err := h.campaignRepo.Create(clone); err != nil {
@@ -411,8 +473,8 @@ func (h *CampaignHandler) Duplicate(c *okapi.Context, req *CampaignActionRequest
}
func (h *CampaignHandler) ListMessages(c *okapi.Context, req *ListCampaignMessagesRequest) error {
- campaign, err := h.campaignRepo.FindByID(uint(req.ID))
- if err != nil || !ownsResource(c, campaign.UserID, campaign.WorkspaceID) {
+ campaign, err := h.findScoped(c, uint(req.ID))
+ if err != nil {
return c.AbortNotFound("campaign not found")
}
page, size, offset := normalizePageParams(req.Page, req.Size)
@@ -423,6 +485,108 @@ func (h *CampaignHandler) ListMessages(c *okapi.Context, req *ListCampaignMessag
return paginated(c, items, total, page, size)
}
+// findScoped centralizes the "find + workspace ownership check" pattern so it
+// can't be forgotten at a callsite.
+func (h *CampaignHandler) findScoped(c *okapi.Context, id uint) (*models.Campaign, error) {
+ return h.campaignRepo.FindByIDForScope(id, getScope(c))
+}
+
+// warnSenderDeliverable logs (but does not block) when the sender domain is
+// registered for this user/workspace but lacks ownership/SPF/DKIM verification.
+// Blocking belongs to the SMTP-server layer, which already enforces per-server
+// policy — here we just give the operator a hint that their bounce rate is
+// about to spike.
+func (h *CampaignHandler) warnSenderDeliverable(campaign *models.Campaign) {
+ if h.domainRepo == nil {
+ return
+ }
+ at := strings.LastIndexByte(campaign.FromEmail, '@')
+ if at < 0 || at == len(campaign.FromEmail)-1 {
+ return
+ }
+ domain := strings.ToLower(campaign.FromEmail[at+1:])
+ d, err := h.domainRepo.FindByUserIDAndDomain(campaign.UserID, domain)
+ if err != nil || d == nil {
+ return
+ }
+ if !d.OwnershipVerified || !d.SPFVerified || !d.DKIMVerified {
+ logger.Warn("campaign: sending from domain with incomplete DNS verification",
+ "campaign_id", campaign.ID,
+ "domain", domain,
+ "ownership_verified", d.OwnershipVerified,
+ "spf_verified", d.SPFVerified,
+ "dkim_verified", d.DKIMVerified,
+ )
+ }
+}
+
+// snapshotFor captures the pre-deletion stats of a campaign so reports survive.
+func (h *CampaignHandler) snapshotFor(campaign *models.Campaign) models.TemplateData {
+ stats := h.buildStats(campaign.ID)
+ if stats == nil {
+ return nil
+ }
+ return models.TemplateData{
+ "total": stats.Total,
+ "pending": stats.Pending,
+ "queued": stats.Queued,
+ "sent": stats.Sent,
+ "failed": stats.Failed,
+ "skipped": stats.Skipped,
+ "snapshot_at": time.Now().UTC().Format(time.RFC3339),
+ "from_email": campaign.FromEmail,
+ "list_id": campaign.ListID,
+ "template_id": campaign.TemplateID,
+ }
+}
+
+// cloneTemplateData is a shallow copy at the top level; campaign template data
+// is JSON so shared references below the top level would only matter if a
+// caller mutated them, which is not a pattern we use.
+func cloneTemplateData(src models.TemplateData) models.TemplateData {
+ if src == nil {
+ return nil
+ }
+ dst := make(models.TemplateData, len(src))
+ for k, v := range src {
+ dst[k] = v
+ }
+ return dst
+}
+
+// translateTransitionErr maps an atomic transition failure to either 409 (on
+// conflict) or 500 (on any other DB error).
+func translateTransitionErr(c *okapi.Context, err error, genericMsg string) error {
+ if errors.Is(err, repositories.ErrStatusConflict) {
+ return c.AbortConflict("campaign is not in a state that allows this action")
+ }
+ return c.AbortInternalServerError(genericMsg)
+}
+
+// statsFromCounts projects a status->count map into the CampaignStats shape.
+func statsFromCounts(counts map[models.CampaignMessageStatus]int64) *CampaignStats {
+ if counts == nil {
+ return nil
+ }
+ stats := &CampaignStats{}
+ for status, count := range counts {
+ stats.Total += count
+ switch status {
+ case models.CampaignMsgPending:
+ stats.Pending = count
+ case models.CampaignMsgQueued:
+ stats.Queued = count
+ case models.CampaignMsgSent:
+ stats.Sent = count
+ case models.CampaignMsgFailed:
+ stats.Failed = count
+ case models.CampaignMsgSkipped:
+ stats.Skipped = count
+ }
+ }
+ return stats
+}
+
// buildStats computes stats for a campaign from the message counts.
func (h *CampaignHandler) buildStats(campaignID uint) *CampaignStats {
counts, err := h.messageRepo.CountByStatus(campaignID)
diff --git a/internal/handlers/dashboard_handler.go b/internal/handlers/dashboard_handler.go
index 31c941a..0badd26 100644
--- a/internal/handlers/dashboard_handler.go
+++ b/internal/handlers/dashboard_handler.go
@@ -49,6 +49,9 @@ type DashboardStats struct {
TotalBounces int64 `json:"total_bounces"`
TotalSuppressions int64 `json:"total_suppressions"`
TotalWebhooks int64 `json:"total_webhooks"`
+ TotalInbound int64 `json:"total_inbound"`
+ ForwardedInbound int64 `json:"forwarded_inbound"`
+ FailedInbound int64 `json:"failed_inbound"`
DailyVolume []DailyVolume `json:"daily_volume"`
// Webhook delivery stats
@@ -106,6 +109,11 @@ func (h *DashboardHandler) Stats(c *okapi.Context) error {
applyScope(&models.Suppression{}).Count(&stats.TotalSuppressions)
applyScope(&models.Webhook{}).Count(&stats.TotalWebhooks)
+ // Inbound email counts
+ applyScope(&models.InboundEmail{}).Count(&stats.TotalInbound)
+ applyScope(&models.InboundEmail{}).Where("status = ?", models.InboundStatusForwarded).Count(&stats.ForwardedInbound)
+ applyScope(&models.InboundEmail{}).Where("status = ?", models.InboundStatusFailed).Count(&stats.FailedInbound)
+
// Failure rate
if stats.TotalEmails > 0 {
stats.FailureRate = float64(stats.FailedEmails) / float64(stats.TotalEmails) * 100
diff --git a/internal/handlers/helper.go b/internal/handlers/helper.go
index a42a131..1c2332c 100644
--- a/internal/handlers/helper.go
+++ b/internal/handlers/helper.go
@@ -18,8 +18,10 @@
package handlers
import (
+ "encoding/base64"
"errors"
"net/http"
+ "strings"
"github.com/goposta/posta/internal/dto"
"github.com/goposta/posta/internal/models"
@@ -30,6 +32,20 @@ import (
var errForbidden = errors.New("insufficient workspace permissions: editor role or higher required")
+// 1x1 transparent GIF
+var transparentPixel, _ = base64.StdEncoding.DecodeString("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")
+var botUASubstrings = []string{
+ "bot", "crawler", "spider", "scanner",
+ "barracuda", "mimecast", "proofpoint",
+ "symantec", "trendmicro", "fortinet",
+ "sophos", "messagelabs", "ironport",
+ "safelinks",
+ "googleimageproxy",
+ "yahoomailproxy",
+ "http-client", "go-http-client", "curl/", "wget/",
+ "headlesschrome", "phantomjs", "puppeteer", "playwright",
+}
+
// QuotaChecker verifies that creating a resource would not exceed plan limits.
type QuotaChecker interface {
CheckQuota(db *gorm.DB, userID uint, workspaceID *uint, resource string) error
@@ -117,3 +133,15 @@ func paginated[T any](c *okapi.Context, items []T, total int64, page, size int)
},
})
}
+func isBotUA(ua string) bool {
+ if ua == "" {
+ return true
+ }
+ low := strings.ToLower(ua)
+ for _, needle := range botUASubstrings {
+ if strings.Contains(low, needle) {
+ return true
+ }
+ }
+ return false
+}
diff --git a/internal/handlers/inbound_handler.go b/internal/handlers/inbound_handler.go
new file mode 100644
index 0000000..d0fa23b
--- /dev/null
+++ b/internal/handlers/inbound_handler.go
@@ -0,0 +1,518 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package handlers
+
+import (
+ "context"
+ "crypto/sha256"
+ "crypto/subtle"
+ "encoding/base64"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "io"
+ "mime"
+ "net/http"
+ "strings"
+ "time"
+
+ "github.com/goposta/posta/internal/models"
+ "github.com/goposta/posta/internal/services/eventbus"
+ "github.com/goposta/posta/internal/services/inbound"
+ "github.com/goposta/posta/internal/storage/blob"
+ "github.com/goposta/posta/internal/storage/repositories"
+ "github.com/goposta/posta/internal/worker"
+ "github.com/jkaninda/logger"
+ "github.com/jkaninda/okapi"
+)
+
+// InboundHandler serves inbound-email HTTP endpoints: the generic webhook ingest
+// endpoint, list/get for authenticated users, and attachment downloads.
+type InboundHandler struct {
+ svc *inbound.Service
+ repo *repositories.InboundEmailRepository
+ blobStore blob.Store
+ producer inbound.Enqueuer
+ bus *eventbus.EventBus
+ secret string
+ hmacKey []byte
+}
+
+func NewInboundHandler(
+ svc *inbound.Service,
+ repo *repositories.InboundEmailRepository,
+ blobStore blob.Store,
+ secret string,
+ hmacKey []byte,
+) *InboundHandler {
+ return &InboundHandler{
+ svc: svc,
+ repo: repo,
+ blobStore: blobStore,
+ secret: secret,
+ hmacKey: hmacKey,
+ }
+}
+
+// SetEnqueuer configures the worker enqueuer for the retry endpoint.
+func (h *InboundHandler) SetEnqueuer(eq inbound.Enqueuer) { h.producer = eq }
+
+// SetEventBus configures the event bus used for SSE streaming.
+func (h *InboundHandler) SetEventBus(b *eventbus.EventBus) { h.bus = b }
+
+// Stream pushes email.inbound.received events to the authenticated user via SSE.
+// Events from other users' inboxes are filtered out.
+func (h *InboundHandler) Stream(c *okapi.Context) error {
+ if h.bus == nil {
+ return c.AbortNotFound("inbound stream not configured")
+ }
+ ctx := c.Request().Context()
+ scope := getScope(c)
+
+ ch, unsub := h.bus.Subscribe()
+ defer unsub()
+
+ msgCh := make(chan okapi.Message, 4)
+ msgCh <- okapi.Message{
+ Event: "system.info",
+ Data: okapi.M{
+ "user_id": scope.UserID,
+ "timestamp": time.Now().UTC().Format(time.RFC3339),
+ },
+ }
+
+ go func() {
+ defer close(msgCh)
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case evt, ok := <-ch:
+ if !ok {
+ return
+ }
+ if evt.Type != "email.inbound.received" && evt.Type != "email.inbound.forwarded" && evt.Type != "email.inbound.failed" {
+ continue
+ }
+ if evt.ActorID == nil || *evt.ActorID != scope.UserID {
+ 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,
+ })
+}
+
+// contentDisposition builds a safe Content-Disposition header. Non-ASCII filenames
+// are RFC 5987 encoded; quotes and CR/LF are stripped from the fallback name.
+func contentDisposition(filename string) string {
+ ascii := strings.Map(func(r rune) rune {
+ if r < 0x20 || r == 0x7f || r == '"' || r == '\\' || r > 0x7e {
+ return -1
+ }
+ return r
+ }, filename)
+ if ascii == "" {
+ ascii = "attachment"
+ }
+ return `attachment; filename="` + ascii + `"; filename*=UTF-8''` + urlPathEscape(filename)
+}
+
+// urlPathEscape percent-encodes a filename per RFC 5987 / 3986 unreserved.
+func urlPathEscape(s string) string {
+ const unreserved = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~"
+ var b strings.Builder
+ for _, c := range []byte(s) {
+ if strings.IndexByte(unreserved, c) >= 0 {
+ b.WriteByte(c)
+ } else {
+ b.WriteByte('%')
+ const hexd = "0123456789ABCDEF"
+ b.WriteByte(hexd[c>>4])
+ b.WriteByte(hexd[c&0x0f])
+ }
+ }
+ return b.String()
+}
+
+// constantTimeSecretEqual compares two secrets in constant time, including length.
+func constantTimeSecretEqual(a, b string) bool {
+ if len(a) != len(b) {
+ // still run the compare to equalize timing
+ _ = subtle.ConstantTimeCompare([]byte(a), []byte(a))
+ return false
+ }
+ return subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1
+}
+
+// DedupFallbackHash derives a stable hash for messages without a Message-ID.
+// Used by the webhook path to reject near-duplicate retries.
+func DedupFallbackHash(sender string, recipients []string, subject string, size int64) string {
+ h := sha256.New()
+ h.Write([]byte(strings.ToLower(sender)))
+ h.Write([]byte{0})
+ for _, r := range recipients {
+ h.Write([]byte(strings.ToLower(r)))
+ h.Write([]byte{0})
+ }
+ h.Write([]byte(subject))
+ h.Write([]byte{0})
+ h.Write([]byte(mime.QEncoding.Encode("utf-8", "") + hex.EncodeToString([]byte{byte(size), byte(size >> 8), byte(size >> 16), byte(size >> 24)})))
+ return "fh-" + hex.EncodeToString(h.Sum(nil))[:24]
+}
+
+// InboundWebhookAttachment is the normalized attachment shape accepted on the
+// generic webhook — content is base64-encoded. Providers (Mailgun/SendGrid/SES)
+// can be adapted upstream to this shape.
+type InboundWebhookAttachment struct {
+ Filename string `json:"filename"`
+ ContentType string `json:"content_type"`
+ Content string `json:"content" doc:"Base64-encoded content"`
+}
+
+// InboundWebhookRequest is the normalized inbound-email payload accepted on the
+// public webhook endpoint.
+type InboundWebhookRequest struct {
+ PostaInboundSecret string `header:"X-Posta-Inbound-Secret" required:"true"`
+ Body struct {
+ From string `json:"from" required:"true"`
+ To []string `json:"to" required:"true"`
+ Subject string `json:"subject"`
+ Text string `json:"text"`
+ HTML string `json:"html"`
+ Headers map[string]string `json:"headers"`
+ MessageID string `json:"message_id"`
+ SpamScore *float64 `json:"spam_score,omitempty"`
+ Attachments []InboundWebhookAttachment `json:"attachments"`
+ Raw string `json:"raw" doc:"Optional base64-encoded raw RFC 5322 message"`
+ } `json:"body"`
+}
+
+type InboundWebhookResponse struct {
+ Accepted bool `json:"accepted"`
+ InboundID string `json:"inbound_id,omitempty"`
+ Status string `json:"status"`
+}
+
+// Receive accepts a normalized inbound email from an external MX provider.
+// Auth is a shared secret provided via X-Posta-Inbound-Secret header.
+func (h *InboundHandler) Receive(c *okapi.Context, req *InboundWebhookRequest) error {
+ if h.secret == "" {
+ return c.AbortForbidden("inbound webhook is not configured")
+ }
+ if !constantTimeSecretEqual(req.PostaInboundSecret, h.secret) {
+ return c.AbortUnauthorized("invalid inbound secret")
+ }
+
+ parsed := &inbound.ParsedEmail{
+ MessageID: strings.Trim(req.Body.MessageID, "<>"),
+ From: req.Body.From,
+ To: req.Body.To,
+ Subject: req.Body.Subject,
+ TextBody: req.Body.Text,
+ HTMLBody: req.Body.HTML,
+ Headers: req.Body.Headers,
+ Date: time.Now().UTC(),
+ }
+ if req.Body.Raw != "" {
+ if raw, err := base64.StdEncoding.DecodeString(req.Body.Raw); err == nil {
+ parsed.Raw = raw
+ }
+ }
+ for _, a := range req.Body.Attachments {
+ decoded, err := base64.StdEncoding.DecodeString(a.Content)
+ if err != nil {
+ return c.AbortBadRequest("invalid base64 in attachment " + a.Filename)
+ }
+ parsed.Attachments = append(parsed.Attachments, inbound.ParsedAttachment{
+ Filename: a.Filename,
+ ContentType: a.ContentType,
+ Content: decoded,
+ Size: int64(len(decoded)),
+ })
+ }
+
+ ctx, cancel := context.WithTimeout(c.Request().Context(), 30*time.Second)
+ defer cancel()
+
+ rec, err := h.svc.Ingest(ctx, parsed, models.InboundSourceWebhook)
+ switch {
+ case err == nil:
+ return c.JSON(http.StatusAccepted, InboundWebhookResponse{Accepted: true, InboundID: rec.UUID, Status: "received"})
+ case errors.Is(err, inbound.ErrDuplicate):
+ return c.JSON(http.StatusOK, InboundWebhookResponse{Accepted: true, InboundID: rec.UUID, Status: "duplicate"})
+ case errors.Is(err, inbound.ErrUnverifiedDomain):
+ return c.AbortForbidden("recipient domain is not verified")
+ case errors.Is(err, inbound.ErrSizeExceeded), errors.Is(err, inbound.ErrAttachmentTooLarge):
+ return c.JSON(http.StatusRequestEntityTooLarge, InboundWebhookResponse{Accepted: false, Status: "too_large"})
+ case errors.Is(err, inbound.ErrSenderSuppressed):
+ uuid := ""
+ if rec != nil {
+ uuid = rec.UUID
+ }
+ return c.JSON(http.StatusAccepted, InboundWebhookResponse{Accepted: true, InboundID: uuid, Status: "suppressed"})
+ default:
+ return c.AbortInternalServerError("failed to ingest inbound email", err)
+ }
+}
+
+// InboundListRequest extends ListRequest with filter query params.
+type InboundListRequest struct {
+ Page int `query:"page" default:"0"`
+ Size int `query:"size" default:"20"`
+ Status string `query:"status" doc:"Filter by status: received|forwarded|failed|rejected"`
+ Source string `query:"source" doc:"Filter by source: smtp|webhook"`
+ Sender string `query:"sender" doc:"Filter by sender address (substring, case-insensitive)"`
+ Q string `query:"q" doc:"Full-text search on subject"`
+}
+
+// List returns inbound emails for the current scope, with optional filters.
+func (h *InboundHandler) List(c *okapi.Context, req *InboundListRequest) error {
+ page, size, offset := normalizePageParams(req.Page, req.Size)
+
+ items, total, err := h.repo.FindByScopeFiltered(getScope(c), repositories.InboundFilter{
+ Status: req.Status,
+ Source: req.Source,
+ Sender: req.Sender,
+ Query: req.Q,
+ }, size, offset)
+ if err != nil {
+ return c.AbortInternalServerError("failed to list inbound emails", err)
+ }
+ return paginated(c, items, total, page, size)
+}
+
+// Delete removes an inbound email by UUID (scope-checked) and cleans up blob-stored content.
+func (h *InboundHandler) Delete(c *okapi.Context, req *GetEmailRequest) error {
+ rec, err := h.repo.FindByUUID(req.ID)
+ if err != nil {
+ return c.AbortNotFound("inbound email not found")
+ }
+ if !ownsResource(c, rec.UserID, rec.WorkspaceID) {
+ return c.AbortNotFound("inbound email not found")
+ }
+ // Best-effort blob cleanup.
+ if h.blobStore != nil {
+ if rec.AttachmentsJSON != "" {
+ var atts []models.InboundAttachmentMeta
+ if err := json.Unmarshal([]byte(rec.AttachmentsJSON), &atts); err == nil {
+ for _, a := range atts {
+ if a.StorageKey != "" {
+ _ = h.blobStore.Delete(c.Request().Context(), a.StorageKey)
+ }
+ }
+ }
+ }
+ if rec.RawStorageKey != "" {
+ _ = h.blobStore.Delete(c.Request().Context(), rec.RawStorageKey)
+ }
+ }
+ if err := h.repo.Delete(rec.ID); err != nil {
+ return c.AbortInternalServerError("failed to delete inbound email", err)
+ }
+ return noContent(c)
+}
+
+// Retry re-enqueues a failed inbound email for another webhook-dispatch attempt.
+func (h *InboundHandler) Retry(c *okapi.Context, req *GetEmailRequest) error {
+ if h.producer == nil {
+ return c.AbortForbidden("inbound retry requires an async worker")
+ }
+ rec, err := h.repo.FindByUUID(req.ID)
+ if err != nil {
+ return c.AbortNotFound("inbound email not found")
+ }
+ if !ownsResource(c, rec.UserID, rec.WorkspaceID) {
+ return c.AbortNotFound("inbound email not found")
+ }
+ if rec.Status != models.InboundStatusFailed && rec.Status != models.InboundStatusReceived {
+ return c.AbortBadRequest("only failed or stuck received messages can be retried")
+ }
+ rec.Status = models.InboundStatusReceived
+ rec.ErrorMessage = ""
+ if err := h.repo.Update(rec); err != nil {
+ return c.AbortInternalServerError("failed to update inbound email", err)
+ }
+ if err := h.producer.EnqueueInboundProcess(rec.ID); err != nil {
+ return c.AbortInternalServerError("failed to enqueue inbound task", err)
+ }
+ return ok(c, map[string]string{"id": rec.UUID, "status": string(rec.Status)})
+}
+
+// DownloadAttachmentAuthed streams an inbound attachment to an authenticated user
+// who owns the record — no signed token required.
+func (h *InboundHandler) DownloadAttachmentAuthed(c *okapi.Context, req *InboundAttachmentOwnedRequest) error {
+ rec, err := h.repo.FindByUUID(req.UUID)
+ if err != nil {
+ return c.AbortNotFound("inbound email not found")
+ }
+ if !ownsResource(c, rec.UserID, rec.WorkspaceID) {
+ return c.AbortNotFound("inbound email not found")
+ }
+ return h.streamAttachment(c, rec, req.Index)
+}
+
+// InboundAttachmentOwnedRequest is the path-params-only variant used by authed users.
+type InboundAttachmentOwnedRequest struct {
+ UUID string `param:"uuid"`
+ Index int `param:"idx"`
+}
+
+// GetRaw streams the raw RFC 5322 message bytes (if stored).
+func (h *InboundHandler) GetRaw(c *okapi.Context, req *GetEmailRequest) error {
+ rec, err := h.repo.FindByUUID(req.ID)
+ if err != nil {
+ return c.AbortNotFound("inbound email not found")
+ }
+ if !ownsResource(c, rec.UserID, rec.WorkspaceID) {
+ return c.AbortNotFound("inbound email not found")
+ }
+ if rec.RawStorageKey == "" || h.blobStore == nil {
+ return c.AbortNotFound("raw message not available")
+ }
+ rc, err := h.blobStore.Get(c.Request().Context(), rec.RawStorageKey)
+ if err != nil {
+ return c.AbortInternalServerError("failed to fetch raw message", err)
+ }
+ defer func() { _ = rc.Close() }()
+ c.ResponseWriter().Header().Set("Content-Type", "message/rfc822")
+ c.ResponseWriter().Header().Set("Content-Disposition", contentDisposition(rec.UUID+".eml"))
+ c.ResponseWriter().WriteHeader(http.StatusOK)
+ if _, err := io.Copy(c.ResponseWriter(), rc); err != nil {
+ logger.Warn("inbound raw stream failed", "uuid", rec.UUID, "error", err)
+ }
+ return nil
+}
+
+// streamAttachment is the shared body for both signed and authed attachment endpoints.
+func (h *InboundHandler) streamAttachment(c *okapi.Context, rec *models.InboundEmail, idx int) error {
+ var atts []models.InboundAttachmentMeta
+ if rec.AttachmentsJSON != "" {
+ if err := json.Unmarshal([]byte(rec.AttachmentsJSON), &atts); err != nil {
+ return c.AbortInternalServerError("failed to decode attachment metadata", err)
+ }
+ }
+ if idx < 0 || idx >= len(atts) {
+ return c.AbortNotFound("attachment not found")
+ }
+ meta := atts[idx]
+ c.ResponseWriter().Header().Set("Content-Type", meta.ContentType)
+ if meta.Filename != "" {
+ c.ResponseWriter().Header().Set("Content-Disposition", contentDisposition(meta.Filename))
+ }
+ if meta.StorageKey != "" && h.blobStore != nil {
+ rc, err := h.blobStore.Get(c.Request().Context(), meta.StorageKey)
+ if err != nil {
+ return c.AbortInternalServerError("failed to fetch attachment", err)
+ }
+ defer func() { _ = rc.Close() }()
+ c.ResponseWriter().WriteHeader(http.StatusOK)
+ if _, err := io.Copy(c.ResponseWriter(), rc); err != nil {
+ // Response already committed — log and return nil since headers are flushed.
+ logger.Warn("inbound attachment stream failed", "uuid", rec.UUID, "error", err)
+ }
+ return nil
+ }
+ if meta.Content != "" {
+ raw, err := base64.StdEncoding.DecodeString(meta.Content)
+ if err != nil {
+ return c.AbortInternalServerError("failed to decode inline attachment", err)
+ }
+ c.ResponseWriter().WriteHeader(http.StatusOK)
+ _, _ = c.ResponseWriter().Write(raw)
+ return nil
+ }
+ return c.AbortNotFound("attachment content unavailable")
+}
+
+// Get returns a single inbound email by UUID (scope-checked).
+func (h *InboundHandler) Get(c *okapi.Context, req *GetEmailRequest) error {
+ rec, err := h.repo.FindByUUID(req.ID)
+ if err != nil {
+ return c.AbortNotFound("inbound email not found")
+ }
+ if !ownsResource(c, rec.UserID, rec.WorkspaceID) {
+ return c.AbortNotFound("inbound email not found")
+ }
+ return ok(c, rec)
+}
+
+// InboundAttachmentRequest identifies a specific attachment on an inbound email.
+type InboundAttachmentRequest struct {
+ UUID string `param:"uuid"`
+ Index int `param:"idx"`
+ Token string `query:"t"`
+}
+
+// ServeAttachment streams an inbound attachment from blob storage after validating
+// the HMAC-signed token. Used by webhook consumers to fetch bytes asynchronously.
+func (h *InboundHandler) ServeAttachment(c *okapi.Context, req *InboundAttachmentRequest) error {
+ if req.Token == "" || !worker.VerifyInboundAttachmentToken(h.hmacKey, req.UUID, req.Index, req.Token) {
+ return c.AbortUnauthorized("invalid or missing token")
+ }
+ rec, err := h.repo.FindByUUID(req.UUID)
+ if err != nil {
+ return c.AbortNotFound("inbound email not found")
+ }
+ var atts []models.InboundAttachmentMeta
+ if rec.AttachmentsJSON != "" {
+ if err := json.Unmarshal([]byte(rec.AttachmentsJSON), &atts); err != nil {
+ return c.AbortInternalServerError("failed to decode attachment metadata", err)
+ }
+ }
+ if req.Index < 0 || req.Index >= len(atts) {
+ return c.AbortNotFound("attachment not found")
+ }
+ meta := atts[req.Index]
+ c.ResponseWriter().Header().Set("Content-Type", meta.ContentType)
+ if meta.Filename != "" {
+ c.ResponseWriter().Header().Set("Content-Disposition", contentDisposition(meta.Filename))
+ }
+
+ if meta.StorageKey != "" && h.blobStore != nil {
+ rc, err := h.blobStore.Get(c.Request().Context(), meta.StorageKey)
+ if err != nil {
+ return c.AbortInternalServerError("failed to fetch attachment", err)
+ }
+ defer func() { _ = rc.Close() }()
+ c.ResponseWriter().WriteHeader(http.StatusOK)
+ if _, err := io.Copy(c.ResponseWriter(), rc); err != nil {
+ logger.Warn("inbound attachment stream failed", "uuid", req.UUID, "error", err)
+ }
+ return nil
+ }
+ if meta.Content != "" {
+ raw, err := base64.StdEncoding.DecodeString(meta.Content)
+ if err != nil {
+ return c.AbortInternalServerError("failed to decode inline attachment", err)
+ }
+ c.ResponseWriter().WriteHeader(http.StatusOK)
+ _, _ = c.ResponseWriter().Write(raw)
+ return nil
+ }
+ return c.AbortNotFound("attachment content unavailable")
+}
diff --git a/internal/handlers/oauth_admin_handler.go b/internal/handlers/oauth_admin_handler.go
index ca69410..410fd4d 100644
--- a/internal/handlers/oauth_admin_handler.go
+++ b/internal/handlers/oauth_admin_handler.go
@@ -31,6 +31,7 @@ type CreateOAuthProviderRequest struct {
UserInfoURL string `json:"userinfo_url"`
Scopes string `json:"scopes"`
AutoRegister *bool `json:"auto_register"`
+ Hidden *bool `json:"hidden"`
AllowedDomains string `json:"allowed_domains"`
} `json:"body"`
}
@@ -47,6 +48,7 @@ type UpdateOAuthProviderRequest struct {
UserInfoURL string `json:"userinfo_url"`
Scopes string `json:"scopes"`
Enabled *bool `json:"enabled"`
+ Hidden *bool `json:"hidden"`
AutoRegister *bool `json:"auto_register"`
AllowedDomains string `json:"allowed_domains"`
} `json:"body"`
@@ -64,6 +66,7 @@ type OAuthProviderResponse struct {
Issuer string `json:"issuer"`
Scopes string `json:"scopes"`
Enabled bool `json:"enabled"`
+ Hidden bool `json:"hidden"`
AutoRegister bool `json:"auto_register"`
AllowedDomains string `json:"allowed_domains"`
CreatedAt string `json:"created_at"`
@@ -111,6 +114,9 @@ func (h *OAuthAdminHandler) CreateProvider(c *okapi.Context, req *CreateOAuthPro
if req.Body.AutoRegister != nil {
provider.AutoRegister = *req.Body.AutoRegister
}
+ if req.Body.Hidden != nil {
+ provider.Hidden = *req.Body.Hidden
+ }
if provider.Scopes == "" {
provider.Scopes = "openid email profile"
}
@@ -171,6 +177,9 @@ func (h *OAuthAdminHandler) UpdateProvider(c *okapi.Context, req *UpdateOAuthPro
if req.Body.Enabled != nil {
provider.Enabled = *req.Body.Enabled
}
+ if req.Body.Hidden != nil {
+ provider.Hidden = *req.Body.Hidden
+ }
if req.Body.AutoRegister != nil {
provider.AutoRegister = *req.Body.AutoRegister
}
@@ -253,6 +262,7 @@ func toProviderResponse(p *models.OAuthProvider) OAuthProviderResponse {
Issuer: p.Issuer,
Scopes: p.Scopes,
Enabled: p.Enabled,
+ Hidden: p.Hidden,
AutoRegister: p.AutoRegister,
AllowedDomains: p.AllowedDomains,
CreatedAt: p.CreatedAt.Format(time.RFC3339),
diff --git a/internal/handlers/oauth_handler.go b/internal/handlers/oauth_handler.go
index 5085c07..dcda48d 100644
--- a/internal/handlers/oauth_handler.go
+++ b/internal/handlers/oauth_handler.go
@@ -6,6 +6,7 @@ import (
"encoding/json"
"fmt"
"net/http"
+ "strings"
"time"
"github.com/google/uuid"
@@ -81,11 +82,23 @@ type UnlinkOAuthRequest struct {
ProviderID int `param:"provider_id"`
}
-// ListProviders returns enabled OAuth providers for the login page (public).
+type DiscoverSSORequest struct {
+ Body struct {
+ Email string `json:"email" required:"true"`
+ } `json:"body"`
+}
+
+type DiscoverSSOResponse struct {
+ Slug string `json:"slug"`
+ Name string `json:"name"`
+ Type string `json:"type"`
+}
+
+// ListProviders returns enabled OAuth providers for the login page
func (h *OAuthHandler) ListProviders(c *okapi.Context) error {
providers, err := h.providerRepo.FindEnabled()
if err != nil {
- return ok(c, okapi.M{"providers": []OAuthProviderInfo{}})
+ return ok(c, okapi.M{"providers": []OAuthProviderInfo{}, "sso_available": false})
}
var result []OAuthProviderInfo
@@ -98,7 +111,31 @@ func (h *OAuthHandler) ListProviders(c *okapi.Context) error {
})
}
- return ok(c, okapi.M{"providers": result})
+ ssoAvailable, _ := h.providerRepo.HasEnabledHidden()
+
+ return ok(c, okapi.M{"providers": result, "sso_available": ssoAvailable})
+}
+
+// DiscoverSSO looks up an enabled OAuth provider whose AllowedDomains matches the
+// email's domain.
+func (h *OAuthHandler) DiscoverSSO(c *okapi.Context, req *DiscoverSSORequest) error {
+ email := strings.TrimSpace(req.Body.Email)
+ at := strings.LastIndex(email, "@")
+ if at < 0 || at == len(email)-1 {
+ return c.AbortBadRequest("invalid email")
+ }
+ domain := email[at+1:]
+
+ provider, err := h.providerRepo.FindEnabledByDomain(domain)
+ if err != nil {
+ return c.AbortNotFound("no SSO provider for this email")
+ }
+
+ return ok(c, DiscoverSSOResponse{
+ Slug: provider.Slug,
+ Name: provider.Name,
+ Type: string(provider.Type),
+ })
}
// Authorize redirects the user to the OAuth provider's authorization page.
diff --git a/internal/handlers/subscriber_list_handler.go b/internal/handlers/subscriber_list_handler.go
index 11bc073..26de875 100644
--- a/internal/handlers/subscriber_list_handler.go
+++ b/internal/handlers/subscriber_list_handler.go
@@ -18,11 +18,14 @@
package handlers
import (
+ "errors"
+ "strings"
"time"
"github.com/goposta/posta/internal/models"
"github.com/goposta/posta/internal/storage/repositories"
"github.com/jkaninda/okapi"
+ "gorm.io/gorm"
)
type SubscriberListHandler struct {
@@ -86,6 +89,47 @@ type PreviewSegmentRequest struct {
} `json:"body"`
}
+// ListUnsubscribeByEmailRequest is the API-key-accessible unsubscribe that
+// takes an email address (the caller usually doesn't know the subscriber ID).
+type ListUnsubscribeByEmailRequest struct {
+ ID int `param:"id"`
+ Body struct {
+ Email string `json:"email" required:"true" format:"email"`
+ Reason string `json:"reason"`
+ } `json:"body"`
+}
+
+// ListResubscribeByEmailRequest is the inverse of ListUnsubscribeByEmailRequest.
+type ListResubscribeByEmailRequest struct {
+ ID int `param:"id"`
+ Body struct {
+ Email string `json:"email" required:"true" format:"email"`
+ } `json:"body"`
+}
+
+// ListSubscribeRequest is the API-key-accessible "subscribe this person to
+// this list" endpoint. The list is identified by name (not id) and created on
+// first use, so external platforms (n8n, forms) don't need a prior list-id
+// lookup. Any prior per-list opt-out for the same (list, email) is cleared —
+// this is the explicit inverse of /unsubscribe.
+type ListSubscribeRequest struct {
+ Body struct {
+ Email string `json:"email" required:"true" format:"email"`
+ Name string `json:"name"`
+ List string `json:"list" required:"true"`
+ } `json:"body"`
+}
+
+type ListSubscribeResponse struct {
+ ListID uint `json:"list_id"`
+ SubscriberID uint `json:"subscriber_id"`
+ Email string `json:"email"`
+ Action string `json:"action"` // "subscribed" | "unsubscribed" | "resubscribed" | "noop"
+ ListCreated bool `json:"list_created,omitempty"`
+ SubscriberCreated bool `json:"subscriber_created,omitempty"`
+ MemberAdded bool `json:"member_added,omitempty"`
+}
+
type SubscriberListWithCount struct {
ID uint `json:"id"`
Name string `json:"name"`
@@ -290,3 +334,147 @@ func (h *SubscriberListHandler) PreviewSegment(c *okapi.Context, req *PreviewSeg
}
return ok(c, okapi.M{"count": count})
}
+
+// Subscribe adds an email to a named list via API key.
+func (h *SubscriberListHandler) Subscribe(c *okapi.Context, req *ListSubscribeRequest) error {
+ if err := requireEdit(c); err != nil {
+ return c.AbortForbidden("insufficient workspace permissions", err)
+ }
+ scope := getScope(c)
+
+ listName := strings.TrimSpace(req.Body.List)
+ if listName == "" {
+ return c.AbortBadRequest("list is required")
+ }
+ email := strings.ToLower(strings.TrimSpace(req.Body.Email))
+ if email == "" {
+ return c.AbortBadRequest("email is required")
+ }
+
+ // Find-or-create list in scope.
+ listCreated := false
+ list, err := h.repo.FindByNameForScope(scope, listName)
+ if err != nil {
+ if !errors.Is(err, gorm.ErrRecordNotFound) {
+ return c.AbortInternalServerError("list lookup failed")
+ }
+ list = &models.SubscriberList{
+ UserID: scope.UserID,
+ WorkspaceID: scope.WorkspaceID,
+ Name: listName,
+ Type: models.SubscriberListTypeStatic,
+ }
+ if err := h.repo.Create(list); err != nil {
+ return c.AbortInternalServerError("failed to create list")
+ }
+ listCreated = true
+ }
+ if list.Type == models.SubscriberListTypeDynamic {
+ return c.AbortBadRequest("cannot subscribe to a dynamic list; adjust filter rules instead")
+ }
+
+ // Find-or-create subscriber.
+ subscriberCreated := false
+ sub, err := h.subscriberRepo.FindByEmail(scope, email)
+ if err != nil {
+ if !errors.Is(err, gorm.ErrRecordNotFound) {
+ return c.AbortInternalServerError("subscriber lookup failed")
+ }
+ now := time.Now()
+ sub = &models.Subscriber{
+ UserID: scope.UserID,
+ WorkspaceID: scope.WorkspaceID,
+ Email: email,
+ Name: strings.TrimSpace(req.Body.Name),
+ Status: models.SubscriberStatusSubscribed,
+ SubscribedAt: &now,
+ }
+ if err := h.subscriberRepo.Create(sub); err != nil {
+ return c.AbortInternalServerError("failed to create subscriber")
+ }
+ subscriberCreated = true
+ } else if req.Body.Name != "" && sub.Name == "" {
+ // Fill in a name we didn't have before; don't overwrite a set one.
+ sub.Name = strings.TrimSpace(req.Body.Name)
+ _ = h.subscriberRepo.Update(sub)
+ }
+
+ _ = h.repo.UnsuppressMember(list.ID, sub.ID)
+
+ memberAdded := !h.repo.IsMember(list.ID, sub.ID)
+ if err := h.repo.AddMember(&models.SubscriberListMember{
+ ListID: list.ID,
+ SubscriberID: sub.ID,
+ }); err != nil {
+ return c.AbortInternalServerError("failed to add to list")
+ }
+
+ return ok(c, ListSubscribeResponse{
+ ListID: list.ID,
+ SubscriberID: sub.ID,
+ Email: sub.Email,
+ Action: "subscribed",
+ ListCreated: listCreated,
+ SubscriberCreated: subscriberCreated,
+ MemberAdded: memberAdded,
+ })
+}
+
+// UnsubscribeByEmail opts an email out of a specific list.
+func (h *SubscriberListHandler) UnsubscribeByEmail(c *okapi.Context, req *ListUnsubscribeByEmailRequest) error {
+ if err := requireEdit(c); err != nil {
+ return c.AbortForbidden("insufficient workspace permissions", err)
+ }
+ list, err := h.repo.FindByID(uint(req.ID))
+ if err != nil || !ownsResource(c, list.UserID, list.WorkspaceID) {
+ return c.AbortNotFound("list not found")
+ }
+ sub, err := h.subscriberRepo.FindByEmail(getScope(c), req.Body.Email)
+ if err != nil || sub == nil {
+ return c.AbortNotFound("subscriber not found for this email")
+ }
+ reason := req.Body.Reason
+ if reason == "" {
+ reason = "api"
+ }
+ if err := h.repo.SuppressMember(list.ID, sub.ID, reason); err != nil {
+ return c.AbortInternalServerError("failed to unsubscribe")
+ }
+ return ok(c, ListSubscribeResponse{
+ ListID: list.ID,
+ SubscriberID: sub.ID,
+ Email: sub.Email,
+ Action: "unsubscribed",
+ })
+}
+
+// ResubscribeByEmail removes the list-scoped opt-out AND re-adds the
+// subscriber to the list (static lists only).
+func (h *SubscriberListHandler) ResubscribeByEmail(c *okapi.Context, req *ListResubscribeByEmailRequest) error {
+ if err := requireEdit(c); err != nil {
+ return c.AbortForbidden("insufficient workspace permissions", err)
+ }
+ list, err := h.repo.FindByID(uint(req.ID))
+ if err != nil || !ownsResource(c, list.UserID, list.WorkspaceID) {
+ return c.AbortNotFound("list not found")
+ }
+ sub, err := h.subscriberRepo.FindByEmail(getScope(c), req.Body.Email)
+ if err != nil || sub == nil {
+ return c.AbortNotFound("subscriber not found for this email")
+ }
+ if err := h.repo.UnsuppressMember(list.ID, sub.ID); err != nil {
+ return c.AbortInternalServerError("failed to resubscribe")
+ }
+ if list.Type == models.SubscriberListTypeStatic {
+ _ = h.repo.AddMember(&models.SubscriberListMember{
+ ListID: list.ID,
+ SubscriberID: sub.ID,
+ })
+ }
+ return ok(c, ListSubscribeResponse{
+ ListID: list.ID,
+ SubscriberID: sub.ID,
+ Email: sub.Email,
+ Action: "resubscribed",
+ })
+}
diff --git a/internal/handlers/tracking_handler.go b/internal/handlers/tracking_handler.go
index 72b3444..78e39b6 100644
--- a/internal/handlers/tracking_handler.go
+++ b/internal/handlers/tracking_handler.go
@@ -18,7 +18,6 @@
package handlers
import (
- "encoding/base64"
"fmt"
"html"
"net/http"
@@ -31,14 +30,14 @@ import (
"github.com/jkaninda/okapi"
)
-// 1x1 transparent GIF
-var transparentPixel, _ = base64.StdEncoding.DecodeString("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")
-
type TrackingHandler struct {
trackingRepo *repositories.TrackingRepository
messageRepo *repositories.CampaignMessageRepository
campaignRepo *repositories.CampaignRepository
subRepo *repositories.SubscriberRepository
+ listRepo *repositories.SubscriberListRepository
+ emailRepo *repositories.EmailRepository
+ suppressionRepo *repositories.SuppressionRepository
trackingService *tracking.Service
}
@@ -47,6 +46,9 @@ func NewTrackingHandler(
messageRepo *repositories.CampaignMessageRepository,
campaignRepo *repositories.CampaignRepository,
subRepo *repositories.SubscriberRepository,
+ listRepo *repositories.SubscriberListRepository,
+ emailRepo *repositories.EmailRepository,
+ suppressionRepo *repositories.SuppressionRepository,
trackingService *tracking.Service,
) *TrackingHandler {
return &TrackingHandler{
@@ -54,17 +56,22 @@ func NewTrackingHandler(
messageRepo: messageRepo,
campaignRepo: campaignRepo,
subRepo: subRepo,
+ listRepo: listRepo,
+ emailRepo: emailRepo,
+ suppressionRepo: suppressionRepo,
trackingService: trackingService,
}
}
type TrackingOpenRequest struct {
- MessageID int `param:"message_id"`
+ MessageID int `param:"message_id"`
+ Sig string `query:"sig"`
}
type TrackingClickRequest struct {
MessageID int `param:"message_id"`
Hash string `param:"hash"`
+ Sig string `query:"sig"`
}
type TrackingUnsubscribeRequest struct {
@@ -72,9 +79,16 @@ type TrackingUnsubscribeRequest struct {
}
// OpenPixel serves a 1x1 transparent GIF and records the open event.
+// Signature is mandatory; unsigned or bad-sig requests get 404.
func (h *TrackingHandler) OpenPixel(c *okapi.Context, req *TrackingOpenRequest) error {
- // Record open asynchronously
- go h.recordOpen(uint(req.MessageID), c.RealIP(), c.Request().UserAgent())
+ if req.Sig == "" || !h.trackingService.VerifyOpenSig(uint(req.MessageID), req.Sig) {
+ return c.AbortNotFound("not found")
+ }
+
+ ua := c.Request().UserAgent()
+ if !isBotUA(ua) {
+ go h.recordOpen(uint(req.MessageID), c.RealIP(), ua)
+ }
c.ResponseWriter().Header().Set("Content-Type", "image/gif")
c.ResponseWriter().Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
@@ -85,6 +99,10 @@ func (h *TrackingHandler) OpenPixel(c *okapi.Context, req *TrackingOpenRequest)
// ClickRedirect records the click and redirects to the original URL.
func (h *TrackingHandler) ClickRedirect(c *okapi.Context, req *TrackingClickRequest) error {
+ if req.Sig == "" || !h.trackingService.VerifyClickSig(uint(req.MessageID), req.Hash, req.Sig) {
+ return c.AbortNotFound("not found")
+ }
+
link, err := h.trackingRepo.FindLinkByHash(req.Hash)
if err != nil {
return c.AbortNotFound("link not found")
@@ -95,8 +113,10 @@ func (h *TrackingHandler) ClickRedirect(c *okapi.Context, req *TrackingClickRequ
return c.AbortBadRequest("invalid redirect URL")
}
- // Record click asynchronously
- go h.recordClick(uint(req.MessageID), link.ID, c.RealIP(), c.Request().UserAgent())
+ ua := c.Request().UserAgent()
+ if !isBotUA(ua) {
+ go h.recordClick(uint(req.MessageID), link.ID, c.RealIP(), ua)
+ }
c.Redirect(http.StatusFound, link.OriginalURL)
return nil
@@ -132,6 +152,70 @@ button:hover{background:#7e22ce}.done{color:#16a34a;font-weight:600}</style></he
return c.HTMLView(http.StatusOK, html, okapi.M{})
}
+// TxUnsubscribePage renders a confirmation page for a transactional one-click
+// unsubscribe link. The link is RFC 8058 compliant: the POST variant will
+// opt the recipient out without any further interaction.
+func (h *TrackingHandler) TxUnsubscribePage(c *okapi.Context, req *TrackingUnsubscribeRequest) error {
+ emailID, err := h.trackingService.VerifyTxUnsubscribeToken(req.Token)
+ if err != nil {
+ return c.HTMLView(http.StatusNotFound, "Invalid or expired unsubscribe link", okapi.M{})
+ }
+ em, err := h.emailRepo.FindByID(emailID)
+ if err != nil || em == nil {
+ return c.HTMLView(http.StatusNotFound, "Message not found", okapi.M{})
+ }
+ shown := ""
+ if len(em.Recipients) > 0 {
+ shown = em.Recipients[0]
+ }
+ page := fmt.Sprintf(`<!DOCTYPE html><html><head><meta charset="utf-8"><title>Unsubscribe</title>
+<style>body{font-family:sans-serif;display:flex;align-items:center;justify-content:center;min-height:100vh;margin:0;background:#f9fafb}
+.card{background:#fff;border-radius:12px;padding:40px;max-width:420px;text-align:center;box-shadow:0 2px 8px rgba(0,0,0,0.08)}
+h1{font-size:20px;margin-bottom:8px}p{color:#6b7280;font-size:14px;margin-bottom:20px}
+button{background:#9333ea;color:#fff;border:none;padding:12px 32px;border-radius:8px;font-size:15px;cursor:pointer}
+button:hover{background:#7e22ce}</style></head><body>
+<div class="card"><h1>Unsubscribe</h1><p>%s</p>
+<form method="POST"><button type="submit">Confirm Unsubscribe</button></form></div></body></html>`, html.EscapeString(shown))
+
+ return c.HTMLView(http.StatusOK, page, okapi.M{})
+}
+
+// TxUnsubscribeConfirm processes a POST to the transactional unsubscribe link.
+// It is the RFC 8058 one-click endpoint — idempotent and requires no session.
+// All recipients on the email are added to the scoped suppression list.
+func (h *TrackingHandler) TxUnsubscribeConfirm(c *okapi.Context, req *TrackingUnsubscribeRequest) error {
+ emailID, err := h.trackingService.VerifyTxUnsubscribeToken(req.Token)
+ if err != nil {
+ return c.HTMLView(http.StatusNotFound, "Invalid or expired unsubscribe link", okapi.M{})
+ }
+ em, err := h.emailRepo.FindByID(emailID)
+ if err != nil || em == nil {
+ return c.HTMLView(http.StatusNotFound, "Message not found", okapi.M{})
+ }
+
+ if h.suppressionRepo != nil {
+ for _, addr := range em.Recipients {
+ if addr == "" {
+ continue
+ }
+ _ = h.suppressionRepo.Upsert(&models.Suppression{
+ UserID: em.UserID,
+ WorkspaceID: em.WorkspaceID,
+ Email: addr,
+ Reason: "one_click_unsubscribe",
+ })
+ }
+ }
+
+ confirmHTML := `<!DOCTYPE html><html><head><meta charset="utf-8"><title>Unsubscribed</title>
+<style>body{font-family:sans-serif;display:flex;align-items:center;justify-content:center;min-height:100vh;margin:0;background:#f9fafb}
+.card{background:#fff;border-radius:12px;padding:40px;max-width:420px;text-align:center;box-shadow:0 2px 8px rgba(0,0,0,0.08)}
+h1{font-size:20px;color:#16a34a}p{color:#6b7280;font-size:14px}</style></head><body>
+<div class="card"><h1>Unsubscribed</h1><p>You will no longer receive emails of this type from the sender.</p></div></body></html>`
+
+ return c.HTMLView(http.StatusOK, confirmHTML, okapi.M{})
+}
+
// UnsubscribeConfirm processes the unsubscribe action.
func (h *TrackingHandler) UnsubscribeConfirm(c *okapi.Context, req *TrackingUnsubscribeRequest) error {
messageID, err := h.trackingService.VerifyUnsubscribeToken(req.Token)
@@ -144,22 +228,20 @@ func (h *TrackingHandler) UnsubscribeConfirm(c *okapi.Context, req *TrackingUnsu
return c.HTMLView(http.StatusNotFound, "Message not found", okapi.M{})
}
- // Update subscriber status
- sub, err := h.subRepo.FindByID(msg.SubscriberID)
+ camp, err := h.campaignRepo.FindByID(msg.CampaignID)
if err != nil {
- return c.HTMLView(http.StatusNotFound, "Subscriber not found", okapi.M{})
+ return c.HTMLView(http.StatusNotFound, "Campaign not found", okapi.M{})
}
- now := time.Now()
- sub.Status = models.SubscriberStatusUnsubscribed
- sub.UnsubscribedAt = &now
- _ = h.subRepo.Update(sub)
+ // Suppress this subscriber on the campaign's list
+ if h.listRepo != nil {
+ _ = h.listRepo.SuppressMember(camp.ListID, msg.SubscriberID, "user_unsubscribed")
+ }
- // Update campaign message
- msg.UnsubscribedAt = &now
+ // Mark the campaign message itself.
_ = h.messageRepo.UpdateUnsubscribedAt(msg.ID)
- // Record event
+ // Record event for analytics.
_ = h.trackingRepo.CreateEvent(&models.TrackingEvent{
CampaignMessageID: msg.ID,
EventType: models.TrackingEventUnsubscribe,
@@ -171,7 +253,7 @@ func (h *TrackingHandler) UnsubscribeConfirm(c *okapi.Context, req *TrackingUnsu
<style>body{font-family:sans-serif;display:flex;align-items:center;justify-content:center;min-height:100vh;margin:0;background:#f9fafb}
.card{background:#fff;border-radius:12px;padding:40px;max-width:420px;text-align:center;box-shadow:0 2px 8px rgba(0,0,0,0.08)}
h1{font-size:20px;color:#16a34a}p{color:#6b7280;font-size:14px}</style></head><body>
-<div class="card"><h1>Unsubscribed</h1><p>You have been successfully unsubscribed.</p></div></body></html>`
+<div class="card"><h1>Unsubscribed</h1><p>You have been removed from this mailing list. Other lists you are subscribed to are unaffected.</p></div></body></html>`
return c.HTMLView(http.StatusOK, confirmHTML, okapi.M{})
}
diff --git a/internal/handlers/user_handler.go b/internal/handlers/user_handler.go
index e862fae..1202d45 100644
--- a/internal/handlers/user_handler.go
+++ b/internal/handlers/user_handler.go
@@ -27,24 +27,27 @@ import (
"github.com/google/uuid"
"github.com/goposta/posta/internal/dto"
"github.com/goposta/posta/internal/models"
+ "github.com/goposta/posta/internal/services/emailverify"
"github.com/goposta/posta/internal/services/eventbus"
"github.com/goposta/posta/internal/services/notification"
"github.com/goposta/posta/internal/services/seeder"
"github.com/goposta/posta/internal/services/settings"
"github.com/goposta/posta/internal/services/twofactor"
"github.com/goposta/posta/internal/storage/repositories"
+ "github.com/jkaninda/logger"
"github.com/jkaninda/okapi"
"golang.org/x/crypto/bcrypt"
)
type UserHandler struct {
- repo *repositories.UserRepository
- sessionRepo *repositories.SessionRepository
- jwtSecret []byte
- seeder *seeder.Seeder
- bus *eventbus.EventBus
- settings *settings.Provider
- notifier *notification.Service
+ repo *repositories.UserRepository
+ sessionRepo *repositories.SessionRepository
+ jwtSecret []byte
+ seeder *seeder.Seeder
+ bus *eventbus.EventBus
+ settings *settings.Provider
+ notifier *notification.Service
+ emailVerifier *emailverify.Service
}
func NewUserHandler(repo *repositories.UserRepository, jwtSecret string, seeder *seeder.Seeder, bus *eventbus.EventBus) *UserHandler {
@@ -71,6 +74,11 @@ func (h *UserHandler) SetNotifier(n *notification.Service) {
h.notifier = n
}
+// SetEmailVerifier wires the email verification service.
+func (h *UserHandler) SetEmailVerifier(s *emailverify.Service) {
+ h.emailVerifier = s
+}
+
type LoginRequest struct {
Body struct {
Email string `json:"email" required:"true" format:"email"`
@@ -90,14 +98,16 @@ type AuthResponse struct {
}
type UserProfile struct {
- ID uint `json:"id"`
- Name string `json:"name"`
- Email string `json:"email"`
- Role models.UserRole `json:"role"`
- TwoFactorEnabled bool `json:"two_factor_enabled"`
- RequireVerifiedDomain bool `json:"require_verified_domain"`
- ScheduledDeletionAt *time.Time `json:"scheduled_deletion_at"`
- CreatedAt time.Time `json:"created_at"`
+ ID uint `json:"id"`
+ Name string `json:"name"`
+ Email string `json:"email"`
+ Role models.UserRole `json:"role"`
+ TwoFactorEnabled bool `json:"two_factor_enabled"`
+ RequireVerifiedDomain bool `json:"require_verified_domain"`
+ ScheduledDeletionAt *time.Time `json:"scheduled_deletion_at"`
+ EmailVerifiedAt *time.Time `json:"email_verified_at"`
+ EmailVerificationRequired bool `json:"email_verification_required"`
+ CreatedAt time.Time `json:"created_at"`
}
type Enable2FAResponse struct {
@@ -196,11 +206,19 @@ func (h *UserHandler) Register(c *okapi.Context, req *RegisterRequest) error {
fmt.Sprintf("User %q registered", user.Email), nil)
}
- // Send welcome email (best-effort)
- if h.notifier != nil {
- go func() {
- _ = h.notifier.SendToUser(user.ID, "Welcome to Posta!", notification.TemplateWelcome, nil)
- }()
+ // Email verification: if the notifier is configured, send a verification email.
+ // Otherwise (self-hosted without SMTP) auto-verify so the account isn't locked out.
+ // The welcome email is deferred until after verification (see VerifyEmail).
+ if h.emailVerifier != nil {
+ if h.emailVerifier.Required() {
+ go func() {
+ if err := h.emailVerifier.IssueAndSend(user); err != nil {
+ logger.Error("failed to send verification email", "user_id", user.ID, "err", err)
+ }
+ }()
+ } else {
+ _ = h.emailVerifier.MarkVerifiedNow(user)
+ }
}
// Auto-login: generate JWT token
@@ -226,6 +244,57 @@ func (h *UserHandler) RegistrationStatus(c *okapi.Context) error {
return ok(c, okapi.M{"registration_enabled": enabled})
}
+type VerifyEmailRequest struct {
+ Token string `query:"token" required:"true"`
+}
+
+// VerifyEmail redeems a verification token and marks the user's email as verified.
+func (h *UserHandler) VerifyEmail(c *okapi.Context, req *VerifyEmailRequest) error {
+ if h.emailVerifier == nil {
+ return c.AbortBadRequest("email verification is not enabled")
+ }
+ user, newlyVerified, err := h.emailVerifier.Redeem(req.Token)
+ if err != nil {
+ return c.AbortBadRequest(err.Error())
+ }
+ if newlyVerified {
+ if h.bus != nil {
+ h.bus.PublishSimple(models.EventCategoryUser, "user.email_verified", &user.ID, user.Email, c.RealIP(),
+ fmt.Sprintf("User %q verified email", user.Email), nil)
+ }
+ // Fire the welcome email now that we know the address works.
+ if h.notifier != nil {
+ go func(uid uint) {
+ _ = h.notifier.SendToUser(uid, "Welcome to Posta!", notification.TemplateWelcome, nil)
+ }(user.ID)
+ }
+ }
+ return ok(c, okapi.M{"message": "email verified"})
+}
+
+// ResendVerificationEmail issues a fresh token for the authenticated user.
+func (h *UserHandler) ResendVerificationEmail(c *okapi.Context) error {
+ if h.emailVerifier == nil || !h.emailVerifier.Required() {
+ return c.AbortBadRequest("email verification is not enabled")
+ }
+ userID := c.GetInt("user_id")
+ user, err := h.repo.FindByID(uint(userID))
+ if err != nil {
+ return c.AbortNotFound("user not found")
+ }
+ if user.EmailVerifiedAt != nil {
+ return ok(c, okapi.M{"message": "email already verified"})
+ }
+ if err := h.emailVerifier.CanResend(user.ID); err != nil {
+ return c.AbortTooManyRequests(err.Error())
+ }
+ if err := h.emailVerifier.IssueAndSend(user); err != nil {
+ logger.Error("failed to resend verification email", "user_id", user.ID, "err", err)
+ return c.AbortInternalServerError("failed to send verification email")
+ }
+ return ok(c, okapi.M{"message": "verification email sent"})
+}
+
// UpdateProfile allows authenticated users to update their profile (name).
func (h *UserHandler) UpdateProfile(c *okapi.Context, req *UpdateProfileRequest) error {
userID := c.GetInt("user_id")
@@ -242,16 +311,7 @@ func (h *UserHandler) UpdateProfile(c *okapi.Context, req *UpdateProfileRequest)
return c.AbortInternalServerError("failed to update profile")
}
- return ok(c, UserProfile{
- ID: user.ID,
- Name: user.Name,
- Email: user.Email,
- Role: user.Role,
- TwoFactorEnabled: user.TwoFactorEnabled,
- RequireVerifiedDomain: user.RequireVerifiedDomain,
- ScheduledDeletionAt: user.ScheduledDeletionAt,
- CreatedAt: user.CreatedAt,
- })
+ return ok(c, h.buildProfile(user))
}
// ChangePassword allows authenticated users to change their own password.
@@ -369,16 +429,23 @@ func (h *UserHandler) Me(c *okapi.Context) error {
return c.AbortNotFound("user not found")
}
- return ok(c, UserProfile{
- ID: user.ID,
- Name: user.Name,
- Email: user.Email,
- Role: user.Role,
- TwoFactorEnabled: user.TwoFactorEnabled,
- RequireVerifiedDomain: user.RequireVerifiedDomain,
- ScheduledDeletionAt: user.ScheduledDeletionAt,
- CreatedAt: user.CreatedAt,
- })
+ return ok(c, h.buildProfile(user))
+}
+
+func (h *UserHandler) buildProfile(user *models.User) UserProfile {
+ required := h.emailVerifier != nil && h.emailVerifier.Required()
+ return UserProfile{
+ ID: user.ID,
+ Name: user.Name,
+ Email: user.Email,
+ Role: user.Role,
+ TwoFactorEnabled: user.TwoFactorEnabled,
+ RequireVerifiedDomain: user.RequireVerifiedDomain,
+ ScheduledDeletionAt: user.ScheduledDeletionAt,
+ EmailVerifiedAt: user.EmailVerifiedAt,
+ EmailVerificationRequired: required,
+ CreatedAt: user.CreatedAt,
+ }
}
// Setup2FA generates a TOTP secret for the user (doesn't enable yet).
diff --git a/internal/handlers/webhook_handler.go b/internal/handlers/webhook_handler.go
index 456cc13..f283c84 100644
--- a/internal/handlers/webhook_handler.go
+++ b/internal/handlers/webhook_handler.go
@@ -53,10 +53,10 @@ func (h *WebhookHandler) Create(c *okapi.Context, req *CreateWebhookRequest) err
scope := getScope(c)
// Validate event names
- validEvents := map[string]bool{"email.sent": true, "email.failed": true}
+ validEvents := map[string]bool{"email.sent": true, "email.failed": true, "email.inbound": true}
for _, event := range req.Body.Events {
if !validEvents[event] {
- return c.AbortBadRequest("invalid event: " + event + ". Valid events: email.sent, email.failed")
+ return c.AbortBadRequest("invalid event: " + event + ". Valid events: email.sent, email.failed, email.inbound")
}
}
diff --git a/internal/metrics/metrics.go b/internal/metrics/metrics.go
index b26b099..e6c703a 100644
--- a/internal/metrics/metrics.go
+++ b/internal/metrics/metrics.go
@@ -59,10 +59,10 @@ var (
},
)
- emailsQueuedTotal = prometheus.NewCounter(
- prometheus.CounterOpts{
- Name: "posta_emails_queued_total",
- Help: "Total number of emails enqueued for delivery",
+ emailsQueueSize = prometheus.NewGauge(
+ prometheus.GaugeOpts{
+ Name: "posta_emails_queue_size",
+ Help: "Number of emails currently enqueued for delivery",
},
)
@@ -103,6 +103,58 @@ var (
Help: "Total number of email suppressions added",
},
)
+
+ inboundReceivedTotal = prometheus.NewCounterVec(
+ prometheus.CounterOpts{
+ Name: "posta_inbound_messages_received_total",
+ Help: "Total number of inbound messages accepted for processing, by source",
+ },
+ []string{"source"},
+ )
+
+ inboundForwardedTotal = prometheus.NewCounter(
+ prometheus.CounterOpts{
+ Name: "posta_inbound_messages_forwarded_total",
+ Help: "Total number of inbound messages successfully dispatched to subscribers",
+ },
+ )
+
+ inboundFailedTotal = prometheus.NewCounter(
+ prometheus.CounterOpts{
+ Name: "posta_inbound_messages_failed_total",
+ Help: "Total number of inbound messages that permanently failed to forward",
+ },
+ )
+
+ inboundRejectedTotal = prometheus.NewCounterVec(
+ prometheus.CounterOpts{
+ Name: "posta_inbound_messages_rejected_total",
+ Help: "Total number of inbound messages rejected at ingestion, by reason",
+ },
+ []string{"reason"},
+ )
+
+ inboundBytesTotal = prometheus.NewCounter(
+ prometheus.CounterOpts{
+ Name: "posta_inbound_bytes_total",
+ Help: "Total bytes of raw inbound messages accepted",
+ },
+ )
+
+ inboundIngestDuration = prometheus.NewHistogram(
+ prometheus.HistogramOpts{
+ Name: "posta_inbound_ingest_duration_seconds",
+ Help: "Time spent ingesting an inbound message (parse + blob upload + DB write)",
+ Buckets: prometheus.DefBuckets,
+ },
+ )
+
+ activeWorkers = prometheus.NewGauge(
+ prometheus.GaugeOpts{
+ Name: "posta_active_workers",
+ Help: "Number of currently-connected Asynq workers (embedded + standalone)",
+ },
+ )
)
func init() {
@@ -110,12 +162,19 @@ func init() {
prometheus.MustRegister(httpRequestDuration)
prometheus.MustRegister(emailsSentTotal)
prometheus.MustRegister(emailsFailedTotal)
- prometheus.MustRegister(emailsQueuedTotal)
+ prometheus.MustRegister(emailsQueueSize)
prometheus.MustRegister(emailRetriesTotal)
prometheus.MustRegister(webhookDeliveriesTotal)
prometheus.MustRegister(webhookDeliveryDuration)
prometheus.MustRegister(bouncesTotal)
prometheus.MustRegister(suppressionsTotal)
+ prometheus.MustRegister(inboundReceivedTotal)
+ prometheus.MustRegister(inboundForwardedTotal)
+ prometheus.MustRegister(inboundFailedTotal)
+ prometheus.MustRegister(inboundRejectedTotal)
+ prometheus.MustRegister(inboundBytesTotal)
+ prometheus.MustRegister(inboundIngestDuration)
+ prometheus.MustRegister(activeWorkers)
}
// IncrementEmailSent increments the emails sent counter.
@@ -128,9 +187,15 @@ func IncrementEmailFailed() {
emailsFailedTotal.Inc()
}
-// IncrementEmailQueued increments the emails queued counter.
+// IncrementEmailQueued increments the in-flight queue-size gauge.
func IncrementEmailQueued() {
- emailsQueuedTotal.Inc()
+ emailsQueueSize.Inc()
+}
+
+// DecrementEmailQueued decrements the in-flight queue-size gauge, called when
+// a queued email finishes delivery (sent or permanently failed).
+func DecrementEmailQueued() {
+ emailsQueueSize.Dec()
}
// IncrementEmailRetry increments the email retries counter.
@@ -158,6 +223,43 @@ func IncrementSuppression() {
suppressionsTotal.Inc()
}
+// IncrementInboundReceived increments the inbound received counter for the given source.
+func IncrementInboundReceived(source string) {
+ inboundReceivedTotal.WithLabelValues(source).Inc()
+}
+
+// IncrementInboundForwarded increments the inbound forwarded counter.
+func IncrementInboundForwarded() {
+ inboundForwardedTotal.Inc()
+}
+
+// IncrementInboundFailed increments the permanently-failed inbound counter.
+func IncrementInboundFailed() {
+ inboundFailedTotal.Inc()
+}
+
+// IncrementInboundRejected increments the rejected inbound counter for the given reason.
+func IncrementInboundRejected(reason string) {
+ inboundRejectedTotal.WithLabelValues(reason).Inc()
+}
+
+// AddInboundBytes adds n bytes to the inbound bytes counter.
+func AddInboundBytes(n int64) {
+ if n > 0 {
+ inboundBytesTotal.Add(float64(n))
+ }
+}
+
+// ObserveInboundIngestDuration records how long a single ingest took, in seconds.
+func ObserveInboundIngestDuration(seconds float64) {
+ inboundIngestDuration.Observe(seconds)
+}
+
+// SetActiveWorkers updates the active worker gauge.
+func SetActiveWorkers(n int) {
+ activeWorkers.Set(float64(n))
+}
+
// PrometheusMiddleware records HTTP request metrics.
func PrometheusMiddleware() okapi.Middleware {
return func(c *okapi.Context) error {
diff --git a/internal/middlewares/middleware.go b/internal/middlewares/middleware.go
index 7156dc1..c105b21 100644
--- a/internal/middlewares/middleware.go
+++ b/internal/middlewares/middleware.go
@@ -25,6 +25,7 @@ import (
"github.com/golang-jwt/jwt/v5"
"github.com/goposta/posta/internal/config"
"github.com/goposta/posta/internal/services/auth"
+ "github.com/goposta/posta/internal/services/emailverify"
"github.com/goposta/posta/internal/services/ratelimit"
sessionpkg "github.com/goposta/posta/internal/services/session"
"github.com/goposta/posta/internal/storage/repositories"
@@ -106,6 +107,38 @@ func JWTAdminQueryAuth(cfg *config.Config, sessionStore ...*sessionpkg.Store) ok
return auth
}
+// JWTQueryAuth creates user JWT auth via query param (for SSE endpoints —
+// browsers cannot attach Authorization headers to EventSource connections).
+func JWTQueryAuth(cfg *config.Config, sessionStore ...*sessionpkg.Store) okapi.JWTAuth {
+ auth := baseJWTAuth(cfg)
+ auth.TokenLookup = "query:token"
+ if len(sessionStore) > 0 && sessionStore[0] != nil {
+ auth.ValidateClaims = sessionValidator(sessionStore[0])
+ }
+ return auth
+}
+
+// RequireVerifiedEmail blocks actions that are risky when the caller's email
+func RequireVerifiedEmail(verifier *emailverify.Service, userRepo *repositories.UserRepository) okapi.Middleware {
+ return func(c *okapi.Context) error {
+ if verifier == nil || !verifier.Required() {
+ return c.Next()
+ }
+ userID := c.GetInt("user_id")
+ if userID == 0 {
+ return c.Next()
+ }
+ user, err := userRepo.FindByID(uint(userID))
+ if err != nil {
+ return c.AbortUnauthorized("user not found")
+ }
+ if user.EmailVerifiedAt == nil {
+ return c.AbortForbidden("email address is not verified")
+ }
+ return c.Next()
+ }
+}
+
// LoginRateLimitMiddleware limits login attempts per IP address using Redis.
func LoginRateLimitMiddleware(limiter *ratelimit.RedisLimiter) okapi.Middleware {
return func(c *okapi.Context) error {
diff --git a/internal/models/campaign.go b/internal/models/campaign.go
index 29daaa7..7fb144d 100644
--- a/internal/models/campaign.go
+++ b/internal/models/campaign.go
@@ -21,6 +21,8 @@ import (
"database/sql/driver"
"encoding/json"
"time"
+
+ "gorm.io/gorm"
)
type CampaignStatus string
@@ -84,5 +86,9 @@ type Campaign struct {
CompletedAt *time.Time `json:"completed_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt *time.Time `json:"updated_at,omitempty"`
- User User `json:"-" gorm:"foreignKey:UserID"`
+ DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
+ // Snapshot captures the aggregated stats at soft-delete time so analytics
+ // for past sends survive after CampaignMessage rows are purged.
+ Snapshot TemplateData `json:"snapshot,omitempty" gorm:"type:text"`
+ User User `json:"-" gorm:"foreignKey:UserID"`
}
diff --git a/internal/models/email.go b/internal/models/email.go
index 9653b87..cbfb743 100644
--- a/internal/models/email.go
+++ b/internal/models/email.go
@@ -44,6 +44,7 @@ type Email struct {
Sender string `json:"sender" gorm:"not null"`
Recipients pq.StringArray `json:"recipients" gorm:"type:text[];not null"`
Subject string `json:"subject" gorm:"not null"`
+ TemplateName string `json:"template_name,omitempty"`
HTMLBody string `json:"html_body"`
TextBody string `json:"text_body"`
AttachmentsJSON string `json:"attachments_json,omitempty" gorm:"type:text"`
@@ -56,6 +57,7 @@ type Email struct {
CreatedAt time.Time `json:"created_at"`
SentAt *time.Time `json:"sent_at"`
ScheduledAt *time.Time `json:"scheduled_at"`
+ Provider string `json:"provider,omitempty" gorm:"index;size:32"`
SMTPHostname string `json:"smtp_hostname,omitempty"`
diff --git a/internal/models/inbound_email.go b/internal/models/inbound_email.go
new file mode 100644
index 0000000..79e050e
--- /dev/null
+++ b/internal/models/inbound_email.go
@@ -0,0 +1,81 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package models
+
+import (
+ "time"
+
+ "github.com/lib/pq"
+)
+
+type InboundEmailStatus string
+
+const (
+ InboundStatusReceived InboundEmailStatus = "received"
+ InboundStatusForwarded InboundEmailStatus = "forwarded"
+ InboundStatusFailed InboundEmailStatus = "failed"
+ InboundStatusRejected InboundEmailStatus = "rejected"
+)
+
+type InboundSource string
+
+const (
+ InboundSourceSMTP InboundSource = "smtp"
+ InboundSourceWebhook InboundSource = "webhook"
+)
+
+type InboundEmail struct {
+ ID uint `json:"id" gorm:"primaryKey"`
+ UUID string `json:"uuid" gorm:"type:uuid;default:gen_random_uuid();uniqueIndex;not null"`
+ UserID uint `json:"user_id" gorm:"index;not null"`
+ WorkspaceID *uint `json:"workspace_id,omitempty" gorm:"index"`
+ DomainID uint `json:"domain_id" gorm:"index;not null"`
+ MessageID string `json:"message_id" gorm:"index"`
+ Sender string `json:"sender" gorm:"not null"`
+ Recipients pq.StringArray `json:"recipients" gorm:"type:text[];not null"`
+ Subject string `json:"subject"`
+ TextBody string `json:"text_body" gorm:"type:text"`
+ HTMLBody string `json:"html_body" gorm:"type:text"`
+ AttachmentsJSON string `json:"attachments_json,omitempty" gorm:"type:text"`
+ HeadersJSON string `json:"headers_json,omitempty" gorm:"type:text"`
+ RawStorageKey string `json:"raw_storage_key,omitempty"`
+ DedupHash string `json:"-" gorm:"index"`
+ Size int64 `json:"size"`
+ SpamScore *float64 `json:"spam_score,omitempty"`
+ Status InboundEmailStatus `json:"status" gorm:"default:received;not null"`
+ Source InboundSource `json:"source" gorm:"not null"`
+ ErrorMessage string `json:"error_message,omitempty"`
+ RetryCount int `json:"retry_count" gorm:"default:0;not null"`
+ ReceivedAt time.Time `json:"received_at" gorm:"not null"`
+ ForwardedAt *time.Time `json:"forwarded_at,omitempty"`
+ CreatedAt time.Time `json:"created_at"`
+
+ User User `json:"-" gorm:"foreignKey:UserID"`
+ Domain Domain `json:"-" gorm:"foreignKey:DomainID"`
+}
+
+// InboundAttachmentMeta describes one inbound attachment stored in blob storage.
+// Serialized into InboundEmail.AttachmentsJSON.
+type InboundAttachmentMeta struct {
+ Filename string `json:"filename"`
+ ContentType string `json:"content_type"`
+ Size int64 `json:"size"`
+ StorageKey string `json:"storage_key,omitempty"`
+ // Content is only populated when no blob store is configured (dev fallback).
+ Content string `json:"content,omitempty"`
+}
diff --git a/internal/models/oauth_provider.go b/internal/models/oauth_provider.go
index 7de3369..ba14573 100644
--- a/internal/models/oauth_provider.go
+++ b/internal/models/oauth_provider.go
@@ -41,6 +41,7 @@ type OAuthProvider struct {
UserInfoURL string `json:"userinfo_url"`
Scopes string `json:"scopes" gorm:"default:'openid email profile'"`
Enabled bool `json:"enabled" gorm:"default:true;not null"`
+ Hidden bool `json:"hidden" gorm:"default:false;not null"`
AutoRegister bool `json:"auto_register" gorm:"default:true"`
AllowedDomains string `json:"allowed_domains"`
CreatedAt time.Time `json:"created_at"`
diff --git a/internal/models/subscriber_list.go b/internal/models/subscriber_list.go
index 01825da..014bfd8 100644
--- a/internal/models/subscriber_list.go
+++ b/internal/models/subscriber_list.go
@@ -83,3 +83,15 @@ type SubscriberListMember struct {
List SubscriberList `json:"-" gorm:"foreignKey:ListID"`
Subscriber Subscriber `json:"-" gorm:"foreignKey:SubscriberID"`
}
+
+// SubscriberListUnsubscribe records that a specific subscriber has opted out
+type SubscriberListUnsubscribe struct {
+ ID uint `json:"id" gorm:"primaryKey"`
+ ListID uint `json:"list_id" gorm:"uniqueIndex:idx_listunsub_sub;not null"`
+ SubscriberID uint `json:"subscriber_id" gorm:"uniqueIndex:idx_listunsub_sub;not null;index"`
+ Reason string `json:"reason" gorm:"size:64"`
+ UnsubscribedAt time.Time `json:"unsubscribed_at"`
+
+ List SubscriberList `json:"-" gorm:"foreignKey:ListID"`
+ Subscriber Subscriber `json:"-" gorm:"foreignKey:SubscriberID"`
+}
diff --git a/internal/models/user.go b/internal/models/user.go
index 14cfe54..fe81648 100644
--- a/internal/models/user.go
+++ b/internal/models/user.go
@@ -40,6 +40,7 @@ type User struct {
AvatarURL string `json:"avatar_url"`
PlanID *uint `json:"plan_id" gorm:"index"`
ScheduledDeletionAt *time.Time `json:"scheduled_deletion_at"`
+ EmailVerifiedAt *time.Time `json:"email_verified_at"`
CreatedAt time.Time `json:"created_at"`
LastLoginAt *time.Time `json:"last_login_at"`
diff --git a/internal/models/user_email_verification.go b/internal/models/user_email_verification.go
new file mode 100644
index 0000000..9435026
--- /dev/null
+++ b/internal/models/user_email_verification.go
@@ -0,0 +1,29 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package models
+
+import "time"
+
+type UserEmailVerification struct {
+ ID uint `gorm:"primaryKey"`
+ UserID uint `gorm:"index;not null"`
+ TokenHash string `gorm:"uniqueIndex;size:64;not null"`
+ ExpiresAt time.Time `gorm:"not null"`
+ UsedAt *time.Time `gorm:""`
+ CreatedAt time.Time `gorm:"not null"`
+}
diff --git a/internal/routes/admin_routes.go b/internal/routes/admin_routes.go
index 9f0896b..f516085 100644
--- a/internal/routes/admin_routes.go
+++ b/internal/routes/admin_routes.go
@@ -29,7 +29,10 @@ import (
// adminRoutes returns route definitions for admin endpoints.
func (r *Router) adminRoutes() []okapi.RouteDefinition {
- adminGroup := r.v1.Group("/admin", r.mw.jwtAdminAuth.Middleware).WithTags([]string{"Admin"})
+ adminGroup := r.v1.Group("/admin", r.mw.jwtAdminAuth.Middleware).WithTagInfo(okapi.GroupTag{
+ Name: "Admin",
+ Description: "Platform-level administration: users, workspaces, global settings, OAuth providers, and live event streams. Admin-only.",
+ })
adminGroup.WithBearerAuth()
routes := []okapi.RouteDefinition{
@@ -236,6 +239,16 @@ func (r *Router) adminRoutes() []okapi.RouteDefinition {
Request: &handlers.DashboardAnalyticsRequest{},
Response: &dto.Response[handlers.DashboardAnalyticsResponse]{},
},
+ {
+ Method: http.MethodGet,
+ Path: "/analytics/providers",
+ Handler: okapi.H(r.h.analytics.AdminProviderBreakdown),
+ Group: adminGroup,
+ Summary: "Platform deliverability by provider",
+ Description: "Returns platform-wide sent/failed counts and delivery rate grouped by recipient mailbox provider",
+ Request: &handlers.ProviderBreakdownRequest{},
+ Response: &dto.Response[handlers.ProviderBreakdownResponse]{},
+ },
// ==================== Platform Settings ====================
{
@@ -477,7 +490,10 @@ func (r *Router) adminRoutes() []okapi.RouteDefinition {
// adminSSERoutes returns route definitions for admin SSE (Server-Sent Events) endpoints.
func (r *Router) adminSSERoutes() []okapi.RouteDefinition {
- adminSSE := r.v1.Group("/admin", r.mw.jwtAdminQueryAuth.Middleware).WithTags([]string{"Admin"})
+ adminSSE := r.v1.Group("/admin", r.mw.jwtAdminQueryAuth.Middleware).WithTagInfo(okapi.GroupTag{
+ Name: "Admin",
+ Description: "Platform-level administration: users, workspaces, global settings, OAuth providers, and live event streams. Admin-only.",
+ })
return []okapi.RouteDefinition{
{
diff --git a/internal/routes/auth_routes.go b/internal/routes/auth_routes.go
index d81b13c..8f14dec 100644
--- a/internal/routes/auth_routes.go
+++ b/internal/routes/auth_routes.go
@@ -64,7 +64,10 @@ func (r *Router) infoRoute() okapi.RouteDefinition {
// authRoutes returns route definitions for authentication endpoints.
func (r *Router) authRoutes() []okapi.RouteDefinition {
- authGroup := r.v1.Group("/auth", r.mw.loginLimiter).WithTags([]string{"Auth"})
+ authGroup := r.v1.Group("/auth", r.mw.loginLimiter).WithTagInfo(okapi.GroupTag{
+ Name: "Auth",
+ Description: "Sign in, register, and verify email ownership. Public endpoints — protected by a per-IP login rate limiter.",
+ })
return []okapi.RouteDefinition{
{
@@ -104,13 +107,30 @@ func (r *Router) authRoutes() []okapi.RouteDefinition {
Description: "Check whether user self-registration is enabled",
Response: &dto.Response[any]{},
},
+ {
+ Method: http.MethodGet,
+ Path: "/verify-email",
+ Handler: okapi.H(r.h.user.VerifyEmail),
+ Group: authGroup,
+ Summary: "Verify email address",
+ Description: "Redeem a verification token sent to the user's email address",
+ Request: &handlers.VerifyEmailRequest{},
+ Response: &dto.Response[any]{},
+ Options: []okapi.RouteOption{
+ okapi.DocErrorResponse(400, &dto.ErrorResponseBody{}),
+ },
+ },
}
}
// apiAuthRoutes returns route definitions for API-key authenticated endpoints.
func (r *Router) apiAuthRoutes() []okapi.RouteDefinition {
- apiAuth := r.v1.Group("", r.mw.apiKey).WithTags([]string{"Emails"})
- apiAuth.WithBearerAuth()
+ apiAuth := r.v1.Group("", r.mw.apiKey).
+ WithTagInfo(okapi.GroupTag{
+ Name: "Emails",
+ Description: "Send transactional and templated emails, run batch sends, and manage scheduled delivery. Authenticated with an API key.",
+ }).
+ WithSecurity([]map[string][]string{{"ApiKeyAuth": {}}})
return []okapi.RouteDefinition{
{
@@ -124,6 +144,7 @@ func (r *Router) apiAuthRoutes() []okapi.RouteDefinition {
Response: &dto.Response[email.SendResponse]{},
Options: []okapi.RouteOption{
okapi.DocErrorResponse(401, &dto.ErrorResponseBody{}),
+ okapi.DocErrorResponse(403, &dto.ErrorResponseBody{}),
okapi.DocErrorResponse(429, &dto.ErrorResponseBody{}),
},
},
@@ -138,6 +159,7 @@ func (r *Router) apiAuthRoutes() []okapi.RouteDefinition {
Response: &dto.Response[email.SendResponse]{},
Options: []okapi.RouteOption{
okapi.DocErrorResponse(401, &dto.ErrorResponseBody{}),
+ okapi.DocErrorResponse(403, &dto.ErrorResponseBody{}),
okapi.DocErrorResponse(429, &dto.ErrorResponseBody{}),
},
},
@@ -152,6 +174,7 @@ func (r *Router) apiAuthRoutes() []okapi.RouteDefinition {
Response: &dto.Response[email.BatchResponse]{},
Options: []okapi.RouteOption{
okapi.DocErrorResponse(401, &dto.ErrorResponseBody{}),
+ okapi.DocErrorResponse(403, &dto.ErrorResponseBody{}),
okapi.DocErrorResponse(429, &dto.ErrorResponseBody{}),
},
},
@@ -195,5 +218,47 @@ func (r *Router) apiAuthRoutes() []okapi.RouteDefinition {
okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
},
},
+
+ {
+ Method: http.MethodPost,
+ Path: "/subscriber-lists/{id:int}/unsubscribe",
+ Handler: okapi.H(r.h.subscriberList.UnsubscribeByEmail),
+ Group: apiAuth,
+ Summary: "Unsubscribe an email from a list",
+ Description: "Opts an email out of a specific list.",
+ Request: &handlers.ListUnsubscribeByEmailRequest{},
+ Response: &dto.Response[handlers.ListSubscribeResponse]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "List ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/subscriber-lists/{id:int}/resubscribe",
+ Handler: okapi.H(r.h.subscriberList.ResubscribeByEmail),
+ Group: apiAuth,
+ Summary: "Re-subscribe an email to a list",
+ Description: "Reverses a list-scoped opt-out and re-adds to the list (static lists only). Idempotent.",
+ Request: &handlers.ListResubscribeByEmailRequest{},
+ Response: &dto.Response[handlers.ListSubscribeResponse]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "List ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/subscriber-lists/subscribe",
+ Handler: okapi.H(r.h.subscriberList.Subscribe),
+ Group: apiAuth,
+ Summary: "Subscribe an email to a list",
+ Description: "Adds an email to a named list, creating the list on first use. Clears any prior list-scoped opt-out for this (list, email). Idempotent.",
+ Request: &handlers.ListSubscribeRequest{},
+ Response: &dto.Response[handlers.ListSubscribeResponse]{},
+ Options: []okapi.RouteOption{
+ okapi.DocErrorResponse(400, &dto.ErrorResponseBody{}),
+ },
+ },
}
}
diff --git a/internal/routes/inbound_routes.go b/internal/routes/inbound_routes.go
new file mode 100644
index 0000000..439c9af
--- /dev/null
+++ b/internal/routes/inbound_routes.go
@@ -0,0 +1,136 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+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/jkaninda/okapi"
+)
+
+// inboundWebhookRoutes returns public routes for the generic inbound-email webhook
+// and signed attachment downloads. Both are auth'd by opaque secret/token — no JWT.
+func (r *Router) inboundWebhookRoutes() []okapi.RouteDefinition {
+ inboundGroup := r.app.Group("/api/v1/inbound").WithTagInfo(okapi.GroupTag{
+ Name: "Inbound",
+ Description: "Inbound email ingestion and retrieval: receive messages from upstream providers, browse history, and stream live events.",
+ })
+ return []okapi.RouteDefinition{
+ {
+ Method: http.MethodPost,
+ Path: "/webhook",
+ Handler: okapi.H(r.h.inbound.Receive),
+ Group: inboundGroup,
+ Summary: "Receive inbound email via webhook",
+ Request: &handlers.InboundWebhookRequest{},
+ Response: &handlers.InboundWebhookResponse{},
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/attachments/{uuid}/{idx:int}",
+ Handler: okapi.H(r.h.inbound.ServeAttachment),
+ Group: inboundGroup,
+ Summary: "Download an inbound email attachment (signed token)",
+ Options: []okapi.RouteOption{okapi.DocHide()},
+ },
+ }
+}
+
+// inboundUserRoutes returns authenticated routes for browsing inbound email history.
+func (r *Router) inboundUserRoutes() []okapi.RouteDefinition {
+ userGroup := r.v1.Group("/users/me", r.mw.jwtAuth.Middleware, r.mw.optionalWorkspace).WithTagInfo(okapi.GroupTag{
+ Name: "Inbound",
+ Description: "Inbound email ingestion and retrieval: receive messages from upstream providers, browse history, and stream live events. Public ingest endpoints use opaque secrets; user endpoints use JWT.",
+ })
+ userGroup.WithBearerAuth()
+
+ // SSE endpoints use query-param auth because browsers cannot set custom
+ // Authorization headers on EventSource connections.
+ streamGroup := r.v1.Group("/users/me", r.mw.jwtQueryAuth.Middleware, r.mw.optionalWorkspace).WithTagInfo(okapi.GroupTag{
+ Name: "Inbound",
+ Description: "Inbound email ingestion and retrieval: receive messages from upstream providers, browse history, and stream live events. Public ingest endpoints use opaque secrets; user endpoints use JWT.",
+ })
+
+ return []okapi.RouteDefinition{
+ {
+ Method: http.MethodGet,
+ Path: "/inbound-emails",
+ Handler: okapi.H(r.h.inbound.List),
+ Group: userGroup,
+ Summary: "List inbound emails",
+ Request: &handlers.InboundListRequest{},
+ Response: &dto.PageableResponse[models.InboundEmail]{},
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/inbound-emails/{id}",
+ Handler: okapi.H(r.h.inbound.Get),
+ Group: userGroup,
+ Summary: "Get an inbound email by UUID",
+ Request: &handlers.GetEmailRequest{},
+ Response: &dto.Response[models.InboundEmail]{},
+ Options: []okapi.RouteOption{okapi.DocPathParam("id", "string", "Inbound email UUID")},
+ },
+ {
+ Method: http.MethodDelete,
+ Path: "/inbound-emails/{id}",
+ Handler: okapi.H(r.h.inbound.Delete),
+ Group: userGroup,
+ Summary: "Delete an inbound email",
+ Request: &handlers.GetEmailRequest{},
+ Options: []okapi.RouteOption{okapi.DocPathParam("id", "string", "Inbound email UUID")},
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/inbound-emails/{id}/retry",
+ Handler: okapi.H(r.h.inbound.Retry),
+ Group: userGroup,
+ Summary: "Retry webhook dispatch for a failed inbound email",
+ Request: &handlers.GetEmailRequest{},
+ Options: []okapi.RouteOption{okapi.DocPathParam("id", "string", "Inbound email UUID")},
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/inbound-emails/{id}/raw",
+ Handler: okapi.H(r.h.inbound.GetRaw),
+ Group: userGroup,
+ Summary: "Download the raw RFC 5322 message (.eml)",
+ Request: &handlers.GetEmailRequest{},
+ Options: []okapi.RouteOption{okapi.DocPathParam("id", "string", "Inbound email UUID")},
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/inbound-emails/{uuid}/attachments/{idx:int}",
+ Handler: okapi.H(r.h.inbound.DownloadAttachmentAuthed),
+ Group: userGroup,
+ Summary: "Download an inbound email attachment (authenticated)",
+ Request: &handlers.InboundAttachmentOwnedRequest{},
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/inbound-stream",
+ Handler: r.h.inbound.Stream,
+ Group: streamGroup,
+ Summary: "Server-sent events stream of inbound-email events",
+ Options: []okapi.RouteOption{okapi.DocHide()},
+ },
+ }
+}
diff --git a/internal/routes/oauth_routes.go b/internal/routes/oauth_routes.go
index d564928..c0c12e8 100644
--- a/internal/routes/oauth_routes.go
+++ b/internal/routes/oauth_routes.go
@@ -11,7 +11,10 @@ import (
// oauthRoutes returns route definitions for OAuth authentication.
func (r *Router) oauthRoutes() []okapi.RouteDefinition {
// Public OAuth routes (no auth required)
- oauthPublic := r.v1.Group("/auth/oauth").WithTags([]string{"OAuth"})
+ oauthPublic := r.v1.Group("/auth/oauth").WithTagInfo(okapi.GroupTag{
+ Name: "OAuth",
+ Description: "Single sign-on via external identity providers (Google, GitHub, generic OIDC). Covers public flow, user-account linking, admin provider config, and workspace SSO enforcement.",
+ })
routes := make([]okapi.RouteDefinition, 0, 12)
routes = append(routes, []okapi.RouteDefinition{
@@ -24,6 +27,16 @@ func (r *Router) oauthRoutes() []okapi.RouteDefinition {
Description: "Returns enabled OAuth providers for the login page",
Response: &dto.Response[okapi.M]{},
},
+ {
+ Method: http.MethodPost,
+ Path: "/discover",
+ Handler: okapi.H(r.h.oauth.DiscoverSSO),
+ Group: oauthPublic,
+ Summary: "Discover SSO provider by email",
+ Description: "Returns the OAuth provider slug whose allowed domains match the given email's domain. Used for email-first SSO login.",
+ Request: &handlers.DiscoverSSORequest{},
+ Response: &dto.Response[handlers.DiscoverSSOResponse]{},
+ },
{
Method: http.MethodGet,
Path: "/{provider}/authorize",
@@ -50,7 +63,10 @@ func (r *Router) oauthRoutes() []okapi.RouteDefinition {
}...)
// Authenticated OAuth routes (linked accounts)
- oauthUser := r.v1.Group("/users/me/oauth", r.mw.jwtAuth.Middleware).WithTags([]string{"OAuth"})
+ oauthUser := r.v1.Group("/users/me/oauth", r.mw.jwtAuth.Middleware).WithTagInfo(okapi.GroupTag{
+ Name: "OAuth",
+ Description: "Single sign-on via external identity providers (Google, GitHub, generic OIDC). Covers public flow, user-account linking, admin provider config, and workspace SSO enforcement.",
+ })
oauthUser.WithBearerAuth()
routes = append(routes, []okapi.RouteDefinition{
@@ -76,7 +92,16 @@ func (r *Router) oauthRoutes() []okapi.RouteDefinition {
}...)
// Admin OAuth provider management
- oauthAdmin := r.v1.Group("/admin/oauth/providers", r.mw.jwtAdminAuth.Middleware).WithTags([]string{"Admin", "OAuth"})
+ oauthAdmin := r.v1.Group("/admin/oauth/providers", r.mw.jwtAdminAuth.Middleware).WithTagInfo(
+ okapi.GroupTag{
+ Name: "Admin",
+ Description: "Platform-level administration: users, workspaces, global settings, OAuth providers, and live event streams. Admin-only.",
+ },
+ okapi.GroupTag{
+ Name: "OAuth",
+ Description: "Single sign-on via external identity providers (Google, GitHub, generic OIDC). Covers public flow, user-account linking, admin provider config, and workspace SSO enforcement.",
+ },
+ )
oauthAdmin.WithBearerAuth()
routes = append(routes, []okapi.RouteDefinition{
@@ -125,7 +150,16 @@ func (r *Router) oauthRoutes() []okapi.RouteDefinition {
}...)
// Workspace SSO config
- wsSSO := r.v1.Group("/workspaces/current/sso", r.mw.jwtAuth.Middleware, r.mw.workspace).WithTags([]string{"Workspaces", "OAuth"})
+ wsSSO := r.v1.Group("/workspaces/current/sso", r.mw.jwtAuth.Middleware, r.mw.workspace).WithTagInfo(
+ okapi.GroupTag{
+ Name: "Workspaces",
+ Description: "Create workspaces, manage members and invitations, and configure workspace-scoped settings (including SSO).",
+ },
+ okapi.GroupTag{
+ Name: "OAuth",
+ Description: "Single sign-on via external identity providers (Google, GitHub, generic OIDC). Covers public flow, user-account linking, admin provider config, and workspace SSO enforcement.",
+ },
+ )
wsSSO.WithBearerAuth()
routes = append(routes, []okapi.RouteDefinition{
diff --git a/internal/routes/routes.go b/internal/routes/routes.go
index 6b115ba..ca4c672 100644
--- a/internal/routes/routes.go
+++ b/internal/routes/routes.go
@@ -35,7 +35,9 @@ import (
"github.com/goposta/posta/internal/services/auth"
"github.com/goposta/posta/internal/services/cache"
"github.com/goposta/posta/internal/services/email"
+ "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/notification"
planpkg "github.com/goposta/posta/internal/services/plan"
"github.com/goposta/posta/internal/services/ratelimit"
@@ -64,12 +66,14 @@ type Router struct {
type routerMiddleware struct {
jwtAuth okapi.JWTAuth
+ jwtQueryAuth okapi.JWTAuth
jwtAdminAuth okapi.JWTAuth
jwtAdminQueryAuth okapi.JWTAuth
loginLimiter okapi.Middleware
apiKey okapi.Middleware
workspace okapi.Middleware
optionalWorkspace okapi.Middleware
+ verifiedEmail okapi.Middleware
}
type routerHandlers struct {
@@ -109,6 +113,7 @@ type routerHandlers struct {
bounceWebhook *handlers.BounceWebhookHandler
workspaceData *handlers.WorkspaceDataHandler
plan *handlers.PlanHandler
+ inbound *handlers.InboundHandler
}
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) {
@@ -134,6 +139,7 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *c
userSettingRepo := repositories.NewUserSettingRepository(db)
sessionRepo := repositories.NewSessionRepository(db)
workspaceRepo := repositories.NewWorkspaceRepository(db)
+ emailVerifyRepo := repositories.NewUserEmailVerificationRepository(db)
// Session store (Redis-backed blacklist)
sessionStore := sessionpkg.NewStore(redisClient)
@@ -190,6 +196,7 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *c
// Start worker connection monitor
wm := workermon.New(inspector, bus, 15*time.Second)
+ wm.OnCount(metrics.SetActiveWorkers)
wm.Start(ctx)
r := &Router{
@@ -198,6 +205,7 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *c
v1: app.Group("/api/v1"),
mw: routerMiddleware{
jwtAuth: middlewares.JWTAuth(cfg, sessionStore),
+ jwtQueryAuth: middlewares.JWTQueryAuth(cfg, sessionStore),
jwtAdminAuth: middlewares.JWTAdminAuth(cfg, sessionStore),
jwtAdminQueryAuth: middlewares.JWTAdminQueryAuth(cfg, sessionStore),
loginLimiter: loginLimiterMiddleware(cfg, limiter),
@@ -248,12 +256,19 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *c
r.h.smtp.SetQuota(planService, db)
// Notifications
+ var notif *notification.Service
if len(notifier) > 0 && notifier[0] != nil {
- r.h.user.SetNotifier(notifier[0])
- r.h.workspace.SetNotifier(notifier[0], cfg.AppWebURL)
- r.h.apiKey.SetNotifier(notifier[0])
+ notif = notifier[0]
+ r.h.user.SetNotifier(notif)
+ r.h.workspace.SetNotifier(notif, cfg.AppWebURL)
+ r.h.apiKey.SetNotifier(notif)
}
+ // Email verification service (coordinates token issuance, delivery, redemption)
+ emailVerifySvc := emailverify.NewService(userRepo, emailVerifyRepo, notif, cfg.AppWebURL, cfg.EmailVerificationRequired)
+ r.h.user.SetEmailVerifier(emailVerifySvc)
+ r.mw.verifiedEmail = middlewares.RequireVerifiedEmail(emailVerifySvc, userRepo)
+
// Email content privacy
r.h.email.SetSettings(settingsProvider)
r.h.admin.SetEmailSettings(settingsProvider)
@@ -286,22 +301,66 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *c
r.h.subscriber = handlers.NewSubscriberHandler(subscriberRepo)
r.h.subscriberList = handlers.NewSubscriberListHandler(subscriberListRepo, subscriberRepo)
+ // Enable list-aware API sends now that the subscriber repos exist.
+ emailService.SetListAutoSubscribe(subscriberListRepo, subscriberRepo)
+
// Campaigns
campaignRepo := repositories.NewCampaignRepository(db)
campaignMessageRepo := repositories.NewCampaignMessageRepository(db)
r.h.campaign = handlers.NewCampaignHandler(
campaignRepo, campaignMessageRepo,
- subscriberListRepo, subscriberRepo, templateRepo, producer,
+ subscriberListRepo, subscriberRepo, templateRepo, domainRepo, producer,
)
// Tracking
trackingRepo := repositories.NewTrackingRepository(db)
trackingService := tracking.NewService(trackingRepo, cfg.AppWebURL, []byte(cfg.JWTSecret))
- r.h.tracking = handlers.NewTrackingHandler(trackingRepo, campaignMessageRepo, campaignRepo, subscriberRepo, trackingService)
+ r.h.tracking = handlers.NewTrackingHandler(trackingRepo, campaignMessageRepo, campaignRepo, subscriberRepo, subscriberListRepo, emailRepo, suppressionRepo, trackingService)
+
+ // Auto-attach RFC 8058 one-click unsubscribe URLs on transactional sends
+ // that target a subscriber list (so Gmail/Yahoo bulk-sender requirements
+ // are met without the caller having to build the header themselves).
+ emailService.SetTxUnsubscribeGenerator(trackingService)
// Bounce webhook
r.h.bounceWebhook = handlers.NewBounceWebhookHandler(subscriberRepo, emailRepo, campaignMessageRepo)
+ // Inbound email
+ if cfg.InboundEnabled {
+ inboundEmailRepo := repositories.NewInboundEmailRepository(db)
+ inboundSvc := inbound.NewService(
+ inboundEmailRepo,
+ domainRepo,
+ suppressionRepo,
+ inbound.Config{
+ MaxMessageSize: cfg.InboundMaxMessageSize,
+ MaxAttachmentSize: cfg.InboundMaxAttachSize,
+ },
+ )
+ if blobStore != nil {
+ inboundSvc.SetBlobStore(blobStore)
+ }
+ if producer != nil {
+ inboundSvc.SetEnqueuer(producer)
+ }
+ inboundSvc.SetEventBus(bus)
+ inboundSvc.OnReceived(func(src models.InboundSource) { metrics.IncrementInboundReceived(string(src)) })
+ inboundSvc.OnRejected(metrics.IncrementInboundRejected)
+ inboundSvc.OnBytes(metrics.AddInboundBytes)
+
+ r.h.inbound = handlers.NewInboundHandler(
+ inboundSvc,
+ inboundEmailRepo,
+ blobStore,
+ cfg.InboundWebhookSecret,
+ []byte(cfg.JWTSecret),
+ )
+ if producer != nil {
+ r.h.inbound.SetEnqueuer(producer)
+ }
+ r.h.inbound.SetEventBus(bus)
+ }
+
// Workspace data export/import
r.h.workspaceData = handlers.NewWorkspaceDataHandler(
db, workspaceRepo, templateRepo, versionRepo, localizationRepo,
@@ -382,6 +441,10 @@ func (r *Router) registerRoutes() {
r.app.Register(r.trackingRoutes()...)
r.app.Register(r.trackingAnalyticsRoutes()...)
r.app.Register(r.bounceWebhookRoutes()...)
+ if r.cfg.InboundEnabled && r.h.inbound != nil {
+ r.app.Register(r.inboundWebhookRoutes()...)
+ r.app.Register(r.inboundUserRoutes()...)
+ }
r.app.Register(r.adminRoutes()...)
r.app.Register(r.adminSSERoutes()...)
diff --git a/internal/routes/tracking_routes.go b/internal/routes/tracking_routes.go
index ffda13a..caf2eda 100644
--- a/internal/routes/tracking_routes.go
+++ b/internal/routes/tracking_routes.go
@@ -29,7 +29,7 @@ func (r *Router) trackingRoutes() []okapi.RouteDefinition {
return []okapi.RouteDefinition{
{
Method: http.MethodGet,
- Path: "/t/o/{message_id:int}.png",
+ Path: "/t/o/{message_id:int}.gif",
Handler: okapi.H(r.h.tracking.OpenPixel),
Tags: []string{"Tracking"},
Summary: "Open tracking pixel",
@@ -59,12 +59,32 @@ func (r *Router) trackingRoutes() []okapi.RouteDefinition {
Summary: "Confirm unsubscribe",
Options: []okapi.RouteOption{okapi.DocHide()},
},
+ {
+ Method: http.MethodGet,
+ Path: "/t/u/tx/{token}",
+ Handler: okapi.H(r.h.tracking.TxUnsubscribePage),
+ Tags: []string{"Tracking"},
+ Summary: "Transactional unsubscribe page",
+ Options: []okapi.RouteOption{okapi.DocHide()},
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/t/u/tx/{token}",
+ Handler: okapi.H(r.h.tracking.TxUnsubscribeConfirm),
+ Tags: []string{"Tracking"},
+ Summary: "Transactional one-click unsubscribe (RFC 8058)",
+ Options: []okapi.RouteOption{okapi.DocHide()},
+ },
}
}
// bounceWebhookRoutes returns the bounce webhook route (authenticated via API key).
func (r *Router) bounceWebhookRoutes() []okapi.RouteDefinition {
- bounceGroup := r.app.Group("/webhooks/bounce", r.mw.apiKey).WithTags([]string{"Webhooks"})
+ bounceGroup := r.app.Group("/webhooks/bounce", r.mw.apiKey).WithTagInfo(okapi.GroupTag{
+ Name: "Webhooks",
+ Description: "Inbound webhook endpoints that receive bounce and complaint notifications from upstream mail providers. Authenticated with an API key.",
+ }).WithSecurity([]map[string][]string{{"ApiKeyAuth": {}}})
+
return []okapi.RouteDefinition{
{
Method: http.MethodPost,
@@ -80,7 +100,10 @@ func (r *Router) bounceWebhookRoutes() []okapi.RouteDefinition {
// trackingAnalyticsRoutes returns the authenticated campaign analytics route.
func (r *Router) trackingAnalyticsRoutes() []okapi.RouteDefinition {
- userGroup := r.v1.Group("/users/me", r.mw.jwtAuth.Middleware, r.mw.optionalWorkspace).WithTags([]string{"Campaigns"})
+ userGroup := r.v1.Group("/users/me", r.mw.jwtAuth.Middleware, r.mw.optionalWorkspace).WithTagInfo(okapi.GroupTag{
+ Name: "Campaigns",
+ Description: "Email campaign analytics — open, click, bounce, and engagement metrics for campaigns you own.",
+ })
userGroup.WithBearerAuth()
return []okapi.RouteDefinition{
diff --git a/internal/routes/user_routes.go b/internal/routes/user_routes.go
index 2471c36..44e9dc6 100644
--- a/internal/routes/user_routes.go
+++ b/internal/routes/user_routes.go
@@ -29,7 +29,10 @@ import (
// userRoutes returns route definitions for all authenticated user endpoints.
func (r *Router) userRoutes() []okapi.RouteDefinition {
- userGroup := r.v1.Group("/users/me", r.mw.jwtAuth.Middleware, r.mw.optionalWorkspace).WithTags([]string{"User"})
+ userGroup := r.v1.Group("/users/me", r.mw.jwtAuth.Middleware, r.mw.optionalWorkspace).WithTagInfo(okapi.GroupTag{
+ Name: "User",
+ Description: "Manage the authenticated user: profile, password, API keys, notification preferences, and session.",
+ })
userGroup.WithBearerAuth()
routes := []okapi.RouteDefinition{
@@ -62,6 +65,18 @@ func (r *Router) userRoutes() []okapi.RouteDefinition {
Request: &handlers.ChangePasswordRequest{},
Response: &dto.Response[dto.MessageData]{},
},
+ {
+ Method: http.MethodPost,
+ Path: "/verify-email/resend",
+ Handler: r.h.user.ResendVerificationEmail,
+ Group: userGroup,
+ Summary: "Resend verification email",
+ Description: "Issue a fresh verification email for the authenticated user",
+ Response: &dto.Response[dto.MessageData]{},
+ Options: []okapi.RouteOption{
+ okapi.DocErrorResponse(429, &dto.ErrorResponseBody{}),
+ },
+ },
// ==================== Plan ====================
{
@@ -197,6 +212,16 @@ func (r *Router) userRoutes() []okapi.RouteDefinition {
Request: &handlers.DashboardAnalyticsRequest{},
Response: &dto.Response[handlers.DashboardAnalyticsResponse]{},
},
+ {
+ Method: http.MethodGet,
+ Path: "/analytics/providers",
+ Handler: okapi.H(r.h.analytics.UserProviderBreakdown),
+ Group: userGroup,
+ Summary: "Deliverability by provider",
+ Description: "Returns sent/failed counts and delivery rate grouped by recipient mailbox provider (Gmail, Outlook, Yahoo, ...)",
+ Request: &handlers.ProviderBreakdownRequest{},
+ Response: &dto.Response[handlers.ProviderBreakdownResponse]{},
+ },
// ==================== Email Logs ====================
{
@@ -270,11 +295,13 @@ func (r *Router) userRoutes() []okapi.RouteDefinition {
Path: "/api-keys",
Handler: okapi.H(r.h.apiKey.Create),
Group: userGroup,
+ Middlewares: []okapi.Middleware{r.mw.verifiedEmail},
Summary: "Create API key",
Description: "Generate a new API key. The raw key is only shown once in the response.",
Request: &handlers.CreateAPIKeyRequest{},
Options: []okapi.RouteOption{
okapi.DocResponse(201, &dto.Response[dto.APIKeyCreatedData]{}),
+ okapi.DocErrorResponse(403, &dto.ErrorResponseBody{}),
},
},
{
@@ -1181,6 +1208,30 @@ func (r *Router) userRoutes() []okapi.RouteDefinition {
Request: &handlers.PreviewSegmentRequest{},
Response: &dto.Response[okapi.M]{},
},
+ {
+ Method: http.MethodPost,
+ Path: "/subscriber-lists/{id:int}/unsubscribe",
+ Handler: okapi.H(r.h.subscriberList.UnsubscribeByEmail),
+ Group: userGroup,
+ Tags: []string{"Subscriber Lists"},
+ Summary: "Unsubscribe an email from a list",
+ Description: "API-key-accessible list opt-out. Idempotent. Does not change global subscriber status.",
+ Request: &handlers.ListUnsubscribeByEmailRequest{},
+ Response: &dto.Response[handlers.ListSubscribeResponse]{},
+ Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "List ID")},
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/subscriber-lists/{id:int}/resubscribe",
+ Handler: okapi.H(r.h.subscriberList.ResubscribeByEmail),
+ Group: userGroup,
+ Tags: []string{"Subscriber Lists"},
+ Summary: "Re-subscribe an email to a list",
+ Description: "Reverses a list-scoped opt-out and re-adds to the list (static lists). Idempotent.",
+ Request: &handlers.ListResubscribeByEmailRequest{},
+ Response: &dto.Response[handlers.ListSubscribeResponse]{},
+ Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "List ID")},
+ },
// ==================== Campaigns ====================
{
diff --git a/internal/routes/workspace_routes.go b/internal/routes/workspace_routes.go
index 75a01bc..53c3370 100644
--- a/internal/routes/workspace_routes.go
+++ b/internal/routes/workspace_routes.go
@@ -29,7 +29,10 @@ import (
// workspaceRoutes returns route definitions for workspace management.
func (r *Router) workspaceRoutes() []okapi.RouteDefinition {
// Routes that don't require workspace context (user-level)
- userGroup := r.v1.Group("/workspaces", r.mw.jwtAuth.Middleware).WithTags([]string{"Workspaces"})
+ userGroup := r.v1.Group("/workspaces", r.mw.jwtAuth.Middleware).WithTagInfo(okapi.GroupTag{
+ Name: "Workspaces",
+ Description: "Create workspaces, manage members and invitations, and configure workspace-scoped settings.",
+ })
userGroup.WithBearerAuth()
routes := make([]okapi.RouteDefinition, 0, 20)
@@ -39,11 +42,13 @@ func (r *Router) workspaceRoutes() []okapi.RouteDefinition {
Path: "",
Handler: okapi.H(r.h.workspace.Create),
Group: userGroup,
+ Middlewares: []okapi.Middleware{r.mw.verifiedEmail},
Summary: "Create workspace",
Description: "Create a new workspace. The creator becomes the owner.",
Request: &handlers.CreateWorkspaceRequest{},
Options: []okapi.RouteOption{
okapi.DocResponse(201, &dto.Response[handlers.WorkspaceResponse]{}),
+ okapi.DocErrorResponse(403, &dto.ErrorResponseBody{}),
okapi.DocErrorResponse(409, &dto.ErrorResponseBody{}),
},
},
@@ -59,7 +64,10 @@ func (r *Router) workspaceRoutes() []okapi.RouteDefinition {
}...)
// Workspace-scoped routes (require workspace context via middleware)
- wsGroup := r.v1.Group("/workspaces/current", r.mw.jwtAuth.Middleware, r.mw.workspace).WithTags([]string{"Workspaces"})
+ wsGroup := r.v1.Group("/workspaces/current", r.mw.jwtAuth.Middleware, r.mw.workspace).WithTagInfo(okapi.GroupTag{
+ Name: "Workspaces",
+ Description: "Create workspaces, manage members and invitations, and configure workspace-scoped settings (including SSO).",
+ })
wsGroup.WithBearerAuth()
routes = append(routes, []okapi.RouteDefinition{
@@ -139,12 +147,14 @@ func (r *Router) workspaceRoutes() []okapi.RouteDefinition {
Path: "/invitations",
Handler: okapi.H(r.h.workspace.InviteMember),
Group: wsGroup,
+ Middlewares: []okapi.Middleware{r.mw.verifiedEmail},
Summary: "Invite member",
Description: "Invite a user to the workspace via email",
Request: &handlers.InviteMemberRequest{},
Options: []okapi.RouteOption{
workspaceHeaderRequired,
okapi.DocResponse(201, &dto.Response[handlers.InvitationResponse]{}),
+ okapi.DocErrorResponse(403, &dto.ErrorResponseBody{}),
},
},
{
@@ -219,7 +229,10 @@ func (r *Router) workspaceRoutes() []okapi.RouteDefinition {
}...)
// User-level invitation actions (no workspace context needed)
- invGroup := r.v1.Group("/invitations", r.mw.jwtAuth.Middleware).WithTags([]string{"Workspaces"})
+ invGroup := r.v1.Group("/invitations", r.mw.jwtAuth.Middleware).WithTagInfo(okapi.GroupTag{
+ Name: "Workspaces",
+ Description: "Create workspaces, manage members and invitations, and configure workspace-scoped settings (including SSO).",
+ })
invGroup.WithBearerAuth()
routes = append(routes, []okapi.RouteDefinition{
diff --git a/internal/services/auth/oauth.go b/internal/services/auth/oauth.go
index 3dac106..afc216d 100644
--- a/internal/services/auth/oauth.go
+++ b/internal/services/auth/oauth.go
@@ -296,6 +296,11 @@ func (s *OAuthService) FindOrCreateUser(provider *models.OAuthProvider, info *OA
if existingUser.AvatarURL == "" {
existingUser.AvatarURL = info.AvatarURL
}
+ // Trusted IdP confirmed the email — auto-verify if still pending.
+ if existingUser.EmailVerifiedAt == nil {
+ now := time.Now()
+ existingUser.EmailVerifiedAt = &now
+ }
_ = s.userRepo.Update(existingUser)
return existingUser, false, nil
@@ -311,13 +316,15 @@ func (s *OAuthService) FindOrCreateUser(provider *models.OAuthProvider, info *OA
name = strings.SplitN(email, "@", 2)[0]
}
+ now := time.Now()
newUser := &models.User{
- Email: email,
- Name: name,
- Role: models.UserRoleUser,
- AuthMethod: "oauth",
- AvatarURL: info.AvatarURL,
- Active: true,
+ Email: email,
+ Name: name,
+ Role: models.UserRoleUser,
+ AuthMethod: "oauth",
+ AvatarURL: info.AvatarURL,
+ Active: true,
+ EmailVerifiedAt: &now,
}
if err := s.userRepo.Create(newUser); err != nil {
return nil, false, fmt.Errorf("failed to create user: %w", err)
diff --git a/internal/services/cache/cache.go b/internal/services/cache/cache.go
index 146007f..4aa9fa7 100644
--- a/internal/services/cache/cache.go
+++ b/internal/services/cache/cache.go
@@ -39,6 +39,8 @@ const (
prefixAdminAnalytics = "cache:analytics:admin"
prefixDashAnalytics = "cache:dash_analytics:user:"
prefixAdminDashAnalytics = "cache:dash_analytics:admin"
+ prefixUserProvider = "cache:provider:user:"
+ prefixAdminProvider = "cache:provider:admin"
)
// Cache provides Redis-backed caching for dashboard stats and metrics.
@@ -101,6 +103,14 @@ func AdminDashboardAnalyticsKey(from, to string) string {
return fmt.Sprintf("%s:%s:%s", prefixAdminDashAnalytics, from, to)
}
+func UserProviderBreakdownKey(userID int, from, to string) string {
+ return fmt.Sprintf("%s%d:%s:%s", prefixUserProvider, userID, from, to)
+}
+
+func AdminProviderBreakdownKey(from, to string) string {
+ return fmt.Sprintf("%s:%s:%s", prefixAdminProvider, from, to)
+}
+
// InvalidateUser removes all cached data scoped to a specific user.
func (c *Cache) InvalidateUser(ctx context.Context, userID int) {
c.Delete(ctx, DashboardKey(userID))
@@ -108,6 +118,7 @@ func (c *Cache) InvalidateUser(ctx context.Context, userID int) {
// Per-user analytics (date-range queries include user ID in key)
c.InvalidateByPattern(ctx, fmt.Sprintf("%s%d:*", prefixUserAnalytics, userID))
c.InvalidateByPattern(ctx, fmt.Sprintf("%s%d:*", prefixDashAnalytics, userID))
+ c.InvalidateByPattern(ctx, fmt.Sprintf("%s%d:*", prefixUserProvider, userID))
// Admin-level caches are affected since user data rolls up into them.
c.Delete(ctx, AdminMetricsKey())
}
@@ -129,6 +140,7 @@ func (c *Cache) InvalidateByPattern(ctx context.Context, pattern string) {
func (c *Cache) InvalidateAnalytics(ctx context.Context) {
c.InvalidateByPattern(ctx, "cache:analytics:*")
c.InvalidateByPattern(ctx, "cache:dash_analytics:*")
+ c.InvalidateByPattern(ctx, "cache:provider:*")
}
// InvalidateAll removes all cache keys (dashboard + metrics + analytics).
diff --git a/internal/services/email/provider.go b/internal/services/email/provider.go
new file mode 100644
index 0000000..ed5986b
--- /dev/null
+++ b/internal/services/email/provider.go
@@ -0,0 +1,159 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package email
+
+import (
+ "net/mail"
+ "strings"
+)
+
+const ProviderOther = "Other"
+
+var providerByDomain = map[string]string{
+ // Gmail (consumer)
+ "gmail.com": "Gmail",
+ "googlemail.com": "Gmail",
+
+ // Google Workspace primary domain
+ "google.com": "Google Workspace",
+
+ // Outlook / Microsoft consumer
+ "outlook.com": "Outlook",
+ "hotmail.com": "Outlook",
+ "live.com": "Outlook",
+ "msn.com": "Outlook",
+ "outlook.co.uk": "Outlook",
+ "hotmail.co.uk": "Outlook",
+ "live.co.uk": "Outlook",
+ "hotmail.fr": "Outlook",
+ "outlook.fr": "Outlook",
+ "live.fr": "Outlook",
+
+ // Yahoo
+ "yahoo.com": "Yahoo",
+ "yahoo.co.uk": "Yahoo",
+ "yahoo.fr": "Yahoo",
+ "yahoo.de": "Yahoo",
+ "yahoo.co.jp": "Yahoo",
+ "yahoo.ca": "Yahoo",
+ "ymail.com": "Yahoo",
+ "rocketmail.com": "Yahoo",
+
+ // Apple iCloud
+ "icloud.com": "Apple iCloud",
+ "me.com": "Apple iCloud",
+ "mac.com": "Apple iCloud",
+
+ // Proton
+ "proton.me": "Proton",
+ "protonmail.com": "Proton",
+ "pm.me": "Proton",
+
+ // AOL
+ "aol.com": "AOL",
+
+ // GMX / mail.com
+ "gmx.com": "GMX",
+ "gmx.net": "GMX",
+ "gmx.de": "GMX",
+ "mail.com": "GMX",
+
+ // Zoho
+ "zoho.com": "Zoho",
+ "zohomail.com": "Zoho",
+
+ // Fastmail
+ "fastmail.com": "Fastmail",
+ "fastmail.fm": "Fastmail",
+
+ // Yandex
+ "yandex.ru": "Yandex",
+ "yandex.com": "Yandex",
+}
+
+// providerBySuffix catches subdomain-style matches (e.g. "mail.google.com").
+// Entries must begin with "." so we don't accidentally match "googlefoo.com".
+var providerBySuffix = []struct {
+ suffix string
+ provider string
+}{
+ {".google.com", "Google Workspace"},
+}
+
+func NormalizeDomain(addr string) string {
+ trimmed := strings.TrimSpace(addr)
+ if trimmed == "" {
+ return ""
+ }
+ // mail.ParseAddress handles "Name" <a@b>, "<a@b>", and "a@b".
+ parsed, err := mail.ParseAddress(trimmed)
+ if err != nil {
+ if at := strings.LastIndex(trimmed, "@"); at >= 0 {
+ tail := trimmed[at+1:]
+ end := len(tail)
+ for i, r := range tail {
+ if notDomainRune(r) {
+ end = i
+ break
+ }
+ }
+ return strings.ToLower(tail[:end])
+ }
+ return ""
+ }
+ at := strings.LastIndex(parsed.Address, "@")
+ if at < 0 {
+ return ""
+ }
+ return strings.ToLower(parsed.Address[at+1:])
+}
+
+func notDomainRune(r rune) bool {
+ return (r < 'a' || r > 'z') && (r < 'A' || r > 'Z') && (r < '0' || r > '9') && r != '.' && r != '-'
+}
+
+func ClassifyProvider(addr string) string {
+ return ClassifyProviderFromDomain(NormalizeDomain(addr))
+}
+
+func ClassifyProviderFromDomain(domain string) string {
+ if domain == "" {
+ return ProviderOther
+ }
+ if p, ok := providerByDomain[domain]; ok {
+ return p
+ }
+ for _, s := range providerBySuffix {
+ if strings.HasSuffix(domain, s.suffix) {
+ return s.provider
+ }
+ }
+ return ProviderOther
+}
+
+func ClassifyRecipients(recipients []string) string {
+ for _, r := range recipients {
+ if p := ClassifyProvider(r); p != ProviderOther {
+ return p
+ }
+ if NormalizeDomain(r) != "" {
+ return ProviderOther
+ }
+ }
+ return ProviderOther
+}
diff --git a/internal/services/email/provider_test.go b/internal/services/email/provider_test.go
new file mode 100644
index 0000000..4b29321
--- /dev/null
+++ b/internal/services/email/provider_test.go
@@ -0,0 +1,89 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ */
+
+package email
+
+import "testing"
+
+func TestNormalizeDomain(t *testing.T) {
+ cases := map[string]string{
+ "[email protected]": "gmail.com",
+ "[email protected]": "gmail.com",
+ `"Jonas" <[email protected]>`: "gmail.com",
+ `Jonas Kaninda <[email protected]>`: "gmail.com",
+ " [email protected] ": "outlook.com",
+ "no-at-sign": "",
+ "": "",
+ "weird<[email protected]>trail": "gmail.com",
+ }
+ for in, want := range cases {
+ if got := NormalizeDomain(in); got != want {
+ t.Errorf("NormalizeDomain(%q) = %q, want %q", in, got, want)
+ }
+ }
+}
+
+func TestClassifyProvider(t *testing.T) {
+ cases := map[string]string{
+ "[email protected]": "Gmail",
+ "[email protected]": "Gmail",
+ "[email protected]": "Google Workspace",
+ "[email protected]": "Google Workspace",
+ "[email protected]": "Google Workspace",
+ "[email protected]": "Outlook",
+ "[email protected]": "Outlook",
+ "[email protected]": "Yahoo",
+ "[email protected]": "Apple iCloud",
+ "[email protected]": "Proton",
+ "[email protected]": "Proton",
+ "[email protected]": "AOL",
+ "[email protected]": "GMX",
+ "[email protected]": "Zoho",
+ "[email protected]": "Fastmail",
+ "[email protected]": "Yandex",
+ "[email protected]": "Other",
+ "": "Other",
+ "bad-address": "Other",
+ `"J" <[email protected]>`: "Gmail",
+ }
+ for in, want := range cases {
+ if got := ClassifyProvider(in); got != want {
+ t.Errorf("ClassifyProvider(%q) = %q, want %q", in, got, want)
+ }
+ }
+}
+
+func TestClassifyRecipients(t *testing.T) {
+ cases := []struct {
+ in []string
+ want string
+ }{
+ {[]string{"[email protected]"}, "Gmail"},
+ {[]string{"[email protected]", "[email protected]"}, "Other"}, // first parseable wins
+ {[]string{"", "[email protected]"}, "Yahoo"},
+ {nil, "Other"},
+ {[]string{}, "Other"},
+ {[]string{""}, "Other"},
+ }
+ for _, tc := range cases {
+ if got := ClassifyRecipients(tc.in); got != tc.want {
+ t.Errorf("ClassifyRecipients(%v) = %q, want %q", tc.in, got, tc.want)
+ }
+ }
+}
+
+// Defense against the original bug: RFC 5322 display names must not leak into
+// the domain column. With the old split_part SQL, this produced "gmail.com>".
+func TestRFC5322DisplayNameIsStripped(t *testing.T) {
+ got := NormalizeDomain(`"Jonas Kaninda" <[email protected]>`)
+ if got != "gmail.com" {
+ t.Fatalf("display-name stripping failed: got %q, want %q", got, "gmail.com")
+ }
+}
diff --git a/internal/services/email/service.go b/internal/services/email/service.go
index 36f069f..de3f283 100644
--- a/internal/services/email/service.go
+++ b/internal/services/email/service.go
@@ -22,6 +22,7 @@ import (
"context"
"encoding/base64"
"encoding/json"
+ "errors"
"fmt"
"io"
"net/mail"
@@ -35,6 +36,7 @@ import (
"github.com/goposta/posta/internal/storage/blob"
"github.com/goposta/posta/internal/storage/repositories"
"github.com/jkaninda/logger"
+ "gorm.io/gorm"
)
const (
@@ -64,6 +66,13 @@ type PlanLimits struct {
MaxBatchSize int
}
+// TxUnsubscribeGenerator produces a signed one-click (RFC 8058) unsubscribe
+// URL for a transactional email. Kept as a narrow interface so the email
+// service does not depend directly on the tracking package.
+type TxUnsubscribeGenerator interface {
+ TxUnsubscribeURL(emailID uint) string
+}
+
type Service struct {
emailRepo *repositories.EmailRepository
smtpRepo *repositories.SMTPRepository
@@ -74,6 +83,8 @@ type Service struct {
contactRepo *repositories.ContactRepository
domainRepo *repositories.DomainRepository
userRepo *repositories.UserRepository
+ listRepo *repositories.SubscriberListRepository
+ subscriberRepo *repositories.SubscriberRepository
sender *SMTPSender
renderer *TemplateRenderer
limiter *ratelimit.RedisLimiter
@@ -82,6 +93,7 @@ type Service struct {
settings *settings.Provider
blobStore blob.Store
planLimits PlanLimitsProvider
+ txUnsubGen TxUnsubscribeGenerator
devMode bool
onSent func()
onFailed func()
@@ -143,6 +155,21 @@ func (s *Service) SetEnqueuer(eq EmailEnqueuer) {
s.enqueuer = eq
}
+// SetListAutoSubscribe enables the optional `list` field on API sends: when
+// set, a send to a single recipient can auto-add that recipient to a named
+// list (creating it if needed), and respect per-list opt-outs.
+func (s *Service) SetListAutoSubscribe(listRepo *repositories.SubscriberListRepository, subRepo *repositories.SubscriberRepository) {
+ s.listRepo = listRepo
+ s.subscriberRepo = subRepo
+}
+
+// SetTxUnsubscribeGenerator wires the one-click unsubscribe URL generator.
+// When set, transactional sends that use a subscriber list but don't supply an
+// explicit list_unsubscribe_url will get an auto-generated RFC 8058 URL.
+func (s *Service) SetTxUnsubscribeGenerator(gen TxUnsubscribeGenerator) {
+ s.txUnsubGen = gen
+}
+
// SetBlobStore sets the blob storage backend for persisting email attachments.
// When configured, attachment content is uploaded to the store and only metadata
// (with a storage key) is kept in the database, reducing DB pressure.
@@ -225,6 +252,10 @@ type SendRequest struct {
ListUnsubscribeURL string `json:"list_unsubscribe_url,omitempty"`
ListUnsubscribePost bool `json:"list_unsubscribe_post,omitempty"`
SendAt *time.Time `json:"send_at,omitempty"`
+ // List (optional) adds the recipient to a subscriber list by name.
+ List string `json:"list,omitempty" doc:"list (optional) adds the recipient to a subscriber list by name."`
+ // TemplateName is populated by internal template-send paths
+ TemplateName string `json:"-"`
}
type SendTemplateRequest struct {
@@ -240,6 +271,15 @@ type SendTemplateRequest struct {
type SendResponse struct {
ID string `json:"id"`
Status models.EmailStatus `json:"status"`
+ // List auto-subscribe outcome. All optional; populated only when the
+ // request's `list` field was set. Skipped=true means the email was NOT
+ // queued because the recipient is suppressed or not in 'subscribed' status.
+ ListID *uint `json:"list_id,omitempty"`
+ SubscriberID *uint `json:"subscriber_id,omitempty"`
+ ListCreated bool `json:"list_created,omitempty"`
+ MemberAdded bool `json:"member_added,omitempty"`
+ Skipped bool `json:"skipped,omitempty"`
+ SkippedReason string `json:"skipped_reason,omitempty"`
}
type BatchRequest struct {
@@ -479,6 +519,44 @@ func (s *Service) Send(ctx context.Context, userID, apiKeyID uint, workspaceID *
}
}
+ // Optional: list auto-subscribe + per-list suppression gate. Runs before
+ // suppression/rate/attachments work is persisted so a skipped send doesn't
+ // leak DB writes. Only applies to single-recipient sends.
+ listResult, err := s.resolveAutoSubscribe(userID, workspaceID, req)
+ if err != nil {
+ return nil, err
+ }
+ if listResult != nil && listResult.Skipped {
+ // Record a 'suppressed' email row for the audit trail, mirroring the
+ // behavior for the global suppression list, then return 200 with
+ // skipped=true so callers can branch on compliance without parsing 4xx.
+ var apiKeyPtr *uint
+ if apiKeyID > 0 {
+ apiKeyPtr = &apiKeyID
+ }
+ em := &models.Email{
+ UserID: userID,
+ WorkspaceID: workspaceID,
+ APIKeyID: apiKeyPtr,
+ Sender: req.From,
+ Recipients: req.To,
+ Subject: req.Subject,
+ TemplateName: req.TemplateName,
+ Status: models.EmailStatusSuppressed,
+ ErrorMessage: listResult.SkippedReason,
+ Provider: ClassifyRecipients(req.To),
+ }
+ _ = s.emailRepo.Create(em)
+ return &SendResponse{
+ ID: em.UUID,
+ Status: em.Status,
+ ListID: listResult.ListID,
+ SubscriberID: listResult.SubscriberID,
+ Skipped: true,
+ SkippedReason: listResult.SkippedReason,
+ }, nil
+ }
+
// Filter out suppressed recipients
scope := repositories.ResourceScope{UserID: userID, WorkspaceID: workspaceID}
if s.suppressionRepo != nil {
@@ -499,10 +577,12 @@ func (s *Service) Send(ctx context.Context, userID, apiKeyID uint, workspaceID *
Sender: req.From,
Recipients: req.To,
Subject: req.Subject,
+ TemplateName: req.TemplateName,
HTMLBody: req.HTML,
TextBody: req.Text,
Status: models.EmailStatusSuppressed,
ErrorMessage: "all recipients are suppressed",
+ Provider: ClassifyRecipients(req.To),
}
_ = s.emailRepo.Create(em)
return &SendResponse{ID: em.UUID, Status: em.Status}, nil
@@ -522,8 +602,10 @@ func (s *Service) Send(ctx context.Context, userID, apiKeyID uint, workspaceID *
Sender: req.From,
Recipients: []string{addr},
Subject: req.Subject,
+ TemplateName: req.TemplateName,
Status: models.EmailStatusSuppressed,
ErrorMessage: "recipient is suppressed",
+ Provider: ClassifyProvider(addr),
}
_ = s.emailRepo.Create(em)
}
@@ -587,6 +669,7 @@ func (s *Service) Send(ctx context.Context, userID, apiKeyID uint, workspaceID *
Sender: req.From,
Recipients: req.To,
Subject: req.Subject,
+ TemplateName: req.TemplateName,
HTMLBody: req.HTML,
TextBody: req.Text,
AttachmentsJSON: attachmentsJSON,
@@ -594,12 +677,21 @@ func (s *Service) Send(ctx context.Context, userID, apiKeyID uint, workspaceID *
ListUnsubscribeURL: req.ListUnsubscribeURL,
ListUnsubscribePost: req.ListUnsubscribePost,
Status: models.EmailStatusPending,
+ Provider: ClassifyRecipients(req.To),
}
if err := s.emailRepo.Create(em); err != nil {
return nil, fmt.Errorf("failed to store email: %w", err)
}
+ // Auto-attach an RFC 8058 one-click unsubscribe URL when the recipient is
+ // being added to a subscriber list and the caller did not supply their own.
+ if em.ListUnsubscribeURL == "" && req.List != "" && s.txUnsubGen != nil {
+ em.ListUnsubscribeURL = s.txUnsubGen.TxUnsubscribeURL(em.ID)
+ em.ListUnsubscribePost = true
+ _ = s.emailRepo.Update(em)
+ }
+
if s.devMode {
em.Status = models.EmailStatusSent
now := time.Now()
@@ -609,7 +701,7 @@ func (s *Service) Send(ctx context.Context, userID, apiKeyID uint, workspaceID *
s.onSent()
}
logger.Info("dev mode: email stored but not sent", "id", em.UUID)
- return &SendResponse{ID: em.UUID, Status: em.Status}, nil
+ return decorateWithList(&SendResponse{ID: em.UUID, Status: em.Status}, listResult), nil
}
// Scheduled sending
@@ -623,7 +715,7 @@ func (s *Service) Send(ctx context.Context, userID, apiKeyID uint, workspaceID *
_ = s.emailRepo.Update(em)
return nil, fmt.Errorf("failed to schedule email: %w", err)
}
- return &SendResponse{ID: em.UUID, Status: em.Status}, nil
+ return decorateWithList(&SendResponse{ID: em.UUID, Status: em.Status}, listResult), nil
}
// Asynchronous path: enqueue the email for background delivery
@@ -643,11 +735,122 @@ func (s *Service) Send(ctx context.Context, userID, apiKeyID uint, workspaceID *
s.onQueued()
}
logger.Debug("email enqueued for background delivery", "id", em.UUID)
- return &SendResponse{ID: em.UUID, Status: em.Status}, nil
+ return decorateWithList(&SendResponse{ID: em.UUID, Status: em.Status}, listResult), nil
}
// Synchronous fallback: send email directly (no worker configured)
- return s.sendSync(em, userID, workspaceID, req)
+ resp, err := s.sendSync(em, userID, workspaceID, req)
+ if err != nil {
+ return nil, err
+ }
+ return decorateWithList(resp, listResult), nil
+}
+
+// autoSubscribeResult captures the outcome of resolveAutoSubscribe for
+// stitching into the SendResponse.
+type autoSubscribeResult struct {
+ ListID *uint
+ SubscriberID *uint
+ ListCreated bool
+ MemberAdded bool
+ Skipped bool
+ SkippedReason string
+}
+
+func decorateWithList(resp *SendResponse, r *autoSubscribeResult) *SendResponse {
+ if resp == nil || r == nil {
+ return resp
+ }
+ resp.ListID = r.ListID
+ resp.SubscriberID = r.SubscriberID
+ resp.ListCreated = r.ListCreated
+ resp.MemberAdded = r.MemberAdded
+ return resp
+}
+
+func (s *Service) resolveAutoSubscribe(userID uint, workspaceID *uint, req *SendRequest) (*autoSubscribeResult, error) {
+ if s.listRepo == nil || s.subscriberRepo == nil {
+ return nil, nil
+ }
+ listName := strings.TrimSpace(req.List)
+ if listName == "" || len(req.To) != 1 {
+ return nil, nil
+ }
+ scope := repositories.ResourceScope{UserID: userID, WorkspaceID: workspaceID}
+
+ // Find-or-create list (static by default).
+ listCreated := false
+ list, err := s.listRepo.FindByNameForScope(scope, listName)
+ if err != nil {
+ if !errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, fmt.Errorf("list lookup: %w", err)
+ }
+ newList := &models.SubscriberList{
+ UserID: userID,
+ WorkspaceID: workspaceID,
+ Name: listName,
+ Type: models.SubscriberListTypeStatic,
+ }
+ if err := s.listRepo.Create(newList); err != nil {
+ return nil, fmt.Errorf("list create: %w", err)
+ }
+ list = newList
+ listCreated = true
+ }
+ if list.Type == models.SubscriberListTypeDynamic {
+ return &autoSubscribeResult{
+ ListID: &list.ID,
+ Skipped: true,
+ SkippedReason: "list_is_dynamic",
+ }, nil
+ }
+
+ recipient := req.To[0]
+ sub, err := s.subscriberRepo.FindByEmail(scope, recipient)
+ if err != nil {
+ if !errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, fmt.Errorf("subscriber lookup: %w", err)
+ }
+ now := time.Now()
+ newSub := &models.Subscriber{
+ UserID: userID,
+ WorkspaceID: workspaceID,
+ Email: strings.ToLower(strings.TrimSpace(recipient)),
+ Status: models.SubscriberStatusSubscribed,
+ SubscribedAt: &now,
+ }
+ if err := s.subscriberRepo.Create(newSub); err != nil {
+ return nil, fmt.Errorf("subscriber create: %w", err)
+ }
+ sub = newSub
+ }
+
+ result := &autoSubscribeResult{
+ ListID: &list.ID,
+ SubscriberID: &sub.ID,
+ ListCreated: listCreated,
+ }
+
+ if sub.Status != models.SubscriberStatusSubscribed {
+ result.Skipped = true
+ result.SkippedReason = "subscriber_" + string(sub.Status)
+ return result, nil
+ }
+ if s.listRepo.IsSuppressed(list.ID, sub.ID) {
+ result.Skipped = true
+ result.SkippedReason = "subscriber_unsubscribed_from_list"
+ return result, nil
+ }
+
+ // Add to list (idempotent; OnConflict DoNothing).
+ if err := s.listRepo.AddMember(&models.SubscriberListMember{
+ ListID: list.ID,
+ SubscriberID: sub.ID,
+ }); err != nil {
+ return nil, fmt.Errorf("list add member: %w", err)
+ }
+ result.MemberAdded = true
+ return result, nil
}
// sendSync performs synchronous SMTP delivery (used when no enqueuer is configured).
@@ -740,17 +943,17 @@ func (s *Service) SendWithTemplate(ctx context.Context, userID, apiKeyID uint, w
}
return s.Send(ctx, userID, apiKeyID, workspaceID, userEmail, &SendRequest{
- From: from,
- To: req.To,
- Subject: rendered.Subject,
- HTML: rendered.HTML,
- Text: rendered.Text,
- Attachments: req.Attachments,
+ From: from,
+ To: req.To,
+ Subject: rendered.Subject,
+ HTML: rendered.HTML,
+ Text: rendered.Text,
+ Attachments: req.Attachments,
+ TemplateName: tmpl.Name,
})
}
func (s *Service) SendBatch(ctx context.Context, userID, apiKeyID uint, workspaceID *uint, userEmail string, req *BatchRequest) (*BatchResponse, error) {
- // Enforce max batch size from plan or platform settings
maxBatch := 0
if s.planLimits != nil {
maxBatch = s.planLimits.EffectiveLimits(workspaceID).MaxBatchSize
@@ -804,8 +1007,10 @@ func (s *Service) SendBatch(ctx context.Context, userID, apiKeyID uint, workspac
Sender: from,
Recipients: []string{recipient.Email},
Subject: req.Template,
+ TemplateName: tmpl.Name,
Status: models.EmailStatusSuppressed,
ErrorMessage: "recipient is suppressed",
+ Provider: ClassifyProvider(recipient.Email),
}
_ = s.emailRepo.Create(em)
@@ -838,11 +1043,12 @@ func (s *Service) SendBatch(ctx context.Context, userID, apiKeyID uint, workspac
}
sendResp, err := s.Send(ctx, userID, apiKeyID, workspaceID, userEmail, &SendRequest{
- From: from,
- To: []string{recipient.Email},
- Subject: rendered.Subject,
- HTML: rendered.HTML,
- Text: rendered.Text,
+ From: from,
+ To: []string{recipient.Email},
+ Subject: rendered.Subject,
+ HTML: rendered.HTML,
+ Text: rendered.Text,
+ TemplateName: tmpl.Name,
})
if err != nil {
resp.Failed++
@@ -884,11 +1090,12 @@ func (s *Service) SendTestByTemplateID(ctx context.Context, userID uint, workspa
}
return s.Send(ctx, userID, 0, workspaceID, userEmail, &SendRequest{
- From: from,
- To: req.To,
- Subject: rendered.Subject,
- HTML: rendered.HTML,
- Text: rendered.Text,
+ From: from,
+ To: req.To,
+ Subject: rendered.Subject,
+ HTML: rendered.HTML,
+ Text: rendered.Text,
+ TemplateName: tmpl.Name,
})
}
diff --git a/internal/services/email/stamper.go b/internal/services/email/stamper.go
new file mode 100644
index 0000000..d21ac41
--- /dev/null
+++ b/internal/services/email/stamper.go
@@ -0,0 +1,101 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package email
+
+import (
+ "crypto/hmac"
+ "crypto/sha256"
+ "encoding/base64"
+ "fmt"
+ "strings"
+
+ "github.com/goposta/posta/internal/models"
+)
+
+// Stamper adds Posta-specific tracing headers and an HMAC origin signature to
+// outbound messages. It is intentionally sender-agnostic: it mutates a headers
+// map the caller then hands to the SMTP layer, so the same logic applies to
+// campaign mail and transactional/API mail without duplicating code.
+type Stamper struct {
+ AppName string
+ AppVersion string
+ SignKey []byte
+}
+
+// NewStamper builds a Stamper. A zero-length SignKey disables X-Posta-Signature
+func NewStamper(appName, appVersion string, signKey []byte) *Stamper {
+ return &Stamper{AppName: appName, AppVersion: appVersion, SignKey: signKey}
+}
+
+// StampCampaign adds campaign-specific headers. trackOpens
+func (s *Stamper) StampCampaign(headers map[string]string, em *models.Email, campaignID, campaignMessageID uint, trackOpens, trackClicks bool) {
+ s.base(headers)
+ headers["X-Posta-Campaign-ID"] = fmt.Sprintf("%d", campaignID)
+ headers["X-Posta-Message-ID"] = fmt.Sprintf("%d", campaignMessageID)
+ headers["X-Posta-Track-Opens"] = boolFlag(trackOpens)
+ headers["X-Posta-Track-Clicks"] = boolFlag(trackClicks)
+
+ headers["Precedence"] = "bulk"
+ headers["Auto-Submitted"] = "auto-generated"
+}
+
+// StampTransactional adds the minimum set of correlation headers for API
+func (s *Stamper) StampTransactional(headers map[string]string, em *models.Email) {
+ s.base(headers)
+ if em.UUID != "" {
+ headers["X-Posta-ID"] = em.UUID
+ }
+ if em.APIKeyID != nil && *em.APIKeyID > 0 {
+ headers["X-Posta-API-Key-ID"] = fmt.Sprintf("%d", *em.APIKeyID)
+ }
+}
+
+// Sign writes X-Posta-Signature over a canonical string of stable message
+func (s *Stamper) Sign(headers map[string]string, em *models.Email, to []string, subject string) {
+ if len(s.SignKey) == 0 || em == nil {
+ return
+ }
+ canonical := fmt.Sprintf("v1:%s:%s:%s:%s",
+ em.UUID,
+ em.Sender,
+ strings.Join(to, ","),
+ subject,
+ )
+ mac := hmac.New(sha256.New, s.SignKey)
+ mac.Write([]byte(canonical))
+ headers["X-Posta-Signature"] = "v1=" + base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
+}
+
+func (s *Stamper) base(headers map[string]string) {
+ name := s.AppName
+ if name == "" {
+ name = "Posta"
+ }
+ version := s.AppVersion
+ if version == "" {
+ version = "unknown"
+ }
+ headers["X-Mailer"] = fmt.Sprintf("%s/%s", name, version)
+}
+
+func boolFlag(b bool) string {
+ if b {
+ return "1"
+ }
+ return "0"
+}
diff --git a/internal/services/emailverify/service.go b/internal/services/emailverify/service.go
new file mode 100644
index 0000000..4834fb7
--- /dev/null
+++ b/internal/services/emailverify/service.go
@@ -0,0 +1,202 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// Package emailverify handles user email verification: token issuance,
+// delivery via notification templates, and redemption.
+package emailverify
+
+import (
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/goposta/posta/internal/models"
+ "github.com/goposta/posta/internal/services/notification"
+ "github.com/goposta/posta/internal/storage/repositories"
+)
+
+const (
+ tokenTTL = 24 * time.Hour
+ resendWindow = 1 * time.Hour
+ resendMaxInWindow = 5
+)
+
+// Service coordinates email verification issuance and redemption.
+type Service struct {
+ userRepo *repositories.UserRepository
+ verRepo *repositories.UserEmailVerificationRepository
+ notifier *notification.Service
+ appURL string
+ required bool
+}
+
+func NewService(
+ userRepo *repositories.UserRepository,
+ verRepo *repositories.UserEmailVerificationRepository,
+ notifier *notification.Service,
+ appURL string,
+ required bool,
+) *Service {
+ return &Service{
+ userRepo: userRepo,
+ verRepo: verRepo,
+ notifier: notifier,
+ appURL: strings.TrimRight(appURL, "/"),
+ required: required,
+ }
+}
+
+// Required returns whether verification is enforced. Returns false when
+// notifier is not configured, since we can't deliver the verification email.
+func (s *Service) Required() bool {
+ if s == nil {
+ return false
+ }
+ if s.notifier == nil || !s.notifier.IsConfigured() {
+ return false
+ }
+ return s.required
+}
+
+// IsUserVerified returns true when verification is not enforced or the user's
+// email has already been verified.
+func (s *Service) IsUserVerified(user *models.User) bool {
+ if !s.Required() {
+ return true
+ }
+ return user != nil && user.EmailVerifiedAt != nil
+}
+
+// IssueAndSend creates a new verification token, invalidates any prior pending
+// ones for this user, and sends the verification email. It is safe to call
+// even when the notifier isn't configured — it will simply no-op.
+func (s *Service) IssueAndSend(user *models.User) error {
+ if s == nil || s.notifier == nil || !s.notifier.IsConfigured() {
+ return nil
+ }
+ if user == nil {
+ return errors.New("emailverify: nil user")
+ }
+
+ if err := s.verRepo.InvalidatePending(user.ID); err != nil {
+ return fmt.Errorf("emailverify: invalidate pending: %w", err)
+ }
+
+ rawToken, hash, err := newToken()
+ if err != nil {
+ return err
+ }
+ v := &models.UserEmailVerification{
+ UserID: user.ID,
+ TokenHash: hash,
+ ExpiresAt: time.Now().Add(tokenTTL),
+ CreatedAt: time.Now(),
+ }
+ if err := s.verRepo.Create(v); err != nil {
+ return fmt.Errorf("emailverify: create token: %w", err)
+ }
+
+ verifyURL := fmt.Sprintf("%s/auth/verify-email?token=%s", s.appURL, rawToken)
+ return s.notifier.Send(user.Email, "Verify your email address", notification.TemplateEmailVerify, map[string]any{
+ "UserName": displayName(user),
+ "VerifyURL": verifyURL,
+ "ExpiryHours": int(tokenTTL.Hours()),
+ })
+}
+
+func (s *Service) Redeem(rawToken string) (*models.User, bool, error) {
+ if rawToken == "" {
+ return nil, false, errors.New("token is required")
+ }
+ hash := hashToken(rawToken)
+ v, err := s.verRepo.FindByTokenHash(hash)
+ if err != nil {
+ return nil, false, errors.New("invalid or expired token")
+ }
+ if v.UsedAt != nil {
+ return nil, false, errors.New("token has already been used")
+ }
+ if time.Now().After(v.ExpiresAt) {
+ return nil, false, errors.New("token has expired")
+ }
+
+ user, err := s.userRepo.FindByID(v.UserID)
+ if err != nil {
+ return nil, false, errors.New("user not found")
+ }
+
+ newlyVerified := user.EmailVerifiedAt == nil
+ if newlyVerified {
+ now := time.Now()
+ user.EmailVerifiedAt = &now
+ if err := s.userRepo.Update(user); err != nil {
+ return nil, false, fmt.Errorf("emailverify: mark user verified: %w", err)
+ }
+ }
+ if err := s.verRepo.MarkUsed(v.ID); err != nil {
+ return nil, false, fmt.Errorf("emailverify: mark used: %w", err)
+ }
+ return user, newlyVerified, nil
+}
+
+// CanResend returns an error when the user has hit the resend rate limit.
+func (s *Service) CanResend(userID uint) error {
+ count, err := s.verRepo.CountRecentByUser(userID, time.Now().Add(-resendWindow))
+ if err != nil {
+ return nil
+ }
+ if count >= resendMaxInWindow {
+ return fmt.Errorf("too many verification emails sent recently, try again later")
+ }
+ return nil
+}
+
+// MarkVerifiedNow marks a user's email as verified immediately (used for OAuth
+// signups and when the notifier isn't configured).
+func (s *Service) MarkVerifiedNow(user *models.User) error {
+ if user == nil || user.EmailVerifiedAt != nil {
+ return nil
+ }
+ now := time.Now()
+ user.EmailVerifiedAt = &now
+ return s.userRepo.Update(user)
+}
+
+func newToken() (raw, hashHex string, err error) {
+ buf := make([]byte, 32)
+ if _, err := rand.Read(buf); err != nil {
+ return "", "", err
+ }
+ raw = hex.EncodeToString(buf)
+ return raw, hashToken(raw), nil
+}
+
+func hashToken(raw string) string {
+ sum := sha256.Sum256([]byte(raw))
+ return hex.EncodeToString(sum[:])
+}
+
+func displayName(u *models.User) string {
+ if u.Name != "" {
+ return u.Name
+ }
+ return u.Email
+}
diff --git a/internal/services/inbound/parser.go b/internal/services/inbound/parser.go
new file mode 100644
index 0000000..14e3c8c
--- /dev/null
+++ b/internal/services/inbound/parser.go
@@ -0,0 +1,277 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package inbound
+
+import (
+ "bytes"
+ "encoding/base64"
+ "fmt"
+ "io"
+ "mime"
+ "mime/multipart"
+ "mime/quotedprintable"
+ "net/mail"
+ "strings"
+ "time"
+)
+
+const contentTypeTextPlain = "text/plain"
+
+// ParsedAttachment represents a decoded attachment extracted from the MIME tree.
+type ParsedAttachment struct {
+ Filename string
+ ContentType string
+ Content []byte
+ Size int64
+}
+
+// ParsedEmail is the normalized shape used throughout the inbound pipeline.
+// Both the SMTP path (via ParseRawEmail) and the webhook path (via NewParsedFromFields)
+// produce the same struct.
+type ParsedEmail struct {
+ MessageID string
+ From string
+ To []string
+ Cc []string
+ Subject string
+ Date time.Time
+ TextBody string
+ HTMLBody string
+ Headers map[string]string
+ Attachments []ParsedAttachment
+ Raw []byte
+}
+
+// ParseRawEmail parses a raw RFC 5322 message into a ParsedEmail.
+func ParseRawEmail(raw []byte) (*ParsedEmail, error) {
+ msg, err := mail.ReadMessage(bytes.NewReader(raw))
+ if err != nil {
+ return nil, fmt.Errorf("read message: %w", err)
+ }
+
+ p := &ParsedEmail{
+ Headers: make(map[string]string),
+ Raw: raw,
+ }
+
+ dec := &mime.WordDecoder{}
+ for k, vs := range msg.Header {
+ if len(vs) == 0 {
+ continue
+ }
+ v := vs[0]
+ if decoded, derr := dec.DecodeHeader(v); derr == nil {
+ v = decoded
+ }
+ p.Headers[k] = v
+ }
+
+ p.MessageID = strings.Trim(p.Headers["Message-Id"], "<>")
+ if p.MessageID == "" {
+ p.MessageID = strings.Trim(p.Headers["Message-ID"], "<>")
+ }
+ p.Subject = p.Headers["Subject"]
+ p.From = headerAddress(msg.Header.Get("From"))
+ p.To = headerAddressList(msg.Header.Get("To"))
+ p.Cc = headerAddressList(msg.Header.Get("Cc"))
+ if d, err := mail.ParseDate(msg.Header.Get("Date")); err == nil {
+ p.Date = d
+ } else {
+ p.Date = time.Now().UTC()
+ }
+
+ contentType := msg.Header.Get("Content-Type")
+ if contentType == "" {
+ contentType = contentTypeTextPlain
+ }
+ mediaType, params, err := mime.ParseMediaType(contentType)
+ if err != nil {
+ mediaType = contentTypeTextPlain
+ params = map[string]string{}
+ }
+
+ if strings.HasPrefix(mediaType, "multipart/") {
+ boundary := params["boundary"]
+ if boundary == "" {
+ return nil, fmt.Errorf("multipart with no boundary")
+ }
+ if err := walkMultipart(msg.Body, boundary, msg.Header.Get("Content-Transfer-Encoding"), p); err != nil {
+ return nil, err
+ }
+ } else {
+ body, err := readBody(msg.Body, msg.Header.Get("Content-Transfer-Encoding"), params["charset"])
+ if err != nil {
+ return nil, err
+ }
+ assignBody(p, mediaType, body)
+ }
+
+ return p, nil
+}
+
+// walkMultipart recursively descends the MIME tree, collecting text/html bodies
+// and attachments.
+func walkMultipart(r io.Reader, boundary string, _ string, p *ParsedEmail) error {
+ mr := multipart.NewReader(r, boundary)
+ for {
+ part, err := mr.NextPart()
+ if err == io.EOF {
+ return nil
+ }
+ if err != nil {
+ return fmt.Errorf("multipart read: %w", err)
+ }
+
+ partCT := part.Header.Get("Content-Type")
+ if partCT == "" {
+ partCT = contentTypeTextPlain
+ }
+ partMedia, partParams, perr := mime.ParseMediaType(partCT)
+ if perr != nil {
+ partMedia = "application/octet-stream"
+ partParams = map[string]string{}
+ }
+
+ disposition, dispParams, _ := mime.ParseMediaType(part.Header.Get("Content-Disposition"))
+ isAttachment := disposition == "attachment" || dispParams["filename"] != "" || partParams["name"] != ""
+
+ if strings.HasPrefix(partMedia, "multipart/") {
+ nestedBoundary := partParams["boundary"]
+ if nestedBoundary != "" {
+ if err := walkMultipart(part, nestedBoundary, part.Header.Get("Content-Transfer-Encoding"), p); err != nil {
+ _ = part.Close()
+ return err
+ }
+ }
+ _ = part.Close()
+ continue
+ }
+
+ enc := part.Header.Get("Content-Transfer-Encoding")
+
+ if isAttachment {
+ raw, rerr := io.ReadAll(part)
+ _ = part.Close()
+ if rerr != nil {
+ return fmt.Errorf("read attachment: %w", rerr)
+ }
+ decoded, derr := decodeTransfer(raw, enc)
+ if derr != nil {
+ return fmt.Errorf("decode attachment: %w", derr)
+ }
+ filename := decodeHeaderValue(dispParams["filename"])
+ if filename == "" {
+ filename = decodeHeaderValue(partParams["name"])
+ }
+ p.Attachments = append(p.Attachments, ParsedAttachment{
+ Filename: filename,
+ ContentType: partMedia,
+ Content: decoded,
+ Size: int64(len(decoded)),
+ })
+ continue
+ }
+
+ body, berr := readBody(part, enc, partParams["charset"])
+ _ = part.Close()
+ if berr != nil {
+ return berr
+ }
+ assignBody(p, partMedia, body)
+ }
+}
+
+func assignBody(p *ParsedEmail, mediaType, body string) {
+ switch {
+ case mediaType == contentTypeTextPlain && p.TextBody == "":
+ p.TextBody = body
+ case mediaType == "text/html" && p.HTMLBody == "":
+ p.HTMLBody = body
+ case mediaType == contentTypeTextPlain:
+ p.TextBody += "\n" + body
+ case mediaType == "text/html":
+ p.HTMLBody += "\n" + body
+ }
+}
+
+func readBody(r io.Reader, encoding, _ string) (string, error) {
+ raw, err := io.ReadAll(r)
+ if err != nil {
+ return "", fmt.Errorf("read body: %w", err)
+ }
+ decoded, err := decodeTransfer(raw, encoding)
+ if err != nil {
+ return "", err
+ }
+ return string(decoded), nil
+}
+
+func decodeTransfer(raw []byte, encoding string) ([]byte, error) {
+ switch strings.ToLower(strings.TrimSpace(encoding)) {
+ case "", "7bit", "8bit", "binary":
+ return raw, nil
+ case "base64":
+ clean := bytes.Map(func(r rune) rune {
+ if r == '\n' || r == '\r' || r == ' ' || r == '\t' {
+ return -1
+ }
+ return r
+ }, raw)
+ return base64.StdEncoding.DecodeString(string(clean))
+ case "quoted-printable":
+ return io.ReadAll(quotedprintable.NewReader(bytes.NewReader(raw)))
+ default:
+ return raw, nil
+ }
+}
+
+func decodeHeaderValue(v string) string {
+ if v == "" {
+ return ""
+ }
+ dec := &mime.WordDecoder{}
+ if out, err := dec.DecodeHeader(v); err == nil {
+ return out
+ }
+ return v
+}
+
+func headerAddress(v string) string {
+ if v == "" {
+ return ""
+ }
+ if addr, err := mail.ParseAddress(v); err == nil {
+ return addr.Address
+ }
+ return v
+}
+
+func headerAddressList(v string) []string {
+ if v == "" {
+ return nil
+ }
+ addrs, err := mail.ParseAddressList(v)
+ if err != nil {
+ return nil
+ }
+ out := make([]string, 0, len(addrs))
+ for _, a := range addrs {
+ out = append(out, a.Address)
+ }
+ return out
+}
diff --git a/internal/services/inbound/parser_test.go b/internal/services/inbound/parser_test.go
new file mode 100644
index 0000000..e531042
--- /dev/null
+++ b/internal/services/inbound/parser_test.go
@@ -0,0 +1,122 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ */
+
+package inbound
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestParsePlainText(t *testing.T) {
+ raw := "From: [email protected]\r\n" +
+ "To: [email protected]\r\n" +
+ "Subject: Hello\r\n" +
+ "Message-Id: <[email protected]>\r\n" +
+ "Content-Type: text/plain; charset=UTF-8\r\n" +
+ "\r\n" +
+ "Hi Bob.\r\n"
+
+ p, err := ParseRawEmail([]byte(raw))
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if p.From != "[email protected]" {
+ t.Errorf("From = %q, want [email protected]", p.From)
+ }
+ if len(p.To) != 1 || p.To[0] != "[email protected]" {
+ t.Errorf("To = %v, want [[email protected]]", p.To)
+ }
+ if p.MessageID != "[email protected]" {
+ t.Errorf("MessageID = %q, want [email protected]", p.MessageID)
+ }
+ if !strings.Contains(p.TextBody, "Hi Bob.") {
+ t.Errorf("TextBody missing body content: %q", p.TextBody)
+ }
+}
+
+func TestParseMultipartAlternative(t *testing.T) {
+ raw := "From: [email protected]\r\n" +
+ "To: [email protected]\r\n" +
+ "Subject: Multi\r\n" +
+ "Content-Type: multipart/alternative; boundary=\"xyz\"\r\n" +
+ "\r\n" +
+ "--xyz\r\n" +
+ "Content-Type: text/plain\r\n\r\n" +
+ "plain body\r\n" +
+ "--xyz\r\n" +
+ "Content-Type: text/html\r\n\r\n" +
+ "<p>html body</p>\r\n" +
+ "--xyz--\r\n"
+
+ p, err := ParseRawEmail([]byte(raw))
+ if err != nil {
+ t.Fatalf("parse: %v", err)
+ }
+ if !strings.Contains(p.TextBody, "plain body") {
+ t.Errorf("TextBody = %q", p.TextBody)
+ }
+ if !strings.Contains(p.HTMLBody, "html body") {
+ t.Errorf("HTMLBody = %q", p.HTMLBody)
+ }
+}
+
+func TestParseMultipartWithAttachment(t *testing.T) {
+ raw := "From: [email protected]\r\n" +
+ "To: [email protected]\r\n" +
+ "Subject: Attach\r\n" +
+ "Content-Type: multipart/mixed; boundary=\"B\"\r\n" +
+ "\r\n" +
+ "--B\r\n" +
+ "Content-Type: text/plain\r\n\r\n" +
+ "hi\r\n" +
+ "--B\r\n" +
+ "Content-Type: application/octet-stream; name=\"x.bin\"\r\n" +
+ "Content-Disposition: attachment; filename=\"x.bin\"\r\n" +
+ "Content-Transfer-Encoding: base64\r\n\r\n" +
+ "aGVsbG8=\r\n" +
+ "--B--\r\n"
+
+ p, err := ParseRawEmail([]byte(raw))
+ if err != nil {
+ t.Fatalf("parse: %v", err)
+ }
+ if len(p.Attachments) != 1 {
+ t.Fatalf("attachments = %d, want 1", len(p.Attachments))
+ }
+ att := p.Attachments[0]
+ if att.Filename != "x.bin" {
+ t.Errorf("filename = %q, want x.bin", att.Filename)
+ }
+ if string(att.Content) != "hello" {
+ t.Errorf("decoded content = %q, want hello", string(att.Content))
+ }
+}
+
+func TestParseQuotedPrintable(t *testing.T) {
+ raw := "From: [email protected]\r\n" +
+ "To: [email protected]\r\n" +
+ "Subject: =?UTF-8?Q?Caf=C3=A9?=\r\n" +
+ "Content-Type: text/plain; charset=UTF-8\r\n" +
+ "Content-Transfer-Encoding: quoted-printable\r\n" +
+ "\r\n" +
+ "Caf=C3=A9\r\n"
+
+ p, err := ParseRawEmail([]byte(raw))
+ if err != nil {
+ t.Fatalf("parse: %v", err)
+ }
+ if p.Subject != "Café" {
+ t.Errorf("Subject = %q, want Café", p.Subject)
+ }
+ if !strings.Contains(p.TextBody, "Café") {
+ t.Errorf("TextBody = %q, want to contain Café", p.TextBody)
+ }
+}
diff --git a/internal/services/inbound/ratelimit.go b/internal/services/inbound/ratelimit.go
new file mode 100644
index 0000000..097ded6
--- /dev/null
+++ b/internal/services/inbound/ratelimit.go
@@ -0,0 +1,84 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package inbound
+
+import (
+ "sync"
+ "time"
+)
+
+// IPRateLimiter is a minimal in-process rate limiter keyed by remote IP. It is
+// intentionally simple: a fixed-window counter with periodic eviction. Used to
+// shed abusive SMTP clients before they can incur parsing cost.
+type IPRateLimiter struct {
+ mu sync.Mutex
+ window time.Duration
+ maxHits int
+ hits map[string]*ipBucket
+ lastEvct time.Time
+}
+
+type ipBucket struct {
+ count int
+ reset time.Time
+}
+
+// NewIPRateLimiter returns a limiter that allows up to maxHits per window per IP.
+// maxHits ≤ 0 disables limiting.
+func NewIPRateLimiter(maxHits int, window time.Duration) *IPRateLimiter {
+ return &IPRateLimiter{
+ window: window,
+ maxHits: maxHits,
+ hits: make(map[string]*ipBucket),
+ }
+}
+
+// Allow returns true if the given IP is under its budget and increments the
+// counter. Disabled limiters always return true.
+func (l *IPRateLimiter) Allow(ip string) bool {
+ if l == nil || l.maxHits <= 0 {
+ return true
+ }
+ l.mu.Lock()
+ defer l.mu.Unlock()
+
+ now := time.Now()
+ if now.Sub(l.lastEvct) > l.window {
+ l.evictLocked(now)
+ l.lastEvct = now
+ }
+
+ b, ok := l.hits[ip]
+ if !ok || now.After(b.reset) {
+ l.hits[ip] = &ipBucket{count: 1, reset: now.Add(l.window)}
+ return true
+ }
+ if b.count >= l.maxHits {
+ return false
+ }
+ b.count++
+ return true
+}
+
+func (l *IPRateLimiter) evictLocked(now time.Time) {
+ for k, b := range l.hits {
+ if now.After(b.reset) {
+ delete(l.hits, k)
+ }
+ }
+}
diff --git a/internal/services/inbound/ratelimit_test.go b/internal/services/inbound/ratelimit_test.go
new file mode 100644
index 0000000..c0f629d
--- /dev/null
+++ b/internal/services/inbound/ratelimit_test.go
@@ -0,0 +1,55 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ */
+
+package inbound
+
+import (
+ "testing"
+ "time"
+)
+
+func TestRateLimiterDisabled(t *testing.T) {
+ l := NewIPRateLimiter(0, time.Second)
+ for i := 0; i < 100; i++ {
+ if !l.Allow("1.2.3.4") {
+ t.Fatalf("disabled limiter denied request #%d", i)
+ }
+ }
+}
+
+func TestRateLimiterAllowsThenDenies(t *testing.T) {
+ l := NewIPRateLimiter(3, time.Second)
+ for i := 0; i < 3; i++ {
+ if !l.Allow("1.2.3.4") {
+ t.Fatalf("denied request #%d within budget", i)
+ }
+ }
+ if l.Allow("1.2.3.4") {
+ t.Fatalf("expected deny after exhausting budget")
+ }
+ // different IP still allowed
+ if !l.Allow("5.6.7.8") {
+ t.Fatalf("unrelated IP denied")
+ }
+}
+
+func TestRateLimiterResetsAfterWindow(t *testing.T) {
+ l := NewIPRateLimiter(1, 30*time.Millisecond)
+ if !l.Allow("x") {
+ t.Fatal("first should succeed")
+ }
+ if l.Allow("x") {
+ t.Fatal("second should deny")
+ }
+ time.Sleep(60 * time.Millisecond)
+ if !l.Allow("x") {
+ t.Fatal("should reset after window")
+ }
+}
diff --git a/internal/services/inbound/service.go b/internal/services/inbound/service.go
new file mode 100644
index 0000000..7b06385
--- /dev/null
+++ b/internal/services/inbound/service.go
@@ -0,0 +1,374 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package inbound
+
+import (
+ "bytes"
+ "context"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/goposta/posta/internal/models"
+ "github.com/goposta/posta/internal/services/eventbus"
+ "github.com/goposta/posta/internal/storage/blob"
+ "github.com/goposta/posta/internal/storage/repositories"
+ "github.com/jkaninda/logger"
+ "gorm.io/gorm"
+)
+
+var (
+ // ErrUnverifiedDomain is returned when none of the recipient domains match an
+ // ownership-verified domain. Maps to SMTP 550.
+ ErrUnverifiedDomain = errors.New("recipient domain is not verified")
+ // ErrSizeExceeded is returned when the raw message exceeds the configured limit.
+ // Maps to SMTP 552.
+ ErrSizeExceeded = errors.New("message size exceeds limit")
+ // ErrAttachmentTooLarge is returned when a single attachment is larger than
+ // the configured per-attachment limit.
+ ErrAttachmentTooLarge = errors.New("attachment exceeds per-attachment size limit")
+ // ErrDuplicate is returned when a message with the same Message-ID already
+ // exists for the resolved user. Callers should treat this as success (idempotent).
+ ErrDuplicate = errors.New("duplicate message-id")
+ // ErrSenderSuppressed is returned when the sender is on the recipient's
+ // suppression list.
+ ErrSenderSuppressed = errors.New("sender is suppressed")
+)
+
+// Enqueuer enqueues inbound-processing tasks. Satisfied by worker.Producer.
+type Enqueuer interface {
+ EnqueueInboundProcess(inboundEmailID uint) error
+}
+
+type Service struct {
+ repo *repositories.InboundEmailRepository
+ domainRepo *repositories.DomainRepository
+ suppressionRepo *repositories.SuppressionRepository
+ blobStore blob.Store
+ producer Enqueuer
+ bus *eventbus.EventBus
+ maxMsgSize int64
+ maxAttachSize int64
+ onReceived func(source models.InboundSource)
+ onRejected func(reason string)
+ onBytes func(int64)
+ onIngestMs func(float64)
+}
+
+// Config holds runtime configuration for the inbound service.
+type Config struct {
+ MaxMessageSize int64
+ MaxAttachmentSize int64
+}
+
+func NewService(
+ repo *repositories.InboundEmailRepository,
+ domainRepo *repositories.DomainRepository,
+ suppressionRepo *repositories.SuppressionRepository,
+ cfg Config,
+) *Service {
+ return &Service{
+ repo: repo,
+ domainRepo: domainRepo,
+ suppressionRepo: suppressionRepo,
+ maxMsgSize: cfg.MaxMessageSize,
+ maxAttachSize: cfg.MaxAttachmentSize,
+ }
+}
+
+// SetBlobStore configures the blob store for attachment persistence.
+// When nil, attachment content is stored inline (base64) on the InboundEmail record.
+func (s *Service) SetBlobStore(bs blob.Store) { s.blobStore = bs }
+
+// SetEnqueuer configures the worker-task enqueuer.
+func (s *Service) SetEnqueuer(eq Enqueuer) { s.producer = eq }
+
+// SetEventBus configures the event bus used to publish inbound.received events.
+func (s *Service) SetEventBus(b *eventbus.EventBus) { s.bus = b }
+
+// OnReceived sets a callback invoked after each successfully ingested inbound message.
+func (s *Service) OnReceived(fn func(source models.InboundSource)) { s.onReceived = fn }
+
+// OnRejected sets a callback invoked after each rejected inbound message.
+func (s *Service) OnRejected(fn func(reason string)) { s.onRejected = fn }
+
+// OnBytes sets a callback invoked with the total inbound byte count.
+func (s *Service) OnBytes(fn func(int64)) { s.onBytes = fn }
+
+// OnIngestDuration sets a callback invoked with ingestion duration in seconds.
+func (s *Service) OnIngestDuration(fn func(float64)) { s.onIngestMs = fn }
+
+// computeDedupHash derives a stable hash for messages without a Message-ID, used
+// on the webhook path to reject near-duplicate retries.
+func computeDedupHash(sender string, recipients []string, subject string, size int64) string {
+ return "fh-" + fmt.Sprintf("%s|%s|%s|%d", strings.ToLower(sender), strings.ToLower(strings.Join(recipients, ",")), subject, size)
+}
+
+// Ingest is the single entry point for both SMTP and webhook paths.
+// It resolves a verified tenant domain from the recipient list, persists the
+// record (and attachments to blob storage when configured), and enqueues an
+// async task to dispatch the email.inbound webhook.
+func (s *Service) Ingest(ctx context.Context, p *ParsedEmail, source models.InboundSource) (*models.InboundEmail, error) {
+ start := time.Now()
+ defer func() {
+ if s.onIngestMs != nil {
+ s.onIngestMs(time.Since(start).Seconds())
+ }
+ }()
+
+ if s.maxMsgSize > 0 && int64(len(p.Raw)) > s.maxMsgSize {
+ s.rejected("size_exceeded")
+ return nil, ErrSizeExceeded
+ }
+
+ domain, recipient, err := s.resolveDomain(p.To)
+ if err != nil {
+ s.rejected("unverified_domain")
+ return nil, err
+ }
+
+ // Suppression check — skip delivery (record as rejected) if sender is suppressed.
+ if s.suppressionRepo != nil && p.From != "" {
+ scope := repositories.ResourceScope{UserID: domain.UserID, WorkspaceID: domain.WorkspaceID}
+ if yes, _ := s.suppressionRepo.IsSuppressed(scope, strings.ToLower(p.From)); yes {
+ s.rejected("sender_suppressed")
+ return s.persistRejected(p, domain, source, "sender is on suppression list"), ErrSenderSuppressed
+ }
+ }
+
+ // Idempotency: first by Message-ID when present, else by content-hash fallback.
+ if p.MessageID != "" {
+ if existing, err := s.repo.FindByMessageID(domain.UserID, p.MessageID); err == nil && existing != nil {
+ return existing, ErrDuplicate
+ } else if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
+ logger.Warn("failed to check message-id dedup", "error", err)
+ }
+ }
+
+ recipients := p.To
+ if len(recipients) == 0 && recipient != "" {
+ recipients = []string{recipient}
+ }
+
+ var dedupHash string
+ if p.MessageID == "" {
+ dedupHash = computeDedupHash(p.From, recipients, p.Subject, int64(len(p.Raw)))
+ if existing, err := s.repo.FindByDedupHash(domain.UserID, dedupHash); err == nil && existing != nil {
+ return existing, ErrDuplicate
+ } else if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
+ logger.Warn("failed to check dedup hash", "error", err)
+ }
+ }
+
+ headersJSON, _ := json.Marshal(p.Headers)
+
+ rec := &models.InboundEmail{
+ UserID: domain.UserID,
+ WorkspaceID: domain.WorkspaceID,
+ DomainID: domain.ID,
+ MessageID: p.MessageID,
+ DedupHash: dedupHash,
+ Sender: p.From,
+ Recipients: recipients,
+ Subject: p.Subject,
+ TextBody: p.TextBody,
+ HTMLBody: p.HTMLBody,
+ HeadersJSON: string(headersJSON),
+ Size: int64(len(p.Raw)),
+ Status: models.InboundStatusReceived,
+ Source: source,
+ ReceivedAt: time.Now().UTC(),
+ }
+
+ if err := s.repo.Create(rec); err != nil {
+ return nil, fmt.Errorf("persist inbound email: %w", err)
+ }
+
+ // Persist raw .eml bytes (best effort) so operators can export later.
+ if s.blobStore != nil && len(p.Raw) > 0 {
+ rawKey := fmt.Sprintf("inbound/%s/raw.eml", rec.UUID)
+ if err := s.blobStore.Put(ctx, rawKey, bytes.NewReader(p.Raw), "message/rfc822"); err == nil {
+ rec.RawStorageKey = rawKey
+ _ = s.repo.Update(rec)
+ } else {
+ logger.Warn("failed to store raw inbound eml", "uuid", rec.UUID, "error", err)
+ }
+ }
+
+ attachments, uploadedKeys, err := s.persistAttachments(ctx, rec.UUID, p.Attachments)
+ if err != nil {
+ // Best-effort cleanup of partial uploads so blob storage doesn't leak.
+ if s.blobStore != nil {
+ for _, k := range uploadedKeys {
+ _ = s.blobStore.Delete(ctx, k)
+ }
+ if rec.RawStorageKey != "" {
+ _ = s.blobStore.Delete(ctx, rec.RawStorageKey)
+ rec.RawStorageKey = ""
+ }
+ }
+ rec.Status = models.InboundStatusFailed
+ rec.ErrorMessage = err.Error()
+ _ = s.repo.Update(rec)
+ s.rejected("attachment_error")
+ return rec, err
+ }
+ if len(attachments) > 0 {
+ if data, mErr := json.Marshal(attachments); mErr == nil {
+ rec.AttachmentsJSON = string(data)
+ _ = s.repo.Update(rec)
+ }
+ }
+
+ if s.producer != nil {
+ if err := s.producer.EnqueueInboundProcess(rec.ID); err != nil {
+ logger.Error("failed to enqueue inbound:process", "inbound_id", rec.ID, "error", err)
+ }
+ }
+
+ if s.bus != nil {
+ actor := rec.UserID
+ s.bus.PublishSimple(
+ models.EventCategoryEmail,
+ "email.inbound.received",
+ &actor,
+ "",
+ "",
+ fmt.Sprintf("Inbound email received from %s", rec.Sender),
+ map[string]any{
+ "inbound_id": rec.UUID,
+ "sender": rec.Sender,
+ "recipients": []string(rec.Recipients),
+ "subject": rec.Subject,
+ "source": string(rec.Source),
+ "size": rec.Size,
+ "workspace_id": rec.WorkspaceID,
+ },
+ )
+ }
+
+ if s.onReceived != nil {
+ s.onReceived(source)
+ }
+ if s.onBytes != nil {
+ s.onBytes(rec.Size)
+ }
+ return rec, nil
+}
+
+// resolveDomain walks the recipient list and returns the first ownership-verified
+// tenant domain that matches. Returns ErrUnverifiedDomain if none match.
+func (s *Service) resolveDomain(recipients []string) (*models.Domain, string, error) {
+ for _, r := range recipients {
+ addr := strings.ToLower(strings.TrimSpace(r))
+ at := strings.LastIndex(addr, "@")
+ if at < 0 || at == len(addr)-1 {
+ continue
+ }
+ d, err := s.domainRepo.FindVerifiedByName(addr[at+1:])
+ if err != nil {
+ continue
+ }
+ return d, addr, nil
+ }
+ return nil, "", ErrUnverifiedDomain
+}
+
+// persistAttachments stores attachment content in blob storage (or inline when
+// no store is configured). Returns attachment metadata plus the list of blob keys
+// that were successfully uploaded — the caller uses the keys to clean up on
+// later failure.
+func (s *Service) persistAttachments(ctx context.Context, uuid string, atts []ParsedAttachment) ([]models.InboundAttachmentMeta, []string, error) {
+ if len(atts) == 0 {
+ return nil, nil, nil
+ }
+ out := make([]models.InboundAttachmentMeta, 0, len(atts))
+ keys := make([]string, 0, len(atts))
+ for i, a := range atts {
+ if s.maxAttachSize > 0 && a.Size > s.maxAttachSize {
+ return nil, keys, fmt.Errorf("%w: %q (%d bytes)", ErrAttachmentTooLarge, a.Filename, a.Size)
+ }
+ meta := models.InboundAttachmentMeta{
+ Filename: a.Filename,
+ ContentType: a.ContentType,
+ Size: a.Size,
+ }
+ if s.blobStore != nil {
+ key := fmt.Sprintf("inbound/%s/%d_%s", uuid, i, sanitizeFilename(a.Filename))
+ if err := s.blobStore.Put(ctx, key, bytes.NewReader(a.Content), a.ContentType); err != nil {
+ return nil, keys, fmt.Errorf("store attachment %q: %w", a.Filename, err)
+ }
+ meta.StorageKey = key
+ keys = append(keys, key)
+ } else {
+ meta.Content = base64.StdEncoding.EncodeToString(a.Content)
+ }
+ out = append(out, meta)
+ }
+ return out, keys, nil
+}
+
+func (s *Service) persistRejected(p *ParsedEmail, domain *models.Domain, source models.InboundSource, reason string) *models.InboundEmail {
+ rec := &models.InboundEmail{
+ UserID: domain.UserID,
+ WorkspaceID: domain.WorkspaceID,
+ DomainID: domain.ID,
+ MessageID: p.MessageID,
+ Sender: p.From,
+ Recipients: p.To,
+ Subject: p.Subject,
+ Size: int64(len(p.Raw)),
+ Status: models.InboundStatusRejected,
+ Source: source,
+ ReceivedAt: time.Now().UTC(),
+ ErrorMessage: reason,
+ }
+ if err := s.repo.Create(rec); err != nil {
+ logger.Error("failed to persist rejected inbound email", "error", err)
+ return nil
+ }
+ return rec
+}
+
+func (s *Service) rejected(reason string) {
+ if s.onRejected != nil {
+ s.onRejected(reason)
+ }
+}
+
+const defaultAttachmentName = "attachment"
+
+func sanitizeFilename(name string) string {
+ if name == "" {
+ return defaultAttachmentName
+ }
+ out := strings.Map(func(r rune) rune {
+ switch {
+ case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '-', r == '_', r == '.':
+ return r
+ }
+ return '_'
+ }, name)
+ if out == "" {
+ return defaultAttachmentName
+ }
+ return out
+}
diff --git a/internal/services/inbound/smtp_server.go b/internal/services/inbound/smtp_server.go
new file mode 100644
index 0000000..09ed3cc
--- /dev/null
+++ b/internal/services/inbound/smtp_server.go
@@ -0,0 +1,210 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package inbound
+
+import (
+ "context"
+ "crypto/tls"
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "net/mail"
+ "strings"
+ "time"
+
+ "github.com/emersion/go-smtp"
+ "github.com/goposta/posta/internal/models"
+ "github.com/goposta/posta/internal/storage/repositories"
+ "github.com/jkaninda/logger"
+)
+
+// SMTPConfig holds configuration for the built-in SMTP receiver.
+type SMTPConfig struct {
+ Host string
+ Port int
+ Hostname string
+ MaxMessageSize int64
+ TLSMode string // "none" or "starttls"
+ TLSCertFile string
+ TLSKeyFile string
+}
+
+// Backend implements smtp.Backend for go-smtp.
+type Backend struct {
+ svc *Service
+ domainRepo *repositories.DomainRepository
+ maxMessageSize int64
+ limiter *IPRateLimiter
+}
+
+func NewBackend(svc *Service, domainRepo *repositories.DomainRepository, maxMessageSize int64) *Backend {
+ return &Backend{svc: svc, domainRepo: domainRepo, maxMessageSize: maxMessageSize}
+}
+
+// SetRateLimiter enables per-IP rate limiting for new SMTP sessions.
+func (b *Backend) SetRateLimiter(l *IPRateLimiter) { b.limiter = l }
+
+func (b *Backend) NewSession(c *smtp.Conn) (smtp.Session, error) {
+ remote := c.Conn().RemoteAddr().String()
+ if b.limiter != nil {
+ ip := remote
+ if host, _, err := net.SplitHostPort(remote); err == nil {
+ ip = host
+ }
+ if !b.limiter.Allow(ip) {
+ logger.Warn("smtp: rate-limited remote", "ip", ip)
+ return nil, &smtp.SMTPError{Code: 421, EnhancedCode: smtp.EnhancedCode{4, 7, 0}, Message: "rate limit exceeded"}
+ }
+ }
+ return &session{
+ backend: b,
+ remote: remote,
+ }, nil
+}
+
+type session struct {
+ backend *Backend
+ from string
+ to []string
+ remote string
+}
+
+func (s *session) Reset() {
+ s.from = ""
+ s.to = nil
+}
+
+func (s *session) Logout() error { return nil }
+
+func (s *session) Mail(from string, _ *smtp.MailOptions) error {
+ if from != "" {
+ if addr, err := mail.ParseAddress(from); err == nil {
+ s.from = addr.Address
+ } else {
+ s.from = from
+ }
+ }
+ return nil
+}
+
+// Rcpt rejects recipients whose domain is not ownership-verified, saving bandwidth
+// by failing before DATA.
+func (s *session) Rcpt(to string, _ *smtp.RcptOptions) error {
+ addr := to
+ if parsed, err := mail.ParseAddress(to); err == nil {
+ addr = parsed.Address
+ }
+ domain := extractDomain(addr)
+ if domain == "" {
+ return &smtp.SMTPError{Code: 550, EnhancedCode: smtp.EnhancedCode{5, 1, 3}, Message: "malformed recipient"}
+ }
+ if _, err := s.backend.domainRepo.FindVerifiedByName(domain); err != nil {
+ return &smtp.SMTPError{Code: 550, EnhancedCode: smtp.EnhancedCode{5, 1, 1}, Message: "relay not permitted"}
+ }
+ s.to = append(s.to, addr)
+ return nil
+}
+
+// Data reads the raw message (bounded by MaxMessageSize), parses it, and delegates
+// to the service. Maps typed service errors back to SMTP status codes.
+func (s *session) Data(r io.Reader) error {
+ limit := s.backend.maxMessageSize
+ if limit <= 0 {
+ limit = 26214400
+ }
+ // +1 to detect overflow.
+ lr := &io.LimitedReader{R: r, N: limit + 1}
+ raw, err := io.ReadAll(lr)
+ if err != nil {
+ return &smtp.SMTPError{Code: 451, EnhancedCode: smtp.EnhancedCode{4, 3, 0}, Message: "read error"}
+ }
+ if int64(len(raw)) > limit {
+ return &smtp.SMTPError{Code: 552, EnhancedCode: smtp.EnhancedCode{5, 3, 4}, Message: "message size exceeds limit"}
+ }
+
+ parsed, err := ParseRawEmail(raw)
+ if err != nil {
+ logger.Warn("smtp parse error", "remote", s.remote, "error", err)
+ return &smtp.SMTPError{Code: 550, EnhancedCode: smtp.EnhancedCode{5, 6, 0}, Message: "malformed message"}
+ }
+ if parsed.From == "" && s.from != "" {
+ parsed.From = s.from
+ }
+ if len(parsed.To) == 0 {
+ parsed.To = append([]string(nil), s.to...)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+
+ _, ierr := s.backend.svc.Ingest(ctx, parsed, models.InboundSourceSMTP)
+ switch {
+ case ierr == nil, errors.Is(ierr, ErrDuplicate):
+ return nil
+ case errors.Is(ierr, ErrUnverifiedDomain):
+ return &smtp.SMTPError{Code: 550, EnhancedCode: smtp.EnhancedCode{5, 1, 1}, Message: "relay not permitted"}
+ case errors.Is(ierr, ErrSizeExceeded), errors.Is(ierr, ErrAttachmentTooLarge):
+ return &smtp.SMTPError{Code: 552, EnhancedCode: smtp.EnhancedCode{5, 3, 4}, Message: "message too large"}
+ case errors.Is(ierr, ErrSenderSuppressed):
+ return &smtp.SMTPError{Code: 550, EnhancedCode: smtp.EnhancedCode{5, 7, 1}, Message: "sender suppressed"}
+ default:
+ logger.Error("inbound ingest failed", "remote", s.remote, "error", ierr)
+ return &smtp.SMTPError{Code: 451, EnhancedCode: smtp.EnhancedCode{4, 3, 0}, Message: "temporary failure"}
+ }
+}
+
+// NewSMTPServer builds a configured *smtp.Server. When cfg.TLSMode == "starttls",
+// STARTTLS is automatically advertised by go-smtp once TLSConfig is set.
+func NewSMTPServer(backend *Backend, cfg SMTPConfig) (*smtp.Server, error) {
+ srv := smtp.NewServer(backend)
+ srv.Addr = fmt.Sprintf("%s:%d", cfg.Host, cfg.Port)
+ srv.Domain = cfg.Hostname
+ srv.ReadTimeout = 30 * time.Second
+ srv.WriteTimeout = 30 * time.Second
+ srv.MaxMessageBytes = cfg.MaxMessageSize
+ srv.MaxRecipients = 50
+ srv.AllowInsecureAuth = true
+ srv.EnableSMTPUTF8 = true
+
+ switch strings.ToLower(strings.TrimSpace(cfg.TLSMode)) {
+ case "", "none":
+ // plain SMTP; STARTTLS not advertised
+ case "starttls":
+ cert, err := tls.LoadX509KeyPair(cfg.TLSCertFile, cfg.TLSKeyFile)
+ if err != nil {
+ return nil, fmt.Errorf("load inbound TLS cert: %w", err)
+ }
+ srv.TLSConfig = &tls.Config{
+ Certificates: []tls.Certificate{cert},
+ ServerName: cfg.Hostname,
+ MinVersion: tls.VersionTLS12,
+ }
+ default:
+ return nil, fmt.Errorf("unsupported inbound TLS mode %q (use none or starttls)", cfg.TLSMode)
+ }
+ return srv, nil
+}
+
+func extractDomain(addr string) string {
+ at := strings.LastIndex(addr, "@")
+ if at < 0 || at == len(addr)-1 {
+ return ""
+ }
+ return strings.ToLower(addr[at+1:])
+}
diff --git a/internal/services/notification/service.go b/internal/services/notification/service.go
index faa61db..85bcddf 100644
--- a/internal/services/notification/service.go
+++ b/internal/services/notification/service.go
@@ -43,6 +43,7 @@ const (
TemplateAPIKeyExpiry = "api_key_expiry"
TemplateBounceAlert = "bounce_alert"
TemplateRoleChanged = "role_changed"
+ TemplateEmailVerify = "email_verification"
)
// Service sends platform notification emails via the system SMTP server.
@@ -86,6 +87,7 @@ func (s *Service) loadTemplates() {
TemplateAPIKeyExpiry,
TemplateBounceAlert,
TemplateRoleChanged,
+ TemplateEmailVerify,
}
for _, name := range names {
tmpl := template.Must(template.ParseFS(templateFS,
@@ -149,6 +151,11 @@ func (s *Service) SendToUser(userID uint, subject, templateName string, data map
return nil
}
+ if templateName != TemplateEmailVerify && user.EmailVerifiedAt == nil {
+ logger.Debug("notification service: skipping send to unverified user", "user_id", userID, "template", templateName)
+ return nil
+ }
+
to := settings.NotificationEmail
if to == "" {
to = user.Email
diff --git a/internal/services/notification/templates/email_verification.tmpl b/internal/services/notification/templates/email_verification.tmpl
new file mode 100644
index 0000000..6d28745
--- /dev/null
+++ b/internal/services/notification/templates/email_verification.tmpl
@@ -0,0 +1,14 @@
+{{ define "content" }}
+<h2>Verify your email address</h2>
+<p>Hi {{ .UserName }},</p>
+<p>To finish setting up your {{ .AppName }} account, please confirm this is your email address by clicking the button below.</p>
+
+<p style="text-align: center; margin: 32px 0;">
+ <a href="{{ .VerifyURL }}" class="btn">Verify email</a>
+</p>
+
+<p class="muted">Or paste this link into your browser:<br>
+<a href="{{ .VerifyURL }}">{{ .VerifyURL }}</a></p>
+
+<p class="muted">This link expires in {{ .ExpiryHours }} hours. If you didn't create an account, you can safely ignore this email.</p>
+{{ end }}
diff --git a/internal/services/tracking/tracking.go b/internal/services/tracking/tracking.go
index a8a833b..e606afb 100644
--- a/internal/services/tracking/tracking.go
+++ b/internal/services/tracking/tracking.go
@@ -42,7 +42,8 @@ func NewService(repo *repositories.TrackingRepository, baseURL string, hmacKey [
return &Service{repo: repo, baseURL: strings.TrimRight(baseURL, "/"), hmacKey: hmacKey}
}
-var linkRegex = regexp.MustCompile(`href\s*=\s*["'](https?://[^"']+)["']`)
+// (?i) makes the href match case-insensitive so HREF="…" still matches.
+var linkRegex = regexp.MustCompile(`(?i)href\s*=\s*["'](https?://[^"']+)["']`)
// ProcessHTML rewrites links for click tracking and injects the open tracking pixel.
func (s *Service) ProcessHTML(html string, campaignID uint, messageID uint) string {
@@ -50,17 +51,25 @@ func (s *Service) ProcessHTML(html string, campaignID uint, messageID uint) stri
return html
}
+ trackingPrefix := s.baseURL + "/t/"
+
// Rewrite links for click tracking
html = linkRegex.ReplaceAllStringFunc(html, func(match string) string {
- // Extract URL from href="..."
sub := linkRegex.FindStringSubmatch(match)
if len(sub) < 2 {
return match
}
originalURL := sub[1]
- // Skip unsubscribe links and tracking URLs
- if strings.Contains(originalURL, "/t/") {
+ // Skip URLs that are already our own tracking endpoints. The previous
+ // `Contains("/t/")` check accidentally skipped any legitimate link
+ // whose path segment contained "/t/" (e.g. blog posts).
+ if strings.HasPrefix(originalURL, trackingPrefix) {
+ return match
+ }
+ // Skip non-http schemes that slipped through the regex bound (defense-in-depth).
+ lower := strings.ToLower(originalURL)
+ if strings.HasPrefix(lower, "mailto:") || strings.HasPrefix(lower, "tel:") {
return match
}
@@ -70,12 +79,14 @@ func (s *Service) ProcessHTML(html string, campaignID uint, messageID uint) stri
return match
}
- trackedURL := fmt.Sprintf("%s/t/c/%d/%s", s.baseURL, messageID, hash)
+ trackedURL := s.ClickURL(messageID, hash)
return strings.Replace(match, originalURL, trackedURL, 1)
})
- // Inject open tracking pixel before </body>
- pixel := fmt.Sprintf(`<img src="%s/t/o/%d.png" width="1" height="1" alt="" style="display:none" />`, s.baseURL, messageID)
+ // Inject open tracking pixel before </body>. The URL is HMAC-signed so
+ // metrics can't be inflated by a third party hitting the predictable
+ // /t/o/<msg_id> path.
+ pixel := fmt.Sprintf(`<img src="%s" width="1" height="1" alt="" style="display:none" />`, s.OpenURL(messageID))
if strings.Contains(html, "</body>") {
html = strings.Replace(html, "</body>", pixel+"</body>", 1)
} else {
@@ -85,6 +96,38 @@ func (s *Service) ProcessHTML(html string, campaignID uint, messageID uint) stri
return html
}
+// OpenURL builds a signed open-tracking pixel URL.
+func (s *Service) OpenURL(messageID uint) string {
+ return fmt.Sprintf("%s/t/o/%d.gif?sig=%s", s.baseURL, messageID, s.signOpen(messageID))
+}
+
+// ClickURL builds a signed click-tracking redirect URL.
+func (s *Service) ClickURL(messageID uint, hash string) string {
+ return fmt.Sprintf("%s/t/c/%d/%s?sig=%s", s.baseURL, messageID, hash, s.signClick(messageID, hash))
+}
+
+// VerifyOpenSig checks an open-tracking signature.
+func (s *Service) VerifyOpenSig(messageID uint, sig string) bool {
+ return hmac.Equal([]byte(sig), []byte(s.signOpen(messageID)))
+}
+
+// VerifyClickSig checks a click-tracking signature.
+func (s *Service) VerifyClickSig(messageID uint, hash, sig string) bool {
+ return hmac.Equal([]byte(sig), []byte(s.signClick(messageID, hash)))
+}
+
+func (s *Service) signOpen(messageID uint) string {
+ mac := hmac.New(sha256.New, s.hmacKey)
+ _, _ = fmt.Fprintf(mac, "open:%d", messageID)
+ return base64.RawURLEncoding.EncodeToString(mac.Sum(nil)[:16])
+}
+
+func (s *Service) signClick(messageID uint, hash string) string {
+ mac := hmac.New(sha256.New, s.hmacKey)
+ _, _ = fmt.Fprintf(mac, "click:%d:%s", messageID, hash)
+ return base64.RawURLEncoding.EncodeToString(mac.Sum(nil)[:16])
+}
+
// SignUnsubscribeToken creates an HMAC-signed token encoding the message ID.
func (s *Service) SignUnsubscribeToken(messageID uint) string {
payload := strconv.FormatUint(uint64(messageID), 10)
@@ -125,6 +168,50 @@ func (s *Service) UnsubscribeURL(messageID uint) string {
return fmt.Sprintf("%s/t/u/%s", s.baseURL, s.SignUnsubscribeToken(messageID))
}
+// SignTxUnsubscribeToken creates an HMAC-signed token encoding a transactional
+// email ID. The "tx:" prefix distinguishes it from campaign-message tokens so
+// the two token kinds can't be confused or replayed against the wrong handler.
+func (s *Service) SignTxUnsubscribeToken(emailID uint) string {
+ payload := "tx:" + strconv.FormatUint(uint64(emailID), 10)
+ mac := hmac.New(sha256.New, s.hmacKey)
+ mac.Write([]byte(payload))
+ sig := base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
+ return base64.RawURLEncoding.EncodeToString([]byte(payload)) + "." + sig
+}
+
+// VerifyTxUnsubscribeToken verifies a transactional unsubscribe
+func (s *Service) VerifyTxUnsubscribeToken(token string) (uint, error) {
+ parts := strings.SplitN(token, ".", 2)
+ if len(parts) != 2 {
+ return 0, errors.New("invalid token format")
+ }
+ payloadBytes, err := base64.RawURLEncoding.DecodeString(parts[0])
+ if err != nil {
+ return 0, errors.New("invalid token encoding")
+ }
+ mac := hmac.New(sha256.New, s.hmacKey)
+ mac.Write(payloadBytes)
+ expectedSig := base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
+ if !hmac.Equal([]byte(parts[1]), []byte(expectedSig)) {
+ return 0, errors.New("invalid token signature")
+ }
+ payload := string(payloadBytes)
+ if !strings.HasPrefix(payload, "tx:") {
+ return 0, errors.New("wrong token kind")
+ }
+ id, err := strconv.ParseUint(payload[3:], 10, 64)
+ if err != nil {
+ return 0, errors.New("invalid email ID in token")
+ }
+ return uint(id), nil
+}
+
+// TxUnsubscribeURL returns the public one-click unsubscribe URL for a
+// transactional email. Suitable for RFC 8058 List-Unsubscribe-Post headers.
+func (s *Service) TxUnsubscribeURL(emailID uint) string {
+ return fmt.Sprintf("%s/t/u/tx/%s", s.baseURL, s.SignTxUnsubscribeToken(emailID))
+}
+
// hashLink generates a deterministic hash for a campaign + URL combination.
func hashLink(campaignID uint, url string) string {
h := sha256.New()
diff --git a/internal/services/webhook/dispatcher.go b/internal/services/webhook/dispatcher.go
index ef3b339..28e4387 100644
--- a/internal/services/webhook/dispatcher.go
+++ b/internal/services/webhook/dispatcher.go
@@ -155,8 +155,29 @@ type Payload struct {
Timestamp string `json:"timestamp"`
}
-// Dispatch sends webhook notifications for the given event. Runs asynchronously.
+// Dispatch sends webhook notifications for the given event using the default
+// outbound payload shape ({event, email_id, timestamp}). Runs asynchronously.
func (d *Dispatcher) Dispatch(userID uint, event string, emailID string, from string) {
+ payload := Payload{
+ Event: event,
+ EmailID: emailID,
+ Timestamp: time.Now().UTC().Format(time.RFC3339),
+ }
+
+ body, err := json.Marshal(payload)
+ if err != nil {
+ logger.Error("failed to marshal webhook payload", "error", err)
+ return
+ }
+
+ d.DispatchJSON(userID, event, body, from)
+}
+
+// DispatchJSON sends a pre-serialized JSON body to all webhooks subscribed to event
+// for the given user that pass the sender-address filter. Runs asynchronously.
+// Callers own the payload shape — this is the escape hatch used by the inbound
+// pipeline (which has a richer payload than the outbound Payload struct).
+func (d *Dispatcher) DispatchJSON(userID uint, event string, body []byte, fromAddr string) {
go func() {
webhooks, err := d.repo.FindByUserIDAndEvent(userID, event)
if err != nil {
@@ -164,20 +185,8 @@ func (d *Dispatcher) Dispatch(userID uint, event string, emailID string, from st
return
}
- payload := Payload{
- Event: event,
- EmailID: emailID,
- Timestamp: time.Now().UTC().Format(time.RFC3339),
- }
-
- body, err := json.Marshal(payload)
- if err != nil {
- logger.Error("failed to marshal webhook payload", "error", err)
- return
- }
-
for _, wh := range webhooks {
- if !matchesFilters(wh.Filters, from) {
+ if !matchesFilters(wh.Filters, fromAddr) {
continue
}
d.deliverWithRetry(userID, wh, body, event)
diff --git a/internal/services/workermon/monitor.go b/internal/services/workermon/monitor.go
index 01a82e1..ad7d2ce 100644
--- a/internal/services/workermon/monitor.go
+++ b/internal/services/workermon/monitor.go
@@ -35,11 +35,16 @@ type Monitor struct {
inspector *asynq.Inspector
bus *eventbus.EventBus
interval time.Duration
+ onCount func(int)
mu sync.Mutex
known map[string]workerInfo // keyed by "host:pid"
}
+// OnCount sets a callback invoked with the current worker count after each poll.
+// Used to feed metrics gauges.
+func (m *Monitor) OnCount(fn func(int)) { m.onCount = fn }
+
type workerInfo struct {
Host string
PID int
@@ -131,4 +136,8 @@ func (m *Monitor) check() {
}
m.known = current
+
+ if m.onCount != nil {
+ m.onCount(len(current))
+ }
}
diff --git a/internal/storage/migration/constraints.go b/internal/storage/migration/constraints.go
index 8564766..90fcf56 100644
--- a/internal/storage/migration/constraints.go
+++ b/internal/storage/migration/constraints.go
@@ -32,9 +32,6 @@ func runConstraints(db *gorm.DB) {
END IF;
END $$`)
- // Ensure template_localizations cascade-deletes when a version is removed.
- // GORM's AutoMigrate does not update existing FK constraints, so we
- // drop and recreate if the current constraint lacks ON DELETE CASCADE.
db.Exec(`DO $$ BEGIN
IF EXISTS (
SELECT 1 FROM pg_constraint c
@@ -49,19 +46,28 @@ func runConstraints(db *gorm.DB) {
END IF;
END $$`)
- // Rebuild unique indexes to include workspace_id so that
- // the same name/email can exist in different workspaces.
rebuildUniqueIndexes(db)
+
+ // Partial unique index: at most one ownership-verified row per domain name
+ // (case-insensitive). Prevents two tenants from both verifying the same domain.
+ db.Exec(`DO $$ BEGIN
+ DROP INDEX IF EXISTS idx_verified_domain;
+ CREATE UNIQUE INDEX idx_verified_domain ON domains (LOWER(domain)) WHERE ownership_verified = true;
+ EXCEPTION WHEN others THEN NULL;
+ END $$`)
+
+ // Composite index for fast Message-ID dedup lookups on inbound_emails.
+ db.Exec(`DO $$ BEGIN
+ CREATE INDEX IF NOT EXISTS idx_inbound_user_message_id ON inbound_emails (user_id, message_id) WHERE message_id <> '';
+ EXCEPTION WHEN others THEN NULL;
+ END $$`)
}
-// rebuildUniqueIndexes drops legacy two-column unique indexes and replaces
-// them with expression indexes that use COALESCE(workspace_id, 0) so that
-// NULL workspace_id values (personal space) are treated as equal.
func rebuildUniqueIndexes(db *gorm.DB) {
type indexDef struct {
table string
name string
- column string // the varying column (name, email, code, domain)
+ column string
}
indexes := []indexDef{
diff --git a/internal/storage/migration/migration.go b/internal/storage/migration/migration.go
index 40112ba..7480ba2 100644
--- a/internal/storage/migration/migration.go
+++ b/internal/storage/migration/migration.go
@@ -38,6 +38,7 @@ func Run(db *gorm.DB) error {
&models.WorkspaceSSOConfig{},
&models.APIKey{},
&models.Email{},
+ &models.InboundEmail{},
&models.StyleSheet{},
&models.Template{},
&models.TemplateVersion{},
@@ -55,9 +56,11 @@ func Run(db *gorm.DB) error {
&models.UserSetting{},
&models.WebhookDelivery{},
&models.Session{},
+ &models.UserEmailVerification{},
&models.Subscriber{},
&models.SubscriberList{},
&models.SubscriberListMember{},
+ &models.SubscriberListUnsubscribe{},
&models.Campaign{},
&models.CampaignMessage{},
&models.TrackedLink{},
@@ -66,25 +69,9 @@ func Run(db *gorm.DB) error {
return fmt.Errorf("failed to migrate database: %w", err)
}
- // Normalize: set workspace_id = NULL where it was previously 0 (personal data)
- normalizeWorkspaceIDs(db)
-
// run constraints
runConstraints(db)
logger.Info("database migrated")
return nil
}
-
-// normalizeWorkspaceIDs sets workspace_id to NULL where it is 0 (legacy default).
-// NULL means personal space; only non-NULL values reference a real workspace.
-func normalizeWorkspaceIDs(db *gorm.DB) {
- tables := []string{
- "api_keys", "emails", "templates", "smtp_servers", "domains",
- "webhooks", "webhook_deliveries", "contacts",
- "bounces", "suppressions", "style_sheets", "languages", "events",
- }
- for _, table := range tables {
- db.Exec(fmt.Sprintf(`UPDATE %s SET workspace_id = NULL WHERE workspace_id = 0`, table))
- }
-}
diff --git a/internal/storage/postgres.go b/internal/storage/postgres.go
index 19176fd..d823aa8 100644
--- a/internal/storage/postgres.go
+++ b/internal/storage/postgres.go
@@ -19,6 +19,7 @@ package storage
import (
"fmt"
+ "time"
"github.com/goposta/posta/internal/models"
"github.com/jkaninda/logger"
@@ -50,11 +51,13 @@ func SeedAdmin(db *gorm.DB, email, password string) error {
return fmt.Errorf("failed to hash admin password: %w", err)
}
+ now := time.Now()
admin := &models.User{
- Email: email,
- Name: "Admin",
- PasswordHash: string(hash),
- Role: models.UserRoleAdmin,
+ Email: email,
+ Name: "Admin",
+ PasswordHash: string(hash),
+ Role: models.UserRoleAdmin,
+ EmailVerifiedAt: &now,
}
if err := db.Create(admin).Error; err != nil {
return fmt.Errorf("failed to create admin user: %w", err)
diff --git a/internal/storage/repositories/analytics_repo.go b/internal/storage/repositories/analytics_repo.go
index 4037169..793b654 100644
--- a/internal/storage/repositories/analytics_repo.go
+++ b/internal/storage/repositories/analytics_repo.go
@@ -357,3 +357,103 @@ func (r *AnalyticsRepository) WorkspaceLatencyPercentiles(workspaceID uint, from
Scan(&result).Error
return &result, err
}
+
+// ProviderBreakdownPoint represents delivery counts bucketed by recipient mailbox provider.
+type ProviderBreakdownPoint struct {
+ Provider string `json:"provider"`
+ Sent int64 `json:"sent"`
+ Failed int64 `json:"failed"`
+ Bounced int64 `json:"bounced"`
+ Total int64 `json:"total"`
+ DeliveryRate float64 `json:"delivery_rate"`
+}
+
+type providerRow struct {
+ Provider string
+ Status string
+ Count int64
+}
+
+// queryProviderRows groups the persisted `provider` column by (provider, status).
+// The column is populated at send time by email.ClassifyRecipients, so the query
+// is a single indexed aggregate — no CASE expression, no unnest.
+func (r *AnalyticsRepository) queryProviderRows(where string, args []any) ([]providerRow, error) {
+ var rows []providerRow
+ err := r.db.Table("emails").
+ Select("COALESCE(NULLIF(provider, ''), 'Other') as provider, status, COUNT(*) as count").
+ Where(where, args...).
+ Group("provider, status").
+ Scan(&rows).Error
+ return rows, err
+}
+
+// ProviderBreakdown returns delivery counts bucketed by mailbox provider for a user.
+func (r *AnalyticsRepository) ProviderBreakdown(userID uint, from, to time.Time) ([]ProviderBreakdownPoint, error) {
+ rows, err := r.queryProviderRows(
+ "user_id = ? AND workspace_id IS NULL AND created_at >= ? AND created_at <= ?",
+ []any{userID, from, to},
+ )
+ if err != nil {
+ return nil, err
+ }
+ return buildProviderBreakdown(rows), nil
+}
+
+// WorkspaceProviderBreakdown returns delivery counts by provider for a workspace.
+func (r *AnalyticsRepository) WorkspaceProviderBreakdown(workspaceID uint, from, to time.Time) ([]ProviderBreakdownPoint, error) {
+ rows, err := r.queryProviderRows(
+ "workspace_id = ? AND created_at >= ? AND created_at <= ?",
+ []any{workspaceID, from, to},
+ )
+ if err != nil {
+ return nil, err
+ }
+ return buildProviderBreakdown(rows), nil
+}
+
+// AdminProviderBreakdown returns delivery counts by provider across all users.
+func (r *AnalyticsRepository) AdminProviderBreakdown(from, to time.Time) ([]ProviderBreakdownPoint, error) {
+ rows, err := r.queryProviderRows(
+ "created_at >= ? AND created_at <= ?",
+ []any{from, to},
+ )
+ if err != nil {
+ return nil, err
+ }
+ return buildProviderBreakdown(rows), nil
+}
+
+func buildProviderBreakdown(rows []providerRow) []ProviderBreakdownPoint {
+ agg := make(map[string]*ProviderBreakdownPoint)
+ for _, row := range rows {
+ p, ok := agg[row.Provider]
+ if !ok {
+ p = &ProviderBreakdownPoint{Provider: row.Provider}
+ agg[row.Provider] = p
+ }
+ switch row.Status {
+ case "sent":
+ p.Sent += row.Count
+ case "failed":
+ p.Failed += row.Count
+ case "suppressed":
+ p.Bounced += row.Count
+ }
+ p.Total += row.Count
+ }
+ out := make([]ProviderBreakdownPoint, 0, len(agg))
+ for _, p := range agg {
+ deliverable := p.Sent + p.Failed
+ if deliverable > 0 {
+ p.DeliveryRate = float64(p.Sent) / float64(deliverable) * 100
+ }
+ out = append(out, *p)
+ }
+ // Sort by total volume desc for stable rendering.
+ for i := 1; i < len(out); i++ {
+ for j := i; j > 0 && out[j].Total > out[j-1].Total; j-- {
+ out[j], out[j-1] = out[j-1], out[j]
+ }
+ }
+ return out
+}
diff --git a/internal/storage/repositories/campaign_message_repo.go b/internal/storage/repositories/campaign_message_repo.go
index 7af361f..b1c6d82 100644
--- a/internal/storage/repositories/campaign_message_repo.go
+++ b/internal/storage/repositories/campaign_message_repo.go
@@ -93,6 +93,33 @@ func (r *CampaignMessageRepository) SetEmailID(id uint, emailID uint) error {
return r.db.Model(&models.CampaignMessage{}).Where("id = ?", id).Update("email_id", emailID).Error
}
+func (r *CampaignMessageRepository) CountByStatusForCampaigns(campaignIDs []uint) (map[uint]map[models.CampaignMessageStatus]int64, error) {
+ result := make(map[uint]map[models.CampaignMessageStatus]int64, len(campaignIDs))
+ if len(campaignIDs) == 0 {
+ return result, nil
+ }
+ type row struct {
+ CampaignID uint
+ Status models.CampaignMessageStatus
+ Count int64
+ }
+ var rows []row
+ if err := r.db.Model(&models.CampaignMessage{}).
+ Select("campaign_id, status, COUNT(*) as count").
+ Where("campaign_id IN ?", campaignIDs).
+ Group("campaign_id, status").
+ Find(&rows).Error; err != nil {
+ return nil, err
+ }
+ for _, rw := range rows {
+ if _, ok := result[rw.CampaignID]; !ok {
+ result[rw.CampaignID] = make(map[models.CampaignMessageStatus]int64)
+ }
+ result[rw.CampaignID][rw.Status] = rw.Count
+ }
+ return result, nil
+}
+
func (r *CampaignMessageRepository) CountByStatus(campaignID uint) (map[models.CampaignMessageStatus]int64, error) {
type result struct {
Status models.CampaignMessageStatus
@@ -114,6 +141,17 @@ func (r *CampaignMessageRepository) CountByStatus(campaignID uint) (map[models.C
return counts, nil
}
+// SkipPendingForCampaign marks all still-pending CampaignMessages as skipped.
+func (r *CampaignMessageRepository) SkipPendingForCampaign(campaignID uint, reason string) (int64, error) {
+ res := r.db.Model(&models.CampaignMessage{}).
+ Where("campaign_id = ? AND status = ?", campaignID, models.CampaignMsgPending).
+ Updates(map[string]interface{}{
+ "status": models.CampaignMsgSkipped,
+ "error_message": reason,
+ })
+ return res.RowsAffected, res.Error
+}
+
func (r *CampaignMessageRepository) CountPending(campaignID uint) (int64, error) {
var count int64
err := r.db.Model(&models.CampaignMessage{}).
diff --git a/internal/storage/repositories/campaign_repo.go b/internal/storage/repositories/campaign_repo.go
index 8899f11..fbce2a0 100644
--- a/internal/storage/repositories/campaign_repo.go
+++ b/internal/storage/repositories/campaign_repo.go
@@ -18,6 +18,7 @@
package repositories
import (
+ "errors"
"time"
"github.com/goposta/posta/internal/models"
@@ -44,6 +45,16 @@ func (r *CampaignRepository) FindByID(id uint) (*models.Campaign, error) {
return &c, nil
}
+// FindByIDForScope returns the campaign only if it belongs to the given scope.
+// Prefer this over FindByID in request handlers so scoping lives in one place.
+func (r *CampaignRepository) FindByIDForScope(id uint, scope ResourceScope) (*models.Campaign, error) {
+ var c models.Campaign
+ if err := ApplyScope(r.db, scope).First(&c, id).Error; err != nil {
+ return nil, err
+ }
+ return &c, nil
+}
+
func (r *CampaignRepository) FindByScope(scope ResourceScope, status string, limit, offset int) ([]models.Campaign, int64, error) {
var items []models.Campaign
var total int64
@@ -68,8 +79,18 @@ func (r *CampaignRepository) Update(c *models.Campaign) error {
return r.db.Save(c).Error
}
-func (r *CampaignRepository) Delete(id uint) error {
+// Delete soft-deletes the campaign and purges its CampaignMessage rows.
+// A snapshot of aggregated stats is written to campaigns.snapshot first so
+// post-deletion analytics survive. The snapshot is optional; callers pass nil
+// for a bare delete (e.g., never-sent drafts).
+func (r *CampaignRepository) Delete(id uint, snapshot models.TemplateData) error {
return r.db.Transaction(func(tx *gorm.DB) error {
+ if snapshot != nil {
+ if err := tx.Model(&models.Campaign{}).Where("id = ?", id).
+ Update("snapshot", snapshot).Error; err != nil {
+ return err
+ }
+ }
if err := tx.Where("campaign_id = ?", id).Delete(&models.CampaignMessage{}).Error; err != nil {
return err
}
@@ -88,6 +109,44 @@ func (r *CampaignRepository) UpdateStatus(id uint, status models.CampaignStatus)
return r.db.Model(&models.Campaign{}).Where("id = ?", id).Updates(updates).Error
}
+// ErrStatusConflict indicates the campaign was not in any of the expected source statuses,
+// so the transition did not happen. Used to detect concurrent writes / double-clicks.
+var ErrStatusConflict = errors.New("campaign status conflict")
+
+// TransitionStatus atomically moves a campaign from one of `from` statuses to `to`.
+// Returns ErrStatusConflict when no row matched (concurrent transition).
+func (r *CampaignRepository) TransitionStatus(id uint, from []models.CampaignStatus, to models.CampaignStatus) error {
+ updates := map[string]interface{}{"status": to, "updated_at": time.Now()}
+ if to == models.CampaignStatusSending {
+ updates["started_at"] = time.Now()
+ }
+ if to == models.CampaignStatusSent || to == models.CampaignStatusCancelled {
+ updates["completed_at"] = time.Now()
+ }
+ res := r.db.Model(&models.Campaign{}).
+ Where("id = ? AND status IN ?", id, from).
+ Updates(updates)
+ if res.Error != nil {
+ return res.Error
+ }
+ if res.RowsAffected == 0 {
+ return ErrStatusConflict
+ }
+ return nil
+}
+
+// FindStuckSending returns campaigns that have been in `sending` status longer
+// than `stuckFor` but still have pending messages — typically the result of a
+// worker crash between enqueue and completion. Used by the restart sweep.
+func (r *CampaignRepository) FindStuckSending(stuckFor time.Duration) ([]models.Campaign, error) {
+ var items []models.Campaign
+ cutoff := time.Now().Add(-stuckFor)
+ err := r.db.
+ Where("status = ? AND (started_at IS NULL OR started_at < ?)", models.CampaignStatusSending, cutoff).
+ Find(&items).Error
+ return items, err
+}
+
func (r *CampaignRepository) FindScheduledReady() ([]models.Campaign, error) {
var campaigns []models.Campaign
if err := r.db.Where("status = ? AND scheduled_at <= ?", models.CampaignStatusScheduled, time.Now()).
diff --git a/internal/storage/repositories/domain_repo.go b/internal/storage/repositories/domain_repo.go
index e9e08ca..f91eff8 100644
--- a/internal/storage/repositories/domain_repo.go
+++ b/internal/storage/repositories/domain_repo.go
@@ -103,6 +103,19 @@ func (r *DomainRepository) FindByScope(scope ResourceScope, limit, offset int) (
return items, total, nil
}
+// FindVerifiedByName returns an ownership-verified Domain row matching the given name,
+// regardless of the owning user. Used for routing inbound email to the right tenant.
+// Returns gorm.ErrRecordNotFound if no verified domain matches.
+func (r *DomainRepository) FindVerifiedByName(domainName string) (*models.Domain, error) {
+ var d models.Domain
+ if err := r.db.Where("LOWER(domain) = LOWER(?) AND ownership_verified = ?", domainName, true).
+ Order("created_at ASC").
+ First(&d).Error; err != nil {
+ return nil, err
+ }
+ return &d, nil
+}
+
// IsOwnershipVerified checks whether the given domain is registered and ownership-verified for the user.
func (r *DomainRepository) IsOwnershipVerified(userID uint, domainName string) bool {
var count int64
diff --git a/internal/storage/repositories/email_repo.go b/internal/storage/repositories/email_repo.go
index 70ca2d2..f6eac3b 100644
--- a/internal/storage/repositories/email_repo.go
+++ b/internal/storage/repositories/email_repo.go
@@ -143,3 +143,14 @@ func (r *EmailRepository) DeleteOlderThan(before time.Time) (int64, error) {
result := r.db.Where("created_at < ?", before).Delete(&models.Email{})
return result.RowsAffected, result.Error
}
+
+// AttachmentsJSONOlderThan returns the attachments_json blob for every email
+// row older than the cutoff. The caller decodes each to enumerate blob-storage
+// keys so they can be deleted before the rows are dropped.
+func (r *EmailRepository) AttachmentsJSONOlderThan(before time.Time) ([]string, error) {
+ var out []string
+ err := r.db.Model(&models.Email{}).
+ Where("created_at < ? AND attachments_json <> ''", before).
+ Pluck("attachments_json", &out).Error
+ return out, err
+}
diff --git a/internal/storage/repositories/inbound_email_repo.go b/internal/storage/repositories/inbound_email_repo.go
new file mode 100644
index 0000000..754cf1f
--- /dev/null
+++ b/internal/storage/repositories/inbound_email_repo.go
@@ -0,0 +1,206 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package repositories
+
+import (
+ "strings"
+ "time"
+
+ "github.com/goposta/posta/internal/models"
+ "gorm.io/gorm"
+)
+
+// InboundFilter captures optional list filters for inbound email queries.
+type InboundFilter struct {
+ Status string
+ Source string
+ Sender string
+ Query string
+}
+
+type InboundEmailRepository struct {
+ db *gorm.DB
+}
+
+func NewInboundEmailRepository(db *gorm.DB) *InboundEmailRepository {
+ return &InboundEmailRepository{db: db}
+}
+
+func (r *InboundEmailRepository) Create(em *models.InboundEmail) error {
+ return r.db.Create(em).Error
+}
+
+func (r *InboundEmailRepository) Update(em *models.InboundEmail) error {
+ return r.db.Save(em).Error
+}
+
+func (r *InboundEmailRepository) FindByID(id uint) (*models.InboundEmail, error) {
+ var em models.InboundEmail
+ if err := r.db.First(&em, id).Error; err != nil {
+ return nil, err
+ }
+ return &em, nil
+}
+
+func (r *InboundEmailRepository) FindByUUID(uuid string) (*models.InboundEmail, error) {
+ var em models.InboundEmail
+ if err := r.db.Where("uuid = ?", uuid).First(&em).Error; err != nil {
+ return nil, err
+ }
+ return &em, nil
+}
+
+func (r *InboundEmailRepository) FindByUserID(userID uint, limit, offset int) ([]models.InboundEmail, int64, error) {
+ var items []models.InboundEmail
+ var total int64
+
+ r.db.Model(&models.InboundEmail{}).Where("user_id = ? AND workspace_id IS NULL", userID).Count(&total)
+
+ if err := r.db.Where("user_id = ? AND workspace_id IS NULL", userID).
+ Order("received_at DESC").
+ Limit(limit).Offset(offset).
+ Find(&items).Error; err != nil {
+ return nil, 0, err
+ }
+ return items, total, nil
+}
+
+func (r *InboundEmailRepository) FindByWorkspaceID(workspaceID uint, limit, offset int) ([]models.InboundEmail, int64, error) {
+ var items []models.InboundEmail
+ var total int64
+
+ r.db.Model(&models.InboundEmail{}).Where("workspace_id = ?", workspaceID).Count(&total)
+
+ if err := r.db.Where("workspace_id = ?", workspaceID).
+ Order("received_at DESC").
+ Limit(limit).Offset(offset).
+ Find(&items).Error; err != nil {
+ return nil, 0, err
+ }
+ return items, total, nil
+}
+
+func (r *InboundEmailRepository) FindByScope(scope ResourceScope, limit, offset int) ([]models.InboundEmail, int64, error) {
+ var items []models.InboundEmail
+ var total int64
+
+ ApplyScope(r.db.Model(&models.InboundEmail{}), scope).Count(&total)
+
+ if err := ApplyScope(r.db, scope).
+ Order("received_at DESC").
+ Limit(limit).Offset(offset).
+ Find(&items).Error; err != nil {
+ return nil, 0, err
+ }
+ return items, total, nil
+}
+
+// FindByMessageID returns an existing inbound email with the same Message-ID for
+// the given user. Used for idempotent ingest (MX providers may retry webhooks).
+// Returns gorm.ErrRecordNotFound when no match exists.
+func (r *InboundEmailRepository) FindByMessageID(userID uint, messageID string) (*models.InboundEmail, error) {
+ var em models.InboundEmail
+ if err := r.db.Where("user_id = ? AND message_id = ?", userID, messageID).First(&em).Error; err != nil {
+ return nil, err
+ }
+ return &em, nil
+}
+
+// FindByDedupHash returns an existing inbound email with the same dedup fallback
+// hash for the given user. Used when Message-ID is absent (webhook ingest).
+func (r *InboundEmailRepository) FindByDedupHash(userID uint, hash string) (*models.InboundEmail, error) {
+ var em models.InboundEmail
+ if err := r.db.Where("user_id = ? AND dedup_hash = ?", userID, hash).First(&em).Error; err != nil {
+ return nil, err
+ }
+ return &em, nil
+}
+
+// FindByScopeFiltered returns inbound emails matching the scope and any optional
+// filters. An empty filter field means "no filter on that column".
+func (r *InboundEmailRepository) FindByScopeFiltered(scope ResourceScope, f InboundFilter, limit, offset int) ([]models.InboundEmail, int64, error) {
+ var items []models.InboundEmail
+ var total int64
+
+ apply := func(q *gorm.DB) *gorm.DB {
+ q = ApplyScope(q, scope)
+ if f.Status != "" {
+ q = q.Where("status = ?", f.Status)
+ }
+ if f.Source != "" {
+ q = q.Where("source = ?", f.Source)
+ }
+ if f.Sender != "" {
+ q = q.Where("LOWER(sender) LIKE ?", "%"+strings.ToLower(f.Sender)+"%")
+ }
+ if f.Query != "" {
+ q = q.Where("LOWER(subject) LIKE ?", "%"+strings.ToLower(f.Query)+"%")
+ }
+ return q
+ }
+
+ apply(r.db.Model(&models.InboundEmail{})).Count(&total)
+
+ if err := apply(r.db).
+ Order("received_at DESC").
+ Limit(limit).Offset(offset).
+ Find(&items).Error; err != nil {
+ return nil, 0, err
+ }
+ return items, total, nil
+}
+
+// Delete permanently removes an inbound email record by ID.
+func (r *InboundEmailRepository) Delete(id uint) error {
+ return r.db.Delete(&models.InboundEmail{}, id).Error
+}
+
+// CountByScope returns aggregate counts per status for dashboard use.
+func (r *InboundEmailRepository) CountByScope(scope ResourceScope) (total, forwarded, failed, received int64, err error) {
+ err = ApplyScope(r.db.Model(&models.InboundEmail{}), scope).Count(&total).Error
+ if err != nil {
+ return
+ }
+ _ = ApplyScope(r.db.Model(&models.InboundEmail{}), scope).Where("status = ?", models.InboundStatusForwarded).Count(&forwarded).Error
+ _ = ApplyScope(r.db.Model(&models.InboundEmail{}), scope).Where("status = ?", models.InboundStatusFailed).Count(&failed).Error
+ _ = ApplyScope(r.db.Model(&models.InboundEmail{}), scope).Where("status = ?", models.InboundStatusReceived).Count(&received).Error
+ return
+}
+
+// DeleteOlderThan removes inbound email records older than the given time.
+// Returns the number of rows deleted.
+func (r *InboundEmailRepository) DeleteOlderThan(before time.Time) (int64, error) {
+ result := r.db.Where("created_at < ?", before).Delete(&models.InboundEmail{})
+ return result.RowsAffected, result.Error
+}
+
+// InboundBlobKeysOlderThan returns the attachments_json and raw_storage_key
+// values for every inbound_emails row older than the cutoff so the caller can
+// remove the underlying blob objects before the DB rows are dropped.
+func (r *InboundEmailRepository) InboundBlobKeysOlderThan(before time.Time) (attachmentsJSON []string, rawKeys []string, err error) {
+ err = r.db.Model(&models.InboundEmail{}).
+ Where("created_at < ? AND attachments_json <> ''", before).
+ Pluck("attachments_json", &attachmentsJSON).Error
+ if err != nil {
+ return nil, nil, err
+ }
+ err = r.db.Model(&models.InboundEmail{}).
+ Where("created_at < ? AND raw_storage_key <> ''", before).
+ Pluck("raw_storage_key", &rawKeys).Error
+ return attachmentsJSON, rawKeys, err
+}
diff --git a/internal/storage/repositories/oauth_provider_repo.go b/internal/storage/repositories/oauth_provider_repo.go
index 8d8d3ad..52e50a4 100644
--- a/internal/storage/repositories/oauth_provider_repo.go
+++ b/internal/storage/repositories/oauth_provider_repo.go
@@ -1,6 +1,8 @@
package repositories
import (
+ "strings"
+
"github.com/goposta/posta/internal/models"
"gorm.io/gorm"
)
@@ -33,26 +35,59 @@ func (r *OAuthProviderRepository) FindBySlug(slug string) (*models.OAuthProvider
return &p, nil
}
-// FindEnabled returns all enabled global providers (workspace_id IS NULL).
+// FindEnabled returns enabled, non-hidden global providers for the login page button list.
func (r *OAuthProviderRepository) FindEnabled() ([]models.OAuthProvider, error) {
var providers []models.OAuthProvider
- if err := r.db.Where("enabled = true AND workspace_id IS NULL").
+ if err := r.db.Where("enabled = true AND hidden = false AND workspace_id IS NULL").
Order("name ASC").Find(&providers).Error; err != nil {
return nil, err
}
return providers, nil
}
-// FindEnabledForWorkspace returns enabled providers: global + workspace-scoped.
+// FindEnabledForWorkspace returns enabled, non-hidden providers: global + workspace-scoped.
func (r *OAuthProviderRepository) FindEnabledForWorkspace(wsID uint) ([]models.OAuthProvider, error) {
var providers []models.OAuthProvider
- if err := r.db.Where("enabled = true AND (workspace_id IS NULL OR workspace_id = ?)", wsID).
+ if err := r.db.Where("enabled = true AND hidden = false AND (workspace_id IS NULL OR workspace_id = ?)", wsID).
Order("name ASC").Find(&providers).Error; err != nil {
return nil, err
}
return providers, nil
}
+// HasEnabledHidden reports whether any enabled, hidden provider exists.
+// Drives the visibility of the "Continue with SSO" entry point on the login page.
+func (r *OAuthProviderRepository) HasEnabledHidden() (bool, error) {
+ var count int64
+ if err := r.db.Model(&models.OAuthProvider{}).
+ Where("enabled = true AND hidden = true").Count(&count).Error; err != nil {
+ return false, err
+ }
+ return count > 0, nil
+}
+
+// FindEnabledByDomain scans enabled providers (including hidden) whose AllowedDomains CSV
+// contains the given domain. Used for email-based SSO discovery.
+func (r *OAuthProviderRepository) FindEnabledByDomain(domain string) (*models.OAuthProvider, error) {
+ if domain == "" {
+ return nil, gorm.ErrRecordNotFound
+ }
+ var providers []models.OAuthProvider
+ if err := r.db.Where("enabled = true AND allowed_domains <> ''").
+ Find(&providers).Error; err != nil {
+ return nil, err
+ }
+ target := strings.ToLower(strings.TrimSpace(domain))
+ for i := range providers {
+ for _, d := range strings.Split(providers[i].AllowedDomains, ",") {
+ if strings.ToLower(strings.TrimSpace(d)) == target {
+ return &providers[i], nil
+ }
+ }
+ }
+ return nil, gorm.ErrRecordNotFound
+}
+
// FindAll returns all providers (admin).
func (r *OAuthProviderRepository) FindAll() ([]models.OAuthProvider, error) {
var providers []models.OAuthProvider
diff --git a/internal/storage/repositories/subscriber_list_repo.go b/internal/storage/repositories/subscriber_list_repo.go
index 45e8215..33e2384 100644
--- a/internal/storage/repositories/subscriber_list_repo.go
+++ b/internal/storage/repositories/subscriber_list_repo.go
@@ -18,6 +18,8 @@
package repositories
import (
+ "time"
+
"github.com/goposta/posta/internal/models"
"gorm.io/gorm"
"gorm.io/gorm/clause"
@@ -43,6 +45,15 @@ func (r *SubscriberListRepository) FindByID(id uint) (*models.SubscriberList, er
return &list, nil
}
+// FindByNameForScope resolves a list by name within the given scope.
+func (r *SubscriberListRepository) FindByNameForScope(scope ResourceScope, name string) (*models.SubscriberList, error) {
+ var list models.SubscriberList
+ if err := ApplyScope(r.db, scope).Where("name = ?", name).First(&list).Error; err != nil {
+ return nil, err
+ }
+ return &list, nil
+}
+
func (r *SubscriberListRepository) FindByScope(scope ResourceScope, limit, offset int) ([]models.SubscriberList, int64, error) {
var items []models.SubscriberList
var total int64
@@ -103,6 +114,17 @@ func (r *SubscriberListRepository) MemberCount(listID uint) int64 {
return count
}
+// IsMember returns true when the subscriber is currently a member of the list.
+// Used by the API Subscribe endpoint to decide whether a call actually added
+// a new member (so the response's member_added flag is accurate).
+func (r *SubscriberListRepository) IsMember(listID, subscriberID uint) bool {
+ var count int64
+ r.db.Model(&models.SubscriberListMember{}).
+ Where("list_id = ? AND subscriber_id = ?", listID, subscriberID).
+ Count(&count)
+ return count > 0
+}
+
func (r *SubscriberListRepository) BulkAddMembers(listID uint, subscriberIDs []uint) (int, error) {
if len(subscriberIDs) == 0 {
return 0, nil
@@ -117,3 +139,50 @@ func (r *SubscriberListRepository) BulkAddMembers(listID uint, subscriberIDs []u
result := r.db.Clauses(clause.OnConflict{DoNothing: true}).CreateInBatches(members, 100)
return int(result.RowsAffected), result.Error
}
+
+// SuppressMember records a list-scoped opt-out (works for static and dynamic
+func (r *SubscriberListRepository) SuppressMember(listID, subscriberID uint, reason string) error {
+ return r.db.Transaction(func(tx *gorm.DB) error {
+ row := models.SubscriberListUnsubscribe{
+ ListID: listID,
+ SubscriberID: subscriberID,
+ Reason: reason,
+ UnsubscribedAt: time.Now(),
+ }
+ if err := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&row).Error; err != nil {
+ return err
+ }
+
+ return tx.Where("list_id = ? AND subscriber_id = ?", listID, subscriberID).
+ Delete(&models.SubscriberListMember{}).Error
+ })
+}
+
+// SuppressedSubscriberIDs returns the set of subscriber IDs that have opted
+func (r *SubscriberListRepository) SuppressedSubscriberIDs(listID uint) (map[uint]struct{}, error) {
+ var ids []uint
+ if err := r.db.Model(&models.SubscriberListUnsubscribe{}).
+ Where("list_id = ?", listID).
+ Pluck("subscriber_id", &ids).Error; err != nil {
+ return nil, err
+ }
+ out := make(map[uint]struct{}, len(ids))
+ for _, id := range ids {
+ out[id] = struct{}{}
+ }
+ return out, nil
+}
+
+// IsSuppressed checks whether a subscriber has opted out of a specific list.
+func (r *SubscriberListRepository) IsSuppressed(listID, subscriberID uint) bool {
+ var count int64
+ r.db.Model(&models.SubscriberListUnsubscribe{}).
+ Where("list_id = ? AND subscriber_id = ?", listID, subscriberID).
+ Count(&count)
+ return count > 0
+}
+
+func (r *SubscriberListRepository) UnsuppressMember(listID, subscriberID uint) error {
+ return r.db.Where("list_id = ? AND subscriber_id = ?", listID, subscriberID).
+ Delete(&models.SubscriberListUnsubscribe{}).Error
+}
diff --git a/internal/storage/repositories/suppression_repo.go b/internal/storage/repositories/suppression_repo.go
index fa7f400..9fe5c65 100644
--- a/internal/storage/repositories/suppression_repo.go
+++ b/internal/storage/repositories/suppression_repo.go
@@ -23,6 +23,7 @@ import (
"github.com/goposta/posta/internal/models"
"gorm.io/gorm"
+ "gorm.io/gorm/clause"
)
// normalizeEmail extracts the bare email address from a string that may be in
@@ -48,6 +49,14 @@ func (r *SuppressionRepository) Create(suppression *models.Suppression) error {
return r.db.Create(suppression).Error
}
+// Upsert adds a suppression idempotently. If a row already exists for the same
+// (user_id, workspace_id, email), the existing row is kept and no error is
+// returned. Intended for automated paths (bounces, one-click unsubscribe).
+func (r *SuppressionRepository) Upsert(suppression *models.Suppression) error {
+ suppression.Email = normalizeEmail(suppression.Email)
+ return r.db.Clauses(clause.OnConflict{DoNothing: true}).Create(suppression).Error
+}
+
func (r *SuppressionRepository) Delete(scope ResourceScope, email string) error {
return ApplyScope(r.db, scope).Where("email = ?", normalizeEmail(email)).Delete(&models.Suppression{}).Error
}
diff --git a/internal/storage/repositories/user_email_verification_repo.go b/internal/storage/repositories/user_email_verification_repo.go
new file mode 100644
index 0000000..4e31d41
--- /dev/null
+++ b/internal/storage/repositories/user_email_verification_repo.go
@@ -0,0 +1,70 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package repositories
+
+import (
+ "time"
+
+ "github.com/goposta/posta/internal/models"
+ "gorm.io/gorm"
+)
+
+type UserEmailVerificationRepository struct {
+ db *gorm.DB
+}
+
+func NewUserEmailVerificationRepository(db *gorm.DB) *UserEmailVerificationRepository {
+ return &UserEmailVerificationRepository{db: db}
+}
+
+func (r *UserEmailVerificationRepository) Create(v *models.UserEmailVerification) error {
+ return r.db.Create(v).Error
+}
+
+func (r *UserEmailVerificationRepository) FindByTokenHash(hash string) (*models.UserEmailVerification, error) {
+ var v models.UserEmailVerification
+ if err := r.db.Where("token_hash = ?", hash).First(&v).Error; err != nil {
+ return nil, err
+ }
+ return &v, nil
+}
+
+func (r *UserEmailVerificationRepository) MarkUsed(id uint) error {
+ now := time.Now()
+ return r.db.Model(&models.UserEmailVerification{}).
+ Where("id = ?", id).
+ Update("used_at", now).Error
+}
+
+// InvalidatePending marks all pending (unused) tokens for a user as used.
+// Called when a new token is issued or when the email becomes verified.
+func (r *UserEmailVerificationRepository) InvalidatePending(userID uint) error {
+ now := time.Now()
+ return r.db.Model(&models.UserEmailVerification{}).
+ Where("user_id = ? AND used_at IS NULL", userID).
+ Update("used_at", now).Error
+}
+
+// CountRecentByUser counts tokens created for a user since a given time (for rate limiting).
+func (r *UserEmailVerificationRepository) CountRecentByUser(userID uint, since time.Time) (int64, error) {
+ var count int64
+ err := r.db.Model(&models.UserEmailVerification{}).
+ Where("user_id = ? AND created_at > ?", userID, since).
+ Count(&count).Error
+ return count, err
+}
diff --git a/internal/worker/campaign_processor.go b/internal/worker/campaign_processor.go
index 30f1521..29542df 100644
--- a/internal/worker/campaign_processor.go
+++ b/internal/worker/campaign_processor.go
@@ -81,8 +81,6 @@ func NewCampaignProcessor(
const campaignBatchSize = 100
// HandleCampaignStart processes a campaign:start task.
-// It resolves the subscriber list, creates campaign_messages in bulk,
-// then enqueues the first CampaignBatch task.
func (p *CampaignProcessor) HandleCampaignStart(_ context.Context, t *asynq.Task) error {
var payload CampaignPayload
if err := json.Unmarshal(t.Payload(), &payload); err != nil {
@@ -128,13 +126,24 @@ func (p *CampaignProcessor) HandleCampaignStart(_ context.Context, t *asynq.Task
return nil
}
+ // Pull list-scoped opt-outs once. Required for dynamic lists (where the
+ // filter rules can re-include a previously-unsubscribed subscriber on the
+ // next send) and a defense-in-depth check for static lists.
+ suppressed, sErr := p.listRepo.SuppressedSubscriberIDs(campaign.ListID)
+ if sErr != nil {
+ logger.Warn("campaign: failed to load list suppressions, proceeding without", "list_id", campaign.ListID, "error", sErr)
+ suppressed = nil
+ }
+
// Create campaign messages in bulk
messages := make([]models.CampaignMessage, 0, len(subscribers))
for _, sub := range subscribers {
- // Only include subscribed subscribers
if sub.Status != models.SubscriberStatusSubscribed {
continue
}
+ if _, opt := suppressed[sub.ID]; opt {
+ continue
+ }
messages = append(messages, models.CampaignMessage{
CampaignID: campaign.ID,
SubscriberID: sub.ID,
@@ -150,12 +159,10 @@ func (p *CampaignProcessor) HandleCampaignStart(_ context.Context, t *asynq.Task
// Assign A/B test variants if enabled
if campaign.ABTestEnabled && len(campaign.ABTestVariants) > 0 {
- // Shuffle messages for random distribution
rand.Shuffle(len(messages), func(i, j int) {
messages[i], messages[j] = messages[j], messages[i]
})
- // Assign variants based on split percentages
idx := 0
for _, variant := range campaign.ABTestVariants {
count := len(messages) * variant.SplitPercentage / 100
@@ -171,7 +178,6 @@ func (p *CampaignProcessor) HandleCampaignStart(_ context.Context, t *asynq.Task
}
idx = end
}
- // Assign remaining messages to last variant
if idx < len(messages) {
lastVariant := campaign.ABTestVariants[len(campaign.ABTestVariants)-1].Name
for i := idx; i < len(messages); i++ {
@@ -240,6 +246,12 @@ func (p *CampaignProcessor) HandleCampaignBatch(_ context.Context, t *asynq.Task
return nil
}
+ // Resolve template name once so it can be stamped on each email record.
+ var templateName string
+ if tmpl, err := p.templateRepo.FindByID(campaign.TemplateID); err == nil && tmpl != nil {
+ templateName = tmpl.Name
+ }
+
// Cache resolved content per language to avoid re-rendering for each subscriber
contentCache := make(map[string]*resolvedContent)
resolveForLang := func(lang string) *resolvedContent {
@@ -297,14 +309,16 @@ func (p *CampaignProcessor) HandleCampaignBatch(_ context.Context, t *asynq.Task
// Create email record
em := &models.Email{
- UserID: campaign.UserID,
- WorkspaceID: campaign.WorkspaceID,
- Sender: sender,
- Recipients: pq.StringArray{msg.Subscriber.Email},
- Subject: content.Subject,
- HTMLBody: content.HTMLBody,
- TextBody: content.TextBody,
- Status: models.EmailStatusQueued,
+ UserID: campaign.UserID,
+ WorkspaceID: campaign.WorkspaceID,
+ Sender: sender,
+ Recipients: pq.StringArray{msg.Subscriber.Email},
+ Subject: content.Subject,
+ TemplateName: templateName,
+ HTMLBody: content.HTMLBody,
+ TextBody: content.TextBody,
+ Status: models.EmailStatusQueued,
+ Provider: email.ClassifyProvider(msg.Subscriber.Email),
}
if err := p.emailRepo.Create(em); err != nil {
@@ -337,11 +351,10 @@ func (p *CampaignProcessor) HandleCampaignBatch(_ context.Context, t *asynq.Task
}
if remaining > 0 {
- // Compute rate limiting delay
var delay time.Duration
if campaign.SendRate > 0 {
- // SendRate is messages per minute
- delay = time.Duration(float64(time.Minute) / float64(campaign.SendRate) * float64(campaignBatchSize))
+ sent := len(pendingMessages)
+ delay = time.Duration(float64(sent) / float64(campaign.SendRate) * float64(time.Minute))
}
return p.producer.EnqueueCampaignBatch(campaign.ID, delay)
}
diff --git a/internal/worker/handler.go b/internal/worker/handler.go
index e92c581..0fa095b 100644
--- a/internal/worker/handler.go
+++ b/internal/worker/handler.go
@@ -38,17 +38,19 @@ import (
// EmailSendHandler processes email:send tasks from the Asynq queue.
type EmailSendHandler struct {
- emailRepo *repositories.EmailRepository
- smtpRepo *repositories.SMTPRepository
- serverRepo *repositories.ServerRepository
- domainRepo *repositories.DomainRepository
- contactRepo *repositories.ContactRepository
- messageRepo *repositories.CampaignMessageRepository
- sender *email.SMTPSender
- dispatcher *webhook.Dispatcher
- blobStore blob.Store
- onSent func()
- onFailed func()
+ emailRepo *repositories.EmailRepository
+ smtpRepo *repositories.SMTPRepository
+ serverRepo *repositories.ServerRepository
+ domainRepo *repositories.DomainRepository
+ contactRepo *repositories.ContactRepository
+ messageRepo *repositories.CampaignMessageRepository
+ campaignRepo *repositories.CampaignRepository
+ sender *email.SMTPSender
+ stamper *email.Stamper
+ dispatcher *webhook.Dispatcher
+ blobStore blob.Store
+ onSent func()
+ onFailed func()
}
func NewEmailSendHandler(
@@ -79,6 +81,19 @@ func (h *EmailSendHandler) SetCampaignMessageRepo(r *repositories.CampaignMessag
h.messageRepo = r
}
+// SetCampaignRepo lets the handler consult the campaign's live status before
+// sending. When set, already-queued emails for cancelled/paused campaigns are
+// dropped instead of dispatched.
+func (h *EmailSendHandler) SetCampaignRepo(r *repositories.CampaignRepository) {
+ h.campaignRepo = r
+}
+
+// SetStamper enables X-Mailer/X-Posta-* header stamping and optional
+// X-Posta-Signature HMAC. Nil disables stamping.
+func (h *EmailSendHandler) SetStamper(s *email.Stamper) {
+ h.stamper = s
+}
+
// OnSent sets a callback invoked after each successful email send.
func (h *EmailSendHandler) OnSent(fn func()) { h.onSent = fn }
@@ -97,6 +112,31 @@ func (h *EmailSendHandler) ProcessTask(ctx context.Context, t *asynq.Task) error
return fmt.Errorf("email not found: %w", err)
}
+ // If this email was enqueued as part of a campaign, respect the live
+ // campaign status. A paused campaign releases the message back to pending
+ // so a Resume will re-dispatch it; cancelled drops it permanently.
+ if h.messageRepo != nil && h.campaignRepo != nil {
+ if msg, mErr := h.messageRepo.FindByEmailID(em.ID); mErr == nil {
+ if camp, cErr := h.campaignRepo.FindByID(msg.CampaignID); cErr == nil {
+ switch camp.Status {
+ case models.CampaignStatusCancelled:
+ _ = h.messageRepo.UpdateStatus(msg.ID, models.CampaignMsgSkipped, "campaign cancelled")
+ em.Status = models.EmailStatusFailed
+ em.ErrorMessage = "campaign cancelled"
+ _ = h.emailRepo.Update(em)
+ logger.Info("worker: dropping email for cancelled campaign", "email_id", em.ID, "campaign_id", camp.ID)
+ return nil
+ case models.CampaignStatusPaused:
+ _ = h.messageRepo.UpdateStatus(msg.ID, models.CampaignMsgPending, "")
+ em.Status = models.EmailStatusQueued
+ _ = h.emailRepo.Update(em)
+ logger.Info("worker: releasing email back to pending (campaign paused)", "email_id", em.ID, "campaign_id", camp.ID)
+ return nil
+ }
+ }
+ }
+ }
+
// Mark as processing
em.Status = models.EmailStatusProcessing
_ = h.emailRepo.Update(em)
@@ -199,6 +239,32 @@ func (h *EmailSendHandler) ProcessTask(ctx context.Context, t *asynq.Task) error
if em.HeadersJSON != "" {
_ = json.Unmarshal([]byte(em.HeadersJSON), &headers)
}
+ if headers == nil {
+ headers = make(map[string]string)
+ }
+
+ // Stamp Posta headers. Campaign mail gets campaign-aware headers; everything
+ // else gets transactional headers. A final HMAC signs the message identity.
+ if h.stamper != nil {
+ var campMsg *models.CampaignMessage
+ if h.messageRepo != nil {
+ if m, err := h.messageRepo.FindByEmailID(em.ID); err == nil {
+ campMsg = m
+ }
+ }
+ if campMsg != nil {
+ // Opens and clicks are rewritten together in the tracking service's
+ tracked := em.HTMLBody != "" && em.ListUnsubscribeURL != ""
+ h.stamper.StampCampaign(
+ headers, em,
+ campMsg.CampaignID, campMsg.ID,
+ tracked, tracked,
+ )
+ } else {
+ h.stamper.StampTransactional(headers, em)
+ }
+ h.stamper.Sign(headers, em, em.Recipients, em.Subject)
+ }
if err := h.sender.Send(smtpServer, em.Sender, em.Recipients, em.Subject, em.HTMLBody, em.TextBody, attachments, headers, em.ListUnsubscribeURL, em.ListUnsubscribePost); err != nil {
em.RetryCount++
diff --git a/internal/worker/inbound_handler.go b/internal/worker/inbound_handler.go
new file mode 100644
index 0000000..7ea5691
--- /dev/null
+++ b/internal/worker/inbound_handler.go
@@ -0,0 +1,232 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package worker
+
+import (
+ "context"
+ "crypto/hmac"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/json"
+ "fmt"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/goposta/posta/internal/models"
+ "github.com/goposta/posta/internal/services/webhook"
+ "github.com/goposta/posta/internal/storage/repositories"
+ "github.com/hibiken/asynq"
+ "github.com/jkaninda/logger"
+)
+
+// InboundAttachmentView is the attachment shape included in the email.inbound webhook.
+// No raw content — only metadata plus a signed download URL (when configured).
+type InboundAttachmentView struct {
+ Filename string `json:"filename"`
+ ContentType string `json:"content_type"`
+ Size int64 `json:"size"`
+ URL string `json:"url,omitempty"`
+}
+
+// InboundWebhookPayload is the body posted to subscribers of email.inbound.
+type InboundWebhookPayload struct {
+ Event string `json:"event"`
+ Timestamp string `json:"timestamp"`
+ InboundID string `json:"inbound_id"`
+ From string `json:"from"`
+ To []string `json:"to"`
+ Subject string `json:"subject"`
+ TextBody string `json:"text_body,omitempty"`
+ HTMLBody string `json:"html_body,omitempty"`
+ Headers map[string]string `json:"headers,omitempty"`
+ Attachments []InboundAttachmentView `json:"attachments,omitempty"`
+ Size int64 `json:"size"`
+ MessageID string `json:"message_id,omitempty"`
+ Source string `json:"source"`
+ ReceivedAt string `json:"received_at"`
+}
+
+// InboundProcessHandler processes inbound:process tasks — builds the inbound
+// webhook payload and dispatches it via the webhook dispatcher.
+type InboundProcessHandler struct {
+ repo *repositories.InboundEmailRepository
+ dispatcher *webhook.Dispatcher
+ baseURL string
+ hmacKey []byte
+ onForwarded func()
+ onFailed func()
+}
+
+func NewInboundProcessHandler(
+ repo *repositories.InboundEmailRepository,
+ dispatcher *webhook.Dispatcher,
+ baseURL string,
+ hmacKey []byte,
+) *InboundProcessHandler {
+ return &InboundProcessHandler{
+ repo: repo,
+ dispatcher: dispatcher,
+ baseURL: strings.TrimRight(baseURL, "/"),
+ hmacKey: hmacKey,
+ }
+}
+
+// OnForwarded sets a callback invoked after a successful inbound forward.
+func (h *InboundProcessHandler) OnForwarded(fn func()) { h.onForwarded = fn }
+
+// OnFailed sets a callback invoked after a permanently failed inbound forward.
+func (h *InboundProcessHandler) OnFailed(fn func()) { h.onFailed = fn }
+
+func (h *InboundProcessHandler) ProcessTask(_ context.Context, t *asynq.Task) error {
+ var payload InboundProcessPayload
+ if err := json.Unmarshal(t.Payload(), &payload); err != nil {
+ return fmt.Errorf("unmarshal inbound payload: %w", err)
+ }
+
+ rec, err := h.repo.FindByID(payload.InboundEmailID)
+ if err != nil {
+ return fmt.Errorf("inbound email not found: %w", err)
+ }
+
+ headers := map[string]string{}
+ if rec.HeadersJSON != "" {
+ _ = json.Unmarshal([]byte(rec.HeadersJSON), &headers)
+ }
+
+ var stored []models.InboundAttachmentMeta
+ if rec.AttachmentsJSON != "" {
+ _ = json.Unmarshal([]byte(rec.AttachmentsJSON), &stored)
+ }
+
+ attachments := make([]InboundAttachmentView, 0, len(stored))
+ for i, a := range stored {
+ view := InboundAttachmentView{
+ Filename: a.Filename,
+ ContentType: a.ContentType,
+ Size: a.Size,
+ }
+ if a.StorageKey != "" && h.baseURL != "" {
+ view.URL = h.attachmentURL(rec.UUID, i)
+ }
+ attachments = append(attachments, view)
+ }
+
+ body := InboundWebhookPayload{
+ Event: "email.inbound",
+ Timestamp: time.Now().UTC().Format(time.RFC3339),
+ InboundID: rec.UUID,
+ From: rec.Sender,
+ To: []string(rec.Recipients),
+ Subject: rec.Subject,
+ TextBody: rec.TextBody,
+ HTMLBody: rec.HTMLBody,
+ Headers: headers,
+ Attachments: attachments,
+ Size: rec.Size,
+ MessageID: rec.MessageID,
+ Source: string(rec.Source),
+ ReceivedAt: rec.ReceivedAt.UTC().Format(time.RFC3339),
+ }
+
+ encoded, err := json.Marshal(body)
+ if err != nil {
+ return fmt.Errorf("marshal inbound webhook body: %w", err)
+ }
+
+ h.dispatcher.DispatchJSON(rec.UserID, "email.inbound", encoded, rec.Sender)
+
+ now := time.Now().UTC()
+ rec.Status = models.InboundStatusForwarded
+ rec.ForwardedAt = &now
+ rec.ErrorMessage = ""
+ if err := h.repo.Update(rec); err != nil {
+ logger.Error("failed to mark inbound forwarded", "id", rec.ID, "error", err)
+ }
+
+ if h.onForwarded != nil {
+ h.onForwarded()
+ }
+ return nil
+}
+
+// attachmentURL builds a signed URL for downloading an inbound attachment.
+// Format: {baseURL}/api/v1/inbound/attachments/{uuid}/{idx}?t={token}
+func (h *InboundProcessHandler) attachmentURL(uuid string, idx int) string {
+ token := SignInboundAttachmentToken(h.hmacKey, uuid, idx)
+ return fmt.Sprintf("%s/api/v1/inbound/attachments/%s/%d?t=%s", h.baseURL, uuid, idx, token)
+}
+
+// SignInboundAttachmentToken creates an HMAC-signed token authorizing access
+// to a specific inbound attachment.
+func SignInboundAttachmentToken(key []byte, uuid string, idx int) string {
+ payload := uuid + ":" + strconv.Itoa(idx)
+ mac := hmac.New(sha256.New, key)
+ mac.Write([]byte(payload))
+ return base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
+}
+
+// VerifyInboundAttachmentToken checks whether the provided token is valid for
+// the given (uuid, idx) pair.
+func VerifyInboundAttachmentToken(key []byte, uuid string, idx int, token string) bool {
+ expected := SignInboundAttachmentToken(key, uuid, idx)
+ return hmac.Equal([]byte(expected), []byte(token))
+}
+
+// InboundExhaustedErrorHandler marks inbound emails permanently failed once Asynq
+// exhausts retries for the inbound:process task.
+type InboundExhaustedErrorHandler struct {
+ repo *repositories.InboundEmailRepository
+ onFailed func()
+}
+
+func NewInboundExhaustedErrorHandler(repo *repositories.InboundEmailRepository, onFailed func()) *InboundExhaustedErrorHandler {
+ return &InboundExhaustedErrorHandler{repo: repo, onFailed: onFailed}
+}
+
+// ChainErrorHandlers returns an asynq.ErrorHandler that invokes each handler in
+// order. Each inner handler is expected to guard on task type and no-op otherwise.
+func ChainErrorHandlers(handlers ...asynq.ErrorHandler) asynq.ErrorHandler {
+ return asynq.ErrorHandlerFunc(func(ctx context.Context, t *asynq.Task, err error) {
+ for _, h := range handlers {
+ h.HandleError(ctx, t, err)
+ }
+ })
+}
+
+func (e *InboundExhaustedErrorHandler) HandleError(_ context.Context, t *asynq.Task, err error) {
+ if t.Type() != TypeInboundProcess {
+ return
+ }
+ var payload InboundProcessPayload
+ if jerr := json.Unmarshal(t.Payload(), &payload); jerr != nil {
+ logger.Error("inbound exhausted: unmarshal", "error", jerr)
+ return
+ }
+ rec, ferr := e.repo.FindByID(payload.InboundEmailID)
+ if ferr != nil {
+ return
+ }
+ rec.Status = models.InboundStatusFailed
+ rec.ErrorMessage = fmt.Sprintf("permanently failed after retries: %v", err)
+ _ = e.repo.Update(rec)
+ if e.onFailed != nil {
+ e.onFailed()
+ }
+ logger.Error("worker: inbound forward permanently failed", "id", rec.ID, "error", err)
+}
diff --git a/internal/worker/producer.go b/internal/worker/producer.go
index a25d2e9..1d33d03 100644
--- a/internal/worker/producer.go
+++ b/internal/worker/producer.go
@@ -18,6 +18,7 @@
package worker
import (
+ "errors"
"fmt"
"time"
@@ -85,16 +86,32 @@ func (p *Producer) EnqueueEmailSendAt(emailID uint, queue string, sendAt time.Ti
}
// EnqueueCampaignStart enqueues a campaign start task (fan-out to subscribers).
+// The TaskID is derived from the campaign ID so double-clicks and retries
+// collapse into a single Redis entry instead of fanning out twice.
func (p *Producer) EnqueueCampaignStart(campaignID uint) error {
- task, err := NewCampaignStartTask(campaignID, asynq.Queue(QueueBulk), asynq.MaxRetry(3))
+ task, err := NewCampaignStartTask(
+ campaignID,
+ asynq.Queue(QueueBulk),
+ asynq.MaxRetry(3),
+ asynq.TaskID(fmt.Sprintf("campaign:start:%d", campaignID)),
+ )
if err != nil {
return fmt.Errorf("failed to create campaign start task: %w", err)
}
- _, err = p.client.Enqueue(task)
- return err
+ if _, err := p.client.Enqueue(task); err != nil {
+ // asynq.ErrTaskIDConflict means the task is already pending: treat as success.
+ if errors.Is(err, asynq.ErrTaskIDConflict) {
+ return nil
+ }
+ return fmt.Errorf("failed to enqueue campaign start: %w", err)
+ }
+ return nil
}
-// EnqueueCampaignBatch enqueues a campaign batch processing task.
+// EnqueueCampaignBatch enqueues a campaign batch processing task. A per-run
+// random suffix keeps successive batches distinct while still letting us dedupe
+// the *first* kick-off from Send (callers that want dedupe pass delay=0 after
+// transitioning status atomically).
func (p *Producer) EnqueueCampaignBatch(campaignID uint, delay time.Duration) error {
opts := []asynq.Option{asynq.Queue(QueueBulk), asynq.MaxRetry(3)}
if delay > 0 {
@@ -108,6 +125,22 @@ func (p *Producer) EnqueueCampaignBatch(campaignID uint, delay time.Duration) er
return err
}
+// EnqueueInboundProcess enqueues an inbound-process task that dispatches the
+// email.inbound webhook for a received message.
+func (p *Producer) EnqueueInboundProcess(inboundEmailID uint) error {
+ task, err := NewInboundProcessTask(inboundEmailID,
+ asynq.Queue(QueueTransactional),
+ asynq.MaxRetry(p.maxRetries),
+ )
+ if err != nil {
+ return fmt.Errorf("failed to create inbound task: %w", err)
+ }
+ if _, err := p.client.Enqueue(task); err != nil {
+ return fmt.Errorf("failed to enqueue inbound 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 f5102a5..e24451f 100644
--- a/internal/worker/tasks.go
+++ b/internal/worker/tasks.go
@@ -24,9 +24,10 @@ import (
)
const (
- TypeEmailSend = "email:send"
- TypeCampaignStart = "campaign:start"
- TypeCampaignBatch = "campaign:batch"
+ TypeEmailSend = "email:send"
+ TypeCampaignStart = "campaign:start"
+ TypeCampaignBatch = "campaign:batch"
+ TypeInboundProcess = "inbound:process"
QueueTransactional = "transactional"
QueueBulk = "bulk"
@@ -65,3 +66,17 @@ func NewCampaignBatchTask(campaignID uint, opts ...asynq.Option) (*asynq.Task, e
}
return asynq.NewTask(TypeCampaignBatch, payload, opts...), nil
}
+
+type InboundProcessPayload struct {
+ InboundEmailID uint `json:"inbound_email_id"`
+}
+
+// NewInboundProcessTask creates an Asynq task to dispatch an inbound email's
+// email.inbound webhook to subscribers.
+func NewInboundProcessTask(id uint, opts ...asynq.Option) (*asynq.Task, error) {
+ payload, err := json.Marshal(InboundProcessPayload{InboundEmailID: id})
+ if err != nil {
+ return nil, err
+ }
+ return asynq.NewTask(TypeInboundProcess, payload, opts...), nil
+}
diff --git a/web/index.html b/web/index.html
index 1b2dae3..54573b7 100644
--- a/web/index.html
+++ b/web/index.html
@@ -4,6 +4,29 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#9333ea" />
+ <meta name="robots" content="noindex,nofollow" />
+ <meta name="author" content="Jonas Kaninda" />
+ <meta name="application-name" content="Posta" />
+ <meta name="apple-mobile-web-app-title" content="Posta" />
+ <meta name="apple-mobile-web-app-capable" content="yes" />
+ <meta name="mobile-web-app-capable" content="yes" />
+
+ <title>Posta — Self-Hosted Email Delivery & Inbound Platform</title>
+ <meta name="description" content="Posta dashboard — send and receive email through a simple HTTP API. Manage SMTP servers, templates, campaigns, subscribers, webhooks, tracking, and inbound mail." />
+
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="Posta" />
+ <meta property="og:locale" content="en_US" />
+ <meta property="og:title" content="Posta — Self-Hosted Email Delivery & Inbound Platform" />
+ <meta property="og:description" content="Dashboard for the Posta email platform: outbound + inbound email, templates, campaigns, webhooks, tracking, and OIDC/SSO." />
+ <meta property="og:image" content="/logo.png" />
+ <meta property="og:image:alt" content="Posta logo" />
+
+ <meta name="twitter:card" content="summary" />
+ <meta name="twitter:title" content="Posta — Self-Hosted Email Delivery Platform" />
+ <meta name="twitter:description" content="Send and receive email through a simple HTTP API. Open-source, self-hosted." />
+ <meta name="twitter:image" content="/logo.png" />
+
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link rel="icon" type="image/png" sizes="96x96" href="/favicon-96x96.png" />
<link rel="icon" type="image/x-icon" href="/favicon.ico" />
@@ -12,7 +35,6 @@
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet" />
- <title>Posta — Self-hosted Email delivery platform</title>
</head>
<body>
<div id="app"></div>
diff --git a/web/src/api/admin.ts b/web/src/api/admin.ts
index 0de427b..04b99d2 100644
--- a/web/src/api/admin.ts
+++ b/web/src/api/admin.ts
@@ -8,7 +8,7 @@ export const adminApi = {
createUser(name: string, email: string, password: string, role: string) {
return api.post<ApiResponse<User>>('/admin/users', { name, email, password, role })
},
- updateUser(id: number, data: { role?: string; active?: boolean }) {
+ updateUser(id: number, data: { role?: string; active?: boolean; email_verified?: boolean }) {
return api.put<ApiResponse<User>>(`/admin/users/${id}`, data)
},
deleteUser(id: number) {
diff --git a/web/src/api/analytics.ts b/web/src/api/analytics.ts
index ef7b662..a01131a 100644
--- a/web/src/api/analytics.ts
+++ b/web/src/api/analytics.ts
@@ -1,5 +1,5 @@
import api from './client'
-import type { ApiResponse, AnalyticsResponse, DashboardAnalyticsResponse } from './types'
+import type { ApiResponse, AnalyticsResponse, DashboardAnalyticsResponse, ProviderBreakdownResponse } from './types'
export const analyticsApi = {
user(from?: string, to?: string, status?: string) {
@@ -28,4 +28,16 @@ export const analyticsApi = {
if (to) params.to = to
return api.get<ApiResponse<DashboardAnalyticsResponse>>('/admin/analytics/dashboard', { params })
},
+ providerBreakdown(from?: string, to?: string) {
+ const params: Record<string, string> = {}
+ if (from) params.from = from
+ if (to) params.to = to
+ return api.get<ApiResponse<ProviderBreakdownResponse>>('/users/me/analytics/providers', { params })
+ },
+ adminProviderBreakdown(from?: string, to?: string) {
+ const params: Record<string, string> = {}
+ if (from) params.from = from
+ if (to) params.to = to
+ return api.get<ApiResponse<ProviderBreakdownResponse>>('/admin/analytics/providers', { params })
+ },
}
diff --git a/web/src/api/auth.ts b/web/src/api/auth.ts
index 9ddb2a1..babdfc5 100644
--- a/web/src/api/auth.ts
+++ b/web/src/api/auth.ts
@@ -40,6 +40,12 @@ export const authApi = {
registrationStatus() {
return api.get<ApiResponse<{ registration_enabled: boolean }>>('/auth/registration-status')
},
+ verifyEmail(token: string) {
+ return api.get<ApiResponse<{ message: string }>>(`/auth/verify-email?token=${encodeURIComponent(token)}`)
+ },
+ resendVerificationEmail() {
+ return api.post<ApiResponse<{ message: string }>>('/users/me/verify-email/resend')
+ },
getMyPlan() {
return api.get<ApiResponse<Plan | null>>('/users/me/plan')
},
diff --git a/web/src/api/inbound.ts b/web/src/api/inbound.ts
new file mode 100644
index 0000000..ede5a51
--- /dev/null
+++ b/web/src/api/inbound.ts
@@ -0,0 +1,44 @@
+import api from './client'
+import type { ApiResponse, PaginatedResponse, InboundEmail } from './types'
+
+export interface InboundListParams {
+ page?: number
+ size?: number
+ status?: string
+ source?: string
+ sender?: string
+ q?: string
+}
+
+export interface InboundRetryResponse {
+ id: string
+ status: string
+}
+
+export const inboundApi = {
+ list(params: InboundListParams = {}) {
+ return api.get<PaginatedResponse<InboundEmail>>('/users/me/inbound-emails', {
+ params: { page: 0, size: 20, ...params },
+ })
+ },
+ get(uuid: string) {
+ return api.get<ApiResponse<InboundEmail>>(`/users/me/inbound-emails/${uuid}`)
+ },
+ delete(uuid: string) {
+ return api.delete<ApiResponse<void>>(`/users/me/inbound-emails/${uuid}`)
+ },
+ retry(uuid: string) {
+ return api.post<ApiResponse<InboundRetryResponse>>(`/users/me/inbound-emails/${uuid}/retry`)
+ },
+ rawUrl(uuid: string) {
+ return `/api/v1/users/me/inbound-emails/${uuid}/raw`
+ },
+ attachmentUrl(uuid: string, idx: number) {
+ return `/api/v1/users/me/inbound-emails/${uuid}/attachments/${idx}`
+ },
+ streamUrl(token?: string) {
+ const t = token ?? localStorage.getItem('posta_token') ?? ''
+ const qs = t ? `?token=${encodeURIComponent(t)}` : ''
+ return `/api/v1/users/me/inbound-stream${qs}`
+ },
+}
diff --git a/web/src/api/oauth.ts b/web/src/api/oauth.ts
index efc88b0..22b98f9 100644
--- a/web/src/api/oauth.ts
+++ b/web/src/api/oauth.ts
@@ -5,13 +5,17 @@ import type {
OAuthLinkedAccount,
OAuthProviderAdmin,
OAuthProviderInput,
+ SSODiscovery,
WorkspaceSSOConfig,
} from './types'
export const oauthApi = {
// Public
providers() {
- return api.get<ApiResponse<{ providers: OAuthProviderInfo[] }>>('/auth/oauth/providers')
+ return api.get<ApiResponse<{ providers: OAuthProviderInfo[]; sso_available: boolean }>>('/auth/oauth/providers')
+ },
+ discoverSSO(email: string) {
+ return api.post<ApiResponse<SSODiscovery>>('/auth/oauth/discover', { email })
},
// Linked accounts (authenticated user)
diff --git a/web/src/api/types.ts b/web/src/api/types.ts
index bf281a5..9ee5b2e 100644
--- a/web/src/api/types.ts
+++ b/web/src/api/types.ts
@@ -36,6 +36,7 @@ export interface User {
auth_method: string
plan_id: number | null
scheduled_deletion_at: string | null
+ email_verified_at: string | null
created_at: string
last_login_at: string | null
}
@@ -54,6 +55,7 @@ export interface Email {
sender: string
recipients: string[]
subject: string
+ template_name?: string
html_body: string
text_body: string
attachments_json: string
@@ -66,6 +68,44 @@ export interface Email {
created_at: string
sent_at: string | null
scheduled_at: string | null
+ provider?: string
+}
+
+export type InboundEmailStatus = 'received' | 'forwarded' | 'failed' | 'rejected'
+export type InboundSource = 'smtp' | 'webhook'
+
+export interface InboundAttachmentMeta {
+ filename: string
+ content_type: string
+ size: number
+ storage_key?: string
+ content?: string
+}
+
+export interface InboundEmail {
+ id: number
+ uuid: string
+ user_id: number
+ workspace_id?: number | null
+ domain_id: number
+ message_id: string
+ sender: string
+ recipients: string[]
+ subject: string
+ text_body: string
+ html_body: string
+ attachments_json: string
+ headers_json: string
+ raw_storage_key?: string
+ size: number
+ spam_score?: number | null
+ status: InboundEmailStatus
+ source: InboundSource
+ error_message?: string
+ retry_count: number
+ received_at: string
+ forwarded_at?: string | null
+ created_at: string
}
export interface ApiKey {
@@ -385,6 +425,9 @@ export interface DashboardStats {
total_suppressions: number
total_webhooks: number
total_contact_lists: number
+ total_inbound?: number
+ forwarded_inbound?: number
+ failed_inbound?: number
daily_volume: DailyVolume[]
webhook_deliveries: WebhookDeliveryStats | null
}
@@ -412,6 +455,11 @@ export interface AdminMetrics {
shared_smtp_servers: number
total_domains: number
total_workspaces: number
+ total_inbound?: number
+ forwarded_inbound?: number
+ failed_inbound?: number
+ received_inbound?: number
+ rejected_inbound?: number
webhook_deliveries: WebhookDeliveryStats | null
server_uptime_seconds: number
current_goroutines: number
@@ -466,6 +514,9 @@ export interface UserDetailMetrics {
total_suppressions: number
total_domains: number
total_smtp_servers: number
+ total_inbound?: number
+ forwarded_inbound?: number
+ failed_inbound?: number
webhook_deliveries: WebhookDeliveryStats | null
}
@@ -515,6 +566,19 @@ export interface DashboardAnalyticsResponse {
latency_percentiles: LatencyPercentiles
}
+export interface ProviderBreakdownPoint {
+ provider: string
+ sent: number
+ failed: number
+ bounced: number
+ total: number
+ delivery_rate: number
+}
+
+export interface ProviderBreakdownResponse {
+ providers: ProviderBreakdownPoint[]
+}
+
// Contact Lists
export interface ContactList {
id: number
@@ -590,6 +654,7 @@ export interface Setup2FAResponse {
export interface UserProfile extends User {
require_verified_domain: boolean
scheduled_deletion_at: string | null
+ email_verification_required: boolean
}
// User Data Export/Import
@@ -796,6 +861,7 @@ export interface OAuthProviderAdmin {
issuer: string
scopes: string
enabled: boolean
+ hidden: boolean
auto_register: boolean
allowed_domains: string
created_at: string
@@ -813,9 +879,16 @@ export interface OAuthProviderInput {
userinfo_url?: string
scopes?: string
auto_register?: boolean
+ hidden?: boolean
allowed_domains?: string
}
+export interface SSODiscovery {
+ slug: string
+ name: string
+ type: string
+}
+
export interface WorkspaceSSOConfig {
provider_id: number
provider_name: string
diff --git a/web/src/assets/styles.css b/web/src/assets/styles.css
index cdbc43c..11363e8 100644
--- a/web/src/assets/styles.css
+++ b/web/src/assets/styles.css
@@ -534,18 +534,105 @@ tr:hover td { background: var(--bg-hover); }
}
/* ─── DNS Records ─── */
+.dns-panel { display: flex; flex-direction: column; gap: 16px; }
+.dns-panel-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: flex-start;
+ gap: 16px;
+ flex-wrap: wrap;
+}
+.dns-panel-title { margin: 0 0 4px 0; font-size: 15px; font-weight: 600; color: var(--text-primary); }
+.dns-panel-subtitle { margin: 0; font-size: 13px; color: var(--text-secondary); max-width: 640px; line-height: 1.5; }
+.dns-panel-actions { display: flex; gap: 8px; flex-shrink: 0; }
+
+.dns-record-list { display: flex; flex-direction: column; gap: 12px; }
+
.dns-record {
- background: var(--bg-tertiary);
+ background: var(--bg-primary);
border: 1px solid var(--border-primary);
border-radius: var(--radius);
- padding: 14px 16px;
- margin-bottom: 10px;
+ padding: 16px;
}
-.dns-record .dns-label { font-size: 12px; font-weight: 600; color: var(--text-secondary); margin-bottom: 4px; }
-.dns-record .dns-type { font-size: 11px; font-weight: 700; color: var(--primary-500); text-transform: uppercase; letter-spacing: 0.06em; }
-.dns-record .dns-name { font-size: 13px; color: var(--text-tertiary); margin-top: 2px; }
-.dns-record .dns-value { font-size: 13px; font-family: 'JetBrains Mono', monospace; color: var(--text-primary); margin-top: 6px; word-break: break-all; }
.dns-record-highlight { border-color: var(--primary-300); background: var(--primary-50, rgba(79, 70, 229, 0.04)); }
+.dns-record-verified { border-color: var(--success-300, #86efac); background: var(--success-50, rgba(34, 197, 94, 0.04)); }
+
+.dns-record-head {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ gap: 12px;
+ margin-bottom: 4px;
+}
+.dns-record-head-left { display: flex; align-items: center; gap: 10px; }
+.dns-record .dns-label { font-size: 13px; font-weight: 600; color: var(--text-primary); }
+.dns-type-badge {
+ display: inline-block;
+ font-size: 11px;
+ font-weight: 700;
+ padding: 2px 8px;
+ border-radius: 999px;
+ background: var(--primary-100, rgba(79, 70, 229, 0.1));
+ color: var(--primary-600, var(--primary-500));
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+}
+.dns-status {
+ font-size: 11px;
+ font-weight: 600;
+ padding: 3px 10px;
+ border-radius: 999px;
+ white-space: nowrap;
+}
+.dns-status-ok { background: var(--success-100, rgba(34, 197, 94, 0.12)); color: var(--success-700, #15803d); }
+.dns-status-pending { background: var(--bg-tertiary); color: var(--text-secondary); }
+
+.dns-record-desc { margin: 2px 0 12px 0; font-size: 12px; color: var(--text-secondary); line-height: 1.5; }
+
+.dns-field { margin-top: 10px; }
+.dns-field-label {
+ font-size: 11px;
+ font-weight: 600;
+ color: var(--text-tertiary);
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ margin-bottom: 4px;
+}
+.dns-field-row { display: flex; align-items: flex-start; gap: 8px; }
+.dns-field-value {
+ flex: 1;
+ font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace;
+ font-size: 12.5px;
+ color: var(--text-primary);
+ background: var(--bg-tertiary);
+ border: 1px solid var(--border-primary);
+ border-radius: var(--radius-sm, 6px);
+ padding: 6px 10px;
+ word-break: break-all;
+ user-select: all;
+}
+.dns-field-value-block { white-space: pre-wrap; }
+.dns-field-hint { margin-top: 6px; font-size: 12px; color: var(--text-tertiary); line-height: 1.5; }
+.dns-field-hint code {
+ background: var(--bg-tertiary);
+ padding: 1px 5px;
+ border-radius: 4px;
+ font-size: 11.5px;
+}
+.dns-ttl-hint { margin-top: 10px; padding-top: 10px; border-top: 1px dashed var(--border-primary); }
+
+.btn-ghost {
+ background: transparent;
+ border: 1px solid var(--border-primary);
+ color: var(--text-secondary);
+}
+.btn-ghost:hover { background: var(--bg-tertiary); color: var(--text-primary); }
+.btn-xs {
+ font-size: 11px;
+ padding: 4px 10px;
+ line-height: 1.2;
+ height: auto;
+}
/* ─── Status ─── */
.verified { color: var(--success-600); }
diff --git a/web/src/components/DomainStatusBadge.vue b/web/src/components/DomainStatusBadge.vue
new file mode 100644
index 0000000..024bad0
--- /dev/null
+++ b/web/src/components/DomainStatusBadge.vue
@@ -0,0 +1,48 @@
+<script setup lang="ts">
+import { computed } from 'vue'
+import type { Domain } from '../api/types'
+
+const props = defineProps<{
+ domain: Domain
+ size?: 'sm' | 'md'
+}>()
+
+const checks = computed(() => [
+ props.domain.ownership_verified,
+ props.domain.spf_verified,
+ props.domain.dkim_verified,
+ props.domain.dmarc_verified,
+])
+
+const verifiedCount = computed(() => checks.value.filter(Boolean).length)
+const total = 4
+
+const status = computed(() => {
+ if (verifiedCount.value === total) return 'verified'
+ if (verifiedCount.value === 0) return 'unverified'
+ return 'partial'
+})
+
+const label = computed(() => {
+ if (status.value === 'verified') return 'Fully verified'
+ if (status.value === 'unverified') return 'Not verified'
+ return `${verifiedCount.value} of ${total} verified`
+})
+
+const icon = computed(() => {
+ if (status.value === 'verified') return '✓'
+ if (status.value === 'unverified') return '○'
+ return '◐'
+})
+</script>
+
+<template>
+ <span
+ class="status-pill"
+ :class="[`status-pill-${status}`, size === 'sm' ? 'status-pill-sm' : '']"
+ :title="`Ownership: ${domain.ownership_verified ? 'yes' : 'no'} · SPF: ${domain.spf_verified ? 'yes' : 'no'} · DKIM: ${domain.dkim_verified ? 'yes' : 'no'} · DMARC: ${domain.dmarc_verified ? 'yes' : 'no'}`"
+ >
+ <span class="status-pill-icon">{{ icon }}</span>
+ <span>{{ label }}</span>
+ </span>
+</template>
diff --git a/web/src/components/EmailVerificationBanner.vue b/web/src/components/EmailVerificationBanner.vue
new file mode 100644
index 0000000..5016e12
--- /dev/null
+++ b/web/src/components/EmailVerificationBanner.vue
@@ -0,0 +1,78 @@
+<script setup lang="ts">
+import { computed, ref } from 'vue'
+import { authApi } from '../api/auth'
+import { useAuthStore } from '../stores/auth'
+import { useNotificationStore } from '../stores/notification'
+
+const auth = useAuthStore()
+const notification = useNotificationStore()
+const sending = ref(false)
+
+const unverified = computed(() => {
+ const u: any = auth.user
+ if (!u) return false
+ // Only nag when the backend says verification is enforced.
+ if (u.email_verification_required === false) return false
+ return !u.email_verified_at
+})
+
+async function resend() {
+ sending.value = true
+ try {
+ await authApi.resendVerificationEmail()
+ notification.success('Verification email sent. Check your inbox.')
+ } catch (err: any) {
+ const msg =
+ err?.response?.data?.error?.message ||
+ err?.response?.data?.error ||
+ err?.message ||
+ 'Failed to send verification email.'
+ notification.error(msg)
+ } finally {
+ sending.value = false
+ }
+}
+</script>
+
+<template>
+ <div v-if="unverified" class="verify-banner">
+ <span class="verify-banner-text">
+ Your email is not verified. Some actions (inviting members, creating API keys) are blocked until you confirm your address.
+ </span>
+ <button class="verify-banner-btn" :disabled="sending" @click="resend">
+ {{ sending ? 'Sending…' : 'Resend email' }}
+ </button>
+ </div>
+</template>
+
+<style scoped>
+.verify-banner {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 16px;
+ padding: 10px 16px;
+ margin: 12px 16px 0;
+ background: var(--warning-50, #fffbeb);
+ border: 1px solid var(--warning-200, #fde68a);
+ color: var(--warning-900, #78350f);
+ border-radius: 6px;
+ font-size: 13px;
+}
+.verify-banner-text { flex: 1; }
+.verify-banner-btn {
+ padding: 6px 12px;
+ border-radius: 4px;
+ border: 1px solid var(--warning-400, #fbbf24);
+ background: var(--warning-100, #fef3c7);
+ color: var(--warning-900, #78350f);
+ font-size: 12px;
+ font-weight: 500;
+ cursor: pointer;
+ white-space: nowrap;
+}
+.verify-banner-btn:disabled {
+ opacity: 0.6;
+ cursor: not-allowed;
+}
+</style>
diff --git a/web/src/layouts/DashboardLayout.vue b/web/src/layouts/DashboardLayout.vue
index 4aae26c..e242d5d 100644
--- a/web/src/layouts/DashboardLayout.vue
+++ b/web/src/layouts/DashboardLayout.vue
@@ -5,6 +5,7 @@ import { useAuthStore } from '../stores/auth'
import { useThemeStore } from '../stores/theme'
import { useWorkspaceStore } from '../stores/workspace'
import { infoApi, type AppInfo } from '../api/info'
+import EmailVerificationBanner from '../components/EmailVerificationBanner.vue'
const router = useRouter()
const route = useRoute()
@@ -57,6 +58,7 @@ const navItems = [
{ name: 'Dashboard', path: '/', icon: 'grid' },
{ name: 'Analytics', path: '/analytics', icon: 'bar-chart' },
{ name: 'Emails', path: '/emails', icon: 'mail' },
+ { name: 'Inbound', path: '/inbound-emails', icon: 'inbox' },
{ name: 'Templates', path: '/templates', icon: 'file-text' },
{ name: 'Languages', path: '/languages', icon: 'type' },
{ name: 'Stylesheets', path: '/stylesheets', icon: 'edit-3' },
@@ -116,7 +118,7 @@ function logout() {
<div class="sidebar-brand">
<div class="logo" @click="navigate('/')">
<img src="/logo.png" alt="Posta" class="logo-img" />
- <span v-if="!sidebarCollapsed" class="logo-text">Posta</span>
+ <span v-if="!sidebarCollapsed" class="logo-text">Posta<span class="logo-text-dot">.</span></span>
</div>
<button class="collapse-btn" @click="toggleSidebar" :title="sidebarCollapsed ? 'Expand' : 'Collapse'">
<svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path :d="sidebarCollapsed ? 'M6 3l5 5-5 5' : 'M10 3L5 8l5 5'" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
@@ -252,6 +254,7 @@ function logout() {
</div>
</header>
<div class="main-body">
+ <EmailVerificationBanner />
<router-view />
</div>
<footer class="main-footer">
@@ -277,6 +280,7 @@ function getIcon(name: string): string {
const icons: Record<string, string> = {
'grid': '<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><rect x="1.5" y="1.5" width="6" height="6" rx="1.5" stroke="currentColor" stroke-width="1.5"/><rect x="10.5" y="1.5" width="6" height="6" rx="1.5" stroke="currentColor" stroke-width="1.5"/><rect x="1.5" y="10.5" width="6" height="6" rx="1.5" stroke="currentColor" stroke-width="1.5"/><rect x="10.5" y="10.5" width="6" height="6" rx="1.5" stroke="currentColor" stroke-width="1.5"/></svg>',
'mail': '<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><rect x="2" y="3.5" width="14" height="11" rx="2" stroke="currentColor" stroke-width="1.5"/><path d="M2 5.5l7 5 7-5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',
+ 'inbox': '<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M16.5 10.5H13.5l-1.5 2.25h-6L4.5 10.5H1.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M4.1 3.2L1.5 10.5v4.5A1.5 1.5 0 003 16.5h12a1.5 1.5 0 001.5-1.5v-4.5l-2.6-7.3A1.5 1.5 0 0012.48 2.25H5.52a1.5 1.5 0 00-1.42 1.05z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',
'key': '<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M15.5 2.5l-2 2m1 1l-2 2-3-3 2-2m-3.18 3.18a4 4 0 10-5.64 5.64 4 4 0 005.64-5.64z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',
'file-text': '<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M10.5 1.5H4.5a1.5 1.5 0 00-1.5 1.5v12a1.5 1.5 0 001.5 1.5h9a1.5 1.5 0 001.5-1.5V6l-4.5-4.5z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M10.5 1.5V6H15M12 9.75H6M12 12.75H6M7.5 6.75H6" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',
'server': '<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><rect x="2" y="2" width="14" height="5" rx="1.5" stroke="currentColor" stroke-width="1.5"/><rect x="2" y="11" width="14" height="5" rx="1.5" stroke="currentColor" stroke-width="1.5"/><circle cx="5" cy="4.5" r="0.75" fill="currentColor"/><circle cx="5" cy="13.5" r="0.75" fill="currentColor"/></svg>',
@@ -351,6 +355,10 @@ export default { methods: { getIcon } }
color: var(--sidebar-text-active);
letter-spacing: -0.5px;
}
+.logo-text-dot {
+ color: var(--primary-500);
+ margin-left: 1px;
+}
/* Workspace Switcher */
.ws-switcher {
diff --git a/web/src/router/index.ts b/web/src/router/index.ts
index dac05f4..c40eab1 100644
--- a/web/src/router/index.ts
+++ b/web/src/router/index.ts
@@ -1,82 +1,100 @@
import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '../stores/auth'
+const APP_NAME = 'Posta'
+const DEFAULT_TITLE = 'Posta — Self-Hosted Email Delivery & Inbound Platform'
+
const routes = [
{
path: '/login',
name: 'login',
component: () => import('../views/auth/Login.vue'),
- meta: { guest: true },
+ meta: { guest: true, title: 'Sign in' },
},
{
path: '/register',
name: 'register',
component: () => import('../views/auth/Register.vue'),
- meta: { guest: true },
+ meta: { guest: true, title: 'Create an account' },
},
{
path: '/auth/oauth/callback',
name: 'oauth-callback',
component: () => import('../views/auth/OAuthCallback.vue'),
- meta: { guest: true },
+ meta: { guest: true, title: 'Signing you in…' },
+ },
+ {
+ path: '/invitations',
+ name: 'invitation-accept',
+ component: () => import('../views/invitations/InvitationAccept.vue'),
+ meta: { title: 'Workspace Invitation' },
+ },
+ {
+ path: '/auth/verify-email',
+ name: 'verify-email',
+ component: () => import('../views/auth/VerifyEmail.vue'),
+ meta: { title: 'Verify email' },
},
{
path: '/',
component: () => import('../layouts/DashboardLayout.vue'),
meta: { auth: true },
children: [
- { path: '', name: 'dashboard', component: () => import('../views/dashboard/Dashboard.vue') },
- { path: 'api-keys', name: 'api-keys', component: () => import('../views/apikeys/ApiKeys.vue') },
- { path: 'emails', name: 'emails', component: () => import('../views/emails/Emails.vue') },
- { path: 'emails/:id', name: 'email-detail', component: () => import('../views/emails/EmailDetail.vue') },
- { path: 'templates', name: 'templates', component: () => import('../views/templates/Templates.vue') },
- { path: 'templates/preview', name: 'template-preview-general', component: () => import('../views/emails/EmailPreview.vue') },
- { path: 'templates/:id/preview', name: 'template-preview', component: () => import('../views/templates/TemplatePreview.vue') },
- { path: 'templates/:id/versions', name: 'template-detail', component: () => import('../views/templates/TemplateDetail.vue') },
- { path: 'templates/:id/versions/:versionId/localizations/:localizationId/edit', name: 'template-editor', component: () => import('../views/templates/TemplateEditor.vue') },
- { path: 'templates/:id/versions/:versionId/localizations/:localizationId/builder', name: 'template-builder', component: () => import('../views/templates/EmailBuilder.vue') },
- { path: 'languages', name: 'languages', component: () => import('../views/languages/Languages.vue') },
- { path: 'stylesheets', name: 'stylesheets', component: () => import('../views/stylesheets/Stylesheets.vue') },
- { path: 'smtp-servers', name: 'smtp-servers', component: () => import('../views/smtp/SmtpServers.vue') },
- { path: 'smtp-servers/:id', name: 'smtp-server-detail', component: () => import('../views/smtp/SmtpServerDetail.vue') },
- { path: 'domains', name: 'domains', component: () => import('../views/domains/Domains.vue') },
- { path: 'webhooks', name: 'webhooks', component: () => import('../views/webhooks/Webhooks.vue') },
- { path: 'webhook-deliveries', name: 'webhook-deliveries', component: () => import('../views/webhooks/WebhookDeliveries.vue') },
- { path: 'bounces', name: 'bounces', component: () => import('../views/bounces/Bounces.vue') },
- { path: 'contacts', name: 'contacts', component: () => import('../views/contacts/Contacts.vue') },
- { path: 'contacts/:id', name: 'contact-detail', component: () => import('../views/contacts/ContactDetail.vue') },
- { path: 'subscribers', name: 'subscribers', component: () => import('../views/subscribers/Subscribers.vue') },
- { path: 'subscribers/:id', name: 'subscriber-detail', component: () => import('../views/subscribers/SubscriberDetail.vue') },
- { path: 'subscriber-lists', name: 'subscriber-lists-page', component: () => import('../views/subscriber-lists/SubscriberLists.vue') },
- { path: 'subscriber-lists/:id', name: 'subscriber-list-detail', component: () => import('../views/subscriber-lists/SubscriberListDetail.vue') },
- { path: 'campaigns', name: 'campaigns', component: () => import('../views/campaigns/Campaigns.vue') },
- { path: 'campaigns/:id', name: 'campaign-detail', component: () => import('../views/campaigns/CampaignDetail.vue') },
- { path: 'analytics', name: 'analytics', component: () => import('../views/analytics/Analytics.vue') },
- { path: 'audit-log', name: 'audit-log', component: () => import('../views/audit/AuditLog.vue') },
- { path: 'settings', name: 'settings', component: () => import('../views/settings/Settings.vue') },
- { path: 'workspaces', name: 'workspaces', component: () => import('../views/workspaces/Workspaces.vue') },
- { path: 'workspaces/:id', name: 'workspace-detail', component: () => import('../views/workspaces/WorkspaceSettings.vue') },
- { path: 'about', name: 'about', component: () => import('../views/about/About.vue') },
- { path: 'profile', name: 'profile', component: () => import('../views/auth/Profile.vue') },
+ { path: '', name: 'dashboard', component: () => import('../views/dashboard/Dashboard.vue'), meta: { title: 'Dashboard' } },
+ { path: 'api-keys', name: 'api-keys', component: () => import('../views/apikeys/ApiKeys.vue'), meta: { title: 'API Keys' } },
+ { path: 'emails', name: 'emails', component: () => import('../views/emails/Emails.vue'), meta: { title: 'Emails' } },
+ { 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: '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' } },
+ { path: 'templates/:id/versions', name: 'template-detail', component: () => import('../views/templates/TemplateDetail.vue'), meta: { title: 'Template Versions' } },
+ { path: 'templates/:id/versions/:versionId/localizations/:localizationId/edit', name: 'template-editor', component: () => import('../views/templates/TemplateEditor.vue'), meta: { title: 'Template Editor' } },
+ { path: 'templates/:id/versions/:versionId/localizations/:localizationId/builder', name: 'template-builder', component: () => import('../views/templates/EmailBuilder.vue'), meta: { title: 'Email Builder' } },
+ { path: 'languages', name: 'languages', component: () => import('../views/languages/Languages.vue'), meta: { title: 'Languages' } },
+ { path: 'stylesheets', name: 'stylesheets', component: () => import('../views/stylesheets/Stylesheets.vue'), meta: { title: 'Stylesheets' } },
+ { path: 'smtp-servers', name: 'smtp-servers', component: () => import('../views/smtp/SmtpServers.vue'), meta: { title: 'SMTP Servers' } },
+ { path: 'smtp-servers/:id', name: 'smtp-server-detail', component: () => import('../views/smtp/SmtpServerDetail.vue'), meta: { title: 'SMTP Server' } },
+ { path: 'domains', name: 'domains', component: () => import('../views/domains/Domains.vue'), meta: { title: 'Domains' } },
+ { path: 'webhooks', name: 'webhooks', component: () => import('../views/webhooks/Webhooks.vue'), meta: { title: 'Webhooks' } },
+ { path: 'webhook-deliveries', name: 'webhook-deliveries', component: () => import('../views/webhooks/WebhookDeliveries.vue'), meta: { title: 'Webhook Deliveries' } },
+ { path: 'bounces', name: 'bounces', component: () => import('../views/bounces/Bounces.vue'), meta: { title: 'Bounces' } },
+ { path: 'contacts', name: 'contacts', component: () => import('../views/contacts/Contacts.vue'), meta: { title: 'Contacts' } },
+ { path: 'contacts/:id', name: 'contact-detail', component: () => import('../views/contacts/ContactDetail.vue'), meta: { title: 'Contact' } },
+ { path: 'subscribers', name: 'subscribers', component: () => import('../views/subscribers/Subscribers.vue'), meta: { title: 'Subscribers' } },
+ { path: 'subscribers/:id', name: 'subscriber-detail', component: () => import('../views/subscribers/SubscriberDetail.vue'), meta: { title: 'Subscriber' } },
+ { path: 'subscriber-lists', name: 'subscriber-lists-page', component: () => import('../views/subscriber-lists/SubscriberLists.vue'), meta: { title: 'Subscriber Lists' } },
+ { path: 'subscriber-lists/:id', name: 'subscriber-list-detail', component: () => import('../views/subscriber-lists/SubscriberListDetail.vue'), meta: { title: 'Subscriber List' } },
+ { path: 'campaigns', name: 'campaigns', component: () => import('../views/campaigns/Campaigns.vue'), meta: { title: 'Campaigns' } },
+ { path: 'campaigns/:id', name: 'campaign-detail', component: () => import('../views/campaigns/CampaignDetail.vue'), meta: { title: 'Campaign' } },
+ { path: 'analytics', name: 'analytics', component: () => import('../views/analytics/Analytics.vue'), meta: { title: 'Analytics' } },
+ { path: 'audit-log', name: 'audit-log', component: () => import('../views/audit/AuditLog.vue'), meta: { title: 'Audit Log' } },
+ { path: 'settings', name: 'settings', component: () => import('../views/settings/Settings.vue'), meta: { title: 'Settings' } },
+ { path: 'workspaces', name: 'workspaces', component: () => import('../views/workspaces/Workspaces.vue'), meta: { title: 'Workspaces' } },
+ { path: 'workspaces/:id', name: 'workspace-detail', component: () => import('../views/workspaces/WorkspaceSettings.vue'), meta: { title: 'Workspace Settings' } },
+ { path: 'about', name: 'about', component: () => import('../views/about/About.vue'), meta: { title: 'About' } },
+ { path: 'profile', name: 'profile', component: () => import('../views/auth/Profile.vue'), meta: { title: 'Profile' } },
{ path: 'change-password', redirect: '/profile' },
// Admin
- { path: 'admin/users', name: 'admin-users', component: () => import('../views/admin/Users.vue'), meta: { admin: true } },
- { path: 'admin/users/:id', name: 'admin-user-detail', component: () => import('../views/admin/UserDetail.vue'), meta: { admin: true } },
- { path: 'admin/metrics', name: 'admin-metrics', component: () => import('../views/admin/Metrics.vue'), meta: { admin: true } },
- { path: 'admin/events', name: 'admin-events', component: () => import('../views/admin/Events.vue'), meta: { admin: true } },
- { path: 'admin/plans', name: 'admin-plans', component: () => import('../views/admin/Plans.vue'), meta: { admin: true } },
- { path: 'admin/plans/:id', name: 'admin-plan-detail', component: () => import('../views/admin/PlanDetail.vue'), meta: { admin: true } },
- { path: 'admin/servers', name: 'admin-servers', component: () => import('../views/admin/Servers.vue'), meta: { admin: true } },
- { path: 'admin/servers/:id', name: 'admin-server-detail', component: () => import('../views/admin/ServerDetail.vue'), meta: { admin: true } },
- { path: 'admin/jobs', name: 'admin-jobs', component: () => import('../views/admin/Jobs.vue'), meta: { admin: true } },
- { path: 'admin/oauth', name: 'admin-oauth', component: () => import('../views/admin/OAuthProviders.vue'), meta: { admin: true } },
- { path: 'admin/settings', name: 'admin-settings', component: () => import('../views/admin/Settings.vue'), meta: { admin: true } },
+ { path: 'admin/users', name: 'admin-users', component: () => import('../views/admin/Users.vue'), meta: { admin: true, title: 'Admin · Users' } },
+ { path: 'admin/users/:id', name: 'admin-user-detail', component: () => import('../views/admin/UserDetail.vue'), meta: { admin: true, title: 'Admin · User' } },
+ { path: 'admin/metrics', name: 'admin-metrics', component: () => import('../views/admin/Metrics.vue'), meta: { admin: true, title: 'Admin · Metrics' } },
+ { path: 'admin/events', name: 'admin-events', component: () => import('../views/admin/Events.vue'), meta: { admin: true, title: 'Admin · Events' } },
+ { path: 'admin/plans', name: 'admin-plans', component: () => import('../views/admin/Plans.vue'), meta: { admin: true, title: 'Admin · Plans' } },
+ { path: 'admin/plans/:id', name: 'admin-plan-detail', component: () => import('../views/admin/PlanDetail.vue'), meta: { admin: true, title: 'Admin · Plan' } },
+ { path: 'admin/servers', name: 'admin-servers', component: () => import('../views/admin/Servers.vue'), meta: { admin: true, title: 'Admin · Servers' } },
+ { path: 'admin/servers/:id', name: 'admin-server-detail', component: () => import('../views/admin/ServerDetail.vue'), meta: { admin: true, title: 'Admin · Server' } },
+ { path: 'admin/jobs', name: 'admin-jobs', component: () => import('../views/admin/Jobs.vue'), meta: { admin: true, title: 'Admin · Jobs' } },
+ { path: 'admin/oauth', name: 'admin-oauth', component: () => import('../views/admin/OAuthProviders.vue'), meta: { admin: true, title: 'Admin · OAuth Providers' } },
+ { path: 'admin/settings', name: 'admin-settings', component: () => import('../views/admin/Settings.vue'), meta: { admin: true, title: 'Admin · Settings' } },
],
},
{
path: '/:pathMatch(.*)*',
name: 'not-found',
component: () => import('../views/NotFound.vue'),
+ meta: { title: 'Page not found' },
},
]
@@ -99,4 +117,9 @@ router.beforeEach((to) => {
}
})
+router.afterEach((to) => {
+ const pageTitle = to.meta.title as string | undefined
+ document.title = pageTitle ? `${pageTitle} · ${APP_NAME}` : DEFAULT_TITLE
+})
+
export default router
diff --git a/web/src/stores/auth.ts b/web/src/stores/auth.ts
index 24ca317..b6df7b0 100644
--- a/web/src/stores/auth.ts
+++ b/web/src/stores/auth.ts
@@ -5,7 +5,7 @@ import type { User, UserProfile, AuthResponse } from '../api/types'
export const useAuthStore = defineStore('auth', () => {
const token = ref(localStorage.getItem('posta_token') || '')
- const user = ref<User | null>(JSON.parse(localStorage.getItem('posta_user') || 'null'))
+ const user = ref<User | UserProfile | null>(JSON.parse(localStorage.getItem('posta_user') || 'null'))
const isAuthenticated = computed(() => !!token.value)
const isAdmin = computed(() => user.value?.role === 'admin')
@@ -17,6 +17,8 @@ export const useAuthStore = defineStore('auth', () => {
throw { requires2FA: true }
}
setAuth(res.data.data)
+ // Refresh to pick up extended profile fields (email_verified_at, etc).
+ await fetchUser()
return res.data.data
}
diff --git a/web/src/views/admin/Metrics.vue b/web/src/views/admin/Metrics.vue
index 7b8cf1f..49a5bee 100644
--- a/web/src/views/admin/Metrics.vue
+++ b/web/src/views/admin/Metrics.vue
@@ -421,6 +421,59 @@ const avgDeliveryRate = computed(() => {
</div>
</div>
+ <!-- Inbound Email Metrics -->
+ <div class="metrics-section-label">Inbound Email</div>
+ <div class="stats-grid" style="margin-bottom: 28px;">
+ <div class="stat-card">
+ <div class="stat-header">
+ <div class="stat-label">Total Inbound</div>
+ <div class="stat-icon stat-icon-info">
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="22 12 16 12 14 15 10 15 8 12 2 12"/><path d="M5.45 5.11L2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"/></svg>
+ </div>
+ </div>
+ <div class="stat-value">{{ metrics.total_inbound ?? 0 }}</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-header">
+ <div class="stat-label">Forwarded</div>
+ <div class="stat-icon stat-icon-success">
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
+ </div>
+ </div>
+ <div class="stat-value">{{ metrics.forwarded_inbound ?? 0 }}</div>
+ <div class="stat-sub">Delivered to user webhooks</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-header">
+ <div class="stat-label">Failed</div>
+ <div class="stat-icon stat-icon-danger">
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>
+ </div>
+ </div>
+ <div class="stat-value">{{ metrics.failed_inbound ?? 0 }}</div>
+ <div class="stat-sub">Webhook dispatch exhausted retries</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-header">
+ <div class="stat-label">Received (pending)</div>
+ <div class="stat-icon stat-icon-info">
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
+ </div>
+ </div>
+ <div class="stat-value">{{ metrics.received_inbound ?? 0 }}</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-header">
+ <div class="stat-label">Rejected</div>
+ <div class="stat-icon stat-icon-warning">
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="4.93" y1="4.93" x2="19.07" y2="19.07"/></svg>
+ </div>
+ </div>
+ <div class="stat-value">{{ metrics.rejected_inbound ?? 0 }}</div>
+ <div class="stat-sub">Unverified domain / suppressed / too large</div>
+ </div>
+ </div>
+
<!-- Email delivery progress bar -->
<div class="card" style="margin-bottom: 28px;">
<div class="card-body">
diff --git a/web/src/views/admin/OAuthProviders.vue b/web/src/views/admin/OAuthProviders.vue
index b6c1667..8b73a50 100644
--- a/web/src/views/admin/OAuthProviders.vue
+++ b/web/src/views/admin/OAuthProviders.vue
@@ -18,7 +18,7 @@ const form = ref({
client_id: '', client_secret: '', issuer: '',
auth_url: '', token_url: '', userinfo_url: '',
scopes: 'openid email profile',
- auto_register: true, allowed_domains: '',
+ auto_register: true, hidden: false, allowed_domains: '',
})
// Edit modal
@@ -28,7 +28,7 @@ const editingProvider = ref<OAuthProviderAdmin | null>(null)
const editForm = ref({
name: '', client_id: '', client_secret: '', issuer: '',
auth_url: '', token_url: '', userinfo_url: '',
- scopes: '', auto_register: true, allowed_domains: '',
+ scopes: '', auto_register: true, hidden: false, allowed_domains: '',
})
async function fetchProviders() {
@@ -54,7 +54,7 @@ async function createProvider() {
await oauthApi.adminCreate(form.value)
notify.success('Provider created')
showCreateModal.value = false
- form.value = { name: '', slug: '', type: 'oidc', client_id: '', client_secret: '', issuer: '', auth_url: '', token_url: '', userinfo_url: '', scopes: 'openid email profile', auto_register: true, allowed_domains: '' }
+ form.value = { name: '', slug: '', type: 'oidc', client_id: '', client_secret: '', issuer: '', auth_url: '', token_url: '', userinfo_url: '', scopes: 'openid email profile', auto_register: true, hidden: false, allowed_domains: '' }
await fetchProviders()
} catch (err: any) {
notify.error(err.response?.data?.error?.message || 'Failed to create provider')
@@ -75,6 +75,7 @@ function openEdit(p: OAuthProviderAdmin) {
userinfo_url: '',
scopes: p.scopes || '',
auto_register: p.auto_register,
+ hidden: p.hidden,
allowed_domains: p.allowed_domains || '',
}
showEditModal.value = true
@@ -91,6 +92,7 @@ async function updateProvider() {
if (editForm.value.issuer) data.issuer = editForm.value.issuer
if (editForm.value.scopes) data.scopes = editForm.value.scopes
data.auto_register = editForm.value.auto_register
+ data.hidden = editForm.value.hidden
data.allowed_domains = editForm.value.allowed_domains
await oauthApi.adminUpdate(editingProvider.value.id, data)
notify.success('Provider updated')
@@ -154,6 +156,7 @@ onMounted(fetchProviders)
<th>Slug</th>
<th>Type</th>
<th>Status</th>
+ <th>Visibility</th>
<th>Auto Register</th>
<th>Created</th>
<th>Actions</th>
@@ -165,6 +168,7 @@ onMounted(fetchProviders)
<td><code>{{ p.slug }}</code></td>
<td><span class="badge badge-neutral">{{ p.type }}</span></td>
<td><span class="badge" :class="p.enabled ? 'badge-primary' : 'badge-neutral'">{{ p.enabled ? 'enabled' : 'disabled' }}</span></td>
+ <td><span class="badge" :class="p.hidden ? 'badge-neutral' : 'badge-primary'">{{ p.hidden ? 'hidden' : 'visible' }}</span></td>
<td>{{ p.auto_register ? 'Yes' : 'No' }}</td>
<td>{{ formatDate(p.created_at) }}</td>
<td>
@@ -235,6 +239,12 @@ onMounted(fetchProviders)
Auto-register new users on first login
</label>
</div>
+ <div class="form-group">
+ <label style="display: flex; align-items: center; gap: 8px; cursor: pointer; font-size: 13px;">
+ <input type="checkbox" v-model="form.hidden" />
+ Hide from login page (only reachable via email-based SSO discovery)
+ </label>
+ </div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" @click="showCreateModal = false">Cancel</button>
@@ -283,6 +293,12 @@ onMounted(fetchProviders)
Auto-register new users on first login
</label>
</div>
+ <div class="form-group">
+ <label style="display: flex; align-items: center; gap: 8px; cursor: pointer; font-size: 13px;">
+ <input type="checkbox" v-model="editForm.hidden" />
+ Hide from login page (only reachable via email-based SSO discovery)
+ </label>
+ </div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" @click="showEditModal = false">Cancel</button>
diff --git a/web/src/views/admin/UserDetail.vue b/web/src/views/admin/UserDetail.vue
index eeb7154..92ec2e2 100644
--- a/web/src/views/admin/UserDetail.vue
+++ b/web/src/views/admin/UserDetail.vue
@@ -15,6 +15,7 @@ const loading = ref(true)
const metrics = ref<UserDetailMetrics | null>(null)
const disabling2FA = ref(false)
const revokingSessions = ref(false)
+const settingVerified = ref(false)
const deleting = ref(false)
const forceDeleting = ref(false)
const cancellingDeletion = ref(false)
@@ -62,6 +63,29 @@ async function handleDisable2FA() {
}
}
+async function handleSetEmailVerified(verified: boolean) {
+ if (!metrics.value) return
+ const confirmed = await confirm({
+ title: verified ? 'Mark email as verified' : 'Revoke email verification',
+ message: verified
+ ? "This will mark the user's email address as verified and unlock verification-gated actions."
+ : "This will clear the user's email verification. Verification-gated actions will be blocked until they re-verify.",
+ confirmText: verified ? 'Mark verified' : 'Revoke',
+ variant: verified ? 'info' : 'danger',
+ })
+ if (!confirmed) return
+ settingVerified.value = true
+ try {
+ const res = await adminApi.updateUser(metrics.value.user.id, { email_verified: verified })
+ metrics.value.user.email_verified_at = res.data.data.email_verified_at
+ notification.success(verified ? 'Email marked as verified.' : 'Email verification revoked.')
+ } catch {
+ notification.error('Failed to update email verification.')
+ } finally {
+ settingVerified.value = false
+ }
+}
+
async function handleRevokeSessions() {
if (!metrics.value) return
const confirmed = await confirm({
@@ -254,6 +278,31 @@ function formatDate(date: string) {
</button>
</td>
</tr>
+ <tr>
+ <td style="font-weight: 600;">Email verified</td>
+ <td>
+ <span v-if="metrics.user.email_verified_at" class="badge badge-success">Verified</span>
+ <span v-else class="badge badge-neutral">Not verified</span>
+ <button
+ v-if="!metrics.user.email_verified_at"
+ class="btn btn-primary btn-sm"
+ style="margin-left: 12px;"
+ :disabled="settingVerified"
+ @click="handleSetEmailVerified(true)"
+ >
+ {{ settingVerified ? 'Updating...' : 'Mark verified' }}
+ </button>
+ <button
+ v-else
+ class="btn btn-danger btn-sm"
+ style="margin-left: 12px;"
+ :disabled="settingVerified"
+ @click="handleSetEmailVerified(false)"
+ >
+ {{ settingVerified ? 'Updating...' : 'Revoke verification' }}
+ </button>
+ </td>
+ </tr>
<tr>
<td style="font-weight: 600;">Sessions</td>
<td>
@@ -363,6 +412,18 @@ function formatDate(date: string) {
<div class="stat-label">SMTP Servers</div>
<div class="stat-value">{{ metrics.total_smtp_servers }}</div>
</div>
+ <div class="stat-card">
+ <div class="stat-label">Inbound Received</div>
+ <div class="stat-value">{{ metrics.total_inbound ?? 0 }}</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-label">Inbound Forwarded</div>
+ <div class="stat-value">{{ metrics.forwarded_inbound ?? 0 }}</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-label">Inbound Failed</div>
+ <div class="stat-value">{{ metrics.failed_inbound ?? 0 }}</div>
+ </div>
</div>
<!-- User Plan -->
diff --git a/web/src/views/analytics/Analytics.vue b/web/src/views/analytics/Analytics.vue
index 3bc320d..a426370 100644
--- a/web/src/views/analytics/Analytics.vue
+++ b/web/src/views/analytics/Analytics.vue
@@ -1,12 +1,13 @@
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { analyticsApi } from '../../api/analytics'
-import type { DailyCount, StatusBreakdown, DashboardAnalyticsResponse } from '../../api/types'
+import type { DailyCount, StatusBreakdown, DashboardAnalyticsResponse, ProviderBreakdownPoint } from '../../api/types'
const loading = ref(true)
const dailyCounts = ref<DailyCount[]>([])
const statusBreakdown = ref<StatusBreakdown[]>([])
const dashAnalytics = ref<DashboardAnalyticsResponse | null>(null)
+const providerBreakdown = ref<ProviderBreakdownPoint[]>([])
const fromDate = ref('')
const toDate = ref('')
@@ -22,13 +23,15 @@ toDate.value = now.toISOString().slice(0, 10)
async function loadAnalytics() {
loading.value = true
try {
- const [res, dashRes] = await Promise.all([
+ const [res, dashRes, provRes] = await Promise.all([
analyticsApi.user(fromDate.value, toDate.value, statusFilter.value || undefined),
analyticsApi.dashboardAnalytics(fromDate.value, toDate.value),
+ analyticsApi.providerBreakdown(fromDate.value, toDate.value),
])
dailyCounts.value = res.data.data.daily_counts || []
statusBreakdown.value = res.data.data.status_breakdown || []
dashAnalytics.value = dashRes.data.data
+ providerBreakdown.value = provRes.data.data.providers || []
} catch (e) {
console.error('Failed to load analytics', e)
} finally {
@@ -70,6 +73,41 @@ function breakdownPercent(count: number): string {
return ((count / totalBreakdown.value) * 100).toFixed(1)
}
+// Provider-specific colors for the mailbox provider breakdown.
+const providerColors: Record<string, string> = {
+ Gmail: '#ea4335',
+ 'Google Workspace': '#4285f4',
+ Outlook: '#0078d4',
+ Yahoo: '#6001d2',
+ 'Apple iCloud': '#8e8e93',
+ Proton: '#6d4aff',
+ AOL: '#00bfff',
+ GMX: '#1c4587',
+ Zoho: '#f04e23',
+ Fastmail: '#2968a6',
+ Yandex: '#ffcc00',
+ China: '#c20000',
+ Other: '#9ca3af',
+}
+
+function providerColor(name: string): string {
+ return providerColors[name] ?? '#6366f1'
+}
+
+const providerTotal = computed(() => providerBreakdown.value.reduce((sum, p) => sum + p.total, 0))
+
+function providerPercent(total: number): string {
+ if (providerTotal.value === 0) return '0'
+ return ((total / providerTotal.value) * 100).toFixed(1)
+}
+
+function providerRateClass(rate: number, total: number): string {
+ if (total === 0) return ''
+ if (rate < 75) return 'rate-danger'
+ if (rate < 90) return 'rate-warning'
+ return ''
+}
+
// Delivery rate chart helpers
const deliveryRateMax = computed(() => {
if (!dashAnalytics.value) return 1
@@ -228,6 +266,51 @@ const avgDeliveryRate = computed(() => {
</div>
</div>
+ <!-- Deliverability by Provider -->
+ <div class="card" style="margin-top: 24px">
+ <div class="card-header">
+ <h2>Deliverability by Provider <span class="card-header-sub">{{ providerTotal }} recipients in period</span></h2>
+ </div>
+ <div class="card-body">
+ <div v-if="providerBreakdown.length === 0" class="empty-state">
+ <h3>No data</h3>
+ <p>No recipient data in the selected range.</p>
+ </div>
+ <div v-else class="provider-table">
+ <div class="provider-row provider-head">
+ <div class="provider-cell provider-name">Provider</div>
+ <div class="provider-cell provider-bar-cell">Volume</div>
+ <div class="provider-cell provider-num">Sent</div>
+ <div class="provider-cell provider-num">Failed</div>
+ <div class="provider-cell provider-num">Rate</div>
+ </div>
+ <div v-for="p in providerBreakdown" :key="p.provider" class="provider-row">
+ <div class="provider-cell provider-name">
+ <span class="breakdown-dot" :style="{ background: providerColor(p.provider) }"></span>
+ {{ p.provider }}
+ </div>
+ <div class="provider-cell provider-bar-cell">
+ <div class="breakdown-bar-track">
+ <div
+ class="breakdown-bar-fill"
+ :style="{ width: providerPercent(p.total) + '%', background: providerColor(p.provider) }"
+ ></div>
+ </div>
+ <div class="provider-pct">{{ providerPercent(p.total) }}%</div>
+ </div>
+ <div class="provider-cell provider-num">{{ p.sent }}</div>
+ <div class="provider-cell provider-num">{{ p.failed }}</div>
+ <div
+ class="provider-cell provider-num provider-rate"
+ :class="providerRateClass(p.delivery_rate, p.sent + p.failed)"
+ >
+ {{ (p.sent + p.failed) > 0 ? p.delivery_rate.toFixed(1) + '%' : '—' }}
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
<!-- Dashboard Analytics: Delivery Rate, Bounce Rate, Latency -->
<template v-if="dashAnalytics">
<!-- Delivery Rate Trends -->
@@ -630,4 +713,89 @@ const avgDeliveryRate = computed(() => {
color: var(--text-muted);
margin-top: 4px;
}
+
+/* Provider breakdown */
+.provider-table {
+ display: grid;
+ gap: 6px;
+}
+
+.provider-row {
+ display: grid;
+ grid-template-columns: minmax(140px, 1.4fr) minmax(200px, 3fr) 80px 80px 80px;
+ align-items: center;
+ gap: 12px;
+ padding: 8px 0;
+ border-bottom: 1px solid var(--border-color, #e5e7eb);
+}
+
+.provider-row:last-child {
+ border-bottom: none;
+}
+
+.provider-head {
+ font-size: 11px;
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+ color: var(--text-muted);
+ font-weight: 600;
+ padding-bottom: 6px;
+}
+
+.provider-cell {
+ font-size: 13px;
+ color: var(--text-primary);
+}
+
+.provider-name {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ font-weight: 500;
+}
+
+.provider-bar-cell {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+}
+
+.provider-bar-cell .breakdown-bar-track {
+ flex: 1;
+}
+
+.provider-pct {
+ font-size: 12px;
+ color: var(--text-muted);
+ min-width: 44px;
+ text-align: right;
+}
+
+.provider-num {
+ text-align: right;
+ font-variant-numeric: tabular-nums;
+}
+
+.provider-rate {
+ font-weight: 600;
+}
+
+.provider-rate.rate-warning {
+ color: var(--warning-600, #ca8a04);
+}
+
+.provider-rate.rate-danger {
+ color: var(--danger-600, #dc2626);
+}
+
+@media (max-width: 640px) {
+ .provider-row {
+ grid-template-columns: minmax(120px, 1fr) 60px 60px 60px;
+ }
+ .provider-bar-cell {
+ grid-column: 1 / -1;
+ order: 99;
+ margin-top: 4px;
+ }
+}
</style>
diff --git a/web/src/views/auth/Login.vue b/web/src/views/auth/Login.vue
index 1ac749f..7e594d6 100644
--- a/web/src/views/auth/Login.vue
+++ b/web/src/views/auth/Login.vue
@@ -1,6 +1,6 @@
<script setup lang="ts">
import { ref, onMounted } from 'vue'
-import { useRouter } from 'vue-router'
+import { useRoute, useRouter } from 'vue-router'
import { authApi } from '../../api/auth'
import { oauthApi } from '../../api/oauth'
import { useAuthStore } from '../../stores/auth'
@@ -9,6 +9,7 @@ import { useThemeStore } from '../../stores/theme'
import type { OAuthProviderInfo } from '../../api/types'
const router = useRouter()
+const route = useRoute()
const auth = useAuthStore()
const notification = useNotificationStore()
const theme = useThemeStore()
@@ -20,7 +21,13 @@ const loading = ref(false)
const requires2FA = ref(false)
const registrationEnabled = ref(false)
const oauthProviders = ref<OAuthProviderInfo[]>([])
+const ssoAvailable = ref(false)
+const ssoMode = ref(false)
const loginError = ref(router.currentRoute.value.query.error as string || '')
+const emailError = ref('')
+const passwordError = ref('')
+const codeError = ref('')
+const showPassword = ref(false)
onMounted(async () => {
try {
@@ -30,6 +37,7 @@ onMounted(async () => {
])
registrationEnabled.value = regRes.data.data.registration_enabled
oauthProviders.value = oauthRes.data.data.providers || []
+ ssoAvailable.value = !!oauthRes.data.data.sso_available
} catch { /* ignore */ }
})
@@ -38,19 +46,60 @@ function oauthLogin(slug: string) {
window.location.href = `/api/v1/auth/oauth/${slug}/authorize`
}
-async function handleLogin() {
- if (!email.value || !password.value) {
- notification.error('Please fill in all fields.')
+const ssoChecking = ref(false)
+function enterSSOMode() {
+ ssoMode.value = true
+ password.value = ''
+}
+function exitSSOMode() {
+ ssoMode.value = false
+}
+async function submitSSO() {
+ emailError.value = ''
+ if (!email.value) {
+ emailError.value = 'Enter your email to continue.'
return
}
- if (requires2FA.value && !twoFactorCode.value) {
- notification.error('Please enter your 2FA code.')
- return
+ ssoChecking.value = true
+ try {
+ const res = await oauthApi.discoverSSO(email.value)
+ const slug = res.data.data?.slug
+ if (slug) {
+ oauthLogin(slug)
+ return
+ }
+ notification.info('No SSO configured for this email.')
+ } catch (err: any) {
+ if (err?.response?.status === 404) {
+ notification.info('No SSO configured for this email.')
+ } else {
+ notification.error('SSO lookup failed.')
+ }
+ } finally {
+ ssoChecking.value = false
+ }
+}
+
+async function handleLogin() {
+ emailError.value = ''
+ passwordError.value = ''
+ codeError.value = ''
+ if (requires2FA.value) {
+ if (!twoFactorCode.value) {
+ codeError.value = 'Enter the 6-digit code from your authenticator app.'
+ return
+ }
+ } else {
+ if (!email.value) emailError.value = 'Enter your email address.'
+ if (!password.value) passwordError.value = 'Enter your password.'
+ if (emailError.value || passwordError.value) return
}
loading.value = true
try {
await auth.login(email.value, password.value, requires2FA.value ? twoFactorCode.value : undefined)
- router.push('/')
+ const redirect = route.query.redirect
+ const target = typeof redirect === 'string' && redirect.startsWith('/') ? redirect : '/'
+ router.push(target)
} catch (err: any) {
if (err?.requires2FA) {
requires2FA.value = true
@@ -84,52 +133,97 @@ function resetLogin() {
<div class="auth-page">
<div class="auth-card">
<div class="auth-header">
- <div class="auth-logo">
- <img src="/logo.png" alt="Posta" class="logo-img" />
- <span>Posta</span>
- </div>
- <p class="auth-subtitle">{{ requires2FA ? 'Two-Factor Authentication' : 'Sign in to your account' }}</p>
+ <div class="auth-wordmark" aria-label="Posta">Posta<span class="auth-wordmark-dot">.</span></div>
+ <h1 class="auth-title">
+ {{ requires2FA ? 'Two-factor authentication' : (ssoMode ? 'Continue with SSO' : 'Sign in to your account') }}
+ </h1>
+ <p v-if="requires2FA" class="auth-subtitle">Enter the code from your authenticator app.</p>
+ <p v-else-if="ssoMode" class="auth-subtitle">We'll redirect you to your identity provider.</p>
</div>
- <form class="auth-form" @submit.prevent="handleLogin">
+ <form class="auth-form" @submit.prevent="ssoMode ? submitSSO() : handleLogin()">
<template v-if="!requires2FA">
<div class="form-group">
<label class="form-label" for="email">Email</label>
- <input id="email" v-model="email" type="email" class="form-input" placeholder="[email protected]" autocomplete="email" />
+ <input
+ id="email"
+ v-model="email"
+ type="email"
+ class="form-input"
+ :class="{ 'form-input-error': emailError }"
+ placeholder="[email protected]"
+ autocomplete="email"
+ @input="emailError = ''"
+ />
+ <small v-if="emailError" class="form-error">{{ emailError }}</small>
</div>
- <div class="form-group">
+ <div v-if="!ssoMode" class="form-group">
<label class="form-label" for="password">Password</label>
- <input id="password" v-model="password" type="password" class="form-input" placeholder="Enter your password" autocomplete="current-password" />
+ <div class="password-wrap">
+ <input
+ id="password"
+ v-model="password"
+ :type="showPassword ? 'text' : 'password'"
+ class="form-input"
+ :class="{ 'form-input-error': passwordError }"
+ placeholder="Enter your password"
+ autocomplete="current-password"
+ @input="passwordError = ''"
+ />
+ <button
+ type="button"
+ class="password-toggle"
+ :aria-label="showPassword ? 'Hide password' : 'Show password'"
+ :title="showPassword ? 'Hide password' : 'Show password'"
+ @click="showPassword = !showPassword"
+ >
+ <svg v-if="showPassword" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17.94 17.94A10.07 10.07 0 0112 20c-7 0-11-8-11-8a18.45 18.45 0 015.06-5.94M9.9 4.24A9.12 9.12 0 0112 4c7 0 11 8 11 8a18.5 18.5 0 01-2.16 3.19m-6.72-1.07a3 3 0 11-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg>
+ <svg v-else width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
+ </button>
+ </div>
+ <small v-if="passwordError" class="form-error">{{ passwordError }}</small>
</div>
</template>
<template v-else>
<div class="form-group">
- <label class="form-label" for="2fa-code">Authentication Code</label>
+ <label class="form-label" for="2fa-code">Authentication code</label>
<input
id="2fa-code"
v-model="twoFactorCode"
type="text"
class="form-input totp-input"
+ :class="{ 'form-input-error': codeError }"
placeholder="000000"
maxlength="6"
inputmode="numeric"
autocomplete="one-time-code"
autofocus
+ @input="codeError = ''"
/>
- <small class="form-hint">Enter the 6-digit code from your authenticator app</small>
+ <small v-if="codeError" class="form-error">{{ codeError }}</small>
</div>
</template>
- <button type="submit" class="btn btn-primary auth-btn" :disabled="loading">
+ <button v-if="!ssoMode" type="submit" class="btn btn-primary auth-btn" :disabled="loading">
<span v-if="loading" class="spinner"></span>
{{ loading ? 'Signing in...' : 'Sign in' }}
</button>
+ <button v-if="ssoMode" type="submit" class="btn btn-primary auth-btn" :disabled="ssoChecking">
+ <span v-if="ssoChecking" class="spinner"></span>
+ {{ ssoChecking ? 'Checking...' : 'Continue' }}
+ </button>
+ <button v-if="!requires2FA && !ssoMode && ssoAvailable" type="button" class="btn btn-secondary auth-btn" style="margin-top: 8px" @click="enterSSOMode">
+ Continue with SSO
+ </button>
+ <button v-if="ssoMode" type="button" class="btn btn-secondary auth-btn" style="margin-top: 8px" @click="exitSSOMode">
+ Back to password sign in
+ </button>
<button v-if="requires2FA" type="button" class="btn btn-secondary auth-btn" style="margin-top: 8px" @click="resetLogin">
Back to Login
</button>
</form>
<!-- OAuth Providers -->
- <div v-if="oauthProviders.length > 0 && !requires2FA" class="oauth-section">
+ <div v-if="oauthProviders.length > 0 && !requires2FA && !ssoMode" class="oauth-section">
<div class="oauth-divider">
<span>or</span>
</div>
@@ -190,26 +284,56 @@ function resetLogin() {
.auth-header { text-align: center; padding: 36px 32px 0; }
-.auth-logo {
- display: flex;
- align-items: center;
- justify-content: center;
- gap: 10px;
- margin-bottom: 10px;
-}
-.auth-logo .logo-img {
- width: 100px;
- height: 100px;
- object-fit: contain;
-}
-.auth-logo span {
+.auth-wordmark {
font-size: 32px;
font-weight: 800;
+ letter-spacing: -1px;
color: var(--text-primary);
- letter-spacing: -0.5px;
+ margin-bottom: 24px;
+ line-height: 1;
+}
+.auth-wordmark-dot {
+ color: var(--primary-500);
+ margin-left: 1px;
}
-.auth-subtitle { font-size: 14px; color: var(--text-muted); }
+.auth-title {
+ font-size: 22px;
+ font-weight: 600;
+ color: var(--text-primary);
+ letter-spacing: -0.2px;
+ margin: 0 0 8px;
+}
+
+.auth-subtitle { font-size: 14px; color: var(--text-muted); margin: 0; }
+
+.password-wrap { position: relative; }
+.password-wrap .form-input { padding-right: 40px; }
+.password-toggle {
+ position: absolute;
+ top: 0;
+ right: 0;
+ bottom: 0;
+ width: 36px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: transparent;
+ border: none;
+ color: var(--text-muted);
+ cursor: pointer;
+}
+.password-toggle:hover { color: var(--text-primary); }
+
+.form-input-error { border-color: var(--danger-500, #ef4444); }
+.form-input-error:focus { border-color: var(--danger-500, #ef4444); }
+
+.form-error {
+ display: block;
+ font-size: 12px;
+ color: var(--danger-600, #dc2626);
+ margin-top: 6px;
+}
.auth-form { padding: 28px 32px 20px; }
@@ -227,12 +351,6 @@ function resetLogin() {
font-family: 'JetBrains Mono', 'Fira Code', monospace;
}
-.form-hint {
- font-size: 12px;
- color: var(--text-muted);
- margin-top: 6px;
-}
-
.auth-footer {
text-align: center;
padding: 0 32px 28px;
diff --git a/web/src/views/auth/Register.vue b/web/src/views/auth/Register.vue
index e7a1937..59423a3 100644
--- a/web/src/views/auth/Register.vue
+++ b/web/src/views/auth/Register.vue
@@ -18,6 +18,13 @@ const confirmPassword = ref('')
const loading = ref(false)
const registrationEnabled = ref<boolean | null>(null)
+const nameError = ref('')
+const emailError = ref('')
+const passwordError = ref('')
+const confirmError = ref('')
+const showPassword = ref(false)
+const showConfirm = ref(false)
+
onMounted(async () => {
try {
const res = await authApi.registrationStatus()
@@ -31,26 +38,30 @@ onMounted(async () => {
})
async function handleRegister() {
- if (!name.value.trim() || !email.value || !password.value || !confirmPassword.value) {
- notification.error('Please fill in all fields.')
- return
- }
- if (password.value.length < 8) {
- notification.error('Password must be at least 8 characters.')
- return
+ nameError.value = ''
+ emailError.value = ''
+ passwordError.value = ''
+ confirmError.value = ''
+ if (!name.value.trim()) nameError.value = 'Enter your name.'
+ if (!email.value) emailError.value = 'Enter your email address.'
+ if (!password.value) {
+ passwordError.value = 'Enter a password.'
+ } else if (password.value.length < 8) {
+ passwordError.value = 'Password must be at least 8 characters.'
}
- if (password.value !== confirmPassword.value) {
- notification.error('Passwords do not match.')
- return
+ if (!confirmPassword.value) {
+ confirmError.value = 'Confirm your password.'
+ } else if (password.value && password.value !== confirmPassword.value) {
+ confirmError.value = 'Passwords do not match.'
}
+ if (nameError.value || emailError.value || passwordError.value || confirmError.value) return
+
loading.value = true
try {
const res = await authApi.register(name.value.trim(), email.value.trim(), password.value)
- // Auto-login with the returned token
const data = res.data.data
localStorage.setItem('posta_token', data.token)
localStorage.setItem('posta_user', JSON.stringify(data.user))
- // Reload to pick up auth state
window.location.href = '/'
} catch (err: any) {
const message = err?.response?.data?.error?.message || err?.response?.data?.error || err?.message || 'Registration failed.'
@@ -65,33 +76,95 @@ async function handleRegister() {
<div class="auth-page" v-if="registrationEnabled">
<div class="auth-card">
<div class="auth-header">
- <div class="auth-logo">
- <img src="/logo.png" alt="Posta" class="logo-img" />
- <span>Posta</span>
- </div>
- <p class="auth-subtitle">Create your account</p>
+ <div class="auth-wordmark" aria-label="Posta">Posta<span class="auth-wordmark-dot">.</span></div>
+ <h1 class="auth-title">Create your account</h1>
+ <p class="auth-subtitle">Get started in under a minute.</p>
</div>
<form class="auth-form" @submit.prevent="handleRegister">
<div class="form-group">
<label class="form-label" for="name">Name</label>
- <input id="name" v-model="name" type="text" class="form-input" placeholder="Your name" autocomplete="name" />
+ <input
+ id="name"
+ v-model="name"
+ type="text"
+ class="form-input"
+ :class="{ 'form-input-error': nameError }"
+ placeholder="Your name"
+ autocomplete="name"
+ @input="nameError = ''"
+ />
+ <small v-if="nameError" class="form-error">{{ nameError }}</small>
</div>
<div class="form-group">
<label class="form-label" for="email">Email</label>
- <input id="email" v-model="email" type="email" class="form-input" placeholder="[email protected]" autocomplete="email" />
+ <input
+ id="email"
+ v-model="email"
+ type="email"
+ class="form-input"
+ :class="{ 'form-input-error': emailError }"
+ placeholder="[email protected]"
+ autocomplete="email"
+ @input="emailError = ''"
+ />
+ <small v-if="emailError" class="form-error">{{ emailError }}</small>
</div>
<div class="form-group">
<label class="form-label" for="password">Password</label>
- <input id="password" v-model="password" type="password" class="form-input" placeholder="Minimum 8 characters" autocomplete="new-password" />
+ <div class="password-wrap">
+ <input
+ id="password"
+ v-model="password"
+ :type="showPassword ? 'text' : 'password'"
+ class="form-input"
+ :class="{ 'form-input-error': passwordError }"
+ placeholder="Minimum 8 characters"
+ autocomplete="new-password"
+ @input="passwordError = ''"
+ />
+ <button
+ type="button"
+ class="password-toggle"
+ :aria-label="showPassword ? 'Hide password' : 'Show password'"
+ :title="showPassword ? 'Hide password' : 'Show password'"
+ @click="showPassword = !showPassword"
+ >
+ <svg v-if="showPassword" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17.94 17.94A10.07 10.07 0 0112 20c-7 0-11-8-11-8a18.45 18.45 0 015.06-5.94M9.9 4.24A9.12 9.12 0 0112 4c7 0 11 8 11 8a18.5 18.5 0 01-2.16 3.19m-6.72-1.07a3 3 0 11-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg>
+ <svg v-else width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
+ </button>
+ </div>
+ <small v-if="passwordError" class="form-error">{{ passwordError }}</small>
</div>
<div class="form-group">
- <label class="form-label" for="confirm-password">Confirm Password</label>
- <input id="confirm-password" v-model="confirmPassword" type="password" class="form-input" placeholder="Re-enter your password" autocomplete="new-password" />
+ <label class="form-label" for="confirm-password">Confirm password</label>
+ <div class="password-wrap">
+ <input
+ id="confirm-password"
+ v-model="confirmPassword"
+ :type="showConfirm ? 'text' : 'password'"
+ class="form-input"
+ :class="{ 'form-input-error': confirmError }"
+ placeholder="Re-enter your password"
+ autocomplete="new-password"
+ @input="confirmError = ''"
+ />
+ <button
+ type="button"
+ class="password-toggle"
+ :aria-label="showConfirm ? 'Hide password' : 'Show password'"
+ :title="showConfirm ? 'Hide password' : 'Show password'"
+ @click="showConfirm = !showConfirm"
+ >
+ <svg v-if="showConfirm" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17.94 17.94A10.07 10.07 0 0112 20c-7 0-11-8-11-8a18.45 18.45 0 015.06-5.94M9.9 4.24A9.12 9.12 0 0112 4c7 0 11 8 11 8a18.5 18.5 0 01-2.16 3.19m-6.72-1.07a3 3 0 11-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg>
+ <svg v-else width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
+ </button>
+ </div>
+ <small v-if="confirmError" class="form-error">{{ confirmError }}</small>
</div>
<button type="submit" class="btn btn-primary auth-btn" :disabled="loading">
<span v-if="loading" class="spinner"></span>
- {{ loading ? 'Creating account...' : 'Create Account' }}
+ {{ loading ? 'Creating account…' : 'Create account' }}
</button>
</form>
@@ -130,26 +203,28 @@ async function handleRegister() {
.auth-header { text-align: center; padding: 36px 32px 0; }
-.auth-logo {
- display: flex;
- align-items: center;
- justify-content: center;
- gap: 10px;
- margin-bottom: 10px;
+.auth-wordmark {
+ font-size: 32px;
+ font-weight: 800;
+ letter-spacing: -1px;
+ color: var(--text-primary);
+ margin-bottom: 24px;
+ line-height: 1;
}
-.auth-logo .logo-img {
- width: 80px;
- height: 80px;
- object-fit: contain;
+.auth-wordmark-dot {
+ color: var(--primary-500);
+ margin-left: 1px;
}
-.auth-logo span {
- font-size: 26px;
- font-weight: 800;
+
+.auth-title {
+ font-size: 22px;
+ font-weight: 600;
color: var(--text-primary);
- letter-spacing: -0.5px;
+ letter-spacing: -0.2px;
+ margin: 0 0 8px;
}
-.auth-subtitle { font-size: 14px; color: var(--text-muted); }
+.auth-subtitle { font-size: 14px; color: var(--text-muted); margin: 0; }
.auth-form { padding: 28px 32px 20px; }
@@ -160,6 +235,34 @@ async function handleRegister() {
margin-top: 4px;
}
+.password-wrap { position: relative; }
+.password-wrap .form-input { padding-right: 40px; }
+.password-toggle {
+ position: absolute;
+ top: 0;
+ right: 0;
+ bottom: 0;
+ width: 36px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: transparent;
+ border: none;
+ color: var(--text-muted);
+ cursor: pointer;
+}
+.password-toggle:hover { color: var(--text-primary); }
+
+.form-input-error { border-color: var(--danger-500, #ef4444); }
+.form-input-error:focus { border-color: var(--danger-500, #ef4444); }
+
+.form-error {
+ display: block;
+ font-size: 12px;
+ color: var(--danger-600, #dc2626);
+ margin-top: 6px;
+}
+
.auth-footer {
text-align: center;
padding: 0 32px 28px;
diff --git a/web/src/views/auth/VerifyEmail.vue b/web/src/views/auth/VerifyEmail.vue
new file mode 100644
index 0000000..58d5aed
--- /dev/null
+++ b/web/src/views/auth/VerifyEmail.vue
@@ -0,0 +1,128 @@
+<script setup lang="ts">
+import { onMounted, ref } from 'vue'
+import { useRoute, useRouter } from 'vue-router'
+import { authApi } from '../../api/auth'
+import { useAuthStore } from '../../stores/auth'
+
+const route = useRoute()
+const router = useRouter()
+const auth = useAuthStore()
+
+const status = ref<'verifying' | 'success' | 'error'>('verifying')
+const message = ref('')
+
+onMounted(async () => {
+ const token = route.query.token as string
+ if (!token) {
+ status.value = 'error'
+ message.value = 'Missing verification token.'
+ return
+ }
+ try {
+ const res = await authApi.verifyEmail(token)
+ message.value = res.data.data?.message || 'Email verified.'
+ status.value = 'success'
+ if (auth.isAuthenticated) {
+ await auth.fetchUser()
+ }
+ } catch (err: any) {
+ message.value =
+ err?.response?.data?.error?.message ||
+ err?.response?.data?.error ||
+ err?.message ||
+ 'Verification failed.'
+ status.value = 'error'
+ }
+})
+
+function goHome() {
+ router.push(auth.isAuthenticated ? '/' : '/login')
+}
+</script>
+
+<template>
+ <div class="verify-page">
+ <div class="verify-card">
+ <h1>Email verification</h1>
+
+ <template v-if="status === 'verifying'">
+ <div class="spinner"></div>
+ <p class="muted">Verifying your email…</p>
+ </template>
+
+ <template v-else-if="status === 'success'">
+ <p class="success">{{ message }}</p>
+ <button class="btn btn-primary" @click="goHome">
+ {{ auth.isAuthenticated ? 'Go to dashboard' : 'Sign in' }}
+ </button>
+ </template>
+
+ <template v-else>
+ <p class="error">{{ message }}</p>
+ <button class="btn" @click="goHome">
+ {{ auth.isAuthenticated ? 'Go to dashboard' : 'Sign in' }}
+ </button>
+ </template>
+ </div>
+ </div>
+</template>
+
+<style scoped>
+.verify-page {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ min-height: 100vh;
+ background: var(--bg-secondary);
+ padding: 24px;
+}
+.verify-card {
+ background: var(--bg-primary);
+ border: 1px solid var(--border-color);
+ border-radius: 8px;
+ padding: 32px;
+ max-width: 420px;
+ width: 100%;
+ text-align: center;
+}
+.verify-card h1 {
+ font-size: 20px;
+ margin: 0 0 16px;
+ color: var(--text-primary);
+}
+.verify-card p {
+ font-size: 14px;
+ color: var(--text-secondary);
+ margin: 8px 0 20px;
+}
+.muted { color: var(--text-muted); }
+.success { color: var(--success-600, #16a34a); }
+.error { color: var(--danger-600, #dc2626); }
+.btn {
+ display: inline-block;
+ padding: 10px 18px;
+ border-radius: 6px;
+ border: 1px solid var(--border-color);
+ background: var(--bg-primary);
+ color: var(--text-primary);
+ font-size: 14px;
+ cursor: pointer;
+}
+.btn-primary {
+ background: var(--primary-600, #2563eb);
+ border-color: var(--primary-600, #2563eb);
+ color: #fff;
+}
+.spinner {
+ width: 32px;
+ height: 32px;
+ border: 3px solid var(--border-color);
+ border-top-color: var(--primary-600, #2563eb);
+ border-radius: 50%;
+ margin: 12px auto;
+ animation: spin 0.8s linear infinite;
+}
+@keyframes spin {
+ to { transform: rotate(360deg); }
+}
+</style>
diff --git a/web/src/views/campaigns/CampaignDetail.vue b/web/src/views/campaigns/CampaignDetail.vue
index a4fdcbc..43f572a 100644
--- a/web/src/views/campaigns/CampaignDetail.vue
+++ b/web/src/views/campaigns/CampaignDetail.vue
@@ -31,7 +31,7 @@ const canSend = computed(() => campaign.value?.status === 'draft')
const canPause = computed(() => campaign.value?.status === 'sending')
const canResume = computed(() => campaign.value?.status === 'paused')
const canCancel = computed(() => ['sending', 'paused', 'scheduled'].includes(campaign.value?.status ?? ''))
-const canDelete = computed(() => ['draft', 'cancelled'].includes(campaign.value?.status ?? ''))
+const canDelete = computed(() => campaign.value ? campaign.value.status !== 'sending' : false)
const showAnalyticsTab = computed(() => ['sending', 'sent', 'paused', 'cancelled'].includes(campaign.value?.status ?? ''))
async function loadCampaign() {
@@ -84,77 +84,70 @@ function switchMessageStatus(status: string) {
loadMessages(0)
}
+// runAction wraps a status-changing API call so we (a) always clear the loading
+// flag, (b) surface 409 conflicts clearly and refresh the campaign so the
+// action buttons resync with server state.
+async function runAction(fn: () => Promise<unknown>, successMsg: string, failMsg: string) {
+ actionLoading.value = true
+ try {
+ await fn()
+ notify.success(successMsg)
+ await loadCampaign()
+ } catch (e: any) {
+ const status = e?.response?.status
+ const msg = e?.response?.data?.error?.message
+ if (status === 409) {
+ notify.error(msg || 'Campaign state changed; refreshing')
+ await loadCampaign()
+ } else {
+ notify.error(msg || failMsg)
+ }
+ } finally {
+ actionLoading.value = false
+ }
+}
+
async function sendCampaign() {
const confirmed = await confirm({
title: 'Send Campaign',
message: `Are you sure you want to send "${campaign.value?.name}"? This will start delivering emails to all subscribers in the list.`,
confirmText: 'Send',
- variant: 'primary',
+ variant: 'info',
})
if (!confirmed) return
- actionLoading.value = true
- try {
+ await runAction(async () => {
await campaignsApi.send(campaignId)
- notify.success('Campaign is being sent')
- await loadCampaign()
await loadMessages(0)
- } catch (e: any) {
- notify.error(e?.response?.data?.error?.message || 'Failed to send campaign')
- } finally {
- actionLoading.value = false
- }
+ }, 'Campaign is being sent', 'Failed to send campaign')
}
async function pauseCampaign() {
- actionLoading.value = true
- try {
- await campaignsApi.pause(campaignId)
- notify.success('Campaign paused')
- await loadCampaign()
- } catch (e: any) {
- notify.error(e?.response?.data?.error?.message || 'Failed to pause campaign')
- } finally {
- actionLoading.value = false
- }
+ await runAction(() => campaignsApi.pause(campaignId), 'Campaign paused', 'Failed to pause campaign')
}
async function resumeCampaign() {
- actionLoading.value = true
- try {
- await campaignsApi.resume(campaignId)
- notify.success('Campaign resumed')
- await loadCampaign()
- } catch (e: any) {
- notify.error(e?.response?.data?.error?.message || 'Failed to resume campaign')
- } finally {
- actionLoading.value = false
- }
+ await runAction(() => campaignsApi.resume(campaignId), 'Campaign resumed', 'Failed to resume campaign')
}
async function cancelCampaign() {
const confirmed = await confirm({
title: 'Cancel Campaign',
- message: `Are you sure you want to cancel "${campaign.value?.name}"? Pending messages will not be sent.`,
+ message: `Are you sure you want to cancel "${campaign.value?.name}"? Pending messages will be skipped; any already-queued messages will be dropped at dispatch time.`,
confirmText: 'Cancel Campaign',
variant: 'danger',
})
if (!confirmed) return
- actionLoading.value = true
- try {
- await campaignsApi.cancel(campaignId)
- notify.success('Campaign cancelled')
- await loadCampaign()
- } catch (e: any) {
- notify.error(e?.response?.data?.error?.message || 'Failed to cancel campaign')
- } finally {
- actionLoading.value = false
- }
+ await runAction(() => campaignsApi.cancel(campaignId), 'Campaign cancelled', 'Failed to cancel campaign')
}
async function deleteCampaign() {
+ const status = campaign.value?.status
+ const warnLossOfData = status === 'sent' || status === 'sending' || status === 'paused'
const confirmed = await confirm({
title: 'Delete Campaign',
- message: `Are you sure you want to delete "${campaign.value?.name}"? This action cannot be undone.`,
+ message: warnLossOfData
+ ? `Delete "${campaign.value?.name}"? Per-message delivery records will be removed. An aggregate stats snapshot is kept for reporting.`
+ : `Are you sure you want to delete "${campaign.value?.name}"? This action cannot be undone.`,
confirmText: 'Delete',
variant: 'danger',
})
diff --git a/web/src/views/campaigns/Campaigns.vue b/web/src/views/campaigns/Campaigns.vue
index 20b5a54..8e4d9e6 100644
--- a/web/src/views/campaigns/Campaigns.vue
+++ b/web/src/views/campaigns/Campaigns.vue
@@ -119,9 +119,12 @@ async function saveCampaign() {
}
async function deleteCampaign(campaign: Campaign) {
+ const warnLossOfData = ['sent', 'paused'].includes(campaign.status)
const confirmed = await confirm({
title: 'Delete Campaign',
- message: `Are you sure you want to delete "${campaign.name}"? This action cannot be undone.`,
+ message: warnLossOfData
+ ? `Delete "${campaign.name}"? Per-message delivery records will be removed. An aggregate stats snapshot is kept for reporting.`
+ : `Are you sure you want to delete "${campaign.name}"? This action cannot be undone.`,
confirmText: 'Delete',
variant: 'danger',
})
@@ -135,6 +138,10 @@ async function deleteCampaign(campaign: Campaign) {
}
}
+function canDeleteStatus(status: CampaignStatus): boolean {
+ return status !== 'sending'
+}
+
function statusBadgeClass(status: CampaignStatus): string {
switch (status) {
case 'draft': return 'badge badge-neutral'
@@ -221,7 +228,7 @@ onMounted(() => loadCampaigns())
<div style="display: flex; gap: 6px">
<button class="btn btn-secondary btn-sm" @click="router.push(`/campaigns/${campaign.id}`)">View</button>
<button
- v-if="wsStore.canEdit && (campaign.status === 'draft' || campaign.status === 'cancelled')"
+ v-if="wsStore.canEdit && canDeleteStatus(campaign.status)"
class="btn btn-danger btn-sm"
@click="deleteCampaign(campaign)"
>Delete</button>
diff --git a/web/src/views/dashboard/Dashboard.vue b/web/src/views/dashboard/Dashboard.vue
index 3e76571..c328c71 100644
--- a/web/src/views/dashboard/Dashboard.vue
+++ b/web/src/views/dashboard/Dashboard.vue
@@ -132,6 +132,16 @@ const totalVolume14d = computed(() => {
</div>
<div class="stat-value">{{ formatNumber(stats.queued_emails + stats.processing_emails) }}</div>
</div>
+ <div v-if="(stats.total_inbound ?? 0) > 0" class="stat-card" style="cursor: pointer" @click="$router.push('/inbound-emails')">
+ <div class="stat-header">
+ <div class="stat-label">Inbound</div>
+ <div class="stat-icon stat-icon-info">
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="22 12 16 12 14 15 10 15 8 12 2 12"/><path d="M5.45 5.11L2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"/></svg>
+ </div>
+ </div>
+ <div class="stat-value">{{ formatNumber(stats.total_inbound ?? 0) }}</div>
+ <div class="stat-sub">{{ formatNumber(stats.forwarded_inbound ?? 0) }} forwarded · {{ formatNumber(stats.failed_inbound ?? 0) }} failed</div>
+ </div>
</div>
<!-- Daily volume chart -->
diff --git a/web/src/views/domains/Domains.vue b/web/src/views/domains/Domains.vue
index 402188a..c6cf5f7 100644
--- a/web/src/views/domains/Domains.vue
+++ b/web/src/views/domains/Domains.vue
@@ -1,7 +1,7 @@
<script setup lang="ts">
-import { ref, onMounted } from 'vue'
+import { ref, onMounted, computed } from 'vue'
import { domainsApi } from '../../api/domains'
-import type { Domain, Pageable } from '../../api/types'
+import type { Domain, DnsRecord, Pageable } from '../../api/types'
import { useNotificationStore } from '../../stores/notification'
import { useConfirm } from '../../composables/useConfirm'
import { useModalSafeClose } from '../../composables/useModalSafeClose';
@@ -23,6 +23,74 @@ const saving = ref(false)
const expandedDomainId = ref<number | null>(null)
const dnsLoading = ref(false)
const dnsRecordsDomain = ref<Domain | null>(null)
+const verifying = ref(false)
+
+type RecordKey = 'verification' | 'spf' | 'dkim' | 'dmarc'
+
+interface RecordRow {
+ key: RecordKey
+ label: string
+ description: string
+ record: DnsRecord
+ verified: boolean
+}
+
+const recordDescriptions: Record<RecordKey, { label: string; description: string }> = {
+ verification: {
+ label: 'Ownership Verification',
+ description: 'Proves you control this domain. Posta will not send for an unverified domain when strict mode is enabled.',
+ },
+ spf: {
+ label: 'SPF',
+ description: 'Authorizes Posta’s mail servers to send on your behalf. Required to avoid spam filtering.',
+ },
+ dkim: {
+ label: 'DKIM',
+ description: 'Cryptographically signs each message so receivers can verify it wasn’t tampered with.',
+ },
+ dmarc: {
+ label: 'DMARC',
+ description: 'Tells receivers how to handle mail that fails SPF/DKIM. Start with p=none for monitoring.',
+ },
+}
+
+const recordRows = computed<RecordRow[]>(() => {
+ const d = dnsRecordsDomain.value
+ if (!d || !d.dns_records) return []
+ return [
+ { key: 'verification', ...recordDescriptions.verification, record: d.dns_records.verification, verified: !!d.ownership_verified },
+ { key: 'spf', ...recordDescriptions.spf, record: d.dns_records.spf, verified: !!d.spf_verified },
+ { key: 'dkim', ...recordDescriptions.dkim, record: d.dns_records.dkim, verified: !!d.dkim_verified },
+ { key: 'dmarc', ...recordDescriptions.dmarc, record: d.dns_records.dmarc, verified: !!d.dmarc_verified },
+ ]
+})
+
+function hostShortForm(fullHost: string, domain: string): string {
+ if (!fullHost || !domain) return fullHost
+ if (fullHost === domain) return '@'
+ const suffix = '.' + domain
+ if (fullHost.endsWith(suffix)) return fullHost.slice(0, -suffix.length)
+ return fullHost
+}
+
+async function copy(text: string, label = 'Value') {
+ try {
+ await navigator.clipboard.writeText(text)
+ notify.success(`${label} copied`)
+ } catch {
+ notify.error('Copy failed')
+ }
+}
+
+async function copyAllRecords() {
+ const d = dnsRecordsDomain.value
+ if (!d || !d.dns_records) return
+ const lines = ['Type\tHost\tValue']
+ for (const row of recordRows.value) {
+ lines.push(`${row.record.type}\t${row.record.name}\t${row.record.value}`)
+ }
+ await copy(lines.join('\n'), 'All records')
+}
async function fetchDomains() {
loading.value = true
@@ -54,12 +122,19 @@ async function addDomain() {
}
async function verifyDomain(domain: Domain) {
+ verifying.value = true
try {
await domainsApi.verify(domain.id)
notify.success(`Verification initiated for ${domain.domain}`)
await fetchDomains()
+ if (expandedDomainId.value === domain.id) {
+ const res = await domainsApi.get(domain.id)
+ dnsRecordsDomain.value = res.data.data
+ }
} catch {
notify.error('Verification failed')
+ } finally {
+ verifying.value = false
}
}
@@ -182,33 +257,84 @@ onMounted(fetchDomains)
<div v-if="dnsLoading" class="loading-page" style="min-height: 100px;">
<div class="spinner"></div>
</div>
- <div v-else-if="dnsRecordsDomain && dnsRecordsDomain.dns_records">
- <h4 style="margin-bottom: 12px; font-size: 14px; font-weight: 600; color: var(--text-secondary);">
- Required DNS Records for {{ domain.domain }}
- </h4>
- <div class="dns-record dns-record-highlight">
- <div class="dns-label">Ownership Verification</div>
- <div class="dns-type">{{ dnsRecordsDomain.dns_records.verification.type }}</div>
- <div class="dns-name">{{ dnsRecordsDomain.dns_records.verification.name }}</div>
- <div class="dns-value">{{ dnsRecordsDomain.dns_records.verification.value }}</div>
+ <div v-else-if="dnsRecordsDomain && dnsRecordsDomain.dns_records" class="dns-panel">
+ <div class="dns-panel-header">
+ <div>
+ <h4 class="dns-panel-title">DNS records for {{ domain.domain }}</h4>
+ <p class="dns-panel-subtitle">
+ Add the records below at your DNS provider, then click
+ <strong>Re-check</strong>. Propagation is usually under 15 minutes but can take up to 48 hours.
+ </p>
+ </div>
+ <div class="dns-panel-actions">
+ <button class="btn btn-secondary btn-sm" @click="copyAllRecords">Copy all</button>
+ <button
+ v-if="wsStore.canEdit"
+ class="btn btn-primary btn-sm"
+ :disabled="verifying"
+ @click="verifyDomain(domain)"
+ >
+ {{ verifying ? 'Checking…' : 'Re-check' }}
+ </button>
+ </div>
</div>
- <div class="dns-record">
- <div class="dns-label">SPF</div>
- <div class="dns-type">{{ dnsRecordsDomain.dns_records.spf.type }}</div>
- <div class="dns-name">{{ dnsRecordsDomain.dns_records.spf.name }}</div>
- <div class="dns-value">{{ dnsRecordsDomain.dns_records.spf.value }}</div>
- </div>
- <div class="dns-record">
- <div class="dns-label">DKIM</div>
- <div class="dns-type">{{ dnsRecordsDomain.dns_records.dkim.type }}</div>
- <div class="dns-name">{{ dnsRecordsDomain.dns_records.dkim.name }}</div>
- <div class="dns-value">{{ dnsRecordsDomain.dns_records.dkim.value }}</div>
- </div>
- <div class="dns-record">
- <div class="dns-label">DMARC</div>
- <div class="dns-type">{{ dnsRecordsDomain.dns_records.dmarc.type }}</div>
- <div class="dns-name">{{ dnsRecordsDomain.dns_records.dmarc.name }}</div>
- <div class="dns-value">{{ dnsRecordsDomain.dns_records.dmarc.value }}</div>
+
+ <div class="dns-record-list">
+ <div
+ v-for="row in recordRows"
+ :key="row.key"
+ class="dns-record"
+ :class="{ 'dns-record-highlight': row.key === 'verification', 'dns-record-verified': row.verified }"
+ >
+ <div class="dns-record-head">
+ <div class="dns-record-head-left">
+ <span class="dns-label">{{ row.label }}</span>
+ <span class="dns-type-badge">{{ row.record.type }}</span>
+ </div>
+ <span v-if="row.verified" class="dns-status dns-status-ok">
+ &#10003; Verified
+ </span>
+ <span v-else class="dns-status dns-status-pending">
+ &#9679; Pending
+ </span>
+ </div>
+ <p class="dns-record-desc">{{ row.description }}</p>
+
+ <div class="dns-field">
+ <div class="dns-field-label">Host / Name</div>
+ <div class="dns-field-row">
+ <code class="dns-field-value">{{ row.record.name }}</code>
+ <button
+ type="button"
+ class="btn btn-ghost btn-xs"
+ @click="copy(row.record.name, 'Host')"
+ >Copy</button>
+ </div>
+ <div
+ v-if="hostShortForm(row.record.name, domain.domain) !== row.record.name"
+ class="dns-field-hint"
+ >
+ Some providers (Cloudflare, Route 53, GoDaddy) only accept the subdomain part —
+ use <code>{{ hostShortForm(row.record.name, domain.domain) }}</code> instead.
+ </div>
+ </div>
+
+ <div class="dns-field">
+ <div class="dns-field-label">Value</div>
+ <div class="dns-field-row">
+ <code class="dns-field-value dns-field-value-block">{{ row.record.value }}</code>
+ <button
+ type="button"
+ class="btn btn-ghost btn-xs"
+ @click="copy(row.record.value, 'Value')"
+ >Copy</button>
+ </div>
+ </div>
+
+ <div class="dns-field-hint dns-ttl-hint">
+ TTL: Auto (or 3600). Leave priority blank unless your provider requires one.
+ </div>
+ </div>
</div>
</div>
<div v-else class="text-muted text-sm">
diff --git a/web/src/views/emails/EmailDetail.vue b/web/src/views/emails/EmailDetail.vue
index adac4b4..4b6c709 100644
--- a/web/src/views/emails/EmailDetail.vue
+++ b/web/src/views/emails/EmailDetail.vue
@@ -130,6 +130,17 @@ function parseHeaders(json: string): Record<string, string> | null {
<td style="font-weight: 600">SMTP Server</td>
<td>{{ email.smtp_hostname || 'N/A' }}</td>
</tr>
+ <tr>
+ <td style="font-weight: 600">Template</td>
+ <td>{{ email.template_name || 'N/A' }}</td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600">Provider</td>
+ <td>
+ <span v-if="email.provider" class="badge badge-info">{{ email.provider }}</span>
+ <span v-else style="color: var(--text-muted)">N/A</span>
+ </td>
+ </tr>
<tr>
<td style="font-weight: 600">Retry Count</td>
<td>{{ email.retry_count }}</td>
diff --git a/web/src/views/emails/Emails.vue b/web/src/views/emails/Emails.vue
index 48cdfc2..0bc6e9d 100644
--- a/web/src/views/emails/Emails.vue
+++ b/web/src/views/emails/Emails.vue
@@ -86,6 +86,7 @@ function formatDate(date: string | null) {
<th>Subject</th>
<th>From</th>
<th>Recipients</th>
+ <th>Template</th>
<th>Status</th>
<th>Sent At</th>
<th></th>
@@ -101,6 +102,7 @@ function formatDate(date: string | null) {
<td>{{ email.subject }}</td>
<td>{{ email.sender }}</td>
<td>{{ email.recipients.join(', ') }}</td>
+ <td>{{ email.template_name || 'N/A' }}</td>
<td><span :class="statusBadgeClass(email.status)">{{ email.status }}</span></td>
<td>{{ formatDate(email.sent_at) }}</td>
<td>
diff --git a/web/src/views/inbound/InboundEmailDetail.vue b/web/src/views/inbound/InboundEmailDetail.vue
new file mode 100644
index 0000000..b838465
--- /dev/null
+++ b/web/src/views/inbound/InboundEmailDetail.vue
@@ -0,0 +1,272 @@
+<script setup lang="ts">
+import { ref, computed, onMounted } from 'vue'
+import { useRoute, useRouter } from 'vue-router'
+import { inboundApi } from '../../api/inbound'
+import { useNotificationStore } from '../../stores/notification'
+import type { InboundEmail, InboundAttachmentMeta } from '../../api/types'
+
+const route = useRoute()
+const router = useRouter()
+const notify = useNotificationStore()
+const loading = ref(true)
+const email = ref<InboundEmail | null>(null)
+const activeTab = ref<'html' | 'text'>('html')
+const retrying = ref(false)
+const deleting = ref(false)
+
+onMounted(async () => {
+ await load()
+})
+
+async function load() {
+ loading.value = true
+ try {
+ const uuid = route.params.id as string
+ const res = await inboundApi.get(uuid)
+ email.value = res.data.data
+ if (!email.value?.html_body && email.value?.text_body) {
+ activeTab.value = 'text'
+ }
+ } catch (e) {
+ console.error('Failed to load inbound email', e)
+ } finally {
+ loading.value = false
+ }
+}
+
+async function retryEmail() {
+ if (!email.value || retrying.value) return
+ retrying.value = true
+ try {
+ const res = await inboundApi.retry(email.value.uuid)
+ email.value.status = res.data.data.status as InboundEmail['status']
+ email.value.error_message = ''
+ notify.success('Inbound email re-queued for webhook dispatch')
+ } catch (e: any) {
+ const msg = e.response?.data?.error?.message || 'Failed to retry inbound email'
+ notify.error(msg)
+ } finally {
+ retrying.value = false
+ }
+}
+
+async function deleteEmail() {
+ if (!email.value || deleting.value) return
+ if (!confirm('Delete this inbound email permanently? Attachments will also be removed.')) return
+ deleting.value = true
+ try {
+ await inboundApi.delete(email.value.uuid)
+ notify.success('Inbound email deleted')
+ router.push('/inbound-emails')
+ } catch (e: any) {
+ const msg = e.response?.data?.error?.message || 'Failed to delete inbound email'
+ notify.error(msg)
+ deleting.value = false
+ }
+}
+
+const headers = computed<Record<string, string> | null>(() => {
+ if (!email.value?.headers_json) return null
+ try {
+ const parsed = JSON.parse(email.value.headers_json)
+ return Object.keys(parsed).length > 0 ? parsed : null
+ } catch { return null }
+})
+
+const attachments = computed<InboundAttachmentMeta[]>(() => {
+ if (!email.value?.attachments_json) return []
+ try {
+ return JSON.parse(email.value.attachments_json)
+ } catch { return [] }
+})
+
+const hasRawEml = computed(() => !!email.value?.raw_storage_key)
+
+function statusBadgeClass(status: string) {
+ switch (status) {
+ case 'forwarded': return 'badge badge-success'
+ case 'failed': return 'badge badge-danger'
+ case 'received': return 'badge badge-info'
+ case 'rejected': return 'badge badge-warning'
+ default: return 'badge'
+ }
+}
+
+function sourceBadgeClass(source: string) {
+ return source === 'smtp' ? 'badge badge-secondary' : 'badge badge-info'
+}
+
+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`
+}
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <h1>Inbound Email</h1>
+ <div style="display: flex; gap: 8px">
+ <button
+ v-if="email && (email.status === 'failed' || email.status === 'received')"
+ class="btn btn-primary"
+ :disabled="retrying"
+ @click="retryEmail"
+ >
+ {{ retrying ? 'Retrying...' : 'Retry dispatch' }}
+ </button>
+ <a
+ v-if="hasRawEml && email"
+ class="btn btn-secondary"
+ :href="inboundApi.rawUrl(email.uuid)"
+ target="_blank"
+ rel="noopener"
+ >Download .eml</a>
+ <button
+ v-if="email"
+ class="btn btn-danger"
+ :disabled="deleting"
+ @click="deleteEmail"
+ >
+ {{ deleting ? 'Deleting...' : 'Delete' }}
+ </button>
+ <button class="btn btn-secondary" @click="router.push('/inbound-emails')">Back to Inbound</button>
+ </div>
+ </div>
+
+ <div v-if="loading" class="loading-page">
+ <div class="spinner"></div>
+ </div>
+
+ <template v-else-if="email">
+ <div class="card" style="margin-bottom: 24px">
+ <div class="card-header">
+ <h2>{{ email.subject || '(no subject)' }}</h2>
+ <div style="display: flex; gap: 8px">
+ <span :class="sourceBadgeClass(email.source)">{{ email.source }}</span>
+ <span :class="statusBadgeClass(email.status)">{{ email.status }}</span>
+ </div>
+ </div>
+ <div class="card-body">
+ <table>
+ <tbody>
+ <tr>
+ <td style="font-weight: 600; width: 160px">From</td>
+ <td>{{ email.sender }}</td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600">To</td>
+ <td>{{ email.recipients.join(', ') }}</td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600">Message-ID</td>
+ <td><code style="font-size: 12px">{{ email.message_id || '-' }}</code></td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600">Size</td>
+ <td>{{ formatBytes(email.size) }}</td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600">Received At</td>
+ <td>{{ formatDate(email.received_at) }}</td>
+ </tr>
+ <tr v-if="email.forwarded_at">
+ <td style="font-weight: 600">Forwarded At</td>
+ <td>{{ formatDate(email.forwarded_at) }}</td>
+ </tr>
+ <tr v-if="email.spam_score != null">
+ <td style="font-weight: 600">Spam Score</td>
+ <td>{{ email.spam_score }}</td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600">Retry Count</td>
+ <td>{{ email.retry_count }}</td>
+ </tr>
+ <tr v-if="email.error_message">
+ <td style="font-weight: 600">Error</td>
+ <td style="color: var(--danger-600)">{{ email.error_message }}</td>
+ </tr>
+ <tr v-if="headers">
+ <td style="font-weight: 600">Headers</td>
+ <td>
+ <div v-for="(value, key) in headers" :key="key" style="font-size: 12px; margin-bottom: 2px">
+ <code>{{ key }}: {{ value }}</code>
+ </div>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ </div>
+
+ <div v-if="attachments.length > 0" class="card" style="margin-bottom: 24px">
+ <div class="card-header">
+ <h3 style="margin: 0">Attachments ({{ attachments.length }})</h3>
+ </div>
+ <div class="card-body">
+ <table>
+ <thead>
+ <tr>
+ <th>Filename</th>
+ <th>Content Type</th>
+ <th>Size</th>
+ <th></th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="(att, idx) in attachments" :key="idx">
+ <td>{{ att.filename }}</td>
+ <td><code style="font-size: 12px">{{ att.content_type }}</code></td>
+ <td>{{ formatBytes(att.size) }}</td>
+ <td>
+ <a
+ class="btn btn-secondary btn-sm"
+ :href="inboundApi.attachmentUrl(email.uuid, idx)"
+ target="_blank"
+ rel="noopener"
+ >Download</a>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ </div>
+
+ <div class="card">
+ <div class="card-header">
+ <div class="tabs" style="margin-bottom: 0;">
+ <button class="tab" :class="{ active: activeTab === 'html' }" @click="activeTab = 'html'" :disabled="!email.html_body">HTML</button>
+ <button class="tab" :class="{ active: activeTab === 'text' }" @click="activeTab = 'text'" :disabled="!email.text_body">Text</button>
+ </div>
+ </div>
+ <div class="card-body">
+ <iframe
+ v-if="activeTab === 'html' && email.html_body"
+ :srcdoc="email.html_body"
+ sandbox=""
+ style="width: 100%; min-height: 400px; border: 1px solid var(--border-primary); border-radius: var(--radius)"
+ ></iframe>
+ <pre
+ v-else-if="activeTab === 'text' && email.text_body"
+ style="white-space: pre-wrap; word-wrap: break-word; font-size: 14px; color: var(--text-secondary); line-height: 1.6"
+ >{{ email.text_body }}</pre>
+ <div v-else class="empty-state" style="padding: 32px">
+ <p>No body content.</p>
+ </div>
+ </div>
+ </div>
+ </template>
+
+ <div v-else class="empty-state">
+ <h3>Inbound email not found</h3>
+ <p>The message you are looking for does not exist.</p>
+ </div>
+ </div>
+</template>
diff --git a/web/src/views/inbound/InboundEmails.vue b/web/src/views/inbound/InboundEmails.vue
new file mode 100644
index 0000000..34e0be7
--- /dev/null
+++ b/web/src/views/inbound/InboundEmails.vue
@@ -0,0 +1,193 @@
+<script setup lang="ts">
+import { onBeforeUnmount, onMounted, ref } from 'vue'
+import { useRouter } from 'vue-router'
+import { inboundApi } from '../../api/inbound'
+import type { InboundEmail } from '../../api/types'
+import Pagination from '../../components/Pagination.vue'
+import { usePagination } from '../../composables/usePagination'
+
+const router = useRouter()
+const loading = ref(true)
+const emails = ref<InboundEmail[]>([])
+const featureDisabled = ref(false)
+
+const status = ref('')
+const source = ref('')
+const sender = ref('')
+const q = ref('')
+
+const { pageable, goToPage } = usePagination(async (page) => {
+ loading.value = true
+ try {
+ const res = await inboundApi.list({
+ page,
+ status: status.value || undefined,
+ source: source.value || undefined,
+ sender: sender.value || undefined,
+ q: q.value || undefined,
+ })
+ emails.value = res.data.data
+ pageable.value = res.data.pageable
+ featureDisabled.value = false
+ } catch (e: any) {
+ if (e?.response?.status === 404) {
+ featureDisabled.value = true
+ } else {
+ console.error('Failed to load inbound emails', e)
+ }
+ } finally {
+ loading.value = false
+ }
+})
+
+function applyFilters() {
+ goToPage(0)
+}
+
+function resetFilters() {
+ status.value = ''
+ source.value = ''
+ sender.value = ''
+ q.value = ''
+ goToPage(0)
+}
+
+// Live updates via SSE — the backend filters to the authenticated user.
+let sse: EventSource | null = null
+onMounted(() => {
+ try {
+ sse = new EventSource(inboundApi.streamUrl(), { withCredentials: true })
+ sse.addEventListener('email.inbound.received', () => {
+ goToPage(pageable.value?.current_page ?? 0)
+ })
+ sse.onerror = () => { /* reconnects are handled by the browser */ }
+ } catch { /* SSE not supported */ }
+})
+onBeforeUnmount(() => {
+ if (sse) sse.close()
+})
+
+function statusBadgeClass(status: string) {
+ switch (status) {
+ case 'forwarded': return 'badge badge-success'
+ case 'failed': return 'badge badge-danger'
+ case 'received': return 'badge badge-info'
+ case 'rejected': return 'badge badge-warning'
+ default: return 'badge'
+ }
+}
+
+function sourceBadgeClass(src: string) {
+ return src === 'smtp' ? 'badge badge-secondary' : 'badge badge-info'
+}
+
+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`
+}
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <h1>Inbound Emails</h1>
+ </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>Inbound email is disabled</h3>
+ <p>
+ Ask your administrator to enable inbound processing by setting
+ <code>POSTA_INBOUND_ENABLED=true</code> and configuring the SMTP receiver.
+ </p>
+ </div>
+ </div>
+
+ <template v-else>
+ <div class="card" style="margin-bottom: 16px">
+ <div class="card-body" style="display: flex; gap: 8px; flex-wrap: wrap; align-items: flex-end">
+ <div>
+ <label style="display: block; font-size: 12px; font-weight: 600">Status</label>
+ <select v-model="status" @change="applyFilters">
+ <option value="">Any</option>
+ <option value="received">Received</option>
+ <option value="forwarded">Forwarded</option>
+ <option value="failed">Failed</option>
+ <option value="rejected">Rejected</option>
+ </select>
+ </div>
+ <div>
+ <label style="display: block; font-size: 12px; font-weight: 600">Source</label>
+ <select v-model="source" @change="applyFilters">
+ <option value="">Any</option>
+ <option value="smtp">SMTP</option>
+ <option value="webhook">Webhook</option>
+ </select>
+ </div>
+ <div>
+ <label style="display: block; font-size: 12px; font-weight: 600">Sender</label>
+ <input v-model="sender" placeholder="[email protected]" @keyup.enter="applyFilters" />
+ </div>
+ <div style="flex: 1; min-width: 200px">
+ <label style="display: block; font-size: 12px; font-weight: 600">Subject</label>
+ <input v-model="q" placeholder="Search subject..." @keyup.enter="applyFilters" />
+ </div>
+ <button class="btn btn-primary" @click="applyFilters">Apply</button>
+ <button class="btn btn-secondary" @click="resetFilters">Reset</button>
+ </div>
+ </div>
+
+ <div class="card">
+ <div v-if="emails.length === 0" class="empty-state">
+ <h3>No inbound emails</h3>
+ <p>Emails received via the built-in SMTP server or provider webhook will appear here.</p>
+ </div>
+ <template v-else>
+ <div class="table-wrapper">
+ <table>
+ <thead>
+ <tr>
+ <th>Subject</th>
+ <th>From</th>
+ <th>Recipients</th>
+ <th>Source</th>
+ <th>Status</th>
+ <th>Size</th>
+ <th>Received At</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr
+ v-for="email in emails"
+ :key="email.uuid"
+ style="cursor: pointer"
+ @click="router.push(`/inbound-emails/${email.uuid}`)"
+ >
+ <td>{{ email.subject || '(no subject)' }}</td>
+ <td>{{ email.sender }}</td>
+ <td>{{ email.recipients.join(', ') }}</td>
+ <td><span :class="sourceBadgeClass(email.source)">{{ email.source }}</span></td>
+ <td><span :class="statusBadgeClass(email.status)">{{ email.status }}</span></td>
+ <td>{{ formatBytes(email.size) }}</td>
+ <td>{{ formatDate(email.received_at) }}</td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ <Pagination :pageable="pageable" @page="goToPage" />
+ </template>
+ </div>
+ </template>
+ </div>
+</template>
diff --git a/web/src/views/invitations/InvitationAccept.vue b/web/src/views/invitations/InvitationAccept.vue
new file mode 100644
index 0000000..4cb9cb7
--- /dev/null
+++ b/web/src/views/invitations/InvitationAccept.vue
@@ -0,0 +1,146 @@
+<script setup lang="ts">
+import { computed, onMounted, ref } from 'vue'
+import { useRoute, useRouter } from 'vue-router'
+import { useAuthStore } from '../../stores/auth'
+import { workspaceApi } from '../../api/workspaces'
+
+const route = useRoute()
+const router = useRouter()
+const auth = useAuthStore()
+
+const token = computed(() => (route.query.token as string) || '')
+const status = ref<'idle' | 'accepting' | 'success' | 'error'>('idle')
+const message = ref('')
+
+const loginHref = computed(() => {
+ const target = `/invitations?token=${encodeURIComponent(token.value)}`
+ return `/login?redirect=${encodeURIComponent(target)}`
+})
+
+onMounted(async () => {
+ if (!token.value) {
+ status.value = 'error'
+ message.value = 'Missing invitation token.'
+ return
+ }
+ if (!auth.isAuthenticated) {
+ return
+ }
+ await accept()
+})
+
+async function accept() {
+ status.value = 'accepting'
+ try {
+ const res = await workspaceApi.acceptInvitationByToken(token.value)
+ message.value = res.data.data?.message || 'Invitation accepted.'
+ status.value = 'success'
+ } catch (err: any) {
+ const apiMsg =
+ err?.response?.data?.error?.message ||
+ err?.response?.data?.error ||
+ err?.message ||
+ 'Failed to accept invitation.'
+ message.value = apiMsg
+ status.value = 'error'
+ }
+}
+
+function goToWorkspaces() {
+ router.push('/workspaces')
+}
+</script>
+
+<template>
+ <div class="invitation-page">
+ <div class="invitation-card">
+ <h1>Workspace invitation</h1>
+
+ <template v-if="status === 'error' && !token">
+ <p class="muted">{{ message }}</p>
+ <router-link to="/" class="btn">Go to dashboard</router-link>
+ </template>
+
+ <template v-else-if="!auth.isAuthenticated">
+ <p>Please sign in to accept this workspace invitation.</p>
+ <a :href="loginHref" class="btn btn-primary">Sign in to continue</a>
+ </template>
+
+ <template v-else-if="status === 'accepting' || status === 'idle'">
+ <div class="spinner"></div>
+ <p class="muted">Accepting invitation…</p>
+ </template>
+
+ <template v-else-if="status === 'success'">
+ <p class="success">{{ message }}</p>
+ <button class="btn btn-primary" @click="goToWorkspaces">Open workspaces</button>
+ </template>
+
+ <template v-else>
+ <p class="error">{{ message }}</p>
+ <router-link to="/workspaces" class="btn">Go to workspaces</router-link>
+ </template>
+ </div>
+ </div>
+</template>
+
+<style scoped>
+.invitation-page {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ min-height: 100vh;
+ background: var(--bg-secondary);
+ padding: 24px;
+}
+.invitation-card {
+ background: var(--bg-primary);
+ border: 1px solid var(--border-color);
+ border-radius: 8px;
+ padding: 32px;
+ max-width: 420px;
+ width: 100%;
+ text-align: center;
+}
+.invitation-card h1 {
+ font-size: 20px;
+ margin: 0 0 16px;
+ color: var(--text-primary);
+}
+.invitation-card p {
+ font-size: 14px;
+ color: var(--text-secondary);
+ margin: 8px 0 20px;
+}
+.muted { color: var(--text-muted); }
+.success { color: var(--success-600, #16a34a); }
+.error { color: var(--danger-600, #dc2626); }
+.btn {
+ display: inline-block;
+ padding: 10px 18px;
+ border-radius: 6px;
+ border: 1px solid var(--border-color);
+ background: var(--bg-primary);
+ color: var(--text-primary);
+ font-size: 14px;
+ text-decoration: none;
+ cursor: pointer;
+}
+.btn-primary {
+ background: var(--primary-600, #2563eb);
+ border-color: var(--primary-600, #2563eb);
+ color: #fff;
+}
+.spinner {
+ width: 32px;
+ height: 32px;
+ border: 3px solid var(--border-color);
+ border-top-color: var(--primary-600, #2563eb);
+ border-radius: 50%;
+ margin: 12px auto;
+ animation: spin 0.8s linear infinite;
+}
+@keyframes spin {
+ to { transform: rotate(360deg); }
+}
+</style>
diff --git a/web/src/views/templates/TemplatePreview.vue b/web/src/views/templates/TemplatePreview.vue
index 53cfdaa..5bd40f8 100644
--- a/web/src/views/templates/TemplatePreview.vue
+++ b/web/src/views/templates/TemplatePreview.vue
@@ -1,5 +1,5 @@
<script setup lang="ts">
-import { ref, onMounted, watch } from 'vue'
+import { computed, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { templatesApi } from '../../api/templates'
import type { Template, TemplatePreview, TemplateLocalization, TemplateVersion } from '../../api/types'
@@ -19,19 +19,43 @@ const previewError = ref('')
const activeTab = ref<'html' | 'text'>('html')
const sampleData = ref('{\n "name": "John",\n "company": "Acme"\n}')
+const allTemplates = ref<Template[]>([])
+const search = ref('')
+const searchOpen = ref(false)
+
+const searchResults = computed<Template[]>(() => {
+ const q = search.value.trim().toLowerCase()
+ if (!q) return allTemplates.value.slice(0, 10)
+ return allTemplates.value.filter(t => t.name.toLowerCase().includes(q)).slice(0, 20)
+})
+
let debounceTimer: ReturnType<typeof setTimeout> | null = null
watch(sampleData, () => {
if (debounceTimer) clearTimeout(debounceTimer)
debounceTimer = setTimeout(() => renderPreview(), 500)
})
-onMounted(async () => {
- const id = Number(route.params.id)
+watch(() => route.params.id, (id) => {
+ if (id) loadTemplate(Number(id))
+})
+
+onMounted(() => {
+ loadTemplate(Number(route.params.id))
+})
+
+async function loadTemplate(id: number) {
+ loading.value = true
+ template.value = null
+ version.value = null
+ localization.value = null
+ preview.value = null
try {
- // Load template
- const res = await templatesApi.list(0, 100)
- template.value = res.data.data.find((t: Template) => t.id === id) || null
+ if (allTemplates.value.length === 0) {
+ const res = await templatesApi.list(0, 100)
+ allTemplates.value = res.data.data
+ }
+ template.value = allTemplates.value.find((t: Template) => t.id === id) || null
if (!template.value) {
notify.error('Template not found')
@@ -39,9 +63,10 @@ onMounted(async () => {
return
}
+ search.value = template.value.name
+
if (template.value.sample_data) sampleData.value = template.value.sample_data
- // Load the active version and its default localization
if (template.value.active_version_id) {
const versionsRes = await templatesApi.listVersions(id)
version.value = (versionsRes.data.data || []).find((v: TemplateVersion) => v.id === template.value!.active_version_id) || null
@@ -59,7 +84,18 @@ onMounted(async () => {
} finally {
loading.value = false
}
-})
+}
+
+function selectTemplate(t: Template) {
+ searchOpen.value = false
+ if (t.id === template.value?.id) return
+ router.push(`/templates/${t.id}/preview`)
+}
+
+function onSearchBlur() {
+ // Delay so click on a result still registers.
+ setTimeout(() => { searchOpen.value = false }, 150)
+}
async function renderPreview() {
if (!template.value || !localization.value || !template.value.active_version_id) return
@@ -108,6 +144,33 @@ function formatDate(dateStr: string): string {
<button class="btn btn-secondary" @click="router.push('/templates')">Back to Templates</button>
</div>
+ <div class="template-search" style="margin-bottom: 16px; position: relative; max-width: 420px;">
+ <input
+ v-model="search"
+ type="text"
+ class="form-input"
+ placeholder="Search templates by name..."
+ @focus="searchOpen = true"
+ @blur="onSearchBlur"
+ />
+ <div v-if="searchOpen && searchResults.length > 0" class="template-search-results">
+ <button
+ v-for="t in searchResults"
+ :key="t.id"
+ type="button"
+ class="template-search-item"
+ :class="{ active: t.id === template?.id }"
+ @mousedown.prevent="selectTemplate(t)"
+ >
+ <span class="template-search-name">{{ t.name }}</span>
+ <span v-if="t.description" class="template-search-desc">{{ t.description }}</span>
+ </button>
+ </div>
+ <div v-else-if="searchOpen && search.trim()" class="template-search-results template-search-empty">
+ No templates match "{{ search }}"
+ </div>
+ </div>
+
<div v-if="loading" class="loading-page">
<div class="spinner"></div>
</div>
@@ -306,4 +369,54 @@ function formatDate(dateStr: string): string {
color: var(--text-muted);
margin-bottom: 6px;
}
+
+.template-search-results {
+ position: absolute;
+ top: 100%;
+ left: 0;
+ right: 0;
+ margin-top: 4px;
+ background: var(--bg-primary);
+ border: 1px solid var(--border-primary);
+ border-radius: var(--radius);
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
+ z-index: 10;
+ max-height: 320px;
+ overflow-y: auto;
+}
+
+.template-search-item {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 2px;
+ width: 100%;
+ padding: 8px 12px;
+ background: transparent;
+ border: none;
+ text-align: left;
+ cursor: pointer;
+ border-bottom: 1px solid var(--border-primary);
+}
+.template-search-item:last-child { border-bottom: none; }
+.template-search-item:hover { background: var(--bg-hover, rgba(0, 0, 0, 0.04)); }
+.template-search-item.active { background: var(--primary-50, rgba(0, 95, 204, 0.08)); }
+
+.template-search-name {
+ font-size: 14px;
+ font-weight: 500;
+ color: var(--text-primary);
+}
+
+.template-search-desc {
+ font-size: 12px;
+ color: var(--text-muted);
+}
+
+.template-search-empty {
+ padding: 12px;
+ font-size: 13px;
+ color: var(--text-muted);
+ text-align: center;
+}
</style>
diff --git a/web/src/views/webhooks/Webhooks.vue b/web/src/views/webhooks/Webhooks.vue
index 43eea4d..d225acd 100644
--- a/web/src/views/webhooks/Webhooks.vue
+++ b/web/src/views/webhooks/Webhooks.vue
@@ -31,7 +31,7 @@ const createdWebhook = ref<Webhook | null>(null)
const showSecretModal = ref(false)
const copied = ref(false)
-const availableEvents = ['email.sent', 'email.failed']
+const availableEvents = ['email.sent', 'email.failed', 'email.inbound']
async function fetchWebhooks(page = 0) {
loading.value = true
@@ -221,6 +221,7 @@ const { watchClickStart, confirmClickEnd } = useModalSafeClose(() => {
<label class="form-label">Sender Filters <span class="text-muted">(optional)</span></label>
<p style="font-size: 0.85em; color: var(--text-muted); margin: 0 0 8px;">
Restrict this webhook to specific senders. Enter an email address or domain. Leave empty to fire for all emails.
+ For <code>email.inbound</code>, the filter matches the <strong>sender</strong> of the incoming message (the <code>From</code> address), not the recipient.
</p>
<div style="display: flex; gap: 8px;">
<input