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.
Go email-relayemail-routinghttp-to-smtpmail-deliverymailchimp-alternativemailgun-alternativemailsendermailservermailtemplatemailtestpostmark-alternativesend-emailsendgrid-alternativesendmailtransactional-emailtransactional-outbox
feat(messages): add hosted form pages and response settings
Jonas Kaninda35b3e18cffff
diff --git a/docs/docs/messages/sharing-a-form.md b/docs/docs/messages/sharing-a-form.mdnew file mode 100644index 0000000..586f03b--- /dev/null+++ b/docs/docs/messages/sharing-a-form.md@@ -0,0 +1,65 @@+---+sidebar_position: 2.5+title: Sharing a form+description: Share a form with a link, control when it accepts responses, and set how it looks+---++# Sharing a Form++Every form has a **share link**: a page Posta hosts at `https://posta.example.com/f/YOUR_PUBLIC_KEY`. Send it by email, post it in a chat, or put it behind a QR code. Nobody needs a website. You find it at the top of the form's **Embed** tab.++The page shows the form's name and description, then the form itself, through the same [widget](./embedding.md#website-widget) you can embed on a website. Submissions arrive in the inbox like any other, with the same spam protection.++## Prefilled links++Add `?<field key>=<value>` to the link to answer a question in advance:++```+https://posta.example.com/f/YOUR_PUBLIC_KEY?plan=pro&source=newsletter+```++For a multi-select, repeat the key: `?topics=api&topics=smtp`. A value that is not one of the question's options is ignored. Questions marked as personal data (`pii`) are never prefilled, so a link cannot plant someone's details in another person's response. Without a [schema](./fields-and-validation.md), the link can prefill `name`, `email`, `phone`, `subject` and `message`.++## Responses++The form's **Responses** tab, or the same settings in the API:++| Setting | API field | Effect |+|---|---|---|+| Confirmation message | `confirmation_message` | Shown after someone submits. Up to 500 characters. |+| Submit another response | `allow_another_response` | Shows a link that brings the form back after submitting. |+| Stop accepting responses after | `close_at` | An RFC 3339 time. From then on the form is closed. |+| Response limit | `max_responses` | The form closes after this many responses. Spam does not count. `0` means no limit. |+| Closed message | `closed_message` | Shown instead of the form while it is closed. |++A form is **closed** while its status is **Paused**, after `close_at`, or once it reaches `max_responses`. The share page and every embed then show the closed message instead of the form, and a submission sent anyway is answered `403` with that message, so nobody is told "thanks" for a response that was not kept.++## Appearance++`appearance` sets the look of the share page and the default look of embeds:++```json+{ "accent": "#0f766e", "theme": "dark", "header_image_url": "https://example.com/banner.png" }+```++- `accent`: a colour like `#9333ea`;+- `theme`: `light`, `dark`, or `auto` to follow the visitor's system;+- `header_image_url`: an `https` image shown at the top of the share page.++On a website, `data-accent` and `data-theme` on the embed take precedence, so the same form can match different pages.++## For administrators++Public pages on your domain can be abused for phishing, so share pages:++- warn visitors to never submit passwords, and offer a **Report abuse** link;+- offer no password question type;+- are served with a strict Content Security Policy and cannot be framed by other sites;+- are hidden from search engines.++Under **Admin → Settings → Security**:++- **Hosted Form Pages** turns share pages off for the whole platform. Links then answer `404`; embeds on websites keep working.+- **Abuse Report Email** is where the **Report abuse** link sends reports. Empty uses the admin email.++Settings take effect within 30 seconds.diff --git a/internal/handlers/form_handler.go b/internal/handlers/form_handler.goindex f37d508..dd16085 100644--- a/internal/handlers/form_handler.go+++ b/internal/handlers/form_handler.go@@ -104,6 +104,13 @@ type CreateFormRequest struct {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"`}@@ -132,11 +139,18 @@ type UpdateFormRequest struct {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"`++ 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"`+ ReplyFrom *string `json:"reply_from"`+ ReplyFromName *string `json:"reply_from_name"`+ RetentionDays *int `json:"retention_days"`} `json:"body"`}@@ -150,6 +164,7 @@ type FormSnippetResponse struct {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"`}func (h *FormHandler) Create(c *okapi.Context, req *CreateFormRequest) error {@@ -237,6 +252,12 @@ func (h *FormHandler) Create(c *okapi.Context, req *CreateFormRequest) error {if err := applySchema(form, fields, optionalString(req.Body.UnknownFields), optionalString(req.Body.ErrorRedirectURL)); err != nil {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")@@ -391,6 +412,11 @@ func (h *FormHandler) Update(c *okapi.Context, req *UpdateFormRequest) error {if err := applySchema(form, b.Fields, b.UnknownFields, b.ErrorRedirectURL); err != nil {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()@@ -458,6 +484,7 @@ func (h *FormHandler) Snippet(c *okapi.Context, req *FormIDRequest) error {HTML: buildHTMLSnippet(endpoint, form),Fetch: buildFetchSnippet(endpoint),Widget: buildWidgetSnippet(h.apiBaseURL, form),+ ShareURL: h.apiBaseURL + "/f/" + url.PathEscape(form.PublicKey),})}@@ -645,6 +672,81 @@ func applySchema(form *models.Form, fields *models.FieldDefs, unknownFields, errreturn 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 falsediff --git a/internal/handlers/form_ingest_handler.go b/internal/handlers/form_ingest_handler.goindex 4dd258a..a81f291 100644--- a/internal/handlers/form_ingest_handler.go+++ b/internal/handlers/form_ingest_handler.go@@ -36,6 +36,7 @@ import ("github.com/goposta/posta/internal/models""github.com/goposta/posta/internal/services/inbound""github.com/goposta/posta/internal/services/messages"+ "github.com/goposta/posta/internal/services/settings""github.com/goposta/posta/internal/storage/blob""github.com/goposta/posta/internal/web/widget""github.com/jkaninda/logger"@@ -45,6 +46,9 @@ import (const genericAcceptMessage = "Thanks — your message has been received."type FormIngestHandler struct {+ settings *settings.Provider+ abuseFallback string+svc *messages.ServiceblobStore blob.Storelimiter *inbound.IPRateLimiter@@ -88,8 +92,41 @@ func (h *FormIngestHandler) Nonce(c *okapi.Context) error {const (widgetReasonUnavailable = "unavailable"widgetReasonOriginNotAllowed = "origin_not_allowed"+ widgetReasonClosed = "closed")+const defaultClosedMessage = "This form is no longer accepting responses."++func closedMessage(form *models.Form) string {+ if form.ClosedMessage != "" {+ return form.ClosedMessage+ }+ return defaultClosedMessage+}++// isSelfOrigin reports whether a request comes from a page Posta serves+// itself, such as a form's hosted page. Browsers send no Origin on a+// same-origin GET, so Sec-Fetch-Site stands in for it there.+func isSelfOrigin(r *http.Request) bool {+ origin := r.Header.Get("Origin")+ if origin == "" {+ return r.Header.Get("Sec-Fetch-Site") == "same-origin"+ }+ u, err := url.Parse(origin)+ return err == nil && u.Host != "" && strings.EqualFold(u.Host, r.Host)+}++// originAllowed applies the form's allowlist to other websites. The+// allowlist decides which sites may embed a form; Posta's own hosted page is+// always allowed.+func originAllowed(r *http.Request, form *models.Form) bool {+ if isSelfOrigin(r) {+ return true+ }+ allowlist, strict := form.OriginPolicy()+ return messages.OriginAllowed(allowlist, strict, r.Header.Get("Origin"))+}+// WidgetConfig is what the website widget needs before it renders a form.type WidgetConfig struct {Enabled bool `json:"enabled"`@@ -99,6 +136,11 @@ type WidgetConfig struct {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."`++ ClosedMessage string `json:"closed_message,omitempty" doc:"Shown instead of the form when reason is closed"`+ ConfirmationMessage string `json:"confirmation_message,omitempty" doc:"Shown after a successful submission"`+ AllowAnotherResponse bool `json:"allow_another_response,omitempty"`+ Appearance *models.FormAppearance `json:"appearance,omitempty"`}// WidgetField is the public view of a schema field: what a browser needs to@@ -152,18 +194,26 @@ func widgetFields(defs models.FieldDefs) []WidgetField {// widgetConfig decides what the widget on origin may see of form. A nil form// is an unknown key.-func widgetConfig(form *models.Form, origin string) WidgetConfig {- if form == nil || !form.IsActive() {+func widgetConfig(form *models.Form, originOK bool, now time.Time) WidgetConfig {+ if form == nil || form.Status == models.FormStatusArchived {return WidgetConfig{Reason: widgetReasonUnavailable}}- allowlist, strict := form.OriginPolicy()- if !messages.OriginAllowed(allowlist, strict, origin) {+ if !originOK {return WidgetConfig{Reason: widgetReasonOriginNotAllowed}}+ if form.Closed(now) {+ return WidgetConfig{Reason: widgetReasonClosed, ClosedMessage: closedMessage(form)}+ }cfg := WidgetConfig{- Enabled: true,- HoneypotField: form.Honeypot(),- RequireNonce: form.RequireNonce,+ Enabled: true,+ HoneypotField: form.Honeypot(),+ RequireNonce: form.RequireNonce,+ ConfirmationMessage: form.ConfirmationMessage,+ AllowAnotherResponse: form.AllowAnotherResponse,+ }+ if form.Appearance != (models.FormAppearance{}) {+ appearance := form.Appearance+ cfg.Appearance = &appearance}if form.RequireNonce {cfg.MinFillSeconds = form.MinFillSeconds@@ -185,7 +235,7 @@ func (h *FormIngestHandler) WidgetConfig(c *okapi.Context) error {if err != nil {form = nil}- cfg := widgetConfig(form, origin)+ cfg := widgetConfig(form, form != nil && originAllowed(c.Request(), form), time.Now())if !cfg.Enabled {// A disabled answer carries no form data, so any origin may read it.if origin != "" {@@ -229,16 +279,20 @@ func (h *FormIngestHandler) Submit(c *okapi.Context) error {}form, err := h.svc.FindFormByKey(key)- if err != nil || !form.IsActive() {+ if err != nil || form.Status == models.FormStatusArchived {return h.respond(c, nil, nil, http.StatusAccepted, "received", genericAcceptMessage)}origin := req.Header.Get("Origin")- allowlist, strict := form.OriginPolicy()- if !messages.OriginAllowed(allowlist, strict, origin) {+ if !originAllowed(req, form) {return h.respond(c, form, nil, http.StatusForbidden, "origin_not_allowed", "This origin is not allowed to submit to this form.")}h.applyCORS(c, form)+ // A closed form says so: the visitor is real enough to have reached it,+ // and the form's owner chose the message.+ if form.Closed(time.Now()) {+ return h.respond(c, form, nil, http.StatusForbidden, "closed", closedMessage(form))+ }fields, attachments, redirect, err := h.parseBody(c, form)if err != nil {diff --git a/internal/handlers/form_page_handler.go b/internal/handlers/form_page_handler.gonew file mode 100644index 0000000..3695a8f--- /dev/null+++ b/internal/handlers/form_page_handler.go@@ -0,0 +1,184 @@+// 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"+ "html/template"+ "net/http"+ "net/url"+ "strings"++ "github.com/goposta/posta/internal/models"+ "github.com/goposta/posta/internal/services/settings"+ "github.com/jkaninda/okapi"+)++const maxPrefillLength = 2000++// builtinPrefillKeys are the fields the widget shows for a form without a+// schema, so its share link can prefill them too.+var builtinPrefillKeys = []string{"name", "email", "phone", "subject", "message"}++// hostedPageCSP keeps a hosted page to Posta's own script and API. Inline+// styles are allowed for the page and the widget's shadow root; images may+// come from any https host for the header image.+const hostedPageCSP = "default-src 'none'; script-src 'self'; connect-src 'self'; " ++ "style-src 'self' 'unsafe-inline'; img-src https: data:; form-action 'none'; " ++ "frame-ancestors 'none'; base-uri 'none'"++// SetHostedPages enables the hosted form pages. adminEmail is the abuse+// contact when the platform setting abuse_report_email is empty.+func (h *FormIngestHandler) SetHostedPages(p *settings.Provider, adminEmail string) {+ h.settings = p+ h.abuseFallback = adminEmail+}++type hostedPageData struct {+ Title string+ Description string+ Key string+ Theme string+ HeaderImage string+ Attrs []template.HTMLAttr+ AbuseMail string+}++// HostedPage serves a form's share link: a page on Posta's own domain that+// shows the form through the website widget.+func (h *FormIngestHandler) HostedPage(c *okapi.Context) error {+ if h.settings == nil || !h.settings.HostedFormsEnabled() {+ return trackingNotice(c, http.StatusNotFound, "Form not found", "This form does not exist.", "error")+ }+ key := c.Param("key")+ form, err := h.svc.FindFormByKey(key)+ if err != nil || form.Status == models.FormStatusArchived {+ return trackingNotice(c, http.StatusNotFound, "Form not found", "This form does not exist.", "error")+ }++ data := hostedPageData{+ Title: form.Name,+ Description: form.Description,+ Key: form.PublicKey,+ Theme: form.Appearance.Theme,+ HeaderImage: form.Appearance.HeaderImageURL,+ Attrs: prefillAttrs(form, c.Request().URL.Query()),+ AbuseMail: abuseMailto(h.abuseContact(h.settings.AbuseReportEmail()), form.PublicKey),+ }+ if data.Theme == "" {+ data.Theme = "light"+ }++ hdr := c.ResponseWriter().Header()+ hdr.Set("Content-Type", "text/html; charset=utf-8")+ hdr.Set("Content-Security-Policy", hostedPageCSP)+ hdr.Set("X-Content-Type-Options", "nosniff")+ hdr.Set("Referrer-Policy", "no-referrer")+ hdr.Set("Cache-Control", "no-store")+ c.ResponseWriter().WriteHeader(http.StatusOK)+ return hostedPageTemplate.Execute(c.ResponseWriter(), data)+}++// abuseContact is the configured abuse address, or the admin's.+func (h *FormIngestHandler) abuseContact(configured string) string {+ if c := strings.TrimSpace(configured); c != "" {+ return c+ }+ return h.abuseFallback+}++func abuseMailto(contact, formKey string) string {+ if contact == "" {+ return ""+ }+ q := url.Values{}+ q.Set("subject", "Abuse report: form "+formKey)+ return "mailto:" + contact + "?" + strings.ReplaceAll(q.Encode(), "+", "%20")+}++// prefillAttrs turns ?<key>=value into data-value-<key> attributes for the+// widget. Only declared, non-PII fields are prefilled: a link must not be a+// way to plant personal data in someone else's submission. Keys come from the+// schema (lowercase letters, digits, _), so they are safe attribute names.+func prefillAttrs(form *models.Form, query url.Values) []template.HTMLAttr {+ var attrs []template.HTMLAttr+ add := func(key, value string) {+ if len(value) > maxPrefillLength {+ return+ }+ attrs = append(attrs, template.HTMLAttr(fmt.Sprintf(`data-value-%s="%s"`, key, html.EscapeString(value))))+ }+ if !form.HasSchema() {+ for _, key := range builtinPrefillKeys {+ if v := query.Get(key); v != "" {+ add(key, v)+ }+ }+ return attrs+ }+ for _, f := range form.Fields.Active() {+ values := query[f.Key]+ if f.PII || len(values) == 0 {+ continue+ }+ if f.Type == models.FieldMultiSelect {+ encoded, _ := json.Marshal(values)+ add(f.Key, string(encoded))+ continue+ }+ add(f.Key, values[0])+ }+ return attrs+}++var hostedPageTemplate = template.Must(template.New("page").Parse(`<!DOCTYPE html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<meta name="robots" content="noindex, nofollow">+<title>{{.Title}}</title>+<style>+:root{--bg:#F2F4FA;--fg:#101A37;--mut:#5A6486}+:root[data-theme=dark]{--bg:#0A1124;--fg:#F2F4FA;--mut:#A9B1CC}+@media (prefers-color-scheme:dark){:root[data-theme=auto]{--bg:#0A1124;--fg:#F2F4FA;--mut:#A9B1CC}}+*{box-sizing:border-box}+body{margin:0;background:var(--bg);color:var(--fg);font:16px/1.5 system-ui,-apple-system,"Segoe UI",sans-serif}+main{max-width:680px;margin:0 auto;padding:32px 16px 24px}+.header{display:block;width:100%;max-height:220px;object-fit:cover;border-radius:12px;margin:0 0 20px}+[data-posta-form]{--posta-form-max-width:100%}+footer{max-width:680px;margin:0 auto;padding:0 16px 32px;font-size:13px;color:var(--mut);text-align:center}+footer a{color:inherit}+</style>+</head>+<body>+<main>+{{if .HeaderImage}}<img class="header" src="{{.HeaderImage}}" alt="">{{end}}+<div data-posta-form="{{.Key}}" data-title="{{.Title}}"{{if .Description}} data-description="{{.Description}}"{{end}} data-theme="{{.Theme}}"{{range .Attrs}} {{.}}{{end}}></div>+</main>+<footer>+Never submit passwords through Posta forms.{{if .AbuseMail}} · <a href="{{.AbuseMail}}">Report abuse</a>{{end}}+</footer>+<script src="/widget/v1/posta-form.js" async></script>+</body>+</html>+`))diff --git a/internal/handlers/form_page_test.go b/internal/handlers/form_page_test.gonew file mode 100644index 0000000..4d5a20a--- /dev/null+++ b/internal/handlers/form_page_test.go@@ -0,0 +1,104 @@+// 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 (+ "bytes"+ "net/url"+ "strings"+ "testing"++ "github.com/goposta/posta/internal/models"+)++func TestPrefillAttrs(t *testing.T) {+ form := &models.Form{Fields: models.FieldDefs{+ {Key: "plan", Label: "Plan", Type: models.FieldSelect, Options: []models.FieldOption{{Value: "pro"}}},+ {Key: "topics", Label: "Topics", Type: models.FieldMultiSelect, Options: []models.FieldOption{{Value: "a, b"}, {Value: "c"}}},+ {Key: "email", Label: "Email", Type: models.FieldEmail, PII: true},+ {Key: "old", Label: "Old", Type: models.FieldText, Archived: true},+ {Key: "note", Label: "Note", Type: models.FieldText},+ }}+ query := url.Values{+ "plan": {"pro"},+ "topics": {"a, b", "c"},+ "email": {"[email protected]"},+ "old": {"x"},+ "unknown": {"x"},+ "note": {strings.Repeat("x", maxPrefillLength+1)},+ }+ var got []string+ for _, a := range prefillAttrs(form, query) {+ got = append(got, string(a))+ }+ want := []string{`data-value-plan="pro"`, `data-value-topics="["a, b","c"]"`}+ if strings.Join(got, " ") != strings.Join(want, " ") {+ t.Errorf("prefill attrs:\n got %v\nwant %v (PII, archived, unknown and overlong values must be skipped)", got, want)+ }++ schemaless := prefillAttrs(&models.Form{}, url.Values{"name": {"Ada"}, "other": {"x"}})+ if len(schemaless) != 1 || string(schemaless[0]) != `data-value-name="Ada"` {+ t.Errorf("schemaless prefill = %v, want only the built-in name field", schemaless)+ }+}++func TestHostedPageEscapesFormText(t *testing.T) {+ var buf bytes.Buffer+ err := hostedPageTemplate.Execute(&buf, hostedPageData{+ Title: `</title><script>alert(1)</script>`,+ Description: `" onmouseover="alert(1)`,+ Key: "abc",+ Theme: "light",+ HeaderImage: "javascript:alert(1)",+ Attrs: prefillAttrs(&models.Form{}, url.Values{"name": {`"><script>alert(1)</script>`}}),+ AbuseMail: "mailto:[email protected]?subject=x",+ })+ if err != nil {+ t.Fatal(err)+ }+ page := buf.String()+ for _, bad := range []string{"<script>alert(1)", `" onmouseover="`, `src="javascript:`} {+ if strings.Contains(page, bad) {+ t.Errorf("page contains unescaped %q", bad)+ }+ }+ for _, want := range []string{+ `<script src="/widget/v1/posta-form.js" async></script>`,+ "Never submit passwords through Posta forms.",+ `href="mailto:[email protected]?subject=x"`,+ } {+ if !strings.Contains(page, want) {+ t.Errorf("page is missing %q", want)+ }+ }+}++func TestAbuseMailtoFallsBackToAdmin(t *testing.T) {+ h := &FormIngestHandler{abuseFallback: "[email protected]"}+ if got := h.abuseContact(""); got != "[email protected]" {+ t.Errorf("fallback contact = %q", got)+ }+ if got := h.abuseContact("[email protected]"); got != "[email protected]" {+ t.Errorf("configured contact = %q", got)+ }+ if got := abuseMailto("[email protected]", "KEY1"); got != "mailto:[email protected]?subject=Abuse%20report%3A%20form%20KEY1" {+ t.Errorf("mailto = %q", got)+ }+}diff --git a/internal/handlers/form_widget_test.go b/internal/handlers/form_widget_test.goindex efee15a..ec71c3c 100644--- a/internal/handlers/form_widget_test.go+++ b/internal/handlers/form_widget_test.go@@ -25,6 +25,7 @@ import ("reflect""strings""testing"+ "time""github.com/goposta/posta/internal/models""github.com/goposta/posta/internal/web/widget"@@ -32,6 +33,8 @@ import ()func TestWidgetConfig(t *testing.T) {+ now := time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC)+ past, future := now.Add(-time.Hour), now.Add(time.Hour)active := func(mut func(*models.Form)) *models.Form {f := &models.Form{Status: models.FormStatusActive, PublicKey: "k"}if mut != nil {@@ -39,6 +42,20 @@ func TestWidgetConfig(t *testing.T) {}return f}+ // request builds a request from origin to Posta at posta.test; an origin+ // of "self-get" is a same-origin GET, which carries no Origin header.+ request := func(origin string) *http.Request {+ r := httptest.NewRequest(http.MethodGet, "https://posta.test/api/v1/f/k/config", nil)+ switch origin {+ case "self-get":+ r.Header.Set("Sec-Fetch-Site", "same-origin")+ case "":+ default:+ r.Header.Set("Origin", origin)+ }+ return r+ }+ open := WidgetConfig{Enabled: true, HoneypotField: "_gotcha"}cases := []struct {name stringform *models.Form@@ -46,17 +63,28 @@ func TestWidgetConfig(t *testing.T) {want WidgetConfig}{{"unknown key", nil, "https://site.test", WidgetConfig{Reason: "unavailable"}},- {"paused", active(func(f *models.Form) { f.Status = models.FormStatusPaused }), "https://site.test", WidgetConfig{Reason: "unavailable"}},{"archived", active(func(f *models.Form) { f.Status = models.FormStatusArchived }), "https://site.test", WidgetConfig{Reason: "unavailable"}},- {"open allowlist", active(nil), "https://site.test", WidgetConfig{Enabled: true, HoneypotField: "_gotcha"}},- {"listed origin", active(func(f *models.Form) { f.AllowedOrigins = []string{"https://site.test"} }), "https://site.test", WidgetConfig{Enabled: true, HoneypotField: "_gotcha"}},+ {"paused is closed", active(func(f *models.Form) { f.Status = models.FormStatusPaused }), "https://site.test", WidgetConfig{Reason: "closed", ClosedMessage: defaultClosedMessage}},+ {"past close_at", active(func(f *models.Form) { f.CloseAt = &past; f.ClosedMessage = "See you next year" }), "https://site.test", WidgetConfig{Reason: "closed", ClosedMessage: "See you next year"}},+ {"future close_at", active(func(f *models.Form) { f.CloseAt = &future }), "https://site.test", open},+ {"response limit reached", active(func(f *models.Form) { f.MaxResponses = 10; f.MessageCount = 12; f.SpamCount = 2 }), "https://site.test", WidgetConfig{Reason: "closed", ClosedMessage: defaultClosedMessage}},+ {"spam does not count", active(func(f *models.Form) { f.MaxResponses = 10; f.MessageCount = 12; f.SpamCount = 3 }), "https://site.test", open},+ {"open allowlist", active(nil), "https://site.test", open},+ {"listed origin", active(func(f *models.Form) { f.AllowedOrigins = []string{"https://site.test"} }), "https://site.test", open},{"unlisted origin", active(func(f *models.Form) { f.AllowedOrigins = []string{"https://other.test"} }), "https://site.test", WidgetConfig{Reason: "origin_not_allowed"}},{"strict without origin", active(func(f *models.Form) { f.StrictOrigin = true }), "", WidgetConfig{Reason: "origin_not_allowed"}},+ {"hosted page post", active(func(f *models.Form) { f.AllowedOrigins = []string{"https://other.test"}; f.StrictOrigin = true }), "https://posta.test", open},+ {"hosted page get", active(func(f *models.Form) { f.AllowedOrigins = []string{"https://other.test"}; f.StrictOrigin = true }), "self-get", open},{"custom honeypot and nonce", active(func(f *models.Form) { f.HoneypotField = "website"; f.RequireNonce = true; f.MinFillSeconds = 3 }), "https://site.test", WidgetConfig{Enabled: true, HoneypotField: "website", RequireNonce: true, MinFillSeconds: 3}},- {"fill time only with a nonce", active(func(f *models.Form) { f.MinFillSeconds = 3 }), "https://site.test", WidgetConfig{Enabled: true, HoneypotField: "_gotcha"}},+ {"fill time only with a nonce", active(func(f *models.Form) { f.MinFillSeconds = 3 }), "https://site.test", open},+ {"responses and appearance", active(func(f *models.Form) {+ f.ConfirmationMessage, f.AllowAnotherResponse = "Thanks!", true+ f.Appearance = models.FormAppearance{Accent: "#0f766e", Theme: "dark"}+ }), "https://site.test", WidgetConfig{Enabled: true, HoneypotField: "_gotcha", ConfirmationMessage: "Thanks!", AllowAnotherResponse: true, Appearance: &models.FormAppearance{Accent: "#0f766e", Theme: "dark"}}},}for _, tc := range cases {- if got := widgetConfig(tc.form, tc.origin); !reflect.DeepEqual(got, tc.want) {+ originOK := tc.form != nil && originAllowed(request(tc.origin), tc.form)+ if got := widgetConfig(tc.form, originOK, now); !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.goindex 536cad7..2cd48da 100644--- a/internal/models/form.go+++ b/internal/models/form.go@@ -72,6 +72,15 @@ type Form struct {UnknownFields UnknownFieldsPolicy `json:"unknown_fields" gorm:"type:varchar(8);default:'keep';not null"`ErrorRedirectURL string `json:"error_redirect_url"`+ // Responses: what visitors see after submitting, and when the form stops+ // accepting submissions. A paused form is closed too.+ ConfirmationMessage string `json:"confirmation_message"`+ ClosedMessage string `json:"closed_message"`+ CloseAt *time.Time `json:"close_at,omitempty"`+ MaxResponses int `json:"max_responses" gorm:"default:0;not null"`+ AllowAnotherResponse bool `json:"allow_another_response" gorm:"default:false;not null"`+ Appearance FormAppearance `json:"appearance" gorm:"type:jsonb"`+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"`@@ -104,6 +113,19 @@ type Form struct {func (f *Form) IsActive() bool { return f.Status == FormStatusActive }+// Closed reports whether the form has stopped accepting submissions: it is+// paused, its close time has passed, or it has reached its response limit.+// Spam does not count towards the limit.+func (f *Form) Closed(now time.Time) bool {+ if f.Status == FormStatusPaused {+ return true+ }+ if f.CloseAt != nil && !now.Before(*f.CloseAt) {+ return true+ }+ return f.MaxResponses > 0 && f.MessageCount-f.SpamCount >= int64(f.MaxResponses)+}+// HasSchema reports whether submissions are validated against Fields.func (f *Form) HasSchema() bool { return f != nil && len(f.Fields.Active()) > 0 }diff --git a/internal/models/form_field.go b/internal/models/form_field.goindex 0dd63b9..c35f107 100644--- a/internal/models/form_field.go+++ b/internal/models/form_field.go@@ -162,6 +162,30 @@ func (d *SubmissionData) Scan(value any) error {return json.Unmarshal(raw, d)}+// FormAppearance is a form's saved look, used by its hosted page and as the+// widget's default. Attributes on an embed take precedence.+type FormAppearance struct {+ Accent string `json:"accent,omitempty"` // #RRGGBB+ Theme string `json:"theme,omitempty"` // light, dark or auto+ HeaderImageURL string `json:"header_image_url,omitempty"` // https only+}++func (a FormAppearance) Value() (driver.Value, error) {+ if a == (FormAppearance{}) {+ return nil, nil+ }+ return json.Marshal(a)+}++func (a *FormAppearance) Scan(value any) error {+ raw, err := jsonBytes(value)+ if err != nil || raw == nil {+ *a = FormAppearance{}+ return err+ }+ return json.Unmarshal(raw, a)+}+func jsonBytes(value any) ([]byte, error) {switch v := value.(type) {case nil:diff --git a/internal/routes/message_routes.go b/internal/routes/message_routes.goindex 0755228..eee770c 100644--- a/internal/routes/message_routes.go+++ b/internal/routes/message_routes.go@@ -61,6 +61,12 @@ func (r *Router) formIngestRoutes() []okapi.RouteDefinition {okapi.DocPathParam("key", "string", "Form public key"),},},+ {+ Method: http.MethodGet,+ Path: "/f/{key}",+ Handler: r.h.formIngest.HostedPage,+ Options: []okapi.RouteOption{okapi.DocHide()},+ },{Method: http.MethodGet,Path: "/posta-form.js",diff --git a/internal/routes/routes.go b/internal/routes/routes.goindex 483ad1a..3cabe82 100644--- a/internal/routes/routes.go+++ b/internal/routes/routes.go@@ -477,6 +477,7 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *cinbound.NewIPRateLimiter(cfg.MessagesIPRateLimit, time.Duration(cfg.MessagesIPRateWindow)*time.Second),cfg.MessagesMaxAttachSize,)+ r.h.formIngest.SetHostedPages(settingsProvider, cfg.AdminEmail)if blobStore != nil {r.h.message.SetBlobStore(blobStore)r.h.formIngest.SetBlobStore(blobStore)diff --git a/internal/services/messages/service.go b/internal/services/messages/service.goindex b3e179b..9dceaf3 100644--- a/internal/services/messages/service.go+++ b/internal/services/messages/service.go@@ -322,6 +322,11 @@ func (s *Service) Submit(ctx context.Context, req SubmitRequest) (*SubmitResult,}_ = s.formRepo.RecordSubmission(form.ID, msg.IsSpam(), msg.CreatedAt)+ // The response limit reads the counts from the cached form; drop it so+ // the next request sees this submission instead of waiting out the TTL.+ if form.MaxResponses > 0 && !msg.IsSpam() {+ s.InvalidateFormKey(form.PublicKey)+ }if len(verdict.FilterHits) > 0 {_ = s.filterRepo.RecordHits(verdict.FilterHits, time.Now())}diff --git a/internal/services/seeder/settings.go b/internal/services/seeder/settings.goindex 520081c..cae43f3 100644--- a/internal/services/seeder/settings.go+++ b/internal/services/seeder/settings.go@@ -57,6 +57,8 @@ func SeedDefaultSettings(repo *repositories.SettingRepository) {{Key: "email_content_visibility", Value: models.SettingFalse, Type: models.SettingTypeBool},{Key: "custom_headers_enabled", Value: models.SettingFalse, Type: models.SettingTypeBool},{Key: "password_reset_enabled", Value: models.SettingFalse, Type: models.SettingTypeBool},+ {Key: "hosted_forms_enabled", Value: models.SettingTrue, Type: models.SettingTypeBool},+ {Key: "abuse_report_email", Value: "", Type: models.SettingTypeString},}for i := range defaults {diff --git a/internal/services/settings/provider.go b/internal/services/settings/provider.goindex 2a3e234..86ad5f6 100644--- a/internal/services/settings/provider.go+++ b/internal/services/settings/provider.go@@ -121,7 +121,14 @@ func (p *Provider) RequireEmailVerification() bool {func (p *Provider) RequireDomainVerification() bool {return p.GetBool("require_domain_verification", true)}-func (p *Provider) TwoFactorRequired() bool { return p.GetBool("two_factor_required", false) }+func (p *Provider) TwoFactorRequired() bool { return p.GetBool("two_factor_required", false) }++// HostedFormsEnabled reports whether forms get a public share page at /f/{key}.+func (p *Provider) HostedFormsEnabled() bool { return p.GetBool("hosted_forms_enabled", true) }++// AbuseReportEmail is the contact behind the "Report abuse" link on hosted+// form pages. Empty falls back to the admin email.+func (p *Provider) AbuseReportEmail() string { return p.GetString("abuse_report_email", "") }func (p *Provider) DefaultRateLimitHourly() int { return p.GetInt("default_rate_limit_hourly", 100) }func (p *Provider) DefaultRateLimitDaily() int { return p.GetInt("default_rate_limit_daily", 1000) }func (p *Provider) MaxBatchSize() int { return p.GetInt("max_batch_size", 100) }diff --git a/internal/web/widget/posta-form.js b/internal/web/widget/posta-form.jsindex 82f9707..dc84509 100644--- a/internal/web/widget/posta-form.js+++ b/internal/web/widget/posta-form.js@@ -24,6 +24,7 @@required: "This field is required.",choose: "Choose…",button: "Send message",+ another: "Submit another response",sending: "Sending…",success: "Thanks — your message has been received.",loading: "Loading…",@@ -43,6 +44,7 @@required: "Ce champ est obligatoire.",choose: "Choisir…",button: "Envoyer",+ another: "Envoyer une autre réponse",sending: "Envoi…",success: "Merci, votre message a bien été reçu.",loading: "Chargement…",@@ -118,6 +120,7 @@".pf .st:empty{display:none}" +".pf .st.err{color:var(--err)}" +".pf .done{margin:4px 0;color:var(--ok);font-weight:600}" ++ ".pf button.again{margin-top:10px;background:none;color:var(--a);padding:0;min-height:0;text-decoration:underline}" +".pf .brand{display:flex;justify-content:flex-end;margin-top:16px;padding-top:10px;border-top:1px solid var(--bd)}" +".pf .brand a{display:inline-flex;align-items:center;gap:5px;font-size:12px;color:var(--mut);text-decoration:none}" +".pf .brand a:hover{color:var(--fg)}" +@@ -174,6 +177,15 @@return node;}+ function safeList(raw) {+ try {+ var v = JSON.parse(raw);+ return Array.isArray(v) ? v.map(String) : [];+ } catch (e) {+ return [];+ }+ }+function emit(el, name, detail) {el.dispatchEvent(new CustomEvent("posta:" + name, { bubbles: true, composed: true, detail: detail }));}@@ -204,10 +216,17 @@style.textContent = STYLE;root.appendChild(style);- var theme = el.getAttribute("data-theme");- var wrap = h("div", { class: "pf", "data-theme": theme === "dark" || theme === "auto" ? theme : "light", part: "form" });- var accent = el.getAttribute("data-accent");- if (accent && window.CSS && CSS.supports && CSS.supports("color", accent)) wrap.style.setProperty("--pf-accent", accent);+ var wrap = h("div", { class: "pf", part: "form" });+ // The form's saved appearance is the default; the embed's own attributes+ // win, so one form can look different on different pages.+ function applyLook(appearance) {+ var a = appearance || {};+ var theme = el.getAttribute("data-theme") || a.theme;+ wrap.setAttribute("data-theme", theme === "dark" || theme === "auto" ? theme : "light");+ var accent = el.getAttribute("data-accent") || a.accent;+ if (accent && window.CSS && CSS.supports && CSS.supports("color", accent)) wrap.style.setProperty("--pf-accent", accent);+ }+ applyLook(null);root.appendChild(wrap);var body = h("div");@@ -223,35 +242,40 @@brand.appendChild(link);wrap.appendChild(brand);- var loading = h("p", { class: "st" }, t.loading);- body.appendChild(loading);-- function showNotice(text) {+ function showNotice(text, isError) {body.textContent = "";- body.appendChild(h("p", { class: "st err", role: "status" }, text));+ body.appendChild(h("p", { class: isError === false ? "st" : "st err", role: "status" }, text));}- getJSON(base + "/" + encodeURIComponent(key) + "/config").then(- function (res) {- var cfg = res.body && res.body.data;- if (!cfg || !cfg.enabled) {- var reason = (cfg && cfg.reason) || "unavailable";- if (reason === "origin_not_allowed") {- console.warn("[posta] " + location.origin + " is not in this form's allowed origins. Add it on the form's Setup tab in Posta.");- showNotice(t.originDenied);- } else {- showNotice(t.unavailable);+ function load() {+ body.textContent = "";+ body.appendChild(h("p", { class: "st" }, t.loading));+ getJSON(base + "/" + encodeURIComponent(key) + "/config").then(+ function (res) {+ var cfg = res.body && res.body.data;+ if (!cfg || !cfg.enabled) {+ var reason = (cfg && cfg.reason) || "unavailable";+ if (reason === "origin_not_allowed") {+ console.warn("[posta] " + location.origin + " is not in this form's allowed origins. Add it on the form's Setup tab in Posta.");+ showNotice(t.originDenied);+ } else if (reason === "closed") {+ showNotice(cfg.closed_message || t.unavailable, false);+ } else {+ showNotice(t.unavailable);+ }+ emit(el, "error", { key: key, status: res.status, code: reason, message: reason });+ return;}- emit(el, "error", { key: key, status: res.status, code: reason, message: reason });- return;+ applyLook(cfg.appearance);+ render(cfg, cfg.fields && cfg.fields.length ? cfg.fields : fieldList(el, t));+ },+ function () {+ showNotice(t.network);+ emit(el, "error", { key: key, status: 0, code: "network", message: t.network });}- render(cfg, cfg.fields && cfg.fields.length ? cfg.fields : fieldList(el, t));- },- function () {- showNotice(t.network);- emit(el, "error", { key: key, status: 0, code: "network", message: t.network });- }- );+ );+ }+ load();// buildField renders one field and returns how to read it, focus it and// show an error on it.@@ -260,6 +284,9 @@var helpId = fid + "-help";var type = f.type || "text";var preset = el.getAttribute("data-value-" + f.key) || "";+ // A multi-value preset is a JSON array (from a hosted page link) or a+ // comma-separated list (written by hand).+ var presets = preset.charAt(0) === "[" ? safeList(preset) : preset ? preset.split(",").map(function (v) { return v.trim(); }) : [];if (type === "hidden") {var hidden = h("input", { type: "hidden", name: f.key, value: preset });@@ -293,6 +320,7 @@} 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 });+ focusEl.checked = /^(true|1|on|yes)$/i.test(preset);tick.appendChild(focusEl);tick.appendChild(h("span", null, f.label || f.key));if (help) row.insertBefore(tick, help);@@ -303,12 +331,16 @@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)); });+ focusEl.value = preset;+ if (focusEl.value !== preset) focusEl.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)); });+ (f.options || []).forEach(function (o) {+ focusEl.appendChild(h("option", { value: o.value, selected: presets.indexOf(o.value) >= 0 }, 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; });@@ -330,6 +362,7 @@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 });+ box.checked = multi ? presets.indexOf(ch.value) >= 0 : ch.value === preset;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));@@ -339,11 +372,13 @@});if (type === "scale" && f.max_label) list.appendChild(h("span", { class: "end" }, f.max_label));if (type === "rating") {- list.addEventListener("change", function () {+ var paint = 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); });- });+ };+ list.addEventListener("change", paint);+ paint();}row.appendChild(list);focusEl = boxes[0];@@ -512,7 +547,13 @@var data = (res.body && res.body.data) || {};if (res.status >= 200 && res.status < 300) {body.textContent = "";- body.appendChild(h("p", { class: "done", role: "status" }, el.getAttribute("data-success") || data.message || t.success));+ var done = el.getAttribute("data-success") || cfg.confirmation_message || data.message || t.success;+ body.appendChild(h("p", { class: "done", role: "status" }, done));+ if (cfg.allow_another_response) {+ var again = h("button", { type: "button", class: "again" }, t.another);+ again.addEventListener("click", load);+ body.appendChild(again);+ }emit(el, "success", { key: key, id: data.id || null });return;}diff --git a/web/src/api/messages.ts b/web/src/api/messages.tsindex 2458387..68e27ad 100644--- a/web/src/api/messages.ts+++ b/web/src/api/messages.ts@@ -3,6 +3,8 @@ import type {ApiResponse,PaginatedResponse,Form,+ FormAppearance,+ FormField,FormSnippet,Message,MessageFilterRule,@@ -42,6 +44,15 @@ export interface FormPayload {reply_from?: stringreply_from_name?: stringretention_days?: number+ fields?: FormField[]+ unknown_fields?: 'keep' | 'drop' | 'reject'+ error_redirect_url?: string+ confirmation_message?: string+ closed_message?: string+ close_at?: string+ max_responses?: number+ allow_another_response?: boolean+ appearance?: FormAppearance}export interface MessageListParams {diff --git a/web/src/api/types.ts b/web/src/api/types.tsindex 7f63b29..460556f 100644--- a/web/src/api/types.ts+++ b/web/src/api/types.ts@@ -1267,6 +1267,16 @@ export interface Form {reply_from: stringreply_from_name: stringretention_days: number+ fields?: FormField[] | null+ schema_version: number+ unknown_fields: 'keep' | 'drop' | 'reject'+ error_redirect_url: string+ confirmation_message: string+ closed_message: string+ close_at?: string | null+ max_responses: number+ allow_another_response: boolean+ appearance?: FormAppearance | nullmessage_count: numberspam_count: numberlast_message_at?: string | null@@ -1274,6 +1284,38 @@ export interface Form {updated_at?: string | null}+export interface FormFieldOption {+ value: string+ label?: string+}++export interface FormField {+ key: string+ label: string+ type: string+ required?: boolean+ role?: string+ pii?: boolean+ min_len?: number+ max_len?: number+ min?: number+ max?: number+ pattern?: string+ options?: FormFieldOption[]+ display?: string+ min_label?: string+ max_label?: string+ placeholder?: string+ help?: string+ archived?: boolean+}++export interface FormAppearance {+ accent?: string+ theme?: '' | 'light' | 'dark' | 'auto'+ header_image_url?: string+}+export interface MessageField {key: stringvalue: string@@ -1359,4 +1401,5 @@ export interface FormSnippet {html: stringfetch: stringwidget: string+ share_url: string}diff --git a/web/src/views/admin/Settings.vue b/web/src/views/admin/Settings.vueindex 3b28dfe..f3219be 100644--- a/web/src/views/admin/Settings.vue+++ b/web/src/views/admin/Settings.vue@@ -33,6 +33,8 @@ const settingMeta: Record<string, { label: string; description: string; categoryaudit_log_retention_days: { label: 'Audit Log Retention (days)', description: 'How long to keep audit/event logs.', category: 'Retention' },webhook_delivery_retention_days: { label: 'Webhook Delivery Retention (days)', description: 'How long to keep webhook delivery logs.', category: 'Retention' },email_content_visibility: { label: 'Email Content Visibility', description: 'When enabled, email body content (HTML/Text) is visible in the dashboard. When disabled, content is redacted for privacy.', category: 'Privacy' },+ hosted_forms_enabled: { label: 'Hosted Form Pages', description: 'Give each form a public share page at /f/{key}. Turn off to stop serving them, for example if forms are abused for phishing.', category: 'Security' },+ abuse_report_email: { label: 'Abuse Report Email', description: 'Where the "Report abuse" link on hosted form pages sends reports. Empty uses the admin email.', category: 'Security' },custom_headers_enabled: { label: 'Custom Email Headers', description: 'Allow users to include custom headers when sending emails. When disabled, custom headers are silently ignored.', category: 'Security' },}diff --git a/web/src/views/forms/FormDetail.vue b/web/src/views/forms/FormDetail.vueindex 336a0f7..32c42f0 100644--- a/web/src/views/forms/FormDetail.vue+++ b/web/src/views/forms/FormDetail.vue@@ -16,9 +16,33 @@ const saving = ref(false);const form = ref<Form | null>(null);const snippet = ref<FormSnippet | null>(null);const loadFailed = ref(false);-const tab = ref<"setup" | "spam" | "notifications" | "embed">("setup");+const tab = ref<"setup" | "responses" | "spam" | "notifications" | "embed">("setup");const originsText = ref("");+// close_at is edited in the browser's local time and stored as UTC.+const closeAtLocal = ref("");+const appearance = ref({ accent: "", theme: "", header_image_url: "" });++function toLocalInput(iso?: string | null) {+ if (!iso) return "";+ const d = new Date(iso);+ const pad = (n: number) => String(n).padStart(2, "0");+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;+}++function setAppearanceAccent(e: Event) {+ appearance.value.accent = (e.target as HTMLInputElement).value;+}++function syncResponseFields(f: Form) {+ closeAtLocal.value = toLocalInput(f.close_at);+ appearance.value = {+ accent: f.appearance?.accent || "",+ // "light" is the default, which the select shows as its empty option.+ theme: f.appearance?.theme === "light" ? "" : f.appearance?.theme || "",+ header_image_url: f.appearance?.header_image_url || "",+ };+}const notifyText = ref("");async function load() {@@ -28,6 +52,7 @@ async function load() {form.value = formRes.data.data;snippet.value = snippetRes.data.data;originsText.value = (formRes.data.data.allowed_origins || []).join(", ");+ syncResponseFields(formRes.data.data);notifyText.value = (formRes.data.data.notify_emails || []).join(", ");} catch (e: any) {loadFailed.value = true;@@ -70,8 +95,19 @@ async function save() {reply_from: form.value.reply_from,reply_from_name: form.value.reply_from_name,retention_days: form.value.retention_days,+ confirmation_message: form.value.confirmation_message,+ closed_message: form.value.closed_message,+ close_at: closeAtLocal.value ? new Date(closeAtLocal.value).toISOString() : "",+ max_responses: Number(form.value.max_responses) || 0,+ allow_another_response: form.value.allow_another_response,+ appearance: {+ accent: appearance.value.accent,+ theme: appearance.value.theme as "" | "light" | "dark" | "auto",+ header_image_url: appearance.value.header_image_url.trim(),+ },});form.value = res.data.data;+ syncResponseFields(res.data.data);notify.success("Form saved.");} catch (e: any) {notify.error(apiMessage(e, "Failed to save form"));@@ -195,7 +231,7 @@ onMounted(load);<div class="card" style="margin-bottom: 20px"><div class="card-body" style="display: flex; gap: 8px; flex-wrap: wrap"><button- v-for="t in (['setup', 'spam', 'notifications', 'embed'] as const)"+ v-for="t in (['setup', 'responses', 'spam', 'notifications', 'embed'] as const)":key="t"class="btn":class="tab === t ? 'btn-primary' : 'btn-secondary'"@@ -315,6 +351,70 @@ onMounted(load);</div></div>+ <div v-show="tab === 'responses'" class="card" style="margin-bottom: 20px">+ <div class="card-header"><h2>Responses</h2></div>+ <div class="card-body">+ <div class="form-group">+ <label class="form-label">Confirmation message</label>+ <textarea v-model="form.confirmation_message" class="form-input" rows="2" maxlength="500" placeholder="Thanks — your message has been received."></textarea>+ <small class="muted">Shown after someone submits the form.</small>+ </div>+ <div class="form-group">+ <label class="checkbox-label">+ <input v-model="form.allow_another_response" type="checkbox" />+ Show a link to submit another response+ </label>+ </div>+ <div class="form-group">+ <label class="form-label">Stop accepting responses after</label>+ <input v-model="closeAtLocal" class="form-input" type="datetime-local" />+ <small class="muted">Your local time. Leave empty to keep the form open.</small>+ </div>+ <div class="form-group">+ <label class="form-label">Response limit</label>+ <input v-model.number="form.max_responses" class="form-input" type="number" min="0" />+ <small class="muted">0 means no limit. Spam does not count.</small>+ </div>+ <div class="form-group">+ <label class="form-label">Closed message</label>+ <textarea v-model="form.closed_message" class="form-input" rows="2" maxlength="500" placeholder="This form is no longer accepting responses."></textarea>+ <small class="muted">+ Shown instead of the form once it closes, or while its status is Paused.+ </small>+ </div>++ <h3 style="margin: 24px 0 12px">Appearance</h3>+ <p class="muted" style="margin: 0 0 12px">+ Used by the form's share page and as the widget's default. Attributes on an embed take precedence.+ </p>+ <div class="form-group">+ <label class="form-label">Accent colour</label>+ <div style="display: flex; gap: 8px; align-items: center">+ <input+ type="color"+ :value="appearance.accent || '#9333ea'"+ aria-label="Accent colour"+ @input="setAppearanceAccent"+ />+ <button v-if="appearance.accent" class="btn btn-secondary" @click="appearance.accent = ''">Reset</button>+ </div>+ </div>+ <div class="form-group">+ <label class="form-label">Theme</label>+ <select v-model="appearance.theme" class="form-select">+ <option value="">Light (default)</option>+ <option value="dark">Dark</option>+ <option value="auto">Follow the visitor's system</option>+ </select>+ </div>+ <div class="form-group">+ <label class="form-label">Header image</label>+ <input v-model="appearance.header_image_url" class="form-input" placeholder="https://example.com/banner.png" />+ <small class="muted">An https image shown at the top of the share page.</small>+ </div>+ </div>+ </div>+<div v-show="tab === 'notifications'" class="card" style="margin-bottom: 20px"><div class="card-header"><h2>Notifications</h2></div><div class="card-body">@@ -353,6 +453,23 @@ onMounted(load);<button class="btn btn-secondary" @click="rotateKey">Rotate key</button></div><div class="card-body">+ <h3 style="margin: 0 0 4px">Share link</h3>+ <p class="muted" style="margin: 0 0 12px">+ A page Posta hosts for this form. Send it to people, or post it anywhere; no website needed.+ </p>+ <div class="form-group">+ <div style="display: flex; gap: 8px">+ <input class="form-input" :value="snippet?.share_url || ''" readonly />+ <button class="btn btn-secondary" @click="copy(snippet?.share_url || '')">Copy</button>+ <a class="btn btn-secondary" :href="snippet?.share_url" target="_blank" rel="noopener">Open</a>+ </div>+ <small class="muted">+ Add <code>?key=value</code> to prefill a question, for example <code>?plan=pro</code>.+ Questions marked as personal data are never prefilled.+ </small>+ </div>++ <hr style="margin: 24px 0; border: 0; border-top: 1px solid var(--border-primary)" /><h3 style="margin: 0 0 4px">Website widget <span class="badge badge-success">Recommended</span></h3><p class="muted" style="margin: 0 0 16px">Paste two lines into any page. Posta renders a styled form, handles spam protection,