Cherry pick #371 into release/9.2 (#50802)

* Use inert `template` tag to strip tags w/o executing any JS

Fixes https://github.com/Automattic/woocommerce/issues/370

* Guard against legacy browsers to avoid executing JS there.

* Make sure `stripTags` always return `string` not `null`

* Fix typo in code comment  packages/js/currency/src/utils.tsx

Co-authored-by: Naman Malhotra <naman03malhotra@gmail.com>

* Add tests and tweak stripTags

* Tweak tests

* Update packages/js/currency/src/utils.tsx

Co-authored-by: Joshua T Flowers <joshuatf@gmail.com>

* Update packages/js/currency/src/utils.tsx

Co-authored-by: Joshua T Flowers <joshuatf@gmail.com>

* Update packages/js/currency/src/utils.tsx

Co-authored-by: Joshua T Flowers <joshuatf@gmail.com>

* Update packages/js/currency/src/utils.tsx

Co-authored-by: Joshua T Flowers <joshuatf@gmail.com>

---------

Co-authored-by: Tomek Wytrębowicz <tomalecpub@gmail.com>
Co-authored-by: Naman Malhotra <naman03malhotra@gmail.com>
Co-authored-by: Miguel Pérez Pellicer <5908855+puntope@users.noreply.github.com>
Co-authored-by: Joshua T Flowers <joshuatf@gmail.com>
This commit is contained in:
Jorge A. Torres 2024-08-20 17:33:59 -03:00 committed by GitHub
parent a9845e6a1d
commit 3625a4f55d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 27 additions and 3 deletions

View File

@ -102,4 +102,20 @@ describe( 'currency.formatDecimalString', () => {
// @ts-expect-error formatAccount expects a number or string;
expect( currency.formatDecimalString( null ) ).toBe( '' );
} );
it( 'should strip tags in getPriceFormat', () => {
const currency = Currency();
expect(
currency.getPriceFormat( {
priceFormat: '<b>tag</b>format',
} )
).toBe( 'tagformat' );
expect(
currency.getPriceFormat( {
priceFormat: '<script>tag</script>format',
} )
).toBe( 'format' );
} );
} );

View File

@ -66,9 +66,17 @@ const CurrencyFactoryBase = function ( currencySetting?: CurrencyConfig ) {
let currency: Currency;
function stripTags( str: string ) {
const tmp = document.createElement( 'DIV' );
tmp.innerHTML = str;
return tmp.textContent || tmp.innerText || '';
// sanitize Polyfill - see https://github.com/WordPress/WordPress/blob/master/wp-includes/js/wp-sanitize.js
const strippedStr = str
.replace( /<!--[\s\S]*?(-->|$)/g, '' )
.replace( /<(script|style)[^>]*>[\s\S]*?(<\/\1>|$)/gi, '' )
.replace( /<\/?[a-z][\s\S]*?(>|$)/gi, '' );
if ( strippedStr !== str ) {
return stripTags( strippedStr );
}
return strippedStr;
}
/**