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.

29.5 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 (
	"encoding/json"
	"fmt"
	"html"
	"maps"
	"net/mail"
	"net/url"
	"regexp"
	"strings"
	"time"

	"github.com/goposta/posta/internal/enterprise"
	"github.com/goposta/posta/internal/models"
	"github.com/goposta/posta/internal/services/audit"
	"github.com/goposta/posta/internal/services/messages"
	"github.com/goposta/posta/internal/services/settings"
	"github.com/goposta/posta/internal/storage/repositories"
	"github.com/jkaninda/okapi"
)

const metaName = "name"

const publicKeyAlphabet = models.FormPublicKeyAlphabet
const publicKeyLength = models.FormPublicKeyLength

type FormHandler struct {
	repo *repositories.FormRepository
	// hostedSettings and workspaces tell the snippet whether the share link works.
	hostedSettings *settings.Provider
	workspaces     *repositories.WorkspaceRepository
	messageRepo    *repositories.MessageRepository
	domainRepo     *repositories.DomainRepository
	audit          *audit.Logger
	apiBaseURL     string
	keyCache       FormKeyInvalidator
	edition        enterprise.EE
}

// FormKeyInvalidator drops cached public-key lookups; *messages.Service
// implements it.
type FormKeyInvalidator interface {
	InvalidateFormKey(keys ...string)
}

// SetEdition enables the Posta Enterprise parts of the form schema
// (branching). Without it they are refused, as in Community.
func (h *FormHandler) SetEdition(ee enterprise.EE) { h.edition = ee }

// SetKeyCache makes form edits take effect on the public endpoint immediately
// instead of after the lookup cache expires.
func (h *FormHandler) SetKeyCache(c FormKeyInvalidator) { h.keyCache = c }

func (h *FormHandler) invalidate(keys ...string) {
	if h.keyCache != nil {
		h.keyCache.InvalidateFormKey(keys...)
	}
}

func NewFormHandler(
	repo *repositories.FormRepository,
	messageRepo *repositories.MessageRepository,
	domainRepo *repositories.DomainRepository,
	auditLogger *audit.Logger,
	apiBaseURL string,
) *FormHandler {
	return &FormHandler{
		repo:        repo,
		messageRepo: messageRepo,
		domainRepo:  domainRepo,
		audit:       auditLogger,
		apiBaseURL:  strings.TrimSuffix(apiBaseURL, "/"),
	}
}

type CreateFormRequest struct {
	Body struct {
		Name             string   `json:"name" doc:"The form's name, as typed: \"Contact form\" is stored as the identifier contact-form, with \"Contact form\" as display_name. It cannot change later."`
		DisplayName      string   `json:"display_name" doc:"The form's label. Defaults to name."`
		Slug             string   `json:"slug,omitempty" doc:"Deprecated: the identifier before 0.18, now name."`
		Description      string   `json:"description"`
		Mode             string   `json:"mode" enum:"inbox,collect" doc:"inbox (default): submissions are conversations to answer. collect: responses read as a table, kept out of the inbox."`
		AllowedOrigins   []string `json:"allowed_origins"`
		StrictOrigin     bool     `json:"strict_origin"`
		RedirectURL      string   `json:"redirect_url"`
		AllowAttachments bool     `json:"allow_attachments"`
		RequireNonce     bool     `json:"require_nonce"`
		NotifyEmails     []string `json:"notify_emails"`
		NotifyMode       string   `json:"notify_mode" enum:"immediate,hourly,daily,off"`
		RedactPII        bool     `json:"redact_pii_in_webhooks" doc:"Leave answers to personal-data questions out of webhook payloads"`
		ReplyFrom        string   `json:"reply_from"`
		ReplyFromName    string   `json:"reply_from_name"`

		Fields           models.FieldDefs `json:"fields" doc:"Optional schema. Submissions are validated against it and stored with typed data."`
		UnknownFields    string           `json:"unknown_fields" enum:"keep,drop,reject" doc:"What happens to submitted keys the schema does not declare. Default keep."`
		ErrorRedirectURL string           `json:"error_redirect_url" doc:"Where a plain HTML form is sent when validation fails, with ?posta_error=validation_failed&field=<key>."`

		ConfirmationMessage  *string                `json:"confirmation_message" doc:"Shown after a successful submission"`
		ClosedMessage        *string                `json:"closed_message" doc:"Shown while the form is paused, past close_at, or at max_responses"`
		CloseAt              *string                `json:"close_at" doc:"RFC 3339 time after which the form stops accepting responses; empty clears it"`
		MaxResponses         *int                   `json:"max_responses" doc:"Stop accepting responses after this many non-spam submissions; 0 means no limit"`
		AllowAnotherResponse *bool                  `json:"allow_another_response" doc:"Offer a link to submit another response after submitting"`
		Appearance           *models.FormAppearance `json:"appearance" doc:"Accent colour (#RRGGBB), theme (light, dark, auto) and https header image for the hosted page and widget"`
	} `json:"body"`
}

type UpdateFormRequest struct {
	ID   int `param:"id"`
	Body struct {
		Name                string            `json:"name" doc:"A form's name cannot change; only accepted when it is the current one."`
		DisplayName         string            `json:"display_name"`
		Slug                string            `json:"slug,omitempty" doc:"Deprecated: the identifier before 0.18, now name."`
		Description         string            `json:"description"`
		Status              string            `json:"status" enum:"active,paused,archived"`
		Mode                *string           `json:"mode" doc:"inbox or collect"`
		AllowedOrigins      *[]string         `json:"allowed_origins"`
		StrictOrigin        *bool             `json:"strict_origin"`
		RedirectURL         *string           `json:"redirect_url"`
		MaxBodyBytes        *int64            `json:"max_body_bytes"`
		MaxFields           *int              `json:"max_fields"`
		AllowAttachments    *bool             `json:"allow_attachments"`
		HoneypotField       *string           `json:"honeypot_field"`
		RequireNonce        *bool             `json:"require_nonce"`
		MinFillSeconds      *int              `json:"min_fill_seconds"`
		ScanEnabled         *bool             `json:"scan_enabled"`
		FlagThreshold       *float64          `json:"flag_threshold"`
		QuarantineThreshold *float64          `json:"quarantine_threshold"`
		RejectThreshold     *float64          `json:"reject_threshold"`
		NotifyEnabled       *bool             `json:"notify_enabled"`
		NotifyEmails        *[]string         `json:"notify_emails"`
		Fields              *models.FieldDefs `json:"fields" doc:"Replaces the schema. Keys already saved cannot be removed; set archived instead."`
		UnknownFields       *string           `json:"unknown_fields" doc:"keep, drop or reject"`
		ErrorRedirectURL    *string           `json:"error_redirect_url"`

		ConfirmationMessage  *string                `json:"confirmation_message" doc:"Shown after a successful submission"`
		ClosedMessage        *string                `json:"closed_message" doc:"Shown while the form is paused, past close_at, or at max_responses"`
		CloseAt              *string                `json:"close_at" doc:"RFC 3339 time after which the form stops accepting responses; empty clears it"`
		MaxResponses         *int                   `json:"max_responses" doc:"Stop accepting responses after this many non-spam submissions; 0 means no limit"`
		AllowAnotherResponse *bool                  `json:"allow_another_response" doc:"Offer a link to submit another response after submitting"`
		Appearance           *models.FormAppearance `json:"appearance" doc:"Accent colour (#RRGGBB), theme (light, dark, auto) and https header image for the hosted page and widget"`
		NotifyMode           *string                `json:"notify_mode" doc:"One of: immediate, hourly, daily, off"`
		NotifyOnFlagged      *bool                  `json:"notify_on_flagged"`
		RedactPII            *bool                  `json:"redact_pii_in_webhooks" doc:"Leave answers to personal-data questions out of webhook payloads"`
		ReplyFrom            *string                `json:"reply_from"`
		ReplyFromName        *string                `json:"reply_from_name"`
		RetentionDays        *int                   `json:"retention_days"`
	} `json:"body"`
}

type FormIDRequest struct {
	ID int `param:"id"`
}

type FormSnippetResponse struct {
	Endpoint  string `json:"endpoint"`
	PublicKey string `json:"public_key"`
	HTML      string `json:"html"`
	Fetch     string `json:"fetch"`
	Widget    string `json:"widget" doc:"Website widget embed: a placeholder element and the script tag"`
	ShareURL  string `json:"share_url" doc:"The form's hosted page, a link that works without a website"`
	// ShareUnavailable is set when the hosted page is offline: "platform" when
	// the instance serves no hosted pages, "workspace" when a platform admin
	// took this workspace's pages offline.
	ShareUnavailable string `json:"share_unavailable,omitempty" enum:"platform,workspace"`
}

// SetHostedPageChecks lets the snippet say when the share link is offline.
func (h *FormHandler) SetHostedPageChecks(p *settings.Provider, workspaces *repositories.WorkspaceRepository) {
	h.hostedSettings, h.workspaces = p, workspaces
}

func (h *FormHandler) Create(c *okapi.Context, req *CreateFormRequest) error {
	if err := requireEdit(c); err != nil {
		return c.AbortForbidden("insufficient workspace permissions", err)
	}
	scope := getScope(c)
	if scope.WorkspaceID == nil {
		return c.AbortBadRequest("a workspace is required to create a form")
	}

	name, displayName, err := resolveNames(req.Body.Name, req.Body.DisplayName, req.Body.Slug)
	if err != nil {
		return c.AbortBadRequest(err.Error())
	}
	if h.repo.NameExists(*scope.WorkspaceID, name, 0) {
		return c.AbortConflict("a form named \"" + name + "\" already exists")
	}

	origins, err := normalizeOrigins(req.Body.AllowedOrigins)
	if err != nil {
		return c.AbortBadRequest(err.Error())
	}
	notify, err := normalizeEmails(req.Body.NotifyEmails)
	if err != nil {
		return c.AbortBadRequest(err.Error())
	}
	if req.Body.RedirectURL != "" && !isHTTPURL(req.Body.RedirectURL) {
		return c.AbortBadRequest("redirect_url must be an absolute http(s) URL")
	}
	replyFrom := strings.TrimSpace(req.Body.ReplyFrom)
	if replyFrom != "" {
		if err := h.checkSender(scope, replyFrom); err != nil {
			return c.AbortBadRequest(err.Error())
		}
	}

	mode, valid := parseFormMode(req.Body.Mode)
	if !valid {
		return c.AbortBadRequest("mode must be inbox or collect")
	}
	notifyMode := normalizeNotifyMode(req.Body.NotifyMode)
	if mode == models.FormModeCollect && strings.TrimSpace(req.Body.NotifyMode) == "" {
		// A survey's responses are rarely urgent: one email a day, not one each.
		notifyMode = models.NotifyModeDaily
	}

	key, err := generatePublicKey()
	if err != nil {
		return c.AbortInternalServerError("failed to generate form key")
	}

	userID := uint(c.GetInt("user_id"))
	form := &models.Form{
		WorkspaceID:         scope.WorkspaceID,
		Name:                name,
		DisplayName:         displayName,
		Description:         strings.TrimSpace(req.Body.Description),
		PublicKey:           key,
		Status:              models.FormStatusActive,
		Mode:                mode,
		AllowedOrigins:      origins,
		StrictOrigin:        req.Body.StrictOrigin,
		RedirectURL:         strings.TrimSpace(req.Body.RedirectURL),
		MaxBodyBytes:        models.DefaultMaxBodyBytes,
		MaxFields:           models.DefaultMaxFields,
		AllowAttachments:    req.Body.AllowAttachments,
		HoneypotField:       models.DefaultHoneypotField,
		RequireNonce:        req.Body.RequireNonce,
		MinFillSeconds:      3,
		ScanEnabled:         true,
		FlagThreshold:       3,
		QuarantineThreshold: 6,
		RejectThreshold:     10,
		NotifyEnabled:       true,
		NotifyEmails:        notify,
		NotifyMode:          notifyMode,
		NotifyOnFlagged:     true,
		RedactPIIInWebhooks: req.Body.RedactPII,
		ReplyFrom:           replyFrom,
		ReplyFromName:       strings.TrimSpace(req.Body.ReplyFromName),
		LastEditedByID:      &userID,
	}

	var fields *models.FieldDefs
	if req.Body.Fields != nil {
		fields = &req.Body.Fields
	}
	if err := applySchema(form, fields, optionalString(req.Body.UnknownFields), optionalString(req.Body.ErrorRedirectURL), h.edition); err != nil {
		if resp := licenseAbort(c, err); resp != nil {
			return resp
		}
		return c.AbortBadRequest(err.Error())
	}
	b := req.Body
	if err := applyResponseSettings(form, responseSettings{
		b.ConfirmationMessage, b.ClosedMessage, b.CloseAt, b.MaxResponses, b.AllowAnotherResponse, b.Appearance,
	}); err != nil {
		return c.AbortBadRequest(err.Error())
	}

	if err := h.repo.Create(form); err != nil {
		return c.AbortConflict("failed to create form")
	}

	h.log(c, "form.created", fmt.Sprintf("Form %s created", form.DisplayName), map[string]any{
		metaFormID: form.ID, metaName: form.Name,
	})
	return created(c, form)
}

func (h *FormHandler) List(c *okapi.Context, req *ListRequest) error {
	page, size, offset := normalizePageParams(req.Page, req.Size)
	forms, total, err := h.repo.FindByScope(getScope(c), size, offset)
	if err != nil {
		return c.AbortInternalServerError("failed to list forms")
	}
	return paginated(c, forms, total, page, size)
}

func (h *FormHandler) Get(c *okapi.Context, req *FormIDRequest) error {
	form, err := h.repo.FindByIDForScope(getScope(c), uint(req.ID))
	if err != nil {
		return c.AbortNotFound("form not found")
	}
	return ok(c, form)
}

func (h *FormHandler) Update(c *okapi.Context, req *UpdateFormRequest) error {
	if err := requireEdit(c); err != nil {
		return c.AbortForbidden("insufficient workspace permissions", err)
	}
	scope := getScope(c)
	form, err := h.repo.FindByIDForScope(scope, uint(req.ID))
	if err != nil {
		return c.AbortNotFound("form not found")
	}

	b := req.Body
	displayName, err := resolveRename(b.Name, b.DisplayName, b.Slug, form.Name, "form")
	if err != nil {
		return c.AbortBadRequest(err.Error())
	}
	if displayName != "" {
		form.DisplayName = displayName
	}
	if strings.TrimSpace(b.Description) != "" {
		form.Description = strings.TrimSpace(b.Description)
	}
	if b.Status != "" {
		status := models.FormStatus(b.Status)
		if status != models.FormStatusActive && status != models.FormStatusPaused && status != models.FormStatusArchived {
			return c.AbortBadRequest("invalid status")
		}
		form.Status = status
	}
	if b.Mode != nil {
		mode, valid := parseFormMode(*b.Mode)
		if !valid {
			return c.AbortBadRequest("mode must be inbox or collect")
		}
		form.Mode = mode
	}
	if b.AllowedOrigins != nil {
		origins, err := normalizeOrigins(*b.AllowedOrigins)
		if err != nil {
			return c.AbortBadRequest(err.Error())
		}
		form.AllowedOrigins = origins
	}
	if b.StrictOrigin != nil {
		form.StrictOrigin = *b.StrictOrigin
	}
	if b.RedirectURL != nil {
		target := strings.TrimSpace(*b.RedirectURL)
		if target != "" && !isHTTPURL(target) {
			return c.AbortBadRequest("redirect_url must be an absolute http(s) URL")
		}
		form.RedirectURL = target
	}
	if b.MaxBodyBytes != nil && *b.MaxBodyBytes > 0 {
		form.MaxBodyBytes = clampInt64(*b.MaxBodyBytes, 1024, 1048576)
	}
	if b.MaxFields != nil && *b.MaxFields > 0 {
		form.MaxFields = clampInt(*b.MaxFields, 1, 200)
	}
	if b.AllowAttachments != nil {
		form.AllowAttachments = *b.AllowAttachments
	}
	if b.HoneypotField != nil {
		field := strings.TrimSpace(*b.HoneypotField)
		if field == "" {
			field = models.DefaultHoneypotField
		}
		form.HoneypotField = field
	}
	if b.RequireNonce != nil {
		form.RequireNonce = *b.RequireNonce
	}
	if b.MinFillSeconds != nil {
		form.MinFillSeconds = clampInt(*b.MinFillSeconds, 0, 120)
	}
	if b.ScanEnabled != nil {
		form.ScanEnabled = *b.ScanEnabled
	}
	if b.FlagThreshold != nil {
		form.FlagThreshold = *b.FlagThreshold
	}
	if b.QuarantineThreshold != nil {
		form.QuarantineThreshold = *b.QuarantineThreshold
	}
	if b.RejectThreshold != nil {
		form.RejectThreshold = *b.RejectThreshold
	}
	if form.QuarantineThreshold < form.FlagThreshold || form.RejectThreshold < form.QuarantineThreshold {
		return c.AbortBadRequest("thresholds must satisfy flag <= quarantine <= reject")
	}
	if b.NotifyEnabled != nil {
		form.NotifyEnabled = *b.NotifyEnabled
	}
	if b.NotifyEmails != nil {
		notify, err := normalizeEmails(*b.NotifyEmails)
		if err != nil {
			return c.AbortBadRequest(err.Error())
		}
		form.NotifyEmails = notify
	}
	if b.NotifyMode != nil {
		mode, valid := parseNotifyMode(*b.NotifyMode)
		if !valid {
			return c.AbortBadRequest("notify_mode must be one of: immediate, hourly, daily, off")
		}
		form.NotifyMode = mode
	}
	if b.NotifyOnFlagged != nil {
		form.NotifyOnFlagged = *b.NotifyOnFlagged
	}
	if b.RedactPII != nil {
		form.RedactPIIInWebhooks = *b.RedactPII
	}
	if b.ReplyFrom != nil {
		replyFrom := strings.TrimSpace(*b.ReplyFrom)
		if replyFrom != "" {
			if err := h.checkSender(scope, replyFrom); err != nil {
				return c.AbortBadRequest(err.Error())
			}
		}
		form.ReplyFrom = replyFrom
	}
	if b.ReplyFromName != nil {
		form.ReplyFromName = strings.TrimSpace(*b.ReplyFromName)
	}
	if b.RetentionDays != nil {
		form.RetentionDays = clampInt(*b.RetentionDays, 0, 3650)
	}
	if err := applySchema(form, b.Fields, b.UnknownFields, b.ErrorRedirectURL, h.edition); err != nil {
		if resp := licenseAbort(c, err); resp != nil {
			return resp
		}
		return c.AbortBadRequest(err.Error())
	}
	if err := applyResponseSettings(form, responseSettings{
		b.ConfirmationMessage, b.ClosedMessage, b.CloseAt, b.MaxResponses, b.AllowAnotherResponse, b.Appearance,
	}); err != nil {
		return c.AbortBadRequest(err.Error())
	}

	userID := uint(c.GetInt("user_id"))
	now := time.Now()
	form.LastEditedByID = &userID
	form.UpdatedAt = &now

	if err := h.repo.Update(form); err != nil {
		return c.AbortInternalServerError("failed to update form")
	}
	h.invalidate(form.PublicKey)

	h.log(c, "form.updated", fmt.Sprintf("Form %s updated", form.DisplayName), map[string]any{metaFormID: form.ID})
	return ok(c, form)
}

func (h *FormHandler) Delete(c *okapi.Context, req *FormIDRequest) error {
	if err := requireEdit(c); err != nil {
		return c.AbortForbidden("insufficient workspace permissions", err)
	}
	form, err := h.repo.FindByIDForScope(getScope(c), uint(req.ID))
	if err != nil {
		return c.AbortNotFound("form not found")
	}
	if err := h.repo.Delete(form.ID); err != nil {
		return c.AbortInternalServerError("failed to delete form")
	}
	h.invalidate(form.PublicKey)
	h.log(c, "form.deleted", fmt.Sprintf("Form %s deleted", form.DisplayName), map[string]any{metaFormID: form.ID})
	return noContent(c)
}

func (h *FormHandler) RotateKey(c *okapi.Context, req *FormIDRequest) error {
	if err := requireEdit(c); err != nil {
		return c.AbortForbidden("insufficient workspace permissions", err)
	}
	form, err := h.repo.FindByIDForScope(getScope(c), uint(req.ID))
	if err != nil {
		return c.AbortNotFound("form not found")
	}
	key, err := generatePublicKey()
	if err != nil {
		return c.AbortInternalServerError("failed to generate form key")
	}
	now := time.Now()
	oldKey := form.PublicKey
	form.PublicKey = key
	form.UpdatedAt = &now
	if err := h.repo.Update(form); err != nil {
		return c.AbortInternalServerError("failed to rotate form key")
	}
	h.invalidate(oldKey, key)
	h.log(c, "form.key_rotated", fmt.Sprintf("Form %s key rotated", form.DisplayName), map[string]any{metaFormID: form.ID})
	return ok(c, form)
}

func (h *FormHandler) Snippet(c *okapi.Context, req *FormIDRequest) error {
	form, err := h.repo.FindByIDForScope(getScope(c), uint(req.ID))
	if err != nil {
		return c.AbortNotFound("form not found")
	}
	endpoint := fmt.Sprintf("%s/api/v1/f/%s", h.apiBaseURL, form.PublicKey)
	return ok(c, FormSnippetResponse{
		Endpoint:  endpoint,
		PublicKey: form.PublicKey,
		HTML:      buildHTMLSnippet(endpoint, form),
		Fetch:     buildFetchSnippet(endpoint),
		Widget:    buildWidgetSnippet(h.apiBaseURL, form),
		ShareURL:  h.apiBaseURL + "/f/" + url.PathEscape(form.PublicKey),

		ShareUnavailable: hostedOffline(h.hostedSettings, h.workspaces, form),
	})
}

func (h *FormHandler) checkSender(scope repositories.ResourceScope, address string) error {
	addr, err := mail.ParseAddress(address)
	if err != nil {
		return fmt.Errorf("reply_from must be a valid email address")
	}
	if h.domainRepo == nil {
		return nil
	}
	at := strings.LastIndex(addr.Address, "@")
	if at < 0 {
		return fmt.Errorf("reply_from must be a valid email address")
	}
	domain := strings.ToLower(addr.Address[at+1:])

	domains, _, err := h.domainRepo.FindByScope(scope, 200, 0)
	if err != nil {
		return nil
	}
	for _, d := range domains {
		if strings.EqualFold(d.Domain, domain) && d.IsOwnershipVerified() {
			return nil
		}
	}
	return fmt.Errorf("reply_from domain %s is not a verified domain in this workspace", domain)
}

func (h *FormHandler) log(c *okapi.Context, action, message string, meta map[string]any) {
	if h.audit == nil {
		return
	}
	h.audit.LogCtx(c, action, message, meta)
}

func generatePublicKey() (string, error) { return models.NewFormPublicKey() }

func normalizeOrigins(in []string) ([]string, error) {
	out := make([]string, 0, len(in))
	for _, raw := range in {
		raw = strings.TrimSpace(raw)
		if raw == "" {
			continue
		}
		if raw == "*" {
			out = append(out, raw)
			continue
		}
		u, err := url.Parse(raw)
		if err != nil || u.Scheme == "" || u.Host == "" {
			return nil, fmt.Errorf("allowed origin %q must include a scheme and host, e.g. https://example.com", raw)
		}
		out = append(out, strings.ToLower(u.Scheme+"://"+u.Host))
	}
	return out, nil
}

func normalizeEmails(in []string) ([]string, error) {
	out := make([]string, 0, len(in))
	for _, raw := range in {
		raw = strings.TrimSpace(raw)
		if raw == "" {
			continue
		}
		addr, err := mail.ParseAddress(raw)
		if err != nil {
			return nil, fmt.Errorf("%q is not a valid email address", raw)
		}
		out = append(out, addr.Address)
	}
	if len(out) > 10 {
		return nil, fmt.Errorf("at most 10 notification recipients are allowed")
	}
	return out, nil
}

func parseNotifyMode(v string) (models.NotifyMode, bool) {
	switch models.NotifyMode(strings.ToLower(strings.TrimSpace(v))) {
	case models.NotifyModeImmediate:
		return models.NotifyModeImmediate, true
	case models.NotifyModeHourly:
		return models.NotifyModeHourly, true
	case models.NotifyModeDaily:
		return models.NotifyModeDaily, true
	case models.NotifyModeOff:
		return models.NotifyModeOff, true
	default:
		return models.NotifyModeImmediate, false
	}
}

// parseFormMode reads a form mode; empty means inbox.
func parseFormMode(v string) (models.FormMode, bool) {
	switch models.FormMode(strings.ToLower(strings.TrimSpace(v))) {
	case "", models.FormModeInbox:
		return models.FormModeInbox, true
	case models.FormModeCollect:
		return models.FormModeCollect, true
	}
	return models.FormModeInbox, false
}

func normalizeNotifyMode(v string) models.NotifyMode {
	if strings.TrimSpace(v) == "" {
		return models.NotifyModeImmediate
	}
	mode, _ := parseNotifyMode(v)
	return mode
}

func isHTTPURL(v string) bool {
	u, err := url.Parse(v)
	return err == nil && (u.Scheme == "http" || u.Scheme == "https") && u.Host != ""
}

func clampInt(v, lo, hi int) int {
	if v < lo {
		return lo
	}
	if v > hi {
		return hi
	}
	return v
}

func clampInt64(v, lo, hi int64) int64 {
	if v < lo {
		return lo
	}
	if v > hi {
		return hi
	}
	return v
}

// applySchema sets a form's schema settings from a create or update request.
// Nil arguments leave the setting as it is. A changed schema gets the next
// version, so each submission records which schema validated it.
//
// Branching is a Posta Enterprise feature. Adding or changing it needs a
// license that allows changes; removing it, or editing a branching form
// without touching its branches, does not. A form keeps branching for its
// respondents whatever the license says.
func applySchema(form *models.Form, fields *models.FieldDefs, unknownFields, errorRedirect *string, edition enterprise.EE) error {
	if unknownFields != nil {
		switch policy := models.UnknownFieldsPolicy(strings.TrimSpace(*unknownFields)); policy {
		case models.UnknownFieldsKeep, models.UnknownFieldsDrop, models.UnknownFieldsReject:
			form.UnknownFields = policy
		default:
			return fmt.Errorf("unknown_fields must be one of: keep, drop, reject")
		}
	}
	if errorRedirect != nil {
		target := strings.TrimSpace(*errorRedirect)
		if target != "" && !isHTTPURL(target) {
			return fmt.Errorf("error_redirect_url must be an absolute http(s) URL")
		}
		form.ErrorRedirectURL = target
	}
	if fields != nil {
		next := append(models.FieldDefs{}, (*fields)...)
		if err := messages.CheckSchema(next, form.Fields, form.Honeypot()); err != nil {
			return err
		}
		if branching := messages.BranchTargets(next); len(branching) > 0 && !maps.Equal(branching, messages.BranchTargets(form.Fields)) {
			if edition == nil {
				edition = enterprise.Community()
			}
			if err := edition.RequireMutable(); err != nil {
				return err
			}
		}
		// The honeypot, _nonce and _redirect count towards max_fields too.
		if active := len(next.Active().Questions()); active+3 > form.FieldLimit() {
			return fmt.Errorf("the schema has %d fields but max_fields is %d; raise max_fields to at least %d", active, form.FieldLimit(), active+3)
		}
		if schemaChanged(form.Fields, next) {
			form.Fields = next
			form.SchemaVersion++
		}
	}
	for _, f := range form.Fields {
		if strings.EqualFold(f.Key, form.Honeypot()) {
			return fmt.Errorf("the honeypot field %q is also a schema field", f.Key)
		}
	}
	return nil
}

const maxFormMessageLength = 500

var accentPattern = regexp.MustCompile(`^#[0-9a-fA-F]{6}$`)

// responseSettings are the optional response and appearance settings of a
// create or update request. Nil leaves a setting as it is.
type responseSettings struct {
	confirmation, closed, closeAt *string
	maxResponses                  *int
	allowAnother                  *bool
	appearance                    *models.FormAppearance
}

func applyResponseSettings(form *models.Form, s responseSettings) error {
	if s.confirmation != nil {
		msg := strings.TrimSpace(*s.confirmation)
		if len([]rune(msg)) > maxFormMessageLength {
			return fmt.Errorf("confirmation_message must be at most %d characters", maxFormMessageLength)
		}
		form.ConfirmationMessage = msg
	}
	if s.closed != nil {
		msg := strings.TrimSpace(*s.closed)
		if len([]rune(msg)) > maxFormMessageLength {
			return fmt.Errorf("closed_message must be at most %d characters", maxFormMessageLength)
		}
		form.ClosedMessage = msg
	}
	if s.closeAt != nil {
		raw := strings.TrimSpace(*s.closeAt)
		if raw == "" {
			form.CloseAt = nil
		} else {
			at, err := time.Parse(time.RFC3339, raw)
			if err != nil {
				return fmt.Errorf("close_at must be an RFC 3339 time, such as 2026-12-31T23:59:00Z")
			}
			at = at.UTC()
			form.CloseAt = &at
		}
	}
	if s.maxResponses != nil {
		if *s.maxResponses < 0 || *s.maxResponses > 1000000 {
			return fmt.Errorf("max_responses must be between 0 and 1000000")
		}
		form.MaxResponses = *s.maxResponses
	}
	if s.allowAnother != nil {
		form.AllowAnotherResponse = *s.allowAnother
	}
	if s.appearance != nil {
		a := models.FormAppearance{
			Accent:         strings.TrimSpace(s.appearance.Accent),
			Theme:          strings.TrimSpace(s.appearance.Theme),
			HeaderImageURL: strings.TrimSpace(s.appearance.HeaderImageURL),
		}
		if a.Accent != "" && !accentPattern.MatchString(a.Accent) {
			return fmt.Errorf("appearance.accent must be a colour like #9333ea")
		}
		switch a.Theme {
		case "", "light", "dark", "auto":
		default:
			return fmt.Errorf("appearance.theme must be light, dark or auto")
		}
		if a.HeaderImageURL != "" {
			u, err := url.Parse(a.HeaderImageURL)
			if err != nil || u.Scheme != "https" || u.Host == "" || len(a.HeaderImageURL) > 2000 {
				return fmt.Errorf("appearance.header_image_url must be an https URL")
			}
		}
		form.Appearance = a
	}
	return nil
}

func schemaChanged(prev, next models.FieldDefs) bool {
	if len(prev) == 0 && len(next) == 0 {
		return false
	}
	a, _ := json.Marshal(prev)
	b, _ := json.Marshal(next)
	return string(a) != string(b)
}

func optionalString(v string) *string {
	if v == "" {
		return nil
	}
	return &v
}

func buildHTMLSnippet(endpoint string, form *models.Form) string {
	return fmt.Sprintf(`<form action="%s" method="POST">
  <label for="posta-name">Name</label>
  <input id="posta-name" type="text" name="name" required>

  <label for="posta-email">Email</label>
  <input id="posta-email" type="email" name="email" required>

  <label for="posta-phone">Phone (optional)</label>
  <input id="posta-phone" type="tel" name="phone" autocomplete="tel">

  <label for="posta-message">Message</label>
  <textarea id="posta-message" name="message" required></textarea>

  <div style="position:absolute;left:-9999px" aria-hidden="true">
    <input type="text" name="%s" tabindex="-1" autocomplete="off">
  </div>

  <button type="submit">Send</button>
</form>`, endpoint, form.Honeypot())
}

func buildWidgetSnippet(apiBaseURL string, form *models.Form) string {
	return fmt.Sprintf(`<div data-posta-form="%s"></div>
<script src="%s/widget/v1/posta-form.js" async></script>`, html.EscapeString(form.PublicKey), html.EscapeString(apiBaseURL))
}

func buildFetchSnippet(endpoint string) string {
	return fmt.Sprintf(`await fetch(%q, {
  method: 'POST',
  headers: { 'Content-Type': 'text/plain;charset=UTF-8' },
  body: JSON.stringify({
    name: form.name.value,
    email: form.email.value,
    phone: form.phone.value,
    message: form.message.value,
  }),
})`, endpoint)
}