Skip to content

armgit / posta

Public Imported from GitHub
0

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

feat(messages): add form schemas with validation and typed data

Jonas Kaninda223a679989a7
diff --git a/docs/docs/messages/embedding.md b/docs/docs/messages/embedding.md
index 87ea01e..fd204bb 100644
--- a/docs/docs/messages/embedding.md
+++ b/docs/docs/messages/embedding.md
@@ -29,7 +29,8 @@ Set these as attributes on the placeholder element:
| Attribute | Default | Notes |
|---|---|---|
-| `data-fields` | `name,email,message` | Any of `name`, `email`, `phone`, `subject`, `message`. Email and message are always included. |
+| `data-fields` | `name,email,message` | Any of `name`, `email`, `phone`, `subject`, `message`. Email and message are always included. Ignored when the form has a [schema](./fields-and-validation.md): the widget then shows the schema's questions. |
+| `data-value-<key>` | none | Value for a `hidden` schema field, for example `data-value-source="pricing-page"` |
| `data-title` | none | Heading above the form |
| `data-description` | none | One line under the heading |
| `data-button` | `Send message` | |
diff --git a/docs/docs/messages/fields-and-validation.md b/docs/docs/messages/fields-and-validation.md
new file mode 100644
index 0000000..ab58401
--- /dev/null
+++ b/docs/docs/messages/fields-and-validation.md
@@ -0,0 +1,113 @@
+---
+sidebar_position: 3.5
+title: Fields and validation
+description: Declare a form's questions so Posta validates submissions and stores typed answers
+---
+
+# Fields and Validation
+
+By default a form accepts any fields and stores them as text. Give it a **schema** and Posta will:
+
+- reject a submission that does not match it, with an error for each field;
+- store each answer with its type (numbers as numbers, checkboxes as `true`/`false`, multi-selects as lists) in the message's `data`;
+- take the sender's email, name, phone, subject and message from the fields you mark, instead of guessing from field names;
+- render exactly these questions in the [website widget](./embedding.md#website-widget).
+
+A form without a schema keeps working exactly as before.
+
+## Setting a schema
+
+Send `fields` when you create or update a form:
+
+```bash
+curl -X PUT https://posta.example.com/api/v1/workspaces/current/forms/42 \
+ -H "Authorization: Bearer $POSTA_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "fields": [
+ { "key": "email", "label": "Email", "type": "email", "required": true, "role": "sender_email" },
+ { "key": "department", "label": "Department", "type": "select", "required": true,
+ "options": [ { "value": "sales", "label": "Sales" }, { "value": "support", "label": "Support" } ] },
+ { "key": "message", "label": "Message", "type": "textarea", "role": "body" },
+ { "key": "terms", "label": "I accept the terms", "type": "checkbox", "required": true }
+ ]
+ }'
+```
+
+Each change to `fields` increases the form's `schema_version`, and every message records the version that validated it.
+
+### Field types
+
+| Type | Accepts | Stored as |
+|---|---|---|
+| `text` | Up to 200 characters by default | string |
+| `textarea` | Up to 8000 characters by default | string |
+| `email` | An email address | string |
+| `phone` | A phone number with at least 6 digits | string |
+| `number` | A number, optionally between `min` and `max` | number |
+| `url` | An `http` or `https` address | string |
+| `date` | `YYYY-MM-DD` | string |
+| `time` | `HH:MM` | string |
+| `select` | One of `options` | the option's `value` |
+| `multiselect` | Any of `options`, sent as a JSON array or repeated keys | list of values |
+| `checkbox` | `true`/`on`/`yes`/`1` or `false`/`off`/`no`/`0`; absent means false | boolean |
+| `scale` | A whole number from `min` (0 or 1, default 1) to `max` (2 to 10, default 5) | number |
+| `rating` | A whole number from 1 to `max` stars (3 to 10, default 5) | number |
+| `hidden` | Text not shown to the visitor | string |
+
+### Field settings
+
+| Setting | Applies to | Meaning |
+|---|---|---|
+| `key` | all | Lowercase letters, digits and `_`, up to 64 characters. Cannot be renamed or removed once saved. |
+| `label` | all | Shown to the visitor and used in error messages |
+| `required` | all | A required `checkbox` must be ticked |
+| `role` | see below | Which message summary value the field fills |
+| `min_len`, `max_len` | `text`, `textarea`, `hidden` | Length limits in characters |
+| `min`, `max` | `number`, `scale`, `rating` | Range |
+| `pattern` | `text`, `textarea`, `hidden` | A regular expression ([RE2 syntax](https://github.com/google/re2/wiki/Syntax)) the whole value must match |
+| `options` | `select`, `multiselect` | `{ "value": "...", "label": "..." }`, 1 to 200 |
+| `display` | `select`: `radio` or `dropdown`; `multiselect`: `checkboxes` or `list` | How the widget draws it. By default a select with up to 6 options shows as radio buttons. |
+| `min_label`, `max_label` | `scale` | Words at each end, such as "Not likely" and "Very likely" |
+| `placeholder`, `help` | all | Hint text in the widget |
+| `pii` | all | Marks personal data, for the privacy features that build on schemas |
+| `archived` | all | Hides the field and stops validating it, while keeping it on old messages |
+
+**Roles:** `sender_email` (an `email` field), `sender_name` (`text`), `sender_phone` (`phone`), `subject` (`text` or `select`) and `body` (`textarea` or `text`). Each role can be used once. A role you leave unset is still filled by guessing from field names, as for forms without a schema.
+
+### Changing a schema
+
+You can add fields, edit labels and settings, and reorder fields at any time. To retire a field, set `"archived": true`; removing it is refused, because older messages refer to it. Submissions from old embeds that still send an archived field are never rejected for it.
+
+### Fields the schema does not declare
+
+`unknown_fields` decides what happens to them:
+
+- `keep` (default): stored with the message, but not in `data`;
+- `drop`: discarded;
+- `reject`: the submission fails with an `unknown_field` error.
+
+## Validation errors
+
+A submission that does not match the schema is not stored.
+
+**JavaScript and the widget** get `422 Unprocessable Entity`:
+
+```json
+{
+ "success": false,
+ "error": {
+ "code": "validation_failed",
+ "message": "Some fields need attention.",
+ "fields": [
+ { "key": "email", "label": "Email", "code": "invalid_email", "message": "Enter a valid email address." }
+ ]
+ }
+}
+```
+
+The widget shows each message under its field. To show your own wording, map the `code`: `required`, `invalid_email`, `invalid_phone`, `invalid_number`, `invalid_url`, `invalid_date`, `invalid_time`, `invalid_option`, `invalid_value`, `too_short`, `too_long`, `out_of_range`, `pattern` or `unknown_field`.
+
+**Plain HTML forms** are sent to the form's `error_redirect_url` with `?posta_error=validation_failed&field=<key>` for the first problem. Without one, Posta shows a short page listing the errors.
+
+Spam protection stays silent: a submission caught by the honeypot or the nonce check is still answered with `202`, whatever its fields contain, so bots learn nothing about your schema.
diff --git a/internal/config/config.go b/internal/config/config.go
index 6f586be..3ac32fe 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -438,6 +438,7 @@ func (c *Config) validateWorker() error {
warnRemovedEnvVars()
return c.ValidateWorker()
}
+
// OpenAPISecuritySchemes are the security schemes the API documentation
// declares. Routes reference them by name with WithSecurity.
func OpenAPISecuritySchemes() okapi.SecuritySchemes {
diff --git a/internal/handlers/form_handler.go b/internal/handlers/form_handler.go
index 79fe856..f37d508 100644
--- a/internal/handlers/form_handler.go
+++ b/internal/handlers/form_handler.go
@@ -21,6 +21,7 @@ package handlers
import (
"crypto/rand"
+ "encoding/json"
"fmt"
"html"
"math/big"
@@ -32,6 +33,7 @@ import (
"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/storage/repositories"
"github.com/jkaninda/okapi"
)
@@ -98,36 +100,43 @@ type CreateFormRequest struct {
NotifyMode string `json:"notify_mode" enum:"immediate,hourly,daily,off"`
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>."`
} `json:"body"`
}
type UpdateFormRequest struct {
ID int `param:"id"`
Body struct {
- Name string `json:"name"`
- Slug string `json:"slug"`
- Description string `json:"description"`
- Status string `json:"status" enum:"active,paused,archived"`
- AllowedOrigins *[]string `json:"allowed_origins"`
- StrictOrigin *bool `json:"strict_origin"`
- RedirectURL *string `json:"redirect_url"`
- MaxBodyBytes *int64 `json:"max_body_bytes"`
- MaxFields *int `json:"max_fields"`
- AllowAttachments *bool `json:"allow_attachments"`
- HoneypotField *string `json:"honeypot_field"`
- RequireNonce *bool `json:"require_nonce"`
- MinFillSeconds *int `json:"min_fill_seconds"`
- ScanEnabled *bool `json:"scan_enabled"`
- FlagThreshold *float64 `json:"flag_threshold"`
- QuarantineThreshold *float64 `json:"quarantine_threshold"`
- RejectThreshold *float64 `json:"reject_threshold"`
- NotifyEnabled *bool `json:"notify_enabled"`
- NotifyEmails *[]string `json:"notify_emails"`
- NotifyMode *string `json:"notify_mode" doc:"One of: immediate, hourly, daily, off"`
- NotifyOnFlagged *bool `json:"notify_on_flagged"`
- ReplyFrom *string `json:"reply_from"`
- ReplyFromName *string `json:"reply_from_name"`
- RetentionDays *int `json:"retention_days"`
+ Name string `json:"name"`
+ Slug string `json:"slug"`
+ Description string `json:"description"`
+ Status string `json:"status" enum:"active,paused,archived"`
+ AllowedOrigins *[]string `json:"allowed_origins"`
+ StrictOrigin *bool `json:"strict_origin"`
+ RedirectURL *string `json:"redirect_url"`
+ MaxBodyBytes *int64 `json:"max_body_bytes"`
+ MaxFields *int `json:"max_fields"`
+ AllowAttachments *bool `json:"allow_attachments"`
+ HoneypotField *string `json:"honeypot_field"`
+ RequireNonce *bool `json:"require_nonce"`
+ MinFillSeconds *int `json:"min_fill_seconds"`
+ ScanEnabled *bool `json:"scan_enabled"`
+ FlagThreshold *float64 `json:"flag_threshold"`
+ QuarantineThreshold *float64 `json:"quarantine_threshold"`
+ RejectThreshold *float64 `json:"reject_threshold"`
+ NotifyEnabled *bool `json:"notify_enabled"`
+ NotifyEmails *[]string `json:"notify_emails"`
+ 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"`
+ NotifyMode *string `json:"notify_mode" doc:"One of: immediate, hourly, daily, off"`
+ NotifyOnFlagged *bool `json:"notify_on_flagged"`
+ ReplyFrom *string `json:"reply_from"`
+ ReplyFromName *string `json:"reply_from_name"`
+ RetentionDays *int `json:"retention_days"`
} `json:"body"`
}
@@ -221,6 +230,14 @@ func (h *FormHandler) Create(c *okapi.Context, req *CreateFormRequest) error {
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)); err != nil {
+ return c.AbortBadRequest(err.Error())
+ }
+
if err := h.repo.Create(form); err != nil {
return c.AbortConflict("failed to create form")
}
@@ -371,6 +388,9 @@ func (h *FormHandler) Update(c *okapi.Context, req *UpdateFormRequest) error {
if b.RetentionDays != nil {
form.RetentionDays = clampInt(*b.RetentionDays, 0, 3650)
}
+ if err := applySchema(form, b.Fields, b.UnknownFields, b.ErrorRedirectURL); err != nil {
+ return c.AbortBadRequest(err.Error())
+ }
userID := uint(c.GetInt("user_id"))
now := time.Now()
@@ -584,6 +604,63 @@ func clampInt64(v, lo, hi int64) int64 {
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.
+func applySchema(form *models.Form, fields *models.FieldDefs, unknownFields, errorRedirect *string) 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
+ }
+ // The honeypot, _nonce and _redirect count towards max_fields too.
+ if active := len(next.Active()); 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
+}
+
+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>
diff --git a/internal/handlers/form_ingest_handler.go b/internal/handlers/form_ingest_handler.go
index 42fe3e2..4dd258a 100644
--- a/internal/handlers/form_ingest_handler.go
+++ b/internal/handlers/form_ingest_handler.go
@@ -98,6 +98,56 @@ type WidgetConfig struct {
RequireNonce bool `json:"require_nonce,omitempty"`
MinFillSeconds int `json:"min_fill_seconds,omitempty" doc:"Seconds that must pass between issuing the nonce and submitting; the widget waits them out instead of letting the submission be rejected"`
Nonce *messages.Nonce `json:"nonce,omitempty" doc:"Submission nonce, present only when require_nonce is true"`
+ Fields []WidgetField `json:"fields,omitempty" doc:"The form's questions, when it has a schema. Without them the widget shows its built-in contact fields."`
+}
+
+// WidgetField is the public view of a schema field: what a browser needs to
+// render and pre-check it, without internal flags such as PII or roles.
+// Defaults are resolved, so the widget does not repeat them.
+type WidgetField struct {
+ Key string `json:"key"`
+ Label string `json:"label"`
+ Type models.FieldType `json:"type"`
+ Required bool `json:"required,omitempty"`
+ MinLen *int `json:"min_len,omitempty"`
+ MaxLen *int `json:"max_len,omitempty"`
+ Min *float64 `json:"min,omitempty"`
+ Max *float64 `json:"max,omitempty"`
+ Pattern string `json:"pattern,omitempty"`
+ Options []models.FieldOption `json:"options,omitempty"`
+ Display models.FieldDisplay `json:"display,omitempty"`
+ MinLabel string `json:"min_label,omitempty"`
+ MaxLabel string `json:"max_label,omitempty"`
+ Placeholder string `json:"placeholder,omitempty"`
+ Help string `json:"help,omitempty"`
+}
+
+func widgetFields(defs models.FieldDefs) []WidgetField {
+ active := defs.Active()
+ out := make([]WidgetField, 0, len(active))
+ for i := range active {
+ f := &active[i]
+ wf := WidgetField{
+ Key: f.Key, Label: f.Label, Type: f.Type, Required: f.Required,
+ MinLen: f.MinLen, Min: f.Min, Max: f.Max, Pattern: f.Pattern,
+ Options: f.Options, Display: f.Display, MinLabel: f.MinLabel, MaxLabel: f.MaxLabel,
+ Placeholder: f.Placeholder, Help: f.Help,
+ }
+ switch f.Type {
+ case models.FieldText, models.FieldTextarea, models.FieldHidden:
+ maxLen := messages.MaxLen(f)
+ wf.MaxLen = &maxLen
+ case models.FieldScale:
+ lo, hi := messages.ScaleRange(f)
+ low, high := float64(lo), float64(hi)
+ wf.Min, wf.Max = &low, &high
+ case models.FieldRating:
+ stars := float64(messages.RatingStars(f))
+ wf.Min, wf.Max = nil, &stars
+ }
+ out = append(out, wf)
+ }
+ return out
}
// widgetConfig decides what the widget on origin may see of form. A nil form
@@ -118,6 +168,9 @@ func widgetConfig(form *models.Form, origin string) WidgetConfig {
if form.RequireNonce {
cfg.MinFillSeconds = form.MinFillSeconds
}
+ if form.HasSchema() {
+ cfg.Fields = widgetFields(form.Fields)
+ }
return cfg
}
@@ -230,6 +283,10 @@ func (h *FormIngestHandler) Submit(c *okapi.Context) error {
NonceFailed: nonceFailed,
})
if err != nil {
+ var invalid *messages.ValidationError
+ if errors.As(err, &invalid) {
+ return h.respondInvalid(c, form, invalid)
+ }
if errors.Is(err, messages.ErrRateLimited) {
return h.respond(c, form, nil, http.StatusTooManyRequests, "rate_limited", "Too many submissions. Try again later.")
}
@@ -273,11 +330,22 @@ func (h *FormIngestHandler) parseBody(c *okapi.Context, form *models.Form) ([]mo
if err := json.Unmarshal(body, &raw); err != nil {
return nil, nil, "", err
}
+ if len(raw) > form.FieldLimit() {
+ return nil, nil, "", messages.ErrTooManyFields
+ }
fields := make([]models.MessageField, 0, len(raw))
for k, v := range raw {
+ // An array is a multi-value answer: keep its values apart so a
+ // multi-select can be validated value by value.
+ if items, isArray := v.([]any); isArray && len(items) > 0 {
+ for _, item := range items {
+ fields = append(fields, models.MessageField{Key: k, Value: stringify(item)})
+ }
+ continue
+ }
fields = append(fields, models.MessageField{Key: k, Value: stringify(v)})
}
- if len(fields) > form.FieldLimit() {
+ if messages.DistinctKeys(fields) > form.FieldLimit() {
return nil, nil, "", messages.ErrTooManyFields
}
return fields, nil, redirectFrom(raw), nil
@@ -287,7 +355,7 @@ func (h *FormIngestHandler) parseBody(c *okapi.Context, form *models.Form) ([]mo
return nil, nil, "", err
}
fields, redirect := valuesToFields(req.PostForm)
- if len(fields) > form.FieldLimit() {
+ if messages.DistinctKeys(fields) > form.FieldLimit() {
return nil, nil, "", messages.ErrTooManyFields
}
return fields, nil, redirect, nil
@@ -312,7 +380,7 @@ func (h *FormIngestHandler) parseMultipart(c *okapi.Context, form *models.Form,
}
fields, redirect := valuesToFields(req.MultipartForm.Value)
- if len(fields) > form.FieldLimit() {
+ if messages.DistinctKeys(fields) > form.FieldLimit() {
return nil, nil, "", messages.ErrTooManyFields
}
@@ -388,6 +456,57 @@ func (h *FormIngestHandler) respond(c *okapi.Context, form *models.Form, msg *mo
return c.JSON(status, ingestResponse{Success: status < 400, Data: data})
}
+// respondInvalid answers a submission that does not match the form's schema:
+// 422 with per-field errors for scripts, or for a plain HTML form a redirect
+// to the form's error page or a minimal page listing the errors.
+func (h *FormIngestHandler) respondInvalid(c *okapi.Context, form *models.Form, invalid *messages.ValidationError) error {
+ h.applyCORS(c, form)
+ if wantsJSON(c.Request()) {
+ return c.JSON(http.StatusUnprocessableEntity, validationResponse{
+ Success: false,
+ Error: validationError{
+ Code: "validation_failed",
+ Message: "Some fields need attention.",
+ Fields: invalid.Fields,
+ },
+ })
+ }
+ if form.ErrorRedirectURL != "" {
+ // The URL is set by the form's admin, and the query only carries a
+ // fixed code and a schema key, never a submitted value.
+ target, err := url.Parse(form.ErrorRedirectURL)
+ if err == nil {
+ q := target.Query()
+ q.Set("posta_error", "validation_failed")
+ q.Set("field", invalid.Fields[0].Key)
+ target.RawQuery = q.Encode()
+ c.Redirect(http.StatusSeeOther, target.String())
+ return nil
+ }
+ }
+ lines := make([]string, 0, len(invalid.Fields))
+ for _, f := range invalid.Fields {
+ name := f.Label
+ if name == "" {
+ name = f.Key
+ }
+ lines = append(lines, name+": "+f.Message)
+ }
+ return trackingNotice(c, http.StatusUnprocessableEntity, "Message not sent",
+ strings.Join(lines, " ")+" Go back to correct the form and send it again.", "error")
+}
+
+type validationResponse struct {
+ Success bool `json:"success"`
+ Error validationError `json:"error"`
+}
+
+type validationError struct {
+ Code string `json:"code"`
+ Message string `json:"message"`
+ Fields []messages.FieldError `json:"fields"`
+}
+
func wantsJSON(req *http.Request) bool {
contentType := req.Header.Get("Content-Type")
if strings.Contains(contentType, "application/json") || strings.Contains(contentType, "text/plain") {
@@ -400,6 +519,8 @@ func wantsJSON(req *http.Request) bool {
return !strings.Contains(accept, "text/html") && accept != ""
}
+// valuesToFields keeps every value of a repeated key as its own field, which
+// is how checkboxes sharing a name submit a multi-select.
func valuesToFields(values url.Values) ([]models.MessageField, string) {
fields := make([]models.MessageField, 0, len(values))
redirect := ""
@@ -407,12 +528,13 @@ func valuesToFields(values url.Values) ([]models.MessageField, string) {
if len(vals) == 0 {
continue
}
- value := strings.Join(vals, ", ")
if strings.EqualFold(key, "_redirect") || strings.EqualFold(key, "_next") {
- redirect = value
+ redirect = strings.Join(vals, ", ")
continue
}
- fields = append(fields, models.MessageField{Key: key, Value: value})
+ for _, v := range vals {
+ fields = append(fields, models.MessageField{Key: key, Value: v})
+ }
}
return fields, redirect
}
diff --git a/internal/handlers/form_widget_test.go b/internal/handlers/form_widget_test.go
index 33c6c28..efee15a 100644
--- a/internal/handlers/form_widget_test.go
+++ b/internal/handlers/form_widget_test.go
@@ -22,6 +22,7 @@ package handlers
import (
"net/http"
"net/http/httptest"
+ "reflect"
"strings"
"testing"
@@ -55,7 +56,7 @@ func TestWidgetConfig(t *testing.T) {
{"fill time only with a nonce", active(func(f *models.Form) { f.MinFillSeconds = 3 }), "https://site.test", WidgetConfig{Enabled: true, HoneypotField: "_gotcha"}},
}
for _, tc := range cases {
- if got := widgetConfig(tc.form, tc.origin); got != tc.want {
+ if got := widgetConfig(tc.form, tc.origin); !reflect.DeepEqual(got, tc.want) {
t.Errorf("%s: widgetConfig = %+v, want %+v", tc.name, got, tc.want)
}
}
diff --git a/internal/models/form.go b/internal/models/form.go
index 289c97c..536cad7 100644
--- a/internal/models/form.go
+++ b/internal/models/form.go
@@ -66,6 +66,12 @@ type Form struct {
MaxFields int `json:"max_fields" gorm:"default:40;not null"`
AllowAttachments bool `json:"allow_attachments" gorm:"default:false;not null"`
+ // Fields is the form's schema. Nil accepts any fields (schemaless).
+ Fields FieldDefs `json:"fields" gorm:"type:jsonb"`
+ SchemaVersion int `json:"schema_version" gorm:"default:0;not null"`
+ UnknownFields UnknownFieldsPolicy `json:"unknown_fields" gorm:"type:varchar(8);default:'keep';not null"`
+ ErrorRedirectURL string `json:"error_redirect_url"`
+
HoneypotField string `json:"honeypot_field" gorm:"default:'_gotcha';not null"`
RequireNonce bool `json:"require_nonce" gorm:"default:false;not null"`
MinFillSeconds int `json:"min_fill_seconds" gorm:"default:3;not null"`
@@ -98,6 +104,18 @@ type Form struct {
func (f *Form) IsActive() bool { return f.Status == FormStatusActive }
+// HasSchema reports whether submissions are validated against Fields.
+func (f *Form) HasSchema() bool { return f != nil && len(f.Fields.Active()) > 0 }
+
+// UnknownFieldsPolicy returns the policy for undeclared keys, keep by default.
+func (f *Form) UnknownFieldsPolicy() UnknownFieldsPolicy {
+ switch f.UnknownFields {
+ case UnknownFieldsDrop, UnknownFieldsReject:
+ return f.UnknownFields
+ }
+ return UnknownFieldsKeep
+}
+
// ScanSource identifies what a submission arrived through, so the scanner can
// apply that source's filters and count repeat submissions per source.
type ScanSource struct {
diff --git a/internal/models/form_field.go b/internal/models/form_field.go
new file mode 100644
index 0000000..0dd63b9
--- /dev/null
+++ b/internal/models/form_field.go
@@ -0,0 +1,176 @@
+// 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 models
+
+import (
+ "database/sql/driver"
+ "encoding/json"
+ "fmt"
+)
+
+// FieldType is the kind of answer a form field accepts.
+type FieldType string
+
+const (
+ FieldText FieldType = "text"
+ FieldTextarea FieldType = "textarea"
+ FieldEmail FieldType = "email"
+ FieldPhone FieldType = "phone"
+ FieldNumber FieldType = "number"
+ FieldURL FieldType = "url"
+ FieldDate FieldType = "date"
+ FieldTime FieldType = "time"
+ FieldSelect FieldType = "select"
+ FieldMultiSelect FieldType = "multiselect"
+ FieldCheckbox FieldType = "checkbox"
+ FieldScale FieldType = "scale"
+ FieldRating FieldType = "rating"
+ FieldHidden FieldType = "hidden"
+)
+
+// FieldRole marks the field that carries one of a message's summary values,
+// replacing the key-name guessing of messages.Extract.
+type FieldRole string
+
+const (
+ RoleNone FieldRole = ""
+ RoleSenderEmail FieldRole = "sender_email"
+ RoleSenderName FieldRole = "sender_name"
+ RoleSenderPhone FieldRole = "sender_phone"
+ RoleSubject FieldRole = "subject"
+ RoleBody FieldRole = "body"
+)
+
+// FieldDisplay chooses how a choice field is drawn. It never changes what is
+// accepted.
+type FieldDisplay string
+
+const (
+ DisplayDefault FieldDisplay = ""
+ DisplayRadio FieldDisplay = "radio" // select
+ DisplayDropdown FieldDisplay = "dropdown" // select
+ DisplayCheckboxes FieldDisplay = "checkboxes" // multiselect
+ DisplayList FieldDisplay = "list" // multiselect
+)
+
+// UnknownFieldsPolicy decides what happens to submitted keys the schema does
+// not declare.
+type UnknownFieldsPolicy string
+
+const (
+ UnknownFieldsKeep UnknownFieldsPolicy = "keep"
+ UnknownFieldsDrop UnknownFieldsPolicy = "drop"
+ UnknownFieldsReject UnknownFieldsPolicy = "reject"
+)
+
+type FieldOption struct {
+ Value string `json:"value"`
+ Label string `json:"label,omitempty"`
+}
+
+// FieldDef declares one question of a form. A key, once saved, can be
+// archived but not renamed or removed, so old submissions keep their meaning.
+type FieldDef struct {
+ Key string `json:"key"`
+ Label string `json:"label"`
+ Type FieldType `json:"type"`
+ Required bool `json:"required,omitempty"`
+ Role FieldRole `json:"role,omitempty"`
+ PII bool `json:"pii,omitempty"`
+
+ MinLen *int `json:"min_len,omitempty"`
+ MaxLen *int `json:"max_len,omitempty"`
+ Min *float64 `json:"min,omitempty"` // number; scale low end
+ Max *float64 `json:"max,omitempty"` // number; scale high end; rating stars
+ Pattern string `json:"pattern,omitempty"`
+
+ Options []FieldOption `json:"options,omitempty"`
+ Display FieldDisplay `json:"display,omitempty"`
+ MinLabel string `json:"min_label,omitempty"` // scale
+ MaxLabel string `json:"max_label,omitempty"` // scale
+
+ Placeholder string `json:"placeholder,omitempty"`
+ Help string `json:"help,omitempty"`
+ Archived bool `json:"archived,omitempty"`
+}
+
+// FieldDefs is a form's schema, stored as jsonb. Nil means the form has no
+// schema and accepts any fields, as before schemas existed.
+type FieldDefs []FieldDef
+
+func (d FieldDefs) Value() (driver.Value, error) {
+ if d == nil {
+ return nil, nil
+ }
+ return json.Marshal(d)
+}
+
+func (d *FieldDefs) Scan(value any) error {
+ raw, err := jsonBytes(value)
+ if err != nil || raw == nil {
+ *d = nil
+ return err
+ }
+ return json.Unmarshal(raw, d)
+}
+
+// Active returns the fields that are not archived, in order.
+func (d FieldDefs) Active() FieldDefs {
+ out := make(FieldDefs, 0, len(d))
+ for _, f := range d {
+ if !f.Archived {
+ out = append(out, f)
+ }
+ }
+ return out
+}
+
+// SubmissionData is a submission's typed answers keyed by field key, stored
+// as jsonb. Numbers, booleans and multi-select arrays keep their JSON type.
+type SubmissionData map[string]any
+
+func (d SubmissionData) Value() (driver.Value, error) {
+ if d == nil {
+ return nil, nil
+ }
+ return json.Marshal(d)
+}
+
+func (d *SubmissionData) Scan(value any) error {
+ raw, err := jsonBytes(value)
+ if err != nil || raw == nil {
+ *d = nil
+ return err
+ }
+ return json.Unmarshal(raw, d)
+}
+
+func jsonBytes(value any) ([]byte, error) {
+ switch v := value.(type) {
+ case nil:
+ return nil, nil
+ case []byte:
+ return v, nil
+ case string:
+ return []byte(v), nil
+ default:
+ return nil, fmt.Errorf("unsupported JSON column value %T", value)
+ }
+}
diff --git a/internal/models/message.go b/internal/models/message.go
index 150dda0..39556d3 100644
--- a/internal/models/message.go
+++ b/internal/models/message.go
@@ -69,8 +69,12 @@ type Message struct {
Subject string `json:"subject"`
Body string `json:"body" gorm:"type:text"`
- FieldsJSON string `json:"-" gorm:"type:text"`
- AttachmentsJSON string `json:"-" gorm:"type:text"`
+ FieldsJSON string `json:"-" gorm:"type:text"`
+ // Data holds the typed answers of a form with a schema; FieldsJSON stays
+ // the display copy. SchemaVersion is the form schema it was validated by.
+ Data SubmissionData `json:"data,omitempty" gorm:"type:jsonb"`
+ SchemaVersion int `json:"schema_version" gorm:"default:0;not null"`
+ AttachmentsJSON string `json:"-" gorm:"type:text"`
ClientIP string `json:"client_ip,omitempty" gorm:"size:45"`
UserAgent string `json:"user_agent,omitempty"`
diff --git a/internal/services/messages/schema.go b/internal/services/messages/schema.go
new file mode 100644
index 0000000..bbf0dbb
--- /dev/null
+++ b/internal/services/messages/schema.go
@@ -0,0 +1,224 @@
+// Copyright (c) 2026 Jonas Kaninda.
+//
+// This file is part of Posta.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+//
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package messages
+
+import (
+ "fmt"
+ "regexp"
+ "strings"
+
+ "github.com/goposta/posta/internal/models"
+)
+
+const (
+ MaxSchemaFields = 100
+ maxFieldOptions = 200
+ maxPatternLength = 256
+ defaultTextMaxLen = 200
+ defaultLongMaxLen = 8000
+ defaultScaleMin = 1
+ defaultScaleMax = 5
+ defaultRatingStars = 5
+)
+
+var fieldKeyPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9_]{0,63}$`)
+
+var fieldTypes = map[models.FieldType]bool{
+ models.FieldText: true, models.FieldTextarea: true, models.FieldEmail: true,
+ models.FieldPhone: true, models.FieldNumber: true, models.FieldURL: true,
+ models.FieldDate: true, models.FieldTime: true, models.FieldSelect: true,
+ models.FieldMultiSelect: true, models.FieldCheckbox: true, models.FieldScale: true,
+ models.FieldRating: true, models.FieldHidden: true,
+}
+
+// roleTypes lists the field types each role may sit on.
+var roleTypes = map[models.FieldRole][]models.FieldType{
+ models.RoleSenderEmail: {models.FieldEmail},
+ models.RoleSenderName: {models.FieldText},
+ models.RoleSenderPhone: {models.FieldPhone},
+ models.RoleSubject: {models.FieldText, models.FieldSelect},
+ models.RoleBody: {models.FieldTextarea, models.FieldText},
+}
+
+// CheckSchema reports the first problem with a schema about to be saved.
+// previous is the schema currently stored; its keys must all survive, since
+// stored submissions refer to them. A key can be archived instead.
+func CheckSchema(defs models.FieldDefs, previous models.FieldDefs, honeypot string) error {
+ if len(defs) > MaxSchemaFields {
+ return fmt.Errorf("a form can have at most %d fields", MaxSchemaFields)
+ }
+ seen := make(map[string]bool, len(defs))
+ roles := make(map[models.FieldRole]string)
+ for i := range defs {
+ f := &defs[i]
+ f.Key = strings.TrimSpace(f.Key)
+ f.Label = strings.TrimSpace(f.Label)
+ if !fieldKeyPattern.MatchString(f.Key) {
+ return fmt.Errorf("field key %q must be 1-64 lowercase letters, digits or underscores, starting with a letter or digit", f.Key)
+ }
+ if seen[f.Key] {
+ return fmt.Errorf("field key %q is used twice", f.Key)
+ }
+ seen[f.Key] = true
+ if strings.EqualFold(f.Key, honeypot) {
+ return fmt.Errorf("field key %q is the form's honeypot field", f.Key)
+ }
+ if !fieldTypes[f.Type] {
+ return fmt.Errorf("field %q has unknown type %q", f.Key, f.Type)
+ }
+ if f.Label == "" && f.Type != models.FieldHidden {
+ return fmt.Errorf("field %q needs a label", f.Key)
+ }
+ if err := checkRole(f, roles); err != nil {
+ return err
+ }
+ if err := checkFieldSettings(f); err != nil {
+ return err
+ }
+ }
+ for _, old := range previous {
+ if !seen[old.Key] {
+ return fmt.Errorf("field %q cannot be removed because submissions may use it; archive it instead", old.Key)
+ }
+ }
+ return nil
+}
+
+func checkRole(f *models.FieldDef, roles map[models.FieldRole]string) error {
+ if f.Role == models.RoleNone {
+ return nil
+ }
+ allowed, known := roleTypes[f.Role]
+ if !known {
+ return fmt.Errorf("field %q has unknown role %q", f.Key, f.Role)
+ }
+ ok := false
+ for _, t := range allowed {
+ ok = ok || t == f.Type
+ }
+ if !ok {
+ return fmt.Errorf("field %q: role %s does not fit a %s field", f.Key, f.Role, f.Type)
+ }
+ if f.Archived {
+ return nil
+ }
+ if other, dup := roles[f.Role]; dup {
+ return fmt.Errorf("fields %q and %q both have role %s", other, f.Key, f.Role)
+ }
+ roles[f.Role] = f.Key
+ return nil
+}
+
+func checkFieldSettings(f *models.FieldDef) error {
+ if f.MinLen != nil && *f.MinLen < 0 {
+ return fmt.Errorf("field %q: min_len cannot be negative", f.Key)
+ }
+ if f.MaxLen != nil && (*f.MaxLen < 1 || *f.MaxLen > defaultLongMaxLen) {
+ return fmt.Errorf("field %q: max_len must be between 1 and %d", f.Key, defaultLongMaxLen)
+ }
+ if f.MinLen != nil && f.MaxLen != nil && *f.MinLen > *f.MaxLen {
+ return fmt.Errorf("field %q: min_len is above max_len", f.Key)
+ }
+ if f.Pattern != "" {
+ if len(f.Pattern) > maxPatternLength {
+ return fmt.Errorf("field %q: pattern is longer than %d characters", f.Key, maxPatternLength)
+ }
+ if _, err := regexp.Compile(f.Pattern); err != nil {
+ return fmt.Errorf("field %q: pattern does not compile: %v", f.Key, err)
+ }
+ }
+
+ switch f.Type {
+ case models.FieldSelect, models.FieldMultiSelect:
+ if len(f.Options) == 0 || len(f.Options) > maxFieldOptions {
+ return fmt.Errorf("field %q needs between 1 and %d options", f.Key, maxFieldOptions)
+ }
+ values := make(map[string]bool, len(f.Options))
+ for i := range f.Options {
+ o := &f.Options[i]
+ o.Value = strings.TrimSpace(o.Value)
+ o.Label = strings.TrimSpace(o.Label)
+ if o.Value == "" {
+ return fmt.Errorf("field %q has an option without a value", f.Key)
+ }
+ if values[o.Value] {
+ return fmt.Errorf("field %q has option %q twice", f.Key, o.Value)
+ }
+ values[o.Value] = true
+ }
+ valid := f.Display == models.DisplayDefault
+ if f.Type == models.FieldSelect {
+ valid = valid || f.Display == models.DisplayRadio || f.Display == models.DisplayDropdown
+ } else {
+ valid = valid || f.Display == models.DisplayCheckboxes || f.Display == models.DisplayList
+ }
+ if !valid {
+ return fmt.Errorf("field %q: display %q does not fit a %s field", f.Key, f.Display, f.Type)
+ }
+ case models.FieldNumber:
+ if f.Min != nil && f.Max != nil && *f.Min > *f.Max {
+ return fmt.Errorf("field %q: min is above max", f.Key)
+ }
+ case models.FieldScale:
+ lo, hi := ScaleRange(f)
+ if (lo != 0 && lo != 1) || hi < 2 || hi > 10 {
+ return fmt.Errorf("field %q: a scale runs from 0 or 1 to between 2 and 10", f.Key)
+ }
+ case models.FieldRating:
+ if stars := RatingStars(f); stars < 3 || stars > 10 {
+ return fmt.Errorf("field %q: a rating has between 3 and 10 stars", f.Key)
+ }
+ }
+ if f.Display != models.DisplayDefault && f.Type != models.FieldSelect && f.Type != models.FieldMultiSelect {
+ return fmt.Errorf("field %q: display only applies to select and multiselect fields", f.Key)
+ }
+ return nil
+}
+
+// ScaleRange returns a scale field's low and high ends.
+func ScaleRange(f *models.FieldDef) (int, int) {
+ lo, hi := defaultScaleMin, defaultScaleMax
+ if f.Min != nil {
+ lo = int(*f.Min)
+ }
+ if f.Max != nil {
+ hi = int(*f.Max)
+ }
+ return lo, hi
+}
+
+// RatingStars returns a rating field's number of stars.
+func RatingStars(f *models.FieldDef) int {
+ if f.Max != nil {
+ return int(*f.Max)
+ }
+ return defaultRatingStars
+}
+
+// MaxLen returns the longest accepted value of a text-like field.
+func MaxLen(f *models.FieldDef) int {
+ if f.MaxLen != nil {
+ return *f.MaxLen
+ }
+ if f.Type == models.FieldTextarea {
+ return defaultLongMaxLen
+ }
+ return defaultTextMaxLen
+}
diff --git a/internal/services/messages/service.go b/internal/services/messages/service.go
index 757071b..b3e179b 100644
--- a/internal/services/messages/service.go
+++ b/internal/services/messages/service.go
@@ -201,7 +201,7 @@ func (s *Service) Submit(ctx context.Context, req SubmitRequest) (*SubmitResult,
if !form.IsActive() {
return nil, ErrFormInactive
}
- if len(req.Fields) > form.FieldLimit() {
+ if DistinctKeys(req.Fields) > form.FieldLimit() {
return nil, ErrTooManyFields
}
if form.WorkspaceID == nil {
@@ -218,12 +218,40 @@ func (s *Service) Submit(ctx context.Context, req SubmitRequest) (*SubmitResult,
fields = append(fields, models.MessageField{Key: key, Value: Sanitize(f.Value)})
}
- extracted := Extract(fields)
+ // Validate only what may be a person: a honeypot or nonce failure is
+ // rejected silently, so it must not learn about the schema from a 422.
+ var (
+ extracted Extracted
+ data models.SubmissionData
+ schemaVersion int
+ invalid []FieldError
+ )
+ if form.HasSchema() && !req.HoneypotHit && !req.NonceFailed {
+ validated, errs := Validate(form, fields)
+ if errs != nil {
+ invalid = errs
+ extracted = Extract(JoinRepeated(fields))
+ } else {
+ fields = validated.Fields
+ data = validated.Data
+ schemaVersion = form.SchemaVersion
+ extracted = ExtractWithRoles(validated.Roles, form.Fields, fields)
+ }
+ } else {
+ fields = JoinRepeated(fields)
+ extracted = Extract(fields)
+ }
senderEmail := NormalizeEmail(extracted.Email)
+ // Quotas come before the 422, so a rate-limited client cannot probe the
+ // schema; validation comes before dedup and scanning, so invalid input
+ // never counts towards them.
if err := s.checkQuotas(ctx, form.ID, *form.WorkspaceID, req.ClientIP, senderEmail, req.HoneypotHit); err != nil {
return nil, err
}
+ if invalid != nil {
+ return nil, &ValidationError{Fields: invalid}
+ }
hash := dedupHash(form.ID, senderEmail, extracted.Body)
if existing, err := s.messageRepo.FindRecentDuplicate(form.ID, hash, time.Now().Add(-dedupWindow)); err == nil && existing != nil {
@@ -271,6 +299,8 @@ func (s *Service) Submit(ctx context.Context, req SubmitRequest) (*SubmitResult,
Subject: subject,
Body: extracted.Body,
FieldsJSON: string(fieldsJSON),
+ Data: data,
+ SchemaVersion: schemaVersion,
AttachmentsJSON: attachmentsJSON,
ClientIP: req.ClientIP,
UserAgent: truncate(req.UserAgent, 400),
diff --git a/internal/services/messages/validate.go b/internal/services/messages/validate.go
new file mode 100644
index 0000000..0e8e46e
--- /dev/null
+++ b/internal/services/messages/validate.go
@@ -0,0 +1,423 @@
+// Copyright (c) 2026 Jonas Kaninda.
+//
+// This file is part of Posta.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+//
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package messages
+
+import (
+ "fmt"
+ "math"
+ "net/mail"
+ "net/url"
+ "regexp"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+ "unicode/utf8"
+
+ "github.com/goposta/posta/internal/models"
+)
+
+// FieldError is one reason a submission does not match its form's schema.
+// Message is an English default; clients can localise by Code.
+type FieldError struct {
+ Key string `json:"key"`
+ Label string `json:"label,omitempty"`
+ Code string `json:"code"`
+ Message string `json:"message"`
+}
+
+// ValidationError is returned by Submit when a submission does not match the
+// form's schema. Nothing is stored.
+type ValidationError struct {
+ Fields []FieldError
+}
+
+func (e *ValidationError) Error() string {
+ return fmt.Sprintf("submission has %d invalid field(s)", len(e.Fields))
+}
+
+// Validated is a submission that matches its form's schema.
+type Validated struct {
+ // Data holds the typed answers, keyed by field key.
+ Data models.SubmissionData
+ // Fields is the display copy: declared fields in schema order, then kept
+ // unknown fields.
+ Fields []models.MessageField
+ // Roles maps each role to its field's display value.
+ Roles map[models.FieldRole]string
+}
+
+const (
+ maxEmailLength = 254
+ maxURLLength = 2000
+ minPhoneDigits = 6
+)
+
+var errorMessages = map[string]string{
+ "required": "This field is required.",
+ "invalid_email": "Enter a valid email address.",
+ "invalid_phone": "Enter a valid phone number.",
+ "invalid_number": "Enter a number.",
+ "invalid_url": "Enter a full web address starting with http:// or https://.",
+ "invalid_date": "Enter a date as YYYY-MM-DD.",
+ "invalid_time": "Enter a time as HH:MM.",
+ "invalid_option": "Choose one of the listed options.",
+ "invalid_value": "This value is not accepted.",
+ "pattern": "This value is not in the expected format.",
+ "unknown_field": "This form does not accept this field.",
+}
+
+func fieldError(f *models.FieldDef, key, code, message string) FieldError {
+ if message == "" {
+ message = errorMessages[code]
+ }
+ label := ""
+ if f != nil {
+ label = f.Label
+ }
+ return FieldError{Key: key, Label: label, Code: code, Message: message}
+}
+
+// Validate checks fields against form's schema. A key may repeat, which is
+// how a multi-select arrives; other fields use their first value.
+func Validate(form *models.Form, fields []models.MessageField) (*Validated, []FieldError) {
+ values := make(map[string][]string, len(fields))
+ var order []string
+ for _, f := range fields {
+ key := strings.ToLower(strings.TrimSpace(f.Key))
+ if _, seen := values[key]; !seen {
+ order = append(order, key)
+ }
+ if v := strings.TrimSpace(f.Value); v != "" {
+ values[key] = append(values[key], v)
+ } else if _, seen := values[key]; !seen {
+ values[key] = nil
+ }
+ }
+
+ out := &Validated{
+ Data: models.SubmissionData{},
+ Roles: map[models.FieldRole]string{},
+ }
+ var errs []FieldError
+ declared := make(map[string]bool, len(form.Fields))
+ for i := range form.Fields {
+ def := &form.Fields[i]
+ declared[def.Key] = true
+ if def.Archived {
+ continue
+ }
+ value, display, err := coerce(def, values[def.Key])
+ if err != nil {
+ errs = append(errs, *err)
+ continue
+ }
+ if value == nil {
+ continue
+ }
+ out.Data[def.Key] = value
+ if display != "" {
+ out.Fields = append(out.Fields, models.MessageField{Key: def.Key, Value: display})
+ if def.Role != models.RoleNone {
+ out.Roles[def.Role] = display
+ }
+ }
+ }
+
+ policy := form.UnknownFieldsPolicy()
+ for _, key := range order {
+ if declared[key] && !isArchived(form.Fields, key) {
+ continue
+ }
+ vals := values[key]
+ // Archived keys come from old embeds; never reject them.
+ if policy == models.UnknownFieldsReject && !declared[key] {
+ errs = append(errs, fieldError(nil, key, "unknown_field", ""))
+ continue
+ }
+ if policy == models.UnknownFieldsDrop || len(vals) == 0 {
+ continue
+ }
+ out.Fields = append(out.Fields, models.MessageField{Key: key, Value: strings.Join(vals, ", ")})
+ }
+ if len(errs) > 0 {
+ return nil, errs
+ }
+ return out, nil
+}
+
+func isArchived(defs models.FieldDefs, key string) bool {
+ for _, d := range defs {
+ if d.Key == key {
+ return d.Archived
+ }
+ }
+ return false
+}
+
+// coerce turns a field's submitted values into its typed value and display
+// string. A nil value with no error means the optional field was left empty.
+func coerce(f *models.FieldDef, vals []string) (any, string, *FieldError) {
+ fail := func(code string) (any, string, *FieldError) {
+ e := fieldError(f, f.Key, code, "")
+ return nil, "", &e
+ }
+ failMsg := func(code, msg string) (any, string, *FieldError) {
+ e := fieldError(f, f.Key, code, msg)
+ return nil, "", &e
+ }
+
+ if f.Type == models.FieldCheckbox {
+ checked := false
+ if len(vals) > 0 {
+ switch strings.ToLower(vals[0]) {
+ case "on", "true", "1", "yes":
+ checked = true
+ case "off", "false", "0", "no":
+ default:
+ return fail("invalid_value")
+ }
+ }
+ if f.Required && !checked {
+ return fail("required")
+ }
+ if checked {
+ return true, "Yes", nil
+ }
+ return false, "No", nil
+ }
+
+ if len(vals) == 0 {
+ if f.Required {
+ return fail("required")
+ }
+ return nil, "", nil
+ }
+ v := vals[0]
+
+ switch f.Type {
+ case models.FieldText, models.FieldTextarea, models.FieldHidden:
+ n := utf8.RuneCountInString(v)
+ if f.MinLen != nil && n < *f.MinLen {
+ return failMsg("too_short", fmt.Sprintf("Enter at least %d characters.", *f.MinLen))
+ }
+ if max := MaxLen(f); n > max {
+ return failMsg("too_long", fmt.Sprintf("Enter at most %d characters.", max))
+ }
+ if f.Pattern != "" && !matchesPattern(f.Pattern, v) {
+ return fail("pattern")
+ }
+ return v, v, nil
+
+ case models.FieldEmail:
+ addr, err := mail.ParseAddress(v)
+ if err != nil || len(addr.Address) > maxEmailLength || !strings.Contains(addr.Address[strings.LastIndex(addr.Address, "@")+1:], ".") {
+ return fail("invalid_email")
+ }
+ return addr.Address, addr.Address, nil
+
+ case models.FieldPhone:
+ phone := NormalizePhone(v)
+ digits := 0
+ for _, r := range phone {
+ if r >= '0' && r <= '9' {
+ digits++
+ }
+ }
+ if digits < minPhoneDigits {
+ return fail("invalid_phone")
+ }
+ return phone, phone, nil
+
+ case models.FieldNumber:
+ n, err := strconv.ParseFloat(v, 64)
+ if err != nil || math.IsNaN(n) || math.IsInf(n, 0) {
+ return fail("invalid_number")
+ }
+ if (f.Min != nil && n < *f.Min) || (f.Max != nil && n > *f.Max) {
+ return failMsg("out_of_range", rangeMessage(f.Min, f.Max))
+ }
+ return n, v, nil
+
+ case models.FieldURL:
+ u, err := url.Parse(v)
+ if err != nil || len(v) > maxURLLength || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
+ return fail("invalid_url")
+ }
+ return v, v, nil
+
+ case models.FieldDate:
+ d, err := time.Parse("2006-01-02", v)
+ if err != nil || d.Year() < 1900 || d.Year() > 2200 {
+ return fail("invalid_date")
+ }
+ return v, v, nil
+
+ case models.FieldTime:
+ for _, layout := range []string{"15:04", "15:04:05"} {
+ if t, err := time.Parse(layout, v); err == nil {
+ s := t.Format("15:04")
+ return s, s, nil
+ }
+ }
+ return fail("invalid_time")
+
+ case models.FieldSelect:
+ for _, o := range f.Options {
+ if o.Value == v {
+ return o.Value, optionLabel(o), nil
+ }
+ }
+ return fail("invalid_option")
+
+ case models.FieldMultiSelect:
+ chosen := make([]string, 0, len(vals))
+ labels := make([]string, 0, len(vals))
+ seen := make(map[string]bool, len(vals))
+ for _, v := range vals {
+ if seen[v] {
+ continue
+ }
+ found := false
+ for _, o := range f.Options {
+ if o.Value == v {
+ chosen = append(chosen, o.Value)
+ labels = append(labels, optionLabel(o))
+ found = true
+ break
+ }
+ }
+ if !found {
+ return fail("invalid_option")
+ }
+ seen[v] = true
+ }
+ return chosen, strings.Join(labels, ", "), nil
+
+ case models.FieldScale, models.FieldRating:
+ lo, hi := ScaleRange(f)
+ if f.Type == models.FieldRating {
+ lo, hi = 1, RatingStars(f)
+ }
+ n, err := strconv.Atoi(v)
+ if err != nil {
+ return fail("invalid_number")
+ }
+ if n < lo || n > hi {
+ low, high := float64(lo), float64(hi)
+ return failMsg("out_of_range", rangeMessage(&low, &high))
+ }
+ return n, strconv.Itoa(n), nil
+ }
+ return fail("invalid_value")
+}
+
+func optionLabel(o models.FieldOption) string {
+ if o.Label != "" {
+ return o.Label
+ }
+ return o.Value
+}
+
+func rangeMessage(lo, hi *float64) string {
+ format := func(f float64) string { return strconv.FormatFloat(f, 'f', -1, 64) }
+ switch {
+ case lo != nil && hi != nil:
+ return fmt.Sprintf("Enter a value from %s to %s.", format(*lo), format(*hi))
+ case lo != nil:
+ return fmt.Sprintf("Enter %s or more.", format(*lo))
+ default:
+ return fmt.Sprintf("Enter %s or less.", format(*hi))
+ }
+}
+
+var patternCache sync.Map // pattern → *regexp.Regexp
+
+// matchesPattern reports whether the whole value matches pattern. Patterns
+// were compiled when the schema was saved, so a failure here is a mismatch.
+func matchesPattern(pattern, value string) bool {
+ cached, ok := patternCache.Load(pattern)
+ if !ok {
+ re, err := regexp.Compile(`^(?:` + pattern + `)$`)
+ if err != nil {
+ return false
+ }
+ cached, _ = patternCache.LoadOrStore(pattern, re)
+ }
+ return cached.(*regexp.Regexp).MatchString(value)
+}
+
+// ExtractWithRoles fills the summary values from role fields, falling back to
+// key-name guessing for roles the schema leaves unset.
+func ExtractWithRoles(roles map[models.FieldRole]string, schema models.FieldDefs, fields []models.MessageField) Extracted {
+ guessed := Extract(fields)
+ has := func(role models.FieldRole) bool {
+ for _, f := range schema.Active() {
+ if f.Role == role {
+ return true
+ }
+ }
+ return false
+ }
+ pickRole := func(role models.FieldRole, fallback string) string {
+ if has(role) {
+ return roles[role]
+ }
+ return fallback
+ }
+ return Extracted{
+ Email: SanitizeHeaderValue(pickRole(models.RoleSenderEmail, guessed.Email)),
+ Name: SanitizeHeaderValue(pickRole(models.RoleSenderName, guessed.Name)),
+ Phone: NormalizePhone(pickRole(models.RoleSenderPhone, guessed.Phone)),
+ Subject: SanitizeHeaderValue(pickRole(models.RoleSubject, guessed.Subject)),
+ Body: pickRole(models.RoleBody, guessed.Body),
+ }
+}
+
+// JoinRepeated merges repeated keys into one field with comma-separated
+// values, in order of first appearance. It is the display copy for forms
+// without a schema, matching how multi-value inputs were always stored.
+func JoinRepeated(fields []models.MessageField) []models.MessageField {
+ index := make(map[string]int, len(fields))
+ out := make([]models.MessageField, 0, len(fields))
+ for _, f := range fields {
+ if i, seen := index[f.Key]; seen {
+ if f.Value != "" {
+ if out[i].Value != "" {
+ out[i].Value += ", "
+ }
+ out[i].Value += f.Value
+ }
+ continue
+ }
+ index[f.Key] = len(out)
+ out = append(out, f)
+ }
+ return out
+}
+
+// DistinctKeys counts the different keys among fields.
+func DistinctKeys(fields []models.MessageField) int {
+ seen := make(map[string]struct{}, len(fields))
+ for _, f := range fields {
+ seen[f.Key] = struct{}{}
+ }
+ return len(seen)
+}
diff --git a/internal/services/messages/validate_test.go b/internal/services/messages/validate_test.go
new file mode 100644
index 0000000..aa4d225
--- /dev/null
+++ b/internal/services/messages/validate_test.go
@@ -0,0 +1,228 @@
+// Copyright (c) 2026 Jonas Kaninda.
+//
+// This file is part of Posta.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+//
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package messages
+
+import (
+ "reflect"
+ "strings"
+ "testing"
+
+ "github.com/goposta/posta/internal/models"
+)
+
+func ptrF(v float64) *float64 { return &v }
+func ptrI(v int) *int { return &v }
+
+func fieldsOf(kv ...string) []models.MessageField {
+ out := make([]models.MessageField, 0, len(kv)/2)
+ for i := 0; i+1 < len(kv); i += 2 {
+ out = append(out, models.MessageField{Key: kv[i], Value: kv[i+1]})
+ }
+ return out
+}
+
+func TestValidateAcceptsAndCoerces(t *testing.T) {
+ form := &models.Form{Fields: models.FieldDefs{
+ {Key: "email", Label: "Email", Type: models.FieldEmail, Required: true, Role: models.RoleSenderEmail},
+ {Key: "age", Label: "Age", Type: models.FieldNumber, Min: ptrF(18), Max: ptrF(120)},
+ {Key: "dept", Label: "Department", Type: models.FieldSelect, Options: []models.FieldOption{{Value: "sales", Label: "Sales"}, {Value: "support"}}},
+ {Key: "topics", Label: "Topics", Type: models.FieldMultiSelect, Options: []models.FieldOption{{Value: "a, b"}, {Value: "c"}}},
+ {Key: "terms", Label: "Terms", Type: models.FieldCheckbox, Required: true},
+ {Key: "news", Label: "Newsletter", Type: models.FieldCheckbox},
+ {Key: "score", Label: "Score", Type: models.FieldScale, Min: ptrF(0), Max: ptrF(10)},
+ {Key: "stars", Label: "Stars", Type: models.FieldRating},
+ {Key: "day", Label: "Day", Type: models.FieldDate},
+ {Key: "at", Label: "At", Type: models.FieldTime},
+ {Key: "site", Label: "Site", Type: models.FieldURL},
+ {Key: "phone", Label: "Phone", Type: models.FieldPhone},
+ {Key: "note", Label: "Note", Type: models.FieldTextarea, Role: models.RoleBody},
+ }}
+ got, errs := Validate(form, fieldsOf(
+ "email", "Ada <[email protected]>", "age", "36", "dept", "sales",
+ "topics", "a, b", "topics", "c", "topics", "c",
+ "terms", "on", "score", "0", "stars", "5", "day", "2026-11-01", "at", "09:30:00",
+ "site", "https://example.com/x", "phone", "+44 (20) 7946-0958", "note", "Hello",
+ "extra", "kept",
+ ))
+ if errs != nil {
+ t.Fatalf("unexpected errors: %+v", errs)
+ }
+ want := models.SubmissionData{
+ "email": "[email protected]", "age": float64(36), "dept": "sales",
+ "topics": []string{"a, b", "c"}, "terms": true, "news": false,
+ "score": 0, "stars": 5, "day": "2026-11-01", "at": "09:30",
+ "site": "https://example.com/x", "phone": "+44 (20) 7946-0958", "note": "Hello",
+ }
+ if !reflect.DeepEqual(got.Data, want) {
+ t.Errorf("data:\n got %#v\nwant %#v", got.Data, want)
+ }
+ display := map[string]string{}
+ keys := []string{}
+ for _, f := range got.Fields {
+ display[f.Key] = f.Value
+ keys = append(keys, f.Key)
+ }
+ if display["dept"] != "Sales" || display["terms"] != "Yes" || display["news"] != "No" || display["topics"] != "a, b, c" {
+ t.Errorf("display copy: %v", display)
+ }
+ if keys[0] != "email" || keys[len(keys)-1] != "extra" {
+ t.Errorf("display order should follow the schema, then unknown fields: %v", keys)
+ }
+ if got.Roles[models.RoleSenderEmail] != "[email protected]" || got.Roles[models.RoleBody] != "Hello" {
+ t.Errorf("roles: %v", got.Roles)
+ }
+}
+
+func TestValidateRejects(t *testing.T) {
+ cases := []struct {
+ name string
+ def models.FieldDef
+ value []string // nil: field absent
+ code string
+ }{
+ {"required text", models.FieldDef{Type: models.FieldText, Required: true}, nil, "required"},
+ {"blank required", models.FieldDef{Type: models.FieldText, Required: true}, []string{" "}, "required"},
+ {"too short", models.FieldDef{Type: models.FieldText, MinLen: ptrI(3)}, []string{"ab"}, "too_short"},
+ {"default text limit", models.FieldDef{Type: models.FieldText}, []string{strings.Repeat("x", 201)}, "too_long"},
+ {"pattern is a full match", models.FieldDef{Type: models.FieldText, Pattern: `[A-Z]{3}`}, []string{"ABCD"}, "pattern"},
+ {"email", models.FieldDef{Type: models.FieldEmail}, []string{"not-an-email"}, "invalid_email"},
+ {"email without a dot", models.FieldDef{Type: models.FieldEmail}, []string{"a@localhost"}, "invalid_email"},
+ {"phone", models.FieldDef{Type: models.FieldPhone}, []string{"12-34"}, "invalid_phone"},
+ {"number", models.FieldDef{Type: models.FieldNumber}, []string{"twelve"}, "invalid_number"},
+ {"NaN", models.FieldDef{Type: models.FieldNumber}, []string{"NaN"}, "invalid_number"},
+ {"number range", models.FieldDef{Type: models.FieldNumber, Max: ptrF(10)}, []string{"11"}, "out_of_range"},
+ {"url scheme", models.FieldDef{Type: models.FieldURL}, []string{"javascript:alert(1)"}, "invalid_url"},
+ {"date", models.FieldDef{Type: models.FieldDate}, []string{"01/11/2026"}, "invalid_date"},
+ {"date range", models.FieldDef{Type: models.FieldDate}, []string{"1800-01-01"}, "invalid_date"},
+ {"time", models.FieldDef{Type: models.FieldTime}, []string{"25:00"}, "invalid_time"},
+ {"select", models.FieldDef{Type: models.FieldSelect, Options: []models.FieldOption{{Value: "a"}}}, []string{"b"}, "invalid_option"},
+ {"multiselect", models.FieldDef{Type: models.FieldMultiSelect, Options: []models.FieldOption{{Value: "a"}}}, []string{"a", "b"}, "invalid_option"},
+ {"required checkbox must be ticked", models.FieldDef{Type: models.FieldCheckbox, Required: true}, []string{"false"}, "required"},
+ {"checkbox value", models.FieldDef{Type: models.FieldCheckbox}, []string{"maybe"}, "invalid_value"},
+ {"scale range", models.FieldDef{Type: models.FieldScale}, []string{"6"}, "out_of_range"},
+ {"rating range", models.FieldDef{Type: models.FieldRating}, []string{"0"}, "out_of_range"},
+ }
+ for _, tc := range cases {
+ tc.def.Key, tc.def.Label = "f", "F"
+ form := &models.Form{Fields: models.FieldDefs{tc.def}}
+ var fields []models.MessageField
+ for _, v := range tc.value {
+ fields = append(fields, models.MessageField{Key: "f", Value: v})
+ }
+ _, errs := Validate(form, fields)
+ if len(errs) != 1 || errs[0].Code != tc.code || errs[0].Key != "f" || errs[0].Message == "" {
+ t.Errorf("%s: errors = %+v, want one %q", tc.name, errs, tc.code)
+ }
+ }
+}
+
+func TestValidateUnknownFields(t *testing.T) {
+ defs := models.FieldDefs{
+ {Key: "email", Label: "Email", Type: models.FieldEmail},
+ {Key: "old", Label: "Old", Type: models.FieldText, Archived: true},
+ }
+ submitted := fieldsOf("email", "[email protected]", "old", "legacy", "extra", "x")
+ keys := func(fs []models.MessageField) string {
+ var k []string
+ for _, f := range fs {
+ k = append(k, f.Key)
+ }
+ return strings.Join(k, ",")
+ }
+
+ keep, errs := Validate(&models.Form{Fields: defs}, submitted)
+ if errs != nil || keys(keep.Fields) != "email,old,extra" {
+ t.Errorf("keep: fields %q, errors %+v", keys(keep.Fields), errs)
+ }
+ if _, inData := keep.Data["extra"]; inData {
+ t.Error("keep: an unknown field must not enter typed data")
+ }
+
+ drop, errs := Validate(&models.Form{Fields: defs, UnknownFields: models.UnknownFieldsDrop}, submitted)
+ if errs != nil || keys(drop.Fields) != "email" {
+ t.Errorf("drop: fields %q, errors %+v", keys(drop.Fields), errs)
+ }
+
+ _, errs = Validate(&models.Form{Fields: defs, UnknownFields: models.UnknownFieldsReject}, submitted)
+ if len(errs) != 1 || errs[0].Key != "extra" || errs[0].Code != "unknown_field" {
+ t.Errorf("reject: errors %+v; archived keys must not be rejected", errs)
+ }
+}
+
+func TestExtractWithRolesFallsBackOnlyForUnsetRoles(t *testing.T) {
+ schema := models.FieldDefs{
+ {Key: "contact", Label: "Contact", Type: models.FieldEmail, Role: models.RoleSenderEmail},
+ {Key: "question", Label: "Question", Type: models.FieldTextarea, Role: models.RoleBody},
+ }
+ fields := fieldsOf("contact", "[email protected]", "email", "[email protected]", "name", "Ada", "question", "Hi")
+ got := ExtractWithRoles(map[models.FieldRole]string{
+ models.RoleSenderEmail: "[email protected]", models.RoleBody: "Hi",
+ }, schema, fields)
+ if got.Email != "[email protected]" || got.Body != "Hi" || got.Name != "Ada" {
+ t.Errorf("got %+v: roles must win, unset roles fall back to guessing", got)
+ }
+}
+
+func TestCheckSchema(t *testing.T) {
+ ok := models.FieldDefs{{Key: "email", Label: "Email", Type: models.FieldEmail, Role: models.RoleSenderEmail}}
+ if err := CheckSchema(ok, nil, "_gotcha"); err != nil {
+ t.Fatalf("valid schema rejected: %v", err)
+ }
+ cases := []struct {
+ name string
+ defs models.FieldDefs
+ prev models.FieldDefs
+ want string
+ }{
+ {"bad key", models.FieldDefs{{Key: "Bad Key", Label: "x", Type: models.FieldText}}, nil, "lowercase"},
+ {"reserved key", models.FieldDefs{{Key: "_nonce", Label: "x", Type: models.FieldText}}, nil, "lowercase"},
+ {"duplicate key", models.FieldDefs{{Key: "a", Label: "a", Type: models.FieldText}, {Key: "a", Label: "a", Type: models.FieldText}}, nil, "twice"},
+ {"honeypot key", models.FieldDefs{{Key: "website", Label: "x", Type: models.FieldText}}, nil, "honeypot"},
+ {"unknown type", models.FieldDefs{{Key: "a", Label: "a", Type: "password"}}, nil, "unknown type"},
+ {"missing label", models.FieldDefs{{Key: "a", Type: models.FieldText}}, nil, "label"},
+ {"role on wrong type", models.FieldDefs{{Key: "a", Label: "a", Type: models.FieldText, Role: models.RoleSenderEmail}}, nil, "does not fit"},
+ {"role twice", models.FieldDefs{{Key: "a", Label: "a", Type: models.FieldEmail, Role: models.RoleSenderEmail}, {Key: "b", Label: "b", Type: models.FieldEmail, Role: models.RoleSenderEmail}}, nil, "both have role"},
+ {"bad pattern", models.FieldDefs{{Key: "a", Label: "a", Type: models.FieldText, Pattern: "("}}, nil, "does not compile"},
+ {"select without options", models.FieldDefs{{Key: "a", Label: "a", Type: models.FieldSelect}}, nil, "options"},
+ {"duplicate option", models.FieldDefs{{Key: "a", Label: "a", Type: models.FieldSelect, Options: []models.FieldOption{{Value: "x"}, {Value: "x"}}}}, nil, "twice"},
+ {"display on wrong type", models.FieldDefs{{Key: "a", Label: "a", Type: models.FieldSelect, Display: models.DisplayCheckboxes, Options: []models.FieldOption{{Value: "x"}}}}, nil, "display"},
+ {"scale range", models.FieldDefs{{Key: "a", Label: "a", Type: models.FieldScale, Min: ptrF(2), Max: ptrF(5)}}, nil, "scale"},
+ {"rating range", models.FieldDefs{{Key: "a", Label: "a", Type: models.FieldRating, Max: ptrF(20)}}, nil, "stars"},
+ {"removed key", models.FieldDefs{}, ok, "archive it"},
+ }
+ for _, tc := range cases {
+ err := CheckSchema(tc.defs, tc.prev, "website")
+ if err == nil || !strings.Contains(err.Error(), tc.want) {
+ t.Errorf("%s: err = %v, want it to mention %q", tc.name, err, tc.want)
+ }
+ }
+ archived := models.FieldDefs{{Key: "email", Label: "Email", Type: models.FieldEmail, Archived: true}}
+ if err := CheckSchema(archived, ok, "_gotcha"); err != nil {
+ t.Errorf("archiving a key must be allowed: %v", err)
+ }
+}
+
+func TestJoinRepeated(t *testing.T) {
+ got := JoinRepeated(fieldsOf("a", "1", "b", "x", "a", "2", "a", ""))
+ want := fieldsOf("a", "1, 2", "b", "x")
+ if !reflect.DeepEqual(got, want) {
+ t.Errorf("got %v, want %v", got, want)
+ }
+}
diff --git a/internal/web/widget/posta-form.js b/internal/web/widget/posta-form.js
index 64c5118..82f9707 100644
--- a/internal/web/widget/posta-form.js
+++ b/internal/web/widget/posta-form.js
@@ -21,6 +21,8 @@
subject: "Subject",
message: "Message",
optional: "optional",
+ required: "This field is required.",
+ choose: "Choose…",
button: "Send message",
sending: "Sending…",
success: "Thanks — your message has been received.",
@@ -38,6 +40,8 @@
subject: "Objet",
message: "Message",
optional: "facultatif",
+ required: "Ce champ est obligatoire.",
+ choose: "Choisir…",
button: "Envoyer",
sending: "Envoi…",
success: "Merci, votre message a bien été reçu.",
@@ -55,7 +59,7 @@
var BUILTIN_FIELDS = {
name: { type: "text", autocomplete: "name", required: true },
email: { type: "email", autocomplete: "email", required: true },
- phone: { type: "tel", autocomplete: "tel", required: false },
+ phone: { type: "phone", autocomplete: "tel", required: false },
subject: { type: "text", required: false },
message: { type: "textarea", required: true },
};
@@ -81,11 +85,28 @@
".pf .f{margin:0 0 12px}" +
".pf label{display:block;margin:0 0 4px;font-weight:600;font-size:.9em}" +
".pf .opt{font-weight:400;color:var(--mut)}" +
+ ".pf fieldset{border:0;padding:0;min-width:0}" +
+ ".pf legend{display:block;padding:0;margin:0 0 6px;font-weight:600;font-size:.9em}" +
+ ".pf .help{margin:-2px 0 6px;font-size:.85em;color:var(--mut)}" +
+ ".pf select{display:block;width:100%;margin:0;padding:9px 11px;font:inherit;color:var(--fg);background:var(--in);border:1px solid var(--bd);border-radius:var(--r)}" +
+ ".pf .opts{display:grid;gap:6px}" +
+ ".pf .opt-item,.pf .tick{display:flex;align-items:center;gap:8px;font-weight:400;font-size:1em;margin:0;cursor:pointer}" +
+ ".pf .opt-item input,.pf .tick input{width:auto;margin:0;accent-color:var(--a)}" +
+ ".pf .scale{display:flex;flex-wrap:wrap;align-items:center;gap:6px}" +
+ ".pf .scale .end{font-size:.85em;color:var(--mut)}" +
+ ".pf .scale .opt-item{position:relative;justify-content:center;min-width:38px;height:38px;border:1px solid var(--bd);border-radius:var(--r);background:var(--in)}" +
+ ".pf .scale .opt-item input{position:absolute;opacity:0;width:100%;height:100%;cursor:pointer}" +
+ ".pf .scale .opt-item:has(input:checked){background:var(--a);border-color:var(--a);color:#fff}" +
+ ".pf .scale .opt-item:has(input:focus-visible){outline:2px solid var(--a);outline-offset:2px}" +
+ ".pf .rating .opt-item{border:0;background:none;min-width:30px;font-size:1.5em;color:var(--bd)}" +
+ ".pf .rating .opt-item.on,.pf .rating .opt-item:has(input:checked){background:none;color:#F5A524}" +
+ ".pf .sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0)}" +
".pf input,.pf textarea{display:block;width:100%;margin:0;padding:9px 11px;font:inherit;color:var(--fg);" +
"background:var(--in);border:1px solid var(--bd);border-radius:var(--r);transition:border-color .15s,box-shadow .15s}" +
".pf textarea{min-height:120px;resize:vertical}" +
".pf input:focus,.pf textarea:focus{outline:none;border-color:var(--a);box-shadow:0 0 0 3px color-mix(in srgb,var(--a) 25%,transparent)}" +
".pf [aria-invalid=true]{border-color:var(--err)}" +
+ ".pf .opts[aria-invalid=true],.pf .scale[aria-invalid=true]{outline:1px solid var(--err);outline-offset:4px;border-radius:2px}" +
".pf .ferr{margin:4px 0 0;font-size:.85em;color:var(--err)}" +
".pf .hp{position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden}" +
".pf button{display:inline-flex;align-items:center;justify-content:center;min-height:42px;padding:0 18px;font:inherit;font-weight:600;" +
@@ -232,6 +253,159 @@
}
);
+ // buildField renders one field and returns how to read it, focus it and
+ // show an error on it.
+ function buildField(f, fid) {
+ var errId = fid + "-err";
+ var helpId = fid + "-help";
+ var type = f.type || "text";
+ var preset = el.getAttribute("data-value-" + f.key) || "";
+
+ if (type === "hidden") {
+ var hidden = h("input", { type: "hidden", name: f.key, value: preset });
+ return { row: hidden, get: function () { return hidden.value; }, focus: function () {}, mark: function () {}, clear: function () {} };
+ }
+
+ var grouped = type === "scale" || type === "rating" || type === "multiselect" && f.display !== "list" ||
+ type === "select" && (f.display === "radio" || !f.display && (f.options || []).length <= 6);
+ var row = h(grouped ? "fieldset" : "div", { class: "f" });
+ var caption = h(grouped ? "legend" : "label", grouped ? null : { for: fid }, type === "checkbox" ? "" : f.label || f.key);
+ if (type !== "checkbox") {
+ if (!f.required) {
+ caption.appendChild(document.createTextNode(" "));
+ caption.appendChild(h("span", { class: "opt" }, "(" + t.optional + ")"));
+ }
+ row.appendChild(caption);
+ }
+ var help = f.help ? h("p", { class: "help", id: helpId }, f.help) : null;
+ if (help) row.appendChild(help);
+ var describedBy = help ? helpId : null;
+
+ var focusEl, get, marked = [];
+ var requiredGroup = false;
+
+ if (type === "textarea") {
+ focusEl = h("textarea", { id: fid, name: f.key, required: !!f.required, maxlength: f.max_len, minlength: f.min_len, placeholder: f.placeholder, "aria-describedby": describedBy });
+ focusEl.value = preset;
+ row.appendChild(focusEl);
+ get = function () { return focusEl.value; };
+ marked = [focusEl];
+ } else if (type === "checkbox") {
+ focusEl = h("input", { id: fid, type: "checkbox", name: f.key, required: !!f.required, "aria-describedby": describedBy });
+ var tick = h("label", { class: "tick", for: fid });
+ tick.appendChild(focusEl);
+ tick.appendChild(h("span", null, f.label || f.key));
+ if (help) row.insertBefore(tick, help);
+ else row.appendChild(tick);
+ get = function () { return focusEl.checked; };
+ marked = [focusEl];
+ } else if (type === "select" && !grouped) {
+ focusEl = h("select", { id: fid, name: f.key, required: !!f.required, "aria-describedby": describedBy });
+ focusEl.appendChild(h("option", { value: "" }, t.choose));
+ (f.options || []).forEach(function (o) { focusEl.appendChild(h("option", { value: o.value }, o.label || o.value)); });
+ row.appendChild(focusEl);
+ get = function () { return focusEl.value; };
+ marked = [focusEl];
+ } else if (type === "multiselect" && !grouped) {
+ focusEl = h("select", { id: fid, name: f.key, multiple: true, size: Math.min((f.options || []).length, 6), "aria-describedby": describedBy });
+ (f.options || []).forEach(function (o) { focusEl.appendChild(h("option", { value: o.value }, o.label || o.value)); });
+ row.appendChild(focusEl);
+ get = function () {
+ return Array.prototype.filter.call(focusEl.options, function (o) { return o.selected; }).map(function (o) { return o.value; });
+ };
+ requiredGroup = !!f.required;
+ marked = [focusEl];
+ } else if (grouped) {
+ var choices = [];
+ if (type === "scale" || type === "rating") {
+ var lo = type === "rating" ? 1 : f.min != null ? f.min : 1;
+ var hi = f.max != null ? f.max : 5;
+ for (var n = lo; n <= hi; n++) choices.push({ value: String(n), label: type === "rating" ? "★" : String(n), title: String(n) });
+ } else {
+ choices = (f.options || []).map(function (o) { return { value: o.value, label: o.label || o.value }; });
+ }
+ var multi = type === "multiselect";
+ var list = h("div", { class: type === "scale" || type === "rating" ? "scale " + type : "opts", role: multi ? "group" : "radiogroup", "aria-describedby": describedBy });
+ if (type === "scale" && f.min_label) list.appendChild(h("span", { class: "end" }, f.min_label));
+ var boxes = choices.map(function (ch, i) {
+ var cid = fid + "-" + i;
+ var box = h("input", { id: cid, type: multi ? "checkbox" : "radio", name: f.key, value: ch.value, required: !multi && !!f.required });
+ var item = h("label", { class: "opt-item", for: cid, title: ch.title || null });
+ item.appendChild(box);
+ item.appendChild(h("span", type === "rating" ? { "aria-hidden": "true" } : null, ch.label));
+ if (type === "rating") item.appendChild(h("span", { class: "sr" }, ch.title + " / " + hi));
+ list.appendChild(item);
+ return box;
+ });
+ if (type === "scale" && f.max_label) list.appendChild(h("span", { class: "end" }, f.max_label));
+ if (type === "rating") {
+ list.addEventListener("change", function () {
+ var picked = 0;
+ boxes.forEach(function (b, i) { if (b.checked) picked = i + 1; });
+ boxes.forEach(function (b, i) { b.parentNode.classList.toggle("on", i < picked); });
+ });
+ }
+ row.appendChild(list);
+ focusEl = boxes[0];
+ get = multi
+ ? function () { return boxes.filter(function (b) { return b.checked; }).map(function (b) { return b.value; }); }
+ : function () { var b = boxes.filter(function (b) { return b.checked; })[0]; return b ? b.value : ""; };
+ requiredGroup = multi && !!f.required;
+ marked = [list];
+ } else {
+ var inputType = { phone: "tel", email: "email", number: "number", url: "url", date: "date", time: "time" }[type] || "text";
+ focusEl = h("input", {
+ id: fid,
+ name: f.key,
+ type: inputType,
+ required: !!f.required,
+ autocomplete: f.autocomplete || { email: "email", tel: "tel" }[inputType],
+ maxlength: f.max_len,
+ minlength: f.min_len,
+ min: inputType === "number" ? f.min : null,
+ max: inputType === "number" ? f.max : null,
+ step: inputType === "number" ? "any" : null,
+ placeholder: f.placeholder,
+ "aria-describedby": describedBy,
+ });
+ focusEl.value = preset;
+ row.appendChild(focusEl);
+ get = function () { return focusEl.value; };
+ marked = [focusEl];
+ }
+
+ var err = h("p", { class: "ferr", id: errId, hidden: true });
+ row.appendChild(err);
+ var control = {
+ row: row,
+ get: get,
+ requiredGroup: requiredGroup,
+ focus: function () { focusEl.focus(); },
+ mark: function (text) {
+ err.textContent = text;
+ err.hidden = false;
+ marked.forEach(function (m) {
+ m.setAttribute("aria-invalid", "true");
+ m.setAttribute("aria-describedby", describedBy ? describedBy + " " + errId : errId);
+ });
+ },
+ clear: function () {
+ err.hidden = true;
+ err.textContent = "";
+ marked.forEach(function (m) {
+ m.removeAttribute("aria-invalid");
+ if (describedBy) m.setAttribute("aria-describedby", describedBy);
+ else m.removeAttribute("aria-describedby");
+ });
+ },
+ };
+ // An error describes the value that was sent; once the visitor
+ // changes the field it no longer applies.
+ row.addEventListener("input", function () { if (!err.hidden) control.clear(); });
+ row.addEventListener("change", function () { if (!err.hidden) control.clear(); });
+ return control;
+ }
+
function render(cfg, fields) {
body.textContent = "";
var nonce = cfg.nonce ? cfg.nonce.nonce : "";
@@ -247,36 +421,13 @@
if (description) body.appendChild(h("p", { class: "desc" }, description));
var form = h("form", { "aria-label": title || null });
- var inputs = {};
- var errors = {};
+
+ var controls = {};
fields.forEach(function (f) {
- var fid = id + "-" + f.key;
- var row = h("div", { class: "f" });
- var label = h("label", { for: fid }, f.label || f.key);
- if (!f.required) {
- label.appendChild(document.createTextNode(" "));
- label.appendChild(h("span", { class: "opt" }, "(" + t.optional + ")"));
- }
- row.appendChild(label);
- var input =
- f.type === "textarea"
- ? h("textarea", { id: fid, name: f.key, required: !!f.required, maxlength: f.max_len })
- : h("input", {
- id: fid,
- name: f.key,
- type: f.type || "text",
- required: !!f.required,
- autocomplete: f.autocomplete,
- maxlength: f.max_len,
- placeholder: f.placeholder,
- });
- row.appendChild(input);
- var err = h("p", { class: "ferr", id: fid + "-err", hidden: true });
- row.appendChild(err);
- inputs[f.key] = input;
- errors[f.key] = err;
- form.appendChild(row);
+ var c = buildField(f, id + "-" + f.key);
+ controls[f.key] = c;
+ form.appendChild(c.row);
});
var hpWrap = h("div", { class: "hp", "aria-hidden": "true" });
@@ -294,12 +445,7 @@
function clearErrors() {
status.textContent = "";
status.className = "st";
- Object.keys(errors).forEach(function (k) {
- errors[k].hidden = true;
- errors[k].textContent = "";
- inputs[k].removeAttribute("aria-invalid");
- inputs[k].removeAttribute("aria-describedby");
- });
+ Object.keys(controls).forEach(function (k) { controls[k].clear(); });
}
function fail(text) {
@@ -322,7 +468,21 @@
e.preventDefault();
clearErrors();
var payload = {};
- Object.keys(inputs).forEach(function (k) { payload[k] = inputs[k].value; });
+ var missing = null;
+ Object.keys(controls).forEach(function (k) {
+ var c = controls[k];
+ payload[k] = c.get();
+ if (c.requiredGroup && !payload[k].length) {
+ c.mark(t.required);
+ missing = missing || c;
+ }
+ });
+ // Native validation covers single inputs; a required group of
+ // checkboxes has no native check.
+ if (missing) {
+ missing.focus();
+ return;
+ }
payload[honeypot.name] = honeypot.value;
if (nonce) payload._nonce = nonce;
@@ -359,14 +519,12 @@
var fieldErrs = (res.body && res.body.error && res.body.error.fields) || [];
var first = null;
fieldErrs.forEach(function (fe) {
- if (!inputs[fe.key]) return;
- errors[fe.key].textContent = fe.message || fe.code;
- errors[fe.key].hidden = false;
- inputs[fe.key].setAttribute("aria-invalid", "true");
- inputs[fe.key].setAttribute("aria-describedby", errors[fe.key].id);
- first = first || inputs[fe.key];
+ var c = controls[fe.key];
+ if (!c) return;
+ c.mark(fe.message || fe.code);
+ first = first || c;
});
- var message = data.message || (res.body && res.body.message) || t.error;
+ var message = data.message || (res.body && res.body.error && res.body.error.message) || (res.body && res.body.message) || t.error;
if (!first) fail(message);
else first.focus();
var code = data.status || (res.body && res.body.error && res.body.error.code) || "error";