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 an embeddable website form widget
Jonas Kanindad2ddb1419632
diff --git a/docs/docs/messages/embedding.md b/docs/docs/messages/embedding.mdindex 5db6aa4..87ea01e 100644--- a/docs/docs/messages/embedding.md+++ b/docs/docs/messages/embedding.md@@ -6,7 +6,89 @@ description: Put a Posta form on your website with plain HTML or JavaScript# Embedding a Form-The **Embed** tab of a form gives you paste-ready code. Both variants below post to the same endpoint.+The **Embed** tab of a form gives you paste-ready code. The website widget is the quickest option; the HTML and JavaScript variants further down post to the same endpoint if you want full control over the markup.++## Website widget++Paste two lines where the form should appear:++```html+<div data-posta-form="YOUR_PUBLIC_KEY"></div>+<script src="https://posta.example.com/widget/v1/posta-form.js" async></script>+```++The script renders a styled, accessible contact form, fills in the honeypot and nonce for you, and shows the result in place. The **Embed** tab has a builder that writes these two lines with your options filled in.++The widget reads the form's settings when the page loads, so changing the honeypot field, turning the nonce on, or pausing the form takes effect without editing your site. A paused form shows *"This form is not accepting messages right now."* instead of the fields.++Every widget carries a small **Powered by Posta** link under the button.++### Options++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-title` | none | Heading above the form |+| `data-description` | none | One line under the heading |+| `data-button` | `Send message` | |+| `data-success` | `Thanks — your message has been received.` | Shown after a successful submit |+| `data-label-<field>` | English or French default | For example `data-label-message="Your question"` |+| `data-theme` | `light` | `light`, `dark`, or `auto` to follow the visitor's system setting |+| `data-accent` | `#9333EA` | Any CSS colour |+| `data-lang` | the visitor's browser language | `en` or `fr` |++### Matching your site's style++The form is drawn inside a Shadow DOM, so your site's CSS cannot break it. It inherits your page's font, and these custom properties pass through:++```css+[data-posta-form] {+ --posta-form-accent: #0f766e;+ --posta-form-radius: 4px;+ --posta-form-font: inherit;+ --posta-form-max-width: 560px;+}+```++### Allowed origins++If the form lists **Allowed origins**, the widget only works on those sites. Anywhere else, visitors see *"This form is not available on this website."* and the browser console tells you which origin to add on the form's **Setup** tab.++### Single-page apps++The script mounts every `[data-posta-form]` element present when it loads. For elements added later, call:++```js+PostaForms.mount(document.querySelector('#contact'))+```++### Events++The placeholder element dispatches events you can use for analytics or a redirect:++| Event | `event.detail` |+|---|---|+| `posta:ready` | `{ key }` |+| `posta:submit` | `{ key }` |+| `posta:success` | `{ key, id }` |+| `posta:error` | `{ key, status, code, message }` |++```js+document.addEventListener('posta:success', () => {+ window.location.href = '/thanks'+})+```++### Content Security Policy++If your site sends a CSP header, allow your Posta host for scripts and requests:++```+script-src https://posta.example.com;+connect-src https://posta.example.com;+```## Plain HTML, no JavaScriptdiff --git a/internal/handlers/form_handler.go b/internal/handlers/form_handler.goindex af227a0..79fe856 100644--- a/internal/handlers/form_handler.go+++ b/internal/handlers/form_handler.go@@ -22,6 +22,7 @@ package handlersimport ("crypto/rand""fmt"+ "html""math/big""net/mail""net/url"@@ -139,6 +140,7 @@ type FormSnippetResponse struct {PublicKey string `json:"public_key"`HTML string `json:"html"`Fetch string `json:"fetch"`+ Widget string `json:"widget" doc:"Website widget embed: a placeholder element and the script tag"`}func (h *FormHandler) Create(c *okapi.Context, req *CreateFormRequest) error {@@ -435,6 +437,7 @@ func (h *FormHandler) Snippet(c *okapi.Context, req *FormIDRequest) error {PublicKey: form.PublicKey,HTML: buildHTMLSnippet(endpoint, form),Fetch: buildFetchSnippet(endpoint),+ Widget: buildWidgetSnippet(h.apiBaseURL, form),})}@@ -603,6 +606,11 @@ func buildHTMLSnippet(endpoint string, form *models.Form) string {</form>`, endpoint, form.Honeypot())}+func buildWidgetSnippet(apiBaseURL string, form *models.Form) string {+ return fmt.Sprintf(`<div data-posta-form="%s"></div>+<script src="%s/widget/v1/posta-form.js" async></script>`, html.EscapeString(form.PublicKey), html.EscapeString(apiBaseURL))+}+func buildFetchSnippet(endpoint string) string {return fmt.Sprintf(`await fetch(%q, {method: 'POST',diff --git a/internal/handlers/form_ingest_handler.go b/internal/handlers/form_ingest_handler.goindex 4129c09..42fe3e2 100644--- a/internal/handlers/form_ingest_handler.go+++ b/internal/handlers/form_ingest_handler.go@@ -31,11 +31,13 @@ import ("net/url""strconv""strings"+ "time""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/storage/blob"+ "github.com/goposta/posta/internal/web/widget""github.com/jkaninda/logger""github.com/jkaninda/okapi")@@ -81,6 +83,89 @@ func (h *FormIngestHandler) Nonce(c *okapi.Context) error {return ok(c, nonce)}+// Widget config reasons. "unavailable" covers unknown, paused and archived+// forms alike, so the endpoint does not reveal which keys exist.+const (+ widgetReasonUnavailable = "unavailable"+ widgetReasonOriginNotAllowed = "origin_not_allowed"+)++// WidgetConfig is what the website widget needs before it renders a form.+type WidgetConfig struct {+ Enabled bool `json:"enabled"`+ Reason string `json:"reason,omitempty" doc:"Why the form cannot be used here: unavailable or origin_not_allowed"`+ HoneypotField string `json:"honeypot_field,omitempty"`+ 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"`+}++// 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() {+ return WidgetConfig{Reason: widgetReasonUnavailable}+ }+ allowlist, strict := form.OriginPolicy()+ if !messages.OriginAllowed(allowlist, strict, origin) {+ return WidgetConfig{Reason: widgetReasonOriginNotAllowed}+ }+ cfg := WidgetConfig{+ Enabled: true,+ HoneypotField: form.Honeypot(),+ RequireNonce: form.RequireNonce,+ }+ if form.RequireNonce {+ cfg.MinFillSeconds = form.MinFillSeconds+ }+ return cfg+}++// WidgetConfig answers 200 in every case so the widget can always read why a+// form is not usable.+func (h *FormIngestHandler) WidgetConfig(c *okapi.Context) error {+ key := c.Param("key")+ origin := c.Request().Header.Get("Origin")+ c.ResponseWriter().Header().Set("Cache-Control", "no-store")++ form, err := h.svc.FindFormByKey(key)+ if err != nil {+ form = nil+ }+ cfg := widgetConfig(form, origin)+ if !cfg.Enabled {+ // A disabled answer carries no form data, so any origin may read it.+ if origin != "" {+ w := c.ResponseWriter()+ w.Header().Set("Access-Control-Allow-Origin", origin)+ w.Header().Set("Vary", "Origin")+ }+ return ok(c, cfg)+ }+ h.applyCORS(c, form)++ if cfg.RequireNonce {+ nonce, err := h.svc.IssueNonce(c.Request().Context(), key)+ if err != nil {+ return c.AbortInternalServerError("failed to issue nonce")+ }+ cfg.Nonce = nonce+ }+ return ok(c, cfg)+}++// FormScript serves the website form widget.+func (h *FormIngestHandler) FormScript(c *okapi.Context) error {+ w := c.ResponseWriter()+ w.Header().Set("Content-Type", "text/javascript; charset=utf-8")+ w.Header().Set("Cache-Control", "public, max-age=3600")+ w.Header().Set("ETag", widget.FormScriptETag)+ w.Header().Set("X-Content-Type-Options", "nosniff")+ w.Header().Set("Cross-Origin-Resource-Policy", "cross-origin")+ http.ServeContent(w, c.Request(), "posta-form.js", time.Time{}, bytes.NewReader(widget.FormScript))+ return nil+}+func (h *FormIngestHandler) Submit(c *okapi.Context) error {req := c.Request()key := c.Param("key")diff --git a/internal/handlers/form_widget_test.go b/internal/handlers/form_widget_test.gonew file mode 100644index 0000000..33c6c28--- /dev/null+++ b/internal/handlers/form_widget_test.go@@ -0,0 +1,110 @@+// 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 (+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/goposta/posta/internal/models"+ "github.com/goposta/posta/internal/web/widget"+ "github.com/jkaninda/okapi"+)++func TestWidgetConfig(t *testing.T) {+ active := func(mut func(*models.Form)) *models.Form {+ f := &models.Form{Status: models.FormStatusActive, PublicKey: "k"}+ if mut != nil {+ mut(f)+ }+ return f+ }+ cases := []struct {+ name string+ form *models.Form+ origin string+ 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"}},+ {"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"}},+ {"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"}},+ }+ for _, tc := range cases {+ if got := widgetConfig(tc.form, tc.origin); got != tc.want {+ t.Errorf("%s: widgetConfig = %+v, want %+v", tc.name, got, tc.want)+ }+ }+}++func TestFormScriptHeaders(t *testing.T) {+ h := NewFormIngestHandler(nil, nil, 0)+ serve := func(req *http.Request) *httptest.ResponseRecorder {+ rec := httptest.NewRecorder()+ if err := h.FormScript(okapi.NewContext(okapi.New(), rec, req)); err != nil {+ t.Fatalf("FormScript: %v", err)+ }+ return rec+ }++ rec := serve(httptest.NewRequest(http.MethodGet, "/widget/v1/posta-form.js", nil))+ if rec.Code != http.StatusOK {+ t.Fatalf("status = %d, want 200", rec.Code)+ }+ for header, want := range map[string]string{+ "Content-Type": "text/javascript; charset=utf-8",+ "X-Content-Type-Options": "nosniff",+ "Cross-Origin-Resource-Policy": "cross-origin",+ "Cache-Control": "public, max-age=3600",+ "ETag": widget.FormScriptETag,+ } {+ if got := rec.Header().Get(header); got != want {+ t.Errorf("%s = %q, want %q", header, got, want)+ }+ }+ if rec.Body.Len() != len(widget.FormScript) {+ t.Fatalf("body is %d bytes, want %d", rec.Body.Len(), len(widget.FormScript))+ }++ req := httptest.NewRequest(http.MethodGet, "/widget/v1/posta-form.js", nil)+ req.Header.Set("If-None-Match", widget.FormScriptETag)+ if rec := serve(req); rec.Code != http.StatusNotModified {+ t.Fatalf("revalidation status = %d, want 304", rec.Code)+ }+}++func TestBuildWidgetSnippet(t *testing.T) {+ got := buildWidgetSnippet("https://posta.example.com", &models.Form{PublicKey: "abc123"})+ for _, want := range []string{+ `<div data-posta-form="abc123"></div>`,+ `<script src="https://posta.example.com/widget/v1/posta-form.js" async></script>`,+ } {+ if !strings.Contains(got, want) {+ t.Errorf("snippet is missing %q:\n%s", want, got)+ }+ }+}diff --git a/internal/routes/message_routes.go b/internal/routes/message_routes.goindex f7b0a65..0755228 100644--- a/internal/routes/message_routes.go+++ b/internal/routes/message_routes.go@@ -49,6 +49,25 @@ func (r *Router) formIngestRoutes() []okapi.RouteDefinition {okapi.DocResponse(429, &dto.ErrorResponseBody{}),},},+ {+ Method: http.MethodGet,+ Path: "/{key}/config",+ Handler: r.h.formIngest.WidgetConfig,+ Group: ingestGroup,+ Summary: "Get the website widget config",+ Description: "What the website form widget needs before rendering: whether the form is usable from the calling origin, its honeypot field, and a nonce when the form requires one. Always answers 200; a form that cannot be used has enabled=false and a reason.",+ Response: &dto.Response[handlers.WidgetConfig]{},+ Options: []okapi.RouteOption{+ okapi.DocPathParam("key", "string", "Form public key"),+ },+ },+ {+ Method: http.MethodGet,+ Path: "/posta-form.js",+ Handler: r.h.formIngest.FormScript,+ Group: r.app.Group("/widget/v1"),+ Options: []okapi.RouteOption{okapi.DocHide()},+ },{Method: http.MethodGet,Path: "/{key}/nonce",diff --git a/internal/routes/message_routes_test.go b/internal/routes/message_routes_test.goindex 06abf36..d12b5da 100644--- a/internal/routes/message_routes_test.go+++ b/internal/routes/message_routes_test.go@@ -22,8 +22,12 @@ package routesimport ("net/http""net/http/httptest"+ "strings""testing"+ "testing/fstest"+ "github.com/goposta/posta/internal/config"+ "github.com/goposta/posta/internal/handlers""github.com/jkaninda/okapi")@@ -91,3 +95,26 @@ func TestFormIngestPostIsNotAPreflightedRequest(t *testing.T) {}}}++// The widget script lives outside /api/v1 and must not fall through to the+// dashboard's SPA fallback, which serves index.html for unknown paths.+func TestFormWidgetScriptIsNotShadowedBySPA(t *testing.T) {+ o := okapi.NewTestServer(t)+ r := &Router{app: o.Okapi, cfg: &config.Config{}, v1: o.Group("/api/v1")}+ r.h.formIngest = handlers.NewFormIngestHandler(nil, nil, 0)+ o.Register(r.formIngestRoutes()...)+ o.WebFS("/", fstest.MapFS{"dist/index.html": {Data: []byte("<!doctype html><title>SPA</title>")}}, okapi.WebConfig{Root: "dist"})++ rec := httptest.NewRecorder()+ o.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/widget/v1/posta-form.js", nil))++ if rec.Code != http.StatusOK {+ t.Fatalf("status = %d, want 200", rec.Code)+ }+ if ct := rec.Header().Get("Content-Type"); !strings.HasPrefix(ct, "text/javascript") {+ t.Fatalf("content type = %q, want text/javascript", ct)+ }+ if !strings.Contains(rec.Body.String(), "PostaForms") {+ t.Fatalf("served the SPA instead of the widget: %.80q", rec.Body.String())+ }+}diff --git a/internal/web/widget/posta-form.js b/internal/web/widget/posta-form.jsnew file mode 100644index 0000000..64c5118--- /dev/null+++ b/internal/web/widget/posta-form.js@@ -0,0 +1,401 @@+/*!+ * Posta form widget — https://goposta.dev+ * SPDX-License-Identifier: AGPL-3.0-or-later+ *+ * <div data-posta-form="PUBLIC_KEY"></div>+ * <script src="https://posta.example.com/widget/v1/posta-form.js" async></script>+ */+(function () {+ "use strict";++ if (window.PostaForms) return;++ var SCRIPT = document.currentScript;+ var BRAND_URL = "https://goposta.dev/?ref=form-widget";++ var STRINGS = {+ en: {+ name: "Name",+ email: "Email",+ phone: "Phone",+ subject: "Subject",+ message: "Message",+ optional: "optional",+ button: "Send message",+ sending: "Sending…",+ success: "Thanks — your message has been received.",+ loading: "Loading…",+ unavailable: "This form is not accepting messages right now.",+ originDenied: "This form is not available on this website.",+ network: "Could not send. Check your connection and try again.",+ error: "Your message could not be sent. Please try again.",+ poweredBy: "Powered by",+ },+ fr: {+ name: "Nom",+ email: "E-mail",+ phone: "Téléphone",+ subject: "Objet",+ message: "Message",+ optional: "facultatif",+ button: "Envoyer",+ sending: "Envoi…",+ success: "Merci, votre message a bien été reçu.",+ loading: "Chargement…",+ unavailable: "Ce formulaire n'accepte pas de messages pour le moment.",+ originDenied: "Ce formulaire n'est pas disponible sur ce site.",+ network: "Envoi impossible. Vérifiez votre connexion et réessayez.",+ error: "Votre message n'a pas pu être envoyé. Veuillez réessayer.",+ poweredBy: "Propulsé par",+ },+ };++ // The fields a form without a schema can show, keyed by the names the+ // server recognises (services/messages/parse.go).+ var BUILTIN_FIELDS = {+ name: { type: "text", autocomplete: "name", required: true },+ email: { type: "email", autocomplete: "email", required: true },+ phone: { type: "tel", autocomplete: "tel", required: false },+ subject: { type: "text", required: false },+ message: { type: "textarea", required: true },+ };+ var DEFAULT_FIELDS = ["name", "email", "message"];++ var MARK_SVG =+ '<svg viewBox="78 96 356 320" width="14" height="13" aria-hidden="true" focusable="false">' ++ '<path fill="currentColor" fill-rule="evenodd" d="M168,96 H344 A20,20 0 0 1 364,116 V272 A20,20 0 0 1 344,292 H168 A20,20 0 0 1 148,272 V116 A20,20 0 0 1 168,96 Z M187,149 H325 A11,11 0 0 1 336,160 V160 A11,11 0 0 1 325,171 H187 A11,11 0 0 1 176,160 V160 A11,11 0 0 1 187,149 Z M187,209 H285 A11,11 0 0 1 296,220 V220 A11,11 0 0 1 285,231 H187 A11,11 0 0 1 176,220 V220 A11,11 0 0 1 187,209 Z M78,250 L256,377 L434,250 L434,380 A36,36 0 0 1 398,416 L114,416 A36,36 0 0 1 78,380 Z"/>' ++ "</svg>";++ var STYLE =+ ":host{display:block}" ++ ".pf{--a:var(--posta-form-accent,var(--pf-accent,#9333EA));--r:var(--posta-form-radius,8px);" ++ "--bg:#fff;--fg:#101A37;--mut:#5A6486;--bd:#DFE5F2;--in:#fff;--err:#B42318;--ok:#067647;" ++ "box-sizing:border-box;max-width:var(--posta-form-max-width,480px);font-family:var(--posta-form-font,inherit);" ++ "font-size:15px;line-height:1.5;color:var(--fg);background:var(--bg);border:1px solid var(--bd);" ++ "border-radius:calc(var(--r) + 4px);padding:20px}" ++ ".pf[data-theme=dark]{--bg:#101A37;--fg:#F2F4FA;--mut:#A9B1CC;--bd:#2A3A66;--in:#0A1124;--err:#FDA29B;--ok:#75E0A7}" ++ "@media (prefers-color-scheme:dark){.pf[data-theme=auto]{--bg:#101A37;--fg:#F2F4FA;--mut:#A9B1CC;--bd:#2A3A66;--in:#0A1124;--err:#FDA29B;--ok:#75E0A7}}" ++ ".pf *{box-sizing:border-box}" ++ ".pf h2{margin:0 0 14px;font-size:1.2em;line-height:1.3}" ++ ".pf .desc{margin:-10px 0 14px;color:var(--mut)}" ++ ".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 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 .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;" ++ "color:#fff;background:var(--a);border:0;border-radius:var(--r);cursor:pointer;transition:filter .15s}" ++ ".pf button:hover{filter:brightness(1.08)}" ++ ".pf button:disabled{opacity:.6;cursor:default;filter:none}" ++ ".pf button:focus-visible{outline:2px solid var(--a);outline-offset:2px}" ++ ".pf .st{margin:10px 0 0;font-size:.9em}" ++ ".pf .st:empty{display:none}" ++ ".pf .st.err{color:var(--err)}" ++ ".pf .done{margin:4px 0;color:var(--ok);font-weight:600}" ++ ".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)}" ++ ".pf .brand strong{font-weight:700}" ++ "@media (prefers-reduced-motion:reduce){.pf *{transition:none!important}}";++ var counter = 0;++ function apiBase(el) {+ var host = el.getAttribute("data-posta-host");+ if (host) return host.replace(/\/+$/, "") + "/api/v1/f";+ if (SCRIPT && SCRIPT.src) {+ var u = new URL(SCRIPT.src, document.baseURI);+ var prefix = u.pathname.replace(/\/widget\/v1\/posta-form\.js$/, "");+ return u.origin + prefix.replace(/\/+$/, "") + "/api/v1/f";+ }+ return "";+ }++ function pickLang(el) {+ var lang = (el.getAttribute("data-lang") || navigator.language || "en").toLowerCase().slice(0, 2);+ return STRINGS[lang] ? lang : "en";+ }++ // fieldList builds the field list from data-fields. Form data (schemas)+ // will hand the same shape to render() from /config instead.+ function fieldList(el, t) {+ var wanted = (el.getAttribute("data-fields") || DEFAULT_FIELDS.join(","))+ .split(",")+ .map(function (s) { return s.trim().toLowerCase(); })+ .filter(function (k, i, all) { return BUILTIN_FIELDS[k] && all.indexOf(k) === i; });+ if (wanted.indexOf("email") < 0) wanted.unshift("email");+ if (wanted.indexOf("message") < 0) wanted.push("message");+ return wanted.map(function (key) {+ var def = BUILTIN_FIELDS[key];+ return {+ key: key,+ label: el.getAttribute("data-label-" + key) || t[key],+ type: def.type,+ required: def.required,+ autocomplete: def.autocomplete,+ };+ });+ }++ function h(tag, attrs, text) {+ var node = document.createElement(tag);+ if (attrs) {+ for (var k in attrs) {+ if (attrs[k] !== undefined && attrs[k] !== null && attrs[k] !== false) node.setAttribute(k, attrs[k] === true ? "" : attrs[k]);+ }+ }+ if (text) node.textContent = text;+ return node;+ }++ function emit(el, name, detail) {+ el.dispatchEvent(new CustomEvent("posta:" + name, { bubbles: true, composed: true, detail: detail }));+ }++ function getJSON(url) {+ return fetch(url, { credentials: "omit", headers: { Accept: "application/json" } }).then(function (res) {+ return res.json().then(function (body) { return { status: res.status, body: body }; }, function () {+ return { status: res.status, body: null };+ });+ });+ }++ function mount(el) {+ if (!el || el.__postaForm) return;+ var key = (el.getAttribute("data-posta-form") || "").trim();+ if (!key) {+ console.warn("[posta] data-posta-form needs the form's public key");+ return;+ }+ el.__postaForm = true;++ var base = apiBase(el);+ var t = STRINGS[pickLang(el)];+ var id = "pf" + ++counter;+ var root = el.attachShadow ? el.attachShadow({ mode: "open" }) : el;++ var style = document.createElement("style");+ 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);+ root.appendChild(wrap);++ var body = h("div");+ wrap.appendChild(body);++ var brand = h("div", { class: "brand" });+ var link = h("a", { href: BRAND_URL, target: "_blank", rel: "noopener" });+ link.appendChild(document.createTextNode(t.poweredBy + " "));+ var mark = h("span", { "aria-hidden": "true", style: "display:inline-flex" });+ mark.innerHTML = MARK_SVG;+ link.appendChild(mark);+ link.appendChild(h("strong", null, "Posta"));+ brand.appendChild(link);+ wrap.appendChild(brand);++ var loading = h("p", { class: "st" }, t.loading);+ body.appendChild(loading);++ function showNotice(text) {+ body.textContent = "";+ body.appendChild(h("p", { class: "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);+ }+ emit(el, "error", { key: key, status: res.status, code: reason, message: reason });+ return;+ }+ 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 });+ }+ );++ function render(cfg, fields) {+ body.textContent = "";+ var nonce = cfg.nonce ? cfg.nonce.nonce : "";+ // The server rejects a nonce younger than min_fill_seconds as a bot.+ // A fast human (or autofill) would lose their message silently, so+ // hold the submit until the nonce is old enough.+ var nonceAt = Date.now();+ var minFillMs = (cfg.min_fill_seconds || 0) * 1000;++ var title = el.getAttribute("data-title");+ var description = el.getAttribute("data-description");+ if (title) body.appendChild(h("h2", null, title));+ if (description) body.appendChild(h("p", { class: "desc" }, description));++ var form = h("form", { "aria-label": title || null });+ var inputs = {};+ var errors = {};++ 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 hpWrap = h("div", { class: "hp", "aria-hidden": "true" });+ var honeypot = h("input", { type: "text", name: cfg.honeypot_field || "_gotcha", tabindex: "-1", autocomplete: "off" });+ hpWrap.appendChild(honeypot);+ form.appendChild(hpWrap);++ var buttonText = el.getAttribute("data-button") || t.button;+ var button = h("button", { type: "submit" }, buttonText);+ form.appendChild(button);+ var status = h("p", { class: "st", role: "status", "aria-live": "polite" });+ form.appendChild(status);+ body.appendChild(form);++ 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");+ });+ }++ function fail(text) {+ status.textContent = text;+ status.className = "st err";+ }++ function refreshNonce() {+ if (!cfg.require_nonce) return Promise.resolve();+ return getJSON(base + "/" + encodeURIComponent(key) + "/nonce").then(+ function (res) {+ nonce = res.body && res.body.data ? res.body.data.nonce : "";+ nonceAt = Date.now();+ },+ function () { nonce = ""; }+ );+ }++ form.addEventListener("submit", function (e) {+ e.preventDefault();+ clearErrors();+ var payload = {};+ Object.keys(inputs).forEach(function (k) { payload[k] = inputs[k].value; });+ payload[honeypot.name] = honeypot.value;+ if (nonce) payload._nonce = nonce;++ button.disabled = true;+ button.textContent = t.sending;+ emit(el, "submit", { key: key });++ var wait = nonce ? Math.max(0, minFillMs + 250 - (Date.now() - nonceAt)) : 0;+ new Promise(function (resolve) { setTimeout(resolve, wait); })+ .then(function () {+ return fetch(base + "/" + encodeURIComponent(key), {+ method: "POST",+ credentials: "omit",+ // text/plain keeps this a CORS simple request: no preflight.+ headers: { "Content-Type": "text/plain;charset=UTF-8", Accept: "application/json" },+ body: JSON.stringify(payload),+ });+ })+ .then(function (res) {+ return res.json().then(+ function (b) { return { status: res.status, body: b }; },+ function () { return { status: res.status, body: null }; }+ );+ })+ .then(+ function (res) {+ 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));+ emit(el, "success", { key: key, id: data.id || null });+ return;+ }+ 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 message = data.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";+ emit(el, "error", { key: key, status: res.status, code: code, message: message });+ return refreshNonce();+ },+ function () {+ fail(t.network);+ emit(el, "error", { key: key, status: 0, code: "network", message: t.network });+ return refreshNonce();+ }+ )+ .then(function () {+ button.disabled = false;+ button.textContent = buttonText;+ });+ });++ emit(el, "ready", { key: key });+ }+ }++ function scan(scope) {+ var nodes = (scope || document).querySelectorAll("[data-posta-form]");+ for (var i = 0; i < nodes.length; i++) mount(nodes[i]);+ }++ window.PostaForms = { mount: mount, scan: scan, version: "1" };++ if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", function () { scan(); });+ else scan();+})();diff --git a/internal/web/widget/widget.go b/internal/web/widget/widget.gonew file mode 100644index 0000000..a01859c--- /dev/null+++ b/internal/web/widget/widget.go@@ -0,0 +1,40 @@+// 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 widget embeds the scripts that websites load from Posta, served+// under /widget/v1/.+package widget++import (+ "crypto/sha256"+ _ "embed"+ "encoding/hex"+)++// FormScript is the website form widget, served at /widget/v1/posta-form.js.+//+//go:embed posta-form.js+var FormScript []byte++// FormScriptETag is a strong ETag over FormScript, so a cached copy is+// revalidated with a 304 until the script changes.+var FormScriptETag = func() string {+ sum := sha256.Sum256(FormScript)+ return `"` + hex.EncodeToString(sum[:12]) + `"`+}()diff --git a/web/src/api/types.ts b/web/src/api/types.tsindex 59556e6..7f63b29 100644--- a/web/src/api/types.ts+++ b/web/src/api/types.ts@@ -1358,4 +1358,5 @@ export interface FormSnippet {public_key: stringhtml: stringfetch: string+ widget: string}diff --git a/web/src/views/forms/FormDetail.vue b/web/src/views/forms/FormDetail.vueindex 5f5c2eb..336a0f7 100644--- a/web/src/views/forms/FormDetail.vue+++ b/web/src/views/forms/FormDetail.vue@@ -113,6 +113,54 @@ function copy(text: string) {const endpoint = computed(() => snippet.value?.endpoint || "");+// Website widget builder. Options become data attributes on the placeholder;+// nothing is saved to the form.+const optionalWidgetFields = ["name", "phone", "subject"] as const;+const widget = ref({+ fields: ["name"] as string[],+ title: "",+ description: "",+ button: "",+ success: "",+ theme: "light",+ accent: "",+ lang: "",+});++function setAccent(e: Event) {+ widget.value.accent = (e.target as HTMLInputElement).value;+}++function escapeAttr(value: string) {+ return value.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<").replace(/>/g, ">");+}++const widgetScriptURL = computed(() =>+ endpoint.value.replace(/\/api\/v1\/f\/[^/]+$/, "") + "/widget/v1/posta-form.js",+);++const widgetSnippet = computed(() => {+ if (!form.value) return "";+ const w = widget.value;+ const attrs: [string, string][] = [["data-posta-form", form.value.public_key]];+ const fields = ["name", "email", "phone", "subject", "message"].filter(+ (f) => f === "email" || f === "message" || w.fields.includes(f),+ );+ if (fields.join(",") !== "name,email,message") attrs.push(["data-fields", fields.join(",")]);+ if (w.title.trim()) attrs.push(["data-title", w.title.trim()]);+ if (w.description.trim()) attrs.push(["data-description", w.description.trim()]);+ if (w.button.trim()) attrs.push(["data-button", w.button.trim()]);+ if (w.success.trim()) attrs.push(["data-success", w.success.trim()]);+ if (w.theme !== "light") attrs.push(["data-theme", w.theme]);+ if (w.accent) attrs.push(["data-accent", w.accent]);+ if (w.lang) attrs.push(["data-lang", w.lang]);+ const placeholder =+ attrs.length > 2+ ? `<div\n${attrs.map(([k, v]) => ` ${k}="${escapeAttr(v)}"`).join("\n")}\n></div>`+ : `<div ${attrs.map(([k, v]) => `${k}="${escapeAttr(v)}"`).join(" ")}></div>`;+ return `${placeholder}\n<script src="${escapeAttr(widgetScriptURL.value)}" async></` + `script>`;+});+onMounted(load);</script>@@ -305,6 +353,81 @@ onMounted(load);<button class="btn btn-secondary" @click="rotateKey">Rotate key</button></div><div class="card-body">+ <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,+ and shows the result in place. Settings you change here later apply without editing your site.+ </p>+ <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 0 16px">+ <div class="form-group">+ <label class="form-label">Fields</label>+ <label v-for="f in optionalWidgetFields" :key="f" class="checkbox-label">+ <input v-model="widget.fields" type="checkbox" :value="f" />+ {{ f }}+ </label>+ <small class="muted">Email and message are always included.</small>+ </div>+ <div class="form-group">+ <label class="form-label">Title</label>+ <input v-model="widget.title" class="form-input" placeholder="Contact us" />+ </div>+ <div class="form-group">+ <label class="form-label">Description</label>+ <input v-model="widget.description" class="form-input" placeholder="We reply within a day." />+ </div>+ <div class="form-group">+ <label class="form-label">Button text</label>+ <input v-model="widget.button" class="form-input" placeholder="Send message" />+ </div>+ <div class="form-group">+ <label class="form-label">Success message</label>+ <input v-model="widget.success" class="form-input" placeholder="Thanks — your message has been received." />+ </div>+ <div class="form-group">+ <label class="form-label">Theme</label>+ <select v-model="widget.theme" class="form-select">+ <option value="light">Light</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">Accent colour</label>+ <div style="display: flex; gap: 8px; align-items: center">+ <input+ type="color"+ :value="widget.accent || '#9333ea'"+ aria-label="Accent colour"+ @input="setAccent"+ />+ <button v-if="widget.accent" class="btn btn-secondary" @click="widget.accent = ''">Reset</button>+ </div>+ </div>+ <div class="form-group">+ <label class="form-label">Language</label>+ <select v-model="widget.lang" class="form-select">+ <option value="">Visitor's browser</option>+ <option value="en">English</option>+ <option value="fr">French</option>+ </select>+ </div>+ </div>+ <div class="form-group">+ <label class="form-label">Embed code</label>+ <pre style="overflow-x: auto; padding: 12px; border-radius: 8px; background: var(--bg-secondary)">{{ widgetSnippet }}</pre>+ <button class="btn btn-primary" @click="copy(widgetSnippet)">Copy widget code</button>+ </div>+ <p v-if="!form.allowed_origins?.length" class="muted">+ Any website can show this form. To restrict it, list your site's origin+ (for example <code>https://example.com</code>) under Allowed origins on the Setup tab.+ </p>+ <p v-else class="muted">+ The widget only works on: <code>{{ form.allowed_origins.join(", ") }}</code>.+ Other sites see "This form is not available on this website."+ </p>++ <hr style="margin: 24px 0; border: 0; border-top: 1px solid var(--border-primary)" />+ <h3 style="margin: 0 0 12px">Build your own</h3><div class="form-group"><label class="form-label">Endpoint</label><div style="display: flex; gap: 8px">@@ -314,12 +437,12 @@ onMounted(load);</div><div class="form-group"><label class="form-label">HTML form</label>- <pre style="overflow-x: auto; padding: 12px; border-radius: 8px; background: var(--bg-subtle)">{{ snippet?.html }}</pre>+ <pre style="overflow-x: auto; padding: 12px; border-radius: 8px; background: var(--bg-secondary)">{{ snippet?.html }}</pre><button class="btn btn-secondary" @click="copy(snippet?.html || '')">Copy HTML</button></div><div class="form-group"><label class="form-label">fetch()</label>- <pre style="overflow-x: auto; padding: 12px; border-radius: 8px; background: var(--bg-subtle)">{{ snippet?.fetch }}</pre>+ <pre style="overflow-x: auto; padding: 12px; border-radius: 8px; background: var(--bg-secondary)">{{ snippet?.fetch }}</pre><button class="btn btn-secondary" @click="copy(snippet?.fetch || '')">Copy JS</button></div></div>