forms

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: AGPL-3.0 Imports: 59 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 (
	CopyLive       = "live"
	CopyIncomplete = "incomplete"
	CopyNotSetUp   = "not_set_up"
)

Copy statuses of a language's pages or a form.

View Source
const (
	LanguagePage    = "page"
	LanguageBrowser = "browser"
	LanguageFixed   = "fixed"
)

Form language modes.

View Source
const (
	KindEmbedded = "embedded"
	KindPopup    = "popup"
	KindHosted   = "hosted"
	// KindPush is a push prompt (design expansion phase 8, X22): a form type
	// the push package designs and serves. It's listed with the forms but
	// never rendered, embedded or submitted as a signup form.
	KindPush = "push"

	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 FieldPhone = "phone"

FieldPhone is the phone field.

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 ClientKey

func ClientKey(a netip.Addr) string

ClientKey names a client for rate limits: an IPv4 address itself, an IPv6 address by its /64. A household, a phone or a server is given a whole /64, so rotating addresses inside it stays one client (review 2026-11 DP-3).

func ConfirmationEmail

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

ConfirmationEmail is the double opt-in email in English.

func ConfirmationEmailIn

func ConfirmationEmailIn(l pagelabels.Set, b Branding, firstName string, lists []string, link string, reminder bool) mailer.Message

ConfirmationEmailIn is the double opt-in email in a language: 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, in its own language: English.

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 in the language c shows it in.

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 FieldLabelIn

func FieldLabelIn(f fieldDoc, customs []store.CustomField, l pagelabels.Set) string

FieldLabelIn is the label a field shows in a language: the form's own, else the built-in field's label in that language, else the custom field's name.

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 PartnerConfirmationEmail

func PartnerConfirmationEmail(b Branding, firstName string, lists []string, link, recommender string) mailer.Message

PartnerConfirmationEmail is the double opt-in email of a partner signup (grow brief §3.9): the usual email with the line "You asked for this on the Acme Weekly Digest's page." It goes out in English.

func PhraseIndex

func PhraseIndex(text, phrase string) (int, int)

PhraseIndex finds phrase in text, ignoring letter case, and returns where it starts and ends in text itself (byte offsets), or -1, -1. The consent text links its words for the privacy policy this way, in every language.

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, in the language c shows it in (it says so, so the signup records the consent text it showed). 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 "İ").

Consent texts in other languages are linked with PhraseIndex and the language's words for it (the form.privacy label).

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 AddressChecker

type AddressChecker interface {
	CheckSignup(ctx context.Context, ws *store.Workspace, formKey, email string) SignupAddress
	// SignedUp records the answer on the contact (risky and unknown are tagged).
	SignedUp(ctx context.Context, ws *store.Workspace, contactID uuid.UUID, a SignupAddress)
}

AddressChecker checks a signup's address with the workspace's own verification service as people sign up (internal/verification), when the form has real-time checks on. It never blocks a signup on the service: without an answer in 3 seconds the signup goes through and is checked later.

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
	// Digest keeps the issues of one recurring digest (internal/digests).
	Digest *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. IBM Plex Sans is followed by Arial scaled to its size (the pages' CSS defines 'IBM Plex Sans Fallback'), so text doesn't move when the font arrives.

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
	// CopyLanguage is the language the form is written in; LanguageMode
	// says which language it shows (page, browser or fixed, with
	// FixedLanguage).
	CopyLanguage  string
	LanguageMode  string
	FixedLanguage string
	// Language is the language this Config shows the form in (FormCopy.In);
	// empty is its copy language. Labels are that language's built-in
	// labels, PrivacyURL its privacy policy link (empty: the branding's) and
	// ListNames the lists' names in it.
	Language   string
	Labels     pagelabels.Set
	PrivacyURL string
	ListNames  map[uuid.UUID]string
	// contains filtered or unexported fields
}

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) SMSConsentText

func (c Config) SMSConsentText(offer TextOffer) string

SMSConsentText is the form's SMS consent text in its language: its own, else the default one.

func (Config) ShownLanguage

func (c Config) ShownLanguage() string

ShownLanguage is the language a form was shown in, for its evidence and emails: the Config's language, else its copy language.

func (Config) Source

func (c Config) Source() string

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

type ConfirmEvent

type ConfirmEvent struct {
	ContactID uuid.UUID
	Lists     []uuid.UUID
	IP        *netip.Addr
	At        time.Time
}

ConfirmEvent is a confirmation click that confirmed lists.

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 FormCopy

type FormCopy struct {
	Form  Config
	Pages *PagesCopy
	// contains filtered or unexported fields
}

FormCopy is a form's copy in every language, with the pages' (the labels, list names and privacy link come from there).

func (*FormCopy) ConsentReview

func (fc *FormCopy) ConsentReview(code string) bool

ConsentReview reports whether a language's consent text was written for an older version of the form's own consent text.

func (*FormCopy) Fallback

func (fc *FormCopy) Fallback() string

Fallback is the language the form shows when the one asked for isn't Live: the workspace's fallback when the form is Live in it, else the form's own language.

func (*FormCopy) In

func (fc *FormCopy) In(code string) Config

In is the form as it shows in a language: its copy there, the language's labels, list names and privacy link. A language the form isn't Live in shows the form in its own language.

func (*FormCopy) Live

func (fc *FormCopy) Live(code string) bool

Live reports whether the form can be shown in a language.

func (*FormCopy) LiveLanguages

func (fc *FormCopy) LiveLanguages() []string

LiveLanguages are the languages the form can be shown in: the workspace's Live ones, the default first, and the form's own language.

func (*FormCopy) Localized

func (fc *FormCopy) Localized(code string, lists []audience.PublicList) Config

Localized is the form in a language, with its lists' names in it.

func (*FormCopy) Pick

func (fc *FormCopy) Pick(requested string) string

Pick is the language a submission or page shows the form in: the one asked for when the form is Live in it ("" is the form's own language, which a copied plain HTML form shows), else the fallback. A form always in one language shows it when it's Live.

func (*FormCopy) Status

func (fc *FormCopy) Status(code string) (status string, missing, written int)

Status is the form's copy in a language: its status, the strings still to write (the form's own and the built-in labels) and how many are written.

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 LanguagePath

type LanguagePath struct {
	Language string `path:"language" pattern:"^[A-Za-z]{2,3}([-_][A-Za-z0-9]{2,8})*$" maxLength:"35" doc:"A workspace language (es)"`
}

LanguagePath names a content language in the path: a workspace language's code ("es"; "es-MX" is es too).

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:"-"`
	// Language is the language the form was shown in: the result page
	// follows it.
	Language string `json:"-"`
	// Texted is "We've also texted +1 312 ••• 0123 to confirm." when the
	// signup gave SMS consent and the opt-in confirmation went out.
	Texted string `json:"texted,omitempty"`
}

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) Download

func (l PageLinks) Download(token string) string

Download is a reward file, behind an expiring signed link.

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 (PageLinks) Join

func (l PageLinks) Join(code string) string

Join is a referral link's invite page: news.acme.io/join/K7Q2MX.

func (PageLinks) Leaderboard

func (l PageLinks) Leaderboard() string

Leaderboard is the program's public leaderboard.

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) Path

func (l PageLinks) Path(parts ...string) string

Path is an address on the pages' host: "/posts/x" on a custom domain, "/p/<workspace>/posts/x" on the instance (the publication website).

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) Poll

func (l PageLinks) Poll(token string) string

Poll is a poll's answer page, and Survey a survey's page (internal/polls).

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) Recommends

func (l PageLinks) Recommends(token string) string

Recommends is the recommendations page; with a token it knows the reader.

func (PageLinks) RecommendsVisit

func (l PageLinks) RecommendsVisit(id string) string

RecommendsVisit counts a click on a recommended newsletter's link and sends the reader there.

func (PageLinks) Referrals

func (l PageLinks) Referrals(token string) string

Referrals is a referrer's hub, opened from a signed link.

func (PageLinks) ReferralsRequest

func (l PageLinks) ReferralsRequest() string

ReferralsRequest asks for a fresh hub link by email.

func (PageLinks) Script

func (l PageLinks) Script(publicID string) string

func (PageLinks) Sitemap

func (l PageLinks) Sitemap() string

func (PageLinks) SmsTerms

func (l PageLinks) SmsTerms() string

SmsTerms is the text message terms page (SMS, X21).

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) Survey

func (l PageLinks) Survey(slug string) string

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 PagesCopy

type PagesCopy struct {
	Languages languages.Settings
	// CopyLanguage is the language the pages are written in.
	CopyLanguage string
	// contains filtered or unexported fields
}

PagesCopy is a workspace's public pages in every language.

func (*PagesCopy) Choose

func (pc *PagesCopy) Choose(live func(string) bool, wants ...string) string

Choose picks the language to show for a visitor's languages, in order of preference: the first that's a workspace language decides, its pages when they're Live, else the fallback's; with none of them, the default's (the fallback's when the default isn't Live). live says whether a language can be shown (the pages and, on a page with a form, the form too).

func (*PagesCopy) Fallback

func (pc *PagesCopy) Fallback() string

Fallback is the language visitors get when theirs isn't Live: the workspace's fallback, else its default, else the pages' own language.

func (*PagesCopy) Labels

func (pc *PagesCopy) Labels(code string) pagelabels.Set

Labels returns the built-in labels of a language.

func (*PagesCopy) ListDescription

func (pc *PagesCopy) ListDescription(code string, l audience.PublicList) string

ListDescription is a list's description in a language.

func (*PagesCopy) ListName

func (pc *PagesCopy) ListName(code string, l audience.PublicList) string

ListName is a list's name in a language.

func (*PagesCopy) Live

func (pc *PagesCopy) Live(code string) bool

Live reports whether the pages can be shown in a language.

func (*PagesCopy) LiveLanguages

func (pc *PagesCopy) LiveLanguages() []string

LiveLanguages are the workspace languages the pages can be shown in, the default first.

func (*PagesCopy) Pages

func (pc *PagesCopy) Pages(code string, p Pages) Pages

Pages are the pages' options with their own text in a language; ReputeCast's default text the workspace kept reads in that language too.

func (*PagesCopy) PrivacyURL

func (pc *PagesCopy) PrivacyURL(code, base string) string

PrivacyURL is the privacy policy link of a language.

func (*PagesCopy) Text

func (pc *PagesCopy) Text(code, key, source string) string

Text is a string of the pages' own text in a language: its translation, else the text in the copy language.

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, in English; notesIn writes
	// them in a reader's language.
	Notes []string `json:"notes"`
	// contains filtered or unexported fields
}

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 PublicCopyLabels

type PublicCopyLabels struct {
	// Shipped is true when ReputeCast ships the labels in the language.
	Shipped bool       `json:"shipped"`
	Written int        `json:"written" doc:"Labels with text in the language (all of them when they ship)"`
	Total   int        `json:"total"`
	By      string     `json:"by" doc:"Who wrote them last"`
	At      *time.Time `json:"at,omitempty"`
}

PublicCopyLabels is the state of a language's built-in labels.

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 PublicPageCopy

type PublicPageCopy struct {
	CopyLanguage string                 `json:"copyLanguage" doc:"The language the pages are written in"`
	Default      string                 `json:"default"`
	Fallback     string                 `json:"fallback"`
	Languages    []PublicPageLanguage   `json:"languages"`
	Language     string                 `json:"language" doc:"The language of strings (?language=)"`
	Strings      []PublicPageCopyString `json:"strings"`
}

PublicPageCopy is the pages' copy: every language's status and, for the language asked for, its strings.

type PublicPageCopyInput

type PublicPageCopyInput struct {
	// Strings are translations by key; an empty text removes one. Keys left
	// out keep their text.
	Strings map[string]string `json:"strings" maxProperties:"500"`
}

PublicPageCopyInput saves strings of the pages' own text in a language.

type PublicPageCopyString

type PublicPageCopyString struct {
	Key    string `json:"key" example:"subscribe.heading"`
	Page   string `json:"page" enum:"subscribe,confirm,preferences,unsubscribe,lists,privacy"`
	ListID string `json:"listId,omitempty"`
	// Source is the text in the pages' own language; Text its translation,
	// empty while it isn't written.
	Source string `json:"source"`
	Text   string `json:"text"`
	// Optional strings may stay as they are: a list's name, the privacy link.
	Optional bool `json:"optional"`
}

PublicPageCopyString is one string of the pages' own text.

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 PublicPageLabel

type PublicPageLabel struct {
	Key    string `json:"key" example:"form.button"`
	Source string `json:"source" doc:"The English text"`
	Note   string `json:"note,omitempty"`
	// Arguments are what the text may use: {publisher}, <b>…
	Arguments []string `json:"arguments"`
	// Text is the label in the language: ReputeCast's translation when it
	// ships the language, else the workspace's ("" until written).
	Text string `json:"text"`
}

PublicPageLabel is a built-in label in a language.

type PublicPageLabels

type PublicPageLabels struct {
	PublicCopyLabels
	Language string            `json:"language"`
	Labels   []PublicPageLabel `json:"labels"`
}

PublicPageLabels is the built-in labels of a language.

type PublicPageLabelsInput

type PublicPageLabelsInput struct {
	// Labels are texts by key; an empty text removes one. Keys left out keep their text.
	Labels map[string]string `json:"labels" maxProperties:"500"`
}

PublicPageLabelsInput saves labels a workspace writes for a language ReputeCast doesn't ship.

type PublicPageLanguage

type PublicPageLanguage struct {
	Code       string `json:"code" example:"es"`
	Name       string `json:"name" example:"Spanish"`
	Native     string `json:"native" example:"Español"`
	IsDefault  bool   `json:"isDefault"`
	IsFallback bool   `json:"isFallback"`
	// IsSource marks the language the pages are written in.
	IsSource bool   `json:"isSource"`
	Status   string `json:"status" enum:"live,incomplete,not_set_up"`
	// Missing counts the strings still to write, the built-in labels included.
	Missing int `json:"missing"`
	// Own counts the strings of the publisher's own text; Written, how many have their translation.
	Own     int              `json:"own"`
	Written int              `json:"written"`
	By      string           `json:"by"`
	At      *time.Time       `json:"at,omitempty"`
	Labels  PublicCopyLabels `json:"labels"`
}

PublicPageLanguage is the public pages in one language.

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
	// Addresses checks signups with the workspace's verification service
	// (nil: forms keep ReputeCast's own checks only).
	Addresses AddressChecker
	Now       func() time.Time
	// Hooks are told about signups and confirmations (Grow's referrals),
	// read at call time.
	Hooks func() []SignupHook
	// Texts adds the phone field and SMS consent (phase 8, internal/texting);
	// nil offers neither.
	Texts Texts
	// 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) AppConfirmation

func (s *Service) AppConfirmation(ctx context.Context, ws *store.Workspace, contactID uuid.UUID, language, link string) (mailer.Message, error)

AppConfirmation is the double opt-in email the team sends from the app (Add contact, Resend opt-in, bulk resend, import re-permission; review 2026-11 AU-15): the forms' branded email, in the contact's language when the public pages offer it (else their fallback), naming the lists the contact is still pending on. link is the confirmation link.

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

func (s *Service) Confirm(ctx context.Context, ws *store.Workspace, contactID, submissionID uuid.UUID, ev audience.PublicEvidence) (audience.ConfirmResult, error)

Confirm completes double opt-in for a contact from the confirmation link: the audience confirms the pending lists of the signup the link was sent for (submissionID; uuid.Nil or a signup that is gone: every pending list); the forms they came from count the confirmation on the day of the submission and start their "form submitted" automations.

func (*Service) ConfirmFormConsent

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

ConfirmFormConsent records that a language's consent text is still right for the form's current consent text ("Spanish is still right").

func (*Service) ConfirmURL

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

ConfirmURL is the double opt-in link of a contact (App.URLs.Confirm). It carries the day it was issued, so it works for 30 days, and the signup it was sent for (uuid.Nil: none), whose lists alone it confirms (review 2026-11 DP-3).

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) DefaultSender

func (s *Service) DefaultSender(ctx context.Context, ws *store.Workspace) (name, email string)

DefaultSender is the workspace's default sender ("Acme Newsletter", "digest@news.acme.io"), empty without one.

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) FormCopy

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

FormCopy returns a form's copy in every workspace language.

func (*Service) FormCopyFor

func (s *Service) FormCopyFor(ctx context.Context, ws *store.Workspace, set *Settings, c Config) (*FormCopy, error)

FormCopyFor reads a form's copy in every language (the hosted pages pick the language with it).

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 (*Service) LocalizedForm

func (s *Service) LocalizedForm(ctx context.Context, ws *store.Workspace, set *Settings, c Config, requested string) (Config, *FormCopy, error)

LocalizedForm returns the form as it shows in a language (see FormCopy.Pick): the hosted pages and the embed script use it.

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) PageCopy

func (s *Service) PageCopy(ctx context.Context, ws *store.Workspace, language string) (PublicPageCopy, error)

PageCopy returns the pages' copy in every language, with the strings of one when language is set. It refreshes the statuses Settings › General shows.

func (*Service) PageLabels

func (s *Service) PageLabels(ctx context.Context, ws *store.Workspace, language string) (PublicPageLabels, error)

PageLabels returns a language's built-in labels.

func (*Service) PagesCopyOf

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

PagesCopyOf reads the public pages' copy in every language.

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) ResendConfirmation

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

ResendConfirmation emails a new confirmation link to a contact who opened an expired one: for their latest signup still waiting, else for every list they are pending on. The limit on confirmation emails applies; an email it holds back is simply not sent (the page says the same either way).

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) SaveFormCopy

func (s *Service) SaveFormCopy(ctx context.Context, ws *store.Workspace, id, language string, in SignupFormCopyText) (SignupFormCopy, error)

SaveFormCopy stores a form's own text in a language: in its copy language that is the form's own content and consent text (a new consent version when the words change); in another, its copy there, whose consent text gets its own version.

func (*Service) SavePage

SavePage stores the options of one or more pages.

func (*Service) SavePageCopy

func (s *Service) SavePageCopy(ctx context.Context, ws *store.Workspace, language string, in PublicPageCopyInput) (PublicPageCopy, error)

SavePageCopy stores strings of the pages' own text in a language.

func (*Service) SavePageLabels

func (s *Service) SavePageLabels(ctx context.Context, ws *store.Workspace, language string, in PublicPageLabelsInput) (PublicPageLabels, error)

SavePageLabels stores built-in labels a workspace writes for a language ReputeCast doesn't ship.

func (*Service) SaveTurnstile

SaveTurnstile stores the keys and checks the secret with Cloudflare.

func (*Service) Script

func (s *Service) Script(ctx context.Context, ws *store.Workspace, set *Settings, c Config, links PageLinks) ([]byte, error)

Script is the script of a form (/p/{workspace}/forms/{id}.js) with its copy in every language it is Live in. It holds no personal data.

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), in English.

func (*Service) SendPreferenceLinkIn

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

SendPreferenceLinkIn emails the link in the language the page asking for it was shown in, when its pages are Live (else their fallback).

func (*Service) SetDomain

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

func (*Service) SetFooter

func (s *Service) SetFooter(ctx context.Context, q *store.Queries, ws *store.Workspace, poweredBy bool, privacyURL string) error

SetFooter saves the footer's branding from Website › Home & navigation: the privacy policy's address and "Sent with ReputeCast". It writes in q's transaction, and the caller audits the change.

func (*Service) SetFormLanguage

func (s *Service) SetFormLanguage(ctx context.Context, ws *store.Workspace, id string, in SignupFormLanguageInput) (SignupFormCopy, error)

SetFormLanguage picks which language a form shows.

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, requested 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) SystemProviderName

func (s *Service) SystemProviderName(ctx context.Context, ws *store.Workspace) string

SystemProviderName names the System stream's provider ("Postmark"), or "" when System mail has nowhere to go: the sender line of the website's sign-in emails.

func (*Service) TurnstileVerifier

func (s *Service) TurnstileVerifier(ctx context.Context, set *Settings, remoteIP string) func(answer string) bool

TurnstileVerifier checks Turnstile answers with the workspace's secret, for the website's sign-in and sign-up when requests look automated (nil when Turnstile isn't set up).

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) CopyLanguage

func (s *Settings) CopyLanguage() string

CopyLanguage is the language the pages are written in.

func (*Settings) CustomDomain

func (s *Settings) CustomDomain() string

CustomDomain is the verified custom domain, or "".

func (*Settings) DomainDates

func (s *Settings) DomainDates() (checkedAt, verifiedAt *time.Time)

DomainDates are when the custom domain's DNS was last checked and when it was verified (the publication website, design expansion phase 7).

func (*Settings) DomainState

func (s *Settings) DomainState() (domain, status, detail string)

DomainState is the custom domain as set, verified or not, with its check's status and finding (polls warn while answer links can't use it).

func (*Settings) DomainStateIn

func (s *Settings) DomainStateIn(l i18n.Lang) (domain, status, detail string)

DomainStateIn is DomainState with the check's finding in a reader's language.

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 SignupAddress

type SignupAddress struct {
	// Invalid: the address can't receive mail, so the form asks to fix it.
	Invalid bool
	// Disposable: a disposable inbox; it follows the form's setting.
	Disposable bool
	// Answer is the checker's own record of the answer, for SignedUp.
	Answer any
}

SignupAddress is a service's answer for one signup.

type SignupEvent

type SignupEvent struct {
	ContactID uuid.UUID
	Email     string
	FirstName string
	// Created: the signup created the contact.
	Created bool
	// Lists the submission asked for; Pending wait for the confirmation,
	// Subscribed joined at once, Already were joined before.
	Lists      []uuid.UUID
	Pending    []uuid.UUID
	Subscribed []uuid.UUID
	Already    []uuid.UUID
	// Page and Referrer are where the signup came from (the page's address
	// keeps its query: ?ref=, ?via=).
	Page      string
	Referrer  string
	IP        *netip.Addr
	UserAgent string
	FormID    *uuid.UUID
	At        time.Time
}

SignupEvent is an accepted signup.

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 SignupFormConsentEvidence

type SignupFormConsentEvidence struct {
	ContactID string    `json:"contactId"`
	Name      string    `json:"name"`
	At        time.Time `json:"at"`
	Version   string    `json:"version" example:"v1"`
}

SignupFormConsentEvidence is the latest signup that agreed to a language's consent text.

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"`
	// AfterSubmitText is what the form says after a signup; empty uses the built-in message.
	AfterSubmitText string `json:"afterSubmitText,omitempty" maxLength:"300"`
	// SmsConsent shows the SMS consent checkbox, unchecked by default; it
	// needs the phone field. SmsConsentText is its text (the default one
	// when empty) and SmsConsentVersion its version, which goes up whenever
	// the text changes (set by the server).
	SmsConsent        bool   `json:"smsConsent,omitempty"`
	SmsConsentText    string `json:"smsConsentText,omitempty" maxLength:"600"`
	SmsConsentVersion int    `json:"smsConsentVersion,omitempty" minimum:"0"`
}

SignupFormContent is the copy of a form.

type SignupFormCopy

type SignupFormCopy struct {
	FormID string `json:"formId"`
	// LanguageMode says which language the form shows: the page it's on
	// (its lang), the browser, or always FixedLanguage.
	LanguageMode  string `json:"languageMode" enum:"page,browser,fixed"`
	FixedLanguage string `json:"fixedLanguage"`
	CopyLanguage  string `json:"copyLanguage" doc:"The language the form is written in"`
	Fallback      string `json:"fallback" doc:"The language the form shows where one isn't Live"`
	// ConsentVersion is the form's own consent text's version, with who changed it last.
	ConsentVersion   int                      `json:"consentVersion"`
	ConsentChangedBy string                   `json:"consentChangedBy"`
	ConsentChangedAt *time.Time               `json:"consentChangedAt,omitempty"`
	Fields           []SignupFormCopyField    `json:"fields"`
	Languages        []SignupFormCopyLanguage `json:"languages"`
}

SignupFormCopy is a form's copy in every workspace language.

type SignupFormCopyField

type SignupFormCopyField struct {
	Key    string `json:"key"`
	Source string `json:"source" doc:"Its label in the form's own language"`
}

SignupFormCopyField is a field whose label is the publisher's text.

type SignupFormCopyLanguage

type SignupFormCopyLanguage struct {
	Code      string `json:"code" example:"es"`
	Name      string `json:"name" example:"Spanish"`
	Native    string `json:"native" example:"Español"`
	IsDefault bool   `json:"isDefault"`
	// IsSource marks the language the form is written in.
	IsSource bool   `json:"isSource"`
	Status   string `json:"status" enum:"live,incomplete,not_set_up"`
	// Missing counts the strings still to write, the built-in labels included;
	// Written how many of the form's Total strings have text.
	Missing int                `json:"missing"`
	Written int                `json:"written"`
	Total   int                `json:"total"`
	By      string             `json:"by"`
	At      *time.Time         `json:"at,omitempty"`
	Copy    SignupFormCopyText `json:"copy"`
	// ConsentVersion is this language's version of the consent text (0
	// before it has one); ConsentFor the version of the form's own consent
	// text it was written or last confirmed for.
	ConsentVersion int  `json:"consentVersion"`
	ConsentFor     int  `json:"consentFor"`
	ConsentReview  bool `json:"consentReview" doc:"The form's own consent text changed since: Review the translation"`
	// Labels are the language's built-in labels; Evidence the latest signup
	// that agreed to its consent text.
	Labels   PublicCopyLabels           `json:"labels"`
	Evidence *SignupFormConsentEvidence `json:"evidence,omitempty"`
	// DefaultAfterSubmit is the built-in after-submit message in the
	// language, shown when the form has no message of its own.
	DefaultAfterSubmit string `json:"defaultAfterSubmit"`
}

SignupFormCopyLanguage is a form in one language.

type SignupFormCopyText

type SignupFormCopyText struct {
	Heading     string `json:"heading" maxLength:"120"`
	Description string `json:"description" maxLength:"500"`
	Button      string `json:"button" maxLength:"40"`
	ConsentText string `json:"consentText" maxLength:"600"`
	AfterSubmit string `json:"afterSubmit" maxLength:"300" doc:"What the form says after a signup"`
	// Fields are the labels of the fields whose label is the publisher's text, by field key.
	Fields map[string]string `json:"fields" maxProperties:"20"`
}

SignupFormCopyText is a form's own text in one language.

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 SignupFormLanguageInput

type SignupFormLanguageInput struct {
	Mode  string `json:"mode" enum:"page,browser,fixed"`
	Fixed string `json:"fixed,omitempty" doc:"The language of a form always shown in one (mode fixed)"`
}

SignupFormLanguageInput picks which language a form shows.

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,push"`
	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 SignupHook

type SignupHook interface {
	// DoubleOptIn reports whether a submission must confirm by email even
	// on a single opt-in form: double opt-in is always on for referrals.
	DoubleOptIn(ctx context.Context, ws *store.Workspace, sub Submission) bool
	// Accepted runs after a signup was recorded.
	Accepted(ctx context.Context, tx pgx.Tx, ws *store.Workspace, e SignupEvent) error
	// Confirmed runs after a contact confirmed their pending lists.
	Confirmed(ctx context.Context, tx pgx.Tx, ws *store.Workspace, e ConfirmEvent) error
}

SignupHook is told about signups and confirmations inside their transactions, so another domain records what it needs with them. Grow's referrals record a referral when someone signs up through a referral link (the invite page, or a page opened with ?ref=) and start its hold when they confirm.

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"`
	// Phone is the number as typed, PhoneCountry the picker's country (for
	// numbers without +), SmsConsent the SMS consent box (phase 8).
	Phone        string `json:"phone,omitempty"`
	PhoneCountry string `json:"phoneCountry,omitempty"`
	SmsConsent   bool   `json:"smsConsent,omitempty"`

	// Language is the language the form was shown in (the embed script's
	// _lang, the hosted page's); empty is the form's own language, which a
	// copied plain HTML form shows. BrowserLanguage is the browser's first
	// language: a new contact gets it as their language.
	Language        string `json:"language,omitempty"`
	BrowserLanguage string `json:"browserLanguage,omitempty"`
	// 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:"-"`
	// Page is the address of the page with the form (its UTM parameters)
	// and Referrer the page before it (growth sources).
	Page     string `json:"-"`
	Referrer string `json:"-"`
	// contains filtered or unexported fields
}

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.

func (SubscribePage) FootnoteIn

func (p SubscribePage) FootnoteIn(code string) string

FootnoteIn is the Subscribe page's footnote on a page in a language (code): the publisher's own text, or ReputeCast's default in that language while the workspace keeps it.

type TextCountry

type TextCountry struct {
	Code string `json:"code"`
	Name string `json:"name"`
	Dial string `json:"dial"`
}

TextCountry is a country of the phone field's picker: US, United States, +1.

type TextEvidence

type TextEvidence struct {
	Source         string
	Page           string
	ConsentText    string
	ConsentVersion string
	IP             string
	UserAgent      string
	At             time.Time
}

TextEvidence is what SMS consent is recorded with.

type TextOffer

type TextOffer struct {
	// Countries are the phone field's picker, the routed ones first;
	// Default is the one it starts on.
	Countries []TextCountry
	Default   string
	// ConsentText is the default SMS consent text: the program, how often,
	// "Msg & data rates may apply", HELP and STOP, the terms and the privacy
	// policy. TermsWords are its words for the terms page, linked to TermsURL.
	ConsentText string
	TermsWords  string
	TermsURL    string
	// The page's words.
	PhoneLabel   string
	CountryLabel string
	Placeholder  string
	InvalidPhone string
	PhoneNeeded  string
}

TextOffer is the SMS part of a form, in one language.

type Texts

type Texts interface {
	// Offer is what a form needs to collect texts in a workspace, in a
	// language (English when texting has no words in it); false when the
	// workspace doesn't text.
	Offer(ctx context.Context, ws *store.Workspace, lang string) (TextOffer, bool)
	// Save records a signup's number on the contact and, when consent is
	// true, SMS consent on the lists with its evidence, in the signup's
	// transaction. It reports whether to text the opt-in confirmation.
	Save(ctx context.Context, tx pgx.Tx, ws *store.Workspace, contactID uuid.UUID, number phone.Number, consent bool, lists []uuid.UUID, ev TextEvidence) (bool, error)
	// Confirm texts the opt-in confirmation, once the transaction committed.
	Confirm(ctx context.Context, ws *store.Workspace, contactID uuid.UUID, lists []uuid.UUID)
	// Texted is the line "We've also texted +1 312 ••• 0123 to confirm.",
	// for a number, in a language.
	Texted(lang, e164 string) string
	// TextedContact is that line for a contact whose opt-in confirmation
	// went out in the last week (the email confirmation page); empty
	// otherwise.
	TextedContact(ctx context.Context, ws *store.Workspace, contactID uuid.UUID, lang string) string
}

Texts is the texting side of signup forms. Nil when texting isn't wired: forms then offer no phone field and no SMS consent.

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