Rich Content Blocks — Design Document

Status (30 Nov 2026): being replaced. Rich content is being dropped for Liquid: each character's and package's Showcase, and a creator's styled bio, becomes a block written in the Forge's code editor (the profile page's engine), and every existing rich text is carried over as its first version, words, pictures and links kept. Plan: docs-internal/architecture/content/RICH_CONTENT_TO_LIQUID.md. History of this page: Phase 1 SHIPPED (custom profile CSS — profile.css). Phase 2 SHIPPED (section.html — custom HTML blocks on profile-dashboard sections; picker-exposed to full-tier creators). Phase 3 SHIPPED for creator bio + characters + packages, including the correction to an additive showcase surface: the plain description always renders, and the rich payload opens from a "View showcase" button in a modal (EntityShowcaseModal; shipped before 2026-07-20 — predates this repo's shallow history). Phase 4 (embeds) planned. Operational map: docs-internal/architecture/profile/RICH_CONTENT_IMPLEMENTATION.md; Phase-2 DoD/build log: docs-internal/archive/superseded/profile/RICH_CONTENT_PHASE2_DOD.md; Phase-3 scope + correction: docs-internal/architecture/profile/RICH_CONTENT_PHASE3_SCOPE.md.

Overview

A reusable system for whitelisted, sanitized HTML and CSS content authored by users. The same primitive backs:

The feature is not "give users a text box and run DOMPurify on it." It's a typed, named profile of capabilities (allowed tags, attributes, CSS properties, length caps, URL schemes) that the calling site picks at the call site. Each context picks its own profile; the engine enforces it.

Strategic positioning

This is the foundation for almost every Pro-tier visual upgrade we plan. Rather than ship N bespoke "rich text" boxes — each with its own one-off sanitizer and edit UI — we ship one engine, configure it per context, and reuse the editor everywhere. New surfaces become a single config + a single component drop-in.


Goals

Non-goals


Library survey (third-party)

We are whitelist-only — every choice below is evaluated on whether it gives us an enforced allowlist, not blacklist heuristics.

Server (C# / .NET 10)

Library Verdict Notes
HtmlSanitizer by mganss (github.com/mganss/HtmlSanitizer) Pick this. Whitelist-based by design. Configurable allowed tags / attributes / CSS properties / URL schemes. Built on AngleSharp (real HTML5 parser, not regex). Actively maintained. Apache-2.0. Handles the CSS subset inside style="..." attributes too.
Ganss.Xss (same author, newer namespace) Same library; current package name. Use this NuGet package name (the Ganss.Xss rename happened a few releases ago).
AngleSharp.Css Useful as a complement Real CSS parser. Use for the page-wide <style> block sanitization where mganss' inline-style support isn't enough. Walk the AST, drop disallowed at-rules, properties, and url() values.
Markdig Not currently in the stack Markdown isn't rendered server-side today (descriptions are stored as plain text). If we ever add server-side markdown rendering, the natural composition is markdown → HTML → mganss sanitize → render. Out of scope here.
Custom regex Reject. Will be wrong. Use a parser.

Client (TypeScript)

Library Verdict Notes
DOMPurify (github.com/cure53/DOMPurify) Pick this. Industry standard. Whitelist config (ALLOWED_TAGS, ALLOWED_ATTR, FORBID_TAGS). Battle-tested. Used as the second line of defense before dangerouslySetInnerHTML.
postcss + postcss-safe-parser Pick this for CSS. Real CSS AST. We walk it, drop disallowed nodes, re-stringify. Same approach AngleSharp.Css gives us server-side, mirrored on the client.
CodeMirror 6 (codemirror.net/6) Pick this for the editor. ~200KB gzipped vs Monaco's ~2MB. Tree-shakeable. First-class HTML and CSS modes (@codemirror/lang-html, @codemirror/lang-css). Linting hook integrates with our sanitizer for inline error markers.
Monaco Editor Reject for now Too heavy for what is functionally a textarea with syntax highlighting. Reconsider only if a creator tool needs IntelliSense-class authoring.
sanitize-html Acceptable alternative npm-side equivalent of mganss. DOMPurify is more widely audited; prefer it.

Sandboxing / scoping

Approach Verdict
Container class scoping (.rich-content-{nonce} { ... }) Default. Cheap, composes with the rest of the React tree, allows page-level CSS to coexist with the editor chrome.
Shadow DOM Defer. Major render rewrite; breaks portal-rendered drawers; not needed if sanitizer is correct.
Sandboxed <iframe srcdoc> Reserve as escape hatch for the most permissive profile. Trades editor live-preview ergonomics for browser-enforced isolation.

Architecture

Profile-based configuration

A profile is a named bundle of rules. Profiles live in Core/RichContent/Profiles/ as static C# definitions. The TypeScript client receives the same profile config from a small read-only endpoint and uses it to drive both the editor's lint hooks and the client-side re-sanitization pass.

Gating is at the call site, not baked into the profile. The sanitizer engine is gate-agnostic — it sanitizes whatever it's handed. Authorization to author rich content is enforced by the endpoint that owns the content, using the substrate that already gates that surface:

So RichContentProfile carries no TierGate — gating is the caller's concern. Where a caller needs per-capability gating (Phase 3+), it maps the surface to a catalog feature_key, never to a limit-matrix row.

public sealed record RichContentProfile
{
    public required string Name { get; init; }                       // "profile.css", "section.html.basic", ...
    public required HtmlPolicy Html { get; init; }
    public required CssPolicy Css { get; init; }
    public required RichContentLimits Limits { get; init; }
    // No TierGate — authorization is enforced by the calling endpoint via the
    // profile slot (profile surfaces) or fn_get_user_feature_metadata (others).
}

public sealed record HtmlPolicy
{
    public bool Enabled { get; init; }                               // false ⇒ HTML stripped entirely
    public ImmutableHashSet<string> AllowedTags { get; init; }
    public ImmutableDictionary<string, ImmutableHashSet<string>> AllowedAttributes { get; init; }
    public ImmutableHashSet<string> AllowedUrlSchemes { get; init; } // {"http","https","mailto"}
    public bool AllowDataUriImages { get; init; }
    public bool AllowExternalImages { get; init; }
    public bool AllowIframes { get; init; }
    public ImmutableHashSet<string>? IframeAllowedHosts { get; init; }
}

public sealed record CssPolicy
{
    public bool Enabled { get; init; }
    public bool AllowPageWide { get; init; }                         // false ⇒ inline style="" only
    public ImmutableHashSet<string> AllowedProperties { get; init; }
    public ImmutableHashSet<string> AllowedAtRules { get; init; }    // e.g. {"media"}
    public ImmutableHashSet<string> AllowedUrlSchemes { get; init; } // usually {} — block url() entirely
    public ImmutableHashSet<string> ForbiddenValueTokens { get; init; } // {"expression(","javascript:","fixed","sticky","absolute"}
    public bool AllowImportant { get; init; }
}

public sealed record RichContentLimits
{
    public int MaxHtmlBytes { get; init; }
    public int MaxCssBytes { get; init; }
    public int MaxNodes { get; init; }                               // anti-DoS
    public int MaxNestingDepth { get; init; }
}

Built-in profiles (initial set)

Profile HTML CSS Use sites Gated by
text.plain none none fallback / downgrade target always (no gate)
text.markdown markdown-derived tag set, no style attr none character/mode descriptions today always (no gate)
text.rich.basic markdown set + <img>, <details>, <summary>, inline style="" (color/background/font-* only) inline only rich descriptions feature catalog (rich_descriptions)
section.html basic + tables, <figure>, <blockquote>, <hr>, classes inline only profile HTML section profile slot (per-profile)
profile.css n/a (CSS-only profile) page-wide allowed; allowlist of safe properties; no position, no url(), no @import, no @font-face profile dashboards profile slot (per-profile)
embed.iframe adds <iframe> from allowlisted hosts (YouTube, Spotify, Bandcamp) none future embed surface feature catalog (embeds)

text.markdown and text.rich.basic are intentionally separate engines. They share the profile registry shape but not the parser pipeline — markdown continues to flow through Markdig (markdown source → constrained HTML, no rich-content sanitizer involved), while rich runs through the HTML/CSS sanitizer described in this doc. The two cover different authoring intents:

Forcing the same engine on both either makes markdown authors deal with HTML sanitizer warnings on their **bold**, or forces rich authors to learn markdown escape rules. Two coherent paths beats one frankenpath. (Note: in the shipped character/package form these are not a tab strip that swaps one field for another — the plain description and the rich showcase are independent fields with their own editors. The plain description always renders inline; the rich showcase is a separate opt-in surface opened in a modal. See Phase 3 below.)

Engine

public interface IRichContentSanitizer
{
    SanitizedRichContent Sanitize(RichContentInput input, string profileName);
}

public sealed record RichContentInput(string? Html, string? Css);

public sealed record SanitizedRichContent(
    string? Html,
    string? Css,
    IReadOnlyList<RichContentWarning> Warnings,    // dropped tags, properties, etc. — surfaced to the editor
    string ContainerClass);                         // generated, deterministic per content hash

Implementation:

  1. Look up the profile by name. Unknown profile ⇒ throw at startup; this is a developer error, not a user error.
  2. HTML: feed through Ganss.Xss.HtmlSanitizer configured from the profile. Capture removed elements/attributes as warnings. Enforce node count and nesting depth on the AngleSharp document before serializing.
  3. CSS: parse with AngleSharp.Css. Walk the AST. For each declaration: drop if property not in allowlist, value contains a forbidden token, or url() scheme not in allowlist. For each at-rule: drop if not in allowlist. Reject @import outright. Re-emit.
  4. Wrap CSS rules under .rich-content-{containerClass} { ... } so the rules cannot leak past the rendered container. Selectors with :root, html, body are rewritten to the container class.
  5. Enforce byte limits on the post-sanitization output (so a creator can't bypass with verbose comments).

Storage

The engine itself is stateless. Each consumer owns its own column / JSON field. Recommended shape:

// stored as JSONB or as a dedicated column
{
  "profile": "profile.css",
  "html": null,
  "css": ".profile-page__about { background: #1a1a2e; }",
  "sanitizedAt": "2026-04-30T12:00:00Z",
  "engineVersion": 1
}

engineVersion is bumped when the sanitizer's behavior changes in a non-trivial way (new property added to the deny list, allowlist tightened in response to a CVE, selector rewriter rule change, etc.). On read, content stored under an older version is re-sanitized lazily and the result cached back.

Re-sanitization is observable. When lazy re-sanitization changes the output:

  1. Write an entity_changelog row (action='update', source='system', source_ref="rich_content_engine:{new_version}", changed_fields carrying the old/new HTML+CSS, summary="Custom CSS re-sanitized for security update — 3 rules removed"). The changelog table is already the canonical "what changed and why" log for entities; this slots in cleanly alongside collaborator edits and assistant edits. entity_changelog.user_id is NOT NULL REFERENCES users(id) — a system sweep has no actor, so supply the entity owner's user_id (creator profile) or a seeded service-account id; never NULL.
  2. Fire a notification to the entity owner via fn_emit_user_notification (triggered_by_user_id = NULL for system events) that deep-links to the changelog row ("Your profile CSS was updated for a security fix. View changes."). No dedicated NotificationType exists yet — reuse System (5) or add a ContentSanitized value. For project profiles the "owner" is ambiguous (any can_manage member could have authored the CSS) — notify all can_manage members, or the project's primary owner; decide before Phase 2.
  3. Surface the diff inside the editor next time it opens — same UI as the existing "3 properties were removed when this was saved" banner, but flagged as a sanitizer update rather than a write-time strip. The banner sticks until the user clicks "Acknowledge" or makes another edit.
  4. Cache the re-sanitized result keyed by (content_hash, engine_version) so the changelog row + notification fire once per (content, version), not on every read.

Silent mutation is the failure mode this defends against — every engine bump that changes a live profile leaves an audit trail and tells the creator.

API surface

Authorization (per surface)

The engine has no gate of its own. Each endpoint authorizes before invoking the sanitizer, using that surface's existing gate:

No surface reads subscription_tier_limits; the keys profile.customization / profile.max_tabs / profile.max_banners were dropped in 43b_remove_legacy_profile_limits.sql.

Slot gates application, not authoring (preview-as-Pro)

Two product decisions, locked:

  1. Lapse preserves, doesn't destroy. When a profile's slot lapses, its saved custom CSS/HTML stays in layout_config — it is simply not applied. The public profile renders the default (unthemed) layout; re-claiming a slot restores the theme instantly with zero re-authoring. Never strip or blank the stored value on lapse.
  2. The editor is a try-before-you-buy. A creator without an active slot can still open the editor and see their theme rendered in the preview pane — "this is how your profile looks with a slot." That makes the editor itself the upsell: build it, watch it come alive in preview, claim a slot to ship it live. The preview always renders the theme (it's the author's own session); the slot only decides whether the public render applies it.

Read-path requirement (new). fn_get_profile_page today renders the saved layout_config regardless of slot. To honor the above, the read path must resolve fn_profile_has_active_slot(entity_type, entity_id) and, when inactive, omit the custom CSS/HTML from the rendered output (the rest of the layout is unchanged — only the rich-content fields are application-gated). Push this into fn_get_profile_page itself (where the anonymity gate already lives and where the entity ids are in hand) rather than stripping in the C# enricher.

One reconcile to decide (Open Questions): UpsertCustomizationAsync currently rejects the entire save when there's no active slot, so today a no-slot user can't persist any customization. For the editor-as-preview flow to actually save a no-slot creator's theme, either (a) exempt the rich-content fields from the write-slot-gate (save the CSS even with no slot; it just won't apply), or (b) make the slot a pure apply-gate for all customization (no-slot users can save layout too, nothing applies until slotted). (b) is the cleaner mental model — "the slot publishes your customization" — but it's a behavior change to shipped layout gating; (a) is the bounded change scoped to this feature.

Catalog entries (non-profile surfaces only)

Profile surfaces need no new seed — the profile_slots feature already gates the editor (and thus its CSS/HTML fields). For Phase 3+ surfaces outside profiles, add a feature-catalog entry rather than a subscription_tier_limits row. Pattern, sibling to the launch catalog in 20l_tables_echo_feature_catalog.sql:

INSERT INTO echo_features (feature_key, label, description, icon, status, kind, sort_order) VALUES
    ('rich_descriptions', 'Rich descriptions',
        'Format character, mode, and lorebook descriptions with HTML and inline styles.',
        'sparkles', 'live', 'tiered', 70)
ON CONFLICT (feature_key) DO UPDATE SET
    label = EXCLUDED.label, description = EXCLUDED.description, icon = EXCLUDED.icon,
    status = EXCLUDED.status, kind = EXCLUDED.kind, sort_order = EXCLUDED.sort_order,
    updated_at = CURRENT_TIMESTAMP;

INSERT INTO echo_feature_tiers (feature_key, tier_key, label, echo_cost, sort_order) VALUES
    ('rich_descriptions', 'off', 'Plain / Markdown', 0,   10),
    ('rich_descriptions', 'on',  'Rich (HTML)',      200, 20)
ON CONFLICT (feature_key, tier_key) DO UPDATE SET
    label = EXCLUDED.label, echo_cost = EXCLUDED.echo_cost, sort_order = EXCLUDED.sort_order;

Access is read at the call site via fn_get_user_feature_metadata(user_id); the endpoint maps rich_descriptions='on' to the text.rich.basic profile, otherwise downgrades. Each new surface = one catalog feature, never a limit-matrix key. New catalog rows go in their own seed file (44_seed_rich_content_features.sql or similar) when we ship Phase 3+.


Edit UI

A single shared component:

<RichContentEditor
  profile="profile.css"
  value={draft.customContent}
  onChange={patchDraft}
  previewSlot={<ProfilePagePreview draft={draft} />}
/>

Layout

Three tabs: HTML, CSS, Preview. Profiles with Html.Enabled = false hide the HTML tab; same for CSS. Single-tab profiles render without the tab strip.

Editor tabs use CodeMirror 6 with:

Preview

The preview pane re-renders on every editor change (300ms debounce). It mounts <RichContentDisplay> inside an previewSlot provided by the host page so the preview matches the real layout context, not a generic mock.

For the most permissive profiles (e.g., embed.iframe once it ships) the preview falls back to a sandboxed <iframe srcdoc> so the host page can't be affected by a half-typed CSS rule mid-edit.

Editor UX rules

Editor mode toggle — Full vs Simple

The editor exposes a persistent toggle ("Full editor" / "Simple editor") in its toolbar. Choice is stored in localStorage under rich-content.editor-mode and applies across every <RichContentEditor> instance.

In-app profile reference modal

The editor toolbar has a "What can I use?" button that opens a modal rendered from the live profile registry (GET /api/rich-content/profiles). Source-of-truth allowlist, in-app, available from every editor instance:

This is distinct from the /docs/ page (see below): the modal answers "can I use X right now in this editor?" while editing; /docs/ answers "what is this feature and should I learn it?" before opening the editor.

Drawer placement

For profile dashboards, the editor lives in a new section in ProfileEditDrawer.tsx, following the existing Banner / Social Links / Tabs section pattern. Other surfaces drop the editor inline on their existing edit page.


Renderer

<RichContentDisplay content={sanitized} profile="profile.css" />

What it does:

  1. Calls DOMPurify.sanitize(content.html, profileConfig.htmlConfig) — second line of defense.
  2. Runs the CSS through postcss-safe-parser with the same allowlist the editor uses; drops anything new.
  3. Renders <style> (scoped under .rich-content-{containerClass}) and the HTML body inside a div carrying that class.
  4. The container has contain: paint; isolation: isolate to limit the visual blast radius.

Server-sanitized content is the source of truth; client re-sanitization exists to catch downgrades when the engine version moves and to make the live preview safe.


Platform chrome isolation — AppShell as the trust boundary

User CSS scoped to a container class is one half of impersonation defense. The other half is making sure the platform chrome (header, sidebar, nav, balance indicator, notifications, user menu) sits in a region user content cannot reach, visually or structurally. The client console's AppShell (clientConsole/src/components/common/AppShell.tsx — renamed from PageLayout for clarity; it's the persistent app shell, not a per-page layout) already provides most of that boundary — this section documents what it gives us for free and the small additions needed to make it the formal trust layer.

What AppShell already provides

AppShell is a layout-route component: mounted once at the parent route, child routes render into its <Outlet />. Per-route metadata is read from useMatches()[last].handle (a PageMeta object — title, hideSidebar, compactMobile, backTo).

That DOM shape means a profile page's user-authored CSS, scoped under .rich-content-{nonce} inside the outlet, cannot select, restyle, or visually overlay anything in the header or sidebar. The chrome is structurally above (in DOM order) and visually above (via z-index + backdrop filter).

Required additions

  1. New PageMeta flag: userContentScope?: boolean. Routes that render user-authored HTML/CSS at page scope (profile dashboards today, themed package readmes / project landing pages tomorrow) set this on their <Route handle={...}>. When true, AppShell:
    • Applies contain: paint; isolation: isolate to the <main> wrapper (limits paint and stacking-context escape to the content region).
    • Renders a small fixed "Custom theme · @slug" pill inside headerRight (outside <Outlet />, can't be hidden by user CSS). Visual trust signal for casual visitors and payment-processor reviewers.
  2. Drop z-index from every CSS profile's allowlist (or cap to a value below the platform floor). Header sits at 100, sidebar at 50–60; no user rule should approach those values. Position is already on the deny list, which is the primary escape vector — z-index removal closes the secondary one.
  3. Selector rewriter must cover main in addition to :root, html, body. AppShell's <main> is the immediate ancestor of the contained region; a main { ... } rule from a user would otherwise restyle the wrapper. Rewrite to the container class or drop.
  4. No structural changes to AppShell itself. Header, sidebar, background, and outlet wrapping are already in the right shape. The two additions (new flag, contain styles, trust pill) are additive — existing routes are unaffected.

What this does not cover


Migration / rollout

Phase 1 — Engine + profile-CSS. (SHIPPED.) Ship IRichContentSanitizer, the profile registry, the GET /api/rich-content/profiles endpoint, and the profile.css profile wired into the existing profile customization flow. The editor ships as a new section in the profile edit drawer. The slot gates public application of the theme (read-path fn_profile_has_active_slot check in fn_get_profile_page, so custom CSS applies only on slotted profiles), and rich-content fields are exempt from the write gate so a saved theme survives a lapse and re-applies on re-claim ("Slot gates application, not authoring").

Shipped entry point (diverges from the original preview-as-Pro sketch). The design above imagined the editor itself as the upsell — a no-slot creator opens the full drawer, previews "Preview only — claim a slot to make this live," and saves. That full-drawer-as-preview flow was not built (it exposes layout controls a no-slot save silently discards). Instead, opening edit mode requires a slot: a paying no-slot creator gets SlotClaimModal (claim for this profile + deep-link to the /account/slots management page); free users go to /pricing. See Open Questions #6–#7. The preview-as-Pro path remains the underlying capability (the write/read gates support it), just not the entry UX.

Phase 2 — Section HTML. (SHIPPED.) The 'html' section type lives in ProfileSectionCatalogService.Registry (full-tier; ComingSoon: false) and is gated through KnownSectionTypes + PaidTierSectionTypes. The section.html profile (structural-tag allowlist, no inline style, http/https/mailto only, CSS disabled; node/byte/depth caps 500 / 16 KB / 40) runs through the same RichContentSanitizer HTML branch (Ganss.Xss). ProfilePageService.ValidateSectionCore now normalizes html sections — NormalizeHtmlSection sanitizes and stores the safe form (never raw), including inside containers — and rejects unknown section types (closed the silent-pass leaf gap, ex-open-Q #5). Renderer HtmlSection → <RichContentDisplay> (DOMPurify second pass, purifySectionHtml); editor is the shared <RichContentEditor channel="html">. OG/crawler exclusion is locked by a CI-blocking test (Suite D). Full build log + scope decisions + the bugs caught in verification: docs-internal/archive/superseded/profile/RICH_CONTENT_PHASE2_DOD.md.

Re-sanitization on engine bumps (resolved). Lazy re-sanitization covers both the page-wide CSS theme and per-section html blocks: on owner read, ResanitizeIfStaleAsync re-runs the current sanitizer over any customContent or tabs[].sections[].config html block stamped with an older engineVersion, persists the lot in one write, and — when the new engine removed something — writes a system changelog row + notifies the owner. So a future allowlist tightening (e.g. a CVE response) re-sanitizes stored section blocks too, with an audit trail. The sweep is a no-op until the next HTML-tightening bump. (Implementation + tests: see RICH_CONTENT_IMPLEMENTATION.md Phase-2 known-gaps block, items 1–3.)

Phase 3 — Rich showcase (additive surface, NEVER a replacement).

Correction (2026-06-30). The first ship of the character/package read-path rendered the rich payload in place of the plain description (the shared EntityDescription was a rich-or-plain switch: present rich → render rich, hide plain). That is wrong. The rich payload is not an alternate rendering of the description — it is a separate, opt-in showcase surface: a creator-authored "mini page" for lore, presentation, or an extra information surface. The plain description is the primary field and always renders inline on the card and detail view; the rich showcase is reached through its own affordance and opens in a standalone modal (a self-contained mini-app surface). Creator bio is unaffected — it uses a single-field projection model (plain auto-derived from rich) on the profile About section, so there is no separate plain description to hide.

Add an optional sanitized rich-HTML payload (description_rich) to character / package entities alongside the existing plain-text description, never in place of it. Plain text is the primary, default surface; the rich showcase is an opt-in extra layer.

Phase 4 — Embed iframes. Add the embed.iframe profile. Ship an <EmbedSection> for profile dashboards that takes a YouTube/Spotify/Bandcamp URL and renders the embed via the iframe-host allowlist.

There is no global feature-flag table in the codebase today (the feature-flags.md planned doc describes a chat-scoped flag system, not a release toggle). Each phase ships gated by its surface's existing gate — Phase 1/2 by the profile slot (profile_slots feature), Phase 3+ by a new feature-catalog entry seeded as above. Kill-switches: for non-profile catalog features, flip the feature's status to coming_soon (it surfaces in the pricing catalog but enforces/unlocks nothing); for the profile editor section, hide it behind a SettingsKeys feature toggle so the slot still unlocks the rest of the editor.


Security boundaries

Threat Mitigation
<script>, event handlers, javascript: URLs Forbidden by every profile. mganss + DOMPurify both strip by default; verify per profile.
Full-page overlays (position: fixed/absolute) position is not in any CSS profile's allowlist. CSS sanitizer drops the property.
@import url(...), @font-face src: url(...), background: url(...) url() allowed schemes set is empty in profile.css; the parser drops the declaration.
expression(...) (legacy IE) Forbidden value token in every CSS profile.
content: attr(data-*) exfiltration content not in the allowlist for profile.css; attribute selectors generally allowed (low-risk inside container scope) but explicitly disallowed for selectors targeting elements outside .rich-content-*.
<iframe> to attacker site Iframes only allowed in embed.iframe profile, and only with src host on the allowlist.
Style escaping via :root, html, body, top-level descendant Selector rewriter rewrites these to the container class; selectors not rooted at the container are dropped.
!important cascade hijack AllowImportant defaults to false in profile.css.
DoS via huge or deeply-nested input MaxHtmlBytes, MaxCssBytes, MaxNodes, MaxNestingDepth enforced post-sanitization.
OG / crawler bot reflection OG endpoints continue reading only the small set of plain-text fields they read today (creator: username, avatar, plain-text bio, aggregate counts; project: name, plain-text description, cover image). They read no accent/layout/html/css columns today — verified in OpenGraphRepository.cs. The OG path must not start reading html/css/description_rich payloads. See "Anonymous viewers and crawler hardening" below.
CSS-based phishing / impersonation Container-scoped CSS + AppShell chrome-trust boundary (see "Platform chrome isolation" above) prevents overlay onto real chrome. Inline impersonation inside the profile is bounded by the "Custom theme · @slug" pill and community moderation.
External <img src> in section.html (tracking-pixel / visitor-IP leak) Accepted, not blocked. http/https are allowed img schemes so creators can embed external images; a visitor loading the profile hits whatever host the creator linked (same as any page with user-authored content). No proxy and no per-host img-src narrowing today. The mitigation path, if reassessed, is a CSP img-src allowlist or an image proxy — neither is in place. data: URIs ARE blocked (svg/script/exfil vector).
class="card" etc. — applying platform component class names inside a block Allowed (class is a global attribute, no value restriction) — it's the intended hook for the creator's own profile.css. Means a creator can visually echo platform UI inside their own content area; bounded by the "Custom theme · @slug" trust pill + container scope + moderation, not by a technical class allowlist. Deliberate design call.

Anonymous viewers and crawler / OG hardening

A profile is visible to logged-in users, logged-out users, search-engine crawlers, embed unfurlers (Discord, Slack, iMessage), and — non-trivially — payment-processor reviewers spot-checking the site. Each audience sees a slightly different view and needs explicit handling.

Per-profile RenderForAnonymous flag

Every rich-content profile declares whether its content renders for anonymous (logged-out) viewers:

public sealed record RichContentProfile
{
    // ... existing fields ...
    public bool RenderForAnonymous { get; init; }    // default false
}

Renderer checks this flag against the request's auth state before mounting <RichContentDisplay>; falls back to the plain text representation otherwise.

OG / crawler path

The cf-worker bot-rewriter (getBotRewritePath) routes crawlers to /og/creator/{slug} and /og/project/{slug}, which hit OpenGraphEndpoints. Hardening rules:

  1. OG endpoints never read description_rich, html, or css columns. Enforced by a test that snapshots OG output and asserts the response body contains no user-supplied rich-content payload. Hard-fails CI if a regression introduces the read.
  2. Crawler user-agent path is renderer-blind. Even on the SPA route, if a request matches a crawler UA and the cf-worker hasn't redirected (paranoia), the React renderer aborts the rich-content mount and falls back to plain.
  3. Cache headers stay strict. OG responses are Cache-Control: public, max-age=300 — short enough that a rich-content change isn't pinned in CDNs for hours, long enough to absorb crawler bursts.

Logged-out preview in the editor

The editor toolbar gets a "View as" dropdown. The author's default is Themed (with slot) — the preview-as-Pro view that always renders their theme so they can see what they're building. The other modes re-render the preview against the corresponding public render path: Logged-in viewer, Logged-out visitor, Crawler / OG. Crucially, for a profile without an active slot these public modes show the default (unthemed) render — making the gap between "what I'm building" and "what visitors see right now" explicit, which is the upsell. A small note ties it together: "Visitors see the unthemed version until you claim a slot."

This closes the "what does my profile actually look like to a stranger?" gap and incidentally answers the original open question about whether to expose a view-as-tier toggle.

Manifesto / brand-voice handoff

The editor's publish-confirmation modal carries a one-liner that surfaces the platform's content policy at the moment the creator commits public-facing CSS or HTML:

Your custom theme will be visible to logged-out visitors and to anyone Echo of Dreams shares a link with (Discord embeds, search snippets, payment-processor reviewers). Keep the public surface representable of your work — adult content belongs inside conversations and behind the rating, not in your profile chrome.

Copy is owned by /brand-voice skill, not hardcoded here — placeholder pending. The intent: set expectations once, at the right moment, in language the manifesto stands behind. Moderation policy gets a pointer to the same copy so removal reasoning is consistent.


User-facing documentation

Two surfaces, split by intent. The allowlist itself lives in the in-app modal (see "In-app profile reference modal" in the Edit UI section) — generated from the live profile registry, can never drift from code. The /docs/ site carries the editorial layer that the modal can't.

/docs/features/custom-themes.md (editorial)

A user-facing guide that the modal links to, not from. Hand-written, not generated. Sections:

Why not put the allowlist in /docs/?

The original instinct ("a reference page would reduce support load") is right about the support load part but wrong about the location part:

/docs/ sells the feature, sets expectations, and shows recipes. The modal answers the literal "can I use X?" question. Two artifacts, no overlap, no drift risk.


Testing strategy

The sanitizer is a high-trust component — a regression is a security incident, not just a UX bug. Three-layer test discipline:

Layer 1 — Profile regression corpus

A versioned corpus of known-bad inputs lives at server/EchoOfDreams.Core.Tests/RichContent/Corpus/. Each entry is a (profile_name, input_html, input_css, expected_output) tuple drawn from:

CI runs the full corpus on every PR. Any profile-output change against the corpus is a forced human review with sanitizer engineer sign-off.

Layer 2 — Allowlist boundary tests

For each profile, generate the transposed test set: for every tag/attribute/property not on the allowlist, assert the sanitizer drops it. For every entry on the allowlist, assert it survives. Generated, not hand-written — adding a new property to the allowlist regenerates the test automatically.

Layer 3 — Tier-scaled review cadence

Profile Review cadence Why
profile.css Quarterly Most permissive, page-wide, public-facing.
section.html, embed.iframe Quarterly Iframe surface and structural HTML.
text.rich.basic Annual Inline-only, narrow allowlist, on every entity page.
text.markdown Annual Smallest allowlist, mature tooling.
text.plain Never No allowlist to maintain.

Reviews are calendar events (not "when someone notices"), assigned to whoever currently owns the engine. Each review produces a short writeup committed alongside the profile definition: what was added, what was rejected, what near-misses to watch for next cycle.

Layer 4 — OG / crawler snapshot tests

Per the Anonymous viewers section: snapshot tests assert that no OG endpoint response contains any byte of user-authored html or css content. Fails CI immediately on regression.

Layer 5 — Phase 3 synthetic monitor

Once rich descriptions ship to characters / modes / lorebooks, a nightly job renders a representative sample (~1000 entities across tiers and entity types) headlessly and diffs against the previous night's render. Unexplained diffs fire a Sev-3. Catches engine drift before users notice.


Open questions

  1. CodeMirror packaging. Bundle once in shared/ or per-app? Both consoles can lazy-load it from shared/; the question is whether the bundle deduplicates cleanly across Vite builds. Resolve when implementing Phase 1's editor.
  2. Storage shape for non-profile surfaces. Single JSONB blob vs separate *_html / *_css columns. Lean toward a single rich_content JSONB across the codebase for consistency.
  3. Read-path behavior when the slot lapses — RESOLVED. The saved custom CSS/HTML stays in layout_config; it is just not applied when the slot is inactive — the public render falls back to default/unthemed, and re-claiming a slot restores the theme with no re-authoring. Implemented via an fn_profile_has_active_slot check pushed into fn_get_profile_page (see "Slot gates application, not authoring"). The same gate doubles as the preview-as-Pro upsell: the editor always renders the theme; only the public read path is gated.
  4. Per-profile slot cost scales with profile count. Because the slot is per-profile, a creator who wants custom CSS on their creator profile and three project profiles needs four slots (4 × 300 Echoes). That's the intended model (slot = "full editor for this one profile"), but the pricing/upsell copy must make the per-profile cost obvious so a creator isn't surprised that theming project #2 costs again. Surface it at the slot-claim step, not after.
  5. 'html' section type passes validation silently today. ValidateSectionCore has no allowlist of leaf section types — an unregistered type isn't rejected, only the tier gate runs. Phase 2's section.html block must add an explicit validator leaf that enforces the byte/node/depth caps, not rely on the pass-through. Registry entry + PaidTierSectionTypes membership alone would gate access but skip content limits.
  6. Write-gate reconcile for editor-as-preview — RESOLVED (path a shipped). UpsertCustomizationAsync no longer hard-rejects a no-slot save: rich-content fields are exempt from the write-slot-gate (saved even with no slot; the read path apply-gates them), while layout customization still needs a slot. Path (b) — slot as a pure apply-gate for all customization — remains the cleaner end-state but is a behavior change to shipped layout gating, deferred to a later unification, not a Phase-1 dependency.
  7. Editor-as-preview entry point — RESOLVED: not built; replaced by the slots page. The speculative "no-slot creator opens the full editor drawer and previews their theme as-if-Pro" flow was dropped — the full drawer exposes layout controls a path-(a) save silently discards, which is confusing, and gating those controls well is a UX project not worth the muddle. Shipped instead: clicking "Edit profile" without a slot opens SlotClaimModal (held-slot count + claim-for-this-profile at 300 ✶/mo + a "Manage all your slots →" link to /account/slots), and the ProfileSlotsPage is the full management surface (active slots, per-profile claim, stop/resume renewal). Free users route to /pricing. This keeps the per-profile slot model legible — "you have X slots — Apply / Manage" — without a half-built preview drawer.

Files this will touch

Dependencies to add