From 3625a4f55dd3ca2082c9075808fcb6a3954e7233 Mon Sep 17 00:00:00 2001 From: "Jorge A. Torres" Date: Tue, 20 Aug 2024 17:33:59 -0300 Subject: [PATCH] Cherry pick #371 into release/9.2 (#50802) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 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 * Add tests and tweak stripTags * Tweak tests * Update packages/js/currency/src/utils.tsx Co-authored-by: Joshua T Flowers * Update packages/js/currency/src/utils.tsx Co-authored-by: Joshua T Flowers * Update packages/js/currency/src/utils.tsx Co-authored-by: Joshua T Flowers * Update packages/js/currency/src/utils.tsx Co-authored-by: Joshua T Flowers --------- Co-authored-by: Tomek Wytrębowicz Co-authored-by: Naman Malhotra Co-authored-by: Miguel Pérez Pellicer <5908855+puntope@users.noreply.github.com> Co-authored-by: Joshua T Flowers --- packages/js/currency/src/test/index.ts | 16 ++++++++++++++++ packages/js/currency/src/utils.tsx | 14 +++++++++++--- 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/packages/js/currency/src/test/index.ts b/packages/js/currency/src/test/index.ts index 3f6ef2529de..f3bdf8c1b68 100644 --- a/packages/js/currency/src/test/index.ts +++ b/packages/js/currency/src/test/index.ts @@ -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: 'tagformat', + } ) + ).toBe( 'tagformat' ); + + expect( + currency.getPriceFormat( { + priceFormat: 'format', + } ) + ).toBe( 'format' ); + } ); } ); diff --git a/packages/js/currency/src/utils.tsx b/packages/js/currency/src/utils.tsx index 2a8901991fa..b0807de6866 100644 --- a/packages/js/currency/src/utils.tsx +++ b/packages/js/currency/src/utils.tsx @@ -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( /|$)/g, '' ) + .replace( /<(script|style)[^>]*>[\s\S]*?(<\/\1>|$)/gi, '' ) + .replace( /<\/?[a-z][\s\S]*?(>|$)/gi, '' ); + + if ( strippedStr !== str ) { + return stripTags( strippedStr ); + } + + return strippedStr; } /**