Skip to content

Commit

Permalink
Tweak: Ensure editor HTML attributes are escaped
Browse files Browse the repository at this point in the history
  • Loading branch information
tomusborne committed Dec 18, 2024
1 parent d66095c commit bb0f610
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 additions & 1 deletion src/hoc/withHtmlAttributes.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,16 @@ function shallowEqual( obj1, obj2 ) {
return true;
}

const sanitizeAttributeValue = ( value ) => {
// Replace characters like &, <, >, " with their HTML entity equivalents
return value
.replace( /&/g, '&amp;' )
.replace( /</g, '&lt;' )
.replace( />/g, '&gt;' )
.replace( /"/g, '&quot;' )
.replace( /'/g, '&#039;' );
};

export function withHtmlAttributes( WrappedComponent ) {
return ( ( props ) => {
const {
Expand All @@ -77,6 +87,10 @@ export function withHtmlAttributes( WrappedComponent ) {

const isSavingPost = useSelect( ( select ) => select( 'core/editor' ).isSavingPost() );
const { style = '', href, ...otherAttributes } = htmlAttributes;
const escapedAttributes = Object.keys( otherAttributes ).reduce( ( acc, key ) => {
acc[ key ] = sanitizeAttributeValue( otherAttributes[ key ] );
return acc;
}, {} );
const [ processedStyle, setProcessedStyle ] = useState( style );

useEffect( () => {
Expand Down Expand Up @@ -111,7 +125,7 @@ export function withHtmlAttributes( WrappedComponent ) {
? convertInlineStyleStringToObject( processedStyle )
: '';
const combinedAttributes = {
...otherAttributes,
...escapedAttributes,
style: inlineStyleObject,
'data-gb-id': uniqueId,
'data-context-post-id': context?.postId ?? context?.[ 'generateblocks/loopIndex' ] ?? 0,
Expand Down

0 comments on commit bb0f610

Please sign in to comment.