From 0d801a2a26130ba38163659c5ce6693972da9766 Mon Sep 17 00:00:00 2001 From: Tsvetan Stoychev Date: Thu, 17 Sep 2026 15:50:57 +0300 Subject: [PATCH 01/28] fix(config): enforce safe monitoring configuration --- .../Analytics/Block/Boomerang/Loader.php | 60 ++++++++++-------- .../BasicRum/Analytics/Helper/Data.php | 62 +++++++++++++++---- .../Analytics/Model/Setup/PrivacyDefault.php | 30 +++++++++ .../System/Config/Backend/BeaconEndpoint.php | 29 +++++++++ .../Model/System/Config/Backend/SiteId.php | 8 +-- .../BasicRum/Analytics/etc/config.xml | 16 ++++- .../BasicRum/Analytics/etc/system.xml | 10 +-- .../install-1.1.0.php | 33 ++++++++++ app/locale/en_US/BasicRum_Analytics.csv | 5 +- js/basicrum/LICENSE.txt | 37 +++++++++++ modman | 6 +- 11 files changed, 245 insertions(+), 51 deletions(-) create mode 100644 app/code/community/BasicRum/Analytics/Model/Setup/PrivacyDefault.php create mode 100644 app/code/community/BasicRum/Analytics/Model/System/Config/Backend/BeaconEndpoint.php create mode 100644 app/code/community/BasicRum/Analytics/sql/basicrum_analytics_setup/install-1.1.0.php create mode 100644 js/basicrum/LICENSE.txt diff --git a/app/code/community/BasicRum/Analytics/Block/Boomerang/Loader.php b/app/code/community/BasicRum/Analytics/Block/Boomerang/Loader.php index dec261f..5288660 100644 --- a/app/code/community/BasicRum/Analytics/Block/Boomerang/Loader.php +++ b/app/code/community/BasicRum/Analytics/Block/Boomerang/Loader.php @@ -25,9 +25,11 @@ public function getBoomerangSnippet(): string return ''; } - // 1. Add anti-tampering technique. - $beaconEndpoint = Mage::helper('core')->escapeUrl($helper->getBeaconEndpoint()); - if ($beaconEndpoint === null || trim($beaconEndpoint) === '') { + $beaconEndpoint = $helper->getBeaconEndpoint(); + $siteId = $helper->getBrumSiteId(); + + // Monitoring is never emitted with an incomplete or invalid identity. + if ($beaconEndpoint === null || $siteId === null) { return ''; } @@ -47,16 +49,32 @@ public function getBoomerangSnippet(): string $boomerangVars = [ ["addVar", "p_type", $pageType], - ["addVar", "p_gen", "mage1"] + ["addVar", "p_gen", "mage1"], + ["addVar", "brum_site_id", $siteId] ]; - $siteId = $helper->getBrumSiteId(); - if ($siteId !== null) { - $boomerangVars[] = ["addVar", "brum_site_id", $siteId]; - } - $jsonFlags = JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT; $boomerangVarsJs = json_encode($boomerangVars, $jsonFlags); + $boomerangJsUrlJs = json_encode($boomerangJsUrl, $jsonFlags); + $loaderScriptUrlJs = json_encode($loaderScriptUrl, $jsonFlags); + $configJs = json_encode([ + 'beacon_url' => $beaconEndpoint, + 'instrument_xhr' => false, + 'Continuity' => [ + 'enabled' => true + ], + 'ResourceTiming' => [ + 'enabled' => true, + 'splitAtPath' => true + ], + 'secure_cookie' => true, + 'same_site_cookie' => 'Strict' + ], $jsonFlags); + + if ($boomerangVarsJs === false || $boomerangJsUrlJs === false + || $loaderScriptUrlJs === false || $configJs === false) { + return ''; + } $waitAfterOnloadScript = ''; if ($waitAfterOnloadEnabled) { @@ -91,37 +109,25 @@ public function getBoomerangSnippet(): string return; } - w.BOOMR_mq = window.BOOMR_mq || []; + w.BOOMR_mq = w.BOOMR_mq || []; w.BOOMR_mq.push.apply(w.BOOMR_mq, {$boomerangVarsJs}); - w.BOOMR = (w.BOOMR !== undefined) ? w.BOOMR : {}; + w.BOOMR = w.BOOMR || {}; var b = w.BOOMR; - - b.url = "{$boomerangJsUrl}"; + + b.url = {$boomerangJsUrlJs}; {$waitAfterOnloadScript} - w.basicRumBoomerangConfig = { - beacon_url: "{$beaconEndpoint}", - instrument_xhr: false, - Continuity: { - enabled: true - }, - ResourceTiming: { - "enabled": true, - "splitAtPath": true - }, - secure_cookie: true, - same_site_cookie: "Strict" - } + w.basicRumBoomerangConfig = {$configJs}; })(window); (function(d, s) { var js = d.createElement(s), sc = d.getElementsByTagName(s)[0]; - js.src="{$loaderScriptUrl}"; + js.src = {$loaderScriptUrlJs}; js.async = true; sc.parentNode.insertBefore(js, sc); diff --git a/app/code/community/BasicRum/Analytics/Helper/Data.php b/app/code/community/BasicRum/Analytics/Helper/Data.php index 460d468..dad9d13 100644 --- a/app/code/community/BasicRum/Analytics/Helper/Data.php +++ b/app/code/community/BasicRum/Analytics/Helper/Data.php @@ -6,6 +6,11 @@ */ class BasicRum_Analytics_Helper_Data extends Mage_Core_Helper_Abstract { + /** + * Basicrum backend identifiers are RFC 4122 UUID v4 values. + */ + const BRUM_SITE_ID_PATTERN = '/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i'; + /** * Check if Basic RUM analytics is enabled @@ -31,15 +36,18 @@ public function isOptInRequired(): bool */ public function getBeaconEndpoint() { - $url = Mage::getStoreConfig('basicrum_analytics/general/beacon_endpoint'); - if ($url && filter_var($url, FILTER_VALIDATE_URL)) { - // Auto-upgrade HTTP to HTTPS when request is secure to prevent mixed content - if (Mage::app()->getRequest()->isSecure()) { - $url = preg_replace('/^http:\/\//i', 'https://', $url); - } - return $url; + $url = trim((string) Mage::getStoreConfig('basicrum_analytics/general/beacon_endpoint')); + + if (!self::isValidBeaconEndpoint($url)) { + return null; } - return null; + + // Auto-upgrade HTTP to HTTPS when request is secure to prevent mixed content. + if (Mage::app()->getRequest()->isSecure()) { + $url = preg_replace('/^http:\/\//i', 'https://', $url); + } + + return $url; } /** @@ -48,8 +56,40 @@ public function getBeaconEndpoint() */ public function getBrumSiteId() { - $value = Mage::getStoreConfig('basicrum_analytics/general/brum_site_id'); - return $value ? trim($value) : null; + $value = trim((string) Mage::getStoreConfig('basicrum_analytics/general/brum_site_id')); + + return self::isValidBrumSiteId($value) ? $value : null; + } + + /** + * Validate a Beacon endpoint without accepting executable URL schemes. + * + * @param mixed $value + * @return bool + */ + public static function isValidBeaconEndpoint($value): bool + { + if (!is_string($value) || $value === '' || filter_var($value, FILTER_VALIDATE_URL) === false) { + return false; + } + + $parts = parse_url($value); + if (!is_array($parts) || empty($parts['scheme']) || empty($parts['host'])) { + return false; + } + + return in_array(strtolower($parts['scheme']), ['http', 'https'], true); + } + + /** + * Validate the Basicrum backend identifier contract (UUID v4). + * + * @param mixed $value + * @return bool + */ + public static function isValidBrumSiteId($value): bool + { + return is_string($value) && preg_match(self::BRUM_SITE_ID_PATTERN, $value) === 1; } /** @@ -68,7 +108,7 @@ public function isWaitAfterOnloadEnabled(): bool public function getWaitAfterOnloadMilliseconds(): int { $value = (int) Mage::getStoreConfig('basicrum_analytics/wait_after_onload/wait_ms'); - return max(0, $value); + return min(30000, max(0, $value)); } /** diff --git a/app/code/community/BasicRum/Analytics/Model/Setup/PrivacyDefault.php b/app/code/community/BasicRum/Analytics/Model/Setup/PrivacyDefault.php new file mode 100644 index 0000000..21d1a99 --- /dev/null +++ b/app/code/community/BasicRum/Analytics/Model/Setup/PrivacyDefault.php @@ -0,0 +1,30 @@ +getValue()); + + if ($value !== '' && !BasicRum_Analytics_Helper_Data::isValidBeaconEndpoint($value)) { + Mage::throwException( + Mage::helper('basicrum_analytics')->__('Beacon Endpoint URL must be a valid HTTP or HTTPS URL.') + ); + } + + $this->setValue($value); + + return parent::_beforeSave(); + } +} diff --git a/app/code/community/BasicRum/Analytics/Model/System/Config/Backend/SiteId.php b/app/code/community/BasicRum/Analytics/Model/System/Config/Backend/SiteId.php index dc3a54b..4e89767 100644 --- a/app/code/community/BasicRum/Analytics/Model/System/Config/Backend/SiteId.php +++ b/app/code/community/BasicRum/Analytics/Model/System/Config/Backend/SiteId.php @@ -6,8 +6,6 @@ */ class BasicRum_Analytics_Model_System_Config_Backend_SiteId extends Mage_Core_Model_Config_Data { - const UUID_PATTERN = '/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i'; - /** * Validate the value before saving * @@ -16,14 +14,16 @@ class BasicRum_Analytics_Model_System_Config_Backend_SiteId extends Mage_Core_Mo */ protected function _beforeSave() { - $value = (string) $this->getValue(); + $value = trim((string) $this->getValue()); - if ($value !== '' && !preg_match(self::UUID_PATTERN, $value)) { + if ($value !== '' && !BasicRum_Analytics_Helper_Data::isValidBrumSiteId($value)) { Mage::throwException( Mage::helper('basicrum_analytics')->__('BasicRUM Site ID must be a valid UUID (e.g. e926c1a2-7e33-4f54-90d0-e6e31f3ad43d).') ); } + $this->setValue($value); + return parent::_beforeSave(); } } diff --git a/app/code/community/BasicRum/Analytics/etc/config.xml b/app/code/community/BasicRum/Analytics/etc/config.xml index fae1b39..8421fb4 100644 --- a/app/code/community/BasicRum/Analytics/etc/config.xml +++ b/app/code/community/BasicRum/Analytics/etc/config.xml @@ -2,7 +2,7 @@ - 1.0.1 + 1.1.0 @@ -22,6 +22,16 @@ BasicRum_Analytics_Block + + + + BasicRum_Analytics + + + core_setup + + + @@ -53,11 +63,11 @@ - 0 + 1 0 - 0 + 0 0 diff --git a/app/code/community/BasicRum/Analytics/etc/system.xml b/app/code/community/BasicRum/Analytics/etc/system.xml index 18b3488..02543d4 100644 --- a/app/code/community/BasicRum/Analytics/etc/system.xml +++ b/app/code/community/BasicRum/Analytics/etc/system.xml @@ -47,11 +47,12 @@ text + basicrum_analytics/system_config_backend_beaconEndpoint 2 1 1 1 - Example: https://www.xxxxxx.com/beacon/catcher + Required. HTTP or HTTPS URL supplied by Basicrum. Example: https://www.example.com/beacon/catcher @@ -61,7 +62,7 @@ 1 1 1 - Example: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx]]> + Example: e926c1a2-7e33-4f54-90d0-e6e31f3ad43d]]> @@ -74,7 +75,7 @@ 1 - + select basicrum_analytics/adminhtml_system_config_form_field_consentInfo adminhtml/system_config_source_yesno @@ -82,6 +83,7 @@ 1 1 1 + Recommended. Monitoring remains off until the external consent tool explicitly allows it on each page. @@ -110,7 +112,7 @@ 1 1 1 - Milliseconds to delay the beacon to capture additional metrics. + Milliseconds to delay the beacon to capture additional metrics. Values are limited to 0–30000 milliseconds (30 seconds); larger values are capped at 30000. 1 diff --git a/app/code/community/BasicRum/Analytics/sql/basicrum_analytics_setup/install-1.1.0.php b/app/code/community/BasicRum/Analytics/sql/basicrum_analytics_setup/install-1.1.0.php new file mode 100644 index 0000000..ef46f2a --- /dev/null +++ b/app/code/community/BasicRum/Analytics/sql/basicrum_analytics_setup/install-1.1.0.php @@ -0,0 +1,33 @@ +startSetup(); + +$connection = $installer->getConnection(); +$configTable = $installer->getTable('core/config_data'); +$consentPath = 'basicrum_analytics/privacy/opt_in_required'; + +$explicitDefaultSelect = $connection->select() + ->from($configTable, 'path') + ->where('path = ?', $consentPath) + ->where('scope = ?', 'default') + ->where('scope_id = ?', 0) + ->limit(1); + +$existingConfigurationSelect = $connection->select() + ->from($configTable, 'path') + ->where('path LIKE ?', 'basicrum_analytics/%') + ->limit(1); + +$value = BasicRum_Analytics_Model_Setup_PrivacyDefault::getValueToPersist( + $connection->fetchOne($explicitDefaultSelect) !== false, + $connection->fetchOne($existingConfigurationSelect) !== false +); + +if ($value !== null) { + Mage::getConfig()->saveConfig($consentPath, $value, 'default', 0); +} + +$installer->endSetup(); diff --git a/app/locale/en_US/BasicRum_Analytics.csv b/app/locale/en_US/BasicRum_Analytics.csv index 7ab2b99..0ac9b9b 100644 --- a/app/locale/en_US/BasicRum_Analytics.csv +++ b/app/locale/en_US/BasicRum_Analytics.csv @@ -4,10 +4,13 @@ "General Settings","General Settings" "Enable Analytics","Enable Analytics" "Beacon Endpoint URL","Beacon Endpoint URL" +"BasicRUM Site ID","BasicRUM Site ID" "Enter the URL where analytics data will be sent","Enter the URL where analytics data will be sent" +"Data Privacy / GDPR","Data Privacy / GDPR" +"Require Consent Before Monitoring","Require Consent Before Monitoring" "Enable Wait After Onload","Enable Wait After Onload" "Wait After Onload (ms)","Wait After Onload (ms)" "Milliseconds to delay the beacon to capture additional metrics.","Milliseconds to delay the beacon to capture additional metrics." "Developer","Developer" "Use Unminified Loaders","Use Unminified Loaders" -"Enable to load non-minified loader scripts for debugging purposes.","Enable to load non-minified loader scripts for debugging purposes." \ No newline at end of file +"Enable to load non-minified loader scripts for debugging purposes.","Enable to load non-minified loader scripts for debugging purposes." diff --git a/js/basicrum/LICENSE.txt b/js/basicrum/LICENSE.txt new file mode 100644 index 0000000..39a8372 --- /dev/null +++ b/js/basicrum/LICENSE.txt @@ -0,0 +1,37 @@ +Software Copyright License Agreement (BSD License) + +Copyright (c) 2011, Yahoo! Inc. +Copyright (c) 2011-2012, Log-Normal, Inc. +Copyright (c) 2012-2017, SOASTA, Inc. +Copyright (c) 2017-2023, Akamai Technologies, Inc. +All rights reserved. + +Redistribution and use of this software in source and binary forms, +with or without modification, are permitted provided that the following +conditions are met: + +* Redistributions of source code must retain the above + copyright notice, this list of conditions and the + following disclaimer. + +* Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the + following disclaimer in the documentation and/or other + materials provided with the distribution. + +* Neither the name of Yahoo! Inc. nor the names of its + contributors may be used to endorse or promote products + derived from this software without specific prior + written permission of Yahoo! Inc. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/modman b/modman index 5f10419..8137da0 100644 --- a/modman +++ b/modman @@ -9,11 +9,14 @@ app/code/community/BasicRum/Analytics/Block/Adminhtml/System/Config/Form/Field/C app/code/community/BasicRum/Analytics/Block/Boomerang/Loader.php app/code/community/BasicRum/Analytics/Block/Boomerang/Loader.php app/code/community/BasicRum/Analytics/Helper/Data.php app/code/community/BasicRum/Analytics/Helper/Data.php app/code/community/BasicRum/Analytics/Helper/PageTypeDetector.php app/code/community/BasicRum/Analytics/Helper/PageTypeDetector.php +app/code/community/BasicRum/Analytics/Model/Setup/PrivacyDefault.php app/code/community/BasicRum/Analytics/Model/Setup/PrivacyDefault.php app/code/community/BasicRum/Analytics/Model/System/Config/Source/Version.php app/code/community/BasicRum/Analytics/Model/System/Config/Source/Version.php +app/code/community/BasicRum/Analytics/Model/System/Config/Backend/BeaconEndpoint.php app/code/community/BasicRum/Analytics/Model/System/Config/Backend/BeaconEndpoint.php app/code/community/BasicRum/Analytics/Model/System/Config/Backend/SiteId.php app/code/community/BasicRum/Analytics/Model/System/Config/Backend/SiteId.php app/code/community/BasicRum/Analytics/etc/config.xml app/code/community/BasicRum/Analytics/etc/config.xml app/code/community/BasicRum/Analytics/etc/adminhtml.xml app/code/community/BasicRum/Analytics/etc/adminhtml.xml app/code/community/BasicRum/Analytics/etc/system.xml app/code/community/BasicRum/Analytics/etc/system.xml +app/code/community/BasicRum/Analytics/sql/basicrum_analytics_setup/install-1.1.0.php app/code/community/BasicRum/Analytics/sql/basicrum_analytics_setup/install-1.1.0.php # Locale/Translation files app/locale/en_US/BasicRum_Analytics.csv app/locale/en_US/BasicRum_Analytics.csv @@ -21,7 +24,8 @@ app/locale/en_US/BasicRum_Analytics.csv a # Frontend files app/design/frontend/base/default/layout/basicrum_analytics.xml app/design/frontend/base/default/layout/basicrum_analytics.xml js/basicrum/boomerangs/boomerang-1.815.60.cutting-edge.min.js js/basicrum/boomerangs/boomerang-1.815.60.cutting-edge.min.js +js/basicrum/LICENSE.txt js/basicrum/LICENSE.txt js/basicrum/loaders/boomerang-loader-v15.js js/basicrum/loaders/boomerang-loader-v15.js js/basicrum/loaders/boomerang-loader-v15.min.js js/basicrum/loaders/boomerang-loader-v15.min.js js/basicrum/loaders/consent-boomerang-loader-v1-15.js js/basicrum/loaders/consent-boomerang-loader-v1-15.js -js/basicrum/loaders/consent-boomerang-loader-v1-15.min.js js/basicrum/loaders/consent-boomerang-loader-v1-15.min.js \ No newline at end of file +js/basicrum/loaders/consent-boomerang-loader-v1-15.min.js js/basicrum/loaders/consent-boomerang-loader-v1-15.min.js From b250a5158e63524ddfabfc957b3f1b069abcbe4d Mon Sep 17 00:00:00 2001 From: Tsvetan Stoychev Date: Thu, 17 Sep 2026 15:51:02 +0300 Subject: [PATCH 02/28] fix(consent): harden loading and withdrawal behavior --- .../System/Config/Form/Field/ConsentInfo.php | 65 ++++------------ .../Analytics/Block/Boomerang/Loader.php | 8 +- .../loaders/consent-boomerang-loader-v1-15.js | 74 +++++++++++++------ .../consent-boomerang-loader-v1-15.min.js | 2 +- 4 files changed, 72 insertions(+), 77 deletions(-) diff --git a/app/code/community/BasicRum/Analytics/Block/Adminhtml/System/Config/Form/Field/ConsentInfo.php b/app/code/community/BasicRum/Analytics/Block/Adminhtml/System/Config/Form/Field/ConsentInfo.php index 90a08af..21d1c93 100644 --- a/app/code/community/BasicRum/Analytics/Block/Adminhtml/System/Config/Form/Field/ConsentInfo.php +++ b/app/code/community/BasicRum/Analytics/Block/Adminhtml/System/Config/Form/Field/ConsentInfo.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Custom renderer for consent/opt-in information in admin config + * Custom renderer for consent/opt-in information in admin config. */ class BasicRum_Analytics_Block_Adminhtml_System_Config_Form_Field_ConsentInfo extends Mage_Adminhtml_Block_System_Config_Form_Field { /** - * Render the field with custom info box below + * Render the field with consent integration guidance. * * @param Varien_Data_Form_Element_Abstract $element * @return string @@ -19,63 +19,26 @@ protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element): $infoHtml = << -
- JavaScript API for Cookie Consent Integration -
-
- When opt-in is enabled, Boomerang will not load until consent is given. Use these global functions to integrate with your cookie consent solution: -
+
JavaScript API for Cookie Consent Integration
+

In consent-controlled mode, Basicrum stays inert until your external consent tool explicitly allows performance monitoring on the current page. Basicrum does not store or infer a consent decision.

- - + + - - + +
- OPT_IN_BASIC_RUM() - - Call when user accepts cookies/tracking. Loads Boomerang and sets consent cookie. - OPT_IN_BASICRUM_LOADER_WRAPPER()Call when the external tool reports that monitoring is allowed.
- OPT_OUT_BASIC_RUM() - - Call when user rejects tracking. Disables Boomerang and clears all RUM cookies. - OPT_OUT_BASICRUM_LOADER_WRAPPER()Call when monitoring is denied or withdrawn. This disables future collection and removes RT, BA, and legacy Basicrum consent cookies, but it cannot retract data already sent.
-
-
- Cookies Created -
- - - - - - - - - - - - - -
BOOMR_CONSENTRemembers user consent preference (expires after 1 year)
RTRound-trip timing cookie (created on opt-in, deleted on opt-out)
BABandwidth/latency cookie (created on opt-in, deleted on opt-out)
-
-
-
- Integration Example: -
-
+

OPT_IN_BASIC_RUM() and OPT_OUT_BASIC_RUM() remain available as backward-compatible Magento 1 aliases.

+

A deny before the first opt-in can be followed by an allow on the same page. After monitoring has started and consent is withdrawn, reload the page before re-granting; monitoring remains disabled for the rest of that page view.

-
// Accept button handler
-if (typeof window.OPT_IN_BASIC_RUM === 'function') {
-    window.OPT_IN_BASIC_RUM();
+        
if (typeof window.OPT_IN_BASICRUM_LOADER_WRAPPER === 'function') {
+    window.OPT_IN_BASICRUM_LOADER_WRAPPER();
 }
-
-// Reject button handler
-if (typeof window.OPT_OUT_BASIC_RUM === 'function') {
-    window.OPT_OUT_BASIC_RUM();
+if (typeof window.OPT_OUT_BASICRUM_LOADER_WRAPPER === 'function') {
+    window.OPT_OUT_BASICRUM_LOADER_WRAPPER();
 }
diff --git a/app/code/community/BasicRum/Analytics/Block/Boomerang/Loader.php b/app/code/community/BasicRum/Analytics/Block/Boomerang/Loader.php index 5288660..18d88dc 100644 --- a/app/code/community/BasicRum/Analytics/Block/Boomerang/Loader.php +++ b/app/code/community/BasicRum/Analytics/Block/Boomerang/Loader.php @@ -83,10 +83,16 @@ public function getBoomerangSnippet(): string b.plugins.WaitAfterOnload = { complete: false, + timer: null, init: function() { b.subscribe("page_ready", function() { - setTimeout(function() { + this.timer = setTimeout(function() { + this.timer = null; + if (w.basicRumConsentWithdrawn) { + return; + } + this.complete = true; b.sendBeacon(); }.bind(this), {$waitAfterOnloadMilliseconds}); diff --git a/js/basicrum/loaders/consent-boomerang-loader-v1-15.js b/js/basicrum/loaders/consent-boomerang-loader-v1-15.js index b66b0aa..b691636 100644 --- a/js/basicrum/loaders/consent-boomerang-loader-v1-15.js +++ b/js/basicrum/loaders/consent-boomerang-loader-v1-15.js @@ -195,44 +195,70 @@ w.attachEvent("onload", boomerangSaveLoadTime); } } - - // Helper to build cookie attributes - function getCookieAttrs() { + + // Remove cookies created by older Basicrum consent loaders and Boomerang. + function removeCookie(name) { var hostname = mainWin.location && mainWin.location.hostname; - var isSecure = mainWin.location && mainWin.location.protocol === "https:"; - var secureAttr = isSecure ? "; Secure" : ""; - var domainAttr = hostname ? "; domain=" + hostname : ""; - return { secure: secureAttr, domain: domainAttr }; + var cookie = name + "=; path=/; max-age=0; SameSite=Strict"; + var domainParts; + var index; + + mainWin.document.cookie = cookie; + if (hostname) { + domainParts = hostname.split("."); + for (index = 0; index < domainParts.length; index++) { + mainWin.document.cookie = cookie + "; domain=" + domainParts.slice(index).join("."); + } + } } - // Callback function to opt-in to Boomerang tracking - mainWin.OPT_IN_BASIC_RUM = function() { - var attrs = getCookieAttrs(); - document.cookie = 'BRUM_CONSENT="opted-in"; path=/; max-age=31536000' + attrs.domain + attrs.secure + '; SameSite=Strict'; // 1 year expiry + // Callback function to opt-in to Boomerang tracking. + mainWin.OPT_IN_BASICRUM_LOADER_WRAPPER = function() { loadBoomr(mainWin); }; - - // Callback function to opt-out of Boomerang tracking - mainWin.OPT_OUT_BASIC_RUM = function() { - var attrs = getCookieAttrs(); - document.cookie = 'BRUM_CONSENT="opted-out"; path=/; max-age=31536000' + attrs.domain + attrs.secure + '; SameSite=Strict'; // 1 year expiry - // If Boomerang is loaded, disable it and remove its cookies + // Consent wrapper opt-out callback: disable collection and remove cookies. + mainWin.OPT_OUT_BASICRUM_LOADER_WRAPPER = function() { + // Neutralize the inline configuration only after an opt-in has already + // started injecting Boomerang on this page: a script that is still + // downloading when consent is withdrawn must not initialize when it + // arrives, because the bundle only calls BOOMR.init() while + // basicRumBoomerangConfig is truthy. A deny that happens before any + // opt-in must keep the configuration - fail-closed adapters report deny + // before the visitor decides, and a later allow on the same page must + // still initialize. After injection, re-granting requires a reload, + // matching the documented consent-loader behavior. + if (mainWin.BOOMR && mainWin.BOOMR.snippetExecuted) { + mainWin.basicRumBoomerangConfig = null; + mainWin.basicRumConsentWithdrawn = true; + } + if (mainWin.BOOMR) { + var waitPlugin = mainWin.BOOMR.plugins && mainWin.BOOMR.plugins.WaitAfterOnload; + if (waitPlugin && waitPlugin.timer !== null) { + mainWin.clearTimeout(waitPlugin.timer); + waitPlugin.timer = null; + } + if (typeof mainWin.BOOMR.disable === "function") { mainWin.BOOMR.disable(); } - // Remove Boomerang RT (Round Trip) and BA (Bandwidth) cookies using Boomerang's utility if (mainWin.BOOMR.utils && typeof mainWin.BOOMR.utils.removeCookie === "function") { mainWin.BOOMR.utils.removeCookie("RT"); mainWin.BOOMR.utils.removeCookie("BA"); + mainWin.BOOMR.utils.removeCookie("BRUM_CONSENT"); + mainWin.BOOMR.utils.removeCookie("BOOMR_CONSENT"); } } + + removeCookie("RT"); + removeCookie("BA"); + removeCookie("BRUM_CONSENT"); + removeCookie("BOOMR_CONSENT"); }; - - // Check if already opted-in - if (document.cookie.indexOf('BRUM_CONSENT="opted-in"') !== -1) { - loadBoomr(mainWin); - } -})(window) \ No newline at end of file + + // Backward-compatible aliases used by earlier Magento 1 integrations. + mainWin.OPT_IN_BASIC_RUM = mainWin.OPT_IN_BASICRUM_LOADER_WRAPPER; + mainWin.OPT_OUT_BASIC_RUM = mainWin.OPT_OUT_BASICRUM_LOADER_WRAPPER; +})(window); diff --git a/js/basicrum/loaders/consent-boomerang-loader-v1-15.min.js b/js/basicrum/loaders/consent-boomerang-loader-v1-15.min.js index e557c05..736b14d 100644 --- a/js/basicrum/loaders/consent-boomerang-loader-v1-15.min.js +++ b/js/basicrum/loaders/consent-boomerang-loader-v1-15.min.js @@ -1 +1 @@ -(t=>{function n(a){if(!a.BOOMR||!a.BOOMR.version&&!a.BOOMR.snippetExecuted){a.BOOMR=a.BOOMR||{};if(Object.prototype.hasOwnProperty.call(a.BOOMR,"url")&&a.BOOMR.url){a.BOOMR.snippetStart=(new Date).getTime();a.BOOMR.snippetExecuted=!0;a.BOOMR.snippetVersion=15;var r=(document.currentScript||document.getElementsByTagName("script")[0]).parentNode,c=!1,e=document.createElement("link");if(e.relList&&"function"==typeof e.relList.supports&&e.relList.supports("preload")&&"as"in e){a.BOOMR.snippetMethod="p";e.href=a.BOOMR.url;e.rel="preload";e.as="script";e.addEventListener("load",function(){if(!c){var e=document.createElement("script");e.id="boomr-scr-as";e.src=a.BOOMR.url;e.async=!0;r.appendChild(e);c=!0}});e.addEventListener("error",function(){t(!0)});setTimeout(function(){c||t(!0)},3e3);BOOMR_lstart=(new Date).getTime();r.appendChild(e)}else t(!1);a.addEventListener?a.addEventListener("load",n,!1):a.attachEvent&&a.attachEvent("onload",n)}}function t(t){c=!0;var e,n,o=document,i=a;a.BOOMR.snippetMethod=t?"if":"i";e=function(e,t){var n=o.createElement("script");n.id=t||"boomr-if-as";n.src=a.BOOMR.url;BOOMR_lstart=(new Date).getTime();(e=e||o.body).appendChild(n)};if(!a.addEventListener&&a.attachEvent&&navigator.userAgent.match(/MSIE [678]\./)){a.BOOMR.snippetMethod="s";e(r,"boomr-async")}else{(t=document.createElement("IFRAME")).src="about:blank";t.title="";t.role="presentation";t.loading="eager";(n=(t.frameElement||t).style).width=0;n.height=0;n.border=0;n.display="none";r.appendChild(t);try{i=t.contentWindow;o=i.document.open()}catch(e){n=document.domain;t.src="javascript:var d=document.open();d.domain='"+n+"';void 0;";i=t.contentWindow;o=i.document.open()}i._boomrl=function(){e()};i.addEventListener?i.addEventListener("load",i._boomrl,!1):i.attachEvent&&i.attachEvent("onload",i._boomrl);o.close()}}function n(e){a.BOOMR_onload=e&&e.timeStamp||(new Date).getTime()}}function o(){var e=t.location&&t.location.hostname;return{secure:t.location&&"https:"===t.location.protocol?"; Secure":"",domain:e?"; domain="+e:""}}t.OPT_IN_BASIC_RUM=function(){var e=o();document.cookie='BRUM_CONSENT="opted-in"; path=/; max-age=31536000'+e.domain+e.secure+"; SameSite=Strict";n(t)};t.OPT_OUT_BASIC_RUM=function(){var e=o();document.cookie='BRUM_CONSENT="opted-out"; path=/; max-age=31536000'+e.domain+e.secure+"; SameSite=Strict";if(t.BOOMR){"function"==typeof t.BOOMR.disable&&t.BOOMR.disable();if(t.BOOMR.utils&&"function"==typeof t.BOOMR.utils.removeCookie){t.BOOMR.utils.removeCookie("RT");t.BOOMR.utils.removeCookie("BA")}}};-1!==document.cookie.indexOf('BRUM_CONSENT="opted-in"')&&n(t)})(window); \ No newline at end of file +(function(r){function e(O){if(O.BOOMR&&(O.BOOMR.version||O.BOOMR.snippetExecuted)){return}O.BOOMR=O.BOOMR||{};if(!Object.prototype.hasOwnProperty.call(O.BOOMR,"url")||!O.BOOMR.url){return}O.BOOMR.snippetStart=(new Date).getTime();O.BOOMR.snippetExecuted=true;O.BOOMR.snippetVersion=15;var e=document.currentScript||document.getElementsByTagName("script")[0],s=e.parentNode,l=false,t=3e3;function n(){if(l){return}var e=document.createElement("script");e.id="boomr-scr-as";e.src=O.BOOMR.url;e.async=true;s.appendChild(e);l=true}function i(e){l=true;var t,i=document,n,o,r,a=O;O.BOOMR.snippetMethod=e?"if":"i";n=function(e,t){var n=i.createElement("script");n.id=t||"boomr-if-as";n.src=O.BOOMR.url;BOOMR_lstart=(new Date).getTime();e=e||i.body;e.appendChild(n)};if(!O.addEventListener&&O.attachEvent&&navigator.userAgent.match(/MSIE [678]\./)){O.BOOMR.snippetMethod="s";n(s,"boomr-async");return}o=document.createElement("IFRAME");o.src="about:blank";o.title="";o.role="presentation";o.loading="eager";r=(o.frameElement||o).style;r.width=0;r.height=0;r.border=0;r.display="none";s.appendChild(o);try{a=o.contentWindow;i=a.document.open()}catch(e){t=document.domain;o.src="javascript:var d=document.open();d.domain='"+t+"';void 0;";a=o.contentWindow;i=a.document.open()}a._boomrl=function(){n()};if(a.addEventListener){a.addEventListener("load",a._boomrl,false)}else if(a.attachEvent){a.attachEvent("onload",a._boomrl)}i.close()}var o=document.createElement("link");if(o.relList&&typeof o.relList.supports==="function"&&o.relList.supports("preload")&&"as"in o){O.BOOMR.snippetMethod="p";o.href=O.BOOMR.url;o.rel="preload";o.as="script";o.addEventListener("load",n);o.addEventListener("error",function(){i(true)});setTimeout(function(){if(!l){i(true)}},t);BOOMR_lstart=(new Date).getTime();s.appendChild(o)}else{i(false)}function r(e){O.BOOMR_onload=e&&e.timeStamp||(new Date).getTime()}if(O.addEventListener){O.addEventListener("load",r,false)}else if(O.attachEvent){O.attachEvent("onload",r)}}function t(e){var t=r.location&&r.location.hostname;var n=e+"=; path=/; max-age=0; SameSite=Strict";var i;var o;r.document.cookie=n;if(t){i=t.split(".");for(o=0;o Date: Thu, 17 Sep 2026 15:51:12 +0300 Subject: [PATCH 03/28] test: add automated verification and CI --- .github/workflows/ci.yml | 47 +++++ .gitignore | 3 + LICENSE.md | 357 ++++++++++++++++++++++++++++++++ THIRD-PARTY-NOTICES.txt | 16 ++ package-lock.json | 74 +++++++ package.json | 16 ++ playwright.config.js | 16 ++ tests/check-package.sh | 72 +++++++ tests/js/build-loaders.js | 24 +++ tests/js/check-minified.js | 30 +++ tests/js/loaders.spec.js | 218 +++++++++++++++++++ tests/js/real-boomerang.spec.js | 161 ++++++++++++++ tests/php/bootstrap.php | 305 +++++++++++++++++++++++++++ tests/php/run.php | 275 ++++++++++++++++++++++++ 14 files changed, 1614 insertions(+) create mode 100644 .github/workflows/ci.yml create mode 100644 .gitignore create mode 100644 LICENSE.md create mode 100644 THIRD-PARTY-NOTICES.txt create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 playwright.config.js create mode 100644 tests/check-package.sh create mode 100644 tests/js/build-loaders.js create mode 100644 tests/js/check-minified.js create mode 100644 tests/js/loaders.spec.js create mode 100644 tests/js/real-boomerang.spec.js create mode 100644 tests/php/bootstrap.php create mode 100644 tests/php/run.php diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..4c18822 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,47 @@ +name: CI + +on: + push: + pull_request: + +permissions: + contents: read + +jobs: + php: + name: PHP ${{ matrix.php }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + php: ["7.4", "8.3"] + steps: + - uses: actions/checkout@v4 + - uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + coverage: none + - name: PHP syntax + run: find app tests/php -type f -name '*.php' -print0 | xargs -0 -n1 php -l + - name: PHP configuration and rendering tests + run: php tests/php/run.php + + browser-and-package: + name: Browser and package checks + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 20 + cache: npm + - name: Install JavaScript dependencies + run: npm ci + - name: Install Chromium + run: npx playwright install --with-deps chromium + - name: Browser loader tests + run: npm test + - name: Install XML and archive tools + run: sudo apt-get update && sudo apt-get install -y libxml2-utils zip unzip + - name: XML and package checks + run: bash tests/check-package.sh diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1fa5c52 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +/node_modules/ +/.test-results/ +/playwright-report/ diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..f655681 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,357 @@ +Basicrum - Real User Monitoring for Magento 1 +Copyright (C) 2026 Tsvetan Stoychev and the Basicrum contributors + +This program is free software; you can redistribute it and/or modify it under +the terms of the GNU General Public License as published by the Free Software +Foundation; either version 2 of the License, or (at your option) any later +version. + +This program is distributed in the hope that it will be useful, but WITHOUT ANY +WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A +PARTICULAR PURPOSE. See the GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along with +this program; if not, write to the Free Software Foundation, Inc., 51 Franklin +Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Bundled third-party software keeps its own license. See +THIRD-PARTY-NOTICES.txt. + + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, see . + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Moe Ghoul, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/THIRD-PARTY-NOTICES.txt b/THIRD-PARTY-NOTICES.txt new file mode 100644 index 0000000..990aeb5 --- /dev/null +++ b/THIRD-PARTY-NOTICES.txt @@ -0,0 +1,16 @@ +# Third-Party Notices + +Basicrum-owned code is licensed under the GNU General Public License version 2 or later in `LICENSE.md`. The extension also distributes the following third-party software under its own license. + +## Boomerang 1.815.60 + +- Project: [Akamai Boomerang](https://github.com/akamai/boomerang) +- Bundled file: `js/basicrum/boomerangs/boomerang-1.815.60.cutting-edge.min.js` +- License: BSD License +- License text: `js/basicrum/LICENSE.txt` +- Source: commit `ead2783a33a2ce91205fe34f8fc992433faba9a2` in the `master` branch of [github.com/basicrum/boomerang](https://github.com/basicrum/boomerang), a fork of upstream [github.com/akamai/boomerang](https://github.com/akamai/boomerang) +- Reproducible build: Node 12 (`.nvmrc`), `npm ci` against the committed lockfile (uglify-js 3.19.3), then `grunt clean build --build-flavor=cutting-edge --build-number=815` reproduces the bundled file byte for byte (SHA-256 `90e8a1c85949b10d43e441efc3f0545f95e4384e26ee3042344a8b2b4110589c`) +- Version banner note: the banner inside the bundled file stamps the parent commit `564759ed70de7801bb64de5e2025fb6ac049ff5f` because the final source change was uncommitted when the shipped file was generated; the code content matches `ead2783a` exactly +- Fork changes vs upstream: maintained commits that remove Long Tasks monitoring, remove the deprecated FID metric and rework Time to First Interaction, drop unused utility functions, and add the Basicrum configuration bootstrap + +The Boomerang copyright notice and license remain applicable to the bundled Boomerang file. Basicrum does not relicense that file under the Basicrum GNU General Public License. diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..de9e9a9 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,74 @@ +{ + "name": "basicrum-magento-1-tests", + "version": "1.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "basicrum-magento-1-tests", + "version": "1.1.0", + "devDependencies": { + "@playwright/test": "1.63.0", + "uglify-js": "3.19.3" + } + }, + "node_modules/@playwright/test": { + "version": "1.63.0", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.63.0.tgz", + "integrity": "sha512-oxMK4vllB9RK5NQ2l1pq1IfOf2AvnEuj/vYGDj0H2nMtmtZpKtCwt/l00GEO6xjGfpBNAvjovvYdCm50dRQkpQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright": "1.63.0" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/playwright": { + "version": "1.63.0", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.63.0.tgz", + "integrity": "sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.63.0" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/playwright-core": { + "version": "1.63.0", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz", + "integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/uglify-js": { + "version": "3.19.3", + "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.19.3.tgz", + "integrity": "sha512-v3Xu+yuwBXisp6QYTcH4UbH+xYJXqnq2m/LtQVWKWzYc1iehYnLixoQDN9FH6/j9/oybfd6W9Ghwkl8+UMKTKQ==", + "dev": true, + "license": "BSD-2-Clause", + "bin": { + "uglifyjs": "bin/uglifyjs" + }, + "engines": { + "node": ">=0.8.0" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..589deb0 --- /dev/null +++ b/package.json @@ -0,0 +1,16 @@ +{ + "name": "basicrum-magento-1-tests", + "version": "1.1.0", + "private": true, + "description": "Automated verification for the Basicrum Magento 1 extension", + "scripts": { + "build:consent-loader": "node tests/js/build-loaders.js", + "check:minified": "node tests/js/check-minified.js", + "test:browser": "playwright test", + "test": "npm run check:minified && npm run test:browser" + }, + "devDependencies": { + "@playwright/test": "1.63.0", + "uglify-js": "3.19.3" + } +} diff --git a/playwright.config.js b/playwright.config.js new file mode 100644 index 0000000..3207440 --- /dev/null +++ b/playwright.config.js @@ -0,0 +1,16 @@ +const { defineConfig } = require("@playwright/test"); + +module.exports = defineConfig({ + testDir: "./tests/js", + testMatch: "**/*.spec.js", + timeout: 15000, + fullyParallel: true, + forbidOnly: Boolean(process.env.CI), + retries: process.env.CI ? 1 : 0, + reporter: "line", + outputDir: ".test-results/playwright", + use: { + browserName: "chromium", + headless: true + } +}); diff --git a/tests/check-package.sh b/tests/check-package.sh new file mode 100644 index 0000000..0460fb1 --- /dev/null +++ b/tests/check-package.sh @@ -0,0 +1,72 @@ +#!/usr/bin/env bash +set -euo pipefail + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$repo_root" + +while IFS= read -r xml_file; do + xmllint --noout "$xml_file" +done < <(find app -type f -name '*.xml' -print | sort) + +module_version="$(xmllint --xpath 'string(/config/modules/BasicRum_Analytics/version)' app/code/community/BasicRum/Analytics/etc/config.xml)" +privacy_default="$(xmllint --xpath 'string(/config/default/basicrum_analytics/privacy/opt_in_required)' app/code/community/BasicRum/Analytics/etc/config.xml)" + +if [[ "$module_version" != "1.1.0" || "$privacy_default" != "1" ]]; then + echo "Unexpected module version or privacy default: version=$module_version opt_in_required=$privacy_default" >&2 + exit 1 +fi + +package_files=(README.md LICENSE.md THIRD-PARTY-NOTICES.txt modman package.json) + +while read -r source_path destination_path extra; do + if [[ -z "${source_path:-}" || "${source_path:0:1}" == "#" ]]; then + continue + fi + + if [[ -n "${extra:-}" ]]; then + echo "Invalid modman row: $source_path $destination_path $extra" >&2 + exit 1 + fi + + if [[ ! -f "$source_path" ]]; then + echo "modman source does not exist: $source_path" >&2 + exit 1 + fi + + package_files+=("$source_path") +done < modman + +while IFS= read -r runtime_file; do + if ! awk -v file="$runtime_file" '$1 == file { found = 1 } END { exit found ? 0 : 1 }' modman; then + echo "Runtime file is missing from modman: $runtime_file" >&2 + exit 1 + fi +done < <(find app js -type f -print | sort) + +expected_boomerang_sha="90e8a1c85949b10d43e441efc3f0545f95e4384e26ee3042344a8b2b4110589c" +if command -v shasum >/dev/null 2>&1; then + actual_boomerang_sha="$(shasum -a 256 js/basicrum/boomerangs/boomerang-1.815.60.cutting-edge.min.js | awk '{print $1}')" +else + actual_boomerang_sha="$(sha256sum js/basicrum/boomerangs/boomerang-1.815.60.cutting-edge.min.js | awk '{print $1}')" +fi + +if [[ "$actual_boomerang_sha" != "$expected_boomerang_sha" ]]; then + echo "Bundled Boomerang checksum changed: $actual_boomerang_sha" >&2 + exit 1 +fi + +if grep -R --line-number '' app/code/community/BasicRum/Analytics/etc; then + echo "Legacy wait-after-onload default key found" >&2 + exit 1 +fi + +package_tmp_dir="$(mktemp -d -t basicrum-magento-1.XXXXXX)" +archive_path="$package_tmp_dir/basicrum-magento-1.zip" +trap 'rm -f "$archive_path"; rmdir "$package_tmp_dir"' EXIT +zip -q "$archive_path" "${package_files[@]}" +unzip -tqq "$archive_path" +diff -u \ + <(printf '%s\n' "${package_files[@]}" | sort -u) \ + <(zipinfo -1 "$archive_path" | sort -u) + +echo "XML, modman, provenance, and package archive checks passed." diff --git a/tests/js/build-loaders.js b/tests/js/build-loaders.js new file mode 100644 index 0000000..0aed773 --- /dev/null +++ b/tests/js/build-loaders.js @@ -0,0 +1,24 @@ +const fs = require("node:fs"); +const path = require("node:path"); +const UglifyJS = require("uglify-js"); + +const root = path.resolve(__dirname, "../.."); +const loaders = ["consent-boomerang-loader-v1-15"]; + +for (const loader of loaders) { + const sourcePath = path.join(root, "js/basicrum/loaders", `${loader}.js`); + const outputPath = path.join(root, "js/basicrum/loaders", `${loader}.min.js`); + const result = UglifyJS.minify(fs.readFileSync(sourcePath, "utf8"), { + compress: false, + mangle: true, + output: { + comments: /^!/ + } + }); + + if (result.error) { + throw result.error; + } + + fs.writeFileSync(outputPath, result.code); +} diff --git a/tests/js/check-minified.js b/tests/js/check-minified.js new file mode 100644 index 0000000..da531d1 --- /dev/null +++ b/tests/js/check-minified.js @@ -0,0 +1,30 @@ +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const path = require("node:path"); +const UglifyJS = require("uglify-js"); + +const root = path.resolve(__dirname, "../.."); + +for (const loader of ["consent-boomerang-loader-v1-15"]) { + const source = fs.readFileSync( + path.join(root, "js/basicrum/loaders", `${loader}.js`), + "utf8" + ); + const actual = fs.readFileSync( + path.join(root, "js/basicrum/loaders", `${loader}.min.js`), + "utf8" + ); + const result = UglifyJS.minify(source, { + compress: false, + mangle: true, + output: { comments: /^!/ } + }); + + if (result.error) { + throw result.error; + } + + assert.equal(actual, result.code, `${loader}.min.js must be regenerated from source`); +} + +console.log("Minified loader checks passed."); diff --git a/tests/js/loaders.spec.js b/tests/js/loaders.spec.js new file mode 100644 index 0000000..9debede --- /dev/null +++ b/tests/js/loaders.spec.js @@ -0,0 +1,218 @@ +const path = require("node:path"); +const { test, expect } = require("@playwright/test"); + +const root = path.resolve(__dirname, "../.."); +const shopUrl = "https://shop.example.test/"; +const boomerangUrl = "https://assets.example.test/boomerang.js"; +const bundleStub = ` +window.__bundleExecutions = (window.__bundleExecutions || 0) + 1; +window.BOOMR = window.BOOMR || {}; +window.BOOMR.version = "test"; +window.BOOMR.window = window; +window.BOOMR.init = function(config) { + window.__initCalls = (window.__initCalls || 0) + 1; + window.__lastConfig = config; +}; +window.BOOMR.disable = function() { + window.__disableCalls = (window.__disableCalls || 0) + 1; +}; +window.BOOMR.utils = { + removeCookie: function(name) { + window.__utilityCookieRemovals = window.__utilityCookieRemovals || []; + window.__utilityCookieRemovals.push(name); + } +}; +window.basicRumInitConfig = window.basicRumBoomerangConfig; +if (window.basicRumInitConfig) { + window.BOOMR.init(window.basicRumInitConfig); +} +`; + +function loaderPath(file) { + return path.join(root, "js/basicrum/loaders", file); +} + +async function preparePage(page, options = {}) { + let releaseDownload; + let markDownloadStarted; + const downloadGate = options.holdDownload + ? new Promise((resolve) => { releaseDownload = resolve; }) + : Promise.resolve(); + const downloadStarted = new Promise((resolve) => { markDownloadStarted = resolve; }); + + await page.route(shopUrl, (route) => route.fulfill({ + contentType: "text/html", + body: "" + })); + await page.route(boomerangUrl, async (route) => { + markDownloadStarted(); + await downloadGate; + await route.fulfill({ contentType: "application/javascript", body: bundleStub }); + }); + + if (options.cookies) { + await page.context().addCookies(options.cookies.map((name) => ({ + name, + value: "legacy", + domain: "shop.example.test", + path: "/" + }))); + } + + await page.goto(shopUrl); + await page.evaluate((url) => { + window.BOOMR = { url }; + window.basicRumBoomerangConfig = { beacon_url: "https://collector.example.test/beacon" }; + window.__initCalls = 0; + window.__bundleExecutions = 0; + window.__disableCalls = 0; + window.__utilityCookieRemovals = []; + }, boomerangUrl); + + return { + downloadStarted, + releaseDownload: () => releaseDownload && releaseDownload() + }; +} + +for (const standardLoader of ["boomerang-loader-v15.js", "boomerang-loader-v15.min.js"]) { + test(`immediate loader executes Boomerang once: ${standardLoader}`, async ({ page }) => { + await preparePage(page); + await page.addScriptTag({ path: loaderPath(standardLoader) }); + await page.waitForFunction(() => window.__initCalls === 1); + + await page.addScriptTag({ path: loaderPath(standardLoader) }); + await page.waitForTimeout(100); + + await expect.poll(() => page.evaluate(() => ({ + initCalls: window.__initCalls, + executions: window.__bundleExecutions + }))).toEqual({ initCalls: 1, executions: 1 }); + }); +} + +for (const consentLoader of [ + "consent-boomerang-loader-v1-15.js", + "consent-boomerang-loader-v1-15.min.js" +]) { + test.describe(`consent wrapper: ${consentLoader}`, () => { + test("stays inert despite a legacy allow cookie", async ({ page }) => { + await preparePage(page, { cookies: ["BRUM_CONSENT"] }); + await page.addScriptTag({ path: loaderPath(consentLoader) }); + await page.waitForTimeout(150); + + expect(await page.evaluate(() => ({ + initCalls: window.__initCalls, + executions: window.__bundleExecutions, + canonicalIn: typeof window.OPT_IN_BASICRUM_LOADER_WRAPPER, + canonicalOut: typeof window.OPT_OUT_BASICRUM_LOADER_WRAPPER, + legacyIn: typeof window.OPT_IN_BASIC_RUM, + legacyOut: typeof window.OPT_OUT_BASIC_RUM + }))).toEqual({ + initCalls: 0, + executions: 0, + canonicalIn: "function", + canonicalOut: "function", + legacyIn: "function", + legacyOut: "function" + }); + }); + + test("repeated opt-in loads only once and persists no consent cookie", async ({ page }) => { + await preparePage(page); + await page.addScriptTag({ path: loaderPath(consentLoader) }); + await page.evaluate(() => { + window.OPT_IN_BASICRUM_LOADER_WRAPPER(); + window.OPT_IN_BASIC_RUM(); + }); + await page.waitForFunction(() => window.__initCalls === 1); + await page.waitForTimeout(100); + + expect(await page.evaluate(() => ({ + initCalls: window.__initCalls, + executions: window.__bundleExecutions, + cookies: document.cookie + }))).toEqual({ initCalls: 1, executions: 1, cookies: "" }); + }); + + test("opt-out before loading clears legacy cookies and still permits a later allow", async ({ page }) => { + const cookieNames = ["RT", "BA", "BRUM_CONSENT", "BOOMR_CONSENT"]; + await preparePage(page, { cookies: cookieNames }); + await page.addScriptTag({ path: loaderPath(consentLoader) }); + await page.evaluate(() => window.OPT_OUT_BASIC_RUM()); + + expect(await page.evaluate(() => ({ + cookies: document.cookie, + configPresent: Boolean(window.basicRumBoomerangConfig), + executions: window.__bundleExecutions + }))).toEqual({ cookies: "", configPresent: true, executions: 0 }); + + await page.evaluate(() => window.OPT_IN_BASICRUM_LOADER_WRAPPER()); + await page.waitForFunction(() => window.__initCalls === 1); + expect(await page.evaluate(() => window.__bundleExecutions)).toBe(1); + }); + + test("opt-out removes host-only and parent-domain cookies", async ({ context, page }) => { + const cookieNames = ["RT", "BA", "BRUM_CONSENT", "BOOMR_CONSENT"]; + await preparePage(page, { cookies: cookieNames }); + await context.addCookies(cookieNames.map((name) => ({ + name, + value: "parent", + domain: ".example.test", + path: "/", + secure: true + }))); + await page.addScriptTag({ path: loaderPath(consentLoader) }); + await page.evaluate(() => window.OPT_OUT_BASICRUM_LOADER_WRAPPER()); + + const remaining = (await context.cookies(shopUrl)) + .filter((cookie) => cookieNames.includes(cookie.name)); + expect(remaining).toEqual([]); + }); + + test("opt-out during download prevents initialization and requires reload to re-grant", async ({ page }) => { + const gate = await preparePage(page, { holdDownload: true }); + await page.addScriptTag({ path: loaderPath(consentLoader) }); + await page.evaluate(() => window.OPT_IN_BASICRUM_LOADER_WRAPPER()); + await gate.downloadStarted; + await page.evaluate(() => window.OPT_OUT_BASICRUM_LOADER_WRAPPER()); + gate.releaseDownload(); + await page.waitForFunction(() => window.__bundleExecutions === 1); + + await page.evaluate(() => window.OPT_IN_BASIC_RUM()); + await page.waitForTimeout(100); + + expect(await page.evaluate(() => ({ + initCalls: window.__initCalls, + executions: window.__bundleExecutions, + config: window.basicRumBoomerangConfig + }))).toEqual({ initCalls: 0, executions: 1, config: null }); + }); + + test("opt-out after initialization disables collection and blocks same-page re-grant", async ({ page }) => { + const cookieNames = ["RT", "BA", "BRUM_CONSENT", "BOOMR_CONSENT"]; + await preparePage(page, { cookies: cookieNames }); + await page.addScriptTag({ path: loaderPath(consentLoader) }); + await page.evaluate(() => window.OPT_IN_BASICRUM_LOADER_WRAPPER()); + await page.waitForFunction(() => window.__initCalls === 1); + + await page.evaluate(() => window.OPT_OUT_BASICRUM_LOADER_WRAPPER()); + await page.evaluate(() => window.OPT_IN_BASICRUM_LOADER_WRAPPER()); + await page.waitForTimeout(100); + + expect(await page.evaluate(() => ({ + initCalls: window.__initCalls, + executions: window.__bundleExecutions, + disableCalls: window.__disableCalls, + cookies: document.cookie, + removals: window.__utilityCookieRemovals.sort() + }))).toEqual({ + initCalls: 1, + executions: 1, + disableCalls: 1, + cookies: "", + removals: ["BA", "BOOMR_CONSENT", "BRUM_CONSENT", "RT"] + }); + }); + }); +} diff --git a/tests/js/real-boomerang.spec.js b/tests/js/real-boomerang.spec.js new file mode 100644 index 0000000..5a53f53 --- /dev/null +++ b/tests/js/real-boomerang.spec.js @@ -0,0 +1,161 @@ +const fs = require("node:fs"); +const path = require("node:path"); +const { test, expect } = require("@playwright/test"); + +const root = path.resolve(__dirname, "../.."); +const shopUrl = "https://shop.example.test/"; +const boomerangUrl = "https://assets.example.test/boomerang.js"; +const beaconUrl = "https://collector.example.test/beacon"; +const realBoomerang = fs.readFileSync( + path.join(root, "js/basicrum/boomerangs/boomerang-1.815.60.cutting-edge.min.js"), + "utf8" +); +const silenceMs = 1500; + +function loaderPath(file) { + return path.join(root, "js/basicrum/loaders", file); +} + +async function prepareRealPage(page) { + let releaseDownload; + let markDownloadStarted; + let beaconRequests = 0; + const downloadGate = new Promise((resolve) => { releaseDownload = resolve; }); + const downloadStarted = new Promise((resolve) => { markDownloadStarted = resolve; }); + + await page.route(shopUrl, (route) => route.fulfill({ + contentType: "text/html", + body: "" + })); + await page.route(`${beaconUrl}*`, (route) => { + beaconRequests += 1; + return route.fulfill({ + status: 204, + headers: { "access-control-allow-origin": "*" }, + body: "" + }); + }); + await page.route(boomerangUrl, async (route) => { + markDownloadStarted(); + await downloadGate; + await route.fulfill({ + status: 200, + contentType: "application/javascript; charset=utf-8", + body: realBoomerang + }); + }); + + await page.goto(shopUrl); + await page.evaluate(({ bundleUrl, collectorUrl }) => { + window.BOOMR = { url: bundleUrl }; + window.basicRumBoomerangConfig = { + beacon_url: collectorUrl, + instrument_xhr: false, + Continuity: { enabled: true }, + secure_cookie: false, + same_site_cookie: "Strict" + }; + }, { bundleUrl: boomerangUrl, collectorUrl: beaconUrl }); + + return { + downloadStarted, + releaseDownload, + beaconRequests: () => beaconRequests + }; +} + +async function waitForRealBoomerang(page) { + await expect.poll( + () => page.evaluate(() => window.BOOMR && window.BOOMR.version) + ).toBe("1.815.60"); +} + +for (const consentLoader of [ + "consent-boomerang-loader-v1-15.js", + "consent-boomerang-loader-v1-15.min.js" +]) { + test.describe(`real Boomerang: ${consentLoader}`, () => { + test("explicit opt-in initializes, sets RT, and sends a beacon", async ({ context, page }) => { + const gate = await prepareRealPage(page); + await page.addScriptTag({ path: loaderPath(consentLoader) }); + + await page.evaluate(() => window.OPT_IN_BASICRUM_LOADER_WRAPPER()); + await gate.downloadStarted; + gate.releaseDownload(); + await waitForRealBoomerang(page); + + await expect.poll(() => gate.beaconRequests(), { timeout: 10000 }).toBeGreaterThan(0); + const cookies = await context.cookies(shopUrl); + expect(cookies.some((cookie) => cookie.name === "RT")).toBe(true); + }); + + test("withdrawal during the real download leaves the arrived bundle inert", async ({ context, page }) => { + const gate = await prepareRealPage(page); + await page.addScriptTag({ path: loaderPath(consentLoader) }); + + await page.evaluate(() => window.OPT_IN_BASICRUM_LOADER_WRAPPER()); + await gate.downloadStarted; + await page.evaluate(() => window.OPT_OUT_BASICRUM_LOADER_WRAPPER()); + gate.releaseDownload(); + await waitForRealBoomerang(page); + await page.waitForTimeout(silenceMs); + + expect(gate.beaconRequests()).toBe(0); + const cookies = await context.cookies(shopUrl); + expect(cookies.some((cookie) => ["RT", "BA"].includes(cookie.name))).toBe(false); + expect(await page.evaluate(() => window.basicRumInitConfig || null)).toBe(null); + }); + + test("withdrawal after initialization cancels a pending Wait After Onload beacon", async ({ context, page }) => { + const gate = await prepareRealPage(page); + await page.addScriptTag({ path: loaderPath(consentLoader) }); + await page.evaluate(() => { + const boomerang = window.BOOMR; + boomerang.plugins = boomerang.plugins || {}; + boomerang.plugins.WaitAfterOnload = { + complete: false, + timer: null, + init() { + boomerang.subscribe("page_ready", function() { + this.timer = window.setTimeout(() => { + this.complete = true; + boomerang.sendBeacon(); + }, 500); + window.__basicRumWaitScheduled = true; + }, {}, this); + }, + is_complete() { + return this.complete; + } + }; + }); + + await page.evaluate(() => window.OPT_IN_BASICRUM_LOADER_WRAPPER()); + await gate.downloadStarted; + gate.releaseDownload(); + await waitForRealBoomerang(page); + await page.waitForFunction(() => window.__basicRumWaitScheduled === true); + await page.evaluate(() => window.OPT_OUT_BASICRUM_LOADER_WRAPPER()); + await page.waitForTimeout(1000); + + expect(gate.beaconRequests()).toBe(0); + const cookies = await context.cookies(shopUrl); + expect(cookies.some((cookie) => ["RT", "BA"].includes(cookie.name))).toBe(false); + }); + + test("a deny before loading does not block a later same-page allow", async ({ context, page }) => { + const gate = await prepareRealPage(page); + await page.addScriptTag({ path: loaderPath(consentLoader) }); + + await page.evaluate(() => window.OPT_OUT_BASICRUM_LOADER_WRAPPER()); + await page.evaluate(() => window.OPT_IN_BASICRUM_LOADER_WRAPPER()); + await gate.downloadStarted; + gate.releaseDownload(); + await waitForRealBoomerang(page); + + await expect.poll(() => gate.beaconRequests(), { timeout: 10000 }).toBeGreaterThan(0); + const cookies = await context.cookies(shopUrl); + expect(cookies.some((cookie) => cookie.name === "RT")).toBe(true); + }); + }); +} diff --git a/tests/php/bootstrap.php b/tests/php/bootstrap.php new file mode 100644 index 0000000..dade091 --- /dev/null +++ b/tests/php/bootstrap.php @@ -0,0 +1,305 @@ +value = $value; + return $this; + } + + public function getValue() + { + return $this->value; + } + + protected function _beforeSave() + { + return $this; + } +} + +class Basicrum_Test_Select +{ + public $table; + public $columns; + public $where = array(); + public $limit; + + public function from($table, $columns) + { + $this->table = $table; + $this->columns = $columns; + return $this; + } + + public function where($condition, $value) + { + $this->where[] = array($condition, $value); + return $this; + } + + public function limit($count) + { + $this->limit = $count; + return $this; + } +} + +class Basicrum_Test_Connection +{ + public $fetchResults; + public $selects = array(); + + public function __construct(array $fetchResults) + { + $this->fetchResults = $fetchResults; + } + + public function select() + { + $select = new Basicrum_Test_Select(); + $this->selects[] = $select; + return $select; + } + + public function fetchOne($select) + { + if (!in_array($select, $this->selects, true)) { + throw new RuntimeException('Installer queried an unknown select object'); + } + + if (!$this->fetchResults) { + throw new RuntimeException('Installer made more queries than expected'); + } + + return array_shift($this->fetchResults); + } +} + +class Basicrum_Test_Config +{ + public $saved = array(); + + public function saveConfig($path, $value, $scope, $scopeId) + { + $this->saved[] = array($path, $value, $scope, $scopeId); + return $this; + } +} + +class Basicrum_Test_Setup +{ + public $connection; + public $started = 0; + public $ended = 0; + public $requestedTables = array(); + + public function __construct(array $fetchResults) + { + $this->connection = new Basicrum_Test_Connection($fetchResults); + } + + public function startSetup() + { + $this->started += 1; + return $this; + } + + public function endSetup() + { + $this->ended += 1; + return $this; + } + + public function getConnection() + { + return $this->connection; + } + + public function getTable($alias) + { + $this->requestedTables[] = $alias; + return 'prefix_core_config_data'; + } + + public function runInstaller($path) + { + include $path; + } +} + +class Basicrum_Test_Request +{ + public $secure = false; + + public function isSecure() + { + return $this->secure; + } +} + +class Basicrum_Test_App +{ + public $request; + + public function __construct() + { + $this->request = new Basicrum_Test_Request(); + } + + public function getRequest() + { + return $this->request; + } +} + +class Basicrum_Test_PageTypeHelper +{ + public $pageType = 'Product'; + + public function getPageType() + { + return $this->pageType; + } +} + +class Mage +{ + public static $storeConfig = array(); + public static $helpers = array(); + public static $baseUrls = array('js' => 'https://shop.example.test/js/'); + public static $app; + public static $configObject; + + public static function getStoreConfig($path) + { + return array_key_exists($path, self::$storeConfig) ? self::$storeConfig[$path] : null; + } + + public static function getStoreConfigFlag($path) + { + $value = self::getStoreConfig($path); + return $value === true || $value === 1 || $value === '1'; + } + + public static function helper($alias) + { + if (!isset(self::$helpers[$alias])) { + throw new RuntimeException('Missing test helper: ' . $alias); + } + + return self::$helpers[$alias]; + } + + public static function getBaseUrl($type) + { + return self::$baseUrls[$type]; + } + + public static function app() + { + return self::$app; + } + + public static function getConfig() + { + if (!self::$configObject) { + throw new RuntimeException('Missing test configuration object'); + } + + return self::$configObject; + } + + public static function throwException($message) + { + throw new Mage_Core_Exception($message); + } +} + +function basicrum_test_reset(array $overrides = array()) +{ + Mage::$storeConfig = array_merge(array( + 'basicrum_analytics/general/enabled' => '1', + 'basicrum_analytics/general/beacon_endpoint' => 'https://collector.example.test/beacon', + 'basicrum_analytics/general/brum_site_id' => 'e926c1a2-7e33-4f54-90d0-e6e31f3ad43d', + 'basicrum_analytics/privacy/opt_in_required' => '0', + 'basicrum_analytics/wait_after_onload/enabled' => '0', + 'basicrum_analytics/wait_after_onload/wait_ms' => '0', + 'basicrum_analytics/developer/use_unminified_loaders' => '0', + ), $overrides); + Mage::$app = new Basicrum_Test_App(); + Mage::$configObject = new Basicrum_Test_Config(); + Mage::$baseUrls = array('js' => 'https://shop.example.test/js/'); + + $helper = new BasicRum_Analytics_Helper_Data(); + $pageType = new Basicrum_Test_PageTypeHelper(); + Mage::$helpers = array( + 'basicrum_analytics' => $helper, + 'basicrum_analytics/pageTypeDetector' => $pageType, + ); + + return array($helper, $pageType); +} + +function basicrum_assert_same($expected, $actual, $message) +{ + if ($expected !== $actual) { + throw new RuntimeException( + $message . "\nExpected: " . var_export($expected, true) . "\nActual: " . var_export($actual, true) + ); + } +} + +function basicrum_assert_true($actual, $message) +{ + basicrum_assert_same(true, (bool) $actual, $message); +} + +function basicrum_assert_contains($needle, $haystack, $message) +{ + if (strpos($haystack, $needle) === false) { + throw new RuntimeException($message . "\nMissing: " . $needle); + } +} + +function basicrum_assert_not_contains($needle, $haystack, $message) +{ + if (strpos($haystack, $needle) !== false) { + throw new RuntimeException($message . "\nUnexpected: " . $needle); + } +} + +function basicrum_assert_throws(callable $callback, $expectedClass, $message) +{ + try { + $callback(); + } catch (Throwable $exception) { + if ($exception instanceof $expectedClass) { + return; + } + + throw new RuntimeException($message . ': received ' . get_class($exception)); + } + + throw new RuntimeException($message . ': no exception was thrown'); +} diff --git a/tests/php/run.php b/tests/php/run.php new file mode 100644 index 0000000..22121d5 --- /dev/null +++ b/tests/php/run.php @@ -0,0 +1,275 @@ +_beforeSave(); + } +} + +class Basicrum_Test_BeaconBackend extends BasicRum_Analytics_Model_System_Config_Backend_BeaconEndpoint +{ + public function validate() + { + return $this->_beforeSave(); + } +} + +$tests = array(); + +$tests['runtime validation follows the backend contract'] = function () { + basicrum_assert_true( + BasicRum_Analytics_Helper_Data::isValidBrumSiteId('550e8400-e29b-41d4-a716-446655440000'), + 'UUID v4 must be accepted' + ); + basicrum_assert_same( + false, + BasicRum_Analytics_Helper_Data::isValidBrumSiteId('550e8400-e29b-11d4-a716-446655440000'), + 'non-v4 UUID must be rejected' + ); + basicrum_assert_true( + BasicRum_Analytics_Helper_Data::isValidBeaconEndpoint('https://collector.example.test/beacon?key=value'), + 'HTTPS Beacon URL must be accepted' + ); + basicrum_assert_true( + BasicRum_Analytics_Helper_Data::isValidBeaconEndpoint('http://localhost:8080/beacon'), + 'HTTP Beacon URL must remain available for compatible development setups' + ); + basicrum_assert_same( + false, + BasicRum_Analytics_Helper_Data::isValidBeaconEndpoint('javascript:alert(1)'), + 'executable URL schemes must be rejected' + ); + basicrum_assert_same( + false, + BasicRum_Analytics_Helper_Data::isValidBeaconEndpoint('https:///missing-host'), + 'hostless URLs must be rejected' + ); +}; + +$tests['helper normalizes secure URLs and wait milliseconds'] = function () { + list($helper) = basicrum_test_reset(array( + 'basicrum_analytics/general/beacon_endpoint' => 'http://collector.example.test/beacon', + 'basicrum_analytics/wait_after_onload/wait_ms' => '90000', + )); + Mage::$app->request->secure = true; + + basicrum_assert_same( + 'https://collector.example.test/beacon', + $helper->getBeaconEndpoint(), + 'secure pages must upgrade the Beacon URL' + ); + basicrum_assert_same(30000, $helper->getWaitAfterOnloadMilliseconds(), 'wait value must be capped'); +}; + +$tests['backend models trim and validate configuration'] = function () { + basicrum_test_reset(); + + $siteId = new Basicrum_Test_SiteIdBackend(); + $siteId->setValue(' 550e8400-e29b-41d4-a716-446655440000 ')->validate(); + basicrum_assert_same( + '550e8400-e29b-41d4-a716-446655440000', + $siteId->getValue(), + 'Site ID backend must trim a valid value' + ); + + basicrum_assert_throws(function () { + $model = new Basicrum_Test_SiteIdBackend(); + $model->setValue('550e8400-e29b-11d4-a716-446655440000')->validate(); + }, Mage_Core_Exception::class, 'Site ID backend must reject non-v4 UUIDs'); + + $beacon = new Basicrum_Test_BeaconBackend(); + $beacon->setValue(' https://collector.example.test/beacon ')->validate(); + basicrum_assert_same( + 'https://collector.example.test/beacon', + $beacon->getValue(), + 'Beacon backend must trim a valid URL' + ); + + basicrum_assert_throws(function () { + $model = new Basicrum_Test_BeaconBackend(); + $model->setValue('data:text/javascript,alert(1)')->validate(); + }, Mage_Core_Exception::class, 'Beacon backend must reject non-HTTP schemes'); +}; + +$tests['disabled and incomplete configurations render nothing'] = function () { + $block = new BasicRum_Analytics_Block_Boomerang_Loader(); + + basicrum_test_reset(array('basicrum_analytics/general/enabled' => '0')); + basicrum_assert_same('', $block->getBoomerangSnippet(), 'disabled configuration must emit no scripts'); + + basicrum_test_reset(array('basicrum_analytics/general/beacon_endpoint' => '')); + basicrum_assert_same('', $block->getBoomerangSnippet(), 'missing Beacon URL must emit no scripts'); + + basicrum_test_reset(array('basicrum_analytics/general/beacon_endpoint' => 'javascript:alert(1)')); + basicrum_assert_same('', $block->getBoomerangSnippet(), 'invalid Beacon URL must emit no scripts'); + + basicrum_test_reset(array('basicrum_analytics/general/brum_site_id' => '')); + basicrum_assert_same('', $block->getBoomerangSnippet(), 'missing Site ID must emit no scripts'); + + basicrum_test_reset(array( + 'basicrum_analytics/general/brum_site_id' => '550e8400-e29b-11d4-a716-446655440000', + )); + basicrum_assert_same('', $block->getBoomerangSnippet(), 'invalid Site ID must emit no scripts'); +}; + +$tests['valid immediate and consent configurations select the expected loader'] = function () { + $block = new BasicRum_Analytics_Block_Boomerang_Loader(); + + basicrum_test_reset(); + $immediate = $block->getBoomerangSnippet(); + basicrum_assert_contains('boomerang-loader-v15.min.js', $immediate, 'immediate mode loader is required'); + basicrum_assert_not_contains('consent-boomerang-loader', $immediate, 'immediate mode must not use consent loader'); + basicrum_assert_contains('brum_site_id', $immediate, 'Site ID must be rendered'); + basicrum_assert_contains('beacon_url', $immediate, 'Beacon URL must be rendered'); + + basicrum_test_reset(array( + 'basicrum_analytics/privacy/opt_in_required' => '1', + 'basicrum_analytics/developer/use_unminified_loaders' => '1', + )); + $consent = $block->getBoomerangSnippet(); + basicrum_assert_contains( + 'consent-boomerang-loader-v1-15.js', + $consent, + 'consent-controlled mode must use the wrapper' + ); +}; + +$tests['wait-after-onload rendering is capped and cancellable on consent withdrawal'] = function () { + basicrum_test_reset(array( + 'basicrum_analytics/privacy/opt_in_required' => '1', + 'basicrum_analytics/wait_after_onload/enabled' => '1', + 'basicrum_analytics/wait_after_onload/wait_ms' => '90000', + )); + + $html = (new BasicRum_Analytics_Block_Boomerang_Loader())->getBoomerangSnippet(); + basicrum_assert_contains('timer: null', $html, 'wait plugin must expose its pending timer for opt-out'); + basicrum_assert_contains('this.timer = setTimeout', $html, 'wait plugin must retain its pending timer'); + basicrum_assert_contains( + 'if (w.basicRumConsentWithdrawn)', + $html, + 'wait callback must remain inert after consent withdrawal' + ); + basicrum_assert_contains('}.bind(this), 30000);', $html, 'rendered wait value must be capped at 30 seconds'); + basicrum_assert_not_contains('}.bind(this), 90000);', $html, 'uncapped wait value must not be rendered'); +}; + +$tests['rendered values are JSON serialized for script safety'] = function () { + list($helper, $pageType) = basicrum_test_reset(array( + 'basicrum_analytics/general/beacon_endpoint' => 'https://collector.example.test/beacon?first=1&second=2', + )); + $pageType->pageType = ''; + + $html = (new BasicRum_Analytics_Block_Boomerang_Loader())->getBoomerangSnippet(); + basicrum_assert_not_contains(' diff --git a/docs/admin-ui-parity-checklist.md b/docs/admin-ui-parity-checklist.md index eddc381..a719609 100644 --- a/docs/admin-ui-parity-checklist.md +++ b/docs/admin-ui-parity-checklist.md @@ -55,7 +55,11 @@ Legend: phase. Any adapter must use documented current-page allow and withdrawal signals rather than inferring consent from the presence of a banner or an arbitrary cookie. -- [ ] Improve manual integration usability with focused examples and copy actions. +- [x] Improve manual integration usability with focused examples and copy actions. + - The allow and deny/expiry/withdrawal callbacks are presented separately so + administrators do not accidentally run both decisions as one sequence. + - Each read-only snippet has an accessible copy action with a select-and-copy + fallback when the Clipboard API is unavailable. - [x] Document the canonical WordPress-compatible opt-in and opt-out callback names. - [x] Document the legacy Magento callback aliases as compatibility APIs. - [x] Explain that Basicrum does not persist or infer consent. @@ -121,7 +125,7 @@ Legend: ### P1 — integration parity - [x] Document manual consent integration as the supported Magento 1 strategy. -- [ ] Improve manual integration examples and copy actions. +- [x] Improve manual integration examples and copy actions. - [ ] Resolve Strip Query Strings and HTTP-policy parity. ### Deferred — consent-provider adapters diff --git a/js/basicrum/admin/consent-info.js b/js/basicrum/admin/consent-info.js new file mode 100644 index 0000000..04d5002 --- /dev/null +++ b/js/basicrum/admin/consent-info.js @@ -0,0 +1,92 @@ +(function(document, navigator) { + "use strict"; + + function setStatus(status, message) { + if (!status) { + return; + } + + if (typeof status.textContent !== "undefined") { + status.textContent = message; + } + else { + status.innerText = message; + } + } + + function selectAndCopy(target, status, copiedLabel, fallbackLabel) { + var copied = false; + + target.focus(); + target.select(); + + try { + copied = typeof document.execCommand === "function" && document.execCommand("copy"); + } + catch (error) { + copied = false; + } + + setStatus(status, copied ? copiedLabel : fallbackLabel); + } + + function initialize(button) { + var targetId; + var target; + var status; + var copiedLabel; + var fallbackLabel; + + if (button.getAttribute("data-basicrum-copy-ready") === "true") { + return; + } + + targetId = button.getAttribute("data-basicrum-copy-target"); + target = targetId ? document.getElementById(targetId) : null; + status = button.parentNode.querySelector(".basicrum-copy-status"); + copiedLabel = button.getAttribute("data-copied-label") || "Copied"; + fallbackLabel = button.getAttribute("data-copy-fallback-label") || "Select the snippet and copy it manually."; + + if (!target) { + return; + } + + function copySnippet() { + function reportCopied() { + setStatus(status, copiedLabel); + } + + function copyWithSelection() { + selectAndCopy(target, status, copiedLabel, fallbackLabel); + } + + if (navigator.clipboard && typeof navigator.clipboard.writeText === "function") { + try { + navigator.clipboard.writeText(target.value).then(reportCopied, copyWithSelection); + return; + } + catch (error) { + copyWithSelection(); + return; + } + } + + copyWithSelection(); + } + + button.setAttribute("data-basicrum-copy-ready", "true"); + if (button.addEventListener) { + button.addEventListener("click", copySnippet, false); + } + else if (button.attachEvent) { + button.attachEvent("onclick", copySnippet); + } + } + + var buttons = document.querySelectorAll(".basicrum-copy-consent-snippet"); + var index; + + for (index = 0; index < buttons.length; index++) { + initialize(buttons[index]); + } +})(document, window.navigator); diff --git a/modman b/modman index d4a15ab..041961d 100644 --- a/modman +++ b/modman @@ -27,6 +27,7 @@ app/locale/en_US/BasicRum_Analytics.csv a app/design/frontend/base/default/layout/basicrum_analytics.xml app/design/frontend/base/default/layout/basicrum_analytics.xml js/basicrum/boomerangs/boomerang-1.815.60.cutting-edge.min.js js/basicrum/boomerangs/boomerang-1.815.60.cutting-edge.min.js js/basicrum/LICENSE.txt js/basicrum/LICENSE.txt +js/basicrum/admin/consent-info.js js/basicrum/admin/consent-info.js js/basicrum/loaders/boomerang-loader-v15.js js/basicrum/loaders/boomerang-loader-v15.js js/basicrum/loaders/boomerang-loader-v15.min.js js/basicrum/loaders/boomerang-loader-v15.min.js js/basicrum/loaders/consent-boomerang-loader-v1-15.js js/basicrum/loaders/consent-boomerang-loader-v1-15.js diff --git a/tests/js/admin-consent-info.spec.js b/tests/js/admin-consent-info.spec.js new file mode 100644 index 0000000..a2af9e0 --- /dev/null +++ b/tests/js/admin-consent-info.spec.js @@ -0,0 +1,68 @@ +const path = require("node:path"); +const { test, expect } = require("@playwright/test"); + +const scriptPath = path.resolve(__dirname, "../../js/basicrum/admin/consent-info.js"); + +async function renderConsentExamples(page) { + await page.setContent(` + +

+ + +

+ +

+ + +

+ `); +} + +test("copies the selected manual consent snippet", async ({ page }) => { + await renderConsentExamples(page); + await page.evaluate(() => { + Object.defineProperty(navigator, "clipboard", { + configurable: true, + value: { + writeText(value) { + window.__basicrumCopiedText = value; + return Promise.resolve(); + } + } + }); + }); + await page.addScriptTag({ path: scriptPath }); + + const allowButton = page.getByRole("button", { name: "Copy allow snippet" }); + await allowButton.click(); + + await expect(allowButton.locator("xpath=following-sibling::*[contains(@class, 'basicrum-copy-status')]")) + .toHaveText("Copied"); + await expect(allowButton).toHaveAttribute("data-basicrum-copy-ready", "true"); + expect(await page.evaluate(() => window.__basicrumCopiedText)) + .toBe("window.OPT_IN_BASICRUM_LOADER_WRAPPER();"); +}); + +test("selects the snippet and explains manual copying when clipboard APIs fail", async ({ page }) => { + await renderConsentExamples(page); + await page.evaluate(() => { + Object.defineProperty(navigator, "clipboard", { + configurable: true, + value: undefined + }); + document.execCommand = function() { + return false; + }; + }); + await page.addScriptTag({ path: scriptPath }); + + const denyButton = page.getByRole("button", { name: "Copy deny snippet" }); + await denyButton.click(); + + await expect(denyButton.locator("xpath=following-sibling::*[contains(@class, 'basicrum-copy-status')]")) + .toHaveText("Press Ctrl+C or Command+C to copy."); + await expect(page.locator("#deny-snippet")).toBeFocused(); + expect(await page.locator("#deny-snippet").evaluate((textarea) => ( + textarea.selectionEnd - textarea.selectionStart + ))).toBeGreaterThan(0); +}); diff --git a/tests/php/run.php b/tests/php/run.php index 7d394e7..762039a 100644 --- a/tests/php/run.php +++ b/tests/php/run.php @@ -67,6 +67,62 @@ public function validate() $html, 'guidance must retain the legacy Magento callback alias' ); + basicrum_assert_contains( + 'Allow or grant callback', + $html, + 'guidance must identify the allow integration point' + ); + basicrum_assert_contains( + 'Deny, expiry, or withdrawal callback', + $html, + 'guidance must identify every opt-out integration point' + ); + basicrum_assert_contains( + 'Do not run the two snippets together', + $html, + 'guidance must prevent the separated callbacks from being pasted as one sequence' + ); + basicrum_assert_same( + 2, + substr_count($html, 'class="scalable basicrum-copy-consent-snippet"'), + 'each focused callback example must have a copy action' + ); + basicrum_assert_same( + 2, + substr_count($html, 'readonly="readonly"'), + 'callback examples must be rendered in read-only fields' + ); + basicrum_assert_contains( + 'https://shop.example.test/js/basicrum/admin/consent-info.js', + $html, + 'guidance must load the copy-action behavior from the Magento JS base URL' + ); + + $allowStart = strpos($html, '', $denyStart) - $denyStart); + basicrum_assert_contains( + 'OPT_IN_BASICRUM_LOADER_WRAPPER', + $allowSnippet, + 'allow example must contain only the opt-in integration' + ); + basicrum_assert_not_contains( + 'OPT_OUT_BASICRUM_LOADER_WRAPPER', + $allowSnippet, + 'allow example must not immediately opt out' + ); + basicrum_assert_contains( + 'OPT_OUT_BASICRUM_LOADER_WRAPPER', + $denySnippet, + 'deny example must contain the opt-out integration' + ); + basicrum_assert_not_contains( + 'OPT_IN_BASICRUM_LOADER_WRAPPER', + $denySnippet, + 'deny example must not opt in' + ); $xml = simplexml_load_file($root . '/app/code/community/BasicRum/Analytics/etc/system.xml'); basicrum_assert_true($xml !== false, 'system configuration XML must parse'); diff --git a/tests/platform/verify.php b/tests/platform/verify.php index d8ec896..25986cf 100644 --- a/tests/platform/verify.php +++ b/tests/platform/verify.php @@ -150,5 +150,9 @@ is_file($assetRoot . '/js/basicrum/loaders/consent-boomerang-loader-v1-15.min.js'), 'consent loader is not deployed under the platform document root' ); +basicrum_platform_assert( + is_file($assetRoot . '/js/basicrum/admin/consent-info.js'), + 'admin consent copy behavior is not deployed under the platform document root' +); echo "Native {$platform} configuration and rendering checks passed.\n"; From a0bb3f60c17e633f9e7db6ce2fc204679a12b1d2 Mon Sep 17 00:00:00 2001 From: Tsvetan Stoychev Date: Thu, 17 Sep 2026 21:39:55 +0300 Subject: [PATCH 14/28] feat: add query-string privacy control --- .github/copilot-instructions.md | 2 ++ README.md | 6 ++++ .../Analytics/Block/Boomerang/Loader.php | 1 + .../BasicRum/Analytics/Helper/Data.php | 10 ++++++ .../BasicRum/Analytics/etc/config.xml | 1 + .../BasicRum/Analytics/etc/system.xml | 14 +++++++-- docs/admin-ui-parity-checklist.md | 5 +-- tests/php/bootstrap.php | 1 + tests/php/run.php | 31 +++++++++++++++++++ tests/platform/configure.php | 1 + tests/platform/verify.php | 5 +++ 11 files changed, 73 insertions(+), 4 deletions(-) diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 5b5b587..b726689 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -67,6 +67,7 @@ Access via `Mage::getStoreConfig()` or `Mage::getStoreConfigFlag()`: |------|------|-------------| | `basicrum_analytics/general/enabled` | bool | Enable/disable the module | | `basicrum_analytics/privacy/opt_in_required` | bool | Require a current-page opt-in signal before loading | +| `basicrum_analytics/privacy/strip_query_string` | bool | Redact query strings in monitored URLs before beaconing | | `basicrum_analytics/general/beacon_endpoint` | string | URL where beacons are sent | | `basicrum_analytics/general/brum_site_id` | string | Required Basicrum backend UUID v4 | | `basicrum_analytics/wait_after_onload/enabled` | bool | Enable delayed beacon sending | @@ -113,6 +114,7 @@ The block is added to the `before_body_end` reference in `basicrum_analytics.xml The module configures Boomerang with these settings: - `beacon_url`: From admin config. - `instrument_xhr`: Disabled. +- `strip_query_string`: Scoped privacy setting; disabled by default for compatibility. - `Continuity.enabled`: Tracks user interaction metrics. - `ResourceTiming.enabled`: Captures resource load times. - `secure_cookie` & `same_site_cookie`: Set to `true` and `"Strict"` for security. diff --git a/README.md b/README.md index 1a3562f..0f06e43 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,12 @@ Monitoring scripts are emitted only when all of these conditions are met: Both identity values are mandatory. Runtime validation is performed again when rendering, so missing, malformed, or programmatically injected values fail closed even if they bypass the admin backend models. Dynamic JavaScript values are JSON encoded with HTML-significant characters escaped. +### Query-string privacy + +**Strip Query Strings** controls Boomerang's native URL redaction. It remains disabled by default to preserve the established Magento 1 behavior and match the WordPress default. When enabled, complete query strings in page, navigation, referrer, and resource URLs are replaced with `?qs-redacted` before beacons are sent; URL paths remain available for performance analysis. + +This setting does not modify query parameters in the configured Beacon Endpoint URL. Those parameters are part of the collector destination and continue to be safely serialized unchanged. + ### Consent-controlled loading **Require Consent Before Monitoring** is the privacy-first default for new installations. In this mode the loader remains inert until an external consent tool explicitly calls the opt-in callback on the current page: diff --git a/app/code/community/BasicRum/Analytics/Block/Boomerang/Loader.php b/app/code/community/BasicRum/Analytics/Block/Boomerang/Loader.php index 18d88dc..769e3d6 100644 --- a/app/code/community/BasicRum/Analytics/Block/Boomerang/Loader.php +++ b/app/code/community/BasicRum/Analytics/Block/Boomerang/Loader.php @@ -60,6 +60,7 @@ public function getBoomerangSnippet(): string $configJs = json_encode([ 'beacon_url' => $beaconEndpoint, 'instrument_xhr' => false, + 'strip_query_string' => $helper->shouldStripQueryString(), 'Continuity' => [ 'enabled' => true ], diff --git a/app/code/community/BasicRum/Analytics/Helper/Data.php b/app/code/community/BasicRum/Analytics/Helper/Data.php index dad9d13..a97a2d1 100644 --- a/app/code/community/BasicRum/Analytics/Helper/Data.php +++ b/app/code/community/BasicRum/Analytics/Helper/Data.php @@ -30,6 +30,16 @@ public function isOptInRequired(): bool return Mage::getStoreConfigFlag('basicrum_analytics/privacy/opt_in_required'); } + /** + * Check whether Boomerang should redact URL query strings. + * + * @return bool + */ + public function shouldStripQueryString(): bool + { + return Mage::getStoreConfigFlag('basicrum_analytics/privacy/strip_query_string'); + } + /** * Get beacon endpoint URL * @return string|null diff --git a/app/code/community/BasicRum/Analytics/etc/config.xml b/app/code/community/BasicRum/Analytics/etc/config.xml index 8421fb4..d24eb57 100644 --- a/app/code/community/BasicRum/Analytics/etc/config.xml +++ b/app/code/community/BasicRum/Analytics/etc/config.xml @@ -63,6 +63,7 @@ + 0 1 diff --git a/app/code/community/BasicRum/Analytics/etc/system.xml b/app/code/community/BasicRum/Analytics/etc/system.xml index 80bfe96..679685c 100644 --- a/app/code/community/BasicRum/Analytics/etc/system.xml +++ b/app/code/community/BasicRum/Analytics/etc/system.xml @@ -76,11 +76,21 @@ 1 1 + + + select + adminhtml/system_config_source_yesno + 1 + 1 + 1 + 1 + When enabled, complete query strings in page, navigation, referrer, and resource URLs are replaced with ?qs-redacted before beacons are sent. URL paths are still collected. Beacon Endpoint URL parameters are not changed. + select basicrum_analytics/system_config_source_consentMode - 1 + 2 1 1 1 @@ -89,7 +99,7 @@ note basicrum_analytics/adminhtml_system_config_form_field_consentInfo - 2 + 3 1 1 1 diff --git a/docs/admin-ui-parity-checklist.md b/docs/admin-ui-parity-checklist.md index a719609..6d9298e 100644 --- a/docs/admin-ui-parity-checklist.md +++ b/docs/admin-ui-parity-checklist.md @@ -65,8 +65,9 @@ Legend: - [x] Explain that Basicrum does not persist or infer consent. - [x] Explain cookie removal and that data already sent cannot be retracted. - [x] Explain safe re-grant behavior after withdrawal. -- [ ] Add a Strip Query Strings privacy setting or record a deliberate reason not - to expose it on Magento 1. +- [x] Add a Strip Query Strings privacy setting. + - It uses Boomerang's native `strip_query_string` option, remains disabled by + default for compatibility, and preserves query parameters in the Beacon URL. ## Validation and state feedback diff --git a/tests/php/bootstrap.php b/tests/php/bootstrap.php index 33a2f27..59de919 100644 --- a/tests/php/bootstrap.php +++ b/tests/php/bootstrap.php @@ -340,6 +340,7 @@ function basicrum_test_reset(array $overrides = array()) 'basicrum_analytics/general/enabled' => '1', 'basicrum_analytics/general/beacon_endpoint' => 'https://collector.example.test/beacon', 'basicrum_analytics/general/brum_site_id' => 'e926c1a2-7e33-4f54-90d0-e6e31f3ad43d', + 'basicrum_analytics/privacy/strip_query_string' => '0', 'basicrum_analytics/privacy/opt_in_required' => '0', 'basicrum_analytics/wait_after_onload/enabled' => '0', 'basicrum_analytics/wait_after_onload/wait_ms' => '0', diff --git a/tests/php/run.php b/tests/php/run.php index 762039a..e41af09 100644 --- a/tests/php/run.php +++ b/tests/php/run.php @@ -137,6 +137,16 @@ public function validate() (string) $privacyFields->consent_integration_info->depends->opt_in_required, 'guidance must depend on consent-controlled mode' ); + basicrum_assert_same( + 'adminhtml/system_config_source_yesno', + (string) $privacyFields->strip_query_string->source_model, + 'query-string privacy must use a scoped Magento Yes/No control' + ); + basicrum_assert_contains( + '?qs-redacted', + (string) $privacyFields->strip_query_string->comment, + 'query-string privacy guidance must name the redaction marker' + ); }; $tests['enabled incomplete configuration is visibly inactive'] = function () use ($root) { @@ -309,6 +319,12 @@ public function validate() 'secure pages must upgrade the Beacon URL' ); basicrum_assert_same(30000, $helper->getWaitAfterOnloadMilliseconds(), 'wait value must be capped'); + basicrum_assert_same(false, $helper->shouldStripQueryString(), 'query stripping must remain disabled by default'); + + list($privacyHelper) = basicrum_test_reset(array( + 'basicrum_analytics/privacy/strip_query_string' => '1', + )); + basicrum_assert_same(true, $privacyHelper->shouldStripQueryString(), 'query stripping must honor scoped config'); }; $tests['backend models trim and validate configuration'] = function () { @@ -371,6 +387,21 @@ public function validate() basicrum_assert_not_contains('consent-boomerang-loader', $immediate, 'immediate mode must not use consent loader'); basicrum_assert_contains('brum_site_id', $immediate, 'Site ID must be rendered'); basicrum_assert_contains('beacon_url', $immediate, 'Beacon URL must be rendered'); + basicrum_assert_contains( + '"strip_query_string":false', + $immediate, + 'query strings must remain unchanged by default for compatibility' + ); + + basicrum_test_reset(array( + 'basicrum_analytics/privacy/strip_query_string' => '1', + )); + $redacted = $block->getBoomerangSnippet(); + basicrum_assert_contains( + '"strip_query_string":true', + $redacted, + 'enabled query-string privacy must reach Boomerang as a boolean' + ); basicrum_test_reset(array( 'basicrum_analytics/privacy/opt_in_required' => '1', diff --git a/tests/platform/configure.php b/tests/platform/configure.php index 3341f24..a995f20 100644 --- a/tests/platform/configure.php +++ b/tests/platform/configure.php @@ -18,6 +18,7 @@ 'basicrum_analytics/general/enabled' => $mode === 'disabled' ? '0' : '1', 'basicrum_analytics/general/beacon_endpoint' => 'https://collector.example.test/beacon', 'basicrum_analytics/general/brum_site_id' => '550e8400-e29b-41d4-a716-446655440000', + 'basicrum_analytics/privacy/strip_query_string' => '0', 'basicrum_analytics/privacy/opt_in_required' => $mode === 'consent' ? '1' : '0', 'basicrum_analytics/developer/use_unminified_loaders' => '0', )); diff --git a/tests/platform/verify.php b/tests/platform/verify.php index 25986cf..3c82774 100644 --- a/tests/platform/verify.php +++ b/tests/platform/verify.php @@ -75,6 +75,7 @@ 'basicrum_analytics/general/enabled' => '1', 'basicrum_analytics/general/beacon_endpoint' => 'https://collector.example.test/beacon', 'basicrum_analytics/general/brum_site_id' => '550e8400-e29b-41d4-a716-446655440000', + 'basicrum_analytics/privacy/strip_query_string' => '1', 'basicrum_analytics/privacy/opt_in_required' => '0', 'basicrum_analytics/wait_after_onload/enabled' => '1', 'basicrum_analytics/wait_after_onload/wait_ms' => '90000', @@ -97,6 +98,10 @@ strpos($immediate, '}.bind(this), 30000);') !== false, 'wait-after-onload value was not capped at 30 seconds' ); +basicrum_platform_assert( + strpos($immediate, '"strip_query_string":true') !== false, + 'query-string privacy setting did not reach the native rendered configuration' +); basicrum_platform_save(array( 'basicrum_analytics/general/beacon_endpoint' => 'javascript:alert(1)', From f44e064b3319b4c80f1d1fb3e90397977fa16694 Mon Sep 17 00:00:00 2001 From: Tsvetan Stoychev Date: Thu, 17 Sep 2026 21:45:53 +0300 Subject: [PATCH 15/28] feat: enforce explicit beacon HTTP policy --- .github/copilot-instructions.md | 3 +- README.md | 7 +- .../BasicRum/Analytics/Helper/Data.php | 15 ++- .../Model/Setup/HttpPolicyDefault.php | 78 ++++++++++++ .../System/Config/Backend/BeaconEndpoint.php | 27 ++++ .../Model/System/Config/Source/HttpPolicy.php | 27 ++++ .../BasicRum/Analytics/etc/config.xml | 1 + .../BasicRum/Analytics/etc/system.xml | 14 +- .../install-1.1.0.php | 24 ++++ app/locale/en_US/BasicRum_Analytics.csv | 4 + docs/admin-ui-parity-checklist.md | 8 +- modman | 2 + tests/check-package.sh | 7 +- tests/js/real-boomerang.spec.js | 44 ++++++- tests/php/bootstrap.php | 34 ++++- tests/php/run.php | 120 +++++++++++++++++- tests/platform/configure.php | 1 + tests/platform/prepare-upgrade.php | 19 ++- tests/platform/run.sh | 8 +- tests/platform/verify-upgrade.php | 26 +++- tests/platform/verify.php | 59 +++++++++ 21 files changed, 493 insertions(+), 35 deletions(-) create mode 100644 app/code/community/BasicRum/Analytics/Model/Setup/HttpPolicyDefault.php create mode 100644 app/code/community/BasicRum/Analytics/Model/System/Config/Source/HttpPolicy.php diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index b726689..82e8222 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -57,7 +57,7 @@ js/basicrum/ | Class | Purpose | |-------|---------| | `BasicRum_Analytics_Block_Boomerang_Loader` | Generates the Boomerang JS inline script. Injected into the `before_body_end` reference. | -| `BasicRum_Analytics_Helper_Data` | Retrieves admin config values: `isEnabled()`, `isOptInRequired()`, `getBeaconEndpoint()`, `useUnminifiedLoaders()`. | +| `BasicRum_Analytics_Helper_Data` | Retrieves and normalizes scoped admin configuration, including privacy and HTTP policy. | | `BasicRum_Analytics_Helper_PageTypeDetector` | Detects page type from layout handles (home, product, category, etc.). | ### Configuration Paths @@ -72,6 +72,7 @@ Access via `Mage::getStoreConfig()` or `Mage::getStoreConfigFlag()`: | `basicrum_analytics/general/brum_site_id` | string | Required Basicrum backend UUID v4 | | `basicrum_analytics/wait_after_onload/enabled` | bool | Enable delayed beacon sending | | `basicrum_analytics/wait_after_onload/wait_ms` | int | Milliseconds to wait before sending beacon | +| `basicrum_analytics/developer/development_mode` | bool | Allow HTTP Beacon URLs only for local testing | | `basicrum_analytics/developer/use_unminified_loaders` | bool | Load non-minified JS for debugging | ### JavaScript Assets diff --git a/README.md b/README.md index 0f06e43..3ea1cce 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,8 @@ Monitoring scripts are emitted only when all of these conditions are met: Both identity values are mandatory. Runtime validation is performed again when rendering, so missing, malformed, or programmatically injected values fail closed even if they bypass the admin backend models. Dynamic JavaScript values are JSON encoded with HTML-significant characters escaped. +HTTPS Beacon URLs are enforced by default. The Developer setting **HTTP Strictness** can allow HTTP only for local testing; do not enable it on production stores. When strict mode is active, an HTTP URL saved through the admin is upgraded to HTTPS, and runtime rendering applies the same upgrade to values injected outside the admin path. + ### Query-string privacy **Strip Query Strings** controls Boomerang's native URL redaction. It remains disabled by default to preserve the established Magento 1 behavior and match the WordPress default. When enabled, complete query strings in page, navigation, referrer, and resource URLs are replaced with `?qs-redacted` before beacons are sent; URL paths remain available for performance analysis. @@ -86,9 +88,10 @@ Version 1.1.0 introduces a versioned Magento setup resource for the privacy defa - A genuinely new installation with no `basicrum_analytics/*` rows in `core_config_data` gets an explicit default-scope `opt_in_required=1`. - An upgraded store with an existing Basicrum configuration footprint and no explicit default-scope consent value gets `opt_in_required=0`, preserving the historical immediate-monitoring behavior. - An existing explicit default-scope consent value is never overwritten. Website and store overrides continue to inherit or override through normal Magento scope rules. +- Existing HTTP Beacon URLs keep working after upgrade: for every explicit Beacon URL, the installer records a matching policy at the same scope (`HTTP` remains allowed and `HTTPS` remains strict) unless that scope already contains an explicit policy decision. Descendant scopes continue to inherit normally, and new installations remain HTTPS-strict. - A previously installed but never configured and disabled module is treated like a new installation; this cannot start monitoring because **Enable**, Beacon URL, and Site ID are still required. -The migration policy lives in `BasicRum_Analytics_Model_Setup_PrivacyDefault` and is covered by the PHP test harness. +The migration policies live in `BasicRum_Analytics_Model_Setup_PrivacyDefault` and `BasicRum_Analytics_Model_Setup_HttpPolicyDefault` and are covered by the PHP and native-platform test harnesses. Two 1.1.0 changes can intentionally stop monitoring until configuration or consent integration is corrected: @@ -147,7 +150,7 @@ It also installs the extension into a real application and boots the storefront | OpenMage 20.18.0 | PHP 8.3 | Native setup resource, configuration/rendering, scopes, and live storefront | | Maho 26.9.0 | PHP 8.3 | Native setup resource, admin rendering with global Varien aliases disabled, configuration/rendering, scopes, and live storefront | -The real-install jobs exercise a fresh privacy-first installation, storefront-triggered upgrades from a simulated pre-1.1.0 database with and without an explicit consent decision, incomplete and unsafe configuration, immediate and consent-controlled rendering, the 30-second wait cap, default/website/store inheritance, frontend and admin block resolution, callback-compatible loader delivery, and disabled-mode suppression. Platform versions are deliberately pinned so upstream releases cannot silently change the test baseline; updates should be made explicitly after local validation. +The real-install jobs exercise a fresh privacy-first installation, storefront-triggered upgrades from a simulated pre-1.1.0 database with and without explicit consent or legacy HTTP behavior, incomplete and unsafe configuration, HTTPS enforcement and development HTTP mode, immediate and consent-controlled rendering, query-string privacy, the 30-second wait cap, default/website/store inheritance, frontend and admin block resolution, callback-compatible loader delivery, and disabled-mode suppression. Platform versions are deliberately pinned so upstream releases cannot silently change the test baseline; updates should be made explicitly after local validation. For a local run, provide a disposable platform checkout and an empty MariaDB database, then run—for example—`bash tests/platform/run.sh openmage /path/to/openmage`. The default database is `basicrum` at `127.0.0.1` with username and password `basicrum`; override it with `BASICRUM_TEST_DB_HOST`, `BASICRUM_TEST_DB_NAME`, `BASICRUM_TEST_DB_USER`, and `BASICRUM_TEST_DB_PASSWORD`. The runner deploys the extension into the checkout and installs the application, so neither target should contain data that must be preserved. diff --git a/app/code/community/BasicRum/Analytics/Helper/Data.php b/app/code/community/BasicRum/Analytics/Helper/Data.php index a97a2d1..38ee1e2 100644 --- a/app/code/community/BasicRum/Analytics/Helper/Data.php +++ b/app/code/community/BasicRum/Analytics/Helper/Data.php @@ -52,8 +52,9 @@ public function getBeaconEndpoint() return null; } - // Auto-upgrade HTTP to HTTPS when request is secure to prevent mixed content. - if (Mage::app()->getRequest()->isSecure()) { + // Enforce the production-safe policy even for values injected outside + // the admin backend model. + if (!$this->isDevelopmentMode()) { $url = preg_replace('/^http:\/\//i', 'https://', $url); } @@ -130,6 +131,16 @@ public function useUnminifiedLoaders(): bool return Mage::getStoreConfigFlag('basicrum_analytics/developer/use_unminified_loaders'); } + /** + * Check whether HTTP Beacon URLs are explicitly allowed for local testing. + * + * @return bool + */ + public function isDevelopmentMode(): bool + { + return Mage::getStoreConfigFlag('basicrum_analytics/developer/development_mode'); + } + /** * Get current page type based on layout handles * diff --git a/app/code/community/BasicRum/Analytics/Model/Setup/HttpPolicyDefault.php b/app/code/community/BasicRum/Analytics/Model/Setup/HttpPolicyDefault.php new file mode 100644 index 0000000..8ed442f --- /dev/null +++ b/app/code/community/BasicRum/Analytics/Model/Setup/HttpPolicyDefault.php @@ -0,0 +1,78 @@ +> $beaconRows + * @param array> $explicitPolicyRows + * @return array + */ + public static function getValuesToPersist(array $beaconRows, array $explicitPolicyRows): array + { + $explicitScopes = array(); + foreach ($explicitPolicyRows as $row) { + $key = self::getScopeKey($row); + if ($key !== null) { + $explicitScopes[$key] = true; + } + } + + $scopes = array(); + foreach ($beaconRows as $row) { + $key = self::getScopeKey($row); + $value = isset($row['value']) ? trim((string) $row['value']) : ''; + + if ($key === null || isset($explicitScopes[$key]) || isset($scopes[$key])) { + continue; + } + + if (stripos($value, 'http://') === 0) { + $policyValue = '1'; + } elseif (stripos($value, 'https://') === 0) { + $policyValue = '0'; + } else { + continue; + } + + $scopes[$key] = array( + 'scope' => (string) $row['scope'], + 'scope_id' => (int) $row['scope_id'], + 'value' => $policyValue, + ); + } + + return array_values($scopes); + } + + /** + * @param array $row + * @return string|null + */ + private static function getScopeKey(array $row) + { + $allowedScopes = array('default', 'websites', 'stores'); + $scope = isset($row['scope']) ? (string) $row['scope'] : ''; + $scopeId = isset($row['scope_id']) ? filter_var($row['scope_id'], FILTER_VALIDATE_INT) : false; + + if (!in_array($scope, $allowedScopes, true) || $scopeId === false || (int) $scopeId < 0) { + return null; + } + + if (($scope === 'default' && (int) $scopeId !== 0) + || ($scope !== 'default' && (int) $scopeId === 0) + ) { + return null; + } + + return $scope . ':' . (int) $scopeId; + } +} diff --git a/app/code/community/BasicRum/Analytics/Model/System/Config/Backend/BeaconEndpoint.php b/app/code/community/BasicRum/Analytics/Model/System/Config/Backend/BeaconEndpoint.php index 02ee1a8..cf3bc29 100644 --- a/app/code/community/BasicRum/Analytics/Model/System/Config/Backend/BeaconEndpoint.php +++ b/app/code/community/BasicRum/Analytics/Model/System/Config/Backend/BeaconEndpoint.php @@ -22,8 +22,35 @@ protected function _beforeSave() ); } + if (!$this->isHttpAllowed() && stripos($value, 'http://') === 0) { + $value = 'https://' . substr($value, 7); + } + $this->setValue($value); return parent::_beforeSave(); } + + /** + * Resolve the HTTP policy submitted on the same configuration form. + * Fall back to the current scoped value when the field was not posted. + * + * @return bool + */ + private function isHttpAllowed(): bool + { + $groups = $this->getGroups(); + + if (is_array($groups) + && isset($groups['developer']['fields']['development_mode']) + && is_array($groups['developer']['fields']['development_mode']) + ) { + $field = $groups['developer']['fields']['development_mode']; + if (empty($field['inherit']) && array_key_exists('value', $field)) { + return (string) $field['value'] === '1'; + } + } + + return Mage::getStoreConfigFlag('basicrum_analytics/developer/development_mode'); + } } diff --git a/app/code/community/BasicRum/Analytics/Model/System/Config/Source/HttpPolicy.php b/app/code/community/BasicRum/Analytics/Model/System/Config/Source/HttpPolicy.php new file mode 100644 index 0000000..4b0e7b4 --- /dev/null +++ b/app/code/community/BasicRum/Analytics/Model/System/Config/Source/HttpPolicy.php @@ -0,0 +1,27 @@ +> + */ + public function toOptionArray(): array + { + $helper = Mage::helper('basicrum_analytics'); + + return array( + array( + 'value' => '0', + 'label' => $helper->__('Require HTTPS Beacon URLs (recommended)'), + ), + array( + 'value' => '1', + 'label' => $helper->__('Allow HTTP Beacon URLs for local testing'), + ), + ); + } +} diff --git a/app/code/community/BasicRum/Analytics/etc/config.xml b/app/code/community/BasicRum/Analytics/etc/config.xml index d24eb57..0795029 100644 --- a/app/code/community/BasicRum/Analytics/etc/config.xml +++ b/app/code/community/BasicRum/Analytics/etc/config.xml @@ -71,6 +71,7 @@ 0 + 0 0 diff --git a/app/code/community/BasicRum/Analytics/etc/system.xml b/app/code/community/BasicRum/Analytics/etc/system.xml index 679685c..100e7ab 100644 --- a/app/code/community/BasicRum/Analytics/etc/system.xml +++ b/app/code/community/BasicRum/Analytics/etc/system.xml @@ -53,7 +53,7 @@ 1 1 1 - Required. HTTP or HTTPS URL supplied by Basicrum. Example: https://www.example.com/beacon/catcher + Required. HTTPS is enforced unless HTTP Strictness explicitly allows HTTP for local testing. Example: https://www.example.com/beacon/catcher @@ -149,11 +149,21 @@ 1 1 + + + select + basicrum_analytics/system_config_source_httpPolicy + 1 + 1 + 1 + 1 + Allow HTTP Beacon URLs only for local testing. Keep HTTPS enforcement enabled on production stores. + select adminhtml/system_config_source_yesno - 1 + 2 1 1 1 diff --git a/app/code/community/BasicRum/Analytics/sql/basicrum_analytics_setup/install-1.1.0.php b/app/code/community/BasicRum/Analytics/sql/basicrum_analytics_setup/install-1.1.0.php index ef46f2a..f2f5008 100644 --- a/app/code/community/BasicRum/Analytics/sql/basicrum_analytics_setup/install-1.1.0.php +++ b/app/code/community/BasicRum/Analytics/sql/basicrum_analytics_setup/install-1.1.0.php @@ -8,6 +8,8 @@ $connection = $installer->getConnection(); $configTable = $installer->getTable('core/config_data'); $consentPath = 'basicrum_analytics/privacy/opt_in_required'; +$beaconPath = 'basicrum_analytics/general/beacon_endpoint'; +$httpPolicyPath = 'basicrum_analytics/developer/development_mode'; $explicitDefaultSelect = $connection->select() ->from($configTable, 'path') @@ -30,4 +32,26 @@ Mage::getConfig()->saveConfig($consentPath, $value, 'default', 0); } +$beaconRowsSelect = $connection->select() + ->from($configTable, array('scope', 'scope_id', 'value')) + ->where('path = ?', $beaconPath); + +$explicitHttpPolicySelect = $connection->select() + ->from($configTable, array('scope', 'scope_id')) + ->where('path = ?', $httpPolicyPath); + +$httpPolicies = BasicRum_Analytics_Model_Setup_HttpPolicyDefault::getValuesToPersist( + $connection->fetchAll($beaconRowsSelect), + $connection->fetchAll($explicitHttpPolicySelect) +); + +foreach ($httpPolicies as $policy) { + Mage::getConfig()->saveConfig( + $httpPolicyPath, + $policy['value'], + $policy['scope'], + $policy['scope_id'] + ); +} + $installer->endSetup(); diff --git a/app/locale/en_US/BasicRum_Analytics.csv b/app/locale/en_US/BasicRum_Analytics.csv index 5a7ac8d..a5fbe3f 100644 --- a/app/locale/en_US/BasicRum_Analytics.csv +++ b/app/locale/en_US/BasicRum_Analytics.csv @@ -8,6 +8,10 @@ "Enter the URL where analytics data will be sent","Enter the URL where analytics data will be sent" "Data Privacy / GDPR","Data Privacy / GDPR" "Require Consent Before Monitoring","Require Consent Before Monitoring" +"Strip Query Strings","Strip Query Strings" +"HTTP Strictness","HTTP Strictness" +"Require HTTPS Beacon URLs (recommended)","Require HTTPS Beacon URLs (recommended)" +"Allow HTTP Beacon URLs for local testing","Allow HTTP Beacon URLs for local testing" "Enable Wait After Onload","Enable Wait After Onload" "Wait After Onload (ms)","Wait After Onload (ms)" "Milliseconds to delay the beacon to capture additional metrics.","Milliseconds to delay the beacon to capture additional metrics." diff --git a/docs/admin-ui-parity-checklist.md b/docs/admin-ui-parity-checklist.md index 6d9298e..305b545 100644 --- a/docs/admin-ui-parity-checklist.md +++ b/docs/admin-ui-parity-checklist.md @@ -87,8 +87,10 @@ Legend: - [ ] Decide whether Track Admin Users has a meaningful Magento 1 equivalent and implement it if applicable. -- [ ] Add an explicit development-only HTTP policy or document why Magento's - current HTTP/HTTPS behavior is intentionally different. +- [x] Add an explicit development-only HTTP policy. + - HTTPS is enforced by default. HTTP requires a scoped, clearly labeled local + testing option, and legacy HTTP/HTTPS endpoints retain their behavior through + a versioned scope-preserving upgrade policy. - [ ] Review Script Position as a behavioral requirement. Do not add a Header/Footer selector solely for visual parity: Magento's layout placement and runtime timing differ from WordPress. @@ -127,7 +129,7 @@ Legend: - [x] Document manual consent integration as the supported Magento 1 strategy. - [x] Improve manual integration examples and copy actions. -- [ ] Resolve Strip Query Strings and HTTP-policy parity. +- [x] Resolve Strip Query Strings and HTTP-policy parity. ### Deferred — consent-provider adapters diff --git a/modman b/modman index 041961d..e3e8bd8 100644 --- a/modman +++ b/modman @@ -10,7 +10,9 @@ app/code/community/BasicRum/Analytics/Block/Adminhtml/System/Config/Form/Field/R app/code/community/BasicRum/Analytics/Block/Boomerang/Loader.php app/code/community/BasicRum/Analytics/Block/Boomerang/Loader.php app/code/community/BasicRum/Analytics/Helper/Data.php app/code/community/BasicRum/Analytics/Helper/Data.php app/code/community/BasicRum/Analytics/Helper/PageTypeDetector.php app/code/community/BasicRum/Analytics/Helper/PageTypeDetector.php +app/code/community/BasicRum/Analytics/Model/Setup/HttpPolicyDefault.php app/code/community/BasicRum/Analytics/Model/Setup/HttpPolicyDefault.php app/code/community/BasicRum/Analytics/Model/Setup/PrivacyDefault.php app/code/community/BasicRum/Analytics/Model/Setup/PrivacyDefault.php +app/code/community/BasicRum/Analytics/Model/System/Config/Source/HttpPolicy.php app/code/community/BasicRum/Analytics/Model/System/Config/Source/HttpPolicy.php app/code/community/BasicRum/Analytics/Model/System/Config/Source/ConsentMode.php app/code/community/BasicRum/Analytics/Model/System/Config/Source/ConsentMode.php app/code/community/BasicRum/Analytics/Model/System/Config/Source/Version.php app/code/community/BasicRum/Analytics/Model/System/Config/Source/Version.php app/code/community/BasicRum/Analytics/Model/System/Config/Backend/BeaconEndpoint.php app/code/community/BasicRum/Analytics/Model/System/Config/Backend/BeaconEndpoint.php diff --git a/tests/check-package.sh b/tests/check-package.sh index 0460fb1..277492d 100644 --- a/tests/check-package.sh +++ b/tests/check-package.sh @@ -10,9 +10,12 @@ done < <(find app -type f -name '*.xml' -print | sort) module_version="$(xmllint --xpath 'string(/config/modules/BasicRum_Analytics/version)' app/code/community/BasicRum/Analytics/etc/config.xml)" privacy_default="$(xmllint --xpath 'string(/config/default/basicrum_analytics/privacy/opt_in_required)' app/code/community/BasicRum/Analytics/etc/config.xml)" +strip_query_default="$(xmllint --xpath 'string(/config/default/basicrum_analytics/privacy/strip_query_string)' app/code/community/BasicRum/Analytics/etc/config.xml)" +http_policy_default="$(xmllint --xpath 'string(/config/default/basicrum_analytics/developer/development_mode)' app/code/community/BasicRum/Analytics/etc/config.xml)" -if [[ "$module_version" != "1.1.0" || "$privacy_default" != "1" ]]; then - echo "Unexpected module version or privacy default: version=$module_version opt_in_required=$privacy_default" >&2 +if [[ "$module_version" != "1.1.0" || "$privacy_default" != "1" \ + || "$strip_query_default" != "0" || "$http_policy_default" != "0" ]]; then + echo "Unexpected module or policy defaults: version=$module_version opt_in_required=$privacy_default strip_query_string=$strip_query_default development_mode=$http_policy_default" >&2 exit 1 fi diff --git a/tests/js/real-boomerang.spec.js b/tests/js/real-boomerang.spec.js index 5a53f53..6716b02 100644 --- a/tests/js/real-boomerang.spec.js +++ b/tests/js/real-boomerang.spec.js @@ -16,19 +16,25 @@ function loaderPath(file) { return path.join(root, "js/basicrum/loaders", file); } -async function prepareRealPage(page) { +async function prepareRealPage(page, options = {}) { let releaseDownload; let markDownloadStarted; let beaconRequests = 0; + const beaconRequestData = []; + const pageUrl = options.pageUrl || shopUrl; const downloadGate = new Promise((resolve) => { releaseDownload = resolve; }); const downloadStarted = new Promise((resolve) => { markDownloadStarted = resolve; }); - await page.route(shopUrl, (route) => route.fulfill({ + await page.route(`${shopUrl}*`, (route) => route.fulfill({ contentType: "text/html", body: "" })); await page.route(`${beaconUrl}*`, (route) => { beaconRequests += 1; + beaconRequestData.push({ + url: route.request().url(), + postData: route.request().postData() + }); return route.fulfill({ status: 204, headers: { "access-control-allow-origin": "*" }, @@ -45,22 +51,28 @@ async function prepareRealPage(page) { }); }); - await page.goto(shopUrl); - await page.evaluate(({ bundleUrl, collectorUrl }) => { + await page.goto(pageUrl); + await page.evaluate(({ bundleUrl, collectorUrl, stripQueryString }) => { window.BOOMR = { url: bundleUrl }; window.basicRumBoomerangConfig = { beacon_url: collectorUrl, instrument_xhr: false, + strip_query_string: stripQueryString, Continuity: { enabled: true }, secure_cookie: false, same_site_cookie: "Strict" }; - }, { bundleUrl: boomerangUrl, collectorUrl: beaconUrl }); + }, { + bundleUrl: boomerangUrl, + collectorUrl: beaconUrl, + stripQueryString: Boolean(options.stripQueryString) + }); return { downloadStarted, releaseDownload, - beaconRequests: () => beaconRequests + beaconRequests: () => beaconRequests, + beaconRequestData: () => beaconRequestData }; } @@ -70,6 +82,26 @@ async function waitForRealBoomerang(page) { ).toBe("1.815.60"); } +test("real Boomerang redacts the monitored page query string when enabled", async ({ page }) => { + const gate = await prepareRealPage(page, { + pageUrl: `${shopUrl}?customer=private-value&campaign=test`, + stripQueryString: true + }); + + await page.addScriptTag({ path: loaderPath("boomerang-loader-v15.js") }); + await gate.downloadStarted; + gate.releaseDownload(); + await waitForRealBoomerang(page); + await expect.poll(() => gate.beaconRequests(), { timeout: 10000 }).toBeGreaterThan(0); + + const request = gate.beaconRequestData()[0]; + const parameters = request.postData + ? new URLSearchParams(request.postData) + : new URL(request.url).searchParams; + expect(parameters.get("u")).toBe(`${shopUrl}?qs-redacted`); + expect(`${request.url}${request.postData || ""}`).not.toContain("private-value"); +}); + for (const consentLoader of [ "consent-boomerang-loader-v1-15.js", "consent-boomerang-loader-v1-15.min.js" diff --git a/tests/php/bootstrap.php b/tests/php/bootstrap.php index 59de919..12be9b8 100644 --- a/tests/php/bootstrap.php +++ b/tests/php/bootstrap.php @@ -118,6 +118,7 @@ public function getElementHtml() class Mage_Core_Model_Config_Data { private $value; + private $groups = array(); public function setValue($value) { @@ -130,6 +131,17 @@ public function getValue() return $this->value; } + public function setGroups(array $groups) + { + $this->groups = $groups; + return $this; + } + + public function getGroups() + { + return $this->groups; + } + protected function _beforeSave() { return $this; @@ -166,11 +178,13 @@ public function limit($count) class Basicrum_Test_Connection { public $fetchResults; + public $fetchAllResults; public $selects = array(); - public function __construct(array $fetchResults) + public function __construct(array $fetchResults, array $fetchAllResults = array()) { $this->fetchResults = $fetchResults; + $this->fetchAllResults = $fetchAllResults; } public function select() @@ -192,6 +206,19 @@ public function fetchOne($select) return array_shift($this->fetchResults); } + + public function fetchAll($select) + { + if (!in_array($select, $this->selects, true)) { + throw new RuntimeException('Installer queried an unknown select object'); + } + + if (!$this->fetchAllResults) { + throw new RuntimeException('Installer made more fetchAll queries than expected'); + } + + return array_shift($this->fetchAllResults); + } } class Basicrum_Test_Config @@ -212,9 +239,9 @@ class Basicrum_Test_Setup public $ended = 0; public $requestedTables = array(); - public function __construct(array $fetchResults) + public function __construct(array $fetchResults, array $fetchAllResults = array()) { - $this->connection = new Basicrum_Test_Connection($fetchResults); + $this->connection = new Basicrum_Test_Connection($fetchResults, $fetchAllResults); } public function startSetup() @@ -344,6 +371,7 @@ function basicrum_test_reset(array $overrides = array()) 'basicrum_analytics/privacy/opt_in_required' => '0', 'basicrum_analytics/wait_after_onload/enabled' => '0', 'basicrum_analytics/wait_after_onload/wait_ms' => '0', + 'basicrum_analytics/developer/development_mode' => '0', 'basicrum_analytics/developer/use_unminified_loaders' => '0', ), $overrides); Mage::$app = new Basicrum_Test_App(); diff --git a/tests/php/run.php b/tests/php/run.php index e41af09..a26d1bc 100644 --- a/tests/php/run.php +++ b/tests/php/run.php @@ -8,8 +8,10 @@ require $root . '/app/code/community/BasicRum/Analytics/Block/Boomerang/Loader.php'; require $root . '/app/code/community/BasicRum/Analytics/Model/System/Config/Backend/SiteId.php'; require $root . '/app/code/community/BasicRum/Analytics/Model/System/Config/Backend/BeaconEndpoint.php'; +require $root . '/app/code/community/BasicRum/Analytics/Model/Setup/HttpPolicyDefault.php'; require $root . '/app/code/community/BasicRum/Analytics/Model/Setup/PrivacyDefault.php'; require $root . '/app/code/community/BasicRum/Analytics/Model/System/Config/Source/ConsentMode.php'; +require $root . '/app/code/community/BasicRum/Analytics/Model/System/Config/Source/HttpPolicy.php'; require $root . '/app/code/community/BasicRum/Analytics/Block/Adminhtml/System/Config/Form/Field/ConsentInfo.php'; require $root . '/app/code/community/BasicRum/Analytics/Block/Adminhtml/System/Config/Form/Field/RequiredSetting.php'; @@ -50,6 +52,17 @@ public function validate() ); }; +$tests['admin HTTP policy choices explain production and development behavior'] = function () { + basicrum_test_reset(); + + $options = (new BasicRum_Analytics_Model_System_Config_Source_HttpPolicy())->toOptionArray(); + + basicrum_assert_same('0', $options[0]['value'], 'HTTPS enforcement must retain its stored value'); + basicrum_assert_contains('Require HTTPS', $options[0]['label'], 'the safe policy must explain HTTPS enforcement'); + basicrum_assert_same('1', $options[1]['value'], 'development HTTP mode must retain its stored value'); + basicrum_assert_contains('local testing', $options[1]['label'], 'HTTP mode must be limited to local testing'); +}; + $tests['admin consent guidance is a full-width dependent row'] = function () use ($root) { $elementId = 'basicrum_analytics_privacy_consent_integration_info'; $renderer = new BasicRum_Analytics_Block_Adminhtml_System_Config_Form_Field_ConsentInfo(); @@ -147,6 +160,11 @@ public function validate() (string) $privacyFields->strip_query_string->comment, 'query-string privacy guidance must name the redaction marker' ); + basicrum_assert_same( + 'basicrum_analytics/system_config_source_httpPolicy', + (string) $xml->sections->basicrum_analytics->groups->developer->fields->development_mode->source_model, + 'HTTP policy must use plain-language choices' + ); }; $tests['enabled incomplete configuration is visibly inactive'] = function () use ($root) { @@ -306,17 +324,16 @@ public function validate() ); }; -$tests['helper normalizes secure URLs and wait milliseconds'] = function () { +$tests['helper enforces the HTTP policy and normalizes wait milliseconds'] = function () { list($helper) = basicrum_test_reset(array( 'basicrum_analytics/general/beacon_endpoint' => 'http://collector.example.test/beacon', 'basicrum_analytics/wait_after_onload/wait_ms' => '90000', )); - Mage::$app->request->secure = true; basicrum_assert_same( 'https://collector.example.test/beacon', $helper->getBeaconEndpoint(), - 'secure pages must upgrade the Beacon URL' + 'strict mode must upgrade the Beacon URL even on an HTTP storefront' ); basicrum_assert_same(30000, $helper->getWaitAfterOnloadMilliseconds(), 'wait value must be capped'); basicrum_assert_same(false, $helper->shouldStripQueryString(), 'query stripping must remain disabled by default'); @@ -325,6 +342,16 @@ public function validate() 'basicrum_analytics/privacy/strip_query_string' => '1', )); basicrum_assert_same(true, $privacyHelper->shouldStripQueryString(), 'query stripping must honor scoped config'); + + list($developmentHelper) = basicrum_test_reset(array( + 'basicrum_analytics/general/beacon_endpoint' => 'http://127.0.0.1:8080/beacon?site=one', + 'basicrum_analytics/developer/development_mode' => '1', + )); + basicrum_assert_same( + 'http://127.0.0.1:8080/beacon?site=one', + $developmentHelper->getBeaconEndpoint(), + 'development mode must retain an explicitly configured HTTP Beacon URL' + ); }; $tests['backend models trim and validate configuration'] = function () { @@ -351,6 +378,29 @@ public function validate() 'Beacon backend must trim a valid URL' ); + $strictBeacon = new Basicrum_Test_BeaconBackend(); + $strictBeacon->setValue('http://collector.example.test/beacon?site=one')->validate(); + basicrum_assert_same( + 'https://collector.example.test/beacon?site=one', + $strictBeacon->getValue(), + 'Beacon backend must upgrade HTTP while strict mode is selected' + ); + + $developmentBeacon = new Basicrum_Test_BeaconBackend(); + $developmentBeacon->setGroups(array( + 'developer' => array( + 'fields' => array( + 'development_mode' => array('value' => '1'), + ), + ), + )); + $developmentBeacon->setValue('http://127.0.0.1:8080/beacon')->validate(); + basicrum_assert_same( + 'http://127.0.0.1:8080/beacon', + $developmentBeacon->getValue(), + 'Beacon backend must honor development mode submitted on the same form' + ); + basicrum_assert_throws(function () { $model = new Basicrum_Test_BeaconBackend(); $model->setValue('data:text/javascript,alert(1)')->validate(); @@ -464,18 +514,47 @@ public function validate() ); }; -$tests['privacy default installer persists the versioned decision through Magento APIs'] = function () use ($root) { +$tests['HTTP policy migration preserves each explicit Beacon URL scope'] = function () { + $policies = BasicRum_Analytics_Model_Setup_HttpPolicyDefault::getValuesToPersist( + array( + array('scope' => 'default', 'scope_id' => '0', 'value' => 'http://collector.example.test/beacon'), + array('scope' => 'websites', 'scope_id' => '2', 'value' => 'https://collector.example.test/beacon'), + array('scope' => 'stores', 'scope_id' => '3', 'value' => ' HTTP://127.0.0.1:8080/beacon '), + array('scope' => 'stores', 'scope_id' => '3', 'value' => 'http://duplicate.example.test'), + array('scope' => 'invalid', 'scope_id' => '4', 'value' => 'http://ignored.example.test'), + array('scope' => 'default', 'scope_id' => '9', 'value' => 'http://ignored.example.test'), + ), + array( + array('scope' => 'default', 'scope_id' => '0'), + ) + ); + + basicrum_assert_same( + array( + array('scope' => 'websites', 'scope_id' => 2, 'value' => '0'), + array('scope' => 'stores', 'scope_id' => 3, 'value' => '1'), + ), + $policies, + 'migration must preserve scoped HTTP and HTTPS behavior without overwriting explicit policy values' + ); +}; + +$tests['setup installer persists versioned defaults through Magento APIs'] = function () use ($root) { $installerPath = $root . '/app/code/community/BasicRum/Analytics/sql/basicrum_analytics_setup/install-1.1.0.php'; $consentPath = 'basicrum_analytics/privacy/opt_in_required'; + $beaconPath = 'basicrum_analytics/general/beacon_endpoint'; + $httpPolicyPath = 'basicrum_analytics/developer/development_mode'; $cases = array( 'new installation' => array( 'queryResults' => array(false, false), + 'fetchAllResults' => array(array(), array()), 'expectedSaves' => array(array($consentPath, '1', 'default', 0)), ), 'existing installation without an explicit decision' => array( 'queryResults' => array(false, 'basicrum_analytics/general/enabled'), + 'fetchAllResults' => array(array(), array()), 'expectedSaves' => array(array($consentPath, '0', 'default', 0)), ), 'installation with an explicit default-scope decision' => array( @@ -483,13 +562,32 @@ public function validate() $consentPath, 'basicrum_analytics/general/enabled', ), + 'fetchAllResults' => array(array(), array()), 'expectedSaves' => array(), ), + 'existing scoped HTTP endpoints' => array( + 'queryResults' => array(false, $beaconPath), + 'fetchAllResults' => array( + array( + array('scope' => 'default', 'scope_id' => '0', 'value' => 'http://collector.example.test'), + array('scope' => 'websites', 'scope_id' => '2', 'value' => 'https://collector.example.test'), + array('scope' => 'stores', 'scope_id' => '3', 'value' => 'http://127.0.0.1:8080/beacon'), + ), + array( + array('scope' => 'stores', 'scope_id' => '3'), + ), + ), + 'expectedSaves' => array( + array($consentPath, '0', 'default', 0), + array($httpPolicyPath, '1', 'default', 0), + array($httpPolicyPath, '0', 'websites', 2), + ), + ), ); foreach ($cases as $caseName => $case) { basicrum_test_reset(); - $setup = new Basicrum_Test_Setup($case['queryResults']); + $setup = new Basicrum_Test_Setup($case['queryResults'], $case['fetchAllResults']); $setup->runInstaller($installerPath); basicrum_assert_same(1, $setup->started, $caseName . ': setup must start exactly once'); @@ -504,7 +602,7 @@ public function validate() Mage::$configObject->saved, $caseName . ': installer persisted the wrong privacy default' ); - basicrum_assert_same(2, count($setup->connection->selects), $caseName . ': expected two detection queries'); + basicrum_assert_same(4, count($setup->connection->selects), $caseName . ': expected four detection queries'); basicrum_assert_same('path', $setup->connection->selects[0]->columns, $caseName . ': query must avoid legacy expression classes'); basicrum_assert_same(1, $setup->connection->selects[0]->limit, $caseName . ': explicit query must stop after one row'); basicrum_assert_same(1, $setup->connection->selects[1]->limit, $caseName . ': footprint query must stop after one row'); @@ -522,6 +620,16 @@ public function validate() $setup->connection->selects[1]->where, $caseName . ': upgrade detection must use the module configuration namespace' ); + basicrum_assert_same( + array(array('path = ?', $beaconPath)), + $setup->connection->selects[2]->where, + $caseName . ': HTTP preservation must inspect only Beacon URL rows' + ); + basicrum_assert_same( + array(array('path = ?', $httpPolicyPath)), + $setup->connection->selects[3]->where, + $caseName . ': HTTP preservation must respect explicit policy rows' + ); } }; diff --git a/tests/platform/configure.php b/tests/platform/configure.php index a995f20..59f65f6 100644 --- a/tests/platform/configure.php +++ b/tests/platform/configure.php @@ -20,6 +20,7 @@ 'basicrum_analytics/general/brum_site_id' => '550e8400-e29b-41d4-a716-446655440000', 'basicrum_analytics/privacy/strip_query_string' => '0', 'basicrum_analytics/privacy/opt_in_required' => $mode === 'consent' ? '1' : '0', + 'basicrum_analytics/developer/development_mode' => '0', 'basicrum_analytics/developer/use_unminified_loaders' => '0', )); diff --git a/tests/platform/prepare-upgrade.php b/tests/platform/prepare-upgrade.php index 28c4ce4..32e0979 100644 --- a/tests/platform/prepare-upgrade.php +++ b/tests/platform/prepare-upgrade.php @@ -2,14 +2,14 @@ declare(strict_types=1); if ($argc !== 4) { - fwrite(STDERR, "Usage: php prepare-upgrade.php \n"); + fwrite(STDERR, "Usage: php prepare-upgrade.php \n"); exit(2); } require __DIR__ . '/bootstrap.php'; $scenario = $argv[3]; -if (!in_array($scenario, array('legacy', 'explicit'), true)) { +if (!in_array($scenario, array('legacy', 'explicit', 'http'), true)) { fwrite(STDERR, "Unsupported upgrade scenario: {$scenario}\n"); exit(2); } @@ -31,14 +31,16 @@ array('path LIKE ?' => 'basicrum_analytics/%') ); -if ($scenario === 'legacy') { +if ($scenario === 'legacy' || $scenario === 'http') { Mage::getConfig()->saveConfig( 'basicrum_analytics/general/enabled', '0', 'default', 0 ); -} else { +} + +if ($scenario === 'explicit') { Mage::getConfig()->saveConfig( 'basicrum_analytics/privacy/opt_in_required', '1', @@ -47,6 +49,15 @@ ); } +if ($scenario === 'http') { + Mage::getConfig()->saveConfig( + 'basicrum_analytics/general/beacon_endpoint', + 'http://127.0.0.1:8080/beacon', + 'default', + 0 + ); +} + Mage::app()->getCacheInstance()->cleanType('config'); echo "Prepared {$scenario} pre-1.1.0 database state for {$platform}.\n"; diff --git a/tests/platform/run.sh b/tests/platform/run.sh index a330bef..7481375 100644 --- a/tests/platform/run.sh +++ b/tests/platform/run.sh @@ -85,8 +85,12 @@ bash "$plugin_root/tests/platform/verify-live.sh" "$platform" "$platform_root" php "$plugin_root/tests/platform/prepare-upgrade.php" "$platform_root" "$platform" legacy bash "$plugin_root/tests/platform/apply-upgrade.sh" "$platform" "$platform_root" -php "$plugin_root/tests/platform/verify-upgrade.php" "$platform_root" "$platform" legacy 0 +php "$plugin_root/tests/platform/verify-upgrade.php" "$platform_root" "$platform" legacy 0 absent php "$plugin_root/tests/platform/prepare-upgrade.php" "$platform_root" "$platform" explicit bash "$plugin_root/tests/platform/apply-upgrade.sh" "$platform" "$platform_root" -php "$plugin_root/tests/platform/verify-upgrade.php" "$platform_root" "$platform" explicit 1 +php "$plugin_root/tests/platform/verify-upgrade.php" "$platform_root" "$platform" explicit 1 absent + +php "$plugin_root/tests/platform/prepare-upgrade.php" "$platform_root" "$platform" http +bash "$plugin_root/tests/platform/apply-upgrade.sh" "$platform" "$platform_root" +php "$plugin_root/tests/platform/verify-upgrade.php" "$platform_root" "$platform" http 0 1 diff --git a/tests/platform/verify-upgrade.php b/tests/platform/verify-upgrade.php index 1e4c1c9..03e68df 100644 --- a/tests/platform/verify-upgrade.php +++ b/tests/platform/verify-upgrade.php @@ -1,10 +1,10 @@ \n" + "Usage: php verify-upgrade.php \n" ); exit(2); } @@ -13,6 +13,7 @@ $scenario = $argv[3]; $expectedConsent = $argv[4]; +$expectedHttpPolicy = $argv[5]; $resourceSetup = Mage::getResourceModel('core/resource'); basicrum_platform_assert_same( @@ -37,4 +38,25 @@ "{$scenario}: upgrade persisted the wrong consent mode" ); +$httpPolicySelect = $connection->select() + ->from($configTable, 'value') + ->where('path = ?', 'basicrum_analytics/developer/development_mode') + ->where('scope = ?', 'default') + ->where('scope_id = ?', 0) + ->limit(1); +$actualHttpPolicy = $connection->fetchOne($httpPolicySelect); + +if ($expectedHttpPolicy === 'absent') { + basicrum_platform_assert( + $actualHttpPolicy === false, + "{$scenario}: upgrade unexpectedly persisted an HTTP policy" + ); +} else { + basicrum_platform_assert_same( + $expectedHttpPolicy, + (string) $actualHttpPolicy, + "{$scenario}: upgrade did not preserve the legacy HTTP policy" + ); +} + echo "Native {$platform} {$scenario} upgrade check passed.\n"; diff --git a/tests/platform/verify.php b/tests/platform/verify.php index 3c82774..23382ec 100644 --- a/tests/platform/verify.php +++ b/tests/platform/verify.php @@ -28,6 +28,10 @@ (string) $connection->fetchOne($select), 'fresh installation did not persist the privacy-first default' ); +basicrum_platform_assert( + !Mage::getStoreConfigFlag('basicrum_analytics/developer/development_mode'), + 'fresh installation did not start with HTTPS enforcement' +); $helper = Mage::helper('basicrum_analytics'); basicrum_platform_assert( @@ -68,6 +72,12 @@ 'Magento did not resolve the Basicrum Beacon URL backend model' ); +$httpPolicy = Mage::getModel('basicrum_analytics/system_config_source_httpPolicy'); +basicrum_platform_assert( + $httpPolicy instanceof BasicRum_Analytics_Model_System_Config_Source_HttpPolicy, + 'Magento did not resolve the Basicrum HTTP policy source model' +); + $layoutFile = Mage::getConfig()->getNode('frontend/layout/updates/basicrumanalytics/file'); basicrum_platform_assert_same('basicrum_analytics.xml', (string) $layoutFile, 'frontend layout update is not registered'); @@ -79,6 +89,7 @@ 'basicrum_analytics/privacy/opt_in_required' => '0', 'basicrum_analytics/wait_after_onload/enabled' => '1', 'basicrum_analytics/wait_after_onload/wait_ms' => '90000', + 'basicrum_analytics/developer/development_mode' => '0', 'basicrum_analytics/developer/use_unminified_loaders' => '0', )); basicrum_platform_reboot(); @@ -103,8 +114,34 @@ 'query-string privacy setting did not reach the native rendered configuration' ); +basicrum_platform_save(array( + 'basicrum_analytics/general/beacon_endpoint' => 'http://collector.example.test/beacon?site=one', + 'basicrum_analytics/developer/development_mode' => '0', +)); +basicrum_platform_reboot(); +$strictHttp = Mage::app()->getLayout() + ->createBlock('basicrum_analytics/boomerang_loader') + ->getBoomerangSnippet(); +basicrum_platform_assert( + strpos($strictHttp, 'https:\/\/collector.example.test\/beacon?site=one') !== false, + 'strict runtime policy did not upgrade an HTTP Beacon URL' +); + +basicrum_platform_save(array( + 'basicrum_analytics/developer/development_mode' => '1', +)); +basicrum_platform_reboot(); +$developmentHttp = Mage::app()->getLayout() + ->createBlock('basicrum_analytics/boomerang_loader') + ->getBoomerangSnippet(); +basicrum_platform_assert( + strpos($developmentHttp, 'http:\/\/collector.example.test\/beacon?site=one') !== false, + 'development HTTP policy did not preserve the configured Beacon URL' +); + basicrum_platform_save(array( 'basicrum_analytics/general/beacon_endpoint' => 'javascript:alert(1)', + 'basicrum_analytics/developer/development_mode' => '0', )); basicrum_platform_reboot(); $invalid = Mage::app()->getLayout() @@ -119,24 +156,46 @@ basicrum_platform_save(array( 'basicrum_analytics/general/beacon_endpoint' => 'https://collector.example.test/beacon', 'basicrum_analytics/privacy/opt_in_required' => '0', + 'basicrum_analytics/privacy/strip_query_string' => '0', + 'basicrum_analytics/developer/development_mode' => '0', )); basicrum_platform_save(array( 'basicrum_analytics/privacy/opt_in_required' => '1', + 'basicrum_analytics/privacy/strip_query_string' => '1', + 'basicrum_analytics/developer/development_mode' => '1', ), 'websites', $websiteId); basicrum_platform_reboot(); basicrum_platform_assert( Mage::getStoreConfigFlag('basicrum_analytics/privacy/opt_in_required', $storeId), 'website-scope consent setting was not inherited by the store' ); +basicrum_platform_assert( + Mage::getStoreConfigFlag('basicrum_analytics/privacy/strip_query_string', $storeId), + 'website-scope query-string setting was not inherited by the store' +); +basicrum_platform_assert( + Mage::getStoreConfigFlag('basicrum_analytics/developer/development_mode', $storeId), + 'website-scope HTTP policy was not inherited by the store' +); basicrum_platform_save(array( 'basicrum_analytics/privacy/opt_in_required' => '0', + 'basicrum_analytics/privacy/strip_query_string' => '0', + 'basicrum_analytics/developer/development_mode' => '0', ), 'stores', $storeId); basicrum_platform_reboot(); basicrum_platform_assert( !Mage::getStoreConfigFlag('basicrum_analytics/privacy/opt_in_required', $storeId), 'store-scope consent setting did not override the website' ); +basicrum_platform_assert( + !Mage::getStoreConfigFlag('basicrum_analytics/privacy/strip_query_string', $storeId), + 'store-scope query-string setting did not override the website' +); +basicrum_platform_assert( + !Mage::getStoreConfigFlag('basicrum_analytics/developer/development_mode', $storeId), + 'store-scope HTTP policy did not override the website' +); basicrum_platform_save(array( 'basicrum_analytics/privacy/opt_in_required' => '1', From 45d3c6dcecd2fb8149ff5ea77ce44f4875ea9867 Mon Sep 17 00:00:00 2001 From: Tsvetan Stoychev Date: Thu, 17 Sep 2026 22:18:04 +0300 Subject: [PATCH 16/28] feat(admin): hide runtime controls while disabled --- .github/copilot-instructions.md | 1 + README.md | 2 + .../BasicRum/Analytics/etc/system.xml | 38 ++++++++ docs/admin-ui-parity-checklist.md | 11 ++- tests/php/run.php | 87 +++++++++++++++++++ tests/platform/bootstrap.php | 17 ++++ tests/platform/verify.php | 61 +++++++++++++ 7 files changed, 214 insertions(+), 3 deletions(-) diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 82e8222..e63156f 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -102,6 +102,7 @@ The block is added to the `before_body_end` reference in `basicrum_analytics.xml - `config.xml`: Module version, models, blocks, helpers, events. - `system.xml`: Backend configuration fields (ACL, Scope). - `adminhtml.xml`: Admin menu items and ACL resources. + - Keep Beacon Endpoint URL and BasicRUM Site ID visible while the module is disabled. Runtime-only privacy, wait, and developer fields use cross-group `system.xml` dependencies on `basicrum_analytics/general/enabled`; preserve those dependencies and Magento's scoped inheritance behavior. ## Important Patterns - **Helpers**: Always access helpers via `Mage::helper('basicrum_analytics')`. diff --git a/README.md b/README.md index 3ea1cce..18cbc44 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,8 @@ Monitoring scripts are emitted only when all of these conditions are met: Both identity values are mandatory. Runtime validation is performed again when rendering, so missing, malformed, or programmatically injected values fail closed even if they bypass the admin backend models. Dynamic JavaScript values are JSON encoded with HTML-significant characters escaped. +When **Enable** is set to No, Magento keeps the bundled Boomerang version, Beacon Endpoint URL, and BasicRUM Site ID visible so an administrator can prepare or inspect the identity configuration before enabling monitoring. Privacy, wait, and developer runtime controls are hidden and disabled through Magento's native field dependencies. Their stored default, website, and store-view values are retained and reappear when monitoring is enabled; normal scope inheritance and **Use Default/Use Website** behavior are unchanged. + HTTPS Beacon URLs are enforced by default. The Developer setting **HTTP Strictness** can allow HTTP only for local testing; do not enable it on production stores. When strict mode is active, an HTTP URL saved through the admin is upgraded to HTTPS, and runtime rendering applies the same upgrade to values injected outside the admin path. ### Query-string privacy diff --git a/app/code/community/BasicRum/Analytics/etc/system.xml b/app/code/community/BasicRum/Analytics/etc/system.xml index 100e7ab..706a1f9 100644 --- a/app/code/community/BasicRum/Analytics/etc/system.xml +++ b/app/code/community/BasicRum/Analytics/etc/system.xml @@ -85,6 +85,12 @@ 1 1 When enabled, complete query strings in page, navigation, referrer, and resource URLs are replaced with ?qs-redacted before beacons are sent. URL paths are still collected. Beacon Endpoint URL parameters are not changed. + + +
general
+ 1 +
+
@@ -95,6 +101,12 @@ 1 1 Choose whether Basicrum may begin monitoring immediately or must wait for explicit consent on each page. + + +
general
+ 1 +
+
note @@ -104,6 +116,10 @@ 1 1 + +
general
+ 1 +
1
@@ -125,6 +141,12 @@ 1 1 1 + + +
general
+ 1 +
+
@@ -136,6 +158,10 @@ 1 Milliseconds to delay the beacon to capture additional metrics. Values are limited to 0–30000 milliseconds (30 seconds); larger values are capped at 30000. + +
general
+ 1 +
1
@@ -158,6 +184,12 @@ 1 1 Allow HTTP Beacon URLs only for local testing. Keep HTTPS enforcement enabled on production stores. + + +
general
+ 1 +
+
@@ -168,6 +200,12 @@ 1 1 Enable to load non-minified loader scripts for debugging purposes. + + +
general
+ 1 +
+
diff --git a/docs/admin-ui-parity-checklist.md b/docs/admin-ui-parity-checklist.md index 305b545..aca72a2 100644 --- a/docs/admin-ui-parity-checklist.md +++ b/docs/admin-ui-parity-checklist.md @@ -78,10 +78,15 @@ Legend: - Feedback is shown only when monitoring is enabled, uses the resolved field values at the current configuration scope, and does not replace the backend validation contract. -- [ ] Disable or hide irrelevant dependent controls when the module is disabled. +- [x] Disable or hide irrelevant dependent controls when the module is disabled. + - Magento's native field dependencies hide and disable privacy, wait, and + developer runtime controls. Stored scoped values remain intact. + - Boomerang version, Beacon Endpoint URL, and BasicRUM Site ID stay visible so + administrators can inspect or prepare identity configuration before enabling. - [x] Reveal Wait After Onload milliseconds only when Wait After Onload is enabled. -- [ ] Review whether consent-specific controls should be disabled when the module - itself is disabled. +- [x] Hide consent-specific controls when the module itself is disabled. + - Consent guidance additionally requires consent-controlled mode, including + when the controlling values are inherited at Website or Store View scope. ## Remaining WordPress controls diff --git a/tests/php/run.php b/tests/php/run.php index a26d1bc..ac109da 100644 --- a/tests/php/run.php +++ b/tests/php/run.php @@ -33,6 +33,23 @@ public function validate() $tests = array(); +function basicrum_config_dependency_map(SimpleXMLElement $field, $defaultFieldset) +{ + $dependencies = array(); + + if (!isset($field->depends)) { + return $dependencies; + } + + foreach ($field->depends->children() as $dependency) { + $fieldset = isset($dependency->fieldset) ? (string) $dependency->fieldset : $defaultFieldset; + $value = isset($dependency->value) ? (string) $dependency->value : (string) $dependency; + $dependencies[$fieldset . '/' . $dependency->getName()] = $value; + } + + return $dependencies; +} + $tests['admin consent choices preserve values and explain behavior'] = function () { basicrum_test_reset(); @@ -167,6 +184,76 @@ public function validate() ); }; +$tests['admin hides runtime controls while monitoring is disabled'] = function () use ($root) { + $xml = simplexml_load_file($root . '/app/code/community/BasicRum/Analytics/etc/system.xml'); + basicrum_assert_true($xml !== false, 'system configuration XML must parse'); + + $groups = $xml->sections->basicrum_analytics->groups; + $generalFields = $groups->general->fields; + $privacyFields = $groups->privacy->fields; + $waitFields = $groups->wait_after_onload->fields; + $developerFields = $groups->developer->fields; + + basicrum_assert_same( + array(), + basicrum_config_dependency_map($generalFields->boomerang_version, 'general'), + 'Boomerang version must remain visible while monitoring is disabled' + ); + basicrum_assert_same( + array(), + basicrum_config_dependency_map($generalFields->beacon_endpoint, 'general'), + 'Beacon URL must remain available for preconfiguration' + ); + basicrum_assert_same( + array(), + basicrum_config_dependency_map($generalFields->brum_site_id, 'general'), + 'Site ID must remain available for preconfiguration' + ); + + $generalEnabledOnly = array('general/enabled' => '1'); + basicrum_assert_same( + $generalEnabledOnly, + basicrum_config_dependency_map($privacyFields->strip_query_string, 'privacy'), + 'query-string privacy must depend on monitoring being enabled' + ); + basicrum_assert_same( + $generalEnabledOnly, + basicrum_config_dependency_map($privacyFields->opt_in_required, 'privacy'), + 'consent mode must depend on monitoring being enabled' + ); + basicrum_assert_same( + array( + 'general/enabled' => '1', + 'privacy/opt_in_required' => '1', + ), + basicrum_config_dependency_map($privacyFields->consent_integration_info, 'privacy'), + 'consent guidance must require both enabled monitoring and consent-controlled mode' + ); + basicrum_assert_same( + $generalEnabledOnly, + basicrum_config_dependency_map($waitFields->enabled, 'wait_after_onload'), + 'wait control must depend on monitoring being enabled' + ); + basicrum_assert_same( + array( + 'general/enabled' => '1', + 'wait_after_onload/enabled' => '1', + ), + basicrum_config_dependency_map($waitFields->wait_ms, 'wait_after_onload'), + 'wait duration must require both enabled monitoring and enabled waiting' + ); + basicrum_assert_same( + $generalEnabledOnly, + basicrum_config_dependency_map($developerFields->development_mode, 'developer'), + 'HTTP policy must depend on monitoring being enabled' + ); + basicrum_assert_same( + $generalEnabledOnly, + basicrum_config_dependency_map($developerFields->use_unminified_loaders, 'developer'), + 'loader debugging must depend on monitoring being enabled' + ); +}; + $tests['enabled incomplete configuration is visibly inactive'] = function () use ($root) { basicrum_test_reset(); diff --git a/tests/platform/bootstrap.php b/tests/platform/bootstrap.php index df4fc0f..57a28df 100644 --- a/tests/platform/bootstrap.php +++ b/tests/platform/bootstrap.php @@ -57,6 +57,23 @@ function basicrum_platform_assert_same($expected, $actual, $message) } } +function basicrum_platform_dependency_map($field, $defaultFieldset) +{ + $dependencies = array(); + + if (!isset($field->depends)) { + return $dependencies; + } + + foreach ($field->depends->children() as $dependency) { + $fieldset = isset($dependency->fieldset) ? (string) $dependency->fieldset : $defaultFieldset; + $value = isset($dependency->value) ? (string) $dependency->value : (string) $dependency; + $dependencies[$fieldset . '/' . $dependency->getName()] = $value; + } + + return $dependencies; +} + function basicrum_platform_save(array $values, $scope = 'default', $scopeId = 0) { foreach ($values as $path => $value) { diff --git a/tests/platform/verify.php b/tests/platform/verify.php index 23382ec..8eace37 100644 --- a/tests/platform/verify.php +++ b/tests/platform/verify.php @@ -78,6 +78,67 @@ 'Magento did not resolve the Basicrum HTTP policy source model' ); +$adminSection = Mage::getSingleton('adminhtml/config')->getSection('basicrum_analytics'); +basicrum_platform_assert($adminSection !== false, 'Magento did not merge the Basicrum admin configuration'); +$adminGroups = $adminSection->groups; +$generalFields = $adminGroups->general->fields; +$privacyFields = $adminGroups->privacy->fields; +$waitFields = $adminGroups->wait_after_onload->fields; +$developerFields = $adminGroups->developer->fields; +$generalEnabledOnly = array('general/enabled' => '1'); + +basicrum_platform_assert_same( + array(), + basicrum_platform_dependency_map($generalFields->beacon_endpoint, 'general'), + 'Beacon URL was hidden behind the module enabled state' +); +basicrum_platform_assert_same( + array(), + basicrum_platform_dependency_map($generalFields->brum_site_id, 'general'), + 'Site ID was hidden behind the module enabled state' +); +basicrum_platform_assert_same( + $generalEnabledOnly, + basicrum_platform_dependency_map($privacyFields->strip_query_string, 'privacy'), + 'query-string privacy does not depend on enabled monitoring' +); +basicrum_platform_assert_same( + $generalEnabledOnly, + basicrum_platform_dependency_map($privacyFields->opt_in_required, 'privacy'), + 'consent mode does not depend on enabled monitoring' +); +basicrum_platform_assert_same( + array( + 'general/enabled' => '1', + 'privacy/opt_in_required' => '1', + ), + basicrum_platform_dependency_map($privacyFields->consent_integration_info, 'privacy'), + 'consent guidance dependencies were not preserved by the native config parser' +); +basicrum_platform_assert_same( + $generalEnabledOnly, + basicrum_platform_dependency_map($waitFields->enabled, 'wait_after_onload'), + 'wait control does not depend on enabled monitoring' +); +basicrum_platform_assert_same( + array( + 'general/enabled' => '1', + 'wait_after_onload/enabled' => '1', + ), + basicrum_platform_dependency_map($waitFields->wait_ms, 'wait_after_onload'), + 'wait duration dependencies were not preserved by the native config parser' +); +basicrum_platform_assert_same( + $generalEnabledOnly, + basicrum_platform_dependency_map($developerFields->development_mode, 'developer'), + 'HTTP policy does not depend on enabled monitoring' +); +basicrum_platform_assert_same( + $generalEnabledOnly, + basicrum_platform_dependency_map($developerFields->use_unminified_loaders, 'developer'), + 'loader debugging does not depend on enabled monitoring' +); + $layoutFile = Mage::getConfig()->getNode('frontend/layout/updates/basicrumanalytics/file'); basicrum_platform_assert_same('basicrum_analytics.xml', (string) $layoutFile, 'frontend layout update is not registered'); From 63deb7d6464aa321e90036d89fbf6ed10956bc71 Mon Sep 17 00:00:00 2001 From: Tsvetan Stoychev Date: Thu, 17 Sep 2026 22:21:33 +0300 Subject: [PATCH 17/28] fix(admin): preserve wait dependency config path --- .github/copilot-instructions.md | 2 +- app/code/community/BasicRum/Analytics/etc/system.xml | 7 ++++--- tests/php/run.php | 9 +++++++-- tests/platform/verify.php | 9 +++++++-- 4 files changed, 19 insertions(+), 8 deletions(-) diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index e63156f..6f841a7 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -102,7 +102,7 @@ The block is added to the `before_body_end` reference in `basicrum_analytics.xml - `config.xml`: Module version, models, blocks, helpers, events. - `system.xml`: Backend configuration fields (ACL, Scope). - `adminhtml.xml`: Admin menu items and ACL resources. - - Keep Beacon Endpoint URL and BasicRUM Site ID visible while the module is disabled. Runtime-only privacy, wait, and developer fields use cross-group `system.xml` dependencies on `basicrum_analytics/general/enabled`; preserve those dependencies and Magento's scoped inheritance behavior. + - Keep Beacon Endpoint URL and BasicRUM Site ID visible while the module is disabled. Runtime-only privacy, wait, and developer fields use cross-group `system.xml` dependencies on `basicrum_analytics/general/enabled`; preserve those dependencies and Magento's scoped inheritance behavior. The wait toggle uses the unique admin field ID `wait_enabled` with `config_path` mapped to the established public path `basicrum_analytics/wait_after_onload/enabled`, avoiding duplicate dependency node names in Magento's merged XML. ## Important Patterns - **Helpers**: Always access helpers via `Mage::helper('basicrum_analytics')`. diff --git a/app/code/community/BasicRum/Analytics/etc/system.xml b/app/code/community/BasicRum/Analytics/etc/system.xml index 706a1f9..99644f3 100644 --- a/app/code/community/BasicRum/Analytics/etc/system.xml +++ b/app/code/community/BasicRum/Analytics/etc/system.xml @@ -133,10 +133,11 @@ 1 1 - + select adminhtml/system_config_source_yesno + basicrum_analytics/wait_after_onload/enabled 1 1 1 @@ -147,7 +148,7 @@ 1 - + text @@ -162,7 +163,7 @@
general
1 - 1 + 1
diff --git a/tests/php/run.php b/tests/php/run.php index ac109da..9755473 100644 --- a/tests/php/run.php +++ b/tests/php/run.php @@ -231,13 +231,18 @@ function basicrum_config_dependency_map(SimpleXMLElement $field, $defaultFieldse ); basicrum_assert_same( $generalEnabledOnly, - basicrum_config_dependency_map($waitFields->enabled, 'wait_after_onload'), + basicrum_config_dependency_map($waitFields->wait_enabled, 'wait_after_onload'), 'wait control must depend on monitoring being enabled' ); + basicrum_assert_same( + 'basicrum_analytics/wait_after_onload/enabled', + (string) $waitFields->wait_enabled->config_path, + 'wait control must retain the established public configuration path' + ); basicrum_assert_same( array( 'general/enabled' => '1', - 'wait_after_onload/enabled' => '1', + 'wait_after_onload/wait_enabled' => '1', ), basicrum_config_dependency_map($waitFields->wait_ms, 'wait_after_onload'), 'wait duration must require both enabled monitoring and enabled waiting' diff --git a/tests/platform/verify.php b/tests/platform/verify.php index 8eace37..e1ed598 100644 --- a/tests/platform/verify.php +++ b/tests/platform/verify.php @@ -117,13 +117,18 @@ ); basicrum_platform_assert_same( $generalEnabledOnly, - basicrum_platform_dependency_map($waitFields->enabled, 'wait_after_onload'), + basicrum_platform_dependency_map($waitFields->wait_enabled, 'wait_after_onload'), 'wait control does not depend on enabled monitoring' ); +basicrum_platform_assert_same( + 'basicrum_analytics/wait_after_onload/enabled', + (string) $waitFields->wait_enabled->config_path, + 'wait control did not retain its established public configuration path' +); basicrum_platform_assert_same( array( 'general/enabled' => '1', - 'wait_after_onload/enabled' => '1', + 'wait_after_onload/wait_enabled' => '1', ), basicrum_platform_dependency_map($waitFields->wait_ms, 'wait_after_onload'), 'wait duration dependencies were not preserved by the native config parser' From f8c4e2d5aa71ea87b5d34a2bb1dd9ed47634b99c Mon Sep 17 00:00:00 2001 From: Tsvetan Stoychev Date: Thu, 17 Sep 2026 22:29:03 +0300 Subject: [PATCH 18/28] feat(admin): complete settings parity refinements --- .github/copilot-instructions.md | 6 +- README.md | 20 +++- .../System/Config/Form/Field/ConsentInfo.php | 34 +++--- .../Config/Form/Field/RequiredSetting.php | 71 +++++++++--- .../Analytics/Block/Boomerang/Loader.php | 2 +- .../BasicRum/Analytics/Helper/Data.php | 4 +- .../Analytics/Helper/PageTypeDetector.php | 2 +- .../System/Config/Backend/BeaconEndpoint.php | 2 +- .../Model/System/Config/Backend/SiteId.php | 2 +- .../BasicRum/Analytics/etc/adminhtml.xml | 2 +- .../BasicRum/Analytics/etc/system.xml | 20 ++-- app/locale/en_US/BasicRum_Analytics.csv | 30 +++-- docs/admin-ui-parity-checklist.md | 49 +++++--- modman | 2 +- tests/check-package.sh | 14 +++ tests/php/run.php | 105 +++++++++++++++++- tests/platform/verify.php | 5 + 17 files changed, 276 insertions(+), 94 deletions(-) diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 6f841a7..4feecd9 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -1,7 +1,7 @@ -# GitHub Copilot Instructions for BasicRum Analytics (Magento 1) +# GitHub Copilot Instructions for Basicrum Analytics (Magento 1) ## Module Purpose -This module integrates **Boomerang.js** (Real User Monitoring) into Magento 1 stores to capture frontend performance analytics. It sends beacon data to a configurable endpoint for analysis via the BasicRUM platform. +This module integrates **Boomerang.js** (Real User Monitoring) into Magento 1 stores to capture frontend performance analytics. It sends beacon data to a configurable endpoint for analysis via the Basicrum platform. ### Key Features - **RUM Data Collection**: Captures page load timing, resource timing, and continuity metrics. @@ -102,7 +102,7 @@ The block is added to the `before_body_end` reference in `basicrum_analytics.xml - `config.xml`: Module version, models, blocks, helpers, events. - `system.xml`: Backend configuration fields (ACL, Scope). - `adminhtml.xml`: Admin menu items and ACL resources. - - Keep Beacon Endpoint URL and BasicRUM Site ID visible while the module is disabled. Runtime-only privacy, wait, and developer fields use cross-group `system.xml` dependencies on `basicrum_analytics/general/enabled`; preserve those dependencies and Magento's scoped inheritance behavior. The wait toggle uses the unique admin field ID `wait_enabled` with `config_path` mapped to the established public path `basicrum_analytics/wait_after_onload/enabled`, avoiding duplicate dependency node names in Magento's merged XML. + - Keep Beacon URL and Brum Site ID visible while the module is disabled. Runtime-only privacy, wait, and developer fields use cross-group `system.xml` dependencies on `basicrum_analytics/general/enabled`; preserve those dependencies and Magento's scoped inheritance behavior. The wait toggle uses the unique admin field ID `wait_enabled` with `config_path` mapped to the established public path `basicrum_analytics/wait_after_onload/enabled`, avoiding duplicate dependency node names in Magento's merged XML. ## Important Patterns - **Helpers**: Always access helpers via `Mage::helper('basicrum_analytics')`. diff --git a/README.md b/README.md index 18cbc44..e7c53b1 100644 --- a/README.md +++ b/README.md @@ -32,17 +32,19 @@ On Maho, place `js/basicrum` under `public/js/basicrum` and run `composer dump-a ## Configuration -Go to **System > Configuration > BasicRUM Analytics**. Configuration remains available at Magento's default, website, and store scopes. +Go to **System > Configuration > Basicrum > Basicrum Settings**. Configuration remains available at Magento's default, website, and store scopes. Monitoring scripts are emitted only when all of these conditions are met: -- **Enable** is set to Yes. -- **Beacon Endpoint URL** is a valid HTTP or HTTPS URL. -- **BasicRUM Site ID** is a valid RFC 4122 UUID v4. +- **Enable Basicrum** is set to Yes. +- **Beacon URL** is a valid HTTP or HTTPS URL. +- **Brum Site ID** is a valid RFC 4122 UUID v4. Both identity values are mandatory. Runtime validation is performed again when rendering, so missing, malformed, or programmatically injected values fail closed even if they bypass the admin backend models. Dynamic JavaScript values are JSON encoded with HTML-significant characters escaped. -When **Enable** is set to No, Magento keeps the bundled Boomerang version, Beacon Endpoint URL, and BasicRUM Site ID visible so an administrator can prepare or inspect the identity configuration before enabling monitoring. Privacy, wait, and developer runtime controls are hidden and disabled through Magento's native field dependencies. Their stored default, website, and store-view values are retained and reappear when monitoring is enabled; normal scope inheritance and **Use Default/Use Website** behavior are unchanged. +The status panel reports whether monitoring is Disabled, Blocked by invalid or incomplete identity configuration, Waiting for consent, or Active in immediate mode. + +When **Enable Basicrum** is set to No, Magento keeps the bundled Boomerang version, Beacon URL, and Brum Site ID visible so an administrator can prepare or inspect the identity configuration before enabling monitoring. Privacy, wait, and developer runtime controls are hidden and disabled through Magento's native field dependencies. Their stored default, website, and store-view values are retained and reappear when monitoring is enabled; normal scope inheritance and **Use Default/Use Website** behavior are unchanged. HTTPS Beacon URLs are enforced by default. The Developer setting **HTTP Strictness** can allow HTTP only for local testing; do not enable it on production stores. When strict mode is active, an HTTP URL saved through the admin is upgraded to HTTPS, and runtime rendering applies the same upgrade to values injected outside the admin path. @@ -50,7 +52,7 @@ HTTPS Beacon URLs are enforced by default. The Developer setting **HTTP Strictne **Strip Query Strings** controls Boomerang's native URL redaction. It remains disabled by default to preserve the established Magento 1 behavior and match the WordPress default. When enabled, complete query strings in page, navigation, referrer, and resource URLs are replaced with `?qs-redacted` before beacons are sent; URL paths remain available for performance analysis. -This setting does not modify query parameters in the configured Beacon Endpoint URL. Those parameters are part of the collector destination and continue to be safely serialized unchanged. +This setting does not modify query parameters in the configured Beacon URL. Those parameters are part of the collector destination and continue to be safely serialized unchanged. ### Consent-controlled loading @@ -110,6 +112,12 @@ basicrum_analytics/wait_after_onload/wait_ms Values are clamped to 0–30000 milliseconds. The older mismatched `ms` default key is no longer used. +### Magento-specific administrator and script behavior + +WordPress can exclude logged-in users with the `manage_options` capability because its administrators and storefront visitors share the same user system. Magento admin users authenticate in the separate `adminhtml` application and do not have a reliable frontend identity. Basicrum is not emitted on Magento admin pages, and a backend user visiting the storefront is indistinguishable from any other storefront visitor without initializing an admin session in the frontend. For that reason Magento 1 does not expose a misleading **Track Admin Users** setting. Stores that need staff-traffic exclusion should use collector-side rules or a separately designed frontend signal. + +Magento inserts the configuration and async loader in the native `before_body_end` layout reference. This is the documented, fixed equivalent of WordPress's default footer placement. A Header/Footer selector is intentionally not provided: moving the consent loader to the header would alter registration timing and could start immediate-mode downloads earlier, while Magento themes do not provide a single portable header insertion point equivalent to WordPress's `wp_head`. + ## Page type compatibility Magento 1 continues to emit its existing `p_type` values in this phase (for example, `Home`, `Product`, and `404 Not Found`). These values are not schema-compatible with the current WordPress and Magento 2 values. They are intentionally unchanged to avoid breaking existing Magento 1 reporting; normalization requires a later coordinated schema-migration phase. diff --git a/app/code/community/BasicRum/Analytics/Block/Adminhtml/System/Config/Form/Field/ConsentInfo.php b/app/code/community/BasicRum/Analytics/Block/Adminhtml/System/Config/Form/Field/ConsentInfo.php index 2339b67..6deb12e 100644 --- a/app/code/community/BasicRum/Analytics/Block/Adminhtml/System/Config/Form/Field/ConsentInfo.php +++ b/app/code/community/BasicRum/Analytics/Block/Adminhtml/System/Config/Form/Field/ConsentInfo.php @@ -36,40 +36,40 @@ public function render(Varien_Data_Form_Element_Abstract $element): string return << -
+
JavaScript API for Cookie Consent Integration

In consent-controlled mode, Basicrum stays inert until your external consent tool explicitly allows performance monitoring on the current page. Basicrum does not store or infer a consent decision. Call the API after this loader has registered the callbacks near the end of the page; calls made before registration are not replayed.

- - - - - - - - - -
OPT_IN_BASICRUM_LOADER_WRAPPER()Call when the external tool reports that monitoring is allowed.
OPT_OUT_BASICRUM_LOADER_WRAPPER()Call when monitoring is denied or withdrawn. This disables future collection and removes RT, BA, and legacy Basicrum consent cookies, but it cannot retract data already sent.
+
+

+ OPT_IN_BASICRUM_LOADER_WRAPPER() + Call when the external tool reports that monitoring is allowed. +

+

+ OPT_OUT_BASICRUM_LOADER_WRAPPER() + Call when monitoring is denied or withdrawn. This disables future collection and removes RT, BA, and legacy Basicrum consent cookies, but it cannot retract data already sent. +

+

OPT_IN_BASIC_RUM() and OPT_OUT_BASIC_RUM() remain available as backward-compatible Magento 1 aliases.

A deny before the first opt-in can be followed by an allow on the same page. After monitoring has started and consent is withdrawn, reload the page before re-granting; monitoring remains disabled for the rest of that page view.

Connect both decisions: place the allow snippet only in your consent tool's allow or grant callback, and the deny snippet in its deny, expiry, or withdrawal callback. Do not run the two snippets together.

- -

+

- +

- -

+

- +

diff --git a/app/code/community/BasicRum/Analytics/Block/Adminhtml/System/Config/Form/Field/RequiredSetting.php b/app/code/community/BasicRum/Analytics/Block/Adminhtml/System/Config/Form/Field/RequiredSetting.php index a3bd916..8c45ea9 100644 --- a/app/code/community/BasicRum/Analytics/Block/Adminhtml/System/Config/Form/Field/RequiredSetting.php +++ b/app/code/community/BasicRum/Analytics/Block/Adminhtml/System/Config/Form/Field/RequiredSetting.php @@ -19,9 +19,10 @@ class BasicRum_Analytics_Block_Adminhtml_System_Config_Form_Field_RequiredSettin private const ENABLED_FIELD_ID = 'basicrum_analytics_general_enabled'; private const BEACON_FIELD_ID = 'basicrum_analytics_general_beacon_endpoint'; private const SITE_ID_FIELD_ID = 'basicrum_analytics_general_brum_site_id'; + private const CONSENT_FIELD_ID = 'basicrum_analytics_privacy_opt_in_required'; /** - * Render the native field row and a page-level warning after the Site ID. + * Render the native field row and monitoring status after the Site ID. * * @param Varien_Data_Form_Element_Abstract $element * @return string @@ -30,14 +31,11 @@ public function render(Varien_Data_Form_Element_Abstract $element): string { $html = parent::render($element); - if (!$this->isSiteIdElement($element) - || !$this->isMonitoringEnabled($element) - || $this->hasValidRequiredSettings($element) - ) { + if (!$this->isSiteIdElement($element)) { return $html; } - return $html . $this->getConfigurationWarningHtml(); + return $html . $this->getMonitoringStatusHtml($element); } /** @@ -93,13 +91,13 @@ private function getValidationMessage(Varien_Data_Form_Element_Abstract $element if ($this->isBeaconElement($element)) { if ($value === '') { return Mage::helper('basicrum_analytics')->__( - 'Beacon Endpoint URL is required while monitoring is enabled. Monitoring remains inactive.' + 'Beacon URL is required while monitoring is enabled. Monitoring remains inactive.' ); } if (!BasicRum_Analytics_Helper_Data::isValidBeaconEndpoint($value)) { return Mage::helper('basicrum_analytics')->__( - 'Enter a valid HTTP or HTTPS Beacon Endpoint URL. Monitoring remains inactive.' + 'Enter a valid HTTP or HTTPS Beacon URL. Monitoring remains inactive.' ); } } @@ -107,13 +105,13 @@ private function getValidationMessage(Varien_Data_Form_Element_Abstract $element if ($this->isSiteIdElement($element)) { if ($value === '') { return Mage::helper('basicrum_analytics')->__( - 'BasicRUM Site ID is required while monitoring is enabled. Monitoring remains inactive.' + 'Brum Site ID is required while monitoring is enabled. Monitoring remains inactive.' ); } if (!BasicRum_Analytics_Helper_Data::isValidBrumSiteId($value)) { return Mage::helper('basicrum_analytics')->__( - 'Enter a valid UUID v4 BasicRUM Site ID. Monitoring remains inactive.' + 'Enter a valid UUID v4 Brum Site ID. Monitoring remains inactive.' ); } } @@ -155,6 +153,19 @@ private function hasValidRequiredSettings(Varien_Data_Form_Element_Abstract $ele && BasicRum_Analytics_Helper_Data::isValidBrumSiteId($siteId); } + /** + * @param Varien_Data_Form_Element_Abstract $element + * @return bool + */ + private function isConsentRequired(Varien_Data_Form_Element_Abstract $element): bool + { + return (string) $this->getFormValue( + $element, + self::CONSENT_FIELD_ID, + 'basicrum_analytics/privacy/opt_in_required' + ) === '1'; + } + /** * Read the resolved form value so Website and Store View inheritance works. * @@ -205,19 +216,47 @@ private function hasIdSuffix(string $value, string $suffix): bool } /** + * @param Varien_Data_Form_Element_Abstract $element * @return string */ - private function getConfigurationWarningHtml(): string + private function getMonitoringStatusHtml(Varien_Data_Form_Element_Abstract $element): string { - $message = Mage::helper('basicrum_analytics')->__( - 'Basicrum monitoring is enabled but inactive. Monitoring scripts are not emitted until both required fields contain valid values.' - ); + $helper = Mage::helper('basicrum_analytics'); + + if (!$this->isMonitoringEnabled($element)) { + $heading = $helper->__('Monitoring status: Disabled'); + $message = $helper->__('Basicrum is disabled. No monitoring scripts are emitted.'); + $background = '#f5f5f5'; + $border = '#777777'; + } elseif (!$this->hasValidRequiredSettings($element)) { + $heading = $helper->__('Monitoring status: Blocked'); + $message = $helper->__( + 'Basicrum monitoring is enabled but inactive. Monitoring scripts are not emitted until both required fields contain valid values.' + ); + $background = '#fff9e6'; + $border = '#eb5202'; + } elseif ($this->isConsentRequired($element)) { + $heading = $helper->__('Monitoring status: Waiting for consent'); + $message = $helper->__( + 'Basicrum is configured. Boomerang loads only after the external consent tool explicitly allows monitoring on the current page.' + ); + $background = '#eef5ff'; + $border = '#1976d2'; + } else { + $heading = $helper->__('Monitoring status: Active'); + $message = $helper->__( + 'Basicrum monitoring starts immediately on storefront pages without waiting for consent.' + ); + $background = '#edf7ed'; + $border = '#2e7d32'; + } return '' . '' . '
' - . '' . htmlspecialchars($message, ENT_QUOTES, 'UTF-8') . '' + . 'background: ' . $background . '; border-left: 4px solid ' . $border . ';">' + . '' . htmlspecialchars($heading, ENT_QUOTES, 'UTF-8') . '' + . '
' . htmlspecialchars($message, ENT_QUOTES, 'UTF-8') . '
' . '
'; } } diff --git a/app/code/community/BasicRum/Analytics/Block/Boomerang/Loader.php b/app/code/community/BasicRum/Analytics/Block/Boomerang/Loader.php index 769e3d6..81dae05 100644 --- a/app/code/community/BasicRum/Analytics/Block/Boomerang/Loader.php +++ b/app/code/community/BasicRum/Analytics/Block/Boomerang/Loader.php @@ -2,7 +2,7 @@ declare(strict_types=1); /** - * BasicRUM Analytics Boomerang Loader Block + * Basicrum Analytics Boomerang Loader Block */ class BasicRum_Analytics_Block_Boomerang_Loader extends Mage_Core_Block_Abstract { diff --git a/app/code/community/BasicRum/Analytics/Helper/Data.php b/app/code/community/BasicRum/Analytics/Helper/Data.php index 38ee1e2..42cc2a5 100644 --- a/app/code/community/BasicRum/Analytics/Helper/Data.php +++ b/app/code/community/BasicRum/Analytics/Helper/Data.php @@ -2,7 +2,7 @@ declare(strict_types=1); /** - * BasicRum Analytics Helper + * Basicrum Analytics Helper */ class BasicRum_Analytics_Helper_Data extends Mage_Core_Helper_Abstract { @@ -62,7 +62,7 @@ public function getBeaconEndpoint() } /** - * Get the BasicRUM Site ID + * Get the Brum Site ID * @return string|null */ public function getBrumSiteId() diff --git a/app/code/community/BasicRum/Analytics/Helper/PageTypeDetector.php b/app/code/community/BasicRum/Analytics/Helper/PageTypeDetector.php index a7c56c1..f0c5fb6 100644 --- a/app/code/community/BasicRum/Analytics/Helper/PageTypeDetector.php +++ b/app/code/community/BasicRum/Analytics/Helper/PageTypeDetector.php @@ -2,7 +2,7 @@ declare(strict_types=1); /** - * BasicRum Analytics Page Type Detector Helper + * Basicrum Analytics Page Type Detector Helper */ class BasicRum_Analytics_Helper_PageTypeDetector extends Mage_Core_Helper_Abstract { diff --git a/app/code/community/BasicRum/Analytics/Model/System/Config/Backend/BeaconEndpoint.php b/app/code/community/BasicRum/Analytics/Model/System/Config/Backend/BeaconEndpoint.php index cf3bc29..2a6135d 100644 --- a/app/code/community/BasicRum/Analytics/Model/System/Config/Backend/BeaconEndpoint.php +++ b/app/code/community/BasicRum/Analytics/Model/System/Config/Backend/BeaconEndpoint.php @@ -18,7 +18,7 @@ protected function _beforeSave() if ($value !== '' && !BasicRum_Analytics_Helper_Data::isValidBeaconEndpoint($value)) { Mage::throwException( - Mage::helper('basicrum_analytics')->__('Beacon Endpoint URL must be a valid HTTP or HTTPS URL.') + Mage::helper('basicrum_analytics')->__('Beacon URL must be a valid HTTP or HTTPS URL.') ); } diff --git a/app/code/community/BasicRum/Analytics/Model/System/Config/Backend/SiteId.php b/app/code/community/BasicRum/Analytics/Model/System/Config/Backend/SiteId.php index 4e89767..679f770 100644 --- a/app/code/community/BasicRum/Analytics/Model/System/Config/Backend/SiteId.php +++ b/app/code/community/BasicRum/Analytics/Model/System/Config/Backend/SiteId.php @@ -18,7 +18,7 @@ protected function _beforeSave() if ($value !== '' && !BasicRum_Analytics_Helper_Data::isValidBrumSiteId($value)) { Mage::throwException( - Mage::helper('basicrum_analytics')->__('BasicRUM Site ID must be a valid UUID (e.g. e926c1a2-7e33-4f54-90d0-e6e31f3ad43d).') + Mage::helper('basicrum_analytics')->__('Brum Site ID must be a valid UUID v4 (e.g. e926c1a2-7e33-4f54-90d0-e6e31f3ad43d).') ); } diff --git a/app/code/community/BasicRum/Analytics/etc/adminhtml.xml b/app/code/community/BasicRum/Analytics/etc/adminhtml.xml index 3994d85..683b6a8 100644 --- a/app/code/community/BasicRum/Analytics/etc/adminhtml.xml +++ b/app/code/community/BasicRum/Analytics/etc/adminhtml.xml @@ -9,7 +9,7 @@ - BasicRum Analytics + Basicrum Settings diff --git a/app/code/community/BasicRum/Analytics/etc/system.xml b/app/code/community/BasicRum/Analytics/etc/system.xml index 99644f3..4b15420 100644 --- a/app/code/community/BasicRum/Analytics/etc/system.xml +++ b/app/code/community/BasicRum/Analytics/etc/system.xml @@ -2,13 +2,13 @@ - + 9999 - + basicrum_analytics text 100 @@ -23,10 +23,10 @@ 1 1 1 - BasicRUM - Open Source Real User Monitoring system - https://www.basicrum.com/]]> + Basicrum — Real User Monitoring
Configure the collector identity and monitoring state for this scope. Visit basicrum.com]]>
- + select adminhtml/system_config_source_yesno 0 @@ -35,7 +35,7 @@ 1 - + select basicrum_analytics/system_config_source_version 1 @@ -45,7 +45,7 @@ disabled - + text basicrum_analytics/adminhtml_system_config_form_field_requiredSetting basicrum_analytics/system_config_backend_beaconEndpoint @@ -53,10 +53,10 @@ 1 1 1 - Required. HTTPS is enforced unless HTTP Strictness explicitly allows HTTP for local testing. Example: https://www.example.com/beacon/catcher + URL where Boomerang beacons are sent. Required when Basicrum is enabled. HTTPS is enforced unless HTTP Strictness allows HTTP for local testing. Example: https://www.example.com/beacon/catcher - + text basicrum_analytics/adminhtml_system_config_form_field_requiredSetting basicrum_analytics/system_config_backend_siteId @@ -64,7 +64,7 @@ 1 1 1 - Example: e926c1a2-7e33-4f54-90d0-e6e31f3ad43d]]> + Example: e926c1a2-7e33-4f54-90d0-e6e31f3ad43d]]> @@ -84,7 +84,7 @@ 1 1 1 - When enabled, complete query strings in page, navigation, referrer, and resource URLs are replaced with ?qs-redacted before beacons are sent. URL paths are still collected. Beacon Endpoint URL parameters are not changed. + When enabled, complete query strings in page, navigation, referrer, and resource URLs are replaced with ?qs-redacted before beacons are sent. URL paths are still collected. Beacon URL parameters are not changed.
general
diff --git a/app/locale/en_US/BasicRum_Analytics.csv b/app/locale/en_US/BasicRum_Analytics.csv index a5fbe3f..ce47186 100644 --- a/app/locale/en_US/BasicRum_Analytics.csv +++ b/app/locale/en_US/BasicRum_Analytics.csv @@ -1,11 +1,10 @@ -"BasicRum","BasicRum" -"Analytics","Analytics" -"Analytics Configuration","Analytics Configuration" +"Basicrum","Basicrum" +"Basicrum Settings","Basicrum Settings" "General Settings","General Settings" -"Enable Analytics","Enable Analytics" -"Beacon Endpoint URL","Beacon Endpoint URL" -"BasicRUM Site ID","BasicRUM Site ID" -"Enter the URL where analytics data will be sent","Enter the URL where analytics data will be sent" +"Enable Basicrum","Enable Basicrum" +"Boomerang Version","Boomerang Version" +"Beacon URL","Beacon URL" +"Brum Site ID","Brum Site ID" "Data Privacy / GDPR","Data Privacy / GDPR" "Require Consent Before Monitoring","Require Consent Before Monitoring" "Strip Query Strings","Strip Query Strings" @@ -18,8 +17,17 @@ "Developer","Developer" "Use Unminified Loaders","Use Unminified Loaders" "Enable to load non-minified loader scripts for debugging purposes.","Enable to load non-minified loader scripts for debugging purposes." -"Beacon Endpoint URL is required while monitoring is enabled. Monitoring remains inactive.","Beacon Endpoint URL is required while monitoring is enabled. Monitoring remains inactive." -"Enter a valid HTTP or HTTPS Beacon Endpoint URL. Monitoring remains inactive.","Enter a valid HTTP or HTTPS Beacon Endpoint URL. Monitoring remains inactive." -"BasicRUM Site ID is required while monitoring is enabled. Monitoring remains inactive.","BasicRUM Site ID is required while monitoring is enabled. Monitoring remains inactive." -"Enter a valid UUID v4 BasicRUM Site ID. Monitoring remains inactive.","Enter a valid UUID v4 BasicRUM Site ID. Monitoring remains inactive." +"Beacon URL is required while monitoring is enabled. Monitoring remains inactive.","Beacon URL is required while monitoring is enabled. Monitoring remains inactive." +"Enter a valid HTTP or HTTPS Beacon URL. Monitoring remains inactive.","Enter a valid HTTP or HTTPS Beacon URL. Monitoring remains inactive." +"Brum Site ID is required while monitoring is enabled. Monitoring remains inactive.","Brum Site ID is required while monitoring is enabled. Monitoring remains inactive." +"Enter a valid UUID v4 Brum Site ID. Monitoring remains inactive.","Enter a valid UUID v4 Brum Site ID. Monitoring remains inactive." +"Monitoring status: Disabled","Monitoring status: Disabled" +"Basicrum is disabled. No monitoring scripts are emitted.","Basicrum is disabled. No monitoring scripts are emitted." +"Monitoring status: Blocked","Monitoring status: Blocked" "Basicrum monitoring is enabled but inactive. Monitoring scripts are not emitted until both required fields contain valid values.","Basicrum monitoring is enabled but inactive. Monitoring scripts are not emitted until both required fields contain valid values." +"Monitoring status: Waiting for consent","Monitoring status: Waiting for consent" +"Basicrum is configured. Boomerang loads only after the external consent tool explicitly allows monitoring on the current page.","Basicrum is configured. Boomerang loads only after the external consent tool explicitly allows monitoring on the current page." +"Monitoring status: Active","Monitoring status: Active" +"Basicrum monitoring starts immediately on storefront pages without waiting for consent.","Basicrum monitoring starts immediately on storefront pages without waiting for consent." +"Beacon URL must be a valid HTTP or HTTPS URL.","Beacon URL must be a valid HTTP or HTTPS URL." +"Brum Site ID must be a valid UUID v4 (e.g. e926c1a2-7e33-4f54-90d0-e6e31f3ad43d).","Brum Site ID must be a valid UUID v4 (e.g. e926c1a2-7e33-4f54-90d0-e6e31f3ad43d)." diff --git a/docs/admin-ui-parity-checklist.md b/docs/admin-ui-parity-checklist.md index aca72a2..f211d0c 100644 --- a/docs/admin-ui-parity-checklist.md +++ b/docs/admin-ui-parity-checklist.md @@ -81,7 +81,7 @@ Legend: - [x] Disable or hide irrelevant dependent controls when the module is disabled. - Magento's native field dependencies hide and disable privacy, wait, and developer runtime controls. Stored scoped values remain intact. - - Boomerang version, Beacon Endpoint URL, and BasicRUM Site ID stay visible so + - Boomerang version, Beacon URL, and Brum Site ID stay visible so administrators can inspect or prepare identity configuration before enabling. - [x] Reveal Wait After Onload milliseconds only when Wait After Onload is enabled. - [x] Hide consent-specific controls when the module itself is disabled. @@ -90,25 +90,38 @@ Legend: ## Remaining WordPress controls -- [ ] Decide whether Track Admin Users has a meaningful Magento 1 equivalent and - implement it if applicable. +- [x] Resolve Track Admin Users as an intentional platform difference. + - WordPress can identify a logged-in frontend user with the `manage_options` + capability. Magento authenticates backend users in the separate `adminhtml` + application and does not expose a reliable admin identity on storefront + requests. Basicrum never runs on admin pages, and initializing the admin + session in the frontend solely for tracking exclusion would add coupling and + session risk. No misleading Magento setting is added; collector-side staff + exclusion or a future explicit frontend signal remains available for stores + that require it. - [x] Add an explicit development-only HTTP policy. - HTTPS is enforced by default. HTTP requires a scoped, clearly labeled local testing option, and legacy HTTP/HTTPS endpoints retain their behavior through a versioned scope-preserving upgrade policy. -- [ ] Review Script Position as a behavioral requirement. Do not add a Header/Footer - selector solely for visual parity: Magento's layout placement and runtime timing - differ from WordPress. +- [x] Keep Script Position fixed at Magento's native `before_body_end` reference. + - This matches WordPress's safe default footer behavior without pretending that + Magento themes provide a portable `wp_head` equivalent. Moving consent mode + earlier would also change callback-registration timing, so no selector is + added without a separate behavioral requirement. ## Presentation and discoverability -- [ ] Align product casing and field terminology across implementations: - - `Basicrum` versus `BasicRUM` - - `Beacon URL` versus `Beacon Endpoint URL` - - `Brum Site ID` versus `BasicRUM Site ID` -- [ ] Give the Magento configuration page a clearer Basicrum identity while +- [x] Align product casing and field terminology with WordPress. + - User-facing Magento copy now consistently uses `Basicrum`, `Beacon URL`, and + `Brum Site ID`; internal `BasicRum_Analytics` class and module identifiers are + retained for backward compatibility. +- [x] Give the Magento configuration page a clearer Basicrum identity while retaining native Magento administration patterns. -- [ ] Improve complex help content for narrower admin viewports. + - The native tab and page are labeled Basicrum and Basicrum Settings, and the + General Settings introduction identifies the product and configuration scope. +- [x] Improve complex help content for narrower admin viewports. + - Long callback names wrap, code fields remain within the available width, and + copy controls wrap without changing Magento's native configuration layout. - [ ] Replace `docs/media/admin-area.png` after the admin UI work is complete; the checked-in screenshot no longer represents the current settings UI. @@ -145,19 +158,19 @@ Legend: ### P2 — refinement -- [ ] Resolve Track Admin Users applicability. -- [ ] Align terminology and branding. -- [ ] Review narrow-viewport presentation. +- [x] Resolve Track Admin Users applicability. +- [x] Align terminology and branding. +- [x] Review narrow-viewport presentation. - [ ] Update the admin screenshot after the UI stabilizes. ## Completion criteria -- [ ] A new administrator can tell whether monitoring is active, inactive, or - blocked by incomplete configuration without reading source code. +- [x] A new administrator can tell whether monitoring is active, disabled, waiting + for consent, or blocked by incomplete configuration without reading source code. - [x] Consent-controlled mode clearly explains what the external consent tool must do and shows only relevant instructions. - [x] Immediate mode does not display consent-integration instructions. - [x] Required configuration errors are visible at the affected fields. - [x] Magento configuration scopes continue to work at all supported levels. -- [ ] Platform-specific differences are documented and intentional. +- [x] Platform-specific differences are documented and intentional. - [ ] Updated screenshots match the shipped admin UI. diff --git a/modman b/modman index e3e8bd8..70ab209 100644 --- a/modman +++ b/modman @@ -1,4 +1,4 @@ -# BasicRum Analytics Module for Magento 1 +# Basicrum Analytics Module for Magento 1 # This Modman file maps all the module files to their correct locations in Magento # Module declaration file diff --git a/tests/check-package.sh b/tests/check-package.sh index 277492d..45a2f0c 100644 --- a/tests/check-package.sh +++ b/tests/check-package.sh @@ -63,6 +63,20 @@ if grep -R --line-number '' app/code/community/BasicRum/Analytics/etc; then exit 1 fi +terminology_paths=( + README.md + docs + app/code/community/BasicRum/Analytics/Block/Adminhtml + app/code/community/BasicRum/Analytics/Model/System/Config/Backend + app/code/community/BasicRum/Analytics/etc/system.xml + app/code/community/BasicRum/Analytics/etc/adminhtml.xml + app/locale/en_US/BasicRum_Analytics.csv +) +if grep -R --line-number -E 'BasicRUM|Beacon Endpoint URL' "${terminology_paths[@]}"; then + echo "Stale user-facing Basicrum terminology found" >&2 + exit 1 +fi + package_tmp_dir="$(mktemp -d -t basicrum-magento-1.XXXXXX)" archive_path="$package_tmp_dir/basicrum-magento-1.zip" trap 'rm -f "$archive_path"; rmdir "$package_tmp_dir"' EXIT diff --git a/tests/php/run.php b/tests/php/run.php index 9755473..6428158 100644 --- a/tests/php/run.php +++ b/tests/php/run.php @@ -127,6 +127,21 @@ function basicrum_config_dependency_map(SimpleXMLElement $field, $defaultFieldse $html, 'guidance must load the copy-action behavior from the Magento JS base URL' ); + basicrum_assert_contains( + 'overflow-wrap: anywhere', + $html, + 'long callback names must wrap on narrow admin viewports' + ); + basicrum_assert_contains( + 'max-width: 100%', + $html, + 'callback snippets must stay within the available width' + ); + basicrum_assert_not_contains( + 'white-space: nowrap', + $html, + 'consent guidance must not force callback names beyond narrow viewports' + ); $allowStart = strpos($html, '

@@ -55,7 +55,7 @@ public function render(Varien_Data_Form_Element_Abstract $element): string

-

diff --git a/tests/js/admin-consent-info.spec.js b/tests/js/admin-consent-info.spec.js index a2af9e0..495c1f4 100644 --- a/tests/js/admin-consent-info.spec.js +++ b/tests/js/admin-consent-info.spec.js @@ -1,8 +1,30 @@ +const fs = require("node:fs"); const path = require("node:path"); const { test, expect } = require("@playwright/test"); const scriptPath = path.resolve(__dirname, "../../js/basicrum/admin/consent-info.js"); +for (const themeHeight of ["auto", "2em"]) { + test(`callback textareas show five lines with theme height ${themeHeight}`, async ({ page }) => { + const renderer = fs.readFileSync(path.resolve(__dirname, + "../../app/code/community/BasicRum/Analytics/Block/Adminhtml/System/Config/Form/Field/ConsentInfo.php"), "utf8"); + const snippets = renderer.match(/]*>[\s\S]*?<\/textarea>/g); + expect(snippets).toHaveLength(2); + await page.setContent(`${snippets.join("\n")}`); + + for (const textarea of await page.locator("textarea").all()) { + await expect(textarea).toHaveAttribute("rows", "5"); + await expect(textarea).toHaveCSS("resize", "vertical"); + const visibleLines = await textarea.evaluate((element) => { + const style = getComputedStyle(element); + return (element.clientHeight - parseFloat(style.paddingTop) - parseFloat(style.paddingBottom)) + / parseFloat(style.lineHeight); + }); + expect(visibleLines).toBeGreaterThanOrEqual(5); + } + }); +} + async function renderConsentExamples(page) { await page.setContent(` diff --git a/tests/php/run.php b/tests/php/run.php index 3d49743..bfcfa36 100644 --- a/tests/php/run.php +++ b/tests/php/run.php @@ -170,6 +170,11 @@ function basicrum_config_dependency_map(SimpleXMLElement $field, $defaultFieldse basicrum_assert_true($allowStart !== false && $denyStart !== false, 'both callback snippets must render'); $allowSnippet = substr($html, $allowStart, strpos($html, '', $allowStart) - $allowStart); $denySnippet = substr($html, $denyStart, strpos($html, '', $denyStart) - $denyStart); + foreach (array($allowSnippet, $denySnippet) as $snippet) { + basicrum_assert_contains('rows="5"', $snippet, 'each callback textarea must show five rows'); + basicrum_assert_contains('min-height: 100px', $snippet, 'admin theme styles must not shrink callback textareas'); + basicrum_assert_contains('resize: vertical', $snippet, 'callback textareas must remain vertically resizable'); + } basicrum_assert_contains( 'OPT_IN_BASICRUM_LOADER_WRAPPER', $allowSnippet, From d3b25c5bd9e755d08d9a3c7f6425282a8826401c Mon Sep 17 00:00:00 2001 From: Tsvetan Stoychev Date: Sun, 20 Sep 2026 11:23:30 +0300 Subject: [PATCH 27/28] ci: publish tested Magento release archives on version tags --- .github/workflows/ci.yml | 44 ++++++++++++++++++- .github/workflows/release.yml | 52 ++++++++++++++++++++++ .gitignore | 1 + README.md | 66 +++++++++++++++++++++++++++- tests/check-package.sh | 38 ++-------------- tests/platform/deploy-module.sh | 9 ++++ tests/release/package.sh | 77 +++++++++++++++++++++++++++++++++ tests/release/version.test.js | 57 ++++++++++++++++++++++++ tools/build-release.sh | 37 ++++++++++++++++ tools/package-files.sh | 45 +++++++++++++++++++ tools/release-version.js | 43 ++++++++++++++++++ tools/verify-release.sh | 40 +++++++++++++++++ 12 files changed, 471 insertions(+), 38 deletions(-) create mode 100644 .github/workflows/release.yml create mode 100644 tests/release/package.sh create mode 100644 tests/release/version.test.js create mode 100644 tools/build-release.sh create mode 100644 tools/package-files.sh create mode 100644 tools/release-version.js create mode 100644 tools/verify-release.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bbc0bd9..a875a77 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,7 +2,17 @@ name: CI on: push: + tags-ignore: + - 'v*.*.*' # Version tags run this workflow through release.yml. pull_request: + workflow_call: + inputs: + release_tag: + type: string + default: '' + outputs: + archive_name: + value: ${{ jobs.browser-and-package.outputs.archive_name }} permissions: contents: read @@ -29,6 +39,8 @@ jobs: browser-and-package: name: Browser and package checks runs-on: ubuntu-latest + outputs: + archive_name: ${{ steps.package.outputs.archive_name }} steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 @@ -45,9 +57,31 @@ jobs: run: sudo apt-get update && sudo apt-get install -y libxml2-utils zip unzip - name: XML and package checks run: bash tests/check-package.sh + - name: Release tooling regression tests + run: | + node --test tests/release/version.test.js + bash tests/release/package.sh + - name: Build installable release ZIP + id: package + env: + BASICRUM_RELEASE_TAG: ${{ inputs.release_tag }} + run: | + version="$(node tools/release-version.js)" + bash tools/build-release.sh + echo "archive_name=basicrum-magento-1-$version.zip" >> "$GITHUB_OUTPUT" + - name: Upload candidate ZIP and checksum + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: basicrum-magento-1-release + path: | + release/*.zip + release/*.zip.sha256 + if-no-files-found: error + retention-days: 14 platform-matrix: name: ${{ matrix.name }} + needs: browser-and-package runs-on: ubuntu-latest timeout-minutes: 20 strategy: @@ -91,5 +125,13 @@ jobs: php-version: ${{ matrix.php }} coverage: none extensions: ctype, curl, dom, ftp, gd, iconv, intl, mbstring, mysqli, pdo_mysql, simplexml, soap, zip - - name: Install and verify module on ${{ matrix.name }} + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: basicrum-magento-1-release + path: release + - name: Install release verification tools + run: sudo apt-get update && sudo apt-get install -y libxml2-utils unzip + - name: Install and verify packaged module on ${{ matrix.name }} + env: + BASICRUM_TEST_RELEASE_ZIP: ${{ github.workspace }}/release/${{ needs.browser-and-package.outputs.archive_name }} run: bash tests/platform/run.sh "${{ matrix.platform }}" "$GITHUB_WORKSPACE/platform" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..5510f3b --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,52 @@ +name: Release Extension + +on: + push: + tags: + - 'v*.*.*' + +permissions: + contents: read + +concurrency: + group: release-${{ github.ref }} + cancel-in-progress: false + +jobs: + checks: + name: Test the tagged release + uses: ./.github/workflows/ci.yml + with: + release_tag: ${{ github.ref_name }} + + publish: + name: Publish the tested ZIP + needs: checks + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1 + with: + persist-credentials: false + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: basicrum-magento-1-release + path: release + - name: Install verification tools + run: sudo apt-get update && sudo apt-get install -y libxml2-utils unzip + - name: Recheck the tested archive without rebuilding + env: + ARCHIVE_NAME: ${{ needs.checks.outputs.archive_name }} + run: bash tools/verify-release.sh "release/$ARCHIVE_NAME" + - name: Create GitHub release and attach assets + uses: softprops/action-gh-release@3d0d9888cb7fd7b750713d6e236d1fcb99157228 # v3.0.2 + with: + tag_name: ${{ github.ref_name }} + generate_release_notes: true + prerelease: ${{ contains(github.ref_name, '-') }} + make_latest: ${{ contains(github.ref_name, '-') && 'false' || 'legacy' }} + fail_on_unmatched_files: true + files: | + release/${{ needs.checks.outputs.archive_name }} + release/${{ needs.checks.outputs.archive_name }}.sha256 diff --git a/.gitignore b/.gitignore index 1fa5c52..a58e2e4 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ /node_modules/ /.test-results/ /playwright-report/ +/release/ diff --git a/README.md b/README.md index 4f3be1c..70cab86 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,12 @@ modman clone https://github.com/basicrum/basicrum-magento-1.git ### Manual installation +Download the versioned `basicrum-magento-1-.zip` asset and its `.sha256` +file from the [GitHub releases](https://github.com/basicrum/basicrum-magento-1/releases). +Verify the checksum, then extract the ZIP. The extension is inside the +`basicrum-magento-1/` directory. GitHub's automatic source-code archives are +repository snapshots, not the filtered installation package. + Copy these paths into the matching locations under the Magento root: - `app/code/community/BasicRum/Analytics` @@ -166,7 +172,8 @@ Script placement and callback registration timing remain Magento-specific; this port does not add automatic consent-provider adapters or change the underlying Boomerang shutdown behavior. -Run XML, Modman, Boomerang checksum, and temporary package-archive verification with: +Run XML, Modman, Boomerang checksum, and temporary release-archive verification +with Node.js 20+, `xmllint`, `zip`, `unzip`, and `sha256sum` or `shasum` installed: ```bash bash tests/check-package.sh @@ -180,7 +187,8 @@ npm run build:loaders GitHub Actions runs PHP syntax/tests on PHP 7.0, 7.4, and 8.3, the Playwright suite, XML validation, and packaging checks. -It also installs the extension into a real application and boots the storefront for this pinned compatibility matrix: +It also installs the built release ZIP (not loose files from the checkout) into +a real application and boots the storefront for this pinned compatibility matrix: | Platform | Runtime | Coverage | |----------|---------|----------| @@ -191,6 +199,60 @@ The real-install jobs exercise a fresh privacy-first installation, storefront-tr For a local run, provide a disposable platform checkout and an empty MariaDB database, then run—for example—`bash tests/platform/run.sh openmage /path/to/openmage`. The default database is `basicrum` at `127.0.0.1` with username and password `basicrum`; override it with `BASICRUM_TEST_DB_HOST`, `BASICRUM_TEST_DB_NAME`, `BASICRUM_TEST_DB_USER`, and `BASICRUM_TEST_DB_PASSWORD`. The runner deploys the extension into the checkout and installs the application, so neither target should contain data that must be preserved. +Set `BASICRUM_TEST_RELEASE_ZIP=/absolute/path/to/basicrum-magento-1-1.1.0.zip` +to exercise a packaged installation locally. Keep its `.sha256` alongside it. +The runner verifies every archive entry against the checkout before deploying; +an invalid archive fails without falling back to source files. + +## Release artifacts + +The release process follows the WordPress plugin's package-and-smoke-test +approach, adapted to Magento's `app/` and `js/` layout and compatibility matrix. + +- Ordinary branch and pull-request CI uploads a candidate ZIP and SHA-256 file + as the `basicrum-magento-1-release` Actions artifact, retained for 14 days. + These are test candidates; check the entire workflow result before using them. +- Pushing a version tag such as `v1.1.0` triggers **Release Extension**, which + calls the same CI workflow. Only after all PHP, browser, packaging, Magento CE, + and OpenMage checks pass does it create a GitHub Release with generated notes + and attach `basicrum-magento-1-1.1.0.zip` and its `.sha256` file. +- Tags such as `v1.1.0-alpha.1`, `v1.1.0-beta.1`, and `v1.1.0-rc.1` follow the + same gates and are marked as prereleases, not latest stable releases. + Their base version must match the module version; the suffix does not alter + Magento's setup version. Unsupported suffixes and mismatched versions fail. +- Creating or editing a release in the GitHub UI is not a separate trigger. + Use a tag push. A literal `/release` is not the release-tag convention. +- The published ZIP is the exact artifact installed by both platform jobs; + the publishing job verifies it again and never rebuilds it. Only that job + receives `contents: write`; test jobs remain read-only. Newly added actions + are pinned to full commit SHAs. + +Before tagging, keep the module version in `app/code/community/BasicRum/Analytics/etc/config.xml`, +the **Version** section below, `package.json`, and both root versions in +`package-lock.json` synchronized. Commit and push the reviewed release changes, +then push the version tag. Do not move a published tag to another commit. +The workflow files must already be present in the tagged commit. No tag or +release is created by the local build commands. + +Build and verify locally: + +```bash +node --test tests/release/version.test.js +bash tests/release/package.sh +bash tests/check-package.sh +BASICRUM_RELEASE_TAG=v1.1.0 bash tools/build-release.sh +bash tools/verify-release.sh release/basicrum-magento-1-1.1.0.zip +(cd release && shasum -a 256 -c basicrum-magento-1-1.1.0.zip.sha256) +``` + +`tools/build-release.sh` optionally accepts an output directory. It refuses to +overwrite an existing version's ZIP/checksum; use a fresh directory for a new +build. The default `release/` directory is ignored by Git. The package includes +only the Modman-listed runtime files, `modman`, README, license, and provenance +notice. Tests, CI files, Node dependencies/manifests, and local configuration +are excluded. Changes to the package boundary must keep Modman and the archive +layout aligned. + ## Bundled Boomerang provenance The bundled `js/basicrum/boomerangs/boomerang-1.815.60.cutting-edge.min.js` is byte-identical to the WordPress bundle and has SHA-256: diff --git a/tests/check-package.sh b/tests/check-package.sh index b9c5bbb..10f9f1d 100644 --- a/tests/check-package.sh +++ b/tests/check-package.sh @@ -13,39 +13,12 @@ privacy_default="$(xmllint --xpath 'string(/config/default/basicrum_analytics/pr strip_query_default="$(xmllint --xpath 'string(/config/default/basicrum_analytics/privacy/strip_query_string)' app/code/community/BasicRum/Analytics/etc/config.xml)" http_policy_default="$(xmllint --xpath 'string(/config/default/basicrum_analytics/developer/development_mode)' app/code/community/BasicRum/Analytics/etc/config.xml)" -if [[ "$module_version" != "1.1.0" || "$privacy_default" != "1" \ +if [[ "$privacy_default" != "1" \ || "$strip_query_default" != "0" || "$http_policy_default" != "0" ]]; then echo "Unexpected module or policy defaults: version=$module_version opt_in_required=$privacy_default strip_query_string=$strip_query_default development_mode=$http_policy_default" >&2 exit 1 fi -package_files=(README.md LICENSE.md THIRD-PARTY-NOTICES.txt modman package.json) - -while read -r source_path destination_path extra; do - if [[ -z "${source_path:-}" || "${source_path:0:1}" == "#" ]]; then - continue - fi - - if [[ -n "${extra:-}" ]]; then - echo "Invalid modman row: $source_path $destination_path $extra" >&2 - exit 1 - fi - - if [[ ! -f "$source_path" ]]; then - echo "modman source does not exist: $source_path" >&2 - exit 1 - fi - - package_files+=("$source_path") -done < modman - -while IFS= read -r runtime_file; do - if ! awk -v file="$runtime_file" '$1 == file { found = 1 } END { exit found ? 0 : 1 }' modman; then - echo "Runtime file is missing from modman: $runtime_file" >&2 - exit 1 - fi -done < <(find app js -type f -print | sort) - expected_boomerang_sha="90e8a1c85949b10d43e441efc3f0545f95e4384e26ee3042344a8b2b4110589c" if command -v shasum >/dev/null 2>&1; then actual_boomerang_sha="$(shasum -a 256 js/basicrum/boomerangs/boomerang-1.815.60.cutting-edge.min.js | awk '{print $1}')" @@ -79,12 +52,7 @@ if grep -R --line-number -E 'BasicRUM|Beacon URL|Beacon Endpoint URL' "${termino fi package_tmp_dir="$(mktemp -d -t basicrum-magento-1.XXXXXX)" -archive_path="$package_tmp_dir/basicrum-magento-1.zip" -trap 'rm -f "$archive_path"; rmdir "$package_tmp_dir"' EXIT -zip -q "$archive_path" "${package_files[@]}" -unzip -tqq "$archive_path" -diff -u \ - <(printf '%s\n' "${package_files[@]}" | sort -u) \ - <(zipinfo -1 "$archive_path" | sort -u) +trap 'rm -rf -- "$package_tmp_dir"' EXIT +bash tools/build-release.sh "$package_tmp_dir" echo "XML, modman, provenance, and package archive checks passed." diff --git a/tests/platform/deploy-module.sh b/tests/platform/deploy-module.sh index aa5089b..a5c3f63 100644 --- a/tests/platform/deploy-module.sh +++ b/tests/platform/deploy-module.sh @@ -24,6 +24,15 @@ if [[ ! -f "$platform_root/app/Mage.php" ]]; then exit 1 fi +if [[ -n "${BASICRUM_TEST_RELEASE_ZIP:-}" ]]; then + bash "$plugin_root/tools/verify-release.sh" "$BASICRUM_TEST_RELEASE_ZIP" + package_tmp_dir="$(mktemp -d "${TMPDIR:-/tmp}/basicrum-platform-release.XXXXXX")" + trap 'rm -rf -- "$package_tmp_dir"' EXIT + unzip -q "$BASICRUM_TEST_RELEASE_ZIP" -d "$package_tmp_dir" + # No source-checkout fallback: every runtime file below comes from the ZIP. + plugin_root="$package_tmp_dir/basicrum-magento-1" +fi + while read -r source_path destination_path extra; do if [[ -z "${source_path:-}" || "${source_path:0:1}" == "#" ]]; then continue diff --git a/tests/release/package.sh b/tests/release/package.sh new file mode 100644 index 0000000..ba47f7e --- /dev/null +++ b/tests/release/package.sh @@ -0,0 +1,77 @@ +#!/usr/bin/env bash +set -euo pipefail + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +test_dir="$(mktemp -d "${TMPDIR:-/tmp}/basicrum-package-test.XXXXXX")" +trap 'rm -rf -- "$test_dir"' EXIT +export BASICRUM_RELEASE_TAG= + +expect_failure() { + if "$@" > "$test_dir/failure.log" 2>&1; then + echo "Unexpected success: $*" >&2 + exit 1 + fi +} + +write_checksum() { + ( + cd "$(dirname "$1")" + if command -v sha256sum >/dev/null 2>&1; then + sha256sum "$(basename "$1")" > "$1.sha256" + else + shasum -a 256 "$(basename "$1")" > "$1.sha256" + fi + ) +} + +version="$(node "$repo_root/tools/release-version.js")" +archive_name="basicrum-magento-1-$version.zip" +bash "$repo_root/tools/build-release.sh" "$test_dir/output" +archive="$test_dir/output/$archive_name" +bash "$repo_root/tools/verify-release.sh" "$archive" +expect_failure bash "$repo_root/tools/build-release.sh" "$test_dir/output" + +# Prerelease packaging must not require changing Magento's setup version. +BASICRUM_RELEASE_TAG="v$version-rc.1" bash "$repo_root/tools/build-release.sh" "$test_dir/prerelease" +test -f "$test_dir/prerelease/basicrum-magento-1-$version-rc.1.zip" +expect_failure env BASICRUM_RELEASE_TAG=v999.0.0 bash "$repo_root/tools/build-release.sh" "$test_dir/mismatch" +test ! -d "$test_dir/mismatch" + +# Neither a bad checksum nor a modified ZIP with a fresh checksum may pass. +mkdir -p "$test_dir/invalid" +cp "$archive" "$archive.sha256" "$test_dir/invalid/" +invalid="$test_dir/invalid/$archive_name" +printf 'invalid checksum\n' > "$invalid.sha256" +expect_failure bash "$repo_root/tools/verify-release.sh" "$invalid" +write_checksum "$invalid" +bash "$repo_root/tools/verify-release.sh" "$invalid" +zip -qd "$invalid" basicrum-magento-1/js/basicrum/LICENSE.txt +write_checksum "$invalid" +expect_failure bash "$repo_root/tools/verify-release.sh" "$invalid" + +cp "$archive" "$invalid" +printf 'development-only\n' > "$test_dir/unwanted.txt" +(cd "$test_dir" && zip -q "$invalid" unwanted.txt) +write_checksum "$invalid" +expect_failure bash "$repo_root/tools/verify-release.sh" "$invalid" + +cp "$archive" "$invalid" +mkdir -p "$test_dir/basicrum-magento-1" +printf 'changed runtime bytes\n' > "$test_dir/basicrum-magento-1/README.md" +(cd "$test_dir" && zip -q "$invalid" basicrum-magento-1/README.md) +write_checksum "$invalid" +expect_failure bash "$repo_root/tools/verify-release.sh" "$invalid" + +# The native runner must deploy the verified ZIP, and stop for a broken one. +mkdir -p "$test_dir/platform/app" +touch "$test_dir/platform/app/Mage.php" +BASICRUM_TEST_RELEASE_ZIP="$archive" bash "$repo_root/tests/platform/deploy-module.sh" openmage "$test_dir/platform" +while read -r source_path destination_path extra; do + if [[ -n "${source_path:-}" && "${source_path:0:1}" != "#" ]]; then + cmp "$repo_root/$source_path" "$test_dir/platform/$destination_path" + fi +done < "$repo_root/modman" +expect_failure env BASICRUM_TEST_RELEASE_ZIP="$invalid" \ + bash "$repo_root/tests/platform/deploy-module.sh" openmage "$test_dir/platform" + +echo "Release archive, checksum, rejection, and packaged deployment tests passed." diff --git a/tests/release/version.test.js b/tests/release/version.test.js new file mode 100644 index 0000000..467c7eb --- /dev/null +++ b/tests/release/version.test.js @@ -0,0 +1,57 @@ +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const os = require("node:os"); +const path = require("node:path"); +const { test } = require("node:test"); +const { releaseVersion } = require("../../tools/release-version"); + +function fixture(t) { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "basicrum-version-")); + t.after(() => fs.rmSync(root, { recursive: true, force: true })); + const configDir = path.join(root, "app/code/community/BasicRum/Analytics/etc"); + fs.mkdirSync(configDir, { recursive: true }); + fs.writeFileSync(path.join(configDir, "config.xml"), + "1.1.0"); + fs.writeFileSync(path.join(root, "README.md"), "# Extension\n\n## Version\n\n1.1.0\n"); + fs.writeFileSync(path.join(root, "package.json"), JSON.stringify({ version: "1.1.0" })); + fs.writeFileSync(path.join(root, "package-lock.json"), + JSON.stringify({ version: "1.1.0", packages: { "": { version: "1.1.0" } } })); + return root; +} + +test("untagged CI builds and stable release tags use the module version", (t) => { + const root = fixture(t); + assert.equal(releaseVersion(root), "1.1.0"); + assert.equal(releaseVersion(root, "v1.1.0"), "1.1.0"); +}); + +test("prerelease suffixes preserve the base module version", (t) => { + const root = fixture(t); + for (const suffix of ["alpha.1", "beta.2", "rc.12"]) { + assert.equal(releaseVersion(root, `v1.1.0-${suffix}`), `1.1.0-${suffix}`); + } +}); + +test("rejects mismatched versions and unsupported tag names", (t) => { + const root = fixture(t); + for (const tag of ["v1.2.0", "1.1.0", "/release", "v1.1.0-rc.0", "v1.1.0-rc.01", + "v1.1.0-preview.1", "v01.1.0", "v1.1.0+build", "v1.1.0-rc.1\n"]) { + assert.throws(() => releaseVersion(root, tag), /Release tag/); + } +}); + +for (const file of ["README.md", "package.json", "package-lock.json"]) { + test(`rejects stale ${file} metadata`, (t) => { + const root = fixture(t); + const filename = path.join(root, file); + fs.writeFileSync(filename, fs.readFileSync(filename, "utf8").replaceAll("1.1.0", "1.0.1")); + assert.throws(() => releaseVersion(root), /versions must agree/); + }); +} + +test("checks the lockfile root package independently", (t) => { + const root = fixture(t); + fs.writeFileSync(path.join(root, "package-lock.json"), + JSON.stringify({ version: "1.1.0", packages: { "": { version: "1.0.1" } } })); + assert.throws(() => releaseVersion(root), /versions must agree/); +}); diff --git a/tools/build-release.sh b/tools/build-release.sh new file mode 100644 index 0000000..65299aa --- /dev/null +++ b/tools/build-release.sh @@ -0,0 +1,37 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [[ $# -gt 1 ]]; then + echo "Usage: $0 [output-directory]" >&2 + exit 2 +fi +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +release_dir="${1:-$repo_root/release}" +version="$(node "$repo_root/tools/release-version.js")" +archive_name="basicrum-magento-1-$version.zip" +stage_dir="$(mktemp -d "${TMPDIR:-/tmp}/basicrum-release.XXXXXX")" +trap 'rm -rf -- "$stage_dir"' EXIT + +bash "$repo_root/tools/package-files.sh" > "$stage_dir/files.txt" +while IFS= read -r package_file; do + mkdir -p "$stage_dir/basicrum-magento-1/$(dirname "$package_file")" + cp -p "$repo_root/$package_file" "$stage_dir/basicrum-magento-1/$package_file" +done < "$stage_dir/files.txt" +( + cd "$stage_dir" + sed 's|^|basicrum-magento-1/|' files.txt | zip -X -q "$archive_name" -@ + if command -v sha256sum >/dev/null 2>&1; then + sha256sum "$archive_name" > "$archive_name.sha256" + else + shasum -a 256 "$archive_name" > "$archive_name.sha256" + fi +) +bash "$repo_root/tools/verify-release.sh" "$stage_dir/$archive_name" + +mkdir -p "$release_dir" +if [[ -e "$release_dir/$archive_name" || -e "$release_dir/$archive_name.sha256" ]]; then + echo "Release output already exists; choose an empty output directory: $release_dir" >&2 + exit 1 +fi +cp "$stage_dir/$archive_name" "$stage_dir/$archive_name.sha256" "$release_dir/" +echo "Built $release_dir/$archive_name and its SHA-256 checksum." diff --git a/tools/package-files.sh b/tools/package-files.sh new file mode 100644 index 0000000..7907b5e --- /dev/null +++ b/tools/package-files.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd "$(dirname "${BASH_SOURCE[0]}")/.." +package_files=(README.md LICENSE.md THIRD-PARTY-NOTICES.txt modman) + +while read -r source_path destination_path extra; do + if [[ -z "${source_path:-}" || "${source_path:0:1}" == "#" ]]; then + continue + fi + # The ZIP is copied directly into Magento's directory layout. Reject mapping + # changes that would make that layout disagree with a Modman installation. + if [[ -n "${extra:-}" || "$source_path" != "$destination_path" \ + || ! "$source_path" =~ ^(app/|js/basicrum/)[a-zA-Z0-9_./-]+$ \ + || "/$source_path/" == *"/../"* || "/$source_path/" == *"/./"* \ + || "$source_path" == *"//"* ]]; then + echo "Invalid or non-identity modman mapping: $source_path $destination_path" >&2 + exit 1 + fi + package_files+=("$source_path") +done < modman + +if [[ -n "$(find app js -type l -print)" ]]; then + echo "Runtime symlinks cannot be included in a release." >&2 + exit 1 +fi +for package_file in "${package_files[@]}"; do + if [[ ! -f "$package_file" || -L "$package_file" ]]; then + echo "Package source is missing or is a symlink: $package_file" >&2 + exit 1 + fi +done +if [[ -n "$(printf '%s\n' "${package_files[@]}" | LC_ALL=C sort | uniq -d)" ]]; then + echo "Duplicate package file in modman." >&2 + exit 1 +fi +while IFS= read -r runtime_file; do + if ! printf '%s\n' "${package_files[@]}" | awk -v file="$runtime_file" \ + '$0 == file { found = 1 } END { exit found ? 0 : 1 }'; then + echo "Runtime file is missing from modman: $runtime_file" >&2 + exit 1 + fi +done < <(find app js -type f -print) + +printf '%s\n' "${package_files[@]}" | LC_ALL=C sort diff --git a/tools/release-version.js b/tools/release-version.js new file mode 100644 index 0000000..81babc1 --- /dev/null +++ b/tools/release-version.js @@ -0,0 +1,43 @@ +const fs = require("node:fs"); +const path = require("node:path"); +const { execFileSync } = require("node:child_process"); + +function releaseVersion(root, tag = "") { + const version = execFileSync("xmllint", [ + "--xpath", "string(/config/modules/BasicRum_Analytics/version)", + path.join(root, "app/code/community/BasicRum/Analytics/etc/config.xml") + ], { encoding: "utf8" }).trim(); + const stableVersion = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/; + if (!stableVersion.test(version)) { + throw new Error("Module version must use major.minor.patch without leading zeroes."); + } + + const manifest = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8")); + const lock = JSON.parse(fs.readFileSync(path.join(root, "package-lock.json"), "utf8")); + const readme = fs.readFileSync(path.join(root, "README.md"), "utf8"); + const readmeVersion = readme.match(/^## Version\s+([^\s]+)/m); + if (manifest.version !== version || lock.version !== version + || lock.packages[""].version !== version || !readmeVersion || readmeVersion[1] !== version) { + throw new Error("Module, README, package.json and package-lock.json versions must agree."); + } + + if (!tag) { + return version; + } + const match = tag.match(/^v((?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*))(-(alpha|beta|rc)\.[1-9]\d*)?$/); + if (!match || match[1] !== version) { + throw new Error(`Release tag must be v${version} or v${version}-{alpha,beta,rc}.N (N >= 1).`); + } + return tag.slice(1); +} + +module.exports = { releaseVersion }; + +if (require.main === module) { + try { + process.stdout.write(releaseVersion(path.resolve(__dirname, ".."), process.env.BASICRUM_RELEASE_TAG) + "\n"); + } catch (error) { + process.stderr.write(error.message + "\n"); + process.exitCode = 1; + } +} diff --git a/tools/verify-release.sh b/tools/verify-release.sh new file mode 100644 index 0000000..d76d978 --- /dev/null +++ b/tools/verify-release.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [[ $# -ne 1 || ! -f "$1" || ! -f "$1.sha256" ]]; then + echo "Usage: $0 (matching .sha256 file required)" >&2 + exit 2 +fi +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +archive_path="$1" +archive_name="$(basename "$archive_path")" +module_version="$(xmllint --xpath 'string(/config/modules/BasicRum_Analytics/version)' \ + "$repo_root/app/code/community/BasicRum/Analytics/etc/config.xml")" +release_version="${archive_name#basicrum-magento-1-}" +release_version="${release_version%.zip}" +if [[ "$archive_name" != "basicrum-magento-1-$release_version.zip" \ + || ! "$release_version" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-(alpha|beta|rc)\.[1-9][0-9]*)?$ \ + || "${release_version%%-*}" != "$module_version" ]]; then + echo "Archive name does not match the module version: $archive_name" >&2 + exit 1 +fi +if command -v sha256sum >/dev/null 2>&1; then + checksum="$(sha256sum "$archive_path" | awk '{print $1}')" +else + checksum="$(shasum -a 256 "$archive_path" | awk '{print $1}')" +fi +if [[ "$(cat "$archive_path.sha256")" != "$checksum $archive_name" ]]; then + echo "Release checksum does not match the archive." >&2 + exit 1 +fi + +expected_files="$(bash "$repo_root/tools/package-files.sh")" +unzip -tqq "$archive_path" +diff -u \ + <(printf '%s\n' "$expected_files" | sed 's|^|basicrum-magento-1/|') \ + <(zipinfo -1 "$archive_path" | LC_ALL=C sort) +while IFS= read -r package_file; do + # Check the actual packaged bytes against this checkout, not just filenames. + unzip -p "$archive_path" "basicrum-magento-1/$package_file" | cmp - "$repo_root/$package_file" +done <<< "$expected_files" +echo "Verified release contents and checksum: $archive_name" From f90de1e78b024b98c533f38fae467beac5f5b2c0 Mon Sep 17 00:00:00 2001 From: Tsvetan Stoychev Date: Sun, 20 Sep 2026 11:24:36 +0300 Subject: [PATCH 28/28] fix(ci): keep branch pushes enabled alongside release tags --- .github/workflows/ci.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a875a77..aac7275 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,6 +2,8 @@ name: CI on: push: + branches: + - '**' tags-ignore: - 'v*.*.*' # Version tags run this workflow through release.yml. pull_request: