Jakub Zych 334697badc feat: MatchHTML and Filter.CheckHTML for rendered content
- read HTML as a member sees it: text joined across inline tags, block
  tags and br separating, entities decoded, alt and title as text,
  href and src values checked as links
- CheckHTML shares Check's settings row, switch, cache and message
2026-11-02 18:48:51 +01:00

golem15.moderation

A content filter for SummerCMS applications: banned words, phrases and links that administrators edit in the admin settings, checked through one Filter any host plugin can call before user content is saved.

import _ "git.golem15.com/golem15/sm-moderation-plugin"

Module git.golem15.com/golem15/sm-moderation-plugin, package moderation, plugin ID golem15.moderation.

Name: The lifeguard's whistle: it does not run the beach, it stops what should not go into the water.

Overview

The plugin is a compiled SummerCMS plugin. Its init registers it with the framework, so an application loads it by listing it in summer.yaml; summer build then emits the blank import above into the application's plugins.gen.go.

It owns one settings singleton, golem15_moderation_settings (row id 1), with an enabled switch and two lists, one entry per line: banned words and phrases, and banned links. At boot it publishes *classes.Filter. The filter knows no content plugin and the plugin imports none: the host application looks the filter up and calls Filter.Check from the pre-save seams of the content plugins it runs, then refuses the write in the way that plugin expects.

Requires() is empty.

Features

  • Words and phrases. An entry matches case- and diacritic-insensitively as a whole word: between characters that are not letters, digits or _, or at the start or end of the text. The boundaries are Unicode-aware, so Polish words (żółw) match only whole (żółwik does not), and zolw or a decomposed żółw match the entry żółw. A phrase (kup tanio) matches with any run of whitespace, Unicode spaces included, between its words. The violation reports the entry as listed.
  • Text as members read it. Before matching, the text is normalised: HTML entities decoded (viagra), NFKC applied (fullwidth viagra), format characters dropped (zero-width space and joiners, word joiner, BOM, soft hyphen, bidi controls), and every Unicode space (no-break, thin, ideographic) made a plain space. A second pass reads the text without inline markup: asterisks, backticks and tildes dropped (via**gra**, via`gra` , via~~gra~~), Markdown backslash escapes dropped and _word_ unwrapped. A lone underscore stays part of the word, so spam_bot is not spam. Entries are normalised the same way.
  • Links. An entry that is a host (example.com, www.example.com, https://example.com) matches that host and every subdomain in the text, with or without an http(s):// scheme or www., and bare domains in running text. An entry with a path (example.com/promo) matches links on that host or a subdomain whose path starts with it.
  • Links as browsers open them. Hosts and paths are compared the way the WHATWG URL parser resolves them: percent-escapes decoded (bit%2Ely, /%70romo), fullwidth letters and the ideographic, fullwidth and halfwidth full stops mapped (bit。ly), userinfo (user@bit.ly) and the port (example.com:443/promo) dropped, trailing dots dropped, the path cleaned (//promo, /./promo), any run of slashes or backslashes after an http(s): scheme read as // (https:bit.ly), and an internationalised name compared in its IDNA ASCII form, so its punycode and Unicode spellings match each other. Entries go through the same host normalisation.
  • Admin settings. Settings entry moderation_settings (category Users, icon shield) behind the permission golem15.moderation.manage_settings on the developer role. A save above the list limits or with a link entry that is neither a host name nor an http(s) URL answers 422 on its field.
  • Rendered HTML. Filter.CheckHTML and classes.MatchHTML read HTML as a member sees it: text joined across inline tags (via<strong>gra</strong> is viagra), block tags and <br> separating, entities decoded, alt and title values read as text, comments, scripts and styles left out, and every href and src value checked as a link.
  • Cached matching. Filter.Check reads the settings row on every call and recompiles its matchers only when the stored lists changed, so an admin edit applies to the next message. The matchers are RE2 (linear time) and the lists are bounded by the config limits.
  • Localized messages. The violation message is the golem15.moderation::lang.violation.word or .link phrase in the locale of the request context (towel.Locale), English when there is none. English and Polish phrasebooks ship in lang/.

Usage

The host application wires the filter into another plugin's pre-save event. Here a neutral host plugin acme refuses comments of its own acme.blog plugin; this plugin imports neither:

func (p *Plugin) Boot(app *backpack.App) error {
	return lagoon.OnDatabase(app, func(_ *sql.DB, _ *gorm.DB) error {
		filter, ok := app.Lookup[*classes.Filter]()
		if !ok {
			return errors.New("acme: golem15.moderation must be listed before acme in summer.yaml")
		}
		app.Events.Listen[*blogevents.CommentSaving](p.ID(), func(ctx context.Context, ev *blogevents.CommentSaving) error {
			v, err := filter.Check(ctx, ev.Body)
			if err != nil || v == nil {
				return err
			}
			return blogcontracts.Rejection{Field: "body", Message: v.Message}
		})
		return nil
	})
}

When the content plugin renders the text before members read it (Markdown to HTML), check the source with Check and the rendered HTML with CheckHTML: the renderer resolves forms the source does not spell out, such as an escape (bit\.ly), a comment inside a word or an entity in a link destination. Here acme.blog's event also carries the rendered HTML:

app.Events.Listen[*blogevents.CommentSaving](p.ID(), func(ctx context.Context, ev *blogevents.CommentSaving) error {
	v, err := filter.Check(ctx, ev.Body)
	if err == nil && v == nil {
		v, err = filter.CheckHTML(ctx, ev.HTML)
	}
	if err != nil || v == nil {
		return err
	}
	return blogcontracts.Rejection{Field: "body", Message: v.Message}
})

classes.Match runs the same rules on lists you pass in, without the database (classes.MatchHTML for rendered HTML):

v := classes.Match(classes.ParseList("spam\nkup tanio"), classes.ParseList("bad.example"), text)

API reference

Identifier Description
moderation.PluginID golem15.moderation
moderation.PermissionManageSettings golem15.moderation.manage_settings
moderation.ConfigMaxEntries / moderation.ConfigMaxEntryLength Config keys of the list limits
classes.Filter The published filter (app.Lookup[*classes.Filter]())
classes.NewFilter NewFilter(db *gorm.DB) *Filter
classes.Filter.Check Check(ctx, text) (*Violation, error): the first violation against the stored lists, nil for clean text or a disabled filter
classes.Filter.CheckHTML CheckHTML(ctx, html) (*Violation, error): Check for rendered HTML, read as MatchHTML reads it
classes.Filter.SetTranslator Translator of the violation messages; the plugin sets the application's
classes.Match Match(words, links []string, text string) *Violation: pure, words before links, English message
classes.MatchHTML MatchHTML(words, links []string, html string) *Violation: Match for rendered HTML (text across inline tags, entities decoded, href/src as links)
classes.ParseList Splits a list into trimmed, lower-cased entries without empty lines and duplicates
classes.Violation {Kind, Match, Message}
classes.KindWord / classes.KindLink word / link
models.Settings Row of golem15_moderation_settings (Enabled, BannedWords, BannedLinks)
models.SetLimits / models.Limits The list limits the settings save enforces
models.LinkEntry Normalizes a banned-links entry to host (IDNA ASCII, so żółw.example is xn--w-uga1v8h.example) and path prefix; refuses a name IDNA refuses
models.CanonicalHost CanonicalHost(host) (ascii string, ok bool): a host the way a browser looks it up (NFKC, dots, lower case, no trailing dot or www., IDNA ASCII)

The migration is 202610280001_create_golem15_moderation_settings (creates the table and row 1).

Configuration

config/config.yaml, read as golem15.moderation.<key>:

Key Default Meaning
max_entries 500 Most lines one list may hold
max_entry_length 200 Longest line, in characters

A value of 0 or less means the default.

Dependencies

  • SummerCMS v0.6.0 modules: backpack, party, pact, lagoon, cabana, phrasebook, towel, diary
  • gorm.io/gorm, github.com/go-gormigrate/gormigrate/v2
  • golang.org/x/text (unicode/norm: NFKC and diacritic folding) and golang.org/x/net (idna: the IDNA ASCII form of hosts; html: the tokenizer MatchHTML walks), at the versions the framework requires directly (v0.42.0 and v0.58.0); the standard library has neither

No other plugin.

Testing

go vet ./...
go test -short ./...   # matching, settings checks and the manifest, no Docker
go test ./...          # also the Postgres tests

Without a database: TestMatchWords, TestMatchWordsFirstAndEmpty, TestMatchLinks, TestMatchLinksInvalidEntries, TestParseList and TestFilterSmoke pin the matching rules (classes); TestMatchBypassWords and TestMatchBypassLinks pin the normalisation, one case per known way around a literal match; TestMatchHTML (Markdown rendered by breakwater) and TestMatchHTMLWalk pin how rendered HTML is read; TestFilterCheckCache the recompile-on-change cache and TestViolationMessage the message locale; TestSettingsLimits, TestLinkEntry and TestSettingsModel (models) the list checks of a settings save. TestPluginManifest checks that plugin.yaml matches what summer plugin:manifest derives from the sources.

The Postgres tests (root package, testcontainers postgres:16-alpine, skipped under -short) boot the plugin alone: TestBootPublishesFilter (the singleton row, the published *classes.Filter, the config limits), TestFilterCheckDisabled (the stored lists, the disabled switch, a missing row, the request locale) TestFilterCheckReload (a list change applies without a restart) and TestFilterCheckNormalises (the stored lists reach the normalised matcher, Check and CheckHTML). The tests use github.com/testcontainers/testcontainers-go and github.com/jackc/pgx/v5; the plugin code does not.

Changelog

v0.1.1

  • Banned entries match what members see: invisible format characters, Unicode spaces, decomposed and folded diacritics, fullwidth letters, HTML entities and inline markup inside a word no longer get a word past the filter, and links are compared the way browsers open them (percent-escapes, fullwidth letters and dots, port, userinfo, trailing dot, doubled or dotted paths, slashes after the scheme, punycode and Unicode spellings).
  • Path rules cover subdomains, as host rules do.
  • classes.MatchHTML and Filter.CheckHTML read rendered HTML the way members see it.
  • No schema or config change; the API gains MatchHTML, Filter.CheckHTML and models.CanonicalHost, and models.LinkEntry returns the IDNA ASCII host.

v0.1.0

  • First release: the banned word and link filter, its settings screen and classes.Filter.
Description
Banned word and link filter for SummerCMS plugins
Readme 158 KiB
Languages
Go 100%