Skip to content

setAttribute("style") violates Content Security Policy (CSP) style-src #287

@eagle-head

Description

@eagle-head

Problem

morphAttrs uses setAttribute(attrName, attrValue) for all attributes, including style. When a page enforces a Content Security Policy with style-src that does not include 'unsafe-inline', setAttribute("style", ...) is blocked by the browser.

This causes CSP violations on every DOM patch that touches inline styles — breaking frameworks like Phoenix LiveView that use morphdom for DOM diffing.

CSP spec behavior

Per the W3C CSP3 spec (§8.3) and MDN style-src documentation:

Method Blocked by CSP style-src?
element.style.property = "value" No — always allowed
element.style.setProperty("prop", "val") No — always allowed
element.setAttribute("style", "...") Yes — blocked without 'unsafe-inline'
element.style.cssText = "..." Yes — blocked without 'unsafe-inline'

Steps to reproduce

  1. Set a CSP header: style-src 'self' 'nonce-abc123' (no 'unsafe-inline')
  2. Have two elements where the style attribute differs
  3. Call morphdom(fromEl, toEl)
  4. Observe CSP violation in the browser console: Refused to apply inline style because it violates the following Content Security Policy directive: "style-src ..."

Expected behavior

morphdom should sync the style attribute using the DOM style API (style.setProperty / style.removeProperty) instead of setAttribute("style", ...), since the DOM style API is never blocked by CSP.

Impact

This affects any project using morphdom with a strict CSP policy:

  • Phoenix LiveView — morphdom is the DOM diffing engine; any LiveView template with inline styles triggers CSP violations
  • htmx (via morphdom-swap extension)
  • CableReady
  • Any application enforcing CSP Level 3 with nonce-based style-src

References

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions