feat(postcard): sample values, file hashes, index sync and the draft editor

- sample.<path> header keys and a parse-tree walker that fills every other
  variable with a visible [path] placeholder, nested fields and range
  targets included
- every file entry carries the sha256 of its CRLF-normalized text; the
  catalog lists its files (Templates, Layouts, Partials) for admin code
- SyncIndex upserts one index row per file and never touches the override
  columns of a customized row; ResetOverride returns a row to its file
- Editor validates, previews and test-sends a template, layout or partial
  draft through the render path of Send and reports field and rule
- pact.RowStateCustomized and pact.RowStateOutdated

Plan 35-01, task 4.
This commit is contained in:
Jakub Zych
2026-11-13 10:57:05 +01:00
parent 5df1ec27cf
commit 495319ee21
11 changed files with 2128 additions and 42 deletions

View File

@@ -2,11 +2,15 @@ package postcard
import (
"bytes"
"crypto/sha256"
"embed"
"encoding/hex"
"errors"
"fmt"
"html/template"
"io/fs"
"regexp"
"sort"
"strings"
"sync"
texttemplate "text/template"
@@ -68,6 +72,9 @@ type parsedTemplate struct {
description string
layout string // short name from header; empty means default
body string
samples map[string]string // sample.<path> header keys by path
source string // the file's text, CRLF normalized to LF
hash string // sha256 of source, hex
}
type parsedLayout struct {
@@ -76,6 +83,8 @@ type parsedLayout struct {
headerName string
textWrap string
htmlWrap string
source string
hash string
}
// parsedPartial is a partial file: the layout file format, a header, a text
@@ -86,6 +95,8 @@ type parsedPartial struct {
headerName string
textWrap string
htmlWrap string
source string
hash string
}
// NewCatalog returns a catalog that already contains postcard's built-in
@@ -309,11 +320,12 @@ func assetPath(fullName string) (string, error) {
}
func parseTemplateFile(name, pluginID, src string) (*parsedTemplate, error) {
src = normalizeNewlines(src)
header, body, err := splitTwo(src)
if err != nil {
return nil, fmt.Errorf("postcard: parse %s: %w", name, err)
}
fields, err := parseINI(header)
fields, samples, err := parseHeader(header)
if err != nil {
return nil, fmt.Errorf("postcard: parse %s: %w", name, err)
}
@@ -324,10 +336,14 @@ func parseTemplateFile(name, pluginID, src string) (*parsedTemplate, error) {
description: fields["description"],
layout: fields["layout"],
body: strings.TrimSuffix(body, "\n"),
samples: samples,
source: src,
hash: fileHash(src),
}, nil
}
func parseLayout(name, pluginID, src string) (*parsedLayout, error) {
src = normalizeNewlines(src)
header, textWrap, htmlWrap, err := splitThree(src)
if err != nil {
return nil, fmt.Errorf("postcard: parse %s: %w", name, err)
@@ -342,15 +358,28 @@ func parseLayout(name, pluginID, src string) (*parsedLayout, error) {
headerName: fields["name"],
textWrap: strings.TrimSuffix(textWrap, "\n"),
htmlWrap: strings.TrimSuffix(htmlWrap, "\n"),
source: src,
hash: fileHash(src),
}, nil
}
func normalizeNewlines(src string) string {
return strings.ReplaceAll(src, "\r\n", "\n")
}
// fileHash is the hash an override's base_hash is compared with: sha256 of
// the file's text with CRLF normalized to LF, in hex.
func fileHash(normalized string) string {
sum := sha256.Sum256([]byte(normalized))
return hex.EncodeToString(sum[:])
}
func parsePartial(name, pluginID, src string) (*parsedPartial, error) {
l, err := parseLayout(name, pluginID, src)
if err != nil {
return nil, err
}
return &parsedPartial{name: l.name, pluginID: l.pluginID, headerName: l.headerName, textWrap: l.textWrap, htmlWrap: l.htmlWrap}, nil
return &parsedPartial{name: l.name, pluginID: l.pluginID, headerName: l.headerName, textWrap: l.textWrap, htmlWrap: l.htmlWrap, source: l.source, hash: l.hash}, nil
}
func splitTwo(src string) (header, body string, err error) {
@@ -370,7 +399,7 @@ func splitThree(src string) (header, textWrap, htmlWrap string, err error) {
}
func splitEQ(src string, n int) ([]string, error) {
src = strings.ReplaceAll(src, "\r\n", "\n")
src = normalizeNewlines(src)
lines := strings.Split(src, "\n")
parts := make([]string, 0, n)
start := 0
@@ -388,18 +417,28 @@ func splitEQ(src string, n int) ([]string, error) {
return nil, fmt.Errorf("missing == separator")
}
// parseINI reads a header's key = value lines. Keys are lower-cased.
func parseINI(header string) (map[string]string, error) {
fields, _, err := parseHeader(header)
return fields, err
}
// parseHeader reads a header's key = value lines into fields, with
// lower-cased keys, and its sample.<path> keys into samples by path. The
// path keeps its case, because template variables are case-sensitive.
func parseHeader(header string) (fields, samples map[string]string, err error) {
out := make(map[string]string)
for _, line := range strings.Split(header, "\n") {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, ";") || strings.HasPrefix(line, "#") {
continue
}
key, val, ok := strings.Cut(line, "=")
rawKey, val, ok := strings.Cut(line, "=")
if !ok {
return nil, fmt.Errorf("invalid header line %q", line)
return nil, nil, fmt.Errorf("invalid header line %q", line)
}
key = strings.ToLower(strings.TrimSpace(key))
rawKey = strings.TrimSpace(rawKey)
key := strings.ToLower(rawKey)
val = strings.TrimSpace(val)
if len(val) >= 2 {
if q := val[0]; (q == '"' || q == '\'') && val[len(val)-1] == q {
@@ -407,11 +446,20 @@ func parseINI(header string) (map[string]string, error) {
}
}
if key == "" {
return nil, fmt.Errorf("invalid header line %q", line)
return nil, nil, fmt.Errorf("invalid header line %q", line)
}
if strings.HasPrefix(key, samplePrefix) {
if path := rawKey[len(samplePrefix):]; path != "" {
if samples == nil {
samples = make(map[string]string)
}
samples[path] = val
}
continue
}
out[key] = val
}
return out, nil
return out, samples, nil
}
type renderOptions struct {
@@ -454,10 +502,71 @@ func (c *Catalog) render(msg Message, opts renderOptions) (RenderedMessage, erro
return c.renderFrom(msg, src, opts)
}
// The parts of a message a render can fail in.
const (
partSubject = "subject"
partBody = "body"
partLayout = "layout"
partLayoutText = "layout.text"
partLayoutHTML = "layout.html"
)
// renderError places a render failure in a part of the message. Its text is
// the failure's own.
type renderError struct {
part string
err error
}
func (e *renderError) Error() string { return e.err.Error() }
func (e *renderError) Unwrap() error { return e.err }
func inPart(part string, err error) error {
return &renderError{part: part, err: err}
}
// tmplError is a template that did not parse or did not execute. name is the
// template's name: a mail name plus .subject, .body, .text or .html.
type tmplError struct {
name string
parse bool
err error
}
func (e *tmplError) Error() string {
verb := "execute"
if e.parse {
verb = "parse"
}
return "postcard: " + verb + " " + e.name + ": " + e.err.Error()
}
func (e *tmplError) Unwrap() error { return e.err }
// unsafeError is rendered HTML that failed a safety check. snippet is the
// text that matched, with some of what surrounds it.
type unsafeError struct {
msg string
snippet string
}
func (e *unsafeError) Error() string { return "postcard: " + e.msg }
var errSubjectLine = errors.New("postcard: subject contains CR/LF")
// renderFrom renders src for msg. The caller's non-empty msg.Subject wins
// over src.subject.
func (c *Catalog) renderFrom(msg Message, src renderSource, opts renderOptions) (RenderedMessage, error) {
var out RenderedMessage
out, part, err := c.renderParts(msg, src, opts)
if err != nil {
return RenderedMessage{}, inPart(part, err)
}
return out, nil
}
// renderParts is renderFrom's work; with an error it returns the part of
// the message that failed.
func (c *Catalog) renderParts(msg Message, src renderSource, opts renderOptions) (out RenderedMessage, part string, err error) {
vars := msg.Vars
if vars == nil {
vars = map[string]any{}
@@ -468,30 +577,30 @@ func (c *Catalog) renderFrom(msg Message, src renderSource, opts renderOptions)
}
subject, err := execHTML(src.name+".subject", subjectSrc, vars)
if err != nil {
return out, err
return out, partSubject, err
}
if strings.ContainsAny(subject, "\r\n") {
return out, fmt.Errorf("postcard: subject contains CR/LF")
return out, partSubject, errSubjectLine
}
// Partial calls in the body leave tokens that are swapped for the
// rendered partials once Markdown has run; see partialRun.
partials := newPartialRun(c, opts.overrides.Partials)
markdownBody, err := execHTMLFuncs(src.name+".body", src.body, vars, template.FuncMap{"partial": partials.bodyCall})
if err != nil {
return out, err
return out, partBody, err
}
htmlBody, err := markdownHTML(markdownBody)
if err != nil {
return out, err
return out, partBody, err
}
htmlBody = partials.swapHTML(htmlBody)
textBody := partials.swapText(markdownBody)
if err := validateHTML(htmlBody); err != nil {
return out, err
return out, partBody, err
}
layout, err := c.layoutFor(src, opts)
if err != nil {
return out, err
return out, partLayout, err
}
// A layout's own CSS goes before mail.css in the css slot.
css := opts.css
@@ -508,7 +617,7 @@ func (c *Catalog) renderFrom(msg Message, src renderSource, opts renderOptions)
"brandCss": opts.brandCSS,
}, texttemplate.FuncMap{"partial": partials.textCall})
if err != nil {
return out, err
return out, partLayoutText, err
}
html, err := execHTMLFuncs(layout.name+".html", layout.htmlWrap, map[string]any{
"Content": template.HTML(htmlBody),
@@ -517,10 +626,10 @@ func (c *Catalog) renderFrom(msg Message, src renderSource, opts renderOptions)
"brandCss": template.CSS(opts.brandCSS),
}, template.FuncMap{"partial": partials.htmlCall})
if err != nil {
return out, err
return out, partLayoutHTML, err
}
if err := validateHTML(html); err != nil {
return out, err
return out, partLayoutHTML, err
}
out = RenderedMessage{
To: append([]string(nil), msg.To...),
@@ -531,7 +640,7 @@ func (c *Catalog) renderFrom(msg Message, src renderSource, opts renderOptions)
HTML: html,
Text: text,
}
return out, nil
return out, "", nil
}
// renderLayout is the layout one render uses: a file layout, a file layout
@@ -593,24 +702,28 @@ func markdownHTML(src string) (string, error) {
}
func validateHTML(html string) error {
if rawUnsafeTag.MatchString(html) {
return fmt.Errorf("postcard: rendered HTML contains raw unsafe tags")
if loc := rawUnsafeTag.FindStringIndex(html); loc != nil {
return &unsafeError{msg: "rendered HTML contains raw unsafe tags", snippet: snippetAt(html, loc)}
}
if eventHandler.MatchString(html) {
return fmt.Errorf("postcard: rendered HTML contains event handlers")
if loc := eventHandler.FindStringIndex(html); loc != nil {
return &unsafeError{msg: "rendered HTML contains event handlers", snippet: snippetAt(html, loc)}
}
if dangerousScheme.MatchString(html) {
return fmt.Errorf("postcard: rendered HTML contains a dangerous URL scheme")
if loc := dangerousScheme.FindStringIndex(html); loc != nil {
return &unsafeError{msg: "rendered HTML contains a dangerous URL scheme", snippet: snippetAt(html, loc)}
}
return nil
}
func execHTML(name, src string, data any) (string, error) {
return execHTMLFuncs(name, src, data, nil)
// snippetAt returns the match at loc with up to snippetContext bytes on
// either side, on one line.
func snippetAt(s string, loc []int) string {
const snippetContext = 24
start, end := max(loc[0]-snippetContext, 0), min(loc[1]+snippetContext, len(s))
return strings.Join(strings.Fields(strings.ToValidUTF8(s[start:end], "")), " ")
}
func execText(name, src string, data any) (string, error) {
return execTextFuncs(name, src, data, nil)
func execHTML(name, src string, data any) (string, error) {
return execHTMLFuncs(name, src, data, nil)
}
// execHTMLFuncs is execHTML with template funcs; they must be set before
@@ -618,11 +731,11 @@ func execText(name, src string, data any) (string, error) {
func execHTMLFuncs(name, src string, data any, funcs template.FuncMap) (string, error) {
tmpl, err := template.New(name).Option("missingkey=zero").Funcs(funcs).Parse(src)
if err != nil {
return "", fmt.Errorf("postcard: parse %s: %w", name, err)
return "", &tmplError{name: name, parse: true, err: err}
}
var buf bytes.Buffer
if err := tmpl.Execute(&buf, data); err != nil {
return "", fmt.Errorf("postcard: execute %s: %w", name, err)
return "", &tmplError{name: name, err: err}
}
return buf.String(), nil
}
@@ -630,11 +743,195 @@ func execHTMLFuncs(name, src string, data any, funcs template.FuncMap) (string,
func execTextFuncs(name, src string, data any, funcs texttemplate.FuncMap) (string, error) {
tmpl, err := texttemplate.New(name).Option("missingkey=zero").Funcs(funcs).Parse(src)
if err != nil {
return "", fmt.Errorf("postcard: parse %s: %w", name, err)
return "", &tmplError{name: name, parse: true, err: err}
}
var buf bytes.Buffer
if err := tmpl.Execute(&buf, data); err != nil {
return "", fmt.Errorf("postcard: execute %s: %w", name, err)
return "", &tmplError{name: name, err: err}
}
return buf.String(), nil
}
// TemplateFile is a registered template as its plugin ships it.
type TemplateFile struct {
Name string
PluginID string
Subject string
Description string
// Layout is the full name of the layout the file selects.
Layout string
Body string
// Samples holds the file's sample.<path> header keys by path.
Samples map[string]string
// Source is the file's text with CRLF normalized to LF.
Source string
// Hash is the sha256 of Source in hex.
Hash string
}
// LayoutFile is a registered layout as its plugin (or postcard) ships it.
type LayoutFile struct {
Name string
PluginID string
// Title is the name in the file's header.
Title string
Text string
HTML string
Source string
Hash string
}
// PartialFile is a registered partial as its plugin (or postcard) ships it.
type PartialFile struct {
Name string
PluginID string
// Title is the name in the file's header.
Title string
Text string
HTML string
Source string
Hash string
}
func (t *parsedTemplate) file() TemplateFile {
layout := t.layout
if layout == "" || layout == defaultLayoutAlias {
layout = defaultLayoutName
}
samples := make(map[string]string, len(t.samples))
for k, v := range t.samples {
samples[k] = v
}
return TemplateFile{
Name: t.name, PluginID: t.pluginID, Subject: t.subject, Description: t.description,
Layout: layout, Body: t.body, Samples: samples, Source: t.source, Hash: t.hash,
}
}
func (l *parsedLayout) file() LayoutFile {
return LayoutFile{Name: l.name, PluginID: l.pluginID, Title: l.headerName, Text: l.textWrap, HTML: l.htmlWrap, Source: l.source, Hash: l.hash}
}
func (p *parsedPartial) file() PartialFile {
return PartialFile{Name: p.name, PluginID: p.pluginID, Title: p.headerName, Text: p.textWrap, HTML: p.htmlWrap, Source: p.source, Hash: p.hash}
}
// Templates returns the registered templates, sorted by name.
func (c *Catalog) Templates() []TemplateFile {
c.mu.RLock()
defer c.mu.RUnlock()
out := make([]TemplateFile, 0, len(c.templates))
for _, t := range c.templates {
out = append(out, t.file())
}
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
return out
}
// Layouts returns the registered layouts, the built-in ones included,
// sorted by name.
func (c *Catalog) Layouts() []LayoutFile {
c.mu.RLock()
defer c.mu.RUnlock()
out := make([]LayoutFile, 0, len(c.layouts))
for _, l := range c.layouts {
out = append(out, l.file())
}
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
return out
}
// Partials returns the registered partials, the built-in ones included,
// sorted by name.
func (c *Catalog) Partials() []PartialFile {
c.mu.RLock()
defer c.mu.RUnlock()
out := make([]PartialFile, 0, len(c.partials))
for _, p := range c.partials {
out = append(out, p.file())
}
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
return out
}
// Template returns the registered template of that full name.
func (c *Catalog) Template(name string) (TemplateFile, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
t, ok := c.templates[name]
if !ok {
return TemplateFile{}, false
}
return t.file(), true
}
// Layout returns the registered layout of that full name.
func (c *Catalog) Layout(name string) (LayoutFile, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
l, ok := c.layouts[name]
if !ok {
return LayoutFile{}, false
}
return l.file(), true
}
// Partial returns the registered partial of that full name.
func (c *Catalog) Partial(name string) (PartialFile, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
p, ok := c.partials[name]
if !ok {
return PartialFile{}, false
}
return p.file(), true
}
// FormatTemplate writes a template's subject, layout and body in the file
// format: the header, a == line, the body. It gives a file version and an
// override the same shape, so the two can be compared line by line.
func FormatTemplate(subject, layout, body string) string {
return "subject = \"" + subject + "\"\nlayout = \"" + layout + "\"\n==\n" + body + "\n"
}
// FormatLayout writes a layout's name, text wrapper and HTML wrapper in the
// file format. A non-empty css is appended as a further section; layout
// files have none, so that form is for display and comparison only.
func FormatLayout(name, text, html, css string) string {
out := "name = \"" + name + "\"\n==\n" + text + "\n==\n" + html + "\n"
if css != "" {
out += "==\n" + css + "\n"
}
return out
}
// FormatPartial writes a partial's name, text section and HTML section in
// the file format.
func FormatPartial(name, text, html string) string {
return "name = \"" + name + "\"\n==\n" + text + "\n==\n" + html + "\n"
}
// TemplateLocale returns the locale a template name ends in: the suffix
// after a dash in the last dotted segment of the name, when it is one of
// locales, as acme.blog::mail.welcome-en is the en variant of
// acme.blog::mail.welcome. It returns "" for any other name, so a dashed
// name such as cancel-notice is not read as a locale. The match ignores
// case and the result is spelled as in locales.
func TemplateLocale(name string, locales []string) string {
_, rest, ok := strings.Cut(name, "::")
if !ok {
return ""
}
segment := rest[strings.LastIndex(rest, ".")+1:]
best := ""
for _, locale := range locales {
if locale == "" || len(segment) <= len(locale)+1 || len(locale) <= len(best) {
continue
}
cut := len(segment) - len(locale)
if segment[cut-1] == '-' && strings.EqualFold(segment[cut:], locale) {
best = locale
}
}
return best
}