forms

package
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 24, 2026 License: AGPL-3.0 Imports: 49 Imported by: 0

Documentation

Overview

Package forms implements signup forms and the settings of the public pages (spec 5.12, 7.12): embedded, popup and hosted forms, the embed script, spam protection, the submission pipeline the public pages call, double opt-in emails on the System stream, and the pages' branding, custom domain and Turnstile keys.

Contacts, lists, consent and suppressions are written through the audience package; the pages themselves are rendered by internal/publicpages.

Index

Constants

View Source
const (
	KindEmbedded = "embedded"
	KindPopup    = "popup"
	KindHosted   = "hosted"

	StatusDraft  = "draft"
	StatusLive   = "live"
	StatusPaused = "paused"
)

Form kinds and statuses.

View Source
const (
	FieldEmail     = "email"
	FieldFirstName = "first_name"
	FieldLastName  = "last_name"
	FieldCompany   = "company"
)

Built-in fields every form can show; custom fields come from the audience.

View Source
const (
	OutcomeConfirm     = "confirm"      // check your inbox (double opt-in)
	OutcomeSubscribed  = "subscribed"   // single opt-in, done
	OutcomeInvalid     = "invalid"      // fix the fields
	OutcomeChallenge   = "challenge"    // prove you're a person (Turnstile)
	OutcomeRejected    = "rejected"     // origin not allowed, spam
	OutcomeRateLimited = "rate_limited" // too many tries
	OutcomeClosed      = "closed"       // form paused or not published
	OutcomeError       = "error"        // couldn't save; nothing was lost
)

Outcome statuses.

View Source
const ArchivePageSize = 10

ArchivePageSize is how many issues an archive page lists.

View Source
const MaxLogoBytes = 256 << 10

MaxLogoBytes bounds an uploaded logo.

View Source
const TurnstileOrigin = "https://challenges.cloudflare.com"

TurnstileOrigin is allowed in the challenge page's CSP.

View Source
const TurnstileScript = "https://challenges.cloudflare.com/turnstile/v0/api.js"

TurnstileScript is the widget script a challenge page loads (only when a submission looked automated; the pages load no third-party code otherwise).

Variables

View Source
var EmbedCSSVersion = func() string {
	sum := sha256.Sum256(embedCSS)
	return hex.EncodeToString(sum[:6])
}()

EmbedCSSVersion changes with the stylesheet (cache busting).

View Source
var SiteverifyURL = "https://challenges.cloudflare.com/turnstile/v0/siteverify"

SiteverifyURL is Cloudflare Turnstile's server-side verification endpoint (a variable so tests can point it at a fake).

Functions

func ConfirmationEmail

func ConfirmationEmail(b Branding, firstName string, lists []string, link string, reminder bool) mailer.Message

ConfirmationEmail is the double opt-in email: plain text and a small HTML version in the publisher's colours, no tracking.

func Contrast

func Contrast(a, b rgb) float64

Contrast is the WCAG contrast ratio of two colours (1 to 21).

func DefaultConsentText

func DefaultConsentText(publisher string) string

DefaultConsentText is the consent sentence of a new form.

func EmbedCSS

func EmbedCSS() []byte

EmbedCSS is the stylesheet of embedded and popup forms (/p/_/embed.css).

func EmbedScript

func EmbedScript(c Config, links PageLinks, b Branding, lists []audience.PublicList, customs []store.CustomField) []byte

EmbedScript is the script of a form (/p/{workspace}/forms/{id}.js): the renderer with the form's configuration. It holds no personal data.

func Excerpt

func Excerpt(text string, n int) string

Excerpt shortens a plain-text body to about n characters at a word boundary.

func FieldLabel

func FieldLabel(f fieldDoc, customs []store.CustomField) string

FieldLabel is the label a field shows.

func FieldName

func FieldName(key string) string

FieldName is the name of a field in a form post: built-ins by key, custom fields as "f.<key>".

func IsNoSystemMail

func IsNoSystemMail(err error) bool

IsNoSystemMail reports that System mail can't go out yet.

func IssueLabel

func IssueLabel(name string) string

IssueLabel is the label a new archive entry gets from its campaign's name: "Weekly Digest #141" is issue "#141".

func NormalizeOrigin

func NormalizeOrigin(raw string) (string, bool)

NormalizeOrigin turns "https://Docs.Acme.io/path" or "docs.acme.io" into the host an origin is matched on ("docs.acme.io", with ":port" when set).

func OriginAllowed

func OriginAllowed(host string, allowed, own []string) bool

OriginAllowed reports whether a form accepts submissions from host: its allowed domains, the instance and the custom domain. Ports must match when an allowed entry names one.

func OriginHost

func OriginHost(origin, referer string) string

OriginHost reads the host a browser request came from: the Origin header, else the Referer. Empty when neither is sent (not a browser form post).

func ParseColor

func ParseColor(s string) (rgb, bool)

ParseColor reads "#4338CA" or "#43C" (any case).

func PlainHTML

func PlainHTML(c Config, links PageLinks, lists []audience.PublicList, customs []store.CustomField, b Branding) string

PlainHTML is the form as plain HTML for sites that can't load scripts. It posts to the hosted page, which answers with the result page.

func PrivacyPolicyIndex

func PrivacyPolicyIndex(text string) int

PrivacyPolicyIndex finds "privacy policy" in a consent sentence, in any letter case, and returns its byte offset in text, or -1. The phrase is ASCII, so the search compares bytes and the offset always points into text itself (lowercasing first would shift it for letters whose lowercase form has another UTF-8 length, like "İ").

func Register

func Register(h huma.API, s *Service)

Register adds the forms and public page settings operations.

func RegisterJobs

func RegisterJobs(reg *jobs.Registry, s *Service)

RegisterJobs adds the forms workers and their schedules.

func RenderTitle

func RenderTitle(subject string) string

RenderTitle renders a subject for a reader without a contact: Liquid tokens get their fallbacks ("{{ first_name | default: "there" }}").

func Slugify

func Slugify(name string, max int) string

Slugify turns a name into a URL segment ("Newsletter signup" → "newsletter-signup").

Types

type ArchiveEntry

type ArchiveEntry struct {
	CampaignID uuid.UUID
	Slug       string
	ListID     *uuid.UUID
	ListName   string
	// Title and Excerpt are the publisher's when set, else the subject and
	// the preheader (or the start of the text).
	Title, Excerpt, Label string
	Subject               string
	// TitleOverride and ExcerptOverride are what the publisher wrote.
	TitleOverride, ExcerptOverride string
	Hidden                         bool
	SentAt, UpdatedAt              time.Time
}

ArchiveEntry is an issue as the archive lists it.

type ArchiveIssueInput

type ArchiveIssueInput struct {
	Hidden  bool   `json:"hidden" doc:"Hide the issue from the archive, the feed and the sitemap"`
	Title   string `json:"title" maxLength:"200" doc:"Empty uses the subject"`
	Excerpt string `json:"excerpt" maxLength:"500" doc:"Empty uses the preheader"`
	Label   string `json:"label" maxLength:"40" example:"#141"`
	ListID  string `json:"listId" doc:"The list the issue is filed under"`
}

ArchiveIssueInput edits an issue on the Archive tab.

type ArchiveIssueItem

type ArchiveIssueItem struct {
	CampaignID string    `json:"campaignId"`
	Slug       string    `json:"slug"`
	URL        string    `json:"url"`
	ListID     string    `json:"listId"`
	ListName   string    `json:"listName"`
	Title      string    `json:"title"`
	Excerpt    string    `json:"excerpt"`
	Label      string    `json:"label"`
	Subject    string    `json:"subject"`
	Hidden     bool      `json:"hidden"`
	SentAt     time.Time `json:"sentAt"`
	// TitleOverride and ExcerptOverride are what the publisher wrote; empty
	// uses the subject and the preheader.
	TitleOverride   string `json:"titleOverride"`
	ExcerptOverride string `json:"excerptOverride"`
}

ArchiveIssueItem is an issue on the Archive tab.

type ArchiveIssuePage

type ArchiveIssuePage struct {
	Issues   []ArchiveIssueItem `json:"issues"`
	Total    int64              `json:"total"`
	Page     int                `json:"page"`
	PageSize int                `json:"pageSize"`
	// Published counts the issues readers see; Lists breaks them down.
	Published int64              `json:"published"`
	Lists     []ArchiveListCount `json:"lists"`
}

ArchiveIssuePage is a page of the Archive tab's issues.

type ArchiveListCount

type ArchiveListCount struct {
	ListID string `json:"listId"`
	Name   string `json:"name"`
	Issues int64  `json:"issues"`
}

ArchiveListCount is how many published issues a list has.

type ArchivePage

type ArchivePage struct {
	Enabled bool `json:"enabled"`
	// Lists whose sent campaigns are published (by id); empty uses every public list.
	Lists        []string `json:"lists"`
	SubscribeBox bool     `json:"subscribeBox"`
	Index        bool     `json:"index"`
}

ArchivePage are the public archive's options.

type ArchiveQuery

type ArchiveQuery struct {
	Search string
	List   *uuid.UUID
	// Page counts from 1.
	Page          int
	PageSize      int
	IncludeHidden bool
}

ArchiveQuery filters the archive.

type Branding

type Branding struct {
	PublisherName    string
	Palette          Palette
	Font             string
	CustomFontFamily string
	CustomFontURL    string
	PoweredBy        bool
	PrivacyURL       string
}

Branding is how a workspace's public pages look, with defaults filled.

func (Branding) FontFace

func (b Branding) FontFace() string

FontFace is the @font-face rule of a custom web font ("" otherwise).

func (Branding) FontOrigin

func (b Branding) FontOrigin() string

FontOrigin is the origin a custom web font loads from ("" for the built-in fonts).

func (Branding) FontStack

func (b Branding) FontStack() string

FontStack is the CSS font-family of the pages.

func (Branding) Initial

func (b Branding) Initial() string

Initial is the letter on the logo tile when there is no logo.

type ChallengeForm

type ChallengeForm func(ctx context.Context, formID string, builtin bool) (Config, error)

ChallengeForm returns the form a held submission belongs to.

type Config

type Config struct {
	ID             uuid.UUID
	WorkspaceID    uuid.UUID
	Name           string
	Kind           string
	Slug           string
	PublicID       string
	Status         string
	Fields         []fieldDoc
	Lists          []uuid.UUID
	DefaultLists   []uuid.UUID
	ListChoice     bool
	DoubleOptIn    bool
	ConsentText    string
	ConsentVersion int
	Content        contentDoc
	Spam           spamDoc
	AllowedOrigins []string
	AfterSubmit    string
	RedirectURL    string
	// Builtin is the hosted page's form when the workspace has none.
	Builtin bool
}

Config is a form as the submission pipeline and the pages read it.

func BuiltinForm

func BuiltinForm(ws *store.Workspace, publisher string, lists []audience.PublicList) Config

BuiltinForm is the hosted page's form for a workspace that hasn't made one: email and first name, every public list, double opt-in.

func ConfigOf

func ConfigOf(f store.Form) Config

ConfigOf reads a stored form.

func (Config) ConsentVersionLabel

func (c Config) ConsentVersionLabel() string

ConsentVersionLabel is the version stored with consent events ("v3").

func (Config) Field

func (c Config) Field(key string) (fieldDoc, bool)

func (Config) HasField

func (c Config) HasField(key string) bool

HasField reports whether the form shows a field.

func (Config) Source

func (c Config) Source() string

Source is the consent and contact source of the form's signups.

type ConfirmPage

type ConfirmPage struct {
	// ListText says what each list sends and when ("Tuesdays at 09:00 your
	// time."); the next scheduled issue is added after it.
	ListText map[string]string `json:"listText"`
	// OfferText names what a list the contact isn't on brings ("release
	// news"): "Add it if you'd like release news too."
	OfferText map[string]string `json:"offerText"`
	// InboxTip asks to add the sender to the contacts.
	InboxTip bool `json:"inboxTip"`
}

ConfirmPage are the options of the page after the confirmation click.

type ConfirmationsArgs

type ConfirmationsArgs struct{}

ConfirmationsArgs sends double opt-in emails that couldn't go out at submission time, reminds contacts who didn't click within 24 hours, and drops expired Turnstile holds.

func (ConfirmationsArgs) InsertOpts

func (ConfirmationsArgs) InsertOpts() river.InsertOpts

InsertOpts runs on the System queue, one run at a time.

func (ConfirmationsArgs) Kind

func (ConfirmationsArgs) Kind() string

Kind implements river.JobArgs.

type ConfirmationsWorker

type ConfirmationsWorker struct {
	river.WorkerDefaults[ConfirmationsArgs]
	S *Service
}

func (*ConfirmationsWorker) Work

Work implements river.Worker.

type DomainsArgs

type DomainsArgs struct{}

DomainsArgs checks custom domains: pending ones on every run, verified ones once a day.

func (DomainsArgs) InsertOpts

func (DomainsArgs) InsertOpts() river.InsertOpts

InsertOpts runs on the maintenance queue.

func (DomainsArgs) Kind

func (DomainsArgs) Kind() string

Kind implements river.JobArgs.

type DomainsWorker

type DomainsWorker struct {
	river.WorkerDefaults[DomainsArgs]
	S *Service
}

func (*DomainsWorker) Work

Work implements river.Worker.

type FormPath

type FormPath struct {
	api.WorkspaceInput
	Form string `path:"form" format:"uuid" doc:"Form id"`
}

FormPath names a form in the path. It is exported because Huma only reads parameters through exported embedded structs.

type Outcome

type Outcome struct {
	Status string `json:"status"`
	// Errors are messages per field (email, first_name, lists, consent, a custom key).
	Errors map[string]string `json:"errors,omitempty"`
	// Message is the form-level message.
	Message     string `json:"message,omitempty"`
	RedirectURL string `json:"redirect,omitempty"`
	// ChallengeID names the held submission waiting for Turnstile.
	ChallengeID string `json:"challenge,omitempty"`
	// Email and FirstName are echoed on the "check your inbox" page.
	Email     string      `json:"-"`
	FirstName string      `json:"-"`
	Lists     []uuid.UUID `json:"-"`
}

Outcome tells the page what to show after a submission.

type PageLinks struct {
	Custom bool
	// contains filtered or unexported fields
}

PageLinks builds the links of a workspace's public pages, either on its verified custom domain (news.acme.io/subscribe) or on the instance (reputecast.acme.io/p/acme-newsletter/subscribe). Form scripts and submissions always use /p/{workspace}/forms/… on whichever host.

func LinksOn

func LinksOn(origin, slug string, custom bool) PageLinks

LinksOn returns links on an origin: the custom domain's ("https://news.acme.io") or the instance's.

func (PageLinks) Archive

func (l PageLinks) Archive() string

func (PageLinks) Challenge

func (l PageLinks) Challenge() string

Challenge receives Turnstile answers.

func (PageLinks) Confirm

func (l PageLinks) Confirm(token string) string

Confirm, Preferences, Unsubscribe and View are the token pages.

func (PageLinks) Feed

func (l PageLinks) Feed() string

func (PageLinks) FormSession

func (l PageLinks) FormSession(publicID string) string

func (PageLinks) Home

func (l PageLinks) Home() string

Home is the root of the pages ("/" on a custom domain, the subscribe page otherwise).

func (PageLinks) Issue

func (l PageLinks) Issue(slug string) string
func (l PageLinks) Logo(version string) string

Logo is the uploaded logo.

func (PageLinks) Origin

func (l PageLinks) Origin() string

Origin is "https://news.acme.io".

func (PageLinks) PlainAction

func (l PageLinks) PlainAction(slug string) string

PlainAction is where the plain HTML form posts: always under /p/ so the cross-site post reaches the form whichever site it sits on.

func (PageLinks) Preferences

func (l PageLinks) Preferences(token string) string

func (PageLinks) PreferencesRequest

func (l PageLinks) PreferencesRequest() string

PreferencesRequest asks for a preference link by email.

func (PageLinks) Script

func (l PageLinks) Script(publicID string) string

func (PageLinks) Sitemap

func (l PageLinks) Sitemap() string

func (PageLinks) Static

func (l PageLinks) Static(file string) string

Static is a file of the shared public assets (stylesheet, fonts, scripts).

func (PageLinks) Submit

func (l PageLinks) Submit(publicID string) string

func (PageLinks) Subscribe

func (l PageLinks) Subscribe(form string) string

Subscribe is the hosted page of a form ("" for the workspace's page).

func (PageLinks) Theme

func (l PageLinks) Theme(version string) string

Theme is the workspace's colours and font as a stylesheet.

func (PageLinks) TurnstileError

func (l PageLinks) TurnstileError() string

TurnstileError receives errors of the Turnstile widget.

func (PageLinks) Unsubscribe

func (l PageLinks) Unsubscribe(token string) string

func (PageLinks) View

func (l PageLinks) View(token string) string

type Pages

type Pages struct {
	Subscribe   SubscribePage   `json:"subscribe"`
	Confirm     ConfirmPage     `json:"confirm"`
	Preferences PreferencesPage `json:"preferences"`
	Unsubscribe UnsubscribePage `json:"unsubscribe"`
	Archive     ArchivePage     `json:"archive"`
	// PreviewEmail is the subscriber the app previews the pages for; empty
	// uses whoever confirmed a subscription last.
	PreviewEmail string `json:"previewEmail"`
}

Pages are every public page's options.

type Palette

type Palette struct {
	Accent     string `json:"accent"`
	Background string `json:"background"`
	// Hover darkens buttons and links; it is also the text on tinted panels.
	Hover string `json:"accentHover"`
	// Soft tints borders and chips (the confirmation tick, the active archive filter).
	Soft string `json:"accentSoft"`
	// Text is the accent as link text: at least 4.5:1 on white and on the background.
	Text string `json:"accentText"`
	// OnAccent is the text on accent buttons: white, or ink when white fails 4.5:1.
	OnAccent string `json:"onAccent"`
	// Notes say what was adjusted for contrast.
	Notes []string `json:"notes"`
}

Palette is what the public pages derive from the publisher's colours.

func DerivePalette

func DerivePalette(accent, background string) (Palette, error)

DerivePalette computes the colours of the public pages from an accent and a page background, keeping every text at WCAG 2.2 AA contrast.

type PreferencesPage

type PreferencesPage struct {
	// Lists offered (by id); empty offers every public list.
	Lists     []string          `json:"lists"`
	ListText  map[string]string `json:"listText"`
	Frequency bool              `json:"frequency"`
	Pause     bool              `json:"pause"`
	FirstName bool              `json:"firstName"`
}

PreferencesPage are the preference center's options.

type PublicBranding

type PublicBranding struct {
	PublisherName    string              `json:"publisherName"`
	Accent           string              `json:"accent"`
	Background       string              `json:"background"`
	AccentHover      string              `json:"accentHover"`
	AccentSoft       string              `json:"accentSoft"`
	AccentText       string              `json:"accentText"`
	OnAccent         string              `json:"onAccent"`
	Font             string              `json:"font" enum:"plex,system,custom"`
	CustomFontFamily string              `json:"customFontFamily"`
	CustomFontURL    string              `json:"customFontUrl"`
	PoweredBy        bool                `json:"poweredBy" doc:"Show \"Sent with ReputeCast\" in the footer"`
	PrivacyURL       string              `json:"privacyUrl"`
	Initial          string              `json:"initial" doc:"The letter on the logo tile when there is no logo"`
	// Notes say what was adjusted to keep text readable.
	Notes []string `json:"notes"`
}

PublicBranding is the Branding card.

type PublicBrandingInput

type PublicBrandingInput struct {
	PublisherName    string `json:"publisherName" minLength:"1" maxLength:"80"`
	Accent           string `json:"accent" pattern:"^#[0-9a-fA-F]{6}$" example:"#4338CA"`
	Background       string `json:"background" pattern:"^#[0-9a-fA-F]{6}$" example:"#F5F3FF"`
	Font             string `json:"font" enum:"plex,system,custom"`
	CustomFontFamily string `json:"customFontFamily,omitempty" maxLength:"80"`
	CustomFontURL    string `json:"customFontUrl,omitempty" maxLength:"500" doc:"https URL of a .woff2 or .woff file"`
	PoweredBy        bool   `json:"poweredBy"`
	PrivacyURL       string `json:"privacyUrl,omitempty" maxLength:"500"`
}

PublicBrandingInput saves the Branding card.

type PublicBrandingLogo struct {
	Name string `json:"name" example:"acme-mark.svg"`
	Type string `json:"type" example:"image/svg+xml"`
	URL  string `json:"url"`
}

PublicBrandingLogo is the uploaded logo.

type PublicCustomDomain

type PublicCustomDomain struct {
	Domain     string     `json:"domain" example:"news.acme.io"`
	Status     string     `json:"status" enum:"none,pending,verified,failed"`
	Detail     string     `json:"detail"`
	CheckedAt  *time.Time `json:"checkedAt,omitempty"`
	VerifiedAt *time.Time `json:"verifiedAt,omitempty"`
	// Target is the host the domain's CNAME record points at.
	Target string `json:"target" example:"reputecast.acme.io"`
	// TXTName and TXTValue are the alternative proof for domains that can't use a CNAME.
	TXTName  string `json:"txtName"`
	TXTValue string `json:"txtValue"`
}

PublicCustomDomain is the custom domain and its DNS check.

type PublicDomainInput

type PublicDomainInput struct {
	Domain string `json:"domain" maxLength:"253" example:"news.acme.io" doc:"Empty removes the custom domain"`
}

PublicDomainInput sets or clears the custom domain.

type PublicPageInput

type PublicPageInput struct {
	Subscribe   *SubscribePage   `json:"subscribe,omitempty"`
	Confirm     *ConfirmPage     `json:"confirm,omitempty"`
	Preferences *PreferencesPage `json:"preferences,omitempty"`
	Unsubscribe *UnsubscribePage `json:"unsubscribe,omitempty"`
	Archive     *ArchivePage     `json:"archive,omitempty"`
	// HostedFormID picks the form behind the subscribe page ("" for the built-in form).
	HostedFormID *string `json:"hostedFormId,omitempty"`
	// PreviewEmail changes whose pages the app previews ("" for the latest confirmation).
	PreviewEmail *string `json:"previewEmail,omitempty" maxLength:"320"`
}

PublicPageInput saves one page's options; only the page named in the path is read.

type PublicPageList

type PublicPageList struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description"`
	Public      bool   `json:"public"`
	Subscribed  int64  `json:"subscribed"`
}

PublicPageList is a list as the page settings show it.

type PublicPageURLs

type PublicPageURLs struct {
	Subscribe   string `json:"subscribe"`
	Preferences string `json:"preferences" doc:"Asks for a preference link by email"`
	Archive     string `json:"archive"`
	Feed        string `json:"feed"`
	Sitemap     string `json:"sitemap"`
}

PublicPageURLs are where the pages live.

type PublicPagesSettings

type PublicPagesSettings struct {
	Branding PublicBranding     `json:"branding"`
	Domain   PublicCustomDomain `json:"domain"`
	Pages    Pages              `json:"pages"`
	// HostedFormID is the form behind the subscribe page; empty uses the built-in form.
	HostedFormID string              `json:"hostedFormId"`
	Forms        []SignupFormSummary `json:"forms"`
	Lists        []PublicPageList    `json:"lists"`
	URLs         PublicPageURLs      `json:"urls"`
	Turnstile    PublicTurnstile     `json:"turnstile"`
	// SenderEmail is the default sender, for the inbox tip on the confirmation page.
	SenderEmail string    `json:"senderEmail"`
	UpdatedAt   time.Time `json:"updatedAt"`
}

PublicPagesSettings feeds the Subscribe page, Preference center, Unsubscribe page, Archive and Branding tabs.

type PublicTurnstile

type PublicTurnstile struct {
	SiteKey   string     `json:"siteKey"`
	HasSecret bool       `json:"hasSecret"`
	Status    string     `json:"status" enum:"off,ok,error"`
	Error     string     `json:"error" doc:"Why Cloudflare rejected the keys, with its error code"`
	CheckedAt *time.Time `json:"checkedAt,omitempty"`
}

PublicTurnstile is the Turnstile set-up (the secret is never returned).

type PublicTurnstileInput

type PublicTurnstileInput struct {
	SiteKey string `json:"siteKey" minLength:"1" maxLength:"100" example:"0x4AAAAAAA…"`
	Secret  string `json:"secret,omitempty" maxLength:"200" doc:"Write-only; omit to keep the stored secret"`
}

PublicTurnstileInput saves the Turnstile keys. An empty secret keeps the stored one (secrets are write-only and never shown again).

type Service

type Service struct {
	Pool     *pgxpool.Pool
	Q        *store.Queries
	Audit    *audit.Logger
	Log      *slog.Logger
	Audience *audience.Service
	Box      *secrets.Box
	// Mail sends double opt-in confirmations on the System stream (App.Mail,
	// read at call time: the system mailer is wired after the services).
	Mail   func() mailer.Sender
	Tokens *linktoken.Signer
	URLs   publicurl.Builder
	// DNS verifies custom domains.
	DNS dnscheck.Resolver
	// Turnstile verifies challenge tokens with Cloudflare.
	Turnstile *Turnstile
	Now       func() time.Time
	// contains filtered or unexported fields
}

Service holds the forms domain dependencies.

func (*Service) Allow

func (s *Service) Allow(key string, every time.Duration) bool

Allow takes one request from key's bucket, which refills once every interval (one preference link per address every ten minutes).

func (*Service) AllowOrigin

func (s *Service) AllowOrigin(ctx context.Context, ws *store.Workspace, id string, in SignupFormOriginInput) (SignupForm, error)

AllowOrigin adds a site to a form's allowed domains (the "Allow staging.acme.io" action of the blocked-origin alert).

func (*Service) AllowPerMinute

func (s *Service) AllowPerMinute(key string, n int) bool

AllowPerMinute takes one request from key's bucket of n a minute.

func (*Service) Archive

func (s *Service) Archive(ctx context.Context, ws *store.Workspace, set *Settings, aq ArchiveQuery) ([]ArchiveEntry, int64, error)

Archive lists the archive's issues, newest first, with the total.

func (*Service) ArchiveIssues

func (s *Service) ArchiveIssues(ctx context.Context, ws *store.Workspace, search, list string, page int) (ArchiveIssuePage, error)

ArchiveIssues lists the archive for the Archive tab, hidden issues included.

func (*Service) ArchiveLists

func (s *Service) ArchiveLists(ctx context.Context, q *store.Queries, ws *store.Workspace, set *Settings) ([]uuid.UUID, error)

ArchiveLists are the lists whose sent campaigns the archive publishes: the ones picked on the Archive tab, or every public list.

func (*Service) CheckDomain

func (s *Service) CheckDomain(ctx context.Context, ws *store.Workspace) (PublicPagesSettings, error)

CheckDomain runs the DNS check now ("Check DNS").

func (*Service) Confirm

Confirm completes double opt-in for a contact from the confirmation link: the audience confirms the pending lists; the forms they came from count the confirmation on the day of the submission and start their "form submitted" automations.

func (*Service) ConfirmURL

func (s *Service) ConfirmURL(ws *store.Workspace, contactID uuid.UUID) string

ConfirmURL is the double opt-in link of a contact (App.URLs.Confirm).

func (*Service) Create

Create adds a draft form with sensible defaults: email and first name, the first public list, double opt-in and every spam check.

func (*Service) Delete

func (s *Service) Delete(ctx context.Context, ws *store.Workspace, id string) error

Delete removes a form. Contacts it brought in stay; automations started by it show that their trigger form is gone.

func (*Service) FormToken

func (s *Service) FormToken(formKey string, at time.Time) string

FormToken signs when a form was rendered, for one form. It is the CSRF token of the hosted page and the timing check of every form: a submission needs a token at least MinSeconds old and at most a day old. It is sealed with the instance key, so it can't be forged or moved to another form.

func (*Service) Get

func (s *Service) Get(ctx context.Context, ws *store.Workspace, id string) (SignupForm, error)

Get returns one form with its numbers.

func (*Service) HostVerified

func (s *Service) HostVerified(ctx context.Context, host string) bool

HostVerified reports whether host is any workspace's verified custom domain (the "ask" endpoint of on-demand TLS in Caddy and similar proxies).

func (*Service) KeepBlocked

func (s *Service) KeepBlocked(ctx context.Context, ws *store.Workspace, id string, in SignupFormOriginInput) (SignupForm, error)

KeepBlocked dismisses a blocked-origin alert ("Keep blocked"): the site stays rejected and the alert stays away until it submits again tomorrow.

func (s *Service) Links(ws *store.Workspace, set *Settings) PageLinks

Links are the preferred (canonical) links of a workspace: its verified custom domain when it has one.

func (*Service) LoadSettings

func (s *Service) LoadSettings(ctx context.Context, ws *store.Workspace) (*Settings, error)

LoadSettings reads (and creates on first use) a workspace's settings.

func (s *Service) Logo(ctx context.Context, ws *store.Workspace) ([]byte, string, time.Time, error)

Logo returns the logo bytes for the public pages.

func (*Service) Overview

func (s *Service) Overview(ctx context.Context, ws *store.Workspace) (SignupFormsOverview, error)

Overview lists the forms and what the builder needs around them.

func (*Service) OwnOrigins

func (s *Service) OwnOrigins(set *Settings) []string

OwnOrigins are the hosts that may always submit a form: the instance and the verified custom domain.

func (*Service) PublicPages

func (s *Service) PublicPages(ctx context.Context, ws *store.Workspace) (PublicPagesSettings, error)

PublicPages returns every public page setting.

func (*Service) RecordView

func (s *Service) RecordView(ctx context.Context, ws *store.Workspace, c Config, userAgent string)

RecordView counts a view of a form (the hosted page, or an embed asking for its token). Crawlers and link previews don't count.

func (s *Service) RemoveLogo(ctx context.Context, ws *store.Workspace) (PublicPagesSettings, error)

RemoveLogo goes back to the letter tile.

func (*Service) RemoveTurnstile

func (s *Service) RemoveTurnstile(ctx context.Context, ws *store.Workspace) (PublicPagesSettings, error)

RemoveTurnstile deletes the keys: suspicious submissions are then refused.

func (*Service) Rename

Rename changes a form's name and the slug of its hosted page.

func (*Service) ReportTurnstileError

func (s *Service) ReportTurnstileError(ctx context.Context, ws *store.Workspace, challengeID, code string) error

ReportTurnstileError records an error the widget showed on a challenge page (a site key Cloudflare doesn't accept for this domain). Reports count only from the page of a submission still held for its check, so nobody can switch Turnstile off from outside.

func (*Service) RunConfirmations

func (s *Service) RunConfirmations(ctx context.Context) error

RunConfirmations is one pass of the confirmations job.

func (*Service) SaveBranding

SaveBranding stores the branding and the colours derived from it.

func (*Service) SavePage

SavePage stores the options of one or more pages.

func (*Service) SaveTurnstile

SaveTurnstile stores the keys and checks the secret with Cloudflare.

func (s *Service) SendPreferenceLink(ctx context.Context, ws *store.Workspace, set *Settings, contactID uuid.UUID) error

SendPreferenceLink emails a contact the link to their preference center ("Send me a link" on the public preferences page).

func (*Service) SetDomain

SetDomain stores the custom domain and checks its DNS right away.

func (*Service) SetStatus

SetStatus pauses a live form (submissions are refused) or makes it live.

func (*Service) SolveChallenge

func (s *Service) SolveChallenge(ctx context.Context, ws *store.Workspace, set *Settings, challengeID, answer string, ip *netip.Addr, formOf ChallengeForm) Outcome

SolveChallenge verifies a Turnstile answer for a held submission and, when Cloudflare agrees, completes it.

func (*Service) Submit

func (s *Service) Submit(ctx context.Context, ws *store.Workspace, set *Settings, c Config, sub Submission) Outcome

Submit runs a public submission through the form's checks and, when it passes, subscribes the contact through the audience package. A filled honeypot is dropped silently, so bots see a success. Copied plain HTML forms can't carry a timestamp token and rely on the origin allowlist. A submission that fails only the token checks goes to a Turnstile challenge when Turnstile is set up.

func (*Service) SyncArchive

func (s *Service) SyncArchive(ctx context.Context, ws *store.Workspace, set *Settings) error

SyncArchive files the sent campaigns of the archived lists that have no archive entry yet. It is cheap when nothing is missing, and serialized per workspace so two requests never hand out the same slug.

func (*Service) SystemMailAvailable

func (s *Service) SystemMailAvailable(ctx context.Context, ws *store.Workspace) bool

SystemMailAvailable reports whether System mail can go out for ws.

func (*Service) UnsubscribeNumbers

func (s *Service) UnsubscribeNumbers(ctx context.Context, ws *store.Workspace) (UnsubscribeStats, error)

UnsubscribeNumbers counts the last 30 days of the unsubscribe page.

func (*Service) Update

func (s *Service) Update(ctx context.Context, ws *store.Workspace, id string, in SignupFormInput) (SignupForm, error)

Update saves the builder ("Save & publish").

func (*Service) UpdateArchiveIssue

func (s *Service) UpdateArchiveIssue(ctx context.Context, ws *store.Workspace, campaignID string, in ArchiveIssueInput) (ArchiveIssueItem, error)

UpdateArchiveIssue saves an issue's archive settings.

func (s *Service) UploadLogo(ctx context.Context, ws *store.Workspace, name string, data []byte) (PublicPagesSettings, error)

UploadLogo stores the publisher's logo.

func (*Service) Waiting

func (s *Service) Waiting(ctx context.Context, ws *store.Workspace, id string) (SignupFormWaiting, error)

Waiting lists a form's signups waiting for their confirmation email.

func (s *Service) WaitingLink(ctx context.Context, ws *store.Workspace, formID, submissionID string) (SignupFormConfirmLink, error)

WaitingLink returns the confirmation link of a waiting signup, to send by hand. Handing out a link that subscribes someone is written to the audit log; the confirmation itself records who clicked, from where, as always.

func (*Service) WithDraft

func (s *Service) WithDraft(ctx context.Context, set *Settings, in PublicPageInput) (*Settings, error)

WithDraft is a copy of the settings with unsaved page options laid over them, for previews. Nothing is stored.

func (*Service) WorkspaceForHost

func (s *Service) WorkspaceForHost(ctx context.Context, host string) string

WorkspaceForHost returns the workspace slug whose verified custom domain is host ("" when none). Answers are cached for a minute.

type Settings

type Settings struct {
	Workspace *store.Workspace

	Branding Branding
	Pages    Pages
	// contains filtered or unexported fields
}

Settings are a workspace's public page settings.

func (*Settings) CustomDomain

func (s *Settings) CustomDomain() string

CustomDomain is the verified custom domain, or "".

func (*Settings) HostedFormID

func (s *Settings) HostedFormID() *uuid.UUID

HostedFormID is the form behind /subscribe, if any.

func (*Settings) LogoVersion

func (s *Settings) LogoVersion() string

LogoVersion changes when the logo changes (cache busting).

func (*Settings) TurnstileSiteKey

func (s *Settings) TurnstileSiteKey() string

TurnstileSiteKey is the public site key when Turnstile can be used.

func (*Settings) UpdatedAt

func (s *Settings) UpdatedAt() time.Time

UpdatedAt is when the settings last changed (theme cache busting).

type SignupForm

type SignupForm struct {
	SignupFormSummary
	Fields         []SignupFormField `json:"fields"`
	ListIDs        []string          `json:"listIds" doc:"Lists offered on the form"`
	DefaultListIDs []string          `json:"defaultListIds" doc:"Offered lists that start checked"`
	ListChoice     bool              `json:"listChoice" doc:"Visitors pick lists; off joins every offered list"`
	DoubleOptIn    bool              `json:"doubleOptIn"`
	ConsentText    string            `json:"consentText"`
	ConsentVersion int               `json:"consentVersion"`
	Spam           SignupFormSpam    `json:"spam"`
	AfterSubmit    string            `json:"afterSubmit" enum:"message,redirect"`
	RedirectURL    string            `json:"redirectUrl"`
	AllowedOrigins []string          `json:"allowedOrigins"`
	Content        SignupFormContent `json:"content"`
	URLs           SignupFormURLs    `json:"urls"`
	// PlainHTML is the form as plain HTML, for sites that can't load scripts.
	PlainHTML      string                    `json:"plainHtml"`
	Stats          SignupFormStats           `json:"stats"`
	BlockedOrigins []SignupFormBlockedOrigin `json:"blockedOrigins"`
	// Waiting counts the signups of the last 30 days whose confirmation
	// email hasn't gone out (nothing could send System mail).
	Waiting     int64      `json:"waiting"`
	PublishedAt *time.Time `json:"publishedAt,omitempty"`
	UpdatedAt   time.Time  `json:"updatedAt"`
}

SignupForm is one form with everything the builder shows.

type SignupFormBlockedOrigin

type SignupFormBlockedOrigin struct {
	Origin string    `json:"origin" example:"staging.acme.io"`
	Count  int64     `json:"count"`
	LastAt time.Time `json:"lastAt"`
}

SignupFormBlockedOrigin is a site whose submissions were rejected today.

type SignupFormConfirmLink struct {
	URL   string `json:"url"`
	Email string `json:"email"`
}

SignupFormConfirmLink is a confirmation link to send by hand.

type SignupFormContent

type SignupFormContent struct {
	Heading          string `json:"heading" maxLength:"120"`
	Description      string `json:"description" maxLength:"500"`
	Button           string `json:"button" maxLength:"40"`
	Footnote         string `json:"footnote" maxLength:"300"`
	ListsLabel       string `json:"listsLabel" maxLength:"80"`
	EmailPlaceholder string `json:"emailPlaceholder" maxLength:"80"`
	NamePlaceholder  string `json:"namePlaceholder" maxLength:"80"`
	PopupDelay       int    `json:"popupDelay" minimum:"0" maximum:"600" doc:"Seconds before a popup opens"`
	PopupScroll      int    `json:"popupScroll" minimum:"0" maximum:"100" doc:"Percent of the page scrolled before a popup opens; 0 is off"`
	PopupRepeatDays  int    `json:"popupRepeatDays" minimum:"0" maximum:"365" doc:"Days a closed popup stays closed"`
}

SignupFormContent is the copy of a form.

type SignupFormCreateInput

type SignupFormCreateInput struct {
	Name string `json:"name" minLength:"1" maxLength:"80"`
	Kind string `json:"kind" enum:"embedded,popup,hosted"`
}

type SignupFormCustomField

type SignupFormCustomField struct {
	Key     string   `json:"key"`
	Label   string   `json:"label"`
	Type    string   `json:"type" enum:"text,number,date,boolean,select"`
	Options []string `json:"options"`
}

SignupFormCustomField is a custom contact field a form can ask for.

type SignupFormField

type SignupFormField struct {
	Key      string `json:"key" pattern:"^[a-z][a-z0-9_]{0,62}$" doc:"email, first_name, last_name, company or a custom field key"`
	Label    string `json:"label" maxLength:"80" doc:"Shown above the input; empty uses the field's name"`
	Required bool   `json:"required"`
}

type SignupFormInput

type SignupFormInput struct {
	Name           string            `json:"name" minLength:"1" maxLength:"80"`
	Kind           string            `json:"kind" enum:"embedded,popup,hosted"`
	Fields         []SignupFormField `json:"fields" maxItems:"20"`
	ListIDs        []string          `json:"listIds" maxItems:"50"`
	DefaultListIDs []string          `json:"defaultListIds" maxItems:"50"`
	ListChoice     bool              `json:"listChoice"`
	DoubleOptIn    bool              `json:"doubleOptIn"`
	ConsentText    string            `json:"consentText" maxLength:"600"`
	Spam           SignupFormSpam    `json:"spam"`
	AfterSubmit    string            `json:"afterSubmit" enum:"message,redirect"`
	RedirectURL    string            `json:"redirectUrl" maxLength:"2000"`
	AllowedOrigins []string          `json:"allowedOrigins" maxItems:"50"`
	Content        SignupFormContent `json:"content"`
	// Publish makes the form live (the builder's Save & publish); false keeps a draft a draft.
	Publish bool `json:"publish"`
}

SignupFormInput saves a form ("Save & publish").

type SignupFormList

type SignupFormList struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description"`
	Public      bool   `json:"public"`
	Subscribed  int64  `json:"subscribed"`
}

SignupFormList is a list a form can offer.

type SignupFormOriginInput

type SignupFormOriginInput struct {
	Origin string `json:"origin" minLength:"1" maxLength:"255" example:"staging.acme.io"`
}

SignupFormOriginInput names a site.

type SignupFormRenameInput

type SignupFormRenameInput struct {
	Name string `json:"name" minLength:"1" maxLength:"80"`
}

SignupFormRenameInput renames a form (its slug follows).

type SignupFormSpam

type SignupFormSpam struct {
	// Honeypot adds an invisible field and the timing check.
	Honeypot   bool `json:"honeypot"`
	MinSeconds int  `json:"minSeconds" minimum:"0" maximum:"60" doc:"Submissions faster than this look automated"`
	// Turnstile asks Cloudflare Turnstile when a submission looks automated.
	Turnstile bool `json:"turnstile"`
	// BlockDisposable rejects disposable domains and role addresses.
	BlockDisposable bool `json:"blockDisposable"`
	RateLimitPerIP  int  `json:"rateLimitPerIp" minimum:"1" maximum:"120" doc:"Submissions per minute from one address"`
}

SignupFormSpam is a form's spam protection.

type SignupFormStats

type SignupFormStats struct {
	Days        int   `json:"days"`
	Views       int64 `json:"views"`
	Submissions int64 `json:"submissions"`
	// SubmissionRate is submissions per view, in percent.
	SubmissionRate float64 `json:"submissionRate"`
	Confirmed      int64   `json:"confirmed"`
	// ConfirmedRate is confirmed submissions per submission, in percent.
	ConfirmedRate float64 `json:"confirmedRate"`
	Blocked       int64   `json:"blocked" doc:"Submissions blocked as spam"`
	Pending       int64   `json:"pending" doc:"Double opt-in confirmations not clicked yet"`
}

SignupFormStats are the builder's "Last 30 days".

type SignupFormStatusInput

type SignupFormStatusInput struct {
	Status string `json:"status" enum:"live,paused"`
}

SignupFormStatusInput pauses or resumes a form.

type SignupFormSummary

type SignupFormSummary struct {
	ID       string `json:"id"`
	Name     string `json:"name"`
	Kind     string `json:"kind" enum:"embedded,popup,hosted"`
	Status   string `json:"status" enum:"draft,live,paused"`
	PublicID string `json:"publicId" example:"frm_8c2e1a"`
	Slug     string `json:"slug"`
	// HostedPage is true for the form behind the workspace's /subscribe page.
	HostedPage bool   `json:"hostedPage"`
	HostedURL  string `json:"hostedUrl"`
}

SignupFormSummary is a form in the selector.

type SignupFormURLs

type SignupFormURLs struct {
	// Hosted is the form's hosted page (the workspace's /subscribe for the hosted page form).
	Hosted string `json:"hosted"`
	// Script is the embed script; Submit receives submissions.
	Script string `json:"script"`
	Submit string `json:"submit"`
	// ScriptKB is what the embed script weighs on the wire (gzip), rounded up.
	ScriptKB int `json:"scriptKb"`
}

SignupFormURLs are where a form lives.

type SignupFormWaiting

type SignupFormWaiting struct {
	Items []SignupFormWaitingItem `json:"items"`
	Total int64                   `json:"total"`
	// SystemMail reports whether System mail can go out now; the
	// confirmations job then sends what's waiting (signups of the last 3 days).
	SystemMail bool `json:"systemMail"`
}

SignupFormWaiting lists the signups of a form whose confirmation email hasn't gone out, newest first.

type SignupFormWaitingItem

type SignupFormWaitingItem struct {
	ID        string    `json:"id" doc:"The submission"`
	Email     string    `json:"email"`
	FirstName string    `json:"firstName"`
	Lists     []string  `json:"lists" doc:"The lists the signup waits to join"`
	CreatedAt time.Time `json:"createdAt"`
	Attempts  int       `json:"attempts" doc:"How many times sending the email was tried"`
}

SignupFormWaitingItem is a signup whose confirmation email hasn't gone out.

type SignupFormsOverview

type SignupFormsOverview struct {
	Forms        []SignupFormSummary     `json:"forms"`
	Lists        []SignupFormList        `json:"lists"`
	CustomFields []SignupFormCustomField `json:"customFields"`
	// HostedURL is the workspace's subscribe page; HostedFormID the form behind it (empty: the built-in form).
	HostedURL    string `json:"hostedUrl"`
	HostedFormID string `json:"hostedFormId"`
	// SystemProvider names the System stream's provider ("Postmark"); empty
	// when none is routed. SystemMail says whether System mail can go out
	// now: without it confirmations wait and their links are sent by hand.
	SystemProvider string             `json:"systemProvider"`
	SystemMail     bool               `json:"systemMail"`
	Turnstile      PublicTurnstile    `json:"turnstile"`
	Branding       PublicBranding     `json:"branding"`
	Domain         PublicCustomDomain `json:"domain"`
	// Origins that may always submit: the instance and the custom domain.
	OwnOrigins []string `json:"ownOrigins"`
}

SignupFormsOverview feeds the Forms & public pages screens: the forms, the lists and fields they can use, and what the preview needs.

type Submission

type Submission struct {
	Email     string            `json:"email"`
	FirstName string            `json:"firstName"`
	LastName  string            `json:"lastName"`
	Company   string            `json:"company"`
	Fields    map[string]string `json:"fields"`
	// Lists are the checked lists (ids) when visitors pick lists.
	Lists   []string `json:"lists"`
	Consent bool     `json:"consent"`
	// Honeypot is the invisible field only bots fill in.
	Honeypot string `json:"-"`
	// Token is the timestamp token rendered with the form.
	Token string `json:"-"`
	// Plain is a post of the copied plain HTML form, which has no token.
	Plain bool `json:"-"`
	// Origin is the host the browser says the form was on.
	Origin    string      `json:"-"`
	IP        *netip.Addr `json:"-"`
	UserAgent string      `json:"-"`
}

Submission is what a visitor sent, with the request it came in.

type SubscribePage

type SubscribePage struct {
	Heading     string `json:"heading" maxLength:"120"`
	Description string `json:"description" maxLength:"600"`
	Footnote    string `json:"footnote" maxLength:"300"`
	// ListText is the line under each list (by list id); {subscribers} is
	// replaced by the list's size.
	ListText map[string]string `json:"listText"`
	// Index lets search engines list the page.
	Index bool `json:"index"`
}

SubscribePage are the hosted subscribe page's options.

type Turnstile

type Turnstile struct {
	Client    *http.Client
	VerifyURL string
}

Turnstile verifies Cloudflare Turnstile answers server-side. Client is an SSRF-guarded client (internal/netguard).

func (*Turnstile) Verify

func (t *Turnstile) Verify(ctx context.Context, secret, response, remoteIP, idempotencyKey string) (TurnstileResult, error)

Verify checks a widget answer with the secret key.

type TurnstileResult

type TurnstileResult struct {
	Success  bool     `json:"success"`
	Codes    []string `json:"error-codes"`
	Hostname string   `json:"hostname"`
	Action   string   `json:"action"`
}

TurnstileResult is Cloudflare's answer.

func (TurnstileResult) SecretRejected

func (r TurnstileResult) SecretRejected() bool

SecretRejected reports whether Cloudflare refused the secret key itself.

type UnsubscribePage

type UnsubscribePage struct {
	Fewer       bool   `json:"fewer" doc:"Offer the monthly best-of instead"`
	FewerTitle  string `json:"fewerTitle" maxLength:"120"`
	FewerText   string `json:"fewerText" maxLength:"400"`
	FewerButton string `json:"fewerButton" maxLength:"60"`
	Reasons     bool   `json:"reasons" doc:"Ask why, optionally"`
}

UnsubscribePage are the unsubscribe page's options.

type UnsubscribeStats

type UnsubscribeStats struct {
	Days int `json:"days"`
	// Unsubscribed counts contacts who left from the public pages: the
	// unsubscribe page, one-click, or unticking lists in the preference center.
	Unsubscribed int64 `json:"unsubscribed"`
	OneClick     int64 `json:"oneClick" doc:"Of them, with their mail app's one-click unsubscribe"`
	ChoseFewer   int64 `json:"choseFewer" doc:"Took the monthly best-of instead of leaving"`
	Answered     int64 `json:"answered" doc:"Said why they left"`
}

UnsubscribeStats are the Unsubscribe page tab's numbers.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL