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.

12.9 KB
Raw Blame
// Copyright (c) 2026 Jonas Kaninda.
//
// This file is part of Posta.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: AGPL-3.0-or-later

package handlers

import (
	"errors"
	"fmt"
	"strings"

	"github.com/goposta/posta/internal/models"
	"github.com/goposta/posta/internal/services/cache"
	"github.com/goposta/posta/internal/services/email"
	"github.com/goposta/posta/internal/services/eventbus"
	"github.com/goposta/posta/internal/services/settings"
	"github.com/goposta/posta/internal/storage/repositories"
	"github.com/jkaninda/okapi"
)

type EmailHandler struct {
	service   *email.Service
	emailRepo *repositories.EmailRepository
	bus       *eventbus.EventBus
	cache     *cache.Cache
	settings  *settings.Provider
}
type SendEmailRequest struct {
	DryRun bool              `query:"dry_run" doc:"Validate the request without sending"`
	Body   email.SendRequest `json:"body"`
}
type SendTemplateEmailRequest struct {
	DryRun bool                      `query:"dry_run"`
	Body   email.SendTemplateRequest `json:"body"`
}
type SendBatchEmailRequest struct {
	DryRun bool               `query:"dry_run" doc:"Validate the request without sending"`
	Body   email.BatchRequest `json:"body"`
}
type ListRequest struct {
	Page int    `query:"page" default:"0"`
	Size int    `query:"size" default:"20"`
	Q    string `query:"q" doc:"Search with operators: from: to: subject: template: has:attachment after: before: status:"`
	Sort string `query:"sort" doc:"Sort key: created_at|sent_at|subject|sender|template|status, prefix '-' for descending (default: -created_at)"`
}
type GetByIDRequest struct {
	ID int `param:"id"`
}
type GetEmailRequest struct {
	ID string `param:"id"`
}

func NewEmailHandler(service *email.Service, emailRepo *repositories.EmailRepository, bus *eventbus.EventBus, c *cache.Cache) *EmailHandler {
	return &EmailHandler{
		service:   service,
		emailRepo: emailRepo,
		bus:       bus,
		cache:     c,
	}
}

func (h *EmailHandler) SetSettings(s *settings.Provider) { h.settings = s }

// redactContent returns true if email body content should be hidden.
func (h *EmailHandler) redactContent() bool {
	if h.settings != nil && h.settings.EmailContentVisibility() {
		return false
	}
	return true
}

type PreviewEmailRequest struct {
	Body struct {
		Template     email.TemplateRef `json:"template" doc:"Template name or ID. A name is matched first; a value that is all digits and matches no name is looked up as an ID."`
		TemplateID   *uint             `json:"template_id,omitempty" deprecated:"true" doc:"Deprecated: pass the ID in template instead. Used only when template is empty."`
		Language     string            `json:"language" doc:"Language code for localization"`
		TemplateData map[string]any    `json:"template_data" doc:"Variables to inject into the template"`
	} `json:"body"`
}

type PreviewEmailResponse struct {
	Subject string `json:"subject"`
	HTML    string `json:"html"`
	Text    string `json:"text"`
}

func (h *EmailHandler) Preview(c *okapi.Context, req *PreviewEmailRequest) error {
	scope := getScope(c)

	rendered, err := h.service.RenderTemplate(scope.UserID, scope.WorkspaceID, req.Body.TemplateID, req.Body.Template, req.Body.Language, req.Body.TemplateData)
	if err != nil {
		return c.AbortBadRequest(err.Error())
	}

	return ok(c, PreviewEmailResponse{
		Subject: rendered.Subject,
		HTML:    rendered.HTML,
		Text:    rendered.Text,
	})
}

const redactedPlaceholder = "[redacted]"

func redactEmail(em *models.Email) {
	em.HTMLBody = redactedPlaceholder
	em.TextBody = redactedPlaceholder
}

func redactEmails(emails []models.Email) {
	for i := range emails {
		redactEmail(&emails[i])
	}
}

func (h *EmailHandler) Send(c *okapi.Context, req *SendEmailRequest) error {
	if err := requireEdit(c); err != nil {
		return c.AbortForbidden("insufficient workspace permissions", err)
	}
	userID := c.GetInt("user_id")
	userEmail := c.GetString("user_email")
	scope := getScope(c)

	if req.DryRun {
		return h.handleDryRun(c, userID, scope.WorkspaceID, userEmail, req)
	}

	apiKeyID := c.GetInt("api_key_id")
	resp, err := h.service.Send(c.Request().Context(), uint(userID), uint(apiKeyID), scope.WorkspaceID, userEmail, &req.Body)
	if err != nil {
		if resp := mapUnsubscribeError(c, err); resp != nil {
			// Call abort here
			return resp
		}
		if isRateLimitError(err) {
			return c.AbortTooManyRequests(err.Error())
		}
		if isDomainVerificationError(err) {
			return c.AbortForbidden("insufficient workspace permissions", err)
		}
		return c.AbortInternalServerError(err.Error())
	}

	// Invalidate dashboard and metrics caches after queuing
	h.cache.InvalidateUser(c.Request().Context(), userID)
	h.cache.InvalidateAnalytics(c.Request().Context())

	if h.bus != nil {
		uid := uint(userID)
		h.bus.PublishSimple(models.EventCategoryEmail, "email.queued", &uid, userEmail, c.RealIP(),
			fmt.Sprintf("Email queued to %v", req.Body.To), map[string]any{"email_uuid": resp.ID})
	}

	return ok(c, resp)
}

func (h *EmailHandler) handleDryRun(c *okapi.Context, userID int, workspaceID *uint, userEmail string, req *SendEmailRequest) error {
	resp, err := h.service.ValidateSend(c.Request().Context(), uint(userID), workspaceID, userEmail, &req.Body)
	if err != nil {
		if resp := mapUnsubscribeError(c, err); resp != nil {
			return resp
		}
		if isRateLimitError(err) {
			return c.AbortTooManyRequests(err.Error())
		}
		if isDomainVerificationError(err) {
			return c.AbortForbidden("insufficient workspace permissions", err)
		}
		return c.AbortBadRequest(err.Error())
	}
	return ok(c, resp)
}

func (h *EmailHandler) SendWithTemplate(c *okapi.Context, req *SendTemplateEmailRequest) error {
	if err := requireEdit(c); err != nil {
		return c.AbortForbidden("insufficient workspace permissions", err)
	}
	userID := c.GetInt("user_id")
	userEmail := c.GetString("user_email")
	scope := getScope(c)

	if req.DryRun {
		resp, err := h.service.ValidateSendWithTemplate(c.Request().Context(), uint(userID), scope.WorkspaceID, userEmail, &req.Body)
		if err != nil {
			if resp := mapUnsubscribeError(c, err); resp != nil {
				return resp
			}
			if isRateLimitError(err) {
				return c.AbortTooManyRequests(err.Error())
			}
			if isDomainVerificationError(err) {
				return c.AbortForbidden("insufficient workspace permissions", err)
			}
			return c.AbortBadRequest(err.Error())
		}
		return ok(c, resp)
	}

	apiKeyID := c.GetInt("api_key_id")
	resp, err := h.service.SendWithTemplate(c.Request().Context(), uint(userID), uint(apiKeyID), scope.WorkspaceID, userEmail, &req.Body)
	if err != nil {
		if resp := mapUnsubscribeError(c, err); resp != nil {
			return resp
		}
		if isRateLimitError(err) {
			return c.AbortTooManyRequests(err.Error())
		}
		if isDomainVerificationError(err) {
			return c.AbortForbidden("insufficient workspace permissions", err)
		}
		return c.AbortInternalServerError(err.Error())
	}

	h.cache.InvalidateUser(c.Request().Context(), userID)
	h.cache.InvalidateAnalytics(c.Request().Context())

	if h.bus != nil {
		uid := uint(userID)
		h.bus.PublishSimple(models.EventCategoryEmail, "email.queued", &uid, userEmail, c.RealIP(),
			fmt.Sprintf("Template email queued to %v", req.Body.To), map[string]any{"email_uuid": resp.ID, "template": req.Body.Template})
	}

	return ok(c, resp)
}

func (h *EmailHandler) SendBatch(c *okapi.Context, req *SendBatchEmailRequest) error {
	if err := requireEdit(c); err != nil {
		return c.AbortForbidden("insufficient workspace permissions", err)
	}
	userID := c.GetInt("user_id")
	userEmail := c.GetString("user_email")
	scope := getScope(c)

	if req.DryRun {
		resp, err := h.service.ValidateSendBatch(c.Request().Context(), uint(userID), scope.WorkspaceID, userEmail, &req.Body)
		if err != nil {
			if resp := mapUnsubscribeError(c, err); resp != nil {
				return resp
			}
			if isRateLimitError(err) {
				return c.AbortTooManyRequests(err.Error())
			}
			return c.AbortBadRequest(err.Error())
		}
		return ok(c, resp)
	}

	apiKeyID := c.GetInt("api_key_id")
	resp, err := h.service.SendBatch(c.Request().Context(), uint(userID), uint(apiKeyID), scope.WorkspaceID, userEmail, &req.Body)
	if err != nil {
		if resp := mapUnsubscribeError(c, err); resp != nil {
			return resp
		}
		if isRateLimitError(err) {
			return c.AbortTooManyRequests(err.Error())
		}
		if isDomainVerificationError(err) {
			return c.AbortForbidden("insufficient workspace permissions", err)
		}
		return c.AbortInternalServerError(err.Error())
	}

	h.cache.InvalidateUser(c.Request().Context(), userID)
	h.cache.InvalidateAnalytics(c.Request().Context())

	if h.bus != nil {
		uid := uint(userID)
		h.bus.PublishSimple(models.EventCategoryEmail, "email.batch_queued", &uid, userEmail, c.RealIP(),
			fmt.Sprintf("Batch of %d emails queued", len(resp.Results)), map[string]any{"count": len(resp.Results)})
	}

	return ok(c, resp)
}

func normalizePageParams(page, size int) (int, int, int) {
	if size <= 0 || size > 100 {
		size = 20
	}
	if page < 0 {
		page = 0
	}
	offset := page * size
	return page, size, offset
}

func (h *EmailHandler) List(c *okapi.Context, req *ListRequest) error {
	page, size, offset := normalizePageParams(req.Page, req.Size)

	filter := repositories.ParseSearchQuery(req.Q)
	emails, total, err := h.emailRepo.FindByScopeFiltered(getScope(c), filter, req.Sort, size, offset)
	if err != nil {
		return c.AbortInternalServerError("failed to list emails")
	}

	if h.redactContent() {
		redactEmails(emails)
	}

	return paginated(c, emails, total, page, size)
}

func (h *EmailHandler) Get(c *okapi.Context, req *GetEmailRequest) error {
	em, err := h.emailRepo.FindByUUIDWithAPIKey(req.ID)
	if err != nil || !ownsResource(c, em.UserID, em.WorkspaceID) {
		return c.AbortNotFound("email not found")
	}

	// Surface the name of the API key used to send this email (if still linked).
	if em.APIKeyID != nil {
		em.APIKeyName = em.APIKey.Name
	}

	if h.redactContent() {
		redactEmail(em)
	}

	return ok(c, em)
}

// EmailStatusResponse is a lightweight view of an email's delivery status.
type EmailStatusResponse struct {
	ID           string             `json:"id"`
	Status       models.EmailStatus `json:"status"`
	ErrorMessage string             `json:"error_message,omitempty"`
	RetryCount   int                `json:"retry_count"`
	CreatedAt    string             `json:"created_at"`
	SentAt       *string            `json:"sent_at,omitempty"`
}

// GetStatus returns only the delivery status of an email (owner only).
func (h *EmailHandler) GetStatus(c *okapi.Context, req *GetEmailRequest) error {
	em, err := h.emailRepo.FindByUUID(req.ID)
	if err != nil || !ownsResource(c, em.UserID, em.WorkspaceID) {
		return c.AbortNotFound("email not found")
	}

	resp := EmailStatusResponse{
		ID:           em.UUID,
		Status:       em.Status,
		ErrorMessage: em.ErrorMessage,
		RetryCount:   em.RetryCount,
		CreatedAt:    em.CreatedAt.Format("2006-01-02T15:04:05Z07:00"),
	}
	if em.SentAt != nil {
		s := em.SentAt.Format("2006-01-02T15:04:05Z07:00")
		resp.SentAt = &s
	}

	return ok(c, resp)
}

// Retry re-enqueues a failed email for another delivery attempt.
func (h *EmailHandler) Retry(c *okapi.Context, req *GetEmailRequest) error {
	userID := c.GetInt("user_id")
	scope := getScope(c)
	resp, err := h.service.RetryEmail(req.ID, uint(userID), scope.WorkspaceID)
	if err != nil {
		if err.Error() == "email not found" {
			return c.AbortNotFound(err.Error())
		}
		return c.AbortBadRequest(err.Error())
	}
	return ok(c, resp)
}

// Dev mode handlers
func (h *EmailHandler) DevList(c *okapi.Context, req *ListRequest) error {
	page, size, offset := normalizePageParams(req.Page, req.Size)

	emails, total, err := h.emailRepo.FindAll(size, offset)
	if err != nil {
		return c.AbortInternalServerError("failed to list emails")
	}

	return paginated(c, emails, total, page, size)
}

func (h *EmailHandler) DevGet(c *okapi.Context) error {
	uuid := c.PathParam("id")
	if uuid == "" {
		return c.AbortBadRequest("invalid email id")
	}

	em, err := h.emailRepo.FindByUUID(uuid)
	if err != nil {
		return c.AbortNotFound("email not found")
	}

	return ok(c, em)
}

func isRateLimitError(err error) bool {
	return err != nil && len(err.Error()) > 11 && err.Error()[:11] == "rate_limit:"
}

func isDomainVerificationError(err error) bool {
	return err != nil && strings.HasPrefix(err.Error(), "domain_verification:")
}

func mapUnsubscribeError(c *okapi.Context, err error) error {
	if errors.Is(err, email.ErrUnsubscribeListNotFound) {
		return c.AbortNotFound(err.Error())
	}
	if errors.Is(err, email.ErrUnsubscribeInvalid) {
		return c.AbortBadRequest(err.Error())
	}
	return nil
}