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(email): add hosted web view and reserved {{ posta_* }} template variables (#89)
Jonas Kaninda64ad733a562a
diff --git a/docs/docs/templates/system-variables.md b/docs/docs/templates/system-variables.mdnew file mode 100644index 0000000..2e43176--- /dev/null+++ b/docs/docs/templates/system-variables.md@@ -0,0 +1,64 @@+---+sidebar_position: 3+title: System Variables+description: Built-in {{ posta_* }} template variables for unsubscribe and web-view links+---++# System Variables++Posta reserves the `{{ posta_* }}` variable namespace for values it injects into+every templated email. You don't pass these in `template_data` — Posta fills them+in per message, after the message identity is known. Using them is opt-in: a+variable only appears if your template references it.++> The `posta_` prefix is reserved. Any key you supply in `template_data` that starts+> with `posta_` is ignored in favour of the system value.++## Available variables++| Variable | Description |+|---|---|+| `{{ posta_web_view_url }}` | Signed link to read this email on the web ("view in browser"). |+| `{{ posta_mail_web_link }}` | Alias for `posta_web_view_url`. |+| `{{ posta_unsubscribe_url }}` | One-click unsubscribe link for this message. |++## View in browser++```html+<a href="{{ posta_web_view_url }}">View this email in your browser</a>+```++Works in the text part too:++```+View online: {{ posta_web_view_url }}+```++The link is an HMAC-signed, **expiring** capability bound to the message's opaque+ID. The hosted page renders the exact HTML that was sent, on Posta's public web+origin (`POSTA_WEB_URL`), with a restrictive content-security policy, `noindex`, and+no cookies. Opening it does **not** count as an email open.++Notes:+- Links expire after 90 days by default.+- `cid:` inline-attachment images don't resolve on the web — use `https`/`data:` image URLs if you rely on the web view.++## Unsubscribe++```html+<a href="{{ posta_unsubscribe_url }}">Unsubscribe</a>+```++For campaign sends this unsubscribes the recipient from that campaign's list. For+transactional sends it adds the recipient to your suppression list. The link is the+RFC 8058 one-click endpoint, so it also works from the mailbox-provider+"Unsubscribe" button.++## Behaviour in previews++In the template editor / preview there is no real message yet, so each system+variable renders as **its own name** (e.g. `{{ posta_web_view_url }}` →+`posta_web_view_url`) rather than a generated link. This lets a preview of a+template that uses system variables render without errors, and shows the author+which variable sits where. The real links are only generated when the message is+actually sent.diff --git a/internal/handlers/template_handler.go b/internal/handlers/template_handler.goindex 79da37e..3dacd29 100644--- a/internal/handlers/template_handler.go+++ b/internal/handlers/template_handler.go@@ -199,6 +199,10 @@ func (h *TemplateHandler) Preview(c *okapi.Context, req *PreviewTemplateRequest)if data == nil {data = map[string]any{}}+ // Expose reserved {{ posta_* }} variables by name so previews of templates that+ // use them render without missing-key errors. No real message exists here, so+ // they resolve to their own names rather than generated links.+ data = email.WithSystemVarNames(data)input := &email.RenderInput{SubjectTemplate: req.Body.SubjectTemplate,diff --git a/internal/handlers/tracking_handler.go b/internal/handlers/tracking_handler.goindex 78e39b6..c1aa24f 100644--- a/internal/handlers/tracking_handler.go+++ b/internal/handlers/tracking_handler.go@@ -21,6 +21,7 @@ import ("fmt""html""net/http"+ "regexp""strings""time"@@ -30,6 +31,11 @@ import ("github.com/jkaninda/okapi")+// openPixelRe matches the open-tracking pixel injected by tracking.ProcessHTML so+// it can be stripped from the hosted "view in browser" page — rendering a stored+// campaign body in a browser would otherwise re-fire the open and inflate metrics.+var openPixelRe = regexp.MustCompile(`(?i)<img[^>]+src=["'][^"']*/t/o/[^"']*["'][^>]*>`)+type TrackingHandler struct {trackingRepo *repositories.TrackingRepositorymessageRepo *repositories.CampaignMessageRepository@@ -78,6 +84,10 @@ type TrackingUnsubscribeRequest struct {Token string `param:"token"`}+type TrackingWebViewRequest struct {+ Token string `param:"token"`+}+// OpenPixel serves a 1x1 transparent GIF and records the open event.// Signature is mandatory; unsigned or bad-sig requests get 404.func (h *TrackingHandler) OpenPixel(c *okapi.Context, req *TrackingOpenRequest) error {@@ -216,6 +226,42 @@ h1{font-size:20px;color:#16a34a}p{color:#6b7280;font-size:14px}</style></head><breturn c.HTMLView(http.StatusOK, confirmHTML, okapi.M{})}+// WebView renders a hosted copy of a sent email ("view in browser"). The token is+// an HMAC-signed, expiring capability bound to the email's opaque UUID. Because the+// page renders arbitrary customer HTML, it is served with a restrictive CSP, no+// cookies, and noindex, and the open-tracking pixel is stripped so a web view does+// not inflate open metrics.+func (h *TrackingHandler) WebView(c *okapi.Context, req *TrackingWebViewRequest) error {+ emailUUID, err := h.trackingService.VerifyWebViewToken(req.Token)+ if err != nil {+ return c.HTMLView(http.StatusNotFound, "This link is invalid or has expired.", okapi.M{})+ }+ em, err := h.emailRepo.FindByUUID(emailUUID)+ if err != nil || em == nil {+ return c.HTMLView(http.StatusNotFound, "Message not found", okapi.M{})+ }++ body := em.HTMLBody+ if strings.TrimSpace(body) == "" {+ body = "<pre style=\"white-space:pre-wrap;font-family:sans-serif\">" + html.EscapeString(em.TextBody) + "</pre>"+ }+ body = openPixelRe.ReplaceAllString(body, "")++ hdr := c.ResponseWriter().Header()+ hdr.Set("Content-Security-Policy", "default-src 'none'; img-src https: http: data:; style-src 'unsafe-inline' https:; font-src https: data:; base-uri 'none'; form-action 'none'")+ hdr.Set("X-Robots-Tag", "noindex, nofollow")+ hdr.Set("Referrer-Policy", "no-referrer")++ page := fmt.Sprintf(`<!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>%s</title>+<style>body{margin:0;background:#f3f4f6}.posta-wv-bar{font-family:sans-serif;font-size:12px;color:#6b7280;text-align:center;padding:10px;background:#fff;border-bottom:1px solid #e5e7eb}.posta-wv-body{max-width:680px;margin:0 auto;padding:16px}</style>+</head><body><div class="posta-wv-bar">You are viewing a copy of an email.</div><div class="posta-wv-body">%s</div></body></html>`,+ html.EscapeString(em.Subject), body)++ return c.HTMLView(http.StatusOK, page, okapi.M{})+}+// UnsubscribeConfirm processes the unsubscribe action.func (h *TrackingHandler) UnsubscribeConfirm(c *okapi.Context, req *TrackingUnsubscribeRequest) error {messageID, err := h.trackingService.VerifyUnsubscribeToken(req.Token)diff --git a/internal/routes/routes.go b/internal/routes/routes.goindex 76d93e2..35d8bfc 100644--- a/internal/routes/routes.go+++ b/internal/routes/routes.go@@ -325,10 +325,10 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *ctrackingService := tracking.NewService(trackingRepo, cfg.AppWebURL, []byte(cfg.JWTSecret))r.h.tracking = handlers.NewTrackingHandler(trackingRepo, campaignMessageRepo, campaignRepo, subscriberRepo, subscriberListRepo, emailRepo, suppressionRepo, trackingService)- // Auto-attach RFC 8058 one-click unsubscribe URLs on transactional sends- // that target a subscriber list (so Gmail/Yahoo bulk-sender requirements- // are met without the caller having to build the header themselves).- emailService.SetTxUnsubscribeGenerator(trackingService)+ // Wire the generator for Posta-injected public links (one-click unsubscribe ++ // hosted "view in browser"), used to resolve reserved {{ posta_* }} template+ // variables once an email's identity is known.+ emailService.SetLinkGenerator(trackingService)// Bounce webhookr.h.bounceWebhook = handlers.NewBounceWebhookHandler(subscriberRepo, emailRepo, campaignMessageRepo)diff --git a/internal/routes/tracking_routes.go b/internal/routes/tracking_routes.goindex caf2eda..d168931 100644--- a/internal/routes/tracking_routes.go+++ b/internal/routes/tracking_routes.go@@ -75,6 +75,14 @@ func (r *Router) trackingRoutes() []okapi.RouteDefinition {Summary: "Transactional one-click unsubscribe (RFC 8058)",Options: []okapi.RouteOption{okapi.DocHide()},},+ {+ Method: http.MethodGet,+ Path: "/t/v/{token}",+ Handler: okapi.H(r.h.tracking.WebView),+ Tags: []string{"Tracking"},+ Summary: "View email in browser",+ Options: []okapi.RouteOption{okapi.DocHide()},+ },}}diff --git a/internal/services/email/service.go b/internal/services/email/service.goindex 07ea5fa..84e228f 100644--- a/internal/services/email/service.go+++ b/internal/services/email/service.go@@ -28,6 +28,7 @@ import ("strings""time"+ "github.com/google/uuid""github.com/goposta/posta/internal/models""github.com/goposta/posta/internal/services/ratelimit""github.com/goposta/posta/internal/services/settings"@@ -64,11 +65,13 @@ type PlanLimits struct {MaxBatchSize int}-// TxUnsubscribeGenerator produces a signed one-click (RFC 8058) unsubscribe-// URL for a transactional email. Kept as a narrow interface so the email-// service does not depend directly on the tracking package.-type TxUnsubscribeGenerator interface {+// LinkGenerator produces the signed public links Posta injects into messages:+// the one-click (RFC 8058) unsubscribe URL and the hosted "view in browser" URL.+// Kept as a narrow interface so the email service does not depend directly on the+// tracking package.+type LinkGenerator interface {TxUnsubscribeURL(emailID uint) string+ WebViewURL(emailUUID string) string}type Service struct {@@ -89,7 +92,7 @@ type Service struct {settings *settings.ProviderblobStore blob.StoreplanLimits PlanLimitsProvider- txUnsubGen TxUnsubscribeGenerator+ linkGen LinkGeneratordevMode boolonSent func()onFailed func()@@ -151,11 +154,11 @@ func (s *Service) SetEnqueuer(eq EmailEnqueuer) {s.enqueuer = eq}-// SetTxUnsubscribeGenerator wires the one-click unsubscribe URL generator.-// When set, transactional sends that use a subscriber list but don't supply an-// explicit list_unsubscribe_url will get an auto-generated RFC 8058 URL.-func (s *Service) SetTxUnsubscribeGenerator(gen TxUnsubscribeGenerator) {- s.txUnsubGen = gen+// SetLinkGenerator wires the generator for Posta-injected public links — the+// one-click unsubscribe URL and the hosted "view in browser" URL used to resolve+// reserved {{ posta_* }} template variables.+func (s *Service) SetLinkGenerator(gen LinkGenerator) {+ s.linkGen = gen}// SetBlobStore sets the blob storage backend for persisting email attachments.@@ -602,6 +605,10 @@ func (s *Service) Send(ctx context.Context, userID, apiKeyID uint, workspaceID *}em := &models.Email{+ // Assign the UUID up front so reserved {{ posta_* }} links (which key the+ // web view off the UUID) can be built without depending on the DB reading+ // the gen_random_uuid() default back after insert.+ UUID: uuid.NewString(),UserID: userID,WorkspaceID: workspaceID,APIKeyID: apiKeyPtr,@@ -623,6 +630,23 @@ func (s *Service) Send(ctx context.Context, userID, apiKeyID uint, workspaceID *return nil, fmt.Errorf("failed to store email: %w", err)}+ // Resolve reserved {{ posta_* }} system links now that the email identity is+ // known. Rendering left sentinels in the body; replace them with the real+ // per-message URLs. Only touches the DB when the template actually used one.+ if s.linkGen != nil && (HasSystemSentinels(em.HTMLBody) || HasSystemSentinels(em.TextBody) || HasSystemSentinels(em.Subject)) {+ webViewURL := s.linkGen.WebViewURL(em.UUID)+ unsubscribeURL := s.linkGen.TxUnsubscribeURL(em.ID)+ em.HTMLBody = SubstituteSystemLinks(em.HTMLBody, webViewURL, unsubscribeURL)+ em.TextBody = SubstituteSystemLinks(em.TextBody, webViewURL, unsubscribeURL)+ em.Subject = SubstituteSystemLinks(em.Subject, webViewURL, unsubscribeURL)+ // Keep req in sync so the synchronous fallback (sendSync) sends the+ // resolved body/subject too.+ req.HTML = em.HTMLBody+ req.Text = em.TextBody+ req.Subject = em.Subject+ _ = s.emailRepo.Update(em)+ }+if s.devMode {em.Status = models.EmailStatusSentnow := time.Now()@@ -1003,7 +1027,17 @@ func (s *Service) RenderTemplate(userID uint, workspaceID *uint, templateID *uinif err != nil {return nil, fmt.Errorf("template not found: %w", err)}- return s.resolveAndRender(tmpl, language, data)+ rendered, err := s.resolveAndRender(tmpl, language, data)+ if err != nil {+ return nil, err+ }+ // This is a preview (editor / dry-run): there is no real message yet, so show+ // the reserved {{ posta_* }} variables by name rather than leaking the internal+ // sentinels or generating throwaway links.+ rendered.HTML = SubstituteSystemLinks(rendered.HTML, VarWebView, VarUnsubscribe)+ rendered.Text = SubstituteSystemLinks(rendered.Text, VarWebView, VarUnsubscribe)+ rendered.Subject = SubstituteSystemLinks(rendered.Subject, VarWebView, VarUnsubscribe)+ return rendered, nil}// findTemplate looks up a template by ID or name. When templateID is provided@@ -1067,7 +1101,9 @@ func (s *Service) resolveAndRender(tmpl *models.Template, language string, dataTextTemplate: l.TextTemplate,CSS: css,}- return s.renderer.Render(input, data)+ // Inject reserved {{ posta_* }} variables as sentinels; the real per-message+ // URLs are substituted later in Send once the email identity is known.+ return s.renderer.Render(input, WithSystemVars(data))}// resolveLocalization implements the language fallback strategy:diff --git a/internal/services/email/system_vars.go b/internal/services/email/system_vars.gonew file mode 100644index 0000000..3041200--- /dev/null+++ b/internal/services/email/system_vars.go@@ -0,0 +1,116 @@+/*+ * Copyright 2026 Jonas Kaninda+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ */++package email++import (+ "sort"+ "strings"+)++// Canonical reserved variable names.+const (+ VarWebView = "posta_web_view_url"+ VarWebViewAlias = "posta_mail_web_link"+ VarUnsubscribe = "posta_unsubscribe_url"+)++// Posta reserves the {{ posta_* }} template-variable namespace for system values+// it injects itself (the hosted "view in browser" link, the unsubscribe link, …).+//+// These values are per-message, but a template is often rendered once and reused+// across many recipients (e.g. campaigns render once per language). So rendering+// does not substitute the real URL — it substitutes a stable *sentinel*, which is+// then replaced per message once the email identity (UUID / id) is known+// (SubstituteSystemLinks).+//+// The sentinels are written as root-relative URLs so that:+// - html/template's URL filter passes them through unchanged (no #ZgotmplZ),+// - premailer leaves them alone during CSS inlining,+// - the campaign click-rewriter (which only matches http(s):// hrefs) ignores them.+const (+ sentinelWebView = "/__posta_web_view__"+ sentinelUnsubscribe = "/__posta_unsubscribe__"+)++// Canonical template variable names and their documented aliases. All map to a+// sentinel; unknown {{ posta_* }} vars are not injected (and will render empty+// under missingkey=zero, or error under missingkey=error — by design, reserved).+var systemVarSentinels = map[string]any{+ VarWebView: sentinelWebView,+ VarWebViewAlias: sentinelWebView, // alias for posta_web_view_url+ VarUnsubscribe: sentinelUnsubscribe,+}++// SystemVarNames returns the reserved {{ posta_* }} variable names (canonical and+// aliases), sorted. Useful for editor/template-view surfaces that advertise the+// available variables.+func SystemVarNames() []string {+ names := make([]string, 0, len(systemVarSentinels))+ for k := range systemVarSentinels {+ names = append(names, k)+ }+ sort.Strings(names)+ return names+}++// WithSystemVarNames returns a copy of data with each reserved {{ posta_* }}+// variable present but set to its own name. Used by previews / template views+// where no real message exists: the template renders without missing-key errors+// and the author sees which system variable sits where, without any generated+// URL/data.+func WithSystemVarNames(data map[string]any) map[string]any {+ out := make(map[string]any, len(data)+len(systemVarSentinels))+ for k, v := range data {+ out[k] = v+ }+ for k := range systemVarSentinels {+ out[k] = k+ }+ return out+}++// WithSystemVars returns a copy of data with the reserved posta_* variables added.+// System values are written last so user-supplied data cannot shadow them.+func WithSystemVars(data map[string]any) map[string]any {+ out := make(map[string]any, len(data)+len(systemVarSentinels))+ for k, v := range data {+ out[k] = v+ }+ for k, v := range systemVarSentinels {+ out[k] = v+ }+ return out+}++// HasSystemSentinels reports whether s still contains any unresolved sentinel,+// so callers can skip the substitution+update when a template uses no system vars.+func HasSystemSentinels(s string) bool {+ return strings.Contains(s, sentinelWebView) || strings.Contains(s, sentinelUnsubscribe)+}++// SubstituteSystemLinks replaces the reserved sentinels with the real per-message+// URLs. An empty URL (e.g. a disabled feature) removes the sentinel rather than+// leaving a broken root-relative link in the message.+func SubstituteSystemLinks(s, webViewURL, unsubscribeURL string) string {+ if s == "" {+ return s+ }+ s = strings.ReplaceAll(s, sentinelWebView, webViewURL)+ s = strings.ReplaceAll(s, sentinelUnsubscribe, unsubscribeURL)+ return s+}diff --git a/internal/services/email/system_vars_test.go b/internal/services/email/system_vars_test.gonew file mode 100644index 0000000..bd76447--- /dev/null+++ b/internal/services/email/system_vars_test.go@@ -0,0 +1,122 @@+/*+ * Copyright 2026 Jonas Kaninda+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ */++package email++import (+ "strings"+ "testing"++ "github.com/jkaninda/okapi"+)++func TestWithSystemVarsAddsReservedKeysAndDoesNotMutateInput(t *testing.T) {+ in := map[string]any{"name": "Ada"}+ out := WithSystemVars(in)++ for _, k := range []string{"posta_web_view_url", "posta_mail_web_link", "posta_unsubscribe_url"} {+ if _, ok := out[k]; !ok {+ t.Fatalf("expected reserved key %q to be present", k)+ }+ }+ if out["name"] != "Ada" {+ t.Fatalf("user data lost: %v", out["name"])+ }+ if _, ok := in["posta_web_view_url"]; ok {+ t.Fatalf("input map must not be mutated")+ }+}++func TestSystemVarsUserCannotShadow(t *testing.T) {+ out := WithSystemVars(map[string]any{"posta_web_view_url": "https://evil.example"})+ if out["posta_web_view_url"] == "https://evil.example" {+ t.Fatalf("user value must not override reserved system variable")+ }+}++func TestRenderThenSubstituteSystemLinks(t *testing.T) {+ r := NewTemplateRenderer()+ r.MissingKeyBehavior = "error"++ // missingkey=error must NOT fire for reserved vars because WithSystemVars+ // always supplies them.+ in := &RenderInput{+ HTMLTemplate: `<a href="{{ posta_web_view_url }}">view</a> <a href="{{ posta_unsubscribe_url }}">unsub</a>`,+ TextTemplate: `view: {{ posta_mail_web_link }}`,+ }+ rendered, err := r.Render(in, WithSystemVars(okapi.M{}))+ if err != nil {+ t.Fatalf("render failed: %v", err)+ }+ if !HasSystemSentinels(rendered.HTML) || !HasSystemSentinels(rendered.Text) {+ t.Fatalf("expected sentinels to survive rendering; got html=%q text=%q", rendered.HTML, rendered.Text)+ }++ html := SubstituteSystemLinks(rendered.HTML, "https://p/t/v/tok", "https://p/t/u/tx/tok")+ if strings.Contains(html, sentinelWebView) || strings.Contains(html, sentinelUnsubscribe) {+ t.Fatalf("sentinels not fully replaced: %q", html)+ }+ if !strings.Contains(html, "https://p/t/v/tok") || !strings.Contains(html, "https://p/t/u/tx/tok") {+ t.Fatalf("real links missing after substitution: %q", html)+ }++ text := SubstituteSystemLinks(rendered.Text, "https://p/t/v/tok", "x")+ if !strings.Contains(text, "view: https://p/t/v/tok") {+ t.Fatalf("text alias not substituted: %q", text)+ }+}++func TestWithSystemVarNamesResolvesToNames(t *testing.T) {+ r := NewTemplateRenderer()+ r.MissingKeyBehavior = "error"++ in := &RenderInput{HTMLTemplate: `<a href="{{ posta_web_view_url }}">v</a>{{ posta_unsubscribe_url }}`}+ // missingkey=error must not fire, and values must be the variable names.+ rendered, err := r.Render(in, WithSystemVarNames(map[string]any{}))+ if err != nil {+ t.Fatalf("render failed: %v", err)+ }+ if !strings.Contains(rendered.HTML, VarWebView) || !strings.Contains(rendered.HTML, VarUnsubscribe) {+ t.Fatalf("expected variable names in output, got %q", rendered.HTML)+ }+ if HasSystemSentinels(rendered.HTML) {+ t.Fatalf("name-mode preview must not contain sentinels: %q", rendered.HTML)+ }+}++func TestSystemVarNames(t *testing.T) {+ names := SystemVarNames()+ want := map[string]bool{VarWebView: false, VarWebViewAlias: false, VarUnsubscribe: false}+ for _, n := range names {+ if _, ok := want[n]; !ok {+ t.Fatalf("unexpected name %q", n)+ }+ want[n] = true+ }+ for n, seen := range want {+ if !seen {+ t.Fatalf("missing name %q", n)+ }+ }+}++func TestSubstituteSystemLinksEmptyRemovesSentinel(t *testing.T) {+ got := SubstituteSystemLinks(`<a href="`+sentinelWebView+`">x</a>`, "", "")+ if strings.Contains(got, sentinelWebView) {+ t.Fatalf("empty url should remove sentinel, got %q", got)+ }+}diff --git a/internal/services/email/template_renderer.go b/internal/services/email/template_renderer.goindex 7837bda..3e572ae 100644--- a/internal/services/email/template_renderer.go+++ b/internal/services/email/template_renderer.go@@ -146,17 +146,20 @@ func dotPrefix(token string) string {return token}+// Missing-key behaviors for template rendering (Go template "missingkey" option).+const (+ missingKeyError = "error" // return an error on a missing data key (default)+ missingKeyZero = "zero" // silently use the zero value+ missingKeyInvalid = "invalid" // render "<no value>"+)+type TemplateRenderer struct {- // MissingKeyBehavior controls how missing data keys are handled.- // "error" (default): return an error on missing key- // "zero": silently use zero value- // "invalid": render "<no value>"MissingKeyBehavior string}func NewTemplateRenderer() *TemplateRenderer {return &TemplateRenderer{- MissingKeyBehavior: "error",+ MissingKeyBehavior: missingKeyError,}}@@ -209,10 +212,10 @@ func (r *TemplateRenderer) Render(input *RenderInput, data okapi.M) (*RenderedTefunc (r *TemplateRenderer) missingKeyOption() string {switch r.MissingKeyBehavior {- case "zero", "invalid":+ case missingKeyZero, missingKeyInvalid:return r.MissingKeyBehaviordefault:- return "error"+ return missingKeyError}}diff --git a/internal/services/tracking/tracking.go b/internal/services/tracking/tracking.goindex e606afb..221f95e 100644--- a/internal/services/tracking/tracking.go+++ b/internal/services/tracking/tracking.go@@ -27,10 +27,16 @@ import ("regexp""strconv""strings"+ "time""github.com/goposta/posta/internal/storage/repositories")+// defaultWebViewTTL bounds how long a hosted "view in browser" link stays valid.+// A web-view link exposes full message content, so unlike unsubscribe tokens it+// carries an expiry.+const defaultWebViewTTL = 90 * 24 * time.Hour+// Service handles link rewriting and pixel injection for campaign emails.type Service struct {repo *repositories.TrackingRepository@@ -212,6 +218,65 @@ func (s *Service) TxUnsubscribeURL(emailID uint) string {return fmt.Sprintf("%s/t/u/tx/%s", s.baseURL, s.SignTxUnsubscribeToken(emailID))}+// SignWebViewToken creates an HMAC-signed token for the hosted "view in browser"+// page. The payload encodes the opaque Email UUID (non-enumerable) plus an expiry,+// and a "view:" prefix binds the token kind so it can't be replayed against the+// unsubscribe handlers.+func (s *Service) SignWebViewToken(emailUUID string, ttl time.Duration) string {+ exp := time.Now().Add(ttl).Unix()+ payload := fmt.Sprintf("view:%s:%d", emailUUID, exp)+ mac := hmac.New(sha256.New, s.hmacKey)+ mac.Write([]byte(payload))+ sig := base64.RawURLEncoding.EncodeToString(mac.Sum(nil))+ return base64.RawURLEncoding.EncodeToString([]byte(payload)) + "." + sig+}++// VerifyWebViewToken verifies the HMAC token, checks the expiry, and returns the+// Email UUID it encodes.+func (s *Service) VerifyWebViewToken(token string) (string, error) {+ parts := strings.SplitN(token, ".", 2)+ if len(parts) != 2 {+ return "", errors.New("invalid token format")+ }+ payloadBytes, err := base64.RawURLEncoding.DecodeString(parts[0])+ if err != nil {+ return "", errors.New("invalid token encoding")+ }+ mac := hmac.New(sha256.New, s.hmacKey)+ mac.Write(payloadBytes)+ expectedSig := base64.RawURLEncoding.EncodeToString(mac.Sum(nil))+ if !hmac.Equal([]byte(parts[1]), []byte(expectedSig)) {+ return "", errors.New("invalid token signature")+ }+ payload := string(payloadBytes)+ if !strings.HasPrefix(payload, "view:") {+ return "", errors.New("wrong token kind")+ }+ rest := payload[len("view:"):]+ sep := strings.LastIndex(rest, ":")+ if sep <= 0 {+ return "", errors.New("invalid token payload")+ }+ emailUUID := rest[:sep]+ exp, err := strconv.ParseInt(rest[sep+1:], 10, 64)+ if err != nil {+ return "", errors.New("invalid token expiry")+ }+ if time.Now().Unix() > exp {+ return "", errors.New("token expired")+ }+ return emailUUID, nil+}++// WebViewURL returns the public "view in browser" URL for a transactional or+// campaign email, keyed by its opaque UUID. Returns "" for an empty UUID.+func (s *Service) WebViewURL(emailUUID string) string {+ if emailUUID == "" {+ return ""+ }+ return fmt.Sprintf("%s/t/v/%s", s.baseURL, s.SignWebViewToken(emailUUID, defaultWebViewTTL))+}+// hashLink generates a deterministic hash for a campaign + URL combination.func hashLink(campaignID uint, url string) string {h := sha256.New()diff --git a/internal/services/tracking/webview_test.go b/internal/services/tracking/webview_test.gonew file mode 100644index 0000000..92b8cfd--- /dev/null+++ b/internal/services/tracking/webview_test.go@@ -0,0 +1,78 @@+/*+ * Copyright 2026 Jonas Kaninda+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ */++package tracking++import (+ "strings"+ "testing"+ "time"+)++func newTestService() *Service {+ return NewService(nil, "https://posta.example.com/", []byte("test-hmac-key"))+}++func TestWebViewTokenRoundTrip(t *testing.T) {+ s := newTestService()+ const uuid = "11111111-2222-3333-4444-555555555555"++ tok := s.SignWebViewToken(uuid, time.Hour)+ got, err := s.VerifyWebViewToken(tok)+ if err != nil {+ t.Fatalf("verify returned error: %v", err)+ }+ if got != uuid {+ t.Fatalf("uuid mismatch: got %q want %q", got, uuid)+ }+}++func TestWebViewURL(t *testing.T) {+ s := newTestService()+ url := s.WebViewURL("abc")+ if !strings.HasPrefix(url, "https://posta.example.com/t/v/") {+ t.Fatalf("unexpected web view URL: %q", url)+ }+ if s.WebViewURL("") != "" {+ t.Fatalf("empty uuid should yield empty url")+ }+}++func TestWebViewTokenExpired(t *testing.T) {+ s := newTestService()+ tok := s.SignWebViewToken("abc", -time.Minute) // already expired+ if _, err := s.VerifyWebViewToken(tok); err == nil {+ t.Fatalf("expected expired token to be rejected")+ }+}++func TestWebViewTokenTampered(t *testing.T) {+ s := newTestService()+ tok := s.SignWebViewToken("abc", time.Hour)+ if _, err := s.VerifyWebViewToken(tok + "x"); err == nil {+ t.Fatalf("expected tampered signature to be rejected")+ }+}++func TestWebViewTokenWrongKind(t *testing.T) {+ s := newTestService()+ // A transactional unsubscribe token must not validate as a web-view token.+ txTok := s.SignTxUnsubscribeToken(42)+ if _, err := s.VerifyWebViewToken(txTok); err == nil {+ t.Fatalf("expected wrong-kind token to be rejected")+ }+}diff --git a/internal/worker/campaign_processor.go b/internal/worker/campaign_processor.goindex 29542df..dee5fe9 100644--- a/internal/worker/campaign_processor.go+++ b/internal/worker/campaign_processor.go@@ -24,6 +24,7 @@ import ("math/rand""time"+ "github.com/google/uuid""github.com/goposta/posta/internal/models""github.com/goposta/posta/internal/services/email""github.com/goposta/posta/internal/services/tracking"@@ -307,8 +308,10 @@ func (p *CampaignProcessor) HandleCampaignBatch(_ context.Context, t *asynq.Tasksender = fmt.Sprintf("%s <%s>", campaign.FromName, campaign.FromEmail)}- // Create email record+ // Create email record. Assign the UUID up front so the per-recipient web+ // view link can be built before persisting.em := &models.Email{+ UUID: uuid.NewString(),UserID: campaign.UserID,WorkspaceID: campaign.WorkspaceID,Sender: sender,@@ -326,10 +329,21 @@ func (p *CampaignProcessor) HandleCampaignBatch(_ context.Context, t *asynq.Taskcontinue}- // Rewrite links for click tracking and inject open pixel- if p.trackingService != nil && em.HTMLBody != "" {- em.HTMLBody = p.trackingService.ProcessHTML(em.HTMLBody, campaign.ID, msg.ID)- em.ListUnsubscribeURL = p.trackingService.UnsubscribeURL(msg.ID)+ if p.trackingService != nil {+ // Resolve reserved {{ posta_* }} system links for this recipient. The+ // generated /t/ URLs are skipped by ProcessHTML's click rewriter, so+ // substitute before it runs.+ webViewURL := p.trackingService.WebViewURL(em.UUID)+ unsubscribeURL := p.trackingService.UnsubscribeURL(msg.ID)+ em.HTMLBody = email.SubstituteSystemLinks(em.HTMLBody, webViewURL, unsubscribeURL)+ em.TextBody = email.SubstituteSystemLinks(em.TextBody, webViewURL, unsubscribeURL)+ em.Subject = email.SubstituteSystemLinks(em.Subject, webViewURL, unsubscribeURL)++ // Rewrite links for click tracking and inject open pixel+ if em.HTMLBody != "" {+ em.HTMLBody = p.trackingService.ProcessHTML(em.HTMLBody, campaign.ID, msg.ID)+ }+ em.ListUnsubscribeURL = unsubscribeURLem.ListUnsubscribePost = true_ = p.emailRepo.Update(em)}@@ -435,6 +449,10 @@ func (p *CampaignProcessor) resolveTemplateContent(campaign *models.Campaign, laif campaign.TemplateData != nil {data = okapi.M(campaign.TemplateData)}+ // Inject reserved {{ posta_* }} variables as sentinels. The campaign render is+ // shared across recipients, so the real per-recipient URLs are substituted+ // later in the per-message loop.+ data = okapi.M(email.WithSystemVars(data))rendered, err := renderer.Render(&email.RenderInput{SubjectTemplate: loc.SubjectTemplate,