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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Add additional Product description sanitization (#14371)
Damian Legawiec220af508d2b4
diff --git a/CLAUDE.md b/CLAUDE.mdindex f41c82a331..782efc79c4 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -27,7 +27,7 @@ Active plans (6.0 target, work pending):- `6.0-tax-provider.md` — Per-Market TaxProvider, replaces TaxRate.adjust + Calculator; TaxRate gets direct country/state FKs (tax decoupled from Zone; Zone model dropped in 6.0 via `6.0-delivery-zones.md`)- `6.0-delivery-rate-provider.md` — Per-DeliveryMethod DeliveryRateProvider wrapping Stock::Estimator (calculators stay — 2026-07-27 reversal), `store_id` on ShippingMethod, enriched DeliveryRate (carrier/service/date/metadata)- `6.0-delivery-zones.md` — Zone → DeliveryZone with postal-code-range/prefix members (country-scoped); owns the full ~183-reference Zone consumer inventory; `Spree::Zone` dropped entirely by end of 6.0 (2026-07-27 — 6.0 is the breaking-change window)-- `6.0-rich-text-descriptions.md` — Drop ActionText storage, store HTML in text columns, sanitize on write, serve `description` + `description_html` in API (description_html serializer field shipped in 5.4)+- `6.0-rich-text-descriptions.md` — Drop ActionText **entirely** at 6.0 (incl. CustomFields::RichText values + Order/User internal notes; gem dependency removed), store sanitized HTML in text columns, serve `field` + `field_html`, **write via `field_html`** (read/write symmetry). description_html serializer shipped 5.4; sanitizer shipped in **5.6.2** with a permissive-but-safe configurable allowlist + `sanitize_rich_text` step in the 5.5→5.6 upgrade manifest (decisions.md 2026-07-27/28), tightened to the Tiptap set at 6.0- `6.0-inventory-operations.md` — StockTransfer lifecycle (draft → ready_to_ship → in_transit → received with partial receive), new `Spree::PurchaseOrder` + `Spree::Supplier` (renamed from Vendor — `Spree::Vendor` is the marketplace seller, see decisions.md 2026-07-14) replacing today's "external receive" hack, variant + stock-location stock history panels. Consumes the typed-movement primitives from `6.0-typed-stock-movements.md`.- `6.0-replace-taxons-with-categories.md` — Split Taxon into Category (hierarchy) + Collection (flat/rule-based). `Spree::Category < Spree::Taxon` alias + Category API surface shipped in 5.5; table rename + Collection pending.- `6.0-store-scoped-custom-field-definitions.md` — Add `store_id` + persisted `filter_key` to `Spree::MetafieldDefinition` (today global and computed), making uniqueness `(store_id, resource_type, filter_key)` with a DB index. Deferred from the 5.6 custom-field search/sort/filter work (schema change, not patch-safe). **Until then:** `filter_key` is a computed method — no Ransack predicates or `where`/`order` against it; definitions are global; uniqueness rests on a `CONCAT` validation with no index behind it.diff --git a/docs/developer/upgrades/5.5-to-5.6.mdx b/docs/developer/upgrades/5.5-to-5.6.mdxindex aa7da6c0e5..a8d181dc09 100644--- a/docs/developer/upgrades/5.5-to-5.6.mdx+++ b/docs/developer/upgrades/5.5-to-5.6.mdx@@ -145,6 +145,42 @@ bundle exec rake spree:upgrade:backfill_product_tag_tenantsSets the `tenant` column on existing `Spree::Product` taggings from each product's `store_id`. New product taggings tenant themselves automatically — only rows created before the upgrade need this. Until it runs, product tags created before the upgrade are hidden from the store's tag-autocomplete vocabulary (they reappear once it completes; storefront and admin tag *display* are unaffected).+### Sanitize stored product descriptions (added in 5.6.2)++Spree 5.6.2 sanitizes product description HTML on every write (`Spree::RichTextSanitizer` — strips `script` tags, event-handler attributes, and `javascript:` URLs; keeps tables, images, links, and safe inline styles). This task runs your **existing** descriptions and their translations through the same sanitizer:++<CodeGroup>++```bash Spree CLI (Docker)+spree rake spree:sanitize_rich_text+```++```bash Without Spree CLI+bundle exec rake spree:sanitize_rich_text+```++</CodeGroup>++Idempotent — only rows whose sanitized output differs are rewritten, and a changed-row count is printed per model.++<Note>+**Already on 5.6.0 or 5.6.1?** This step was added to the manifest in 5.6.2, so a `spree:upgrade` you ran earlier did not include it. Re-run `spree:upgrade` after bumping (every step is idempotent, so the earlier steps are no-ops), or run just this one:++```bash+bundle exec rake spree:upgrade STEP=sanitize_rich_text+```+</Note>++<Warning>+`iframe` is stripped by default. If your descriptions embed videos or other iframes, permit the tag **before** running the task (and before saving products under 5.6.2):++```ruby+# config/initializers/spree.rb+Spree::RichTextSanitizer.allowed_tags += %w[iframe]+Spree::RichTextSanitizer.allowed_attributes += %w[allow allowfullscreen frameborder]+```+</Warning>+## Update the Spree SDKSpree 5.6 ships alongside `@spree/sdk` 1.2. The backend upgrade never touches your frontend source — bump the SDK in every JavaScript consumer of the Store API and take it through your normal PR/CI cycle:@@ -185,3 +221,9 @@ With `store_id` on role assignments, an admin's abilities are scoped to the stor### Product tag autocomplete is store-scopedThe Admin API tag-autocomplete endpoint (`GET /api/v3/admin/tags`) now returns only tags used within the current store for store-owned taggables (products and orders). Customer tags remain global. If an integration relied on this endpoint returning tags across every store, that cross-store vocabulary is no longer exposed. Run [the tag-tenant backfill](#backfill-the-store-tenant-on-product-tags) so pre-upgrade product tags are included.++### Product descriptions are sanitized on write (5.6.2)++From 5.6.2, product description HTML is sanitized on save — Admin API writes, CSV imports, and translation writes all pass through `Spree::RichTextSanitizer`. `script`, event-handler attributes, and `javascript:` URLs are removed; tables, images, links, and safe inline CSS are preserved. The allowlist is configurable (`Spree::RichTextSanitizer.allowed_tags` / `.allowed_attributes`) — see [the sanitize task](#sanitize-stored-product-descriptions-added-in-562) for the iframe note. If an integration wrote raw `<script>` into descriptions for storefront injection, that pattern no longer works — move such code into your storefront theme.++Sanitization runs in an ActiveRecord callback, so it covers writes that go through `save`/`update`. Callback-bypassing writes (`update_columns`, `update_all`, raw SQL) are not sanitized — if your code writes descriptions that way, call `Spree::RichTextSanitizer.sanitize` explicitly.diff --git a/docs/plans/5.4-6.0-custom-fields-rename.md b/docs/plans/5.4-6.0-custom-fields-rename.mdindex 02aff8e29a..f92d683b1f 100644--- a/docs/plans/5.4-6.0-custom-fields-rename.md+++ b/docs/plans/5.4-6.0-custom-fields-rename.md@@ -4,7 +4,7 @@**Target:** 5.4 (Store API serializer bridge ✓) + 5.5 (Admin CRUD API + SDK + `Spree::CustomField` constant alias ✓) + 6.0 (model/table rename + visibility simplification + STI rename)**Depends on:** None — 5.4/5.5 changes are additive. 6.0 rename is part of the model rename wave.**Author:** Damian + Claude-**Last updated:** 2026-05-20+**Last updated:** 2026-07-27## Summary@@ -443,7 +443,7 @@ Full internal rename. Part of the 6.0 model rename wave alongside Shipment→Ful| `Spree::MetafieldDefinition` | `Spree::CustomFieldDefinition` | || `Spree::Metafields::ShortText` | `Spree::CustomFields::ShortText` | STI subclass || `Spree::Metafields::LongText` | `Spree::CustomFields::LongText` | STI subclass |-| `Spree::Metafields::RichText` | `Spree::CustomFields::RichText` | STI subclass |+| `Spree::Metafields::RichText` | `Spree::CustomFields::RichText` | STI subclass. **Value storage also migrates in the same 6.0 wave**: `has_rich_text :value` (ActionText) → the existing `value` text column, sanitized — owned by `6.0-rich-text-descriptions.md` Phase 5 (the dashboard already writes Tiptap HTML through ActionText's Trix allowlist today) || `Spree::Metafields::Number` | `Spree::CustomFields::Number` | STI subclass || `Spree::Metafields::Boolean` | `Spree::CustomFields::Boolean` | STI subclass || `Spree::Metafields::Json` | `Spree::CustomFields::Json` | STI subclass |diff --git a/docs/plans/5.4-metafield-translations.md b/docs/plans/5.4-metafield-translations.mdindex 67995a00e6..071f455c2d 100644--- a/docs/plans/5.4-metafield-translations.md+++ b/docs/plans/5.4-metafield-translations.md@@ -4,7 +4,7 @@**Target:** Spree 5.4**Depends on:** Metafields system (shipped), TranslatableResource / Mobility infrastructure**Author:** Damian-**Last updated:** 2026-04-08+**Last updated:** 2026-07-27## Summary@@ -244,10 +244,10 @@ When reading a RichText metafield:- **Other locales:** HTML string from the translation tableWhen writing a RichText translation:-- Accept HTML string, sanitize on write (same sanitization rules as the base value)-- Store sanitized HTML in the translation table's `value` column+- Accept HTML string, store it in the translation table's `value` column+- **Sanitization is not wired for custom fields yet.** The 5.6.2 `Spree::RichTextSanitizer` covers `Spree::Product#description` and its translations only; the base RichText value still goes through ActionText's Trix allowlist, which is a *different* ruleset. Applying `sanitizes_rich_text` to custom-field values (base + translations, one shared allowlist) lands with `6.0-rich-text-descriptions.md` Phase 5, which also moves the base value off ActionText. Until then, treat stored custom-field rich text as unsanitized by Spree's own sanitizer.-This asymmetry is temporary — the `6.0-rich-text-descriptions.md` plan will move all rich text to plain HTML columns, at which point RichText metafields will be fully symmetric.+This asymmetry is temporary — `6.0-rich-text-descriptions.md` **Phase 5** (2026-07-27 revision) migrates `has_rich_text :value` to the existing `value` text column with sanitization, at which point RichText metafields are fully symmetric.### Translation Coverage Trackingdiff --git a/docs/plans/5.4-search-provider.md b/docs/plans/5.4-search-provider.mdindex 9f94bcb6bf..378da17794 100644--- a/docs/plans/5.4-search-provider.md+++ b/docs/plans/5.4-search-provider.md@@ -356,7 +356,9 @@ module SpreeMeilisearchid: product.id,prefixed_id: product.prefixed_id,name: product.name,- description: product.description,+ # plain text, not raw HTML — else tag names/attributes become searchable+ # tokens and pollute highlights (6.0-rich-text-descriptions.md Phase 5)+ description: Spree::RichTextHelper.to_plain_text(product.description),slug: product.slug,status: product.status,price: product.price_in(store.default_currency)&.amount&.to_f,diff --git a/docs/plans/5.5-6.0-resource-translations-api.md b/docs/plans/5.5-6.0-resource-translations-api.mdindex 0e65328441..dda8c22503 100644--- a/docs/plans/5.5-6.0-resource-translations-api.md+++ b/docs/plans/5.5-6.0-resource-translations-api.md@@ -4,7 +4,7 @@**Target:** Spree 5.5 (Phase 1 API) → 6.0 (staleness + bulk + metafields fold-in)**Depends on:** Mobility / `Spree::TranslatableResource` (shipped), Markets (locale config, shipped), Admin API v3 (shipped), `5.4-centralized-translations-admin.md`, `5.4-metafield-translations.md`**Author:** Damian + Claude-**Last updated:** 2026-06-24+**Last updated:** 2026-07-27## Summary@@ -105,7 +105,7 @@ endBoth write paths call `record.upsert_translations(values)` and rescue `ActiveRecord::RecordInvalid` → `render_validation_error(e.record.errors)` (422). Value normalization (HTML sanitization, slug parameterization) stays on the model's own field writers — `upsert_translations` only routes values to them. No `Spree::Dependencies` entry: the behavior is on the model, overridable like any model method via a decorator.-> **Note on rich text:** `Taxon#description` and `Policy#body` use the ActionText Mobility backend today. Translated HTML must be sanitized on write per the `6.0-rich-text-descriptions.md` plan. The `fields[].type == "html"` hint (below) tells both the serializer and the sanitizer how to treat the field.+> **Note on rich text:** `Taxon#description` and `Policy#body` use the ActionText Mobility backend today (removed at 6.0 per `6.0-rich-text-descriptions.md`). Translated HTML must be sanitized on write per that plan. The `fields[].type == "html"` hint (below) tells both the serializer and the sanitizer how to treat the field. **Deliberate, documented divergence** (2026-07-27): this surface keys on the model attribute (`description` carrying HTML, both directions — symmetric *within* the matrix), while resource serializers use the `description` (plain) / `description_html` (HTML) pair with writes on `description_html`.### A. Dedicated nested endpoint (contract of record)diff --git a/docs/plans/6.0-admin-api.md b/docs/plans/6.0-admin-api.mdindex 6a240b4039..833ac9f1d0 100644--- a/docs/plans/6.0-admin-api.md+++ b/docs/plans/6.0-admin-api.md@@ -290,6 +290,8 @@ Each endpoint below is tracked as `[ ]` (pending) or `[x]` (shipped). When you i> **Bulk envelope decision (resolved):** per-action bulk routes (not a single `/bulk`), bodies `{ ids: [...], ... }`, shared via the `Spree::Api::V3::BulkOperations` concern. Resolves the "Bulk operations envelope" open question.> **6.0 field changes:** `shipping_category_id` is dropped (fulfillment types come from `ProductType.fulfillment_types`). `prototype_id` → `product_type_id`. `taxon_ids` → `category_ids`. Product has `default_variant_id` FK (no more `is_master`).+>+> **Rich-text write contract (2026-07-27, per `6.0-rich-text-descriptions.md`):** reads are `description` (plain) + `description_html` (HTML); **writes accept `description_html`** — sanitized by the model-owned bridge. HTML under the plain `description` param is rejected (422), preserving read/write symmetry. Same pattern for `body`/`body_html` on Policies (whose Admin CRUD is built in that plan's Phase 4 — no policies controller exists today) and `internal_note`/`internal_note_html` on Orders/Customers.### Variants (nested under Products)- [x] `GET /api/v3/admin/products/:product_id/variants`diff --git a/docs/plans/6.0-multi-vendor-marketplace.md b/docs/plans/6.0-multi-vendor-marketplace.mdindex 06fbc1fcb9..41e3b654ac 100644--- a/docs/plans/6.0-multi-vendor-marketplace.md+++ b/docs/plans/6.0-multi-vendor-marketplace.md@@ -576,6 +576,7 @@ This is **new OSS code**, not a rename of existing core — there is no in-placeEven before this lands, work touching adjacent areas should:- **Cart/Order split (`6.0-cart-order-split.md`)**: keep `cart.complete!`/`Spree::Carts::Complete` as the single completion entry point — the vendor split hooks in there. Do not reintroduce an order-level `after_transition` extension surface; multi-vendor must not depend on one. When fleshing out the checkout flow on Cart, design delivery selection **per package** (packages come from order routing) — the multi-vendor checkout needs one delivery choice per vendor package before completion, and payments must be attachable to an `OrderGroup`, not only to an `Order`.+- **Rich text sanitization (`6.0-rich-text-descriptions.md`)**: vendors are the marketplace's lower-trust writers, and today they are protected by the 5.x-only Enterprise gem's `Spree::SanitizeConcern` (`sanitize :description, :meta_description, if: -> { vendor_id.present? }`). That gem does not carry into 6.0 — this plan rewrites its functionality as core models — so **core must own the sanitization before vendor-authored content lands here**. Core's `SanitizableRichText` (shipped 5.6.2) sanitizes on write rather than deriving `sanitized_*` on read, which is the stronger form. Three obligations for this plan: (1) apply it to every vendor-writable rich text field (`Vendor#about`, vendor-authored product descriptions); (2) keep vendor-facing write paths — the vendor dashboard, vendor CSV/feed imports, bulk maintenance jobs — on save-backed writers, since the concern is a `before_save` and does not cover `update_columns`/`update_all`/raw SQL (anything that must bypass callbacks calls `Spree::RichTextSanitizer.sanitize` explicitly); (3) do **not** ship a 6.0 allowlist weaker than the Enterprise scrubber vendors have on 5.x — that one prunes `script`/`style` element bodies entirely.- **Split adjustments (`6.0-split-adjustments.md`)**: `TaxLine` and `Discount` stay strictly line-item- or fulfillment-attached (order-level discounts distribute to line items at application time), so they re-home unambiguously to one child order during the split. `Fee` may additionally be **order-level** (payment surcharge, COD — resolved 2026-07-27); at split, order-level fees prorate across child orders by item totals (largest-remainder), tax lines following the fee. Do **not** add a commission/marketplace `Fee` kind — commission is `Spree::CommissionLine`, off-order (Decision 2); `Fee` stays buyer-facing.- **Inventory operations (`6.0-inventory-operations.md`)**: the procurement model is `Spree::Supplier` — never reuse `Spree::Vendor` (reserved for marketplace sellers) for purchase-order sources. See `decisions.md` 2026-07-14.- **External-store sync stays Enterprise**: do **not** add external store/resource models, associations, or callbacks to core (no `external_store` on Vendor, no external product/order/category tables, no platform sync hooks). The Shopify/WooCommerce connection layer is an Enterprise concern that decorates core's Vendor from outside; core only needs to stay decorable (events + the onboarding task registry are the seams it plugs into).diff --git a/docs/plans/6.0-replace-taxons-with-categories.md b/docs/plans/6.0-replace-taxons-with-categories.mdindex 2f27ae1d3b..bd3b76b1f3 100644--- a/docs/plans/6.0-replace-taxons-with-categories.md+++ b/docs/plans/6.0-replace-taxons-with-categories.md@@ -115,7 +115,10 @@ class Spree::Category < Spree.base_class# TranslationsTRANSLATABLE_FIELDS = %i[name pretty_name description permalink].freezetranslates(*TRANSLATABLE_FIELDS, column_fallback: !Spree.always_use_translations?)- translates :description, backend: :action_text+ # description rides the table backend above — NOT action_text. The old+ # `translates :description, backend: :action_text` line is removed by+ # 6.0-rich-text-descriptions.md Phase 3, which runs BEFORE this plan's+ # table rename (its rake task is table-name-agnostic either way).# Scopesscope :for_store, ->(store) { where(store_id: store.id) }@@ -334,6 +337,20 @@ class RenameTaxonsToCategories < ActiveRecord::Migration[7.2]rename_table :spree_products_taxons, :spree_product_categoriesrename_table :spree_taxon_rules, :spree_collection_rules+ # Translation tables (missed by the original draft — 2026-07-27):+ # spree_taxon_translations carries the description text column that+ # 6.0-rich-text-descriptions.md Phase 3 populates before this rename+ rename_table :spree_taxon_translations, :spree_category_translations+ create_table :spree_collection_translations do |t|+ t.string :name+ t.text :description+ t.string :permalink+ t.string :locale, null: false+ t.references :collection, null: false+ t.timestamps+ end+ add_index :spree_collection_translations, [:collection_id, :locale], unique: true+# Rename FK columnsrename_column :spree_product_categories, :taxon_id, :category_idrename_column :spree_collection_rules, :taxon_id, :collection_iddiff --git a/docs/plans/6.0-rich-text-descriptions.md b/docs/plans/6.0-rich-text-descriptions.mdindex d91d63fd89..008d1be288 100644--- a/docs/plans/6.0-rich-text-descriptions.md+++ b/docs/plans/6.0-rich-text-descriptions.md@@ -1,246 +1,178 @@# Rich Text Descriptions-**Status:** Partially Complete (description_html shipped in 5.4, ActionText removal in 6.0)-**Target:** Spree 5.4 (description_html) + Spree 6.0 (ActionText removal)-**Depends on:** Admin SPA (6.0-admin-spa.md) for ActionText removal+**Status:** Phases 1–2 partially shipped in 5.4 (`RichTextHelper` + Product serializer split ✓ — PR #13811); **sanitizer retargeted to 5.6** (never shipped, live XSS surface — decisions.md 2026-07-27); ActionText removal pending in 6.0+**Target:** Spree 5.4 (serializer split ✓) + **5.6 (sanitization — permissive allowlist)** + 6.0 (allowlist tightened to Tiptap set; 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 runs **before** the `spree_taxons` table rename; 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-03-21+**Last updated:** 2026-07-27## Summary-Standardize how rich text content (product descriptions, category descriptions, policy bodies) is stored and served across Spree. Move away from ActionText as a storage backend in favor of plain HTML text columns, since the 6.0 admin uses Tiptap (not Trix). Unify the API response shape so every rich text field returns both `description` (plain text) and `description_html` (HTML).+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), and **writes as `field_html`** (read/write symmetry).-## Problem--Rich text storage is inconsistent across models:+**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.-| Model | Current storage | Translation | API output |-|-------|----------------|-------------|------------|-| Product | `text` column on `spree_products` | Mobility (table backend) | `description` → raw HTML string |-| Taxon | ActionText (`action_text_rich_texts`) | Mobility (action_text backend) | `description` → plain text, `description_html` → HTML |-| Policy | ActionText (`action_text_rich_texts`) | Mobility (action_text backend) | `body` → plain text, `body_html` → HTML |--This creates three problems:+## Problem-1. **ActionText is a Trix companion, not a generic HTML store.** It sanitizes HTML against Trix's allowlist, which strips valid Tiptap output (tables, colored text, custom attributes). It wraps content in `<div class="trix-content">` and uses `<action-text-attachment>` tags for embeds. None of this is compatible with a Tiptap editor.+Rich text storage is inconsistent across models (state at HEAD, 2026-07-27):-2. **Inconsistent API responses.** Product returns raw HTML as `description`. Taxon returns plain text as `description` and HTML as `description_html`. Consumers can't predict what format they'll get.+| 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 |-3. **Inconsistent storage.** Two different storage mechanisms (text column vs `action_text_rich_texts` table) with different querying, indexing, and translation strategies.+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()`. Store that directly. No ActionText, no Tiptap JSON.-- **HTML, not Tiptap JSON.** HTML is universally consumable (storefronts, emails, search indexing, feeds, mobile apps). Tiptap JSON would force every consumer to depend on a Tiptap renderer. The admin is the only writer — optimizing storage for one writer at the cost of every reader is wrong.-- **Use Nokogiri for plain text extraction.** `Nokogiri::HTML.fragment(html).text.squish` strips tags without any ActionText dependency.-- **Every rich text field returns two API attributes:** `description` (plain text) and `description_html` (HTML). Same pattern for `body` / `body_html` on Policy.-- **Sanitize HTML on write.** Server-side allowlist sanitization to prevent XSS, configured to permit Tiptap's output (headings, paragraphs, lists, tables, images, links, text marks).-- **Models with plain-text-only descriptions keep simple text columns.** Promotion, PaymentMethod, Store, PriceList, CustomerGroup descriptions are short admin labels — no rich text, no `_html` variant.+- **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`.+- **Read/write symmetry (the v3 non-negotiable):** reads are `field` (plain) + `field_html` (HTML); **writes accept `field_html`**, never HTML-in-the-plain-field — the original draft's "accept HTML in the `description` param" meant a client PATCHing `description: "<p>x</p>"` read back `description: "x"`. The **model owns the bridge** (the OptionType#label pattern): `description_html=` sanitizes and writes the underlying column, paired with the existing reader. Writes to the plain field on rich-text models are rejected (422), not silently stripped.+- **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`, no `class`** (resolving the original draft's own open question flagging them as attack vectors), no tables/img/figure/span/div until the editor gains them (each future extension widens the allowlist deliberately). Server-side via `Rails::HTML5::SafeListSanitizer` (rails-html-sanitizer ≥ 1.6, present).+- **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 `internal_note_html`. Text columns on `spree_orders`/`spree_users`, 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+### Storage + translations-All rich text fields are `text` columns on the model's own table, translated via Mobility table backend:+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):```ruby-class Spree::Product < Spree.base_class- TRANSLATABLE_FIELDS = %i[name description slug meta_description meta_title].freeze- translates(*TRANSLATABLE_FIELDS, column_fallback: !Spree.always_use_translations?)-end-class Spree::Taxon < Spree.base_classTRANSLATABLE_FIELDS = %i[name pretty_name description permalink].freeze- translates(*TRANSLATABLE_FIELDS, column_fallback: !Spree.always_use_translations?)- # Remove: translates :description, backend: :action_text-end--class Spree::Policy < Spree.base_class- TRANSLATABLE_FIELDS = %i[name body].freeze- translates(*TRANSLATABLE_FIELDS, column_fallback: !Spree.always_use_translations?)- # Remove: translates :body, backend: :action_text+ 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.```-### Sanitization concern+`RICH_TEXT_TRANSLATABLE_FIELDS` stays — it drives the SPA translation matrix's rich-text editor (`translatable_rich_text_fields`).-```ruby-module Spree- module SanitizableRichText- extend ActiveSupport::Concern-- class_methods do- def sanitizes_rich_text(*attributes)- before_save do- attributes.each do |attr|- value = public_send(attr)- next if value.blank?-- public_send(:"#{attr}=", Spree::RichTextSanitizer.sanitize(value))- end- end- end- end- end-end-```+### Sanitization```rubymodule Spreeclass RichTextSanitizer- ALLOWED_TAGS = %w[- h1 h2 h3 h4 h5 h6 p br hr- ul ol li- table thead tbody tfoot tr th td- a img- strong em u s del sub sup- blockquote pre code- span div figure figcaption- ].freeze-- ALLOWED_ATTRIBUTES = %w[- href src alt title target rel- class style- colspan rowspan- width height- ].freeze+ # 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-27def self.sanitize(html)- Rails::HTML5::SafeListSanitizer.new.sanitize(- html,- tags: ALLOWED_TAGS,- attributes: ALLOWED_ATTRIBUTES- )+ Rails::HTML5::SafeListSanitizer.new.sanitize(html, tags: ALLOWED_TAGS, attributes: ALLOWED_ATTRIBUTES)endendend-```--Usage in models:--```ruby-class Spree::Product < Spree.base_class- include Spree::SanitizableRichText- sanitizes_rich_text :description-end-```--### Plain text extraction-A shared helper for serializers using Nokogiri (no ActionText dependency):--```rubymodule Spree- module RichTextHelper- def self.to_plain_text(html)- return '' if html.blank?-- Nokogiri::HTML.fragment(html).text.squish- end+ module SanitizableRichText # concern: sanitizes_rich_text :description — before_save allowlist passendend```-### API serializers+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.-**Product** (adding `description_html`, changing `description` to plain text):+### Write bridge (per model)```ruby-class ProductSerializer < BaseSerializer- typelize description: :string, description_html: :string-- attribute :description do |product|- Spree::RichTextHelper.to_plain_text(product.description)- end+class Spree::Product < Spree.base_class+ include Spree::SanitizableRichText+ sanitizes_rich_text :description- attribute :description_html do |product|- product.description.to_s- end+ def description_html = description.to_s+ def description_html=(value) = self.description = value # sanitized by the concern on saveend```-**Category** (no change to shape, but simplified implementation — no ActionText storage):+Controllers permit `:description_html` (products, categories), `:body_html` (policies), `:internal_note_html` (orders, customers) — and stop permitting HTML under the plain names.-```ruby-class CategorySerializer < BaseSerializer- typelize description: :string, description_html: :string+### Serializers- attribute :description do |category|- Spree::RichTextHelper.to_plain_text(category.description)- end+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).- attribute :description_html do |category|- category.description.to_s- end-end-```+### Consumers of raw HTML (all routed through the helper/sanitizer in Phase 5)-**Policy** (same pattern with `body` / `body_html`):+- **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.-```ruby-class PolicySerializer < BaseSerializer- typelize body: :string, body_html: :string+### Translations surface (deliberate, documented divergence)- attribute :body do |policy|- Spree::RichTextHelper.to_plain_text(policy.body)- end+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.- attribute :body_html do |policy|- policy.body.to_s- end-end-```+## Migration Path-### Admin API write+### Phase 1 (remainder): Sanitizer — **ships in 5.6.2** (implemented 2026-07-28), it closes a live hole ✳-The admin API accepts HTML in the `description` (or `body`) parameter. The Tiptap editor calls `editor.getHTML()` on save and sends the result. No special endpoint or content type needed — it's just a string param.+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.-### Internal notes (Order, User)+**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).-`has_rich_text :internal_note` on Order and User stays on ActionText for now. These are admin-only fields edited within the Rails admin (or later in the Tiptap admin), never exposed in the Store API, and don't need translation. They can be migrated later if desired.+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.-## Migration Path+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.-### Phase 1: Sanitization concern + plain text helper+The 5.6 cut deliberately differs from the 6.0 end-state in two ways:-Add `Spree::SanitizableRichText` concern and `Spree::RichTextHelper`. Apply to Product immediately (it already stores HTML in a text column). No data migration needed.+- **Permissive-but-safe allowlist** — legacy content was written with TinyMCE (spans, divs, inline styles, tables, images) and real descriptions embed video `iframe`s; 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.-### Phase 2: Update Product serializer+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`.-- Change `description` to return plain text via `RichTextHelper.to_plain_text`-- Add `description_html` returning raw HTML-- Update TypeScript types and Zod schemas+### Phase 2: Product serializer ✓ shipped (5.4, PR #13811)-### Phase 3: Migrate Taxon off ActionText+### Phase 3: Taxon off ActionText (before the `spree_categories` rename)-1. Remove `translates :description, backend: :action_text` from Taxon-2. Rake task: copy rich text content from `action_text_rich_texts` into the `description` column on `spree_taxons` (and Mobility translation records)-3. Apply `sanitizes_rich_text :description`-4. Update CategorySerializer to use `RichTextHelper` instead of `.to_plain_text` / `.body.to_s`+Both target columns **already exist** (`spree_taxons.description`, `spree_taxon_translations.description` — verified), and may hold stale pre-ActionText data: the rake task copies **only where an ActionText row exists**, never blindly overwriting; per-locale `action_text_rich_texts` rows (mobility-actiontext `locale` column) land in the translation table. Remove `backend: :action_text`, apply `sanitizes_rich_text`, update `CategorySerializer` to the helper. Table names via `Spree::Taxon.table_name`.-### Phase 4: Migrate Policy off ActionText+### Phase 4: Policy off ActionText — **needs migrations the original draft lacked**-Same as Phase 3, but for `body` field.+`spree_policies` has **no `body` column** and `spree_policy_translations` has **no `body` column** — add both first, then the copy task (same only-where-ActionText-exists rule). Rewrite the ActionText-coupled scopes (`with_body` joins `:rich_text_body`, `without_body` uses `where.missing` — `policy.rb:42-43, 66`) as column-presence checks. **There is no Admin API v3 policies controller at all today** (Store API read-only) — Policy CRUD is built as part of this phase, coordinated with `6.0-admin-api.md`.-### Phase 5: Cleanup+### Phase 5: CustomFields::RichText + internal notes + consumer sweep + drop ActionText-- Remove orphaned `action_text_rich_texts` records for migrated models-- ActionText gem stays as a dependency for models that still use it (Order `internal_note`, User `internal_note`, Metafields::RichText). Plain text extraction uses Nokogiri directly — no ActionText dependency for that path.-- Run type generation pipeline (typelizer → Zod → OpenAPI → SDK tests)+- `CustomFields::RichText`: `has_rich_text :value` → the already-existing `value` text column (currently ignored by the model), sanitized; rake copy task. Listed in `5.4-6.0-custom-fields-rename.md`'s 6.0 wave alongside the STI rename.+- `Order#internal_note` + `User` internal_note → text columns + `sanitizes_rich_text`; serializers/params standardized (`internal_note` + `internal_note_html` on both).+- Consumer sweep: Meilisearch serialize, Google feed, CSV export (above); model generator template's ActionText line (`generators/spree/model/templates/model.rb.tt:22`).+- Then: remove `mobility-actiontext` from `spree_core.gemspec`, drop migrated `action_text_rich_texts` rows, drop the ActionText tables in 6.1 alongside the other legacy drops.+- Type pipeline (typelizer → Zod → OpenAPI → SDK tests) after each serializer change.## Constraints on Current Work-- **Do not add new `has_rich_text` or `backend: :action_text` declarations.** New rich text fields should use text columns + `SanitizableRichText` concern.-- **New serializers with rich text must return both `field` (plain text) and `field_html` (HTML).**-- **Do not store Tiptap JSON.** Always convert to HTML before saving.+- **No new `has_rich_text` or `backend: :action_text` declarations.** New rich text = text column + `SanitizableRichText`.+- **New rich-text serializers return `field` + `field_html`; writes accept `field_html`.** Never HTML under a plain field name.+- **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).++## Resolved Questions++1. **`style`/`class` stripped entirely** (2026-07-27, closing the original open question): the shipped Tiptap editor (StarterKit + Link) emits neither; the original allowlist admitted attack surface (CSS overlays, class collisions) for markup no writer produces. Text-align classes get allowlisted if/when the editor gains the extension.+2. **Write contract is `field_html`** (2026-07-27): read/write symmetry per the v3 rule; model-owned bridge; plain-field HTML writes rejected.+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): Phase 3 before the table rename by intent, table-name-agnostic by construction. The categories plan drops its `backend: :action_text` line (fixed) and owns the translation-table renames.## Open Questions-- **`style` and `class` attributes in sanitizer allowlist.** Allowing arbitrary `style` attributes opens the door to CSS-based attacks (e.g., `position: fixed` overlays). Allowing `class` could conflict with storefront CSS or be exploited if malicious classes are defined. May want to restrict both to specific values (e.g., Tiptap's text-align classes) or strip them entirely and rely on semantic HTML tags.-- **Image handling.** Tiptap image nodes produce `<img src="...">`. Need to decide whether images in descriptions are uploaded to Active Storage (and URLs rewritten) or stored as external URLs. This intersects with the admin SPA media management.+- **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-- Related plan: `6.0-admin-spa.md` (Tiptap editor in React admin)-- Current ActionText models: Taxon (`description`), Policy (`body`), Order (`internal_note`), User (`internal_note`), Metafields::RichText (`value`)+- Shipped: `spree/core/app/helpers/spree/rich_text_helper.rb`, `spree/api/app/serializers/spree/api/v3/product_serializer.rb:48-56` (PR #13811)+- ActionText users (the complete set, verified): `taxon.rb:164`, `policy.rb:30`, `order.rb:49`, `user_methods.rb:109`, `metafields/rich_text.rb:7`+- Inconsistent internal-note serializers: `admin/order_serializer.rb:51-52` (plain only) vs `admin/customer_serializer.rb:48-49` (html only)+- Raw-HTML consumers: `search_provider/product_presenter.rb:52`, `data_feeds/google_presenter.rb:68`, `csv/product_variant_presenter.rb:88`, `import_schemas/products.rb:10`+- 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#htmldiff --git a/spree/core/app/models/concerns/spree/sanitizable_rich_text.rb b/spree/core/app/models/concerns/spree/sanitizable_rich_text.rbnew file mode 100644index 0000000000..a98d2b6394--- /dev/null+++ b/spree/core/app/models/concerns/spree/sanitizable_rich_text.rb@@ -0,0 +1,37 @@+# frozen_string_literal: true++module Spree+ # Sanitizes rich text attributes through {Spree::RichTextSanitizer} before+ # they hit the database, covering every writer path that ends in a save+ # (Admin API, CSV import, console, translations upsert).+ #+ # Callback-bypassing writes — +update_columns+, +update_all+, raw SQL — are+ # NOT covered by design; call {Spree::RichTextSanitizer.sanitize} explicitly+ # when writing rich text through those paths.+ module SanitizableRichText+ extend ActiveSupport::Concern++ class_methods do+ # Installs a +before_save+ pass sanitizing each named attribute. Only+ # attributes that actually changed are rewritten, so unrelated saves+ # never touch stored content.+ #+ # @param attributes [Array<Symbol>] rich text attribute names+ # @return [void]+ def sanitizes_rich_text(*attributes)+ attributes = attributes.map(&:to_s)++ before_save do+ attributes.each do |attribute|+ next unless will_save_change_to_attribute?(attribute)++ value = self[attribute]+ next if value.blank?++ self[attribute] = Spree::RichTextSanitizer.sanitize(value)+ end+ end+ end+ end+ end+enddiff --git a/spree/core/app/models/spree/product.rb b/spree/core/app/models/spree/product.rbindex 86795d97fe..b41b26a994 100644--- a/spree/core/app/models/spree/product.rb+++ b/spree/core/app/models/spree/product.rb@@ -30,6 +30,7 @@ module Spreeinclude Spree::ProductScopesinclude Spree::TranslatableResourceinclude Spree::MemoizedData+ include Spree::SanitizableRichTextinclude Spree::Metafieldsinclude Spree::MetafieldFilterableinclude Spree::Metadata@@ -62,8 +63,17 @@ module SpreeRICH_TEXT_TRANSLATABLE_FIELDS = %i[description].freezetranslates(*TRANSLATABLE_FIELDS, column_fallback: Spree.mobility_column_fallback)+ sanitizes_rich_text :description++ # Translated descriptions live on the Mobility translation table, so writes+ # through locale accessors or +upsert_translations+ never touch the base+ # record's +description+ attribute — the translation model needs its own+ # sanitization pass.self::Translation.class_eval do+ include Spree::SanitizableRichText+normalizes :name, :meta_title, with: ->(value) { value&.to_s&.squish&.presence }+ sanitizes_rich_text :descriptionend# we need to have this callback before any dependent: :destroy associationsdiff --git a/spree/core/app/models/spree/rich_text_sanitizer.rb b/spree/core/app/models/spree/rich_text_sanitizer.rbnew file mode 100644index 0000000000..f018cb5a05--- /dev/null+++ b/spree/core/app/models/spree/rich_text_sanitizer.rb@@ -0,0 +1,38 @@+# frozen_string_literal: true++module Spree+ # Allowlist sanitizer for rich text HTML stored in plain text columns+ # (e.g. +Spree::Product#description+).+ #+ # The default allowlist is deliberately permissive: legacy descriptions were+ # written with TinyMCE (spans, divs, inline styles, tables, images) and must+ # survive a re-save. It still removes the dangerous surface — +script+,+ # +iframe+, event-handler attributes and +javascript:+ URLs — and Loofah+ # scrubs the contents of +style+ against its own CSS property allowlist.+ #+ # Merchants who embed videos can re-permit +iframe+ from an initializer:+ #+ # Spree::RichTextSanitizer.allowed_tags += %w[iframe]+ # Spree::RichTextSanitizer.allowed_attributes += %w[allowfullscreen frameborder]+ class RichTextSanitizer+ class_attribute :allowed_tags,+ default: (Rails::HTML5::SafeListSanitizer.allowed_tags.to_a ++ %w[table thead tbody tfoot tr th td]).uniq.freeze++ class_attribute :allowed_attributes,+ default: (Rails::HTML5::SafeListSanitizer.allowed_attributes.to_a ++ %w[style target rel colspan rowspan]).uniq.freeze++ # @param html [String, nil] rich text HTML+ # @return [String, nil] HTML with disallowed tags and attributes removed, or the input unchanged when blank+ def self.sanitize(html)+ return html if html.blank?++ Rails::HTML5::SafeListSanitizer.new.sanitize(+ html,+ tags: allowed_tags,+ attributes: allowed_attributes+ )+ end+ end+enddiff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rbindex e7fe77c959..595e314cfc 100644--- a/spree/core/lib/spree/core.rb+++ b/spree/core/lib/spree/core.rb@@ -23,7 +23,10 @@ require 'jwt'require 'monetize'require 'mobility'require 'name_of_person'+require 'nokogiri'+require 'rails-html-sanitizer'require 'paranoia'+require 'request_store'require 'ransack'require 'state_machines-activerecord'require 'active_storage_validations'diff --git a/spree/core/lib/spree/upgrades/5_5_to_5_6/manifest.yml b/spree/core/lib/spree/upgrades/5_5_to_5_6/manifest.ymlindex 3d6aace614..29eb2073fe 100644--- a/spree/core/lib/spree/upgrades/5_5_to_5_6/manifest.yml+++ b/spree/core/lib/spree/upgrades/5_5_to_5_6/manifest.yml@@ -67,3 +67,20 @@ steps:store (matching Spree::Order). New product taggings tenant themselves;only rows created before the upgrade need this. Until it runs, olderproduct tags are hidden from the store-scoped tag vocabulary.++ - id: sanitize_rich_text+ name: "Sanitize stored product descriptions (added in 5.6.2)"+ task: "spree:sanitize_rich_text"+ notes: |+ Runs stored spree_products.description rows (and their translations)+ through Spree::RichTextSanitizer, which also sanitizes all NEW writes+ from 5.6.2 on. Strips script tags, event-handler attributes, and+ javascript: URLs; keeps tables, images, links, and safe inline styles.+ IMPORTANT: iframes (e.g. embedded videos) are stripped by default — if+ your descriptions embed them, permit iframe via+ Spree::RichTextSanitizer.allowed_tags in an initializer BEFORE running.+ Idempotent; only rewrites rows whose sanitized output differs, and+ prints a changed-row count per model.+ Added in 5.6.2: stores that already ran spree:upgrade on 5.6.0/5.6.1 did+ not get this step — re-run spree:upgrade (earlier steps no-op) or run+ `spree:upgrade STEP=sanitize_rich_text`.diff --git a/spree/core/lib/tasks/rich_text.rake b/spree/core/lib/tasks/rich_text.rakenew file mode 100644index 0000000000..191afb4d21--- /dev/null+++ b/spree/core/lib/tasks/rich_text.rake@@ -0,0 +1,44 @@+namespace :spree do+ desc <<~DESC+ Sanitizes rich text HTML already stored in the database through+ +Spree::RichTextSanitizer+ — +spree_products.description+ and its+ per-locale translations.++ Run through +spree:upgrade+ (or on its own) after upgrading to Spree 5.6.2+,+ ideally after reviewing the allowlist (+Spree::RichTextSanitizer.allowed_tags++ / +allowed_attributes+) and re-permitting anything your content relies on,+ e.g. +iframe+ for embedded videos.++ Idempotent — rows whose sanitized output already matches what is stored are+ left untouched, and writes go through +update_all+ so callbacks, timestamps+ and webhooks don't churn. Each write is conditional on the row still holding+ the value that was sanitized, so concurrent edits are never clobbered.+ DESC+ task sanitize_rich_text: :environment do+ # Writes only when the row still holds the value we sanitized, so an edit+ # landing between the read and the write is never clobbered by this batch.+ sanitize = lambda do |record|+ original = record.description+ sanitized = Spree::RichTextSanitizer.sanitize(original)+ next false if sanitized == original++ updated = record.class.unscoped.+ where(id: record.id, description: original).+ update_all(description: sanitized)++ updated.positive?+ end++ products = 0+ Spree::Product.with_deleted.where.not(description: [nil, '']).find_each do |product|+ products += 1 if sanitize.call(product)+ end+ puts " Spree::Product: sanitized #{products} description(s)."++ translations = 0+ Spree::Product::Translation.where.not(description: [nil, '']).find_each do |translation|+ translations += 1 if sanitize.call(translation)+ end+ puts " Spree::Product::Translation: sanitized #{translations} description(s)."+ end+enddiff --git a/spree/core/spec/lib/tasks/rich_text_spec.rb b/spree/core/spec/lib/tasks/rich_text_spec.rbnew file mode 100644index 0000000000..b48fdd803c--- /dev/null+++ b/spree/core/spec/lib/tasks/rich_text_spec.rb@@ -0,0 +1,52 @@+require 'spec_helper'+require 'rake'++describe 'spree:sanitize_rich_text' do+ subject { Rake::Task[task_name] }++ let(:task_name) { 'spree:sanitize_rich_text' }++ before(:all) do+ Rake::Task.define_task(:environment)+ load Spree::Core::Engine.root.join('lib', 'tasks', 'rich_text.rake')+ end++ before { subject.reenable }++ let(:store) { Spree::Store.default || create(:store) }+ # +update_columns+ writes past the sanitizing callback to reproduce+ # pre-upgrade rows.+ let!(:product) { create(:product, store: store).tap { |p| p.update_columns(description: '<p>hi</p><script>alert(1)</script>') } }++ it 'sanitizes stored descriptions' do+ subject.invoke++ expect(product.reload.description).not_to include('<script')+ end++ it 'sanitizes stored translation descriptions' do+ translation = product.translations.create!(locale: 'fr', description: '<p>bonjour</p>')+ translation.update_columns(description: '<p>bonjour</p><script>alert(1)</script>')++ subject.invoke++ expect(translation.reload.description).not_to include('<script')+ end++ it 'leaves clean rows untouched' do+ clean = create(:product, store: store, description: '<p>clean</p>')++ expect { subject.invoke }.not_to change { clean.reload.updated_at }+ end++ it 'does not clobber an edit made after the row was read' do+ allow(Spree::RichTextSanitizer).to receive(:sanitize).and_wrap_original do |original, html|+ product.update_columns(description: '<p>edited elsewhere</p>')+ original.call(html)+ end++ subject.invoke++ expect(product.reload.description).to eq('<p>edited elsewhere</p>')+ end+enddiff --git a/spree/core/spec/models/spree/rich_text_sanitizer_spec.rb b/spree/core/spec/models/spree/rich_text_sanitizer_spec.rbnew file mode 100644index 0000000000..1681fca336--- /dev/null+++ b/spree/core/spec/models/spree/rich_text_sanitizer_spec.rb@@ -0,0 +1,76 @@+require 'spec_helper'++describe Spree::RichTextSanitizer do+ subject { described_class.sanitize(html) }++ describe '.sanitize' do+ context 'with a script tag' do+ let(:html) { '<p>safe</p><script>alert(1)</script>' }++ it { is_expected.not_to include('<script') }+ it { is_expected.to include('<p>safe</p>') }+ end++ context 'with event handler attributes' do+ let(:html) { '<img src="a.png" onerror="steal()"><div onclick="steal()">x</div>' }++ it { is_expected.not_to include('onerror') }+ it { is_expected.not_to include('onclick') }+ end++ context 'with a javascript: URL' do+ let(:html) { '<a href="javascript:alert(1)">x</a>' }++ it { is_expected.not_to include('javascript:') }+ end++ context 'with a link' do+ let(:html) { '<a href="https://example.com" target="_blank" rel="noopener">x</a>' }++ it { is_expected.to eq(html) }+ end++ context 'with table markup' do+ let(:html) { '<table><thead><tr><th colspan="2">h</th></tr></thead><tbody><tr><td rowspan="2">c</td></tr></tbody></table>' }++ it { is_expected.to eq(html) }+ end++ context 'with an image' do+ let(:html) { '<img src="https://example.com/a.png" alt="a" width="10" height="20">' }++ it { is_expected.to include('src="https://example.com/a.png"', 'alt="a"', 'width="10"', 'height="20"') }+ end++ context 'with an iframe' do+ let(:html) { '<iframe src="https://example.com/video"></iframe>' }++ it { is_expected.not_to include('<iframe') }++ context 'when iframe is added to the allowlist' do+ around do |example|+ original = described_class.allowed_tags+ described_class.allowed_tags = original + %w[iframe]+ example.run+ described_class.allowed_tags = original+ end++ it { is_expected.to include('<iframe') }+ end+ end++ context 'with inline styles' do+ let(:html) { '<p style="color: red; position: fixed">x</p>' }++ it 'keeps allowed CSS properties and drops the rest' do+ expect(subject).to include('color:red')+ expect(subject).not_to include('position')+ end+ end++ context 'when blank' do+ it { expect(described_class.sanitize(nil)).to be_nil }+ it { expect(described_class.sanitize('')).to eq('') }+ end+ end+enddiff --git a/spree/core/spec/models/spree/sanitizable_rich_text_spec.rb b/spree/core/spec/models/spree/sanitizable_rich_text_spec.rbnew file mode 100644index 0000000000..ce136902bd--- /dev/null+++ b/spree/core/spec/models/spree/sanitizable_rich_text_spec.rb@@ -0,0 +1,29 @@+require 'spec_helper'++describe Spree::SanitizableRichText do+ let(:store) { Spree::Store.default || create(:store) }+ let(:product) { create(:product, store: store) }++ it 'sanitizes the description on save' do+ product.update!(description: '<p>safe</p><script>alert(1)</script>')++ expect(product.reload.description).to include('<p>safe</p>')+ expect(product.reload.description).not_to include('<script')+ end++ it 'leaves an already stored raw description alone when an unrelated attribute changes' do+ product.update_columns(description: '<script>alert(1)</script>')++ product.update!(name: 'Renamed')++ expect(product.reload.description).to eq('<script>alert(1)</script>')+ end++ it 'sanitizes translated descriptions' do+ store.update!(supported_locales: 'en,fr')++ product.upsert_translations('fr' => { 'description' => '<p>bonjour</p><script>alert(1)</script>' })++ expect(product.reload.get_field_with_locale(:fr, :description)).not_to include('<script')+ end+enddiff --git a/spree/core/spree_core.gemspec b/spree/core/spree_core.gemspecindex 04224cfd97..6cb7298003 100644--- a/spree/core/spree_core.gemspec+++ b/spree/core/spree_core.gemspec@@ -45,9 +45,12 @@ Gem::Specification.new do |s|s.add_dependency 'money', '~> 6.13's.add_dependency 'monetize', '~> 1.9's.add_dependency 'name_of_person', '~> 1.1'+ s.add_dependency 'nokogiri', '~> 1.18's.add_dependency 'ostruct's.add_dependency 'paranoia', '>= 2.4'+ s.add_dependency 'rails-html-sanitizer', '~> 1.6's.add_dependency 'ransack', '>= 4.1'+ s.add_dependency 'request_store', '~> 1.5's.add_dependency 'rexml's.add_dependency 'state_machines-activerecord', '~> 0.100'