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:
- Profile dashboards — page-wide custom CSS, custom HTML sections.
- Character / mode / lorebook descriptions — richer than markdown, safer than freeform HTML.
- Project landing pages, package readmes, creator changelogs — long-form rich content.
- Anywhere we currently render plain text or markdown and want a Pro upgrade path.
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
- Single sanitization engine with named profiles. Adding a new surface = picking or defining a profile, not writing new sanitizer code.
- Whitelist-only, server-authoritative. Allowlists declared in C#, mirrored to TypeScript for client preview parity.
- Gating rides the existing profile substrate, not a new limit table. Profile surfaces (
profile.css,section.html) are editor capabilities unlocked by an active profile slot on that specific profile — creator or project. The slot unlocks the full editor for that particular profile; nothing checks the editor's personal tier. Non-profile surfaces (rich descriptions, embeds) gate on a feature-catalog entry (echo_features→fn_get_user_feature_metadata). Nothing reads the retiredsubscription_tier_limitsmatrix. - Reusable editor component — single
<RichContentEditor>accepting a profile name, rendering a tabbed editor (HTML / CSS / Preview) with live preview. - Reusable renderer component — single
<RichContentDisplay>that re-sanitizes client-side and scopes styles to a generated container class. - Defense in depth — sanitize on write, sanitize on read, scope CSS via container class, contain layout via
contain: paint; isolation: isolate.
Non-goals
- Not a full WYSIWYG. Authors write HTML/CSS directly with syntax-highlighted editors.
- Not a CMS. No version history, no collaborative editing.
- Not a templating engine. No variable interpolation; no Handlebars/Liquid/etc.
- Not a JavaScript runtime.
<script>, event handlers, and any executable surface are forbidden in every profile.
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:
- Profile surfaces (
profile.css,section.html). The dashboard editor is unlocked per-profile by an active profile slot —IProfileSlotRepository.IsActiveForEntityAsync(entityType, entityId), creatorentity_type=3or projectentity_type=7; PremiumBypassLimitsshort-circuits. A slot is aquantity-kind feature in theecho_featurescatalog (feature_key='profile_slots'), committed throughuser_feature_commitments. The slot unlocks the full editor for that particular profile — including custom CSS/HTML. There is no separate per-actor "is Pro" check and nosubscription_tier_limitskey: if the profile-customizationPUTaccepted the layout (slot active), the rich-content fields on that layout are authorized too. - Non-profile surfaces (Phase 3 descriptions, Phase 4 embeds). No profile slot exists for these. Add a feature-catalog entry (
echo_featuresrow +echo_feature_tiersrows) and resolve access viafn_get_user_feature_metadata, exactly likegallery/conversation_retention.
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:
text.markdownis a writing tool: prose with light formatting (**bold**,_italic_, links, lists). The mental model is "I'm writing words; the tool emphasizes them." Markdig's output set is already narrow and safe by construction — wrapping it in the rich-content sanitizer adds no security and adds a lot of false-positive warnings on legal markdown.text.rich.basicis a layout tool: an opt-in upgrade where the creator authors HTML directly to get visual structure (a styled blockquote, an inline image with a caption, a<details>reveal). The mental model is "I'm building a small page." Markdown sugar in this path would just confuse authors who came here specifically to write tags.
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:
- Look up the profile by name. Unknown profile ⇒ throw at startup; this is a developer error, not a user error.
- HTML: feed through
Ganss.Xss.HtmlSanitizerconfigured from the profile. Capture removed elements/attributes as warnings. Enforce node count and nesting depth on the AngleSharp document before serializing. - 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@importoutright. Re-emit. - Wrap CSS rules under
.rich-content-{containerClass} { ... }so the rules cannot leak past the rendered container. Selectors with:root,html,bodyare rewritten to the container class. - 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:
- Write an
entity_changelogrow (action='update',source='system',source_ref="rich_content_engine:{new_version}",changed_fieldscarrying 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_idisNOT NULL REFERENCES users(id)— a system sweep has no actor, so supply the entity owner'suser_id(creator profile) or a seeded service-account id; never NULL. - Fire a notification to the entity owner via
fn_emit_user_notification(triggered_by_user_id = NULLfor system events) that deep-links to the changelog row ("Your profile CSS was updated for a security fix. View changes."). No dedicatedNotificationTypeexists yet — reuseSystem(5) or add aContentSanitizedvalue. For project profiles the "owner" is ambiguous (anycan_managemember could have authored the CSS) — notify allcan_managemembers, or the project's primary owner; decide before Phase 2. - 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.
- 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
GET /api/rich-content/profiles— returns the public-safe view of all profiles (allowed tags, properties, limits, tier requirement). Cached aggressively (max-age=3600, immutable per deploy). Used by the editor for lint config and by the client renderer for the second sanitization pass.- No write endpoints. Sanitization happens inside whichever endpoint owns the content (profile customization PUT, character description PUT, etc.). Each endpoint resolves the profile name from its context, calls
IRichContentSanitizer.Sanitize, persists the result.
Authorization (per surface)
The engine has no gate of its own. Each endpoint authorizes before invoking the sanitizer, using that surface's existing gate:
- Profile surfaces (
profile.css,section.html) — for these fields the slot gates application on the public read path, not authoring. Anyone with edit permission on the profile (creator on their own;can_managemember on a project) can open the editor, write CSS/HTML, see it rendered live in the preview pane, and save it — the sanitized value persists inlayout_configregardless of slot state. The public render applies it only when the profile has an active slot (fn_profile_has_active_slot); with no active slot the render falls back to the default (unthemed) output while the stored value is left untouched. PremiumBypassLimitsprofiles always apply. The slot is per-profile, so theming is unlocked one profile at a time, and a project profile applies independently of its members' personal subscriptions. See "Slot gates application, not authoring" immediately below — this is a deliberate move of the rich-content gate from the write path to the read/apply path. - Non-profile surfaces — the owning endpoint resolves the surface's
feature_keyviafn_get_user_feature_metadata. If the feature isn't unlocked, the endpoint silently downgrades to the safest profile (text.plain/text.markdown) for layout-ish fields, or rejects with 403 when the request explicitly selected the richer profile. Default: silent-downgrade for descriptions, 403 for explicit profile selection.
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:
- 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. - 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:
@codemirror/lang-html/@codemirror/lang-cssfor syntax highlighting.- A custom lint extension that calls a debounced (500ms) client-side sanitization pass and emits diagnostics for every dropped tag/property/value, inline in the gutter.
- Byte-count footer (
1,247 / 8,192 bytes) per tab.
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
- No autosave from the editor itself. It calls
onChange; the host's existing autosave (3s debounce inuseProfileDraft) handles persistence. - Cmd/Ctrl+S force-flushes the host autosave (already wired).
- Diff between server-sanitized and editor input surfaces as a banner: "3 properties were removed when this was saved. View." Clicking opens a modal listing every warning from the last server response.
- Reset to default button (per profile) — clears the field to the empty string.
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.
- Full editor (default on desktop). CodeMirror 6 with syntax highlighting, gutter, inline lint diagnostics, byte-count footer. The richer authoring experience.
- Simple editor (default on mobile, available everywhere). Plain
<textarea>with monospace font, server-side validation on blur/debounce, warnings rendered below the textarea. No CodeMirror bundle loaded for the user's session.- Why it exists for everyone, not just mobile:
- Paste-from-AI flow. A creator generating CSS in another chat and pasting it in doesn't want CodeMirror's auto-indent / bracket-matching reformatting the paste. A textarea is faithfully literal.
- Testing / debugging. The dev can verify that the server-side sanitizer behaves identically whether the input went through CodeMirror's lint hook or not. Catches a class of bug where the lint hook silently pre-fixes things the server wouldn't.
- Accessibility / preference. Screen-reader users and users on older browsers get a known-good fallback without us having to special-case detection.
- Why it exists for everyone, not just mobile:
- Bundle behavior. CodeMirror is loaded via
React.lazyonly when the user selects Full mode (or has Full mode persisted). Users who never touch the editor — most of the user base — never download it. Users in Simple mode never download it.
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:
- Per-tab section. HTML tab: allowed tags + per-tag attributes. CSS tab: allowed properties + at-rules + URL schemes + forbidden value tokens. Both tabs: byte / node / depth caps.
- Per-profile. The modal scopes to the profile the editor is currently configured with (
profile.css,section.html, etc.). A small dropdown lets the user peek at other profiles to compare ("what would I get if I upgraded?" — Pro upsell). - Working copy-paste snippets. Each profile ships a small bundle of valid example snippets (a basic CSS theme, a section-HTML layout, a markdown-with-images description). One-click copy into the editor.
- Deep-link from warnings. When the server-side sanitizer drops a rule, the warning banner ("
positionwas removed") links to the modal scrolled to the relevant entry with the reason ("positionis not allowed — would let custom CSS escape the profile region"). - Available in both editor modes. Full and Simple share the same modal; both surface the "What can I use?" button.
- Generated, not maintained. The modal's content endpoint reads the profile registry directly — adding a new property to the allowlist in C# instantly updates the modal. No drift between code and docs.
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:
- Calls
DOMPurify.sanitize(content.html, profileConfig.htmlConfig)— second line of defense. - Runs the CSS through
postcss-safe-parserwith the same allowlist the editor uses; drops anything new. - Renders
<style>(scoped under.rich-content-{containerClass}) and the HTML body inside a div carrying that class. - The container has
contain: paint; isolation: isolateto 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).
- Sticky glass header at
z-index: 100withbackdrop-filter: blur(12px)containing logo, page title,EchoBalanceIndicator,NotificationBell,UserDropdown. Rendered outside<Outlet />— not reachable through the DOM tree from inside a profile page's content. - Sidebar / mobile drawer at
z-index: 50–60— same containment. - Theme background rendered as a fixed
z-index: -1div at the layout root, outside the content container. <main>wraps<Outlet />— natural mount point for acontain: paint; isolation: isolateboundary when a route opts in.
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
- New
PageMetaflag: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: isolateto 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.
- Applies
- Drop
z-indexfrom 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-indexremoval closes the secondary one. - Selector rewriter must cover
mainin addition to:root,html,body.AppShell's<main>is the immediate ancestor of the contained region; amain { ... }rule from a user would otherwise restyle the wrapper. Rewrite to the container class or drop. - No structural changes to
AppShellitself. 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
- Inline impersonation inside a profile. A creator can still author CSS that visually mimics a "tip received" toast or a "verified" badge inside their own profile content area. The container scope means it can't overlap the real chrome, but a user scrolling through the profile could still be confused by an artistic recreation. Mitigated by the "Custom theme · @slug" pill (clear scope indicator) and community moderation.
- AdminConsole / non-
AppShellsurfaces. Admin areas, the landing page, the auth flow do not use the layout-routeAppShelland should not render user-authored rich content. Enforced by gating<RichContentDisplay>use to routes mounted under theAppShellroute, plus a runtime assertion in dev. - Name resolution. This component was originally called
PageLayout, which was misleading (it's not a per-page layout — it's the persistent app shell with<Outlet />). It was renamed toAppShellas part of preparing this design; theclientConsole/CLAUDE.mdpage-pattern example was corrected at the same time. The admin console still has a separatePageLayoutcomponent, which is accurately named (it wraps each admin page's content with{ title, children }) — no collision.
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/slotsmanagement 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
htmlblocks: on owner read,ResanitizeIfStaleAsyncre-runs the current sanitizer over anycustomContentortabs[].sections[].confightml block stamped with an olderengineVersion, 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: seeRICH_CONTENT_IMPLEMENTATION.mdPhase-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
EntityDescriptionwas 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 plaindescriptionis 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.
- Schema: nullable
description_rich JSONBcolumn per entity table. Plaindescriptionstays as-is and is independent — authored separately, never derived from or overwritten by the rich payload. - Read path (additive, not a switch): the plain
descriptionalways renders inline wherever it does today. Whendescription_richis present, the detail surface additionally shows a "View showcase" affordance that opens a standalone showcase modal rendering the sanitized rich HTML via<RichContentDisplay>. The rich payload never replaces or hides the plain description. Absent rich → no affordance, detail view unchanged. Zero-risk for existing content (every row startsdescription_rich = NULL). - Write path: the edit form carries a separate rich-showcase editor (its own
RichContentEditor,text.rich.basicprofile) next to — not toggled against — the plain description field. Editing one never mutates the other; three-state surgical updates (omit = preserve, null = clear, object = set). - Editor default: nothing authored. Rich is purely opt-in; a creator who writes only a plain description gets exactly today's detail view with no extra surface and no obligation to learn the allowlist.
- Rollout (shipped):
creator.bio(projection, About section) → characters → packages. Modes / lorebooks deferred — not a primary discovery surface. - Server-rendered HTML cache. Each write produces a pre-sanitized HTML blob stored alongside the source
RichContentInput. The read path serves the cached HTML — no re-parse per render. Invalidated on edit or engine-version bump (which triggers the entity-changelog write path above).
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
}
profile.css,section.html,text.rich.basic⇒true(profiles look right when shared publicly; that's the point).embed.iframe⇒false(don't autoplay third-party embeds to crawlers; only render to authenticated sessions).- New profiles default to
false; opt-in is deliberate.
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:
- OG endpoints never read
description_rich,html, orcsscolumns. 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. - 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.
- 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."
- Logged-out visitor shows the same rich-content view but with the platform's logged-out chrome (sign-in CTA in header, no balance indicator).
- Crawler / OG shows the plain-text fallback — what a payment-processor reviewer or Discord unfurler will see.
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:
- What custom themes are. Plain-English intro: why a creator might want them, how they're scoped to the creator's own profile, the boundary against impersonating platform UI.
- What a profile slot unlocks. Default profile (no slot — standard layout, no custom CSS) → slotted profile (full editor incl. custom CSS + section HTML), per-profile and applying to creator and project profiles. Rich descriptions on other surfaces unlock via their own feature-catalog entry. Pricing context with a deep-link to
/pricing. - Getting started recipes. Three or four curated examples: a dark-academia theme, a soft-pastel theme, a minimalist text-only theme, an embed-heavy "linktree-style" profile. Real CSS, screenshots, copy-paste blocks.
- Common patterns. "How do I change the section card background?", "How do I add a custom font?" (answer: you can't —
@font-faceis blocked; pick from the bundled font stack and link to that section of the modal), "Why did my rule disappear?" (link to the modal's deep-linked warnings). - Brand-voice / public-surface reminder. The same one-liner the publish-confirmation modal carries — sets expectations once in the docs path too.
- Link to the in-app modal. "For the exhaustive list of every allowed tag and property, open your profile editor and click 'What can I use?'." This intentionally avoids duplicating the registry into Markdown that would rot.
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:
- The allowlist updates every time the engine ships a new property or tightens a rule. A Markdown table would lag.
- A reader looking at
/docs/doesn't know which profile applies to their current editor —profile.cssvssection.htmlhave different allowlists. The modal knows because it's mounted from the editor. - The "deep-link from warnings" UX collapses the question loop: drop happens → click the warning → land on the exact entry in the modal explaining why. That round-trip is impossible if the reference lives on a different domain.
/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:
- OWASP XSS Filter Evasion Cheat Sheet (HTML payloads).
- HackerOne / Bugcrowd reports against similar features (Tumblr theme injection, Discord profile bio CSS, Substack custom domain CSS).
- Internal payloads added each time the engine is bumped or a profile is widened.
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
- CodeMirror packaging. Bundle once in
shared/or per-app? Both consoles can lazy-load it fromshared/; the question is whether the bundle deduplicates cleanly across Vite builds. Resolve when implementing Phase 1's editor. - Storage shape for non-profile surfaces. Single JSONB blob vs separate
*_html/*_csscolumns. Lean toward a singlerich_contentJSONB across the codebase for consistency. Read-path behavior when the slot lapses— RESOLVED. The saved custom CSS/HTML stays inlayout_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 anfn_profile_has_active_slotcheck pushed intofn_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.- 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.
'html'section type passes validation silently today.ValidateSectionCorehas no allowlist of leaf section types — an unregistered type isn't rejected, only the tier gate runs. Phase 2'ssection.htmlblock must add an explicit validator leaf that enforces the byte/node/depth caps, not rely on the pass-through. Registry entry +PaidTierSectionTypesmembership alone would gate access but skip content limits.Write-gate reconcile for editor-as-preview— RESOLVED (path a shipped).UpsertCustomizationAsyncno 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.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 opensSlotClaimModal(held-slot count + claim-for-this-profile at 300 ✶/mo + a "Manage all your slots →" link to/account/slots), and theProfileSlotsPageis 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
- New:
server/EchoOfDreams.Core/RichContent/— engine, profiles, models. - New:
server/EchoOfDreams.ServerAPI/Api/Endpoints/RichContentEndpoints.cs— read-only profile listing. - New:
shared/src/components/common/RichContentEditor.tsx,RichContentDisplay.tsx+ showcase entries. - New:
shared/src/api/richContent.ts— typed profile fetcher. - Modified:
server/EchoOfDreams.Core/Services/ProfilePageService.cs— call into sanitizer for the new fields. - Modified:
server/EchoOfDreams.Core/Models/ProfileLayoutConfig.cs— addcustomContentfield carrying aRichContentInput. - Modified (Phase 3+ only):
database/v1/20l_tables_echo_feature_catalog.sqlor a new sibling seed — feature-catalog rows for non-profile surfaces. Profile surfaces (Phase 1/2) need no seed — gated by the existingprofile_slotsfeature. - Modified:
clientConsole/src/pages/profile/edit/ProfileEditDrawer.tsx— new section embedding<RichContentEditor>. - Modified:
clientConsole/src/pages/profile/ProfilePage.tsx— render<RichContentDisplay>inside the contained.profile-pagediv. - Future (Phase 2+): new
HtmlSectionRenderer, character/mode/lorebook description form updates.
Dependencies to add
Ganss.Xss(NuGet) — server HTML sanitizer.AngleSharp.Css(NuGet) — server CSS parser.dompurify(npm) — client HTML sanitizer.postcss+postcss-safe-parser(npm) — client CSS parser.codemirror+@codemirror/lang-html+@codemirror/lang-css+@codemirror/lint(npm) — editor.