Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

24.7 KB
Raw Blame

Rich Text Descriptions

Status: Implemented (2026-08-09) — all five phases in, including the 6.0 allowlist tightening. ActionText is gone from every model, the mobility-actiontext dependency is dropped, field + field_html reads are live across Product, Category, Collection, Policy, Order and Customer (writes stay on the plain attribute), the allowlist is scoped to the Tiptap-emitted set, and spree:migrate_rich_text_to_columns is in the 5.6→6.0 upgrade manifest. The action_text_rich_texts tables deliberately survive to 6.1 as the data migration's source and rollback path. Target: Spree 5.4 (serializer split ✓) + 5.6 (sanitization — permissive allowlist ✓) + 6.0 (ActionText removal ✓ — entirely, dependency included) Depends on: 6.0-admin-spa.md (Tiptap is the only editor at 6.0 — no legacy admin), 6.0-replace-taxons-with-categories.md (sequencing: Phase 3 shipped after the spree_taxons table rename, so spree:migrate_rich_text_to_columns runs after migrate_taxons_to_categories_and_collections in the manifest — that step retypes the Action Text rows so the copy can still find them; that plan owns the translation-table renames), 5.4-6.0-custom-fields-rename.md (CustomFields::RichText value storage migrates here), 5.4-metafield-translations.md, 5.5-6.0-resource-translations-api.md (translated HTML flows through the same sanitizer) Author: Damian + Claude Last updated: 2026-08-10

Summary

Standardize how rich text (product descriptions, category descriptions, policy bodies, custom-field rich text, internal notes) is stored and served. Move off ActionText as a storage backend in favor of sanitized plain HTML text columns, since the 6.0 admin uses Tiptap (not Trix). Unify the API shape: every rich text field reads as field (plain text) + field_html (HTML). Writes stay on the plain attribute — the value is HTML either way, so a second setter would only be a second spelling of the same write.

Scope expansion vs the original draft (2026-07-27 review): ActionText is removed entirely at 6.0 — including CustomFields::RichText values and Order/User internal notes, which the original draft deferred. Both deferrals collapsed under scrutiny: the dashboard already writes Tiptap HTML into rich-text custom fields today (through ActionText's Trix allowlist — the exact bug this plan exists to fix), and at 6.0 the SPA's internal-note editor is the only editor, so "stays on ActionText for the Rails admin" describes a UI that no longer exists. With those two migrated, nothing in core uses ActionText and the dependency is dropped.

Problem

Rich text storage is inconsistent across models (state at HEAD, 2026-07-27):

Model Storage Translation API output
Product text column Mobility (table backend) description (plain) + description_html ✓ shipped 5.4 — but unsanitized
Taxon ActionText Mobility (action_text backend) description + description_html (reading ActionText objects)
Policy ActionText Mobility (action_text backend) body + body_html (reading ActionText objects)
CustomFields::RichText ActionText (has_rich_text :value, ignores its own value column) per 5.4-metafield-translations.md serialized via value.body
Order#internal_note ActionText none Admin API: plain text only (internal_note)
User internal_note ActionText none Admin API: HTML only (internal_note_html) — inconsistent with Order
  1. ActionText is a Trix companion, not a generic HTML store. It sanitizes against Trix's allowlist, which strips valid Tiptap output; it wraps content in <div class="trix-content"> and uses <action-text-attachment> tags. The dashboard's Tiptap editor already writes custom-field rich text through this today — silent corruption in production, not a future risk.
  2. No sanitization exists anywhere on the shipped path. Admin API :description writes are stored raw and served as description_html to storefronts. The concern/sanitizer classes in the original draft (SanitizableRichText, RichTextSanitizer) were never implemented — verified repo-wide.
  3. Inconsistent shapes. The two internal-note serializers ship opposite conventions (plain-only vs html-only); write params accept HTML under plain field names.

Key Decisions (do not deviate without discussion)

  • Store HTML in text columns. Tiptap produces HTML via editor.getHTML(). No ActionText, no Tiptap JSON — HTML is universally consumable (storefronts, emails, search, feeds, mobile); the admin is the only writer.
  • ActionText is dropped entirely at 6.0 — code in 6.0, tables in 6.1. All five users migrate in 6.0 (Taxon, Policy, CustomFields::RichText, Order#internal_note, User internal_note), and 6.0 removes the runtime surface: the mobility-actiontext gemspec dependency, the has_rich_text/backend: :action_text declarations, and the model-generator template line. The action_text_rich_texts tables are dropped in 6.1 with the other legacy-table drops (data is copied out in 6.0; the tables linger one release as the rollback path — the same convention spree_adjustments follows). Nokogiri (already used by the shipped helper, but only a transitive dependency) is declared in spree_core.gemspec.
  • One write path, two read shapes (revised on implementation, 2026-08-10). The draft called for field_html write params and treated read/write symmetry as non-negotiable. That was dropped: the value is HTML whichever name it arrives under, so a field_html= setter was a second spelling of field= — it broke every existing client to match a read field that deliberately returns something else (plain text, for meta tags, search and feeds). Writes are therefore unchanged from 5.6 (description, internal_note, body), sanitized by a before_save; field_html is a reader only, and no field_html= exists on any model. Pinned by sanitizable_rich_text_spec.rb and categories_controller_spec.rb.
  • Sanitize on write, allowlist scoped to what the editor emits. The dashboard's Tiptap is StarterKit + Link (bold/italic/strike, lists, blockquote, code/pre, headings, links). The allowlist matches that — no style; class only as a code block's language-* hint, which is the one class Tiptap emits (resolving the original draft's open question flagging both as attack vectors), no tables/img/figure/span/div until the editor gains them (each future extension widens the allowlist deliberately). Server-side via Loofah scrubbers — a PermitScrubber for tags/attributes, preceded by one that prunes script/style subtrees and narrows class — both applied to a single parsed fragment.
  • Plain text extraction via the shipped Spree::RichTextHelper (app/helpers/spree/rich_text_helper.rb) — it deliberately maps block boundaries and <br> to newlines; the original draft's .text.squish would glue Tiptap's whitespace-free blocks together. Serializers standardize on it.
  • Internal notes standardize on the same shape: both Admin serializers expose internal_note (plain) + internal_note_html; controllers permit the plain internal_note. Text columns on spree_orders/spree_customers, no translations.
  • Rake tasks never hardcode table names (Spree::Taxon.table_name etc.) — Phase 3 must survive shipping before or after the spree_taxons → spree_categories rename, though the intended order is before.
  • Models with plain-text-only descriptions keep simple text columns (Promotion, PaymentMethod, Store, PriceList, CustomerGroup) — no _html variant.

Design Details

Storage + translations

All rich text fields are text columns on the model's own table, translated via the Mobility table backend. Current-code forms (the original draft's snippets were stale):

class Spree::Taxon < Spree.base_class
  TRANSLATABLE_FIELDS = %i[name pretty_name description permalink].freeze
  RICH_TEXT_TRANSLATABLE_FIELDS = %i[description].freeze
  translates(*TRANSLATABLE_FIELDS, column_fallback: Spree.mobility_column_fallback)
  # Removed: translates :description, backend: :action_text   (taxon.rb:164)
end
# Policy: same shape with body (RICH_TEXT_TRANSLATABLE_FIELDS = %i[body]); Product already correct.

RICH_TEXT_TRANSLATABLE_FIELDS stays — it drives the SPA translation matrix's rich-text editor (translatable_rich_text_fields).

Sanitization

module Spree
  class RichTextSanitizer
    # Matches the dashboard Tiptap editor (StarterKit + Link). Widen ONLY when the editor gains a node type.
    ALLOWED_TAGS = %w[h1 h2 h3 h4 h5 h6 p br hr ul ol li a strong em u s del sub sup blockquote pre code].freeze
    ALLOWED_ATTRIBUTES = %w[href target rel].freeze   # no style, no class — resolved 2026-07-27

    def self.sanitize(html)
      Rails::HTML5::SafeListSanitizer.new.sanitize(html, tags: ALLOWED_TAGS, attributes: ALLOWED_ATTRIBUTES)
    end
  end
end

module Spree
  module SanitizableRichText   # concern: has_spree_rich_text :description — before_save allowlist pass + field_html reader
  end
end

Applied to every rich-text writer path — which includes CSV import (import_schemas/products.rb maps description raw; the before_save hook covers it) and the translations batch endpoint.

Write bridge (per model)

class Spree::Product < Spree.base_class
  include Spree::SanitizableRichText
  has_spree_rich_text :description

  # `has_spree_rich_text` defines the `description_html` reader and sanitizes
  # writes made to `description` — there is no `description_html=` writer.
end

Controllers permit the plain names — :description (products, categories), :body (policies), :internal_note (orders, customers) — which sanitizes_rich_text cleans on save. An earlier draft of this line said *_html; that contradicted this plan's own summary ("writes stay on the plain attribute") and was never implemented. The field_html reader has no writer.

Serializers

Product shipped in 5.4 (product_serializer.rb:48-56) and is the reference. Category/Policy switch from reading ActionText objects (.to_plain_text / .body.to_s) to RichTextHelper.to_plain_text(record.description) + record.description.to_s. Both internal-note serializers converge on internal_note + internal_note_html (today Order ships plain-only, Customer ships html-only — both wrong against this plan's own convention).

Consumers of raw HTML (all routed through the helper/sanitizer in Phase 5)

  • Meilisearch indexing (search_provider/product_presenter.rb:52) indexes raw HTML — tag names become searchable tokens; switch to RichTextHelper.to_plain_text.
  • Google data feed (data_feeds/google_presenter.rb:68) emits raw HTML into g:description against Google's plain-text guidance — same fix.
  • CSV export (csv/product_variant_presenter.rb:88 — description&.html_safe) — export the HTML but drop the spurious html_safe.
  • Emails render no descriptions (verified) — no work.

Translations surface (deliberate, documented divergence)

The 5.5-6.0-resource-translations-api.md matrix keys stay model-attribute-based: { "fr" => { "description" => "<p>…</p>" } } with the field's type: 'html' hint — HTML in both directions, symmetric within that surface. The resource-level pair remains description/description_html. Translated HTML passes through the same sanitizer on write.

Migration Path

Phase 1 (remainder): Sanitizer — ships in 5.6.2 (implemented 2026-07-28), it closes a live hole ✳

Implemented and registered as the sanitize_rich_text step in the 5.5→5.6 upgrade manifest, so spree:upgrade runs it automatically — both for 5.5 upgraders and for existing 5.6.x installs re-walking the manifest on the patch bump (every step is idempotent by contract). Upgrade guide: docs/developer/upgrades/5.5-to-5.6.mdx (incl. the iframe allowlist warning). Decided 2026-07-27: don't wait for 6.0.

Severity (corrected 2026-07-28). This is defense-in-depth and 6.0 preparation, not a live-XSS fix. On 5.x the lower-trust writers are Enterprise vendors, and the spree_multi_vendor gem already covers them: Spree::SanitizeConcern, applied as sanitize :description, :meta_description, if: -> { vendor_id.present? }. Every remaining core writer is privileged (admin JWT, write_products keys, CSV import).

The real driver is 6.0-multi-vendor-marketplace.md. That gem is 5.x-only — its multi-vendor functionality is rewritten as native core models for 6.0 — so at 6.0 the vendor write path lands in core without the concern that protects it today. Core needs its own sanitizer before that happens, and shipping it in 5.6.2 gets the primitive exercised and its allowlist merchant-tuned a full release ahead of the rewrite.

Treat the Enterprise concern as prior art to absorb, not a dependency to coordinate with — two lessons carry over to the core implementation:

  • Sanitize on write, not on read. Enterprise derives sanitized_description at read time, so the stored value stays raw and only call sites that remember the sanitized_* prefix are protected. Core sanitizes in a before_save, so the column itself is clean.
  • Adopt its stricter scrubbing. PruneScrubber with tags_to_prune = %w[script style] drops those element bodies entirely; SafeListSanitizer (5.6.2) strips the tags but keeps their inner text. When 6.0 tightens the allowlist to the Tiptap-emitted set, add body-pruning too — the 6.0 result must not be weaker than what vendors have on 5.x.

The 5.6 cut deliberately differs from the 6.0 end-state in two ways:

  • Permissive-but-safe allowlist — legacy content was written with TinyMCE (spans, divs, inline styles, tables, images) and real descriptions embed video iframes; the 6.0 Tiptap-scoped list would corrupt that on next save. 5.6 ships Rails safe-list defaults + tables/img (kills script, event handlers, javascript: URLs; Loofah scrubs style contents). iframe stripped by default, re-permittable via the class-level configurable allowlist (RichTextSanitizer.allowed_tags/allowed_attributes in an initializer). 6.0 tightens to the Tiptap-emitted set (Key Decisions above).
  • No write-contract change — the description_html= bridge and plain-param rejection are 6.0 breaking scope; 5.6 keeps the :description param and sanitizes it.

Contents: RichTextSanitizer + SanitizableRichText applied to Product (covers Admin API writes and CSV import via before_save); the spree:sanitize_rich_text rake task for existing spree_products.description rows + translation rows — idempotent and loud, run through the operator-invoked spree:upgrade flow (never as a migration side effect: a patch release must not mutate merchant data outside an explicit upgrade run); nokogiri + rails-html-sanitizer declared in spree_core.gemspec and required in lib/spree/core.rb.

Phase 2: Product serializer ✓ shipped (5.4, PR #13811)

Phase 3: Category (and Collection) off ActionText ✓ shipped (2026-08-09)

Landed after the spree_categories rename rather than before — the rename shipped first (PR #14302), which is why spree:migrate_rich_text_to_columns runs immediately after migrate_taxons_to_categories_and_collections in the manifest: that step retypes the Action Text rows from Spree::Taxon to Spree::Category, so the copy can still find them. Both target columns already existed.

Spree::Collection was missing from this plan's model list — it was added after the plan was written (its own comment pointed back here) and carried backend: :action_text too, so the real count was five models, not four. Its description columns did not exist and were added; it also gained the RICH_TEXT_TRANSLATABLE_FIELDS constant it was missing, so the SPA translation matrix renders a rich-text editor for it.

Phase 4: Policy off ActionText ✓ shipped (2026-08-09)

spree_policies.body and spree_policy_translations.body added as predicted. The ActionText-coupled scopes are now column-presence checks (with_body → where.not(body: [nil, ''])). Admin API Policy CRUD was NOT built here — it landed later, with the seller-owned policies work (6.0-store-policies.md, 2026-08-27); this phase only changed how the existing Store API read path stores and serves the body.

Phase 5: internal notes + consumer sweep + drop ActionText ✓ shipped (2026-08-09)

  • CustomFields::RichText: shipped earlier with the custom-fields rename (spree/spree#14415).
  • Order#internal_note + Customer internal_note → text columns + has_spree_rich_text; both Admin serializers now expose internal_note + internal_note_html (Order previously shipped plain-only, Customer html-only).
  • Consumer sweep done: Meilisearch presenter and Google feed now index/emit RichTextHelper.to_plain_text, CSV export dropped its spurious html_safe, and the model generator template emits has_spree_rich_text instead of has_rich_text.
  • mobility-actiontext removed from spree_core.gemspec, along with the require 'mobility/action_text' in config/initializers/mobility.rb that pulled it in (nothing declares that backend now). action_text/engine stays required — ActionText::RichText must keep loading for the data migration and the 6.1 rollback path.
  • Type pipeline run (typelizer → Zod → OpenAPI → SDK tests). Dashboard write sites and the hand-written packages/admin-sdk/src/params.ts were updated to the *_html write contract.

Two implementation notes worth keeping:

  • The copy reads the raw body column, never body.to_s. ActionText's renderer wraps output in <div class="trix-content">; copying through it would have migrated that wrapper into every column, and since the allowlist drops class, it would have left a bare <div> behind.
  • Customer notes are copied after migrate_users_to_customers, not before. That step now retypes action_text_rich_texts too (it previously left them behind, so legacy notes stayed filed under the pre-6.0 user class), and the copy still matches SOURCE_USER_TYPE for installs that ran an older build of it. The manifest order is nevertheless load-bearing: a note is copied onto the customer row it belongs to, and spree_customers is empty until that step runs, so going first would count every legacy note as orphaned and skip it for good.

Body-pruning shipped with the 6.0 allowlist: script/style elements are removed subtree-and-all, so a script body can no longer survive as visible text. Implemented as a Loofah::Scrubber chained ahead of Rails::HTML::PermitScrubber on one parsed fragment — going through SafeListSanitizer twice would parse and re-serialize the whole document on every save. loofah is declared in spree_core.gemspec rather than leaned on transitively, though it was already a hard runtime requirement: Rails::HTML5::SafeListSanitizer is Loofah under the hood.

Deliberately not SafeListSanitizer.new(prune: true), which prunes the contents of every disallowed tag: <iframe>keepme</iframe> would become "" instead of "keepme", silently destroying text out of the legacy TinyMCE content this allowlist exists to preserve. pruned_tags keeps the destructive behavior scoped to the two tags whose bodies are never prose — everywhere else a stripped tag leaves its text behind, which is what limits the damage the tightened allowlist does to legacy TinyMCE markup.

Constraints on Current Work

  • No new has_rich_text or backend: :action_text declarations. New rich text = text column + has_spree_rich_text (from SanitizableRichText), which sanitizes on save and defines the field_html reader. A translated field needs a bare sanitizes_rich_text on the Translation class too — Mobility writes bypass the base record's callbacks, and the reader belongs on the parent. Writes use the plain attribute; there is no field_html=.
  • New rich-text serializers return field + field_html; writes take the plain attribute. field_html is a reader — don't add a field_html= alongside it.
  • Do not store Tiptap JSON.
  • Don't widen the sanitizer allowlist ahead of the editor. Editor gains a node type → allowlist widens in the same PR.
  • Rake tasks use Model.table_name — never literal table names (CLAUDE.md rule; the categories rename may land on either side).
  • Don't drop the action_text_rich_texts tables or the action_text/engine require before 6.1. spree:migrate_rich_text_to_columns reads them, and they are the rollback path.

Resolved Questions

  1. style stripped entirely; class narrowed to the code-block hint (2026-07-27, revised on implementation 2026-08-09): the original allowlist admitted attack surface (CSS overlays, class collisions) for markup no writer produces. style is gone outright. class turned out not to be strippable outright — Tiptap's code block emits language-* from its languageClassPrefix, so dropping class wholesale would corrupt every code block; it is permitted and pattern-narrowed instead. Text-align classes get allowlisted if/when the editor gains the extension.

    Shipped 2026-08-09. style is gone entirely. class is permitted only as a code block's language-* hint (Tiptap's languageClassPrefix, the one class the editor does emit), narrowed by allowed_class_pattern in the same scrubber pass that prunes script/style — so it is not an open attribute. The tag list was derived by reading each StarterKit extension's renderHTML rather than inferring from the toolbar, and every editor construct round-trips byte-identical (asserted per node type in the spec).

    Legacy TinyMCE markup outside the set (tables, images, div/span) is unwrapped on next save: text survives, formatting does not. That is the deliberate trade — the alternative was permitting markup no writer produces. The 5.6→6.0 upgrade guide documents the narrowing and shows the initializer to widen it, which merchants with richer legacy content should apply before running the migration.

  2. Write contract is field_html (2026-07-27) — reversed on implementation (2026-08-10). It shipped that way briefly and was reverted: the value is HTML under either name, so field_html= was a second spelling of field= that broke every existing client to chase symmetry with a read field which intentionally differs. Writes stay on the plain attribute, sanitized on save; field_html is a reader only. See the Key Decisions entry above.

  3. ActionText is fully dropped, not reduced (2026-07-27): custom-field rich text and internal notes migrate too — the dashboard already Tiptaps both surfaces (custom fields today, internal notes at 6.0 when the SPA is the only admin), and keeping ActionText for them preserves the exact Trix-corruption bug this plan exists to fix.

  4. Sequencing with the categories rename (2026-07-27; outcome reversed 2026-08-09): the intent was Phase 3 first, but the rename shipped first (PR #14302). Being table-name-agnostic by construction is what made that harmless — the copy task simply runs after migrate_taxons_to_categories_and_collections in the manifest, which retypes the Action Text rows from Spree::Taxon to Spree::Category so they remain findable. The categories plan drops its backend: :action_text line (fixed) and owns the translation-table renames.

Open Questions

  • Image handling. Tiptap image nodes produce <img src="..."> — uploaded to Active Storage with URLs rewritten, or external URLs allowed? Intersects 5.4-6.0-product-media-system.md and the SPA media manager; the sanitizer excludes img until this is decided.

References

  • Primitives: spree/core/app/helpers/spree/rich_text_helper.rb (plain-text extraction), app/models/spree/rich_text_sanitizer.rb (allowlist + body-pruning), app/models/concerns/spree/sanitizable_rich_text.rb (has_spree_rich_text, plus sanitizes_rich_text alone for Translation classes)
  • Data migration: lib/tasks/migrate_rich_text_to_columns.rake + spec/lib/tasks/migrate_rich_text_to_columns_spec.rb; manifest step migrate_rich_text_to_columns in lib/spree/upgrades/5_6_to_6_0/manifest.yml
  • Migrated models (was taxon.rb, collection.rb, policy.rb, order.rb, customer_methods.rb, custom_fields/rich_text.rb): all now text column + sanitizes_rich_text, with the sanitize pass repeated on each Translation class
  • Columns added: 20260809200001_add_rich_text_columns_for_action_text_removal.rb (collection + policy descriptions/bodies and their translations, customer internal_note)
  • Related plans: 6.0-admin-spa.md (Tiptap; <InternalNoteCard>, <CustomFieldsDrawer>), 6.0-replace-taxons-with-categories.md, 5.4-6.0-custom-fields-rename.md, 5.4-metafield-translations.md, 5.5-6.0-resource-translations-api.md, 6.0-admin-api.md (Policy CRUD; write-contract mirror)
  • Tiptap HTML output docs: https://tiptap.dev/docs/editor/guide/output#html