diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 9dd492b..48bb673 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -1,18 +1,18 @@ -# 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. -- **GDPR/Privacy Compliance**: Supports opt-in mode for cookie consent requirements. +- **GDPR/Privacy Compliance**: Uses consent-controlled loading by default for new installations. - **Configurable Beacon Endpoint**: Admin can specify where analytics data is sent. - **Async Loading**: Boomerang JS loads asynchronously to minimize performance impact. ## Project Context - **Framework**: Magento 1 (OpenMage LTS) / Modernized M1. - **Module Name**: `BasicRum_Analytics` -- **Module Version**: `1.0.0` +- **Module Version**: `1.1.0` - **Code Pool**: `community` - **Deployment**: Uses `modman` for file mapping. @@ -33,7 +33,7 @@ This module integrates **Boomerang.js** (Real User Monitoring) into Magento 1 st app/code/community/BasicRum/Analytics/ ├── Block/ │ └── Boomerang/ -│ └── Loader.php # Renders JS snippet in footer +│ └── Loader.php # Renders JS snippet before the closing body tag ├── Helper/ │ ├── Data.php # Config retrieval methods │ └── PageTypeDetector.php # Layout handle-based page type detection @@ -56,8 +56,8 @@ js/basicrum/ | Class | Purpose | |-------|---------| -| `BasicRum_Analytics_Block_Boomerang_Loader` | Generates the Boomerang JS inline script. Injected into `footer` reference. | -| `BasicRum_Analytics_Helper_Data` | Retrieves admin config values: `isEnabled()`, `isOptInRequired()`, `getBeaconEndpoint()`, `useUnminifiedLoaders()`. | +| `BasicRum_Analytics_Block_Boomerang_Loader` | Generates the Boomerang JS inline script. Injected into the `before_body_end` reference. | +| `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 @@ -66,14 +66,17 @@ Access via `Mage::getStoreConfig()` or `Mage::getStoreConfigFlag()`: | Path | Type | Description | |------|------|-------------| | `basicrum_analytics/general/enabled` | bool | Enable/disable the module | -| `basicrum_analytics/general/opt_in_required` | bool | Use opt-in loader for GDPR compliance | +| `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 | | `basicrum_analytics/wait_after_onload/wait_ms` | int | Milliseconds to wait before sending beacon | +| `basicrum_analytics/developer/development_mode` | bool | Allow HTTP Beacon Endpoints only for local testing | | `basicrum_analytics/developer/use_unminified_loaders` | bool | Load non-minified JS for debugging | ### JavaScript Assets -Located in `js/basicrum/` and symlinked to Magento's `public/js/basicrum/`: +Located in `js/basicrum/` and mapped by Modman to Magento's root-level `js/basicrum/` directory: | File | Purpose | |------|---------| @@ -84,9 +87,9 @@ Located in `js/basicrum/` and symlinked to Magento's `public/js/basicrum/`: | `loaders/consent-boomerang-loader-v1-15.js` | GDPR-compliant loader (development) | ### Layout Integration -The block is added to the `footer` reference in `basicrum_analytics.xml`: +The block is added to the `before_body_end` reference in `basicrum_analytics.xml`: ```xml - + ``` @@ -94,11 +97,12 @@ The block is added to the `footer` reference in `basicrum_analytics.xml`: ## Specific Instructions 1. **Modman**: When adding new files, always verify if the `modman` file needs updating to map the file from the source to the Magento root. 2. **Layouts**: Layout updates reside in `app/design/frontend/base/default/layout/`. -3. **JS/CSS**: Static assets are symlinked from `js/basicrum/` to the Magento root `public/js/` folder. +3. **JavaScript**: Static assets under `js/basicrum/` are mapped by Modman to the Magento root `js/basicrum/` directory. 4. **Configuration**: - `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 and Brum Site ID visible while the module is disabled. Privacy controls and consent guidance live in General Settings, with `config_path` preserving the established `basicrum_analytics/privacy/*` storage paths. Runtime-only privacy, wait, and developer fields depend 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')`. @@ -111,7 +115,8 @@ The block is added to the `footer` reference in `basicrum_analytics.xml`: ## Boomerang Configuration The module configures Boomerang with these settings: - `beacon_url`: From admin config. -- `instrument_xhr`: Enabled for XHR tracking. +- `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/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..aac7275 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,139 @@ +name: CI + +on: + push: + branches: + - '**' + 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 + +jobs: + php: + name: PHP ${{ matrix.php }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + php: ["7.0", "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 tests/platform -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 + outputs: + archive_name: ${{ steps.package.outputs.archive_name }} + 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 + - 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: + fail-fast: false + matrix: + include: + - name: Magento CE 1.9.4.5 / PHP 7.4 + platform: magento-ce + repository: OpenMage/magento-mirror + ref: 1.9.4.5 + php: "7.4" + - name: OpenMage 20.18.0 / PHP 8.3 + platform: openmage + repository: OpenMage/magento-lts + ref: v20.18.0 + php: "8.3" + services: + database: + image: mariadb:10.11 + env: + MARIADB_DATABASE: basicrum + MARIADB_USER: basicrum + MARIADB_PASSWORD: basicrum + MARIADB_ROOT_PASSWORD: root + ports: + - 3306:3306 + options: >- + --health-cmd="healthcheck.sh --connect --innodb_initialized" + --health-interval=10s + --health-timeout=5s + --health-retries=10 + steps: + - uses: actions/checkout@v4 + - uses: actions/checkout@v4 + with: + repository: ${{ matrix.repository }} + ref: ${{ matrix.ref }} + path: platform + - uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + coverage: none + extensions: ctype, curl, dom, ftp, gd, iconv, intl, mbstring, mysqli, pdo_mysql, simplexml, soap, zip + - 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 new file mode 100644 index 0000000..a58e2e4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +/node_modules/ +/.test-results/ +/playwright-report/ +/release/ 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/README.md b/README.md index cefc66b..70cab86 100644 --- a/README.md +++ b/README.md @@ -1,118 +1,272 @@ -# BasicRUM Analytics module for Magento 1 +# Basicrum Analytics for Magento 1 -The BasicRUM Analytics module provides analytics integration with BasicRUM for Magento 1 stores. +Basicrum Analytics integrates Magento 1 and OpenMage LTS stores with a Basicrum collector using the bundled Boomerang Real User Monitoring library. ## Requirements -- Magento 1.x (including OpenMage LTS and Maho Commerce) -- PHP 7.0 or higher (compatible with PHP 8.x) +- Magento 1.x or OpenMage LTS +- PHP 7.0 or newer +- A Beacon Endpoint and matching Brum Site ID supplied by the Basicrum backend ## Installation -The module can be installed manually by copying files or by using Modman. - -### Option 1: Modman (Recommended) +### Modman ```bash cd /path/to/magento modman clone https://github.com/basicrum/basicrum-magento-1.git ``` -### Option 2: Manual Installation +### Manual installation -1. Copy the module files to your Magento installation: - - Copy `app/code/community/BasicRum/Analytics` to your Magento installation's `app/code/community` directory - - Copy `app/etc/modules/BasicRum_Analytics.xml` to your Magento installation's `app/etc/modules` directory - - Copy `app/design/frontend/base/default/layout/basicrum_analytics.xml` to your Magento installation's `app/design/frontend/base/default/layout` directory - - Copy `js/basicrum` to your Magento installation's `js` directory +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. -### Post-Installation +Copy these paths into the matching locations under the Magento root: -1. Clear Magento cache: - - Go to System > Cache Management in the admin panel - - Click "Flush Magento Cache" +- `app/code/community/BasicRum/Analytics` +- `app/etc/modules/BasicRum_Analytics.xml` +- `app/design/frontend/base/default/layout/basicrum_analytics.xml` +- `app/locale/en_US/BasicRum_Analytics.csv` +- `js/basicrum` -2. Verify the module is enabled: - - Go to System > Configuration > Advanced > Advanced - - Look for "BasicRum Analytics" in the list of modules +Clear Magento configuration and layout caches after installation or upgrade. ## Configuration -The module configuration can be found in **System > Configuration > BasicRUM Analytics**. +Go to **System > Configuration > Basicrum > Basicrum Settings**. Configuration remains available at Magento's default, website, and store scopes. + +**Enable Basicrum** defaults to **No (disabled)**. General Settings includes the collector identity, **Strip Query Strings**, **Require Consent Before Monitoring**, and consent integration guidance. The privacy controls retain their existing `basicrum_analytics/privacy/*` configuration paths and scoped values; only their placement in the admin changes. + +Monitoring scripts are emitted only when all of these conditions are met: + +- **Enable Basicrum** is set to Yes. +- **Beacon Endpoint** 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. + +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 Endpoint, 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. -![Admin Configuration](docs/media/admin-area.png) +HTTPS Beacon Endpoints 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. HTTPS storefronts always upgrade HTTP Beacon Endpoints to HTTPS to prevent mixed-content blocking, even when HTTP is allowed by the selected policy. -### General Settings +### Query-string privacy -| Setting | Description | -|---------|-------------| -| **Enable** | Enable or disable the module | -| **Beacon Endpoint URL** | **(Required)** The URL where analytics data will be sent. This should point to your BasicRUM collector endpoint. | +**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. -### Data Privacy / GDPR +This setting does not modify query parameters in the configured Beacon Endpoint. Those parameters are part of the collector destination and continue to be safely serialized unchanged. -| Setting | Description | -|---------|-------------| -| **Opt-In Required** | When enabled, Boomerang will not load until the visitor gives consent. Use the JavaScript API to integrate with your cookie consent solution. | +### Consent-controlled loading -**JavaScript API for consent integration:** +**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: ```javascript -// Call when user accepts cookies/tracking -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(); } +``` + +Call the opt-out callback whenever monitoring is denied or withdrawn: -// Call when user rejects tracking -if (typeof window.OPT_OUT_BASIC_RUM === 'function') { - window.OPT_OUT_BASIC_RUM(); +```javascript +if (typeof window.OPT_OUT_BASICRUM_LOADER_WRAPPER === 'function') { + window.OPT_OUT_BASICRUM_LOADER_WRAPPER(); } ``` -**Cookies created:** -- `BOOMR_CONSENT` - Remembers user consent preference (expires after 1 year) -- `RT` - Round-trip timing cookie (created on opt-in, deleted on opt-out) -- `BA` - Bandwidth/latency cookie (created on opt-in, deleted on opt-out) +Basicrum does not show a consent dialog, determine the site's legal basis, persist a consent choice, or trust a decision from an earlier page. The external consent tool remains the source of truth and must signal the current decision on each page. + +For backward compatibility, existing Magento integrations may continue calling: + +- `window.OPT_IN_BASIC_RUM()` +- `window.OPT_OUT_BASIC_RUM()` + +They are aliases of the canonical callbacks above. + +Repeated opt-in calls inject Boomerang only once. Opt-out before the first opt-in clears RUM and legacy consent cookies but retains the in-page configuration, so a later allow decision on that page can start monitoring. Opt-out during download neutralizes the configuration before the bundle can initialize. Opt-out after initialization disables Boomerang. Once loading has started and consent is withdrawn, re-granting does not restart monitoring on that page; reload the page and let the external tool report the new allow decision. Opt-out stops future browser collection but cannot retract beacon data already sent to the configured collector. + +When monitoring runs, Boomerang sets a first-party `RT` cookie at path `/`. It contains a random session identifier that links monitored page views, uses a 30-minute session window, and has a rolling seven-day expiry. It uses `SameSite=Strict` and is marked `Secure` on HTTPS sites. `BA` is a legacy Boomerang cookie. Opt-out removes `RT`, `BA`, and the legacy `BRUM_CONSENT` and `BOOMR_CONSENT` cookies across applicable host-domain paths. The extension never creates either consent cookie. + +### Upgrade behavior in 1.1.0 + +Version 1.1.0 introduces a versioned Magento setup resource for the privacy default: + +- 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 Endpoints keep their policy after upgrade: for every explicit Beacon Endpoint, 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. As before, HTTPS storefronts upgrade HTTP Beacon Endpoints to HTTPS regardless of that policy. +- A previously installed but never configured and disabled module is treated like a new installation; this cannot start monitoring because **Enable**, Beacon Endpoint, and Site ID are still required. + +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: + +- Beacon Endpoint and Brum Site ID are now both mandatory, and the Site ID must be a UUID v4. A store with an empty or previously accepted non-v4 Site ID emits no monitoring scripts until a valid backend identifier is saved. +- Basicrum no longer resumes from a `BRUM_CONSENT` cookie. In consent-controlled mode, the external consent tool must call the opt-in callback on every page after the Basicrum loader has registered it near the end of the document. Calls made before registration are not queued or replayed. ### Wait After Onload -| Setting | Description | -|---------|-------------| -| **Enable Wait After Onload** | Enable delayed beacon sending to capture additional metrics | -| **Wait After Onload (ms)** | Milliseconds to wait after page load before sending the beacon | +Enable this option to delay the page-load beacon while collecting additional metrics. The canonical configuration path is: -### Developer +```text +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. -| Setting | Description | -|---------|-------------| -| **Use Unminified Loaders** | Load non-minified loader scripts for debugging purposes | +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 Detection +## Page type compatibility -The module sends `p_type` to Boomerang based on Magento layout handles. Known handles are mapped -to friendly page types (e.g., `cms_index_index` → `home`, `catalog_product_view` → `product`). -If no known handle matches, the first non-generic handle is sent as `unmapped_{handle}`. +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. -## Developer +## Automated verification -### Minifying Loader Scripts +PHP configuration and rendering tests use a lightweight Magento compatibility harness and do not require a full Magento installation: + +```bash +php tests/php/run.php +``` -Use UglifyJS to minify the Boomerang loader scripts with IE compatibility: +Browser tests use Playwright and exercise both source and minified loaders in Chromium, including immediate loading, current-page consent, repeated opt-in, and opt-out before loading, during download, and after initialization: ```bash -# Standard loader -npx uglify-js js/basicrum/loaders/boomerang-loader-v15.js \ - --mangle \ - --compress sequences=false,ie=true \ - --output js/basicrum/loaders/boomerang-loader-v15.min.js - -# Consent loader (GDPR opt-in) -npx uglify-js js/basicrum/loaders/consent-boomerang-loader-v1-15.js \ - --mangle \ - --compress sequences=false,ie=true \ - --output js/basicrum/loaders/consent-boomerang-loader-v1-15.min.js +npm ci +npx playwright install chromium +npm test ``` +The WordPress loaders are the source of truth. `tests/js/wordpress-parity.spec.js` +pins their source/minified SHA-256 hashes and the Boomerang bundle to WordPress +commit `64f19d9e5a9fbe580c12c19796e86e3ad0dd17ff`. It also requires the consent +wrapper to embed the standard loader byte-for-byte. These checks run in the +normal CI suite without a WordPress checkout or network access. + +The only allowed consent-wrapper additions are Magento's legacy callback +aliases, legacy consent-cookie cleanup, and its existing Wait After Onload +timer cancellation/withdrawal guard. The parity test removes only these exact +additions before checking the WordPress hash; unexpected differences fail. +General loader behavior changes should be reviewed in WordPress first, then +ported here with the baseline updated explicitly. Do not remove Magento's +existing withdrawal protection just to match the current WordPress wrapper. + +To also verify the baseline against a local WordPress checkout: + +```bash +BASICRUM_WORDPRESS_ROOT=/path/to/basicrum-wordpress npm test +``` + +When updating the baseline, compare both WordPress loaders, retain only the +documented Magento additions, regenerate the minified files, update the pinned +revision/hashes and notices, and run the browser suite against the real bundle. +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 release-archive verification +with Node.js 20+, `xmllint`, `zip`, `unzip`, and `sha256sum` or `shasum` installed: + +```bash +bash tests/check-package.sh +``` + +Regenerate both minified loaders after changing either source file: + +```bash +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 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 | +|----------|---------|----------| +| Magento CE 1.9.4.5 | PHP 7.4 | Native setup resource, configuration/rendering, scopes, and live storefront | +| OpenMage 20.18.0 | PHP 8.3 | Native setup resource, 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 explicit consent or legacy HTTP behavior, incomplete and unsafe configuration, HTTPS enforcement and development HTTP mode, native admin saves with explicit/omitted/newly inherited HTTP policy at default/website/store scopes, 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. + +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: + +```text +90e8a1c85949b10d43e441efc3f0545f95e4384e26ee3042344a8b2b4110589c +``` + +It was built from commit `ead2783a33a2ce91205fe34f8fc992433faba9a2` in the [Basicrum Boomerang fork](https://github.com/basicrum/boomerang), based on [Akamai Boomerang](https://github.com/akamai/boomerang). The embedded banner identifies parent commit `564759ed70de7801bb64de5e2025fb6ac049ff5f` because the final source change was uncommitted when that artifact was generated. Reproducible-build and fork-change details are in [THIRD-PARTY-NOTICES.txt](THIRD-PARTY-NOTICES.txt). + +## License + +Basicrum-owned code is licensed under the GNU General Public License version 2 or later; see [LICENSE.md](LICENSE.md). Bundled Boomerang retains its BSD license in [js/basicrum/LICENSE.txt](js/basicrum/LICENSE.txt). + ## Version -1.0.0 +1.1.0 diff --git a/THIRD-PARTY-NOTICES.txt b/THIRD-PARTY-NOTICES.txt new file mode 100644 index 0000000..916417b --- /dev/null +++ b/THIRD-PARTY-NOTICES.txt @@ -0,0 +1,27 @@ +# 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. + +## Boomerang Loader Snippet + +- Project: [Akamai Boomerang](https://github.com/akamai/boomerang) +- Bundled and adapted files: `js/basicrum/loaders/boomerang-loader-v15.js`, `js/basicrum/loaders/boomerang-loader-v15.min.js`, and the Boomerang-loading portion of `js/basicrum/loaders/consent-boomerang-loader-v1-15.js` and its minified build +- License: BSD License +- License text: `js/basicrum/LICENSE.txt` +- Provenance: Boomerang Loader Snippet version 15, adapted from the loader distributed by the Akamai Boomerang project. The consent wrapper adds Basicrum-owned lifecycle and withdrawal handling around that loader. +- Canonical Basicrum implementation: `plugins/basicrum/assets/js/loaders/` at commit `64f19d9e5a9fbe580c12c19796e86e3ad0dd17ff` in [Basicrum WordPress](https://github.com/basicrum/basicrum-wordpress/tree/64f19d9e5a9fbe580c12c19796e86e3ad0dd17ff). The standard loader and the standard-loader block inside the consent wrapper are copied unchanged. Magento retains only its legacy callback aliases, legacy consent-cookie cleanup, and existing delayed-beacon withdrawal protection around the canonical wrapper. `tests/js/wordpress-parity.spec.js` pins upstream source and minified hashes and verifies these explicit differences. + +The Akamai Boomerang copyright notice and BSD license remain applicable to the loader code. Basicrum-owned adaptations remain under the extension license without changing the license of the original loader snippet. 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..2f57fc0 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,85 +2,71 @@ 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 consent guidance as a full-width configuration row. * * @param Varien_Data_Form_Element_Abstract $element * @return string */ - protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element): string + public function render(Varien_Data_Form_Element_Abstract $element): string { - $html = parent::_getElementHtml($element); + $rowId = htmlspecialchars('row_' . $element->getHtmlId(), ENT_QUOTES, 'UTF-8'); + $allowSnippetId = htmlspecialchars($element->getHtmlId() . '_allow_snippet', ENT_QUOTES, 'UTF-8'); + $denySnippetId = htmlspecialchars($element->getHtmlId() . '_deny_snippet', ENT_QUOTES, 'UTF-8'); + $scriptUrl = htmlspecialchars( + Mage::getBaseUrl('js') . 'basicrum/admin/consent-info.js', + ENT_QUOTES, + 'UTF-8' + ); - $infoHtml = << -
- JavaScript API for Cookie Consent Integration + 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. +

-
- When opt-in is enabled, Boomerang will not load until consent is given. Use these global functions to integrate with your cookie consent solution: +

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.

+
+ + +

+ + +

- - - - - - - - - -
- OPT_IN_BASIC_RUM() - - Call when user accepts cookies/tracking. Loads Boomerang and sets consent cookie. -
- OPT_OUT_BASIC_RUM() - - Call when user rejects tracking. Disables Boomerang and clears all RUM cookies. -
-
-
- 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: -
-
-
-
// Accept button handler
-if (typeof window.OPT_IN_BASIC_RUM === 'function') {
-    window.OPT_IN_BASIC_RUM();
-}
-
-// Reject button handler
-if (typeof window.OPT_OUT_BASIC_RUM === 'function') {
-    window.OPT_OUT_BASIC_RUM();
-}
+
+ + +

+ + +

+
+ + HTML; - - return $html . $infoHtml; } } 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 new file mode 100644 index 0000000..cec5ffd --- /dev/null +++ b/app/code/community/BasicRum/Analytics/Block/Adminhtml/System/Config/Form/Field/RequiredSetting.php @@ -0,0 +1,253 @@ +isSiteIdElement($element)) { + return $html; + } + + return $html . $this->getMonitoringStatusHtml($element); + } + + /** + * Add accessible, field-level feedback without replacing Magento's input. + * + * @param Varien_Data_Form_Element_Abstract $element + * @return string + */ + protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element): string + { + $isEnabled = $this->isMonitoringEnabled($element); + $message = $isEnabled ? $this->getValidationMessage($element) : null; + + if ($message !== null) { + $element->addClass('validation-failed'); + } + + $html = parent::_getElementHtml($element); + $errorId = $element->getHtmlId() . '_basicrum_error'; + $attributes = sprintf( + ' aria-required="%s" aria-invalid="%s"', + $isEnabled ? 'true' : 'false', + $message !== null ? 'true' : 'false' + ); + + if ($message !== null) { + $attributes .= ' aria-describedby="' + . htmlspecialchars($errorId, ENT_QUOTES, 'UTF-8') + . '"'; + } + + $html = preg_replace('/' + . htmlspecialchars($message, ENT_QUOTES, 'UTF-8') + . '
'; + } + + /** + * @param Varien_Data_Form_Element_Abstract $element + * @return string|null + */ + private function getValidationMessage(Varien_Data_Form_Element_Abstract $element) + { + $value = trim((string) $element->getValue()); + + if ($this->isBeaconElement($element)) { + if ($value === '') { + return Mage::helper('basicrum_analytics')->__( + 'Beacon Endpoint 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. Monitoring remains inactive.' + ); + } + } + + if ($this->isSiteIdElement($element)) { + if ($value === '') { + return Mage::helper('basicrum_analytics')->__( + '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 Brum Site ID. Monitoring remains inactive.' + ); + } + } + + return null; + } + + /** + * @param Varien_Data_Form_Element_Abstract $element + * @return bool + */ + private function isMonitoringEnabled(Varien_Data_Form_Element_Abstract $element): bool + { + return (string) $this->getFormValue( + $element, + self::ENABLED_FIELD_ID, + 'basicrum_analytics/general/enabled' + ) === '1'; + } + + /** + * @param Varien_Data_Form_Element_Abstract $element + * @return bool + */ + private function hasValidRequiredSettings(Varien_Data_Form_Element_Abstract $element): bool + { + $beacon = trim((string) $this->getFormValue( + $element, + self::BEACON_FIELD_ID, + 'basicrum_analytics/general/beacon_endpoint' + )); + $siteId = trim((string) $this->getFormValue( + $element, + self::SITE_ID_FIELD_ID, + 'basicrum_analytics/general/brum_site_id' + )); + + return BasicRum_Analytics_Helper_Data::isValidBeaconEndpoint($beacon) + && 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. + * + * @param Varien_Data_Form_Element_Abstract $element + * @param string $fieldId + * @param string $configPath + * @return mixed + */ + private function getFormValue( + Varien_Data_Form_Element_Abstract $element, + string $fieldId, + string $configPath + ) { + $form = $element->getForm(); + $field = $form ? $form->getElement($fieldId) : null; + + return $field ? $field->getValue() : Mage::getStoreConfig($configPath); + } + + /** + * @param Varien_Data_Form_Element_Abstract $element + * @return bool + */ + private function isBeaconElement(Varien_Data_Form_Element_Abstract $element): bool + { + return $this->hasIdSuffix($element->getHtmlId(), '_beacon_endpoint'); + } + + /** + * @param Varien_Data_Form_Element_Abstract $element + * @return bool + */ + private function isSiteIdElement(Varien_Data_Form_Element_Abstract $element): bool + { + return $this->hasIdSuffix($element->getHtmlId(), '_brum_site_id'); + } + + /** + * PHP 7.4-compatible suffix check. + * + * @param string $value + * @param string $suffix + * @return bool + */ + private function hasIdSuffix(string $value, string $suffix): bool + { + return substr($value, -strlen($suffix)) === $suffix; + } + + /** + * @param Varien_Data_Form_Element_Abstract $element + * @return string + */ + private function getMonitoringStatusHtml(Varien_Data_Form_Element_Abstract $element): string + { + $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($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 dec261f..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 { @@ -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,33 @@ 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, + 'strip_query_string' => $helper->shouldStripQueryString(), + '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) { @@ -65,10 +84,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}); @@ -91,37 +116,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..526a270 100644 --- a/app/code/community/BasicRum/Analytics/Helper/Data.php +++ b/app/code/community/BasicRum/Analytics/Helper/Data.php @@ -2,10 +2,15 @@ declare(strict_types=1); /** - * BasicRum Analytics Helper + * Basicrum Analytics Helper */ 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 @@ -25,31 +30,77 @@ 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 */ 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; + } + + // Enforce strict mode and preserve HTTPS storefronts' mixed-content + // protection, even for values injected outside the admin backend model. + if (!$this->isDevelopmentMode() || Mage::app()->getRequest()->isSecure()) { + $url = preg_replace('/^http:\/\//i', 'https://', $url); } - return null; + + return $url; } /** - * Get the BasicRUM Site ID + * Get the Brum Site ID * @return string|null */ 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 +119,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)); } /** @@ -80,6 +131,16 @@ public function useUnminifiedLoaders(): bool return Mage::getStoreConfigFlag('basicrum_analytics/developer/use_unminified_loaders'); } + /** + * Check whether HTTP Beacon Endpoints 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/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/Setup/HttpPolicyDefault.php b/app/code/community/BasicRum/Analytics/Model/Setup/HttpPolicyDefault.php new file mode 100644 index 0000000..fd5f813 --- /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/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 must be a valid HTTP or HTTPS URL.') + ); + } + + 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. + * Use the edited scope when omitted, or its parent when inheritance is selected. + * + * @return bool + */ + private function isHttpAllowed(): bool + { + $groups = $this->getGroups(); + $inherit = false; + + if (is_array($groups) + && isset($groups['developer']['fields']['development_mode']) + && is_array($groups['developer']['fields']['development_mode']) + ) { + $field = $groups['developer']['fields']['development_mode']; + $inherit = !empty($field['inherit']); + if (!$inherit && array_key_exists('value', $field)) { + return (string) $field['value'] === '1'; + } + } + + $path = 'basicrum_analytics/developer/development_mode'; + $storeCode = $this->getStoreCode(); + $websiteCode = $this->getWebsiteCode(); + + if ($storeCode) { + $store = Mage::app()->getStore($storeCode); + $value = $inherit ? $store->getWebsite()->getConfig($path) : $store->getConfig($path); + } elseif ($websiteCode && !$inherit) { + $value = Mage::app()->getWebsite($websiteCode)->getConfig($path); + } else { + $value = Mage::getConfig()->getNode('default/' . $path); + } + + return (string) $value === '1'; + } +} 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..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 @@ -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).') + Mage::helper('basicrum_analytics')->__('Brum Site ID must be a valid UUID v4 (e.g. e926c1a2-7e33-4f54-90d0-e6e31f3ad43d).') ); } + $this->setValue($value); + return parent::_beforeSave(); } } diff --git a/app/code/community/BasicRum/Analytics/Model/System/Config/Source/ConsentMode.php b/app/code/community/BasicRum/Analytics/Model/System/Config/Source/ConsentMode.php new file mode 100644 index 0000000..43c43ec --- /dev/null +++ b/app/code/community/BasicRum/Analytics/Model/System/Config/Source/ConsentMode.php @@ -0,0 +1,29 @@ +> + */ + public function toOptionArray(): array + { + $helper = Mage::helper('basicrum_analytics'); + + return array( + array( + 'value' => '0', + 'label' => $helper->__('Monitor without consent (immediate monitoring)'), + ), + array( + 'value' => '1', + 'label' => $helper->__('Require consent before monitoring (recommended)'), + ), + ); + } +} 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..a12d51a --- /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 Endpoints (recommended)'), + ), + array( + 'value' => '1', + 'label' => $helper->__('Allow HTTP Beacon Endpoints for local testing'), + ), + ); + } +} 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/config.xml b/app/code/community/BasicRum/Analytics/etc/config.xml index fae1b39..0795029 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,13 +63,15 @@ - 0 + 0 + 1 0 - 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..eb98c90 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,46 +45,78 @@ disabled - + text + basicrum_analytics/adminhtml_system_config_form_field_requiredSetting + basicrum_analytics/system_config_backend_beaconEndpoint 2 1 1 1 - Example: https://www.xxxxxx.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 3 1 1 1 - Example: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx]]> + Example: e926c1a2-7e33-4f54-90d0-e6e31f3ad43d]]> - - - - - text - 15 - 1 - 1 - 1 - - - + + select - basicrum_analytics/adminhtml_system_config_form_field_consentInfo adminhtml/system_config_source_yesno - 1 + basicrum_analytics/privacy/strip_query_string + 4 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 parameters are not changed. + + +
general
+ 1 +
+
+
+ + + select + basicrum_analytics/system_config_source_consentMode + basicrum_analytics/privacy/opt_in_required + 5 + 1 + 1 + 1 + Choose whether Basicrum may begin monitoring immediately or must wait for explicit consent on each page. + + +
general
+ 1 +
+
+ + note + basicrum_analytics/adminhtml_system_config_form_field_consentInfo + 6 + 1 + 1 + 1 + + +
general
+ 1 +
+ 1 +
+
-
+ text @@ -93,15 +125,22 @@ 1 1 - + select adminhtml/system_config_source_yesno + basicrum_analytics/wait_after_onload/enabled 1 1 1 1 - + + +
general
+ 1 +
+
+ text @@ -110,9 +149,13 @@ 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 + +
general
+ 1 +
+ 1
@@ -125,15 +168,37 @@ 1 1 + + + select + basicrum_analytics/system_config_source_httpPolicy + 1 + 1 + 1 + 1 + Allow HTTP Beacon Endpoints only for local testing. Keep HTTPS enforcement enabled on production stores. + + +
general
+ 1 +
+
+
select adminhtml/system_config_source_yesno - 1 + 2 1 1 1 Enable to load non-minified loader scripts for debugging purposes. + + +
general
+ 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..f2f5008 --- /dev/null +++ b/app/code/community/BasicRum/Analytics/sql/basicrum_analytics_setup/install-1.1.0.php @@ -0,0 +1,57 @@ +startSetup(); + +$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') + ->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); +} + +$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 7ab2b99..ea289ab 100644 --- a/app/locale/en_US/BasicRum_Analytics.csv +++ b/app/locale/en_US/BasicRum_Analytics.csv @@ -1,13 +1,33 @@ -"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" -"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 Endpoint","Beacon Endpoint" +"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" +"HTTP Strictness","HTTP Strictness" +"Require HTTPS Beacon Endpoints (recommended)","Require HTTPS Beacon Endpoints (recommended)" +"Allow HTTP Beacon Endpoints for local testing","Allow HTTP Beacon Endpoints 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." "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." +"Beacon Endpoint is required while monitoring is enabled. Monitoring remains inactive.","Beacon Endpoint is required while monitoring is enabled. Monitoring remains inactive." +"Enter a valid HTTP or HTTPS Beacon Endpoint. Monitoring remains inactive.","Enter a valid HTTP or HTTPS Beacon Endpoint. 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 Endpoint must be a valid HTTP or HTTPS URL.","Beacon Endpoint 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 new file mode 100644 index 0000000..658d754 --- /dev/null +++ b/docs/admin-ui-parity-checklist.md @@ -0,0 +1,179 @@ +# Admin UI parity checklist + +This checklist tracks Magento 1 admin UI parity with the Basicrum WordPress +settings UI. It focuses on equivalent administrator outcomes rather than making +Magento look or behave exactly like WordPress. + +## Inspection baseline + +- Inspected: 2026-09-17 +- WordPress: WordPress 7.1 with the current `basicrum-wordpress` implementation +- Magento 1: OpenMage 20.18.0 with the current Magento 1 plugin branch +- Scope: settings presentation, discoverability, validation feedback, consent + integration guidance, and platform-specific configuration behavior + +Legend: + +- `[x]` Parity is present or the platform-specific behavior is intentionally kept. +- `[ ]` Work remains. +- `Partial` means the core capability exists but the administrator experience is + not yet equivalent. + +## Core configuration + +- [x] Provide an Enable Monitoring control. +- [x] Provide a required Beacon Endpoint field. +- [x] Provide a required Brum Site ID field with UUID v4 guidance. +- [x] Display the bundled Boomerang version. + - Partial: WordPress presents this as read-only text; Magento uses a disabled + select-style control. +- [x] Default genuinely new installations to consent-controlled monitoring. +- [x] Provide Wait After Onload enablement and a millisecond delay field. +- [x] Document and enforce the 0–30000 millisecond delay range. +- [x] Provide a Use Unminified Loaders developer setting. +- [x] Keep privacy controls and consent guidance within General Settings, with + separate Wait After Onload and Developer sections. Existing privacy + configuration paths and scope inheritance are preserved. + +## Consent and privacy experience + +- [x] Replace the Magento `Yes`/`No` consent choice with labels that explain the + consequences, equivalent to WordPress's “Monitor without consent” and “Require + consent before monitoring” choices. +- [x] Make the Magento consent integration guidance use the available content + width. + - Implemented as a separate full-width configuration row so the instructions + remain readable in Magento's native table layout. +- [x] Hide the consent integration guidance when consent-controlled monitoring is + disabled. + - Implemented with Magento's native field dependency mechanism, including + inherited Website and Store View configuration. +- [x] Keep manual callbacks as the intentional Magento 1 consent integration. + - Magento 1/OpenMage does not provide a standardized consent-provider API + comparable to WordPress. Native Cookie Restriction Mode is a basic persisted + allow signal, while third-party consent tools expose provider-specific APIs. + - Automatic native or third-party provider adapters are deferred to a future + 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. +- [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. +- [x] Explain cookie removal and that data already sent cannot be retracted. +- [x] Explain safe re-grant behavior after withdrawal. +- [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 Endpoint. + +## Validation and state feedback + +- [x] Show a visible incomplete-configuration state when Beacon Endpoint or Brum Site ID + is missing, making clear that monitoring remains disabled. +- [x] Add field-level invalid-state feedback comparable to WordPress warnings and + inline errors while retaining Magento's server-side validation. + - 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. +- [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, 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. + - Consent guidance additionally requires consent-controlled mode, including + when the controlling values are inherited at Website or Store View scope. + +## Remaining WordPress controls + +- [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. +- [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 + +- [x] Align product casing and field terminology with Basicrum. + - User-facing Magento copy now consistently uses `Basicrum`, `Beacon Endpoint`, and + `Brum Site ID`; internal `BasicRum_Analytics` class and module identifiers are + retained for backward compatibility. `Beacon Endpoint` follows the Basicrum + backoffice terminology. +- [x] Give the Magento configuration page a clearer Basicrum identity while + retaining native Magento administration patterns. + - 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. +- [ ] Refresh `docs/media/admin-area.png` after moving privacy into General Settings + and renaming the Beacon Endpoint field. + - The previous capture predates these UI changes. + +## Intentional Magento-specific behavior + +- [x] Preserve Default, Website, and Store View configuration scopes and inheritance. +- [x] Retain Magento's System Configuration placement and accordion structure. +- [x] Retain native Magento controls where they communicate the choice clearly. +- [x] Retain legacy Magento callback aliases for existing integrations. +- [x] Keep the current script placement unless a separate behavioral requirement + demonstrates that a configurable position is safe and useful. + +## Suggested processing order + +### P0 — consent clarity and configuration safety + +- [x] Fix the consent guidance width and wrapping. +- [x] Conditionally display consent guidance. +- [x] Use plain-language consent choices. +- [x] Add incomplete and invalid configuration feedback. + +### P1 — integration parity + +- [x] Document manual consent integration as the supported Magento 1 strategy. +- [x] Improve manual integration examples and copy actions. +- [x] Resolve Strip Query Strings and HTTP-policy parity. + +### Deferred — consent-provider adapters + +- [ ] Investigate optional adapters for Magento Cookie Restriction Mode and named + third-party consent tools when they expose reliable allow and withdrawal APIs. +- [ ] If adapters are added, provide explicit selection, active-provider status, + diagnostics, and a clear next action instead of heuristic auto-detection. + +### P2 — refinement + +- [x] Resolve Track Admin Users applicability. +- [x] Align terminology and branding. +- [x] Review narrow-viewport presentation. +- [x] Update the admin screenshot after the UI stabilizes. + +## Completion criteria + +- [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. +- [x] Platform-specific differences are documented and intentional. +- [x] Updated screenshots match the shipped admin UI. diff --git a/docs/media/admin-area.png b/docs/media/admin-area.png index c4c9841..71f6cb4 100644 Binary files a/docs/media/admin-area.png and b/docs/media/admin-area.png differ 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/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/js/basicrum/loaders/boomerang-loader-v15.min.js b/js/basicrum/loaders/boomerang-loader-v15.min.js index 6cf40af..5367b0e 100644 --- a/js/basicrum/loaders/boomerang-loader-v15.min.js +++ b/js/basicrum/loaders/boomerang-loader-v15.min.js @@ -1 +1 @@ -(()=>{if(!window.BOOMR||!window.BOOMR.version&&!window.BOOMR.snippetExecuted){window.BOOMR=window.BOOMR||{};if(Object.prototype.hasOwnProperty.call(window.BOOMR,"url")&&window.BOOMR.url){window.BOOMR.snippetStart=(new Date).getTime();window.BOOMR.snippetExecuted=!0;window.BOOMR.snippetVersion=15;var d=(document.currentScript||document.getElementsByTagName("script")[0]).parentNode,a=!1,e=document.createElement("link");if(e.relList&&"function"==typeof e.relList.supports&&e.relList.supports("preload")&&"as"in e){window.BOOMR.snippetMethod="p";e.href=window.BOOMR.url;e.rel="preload";e.as="script";e.addEventListener("load",function(){if(!a){var e=document.createElement("script");e.id="boomr-scr-as";e.src=window.BOOMR.url;e.async=!0;d.appendChild(e);a=!0}});e.addEventListener("error",function(){t(!0)});setTimeout(function(){a||t(!0)},3e3);BOOMR_lstart=(new Date).getTime();d.appendChild(e)}else t(!1);window.addEventListener?window.addEventListener("load",n,!1):window.attachEvent&&window.attachEvent("onload",n)}}function t(t){a=!0;var e,n,o=document,i=window;window.BOOMR.snippetMethod=t?"if":"i";e=function(e,t){var n=o.createElement("script");n.id=t||"boomr-if-as";n.src=window.BOOMR.url;BOOMR_lstart=(new Date).getTime();(e=e||o.body).appendChild(n)};if(!window.addEventListener&&window.attachEvent&&navigator.userAgent.match(/MSIE [678]\./)){window.BOOMR.snippetMethod="s";e(d,"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";d.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){window.BOOMR_onload=e&&e.timeStamp||(new Date).getTime()}})(); \ No newline at end of file +(function(){if(window.BOOMR&&(window.BOOMR.version||window.BOOMR.snippetExecuted)){return}window.BOOMR=window.BOOMR||{};if(!Object.prototype.hasOwnProperty.call(window.BOOMR,"url")||!window.BOOMR.url){return}window.BOOMR.snippetStart=(new Date).getTime();window.BOOMR.snippetExecuted=true;window.BOOMR.snippetVersion=15;var e=document.currentScript||document.getElementsByTagName("script")[0],a=e.parentNode,s=false,t=3e3;function n(){if(s){return}var e=document.createElement("script");e.id="boomr-scr-as";e.src=window.BOOMR.url;e.async=true;a.appendChild(e);s=true}function o(e){s=true;var t,o=document,n,i,r,d=window;window.BOOMR.snippetMethod=e?"if":"i";n=function(e,t){var n=o.createElement("script");n.id=t||"boomr-if-as";n.src=window.BOOMR.url;BOOMR_lstart=(new Date).getTime();e=e||o.body;e.appendChild(n)};if(!window.addEventListener&&window.attachEvent&&navigator.userAgent.match(/MSIE [678]\./)){window.BOOMR.snippetMethod="s";n(a,"boomr-async");return}i=document.createElement("IFRAME");i.src="about:blank";i.title="";i.role="presentation";i.loading="eager";r=(i.frameElement||i).style;r.width=0;r.height=0;r.border=0;r.display="none";a.appendChild(i);try{d=i.contentWindow;o=d.document.open()}catch(e){t=document.domain;i.src="javascript:var d=document.open();d.domain='"+t+"';void 0;";d=i.contentWindow;o=d.document.open()}d._boomrl=function(){n()};if(d.addEventListener){d.addEventListener("load",d._boomrl,false)}else if(d.attachEvent){d.attachEvent("onload",d._boomrl)}o.close()}var i=document.createElement("link");if(i.relList&&typeof i.relList.supports==="function"&&i.relList.supports("preload")&&"as"in i){window.BOOMR.snippetMethod="p";i.href=window.BOOMR.url;i.rel="preload";i.as="script";i.addEventListener("load",n);i.addEventListener("error",function(){o(true)});setTimeout(function(){if(!s){o(true)}},t);BOOMR_lstart=(new Date).getTime();a.appendChild(i)}else{o(false)}function r(e){window.BOOMR_onload=e&&e.timeStamp||(new Date).getTime()}if(window.addEventListener){window.addEventListener("load",r,false)}else if(window.attachEvent){window.attachEvent("onload",r)}})(); \ No newline at end of file diff --git a/js/basicrum/loaders/consent-boomerang-loader-v1-15.js b/js/basicrum/loaders/consent-boomerang-loader-v1-15.js index b66b0aa..20c955c 100644 --- a/js/basicrum/loaders/consent-boomerang-loader-v1-15.js +++ b/js/basicrum/loaders/consent-boomerang-loader-v1-15.js @@ -1,22 +1,26 @@ -// Ultra-concise version +/*! Basicrum consent wrapper: exposes OPT_IN_BASICRUM_LOADER_WRAPPER() and OPT_OUT_BASICRUM_LOADER_WRAPPER(). */ (function(mainWin) { - function loadBoomr(w) { - // Your opted-in code here + // Consent wrapper opt-in callback: execute the standard Boomerang loader. + mainWin.OPT_IN_BASICRUM_LOADER_WRAPPER = function() { + // Keep the block between these markers byte-for-byte identical to + // boomerang-loader-v15.js. The browser tests enforce this contract. + /* BEGIN BASICRUM STANDARD LOADER */ +(function() { // Boomerang Loader Snippet version 15 - if (w.BOOMR && (w.BOOMR.version || w.BOOMR.snippetExecuted)) { + if (window.BOOMR && (window.BOOMR.version || window.BOOMR.snippetExecuted)) { return; } - w.BOOMR = w.BOOMR || {}; + window.BOOMR = window.BOOMR || {}; // Ensure url is an own property (protect against prototype pollution) - if (!Object.prototype.hasOwnProperty.call(w.BOOMR, "url") || !w.BOOMR.url) { + if (!Object.prototype.hasOwnProperty.call(window.BOOMR, "url") || !window.BOOMR.url) { return; } - w.BOOMR.snippetStart = new Date().getTime(); - w.BOOMR.snippetExecuted = true; - w.BOOMR.snippetVersion = 15; + window.BOOMR.snippetStart = new Date().getTime(); + window.BOOMR.snippetExecuted = true; + window.BOOMR.snippetVersion = 15; // document.currentScript is supported in all browsers other than IE var where = document.currentScript || document.getElementsByTagName("script")[0], @@ -36,7 +40,7 @@ var script = document.createElement("script"); script.id = "boomr-scr-as"; - script.src = w.BOOMR.url; + script.src = window.BOOMR.url; // Not really needed since dynamic scripts are async by default and the script is already in cache at this point, // but some naive parsers will see a missing async attribute and think we're not async @@ -55,16 +59,16 @@ var dom, doc = document, bootstrap, iframe, iframeStyle, - win = w; + win = window; - w.BOOMR.snippetMethod = wasFallback ? "if" : "i"; + window.BOOMR.snippetMethod = wasFallback ? "if" : "i"; // Adds Boomerang within the iframe bootstrap = function(parent, scriptId) { var script = doc.createElement("script"); script.id = scriptId || "boomr-if-as"; - script.src = w.BOOMR.url; + script.src = window.BOOMR.url; BOOMR_lstart = new Date().getTime(); @@ -76,8 +80,8 @@ // * IE 6/7 don't support 'about:blank' for an iframe src (it triggers warnings on secure sites) // * IE 8 required a doc write call for it to work, which is bad practice // This means loading on IE 6/7/8 may cause SPoF. - if (!w.addEventListener && w.attachEvent && navigator.userAgent.match(/MSIE [678]\./)) { - w.BOOMR.snippetMethod = "s"; + if (!window.addEventListener && window.attachEvent && navigator.userAgent.match(/MSIE [678]\./)) { + window.BOOMR.snippetMethod = "s"; bootstrap(parentNode, "boomr-async"); @@ -152,18 +156,18 @@ typeof link.relList.supports === "function" && link.relList.supports("preload") && ("as" in link)) { - w.BOOMR.snippetMethod = "p"; + window.BOOMR.snippetMethod = "p"; // Set attributes to trigger a Preload - link.href = w.BOOMR.url; + link.href = window.BOOMR.url; link.rel = "preload"; link.as = "script"; // Add our script tag if successful, fallback to iframe if not link.addEventListener("load", promote); link.addEventListener("error", function() { - iframeLoader(true); - }); + iframeLoader(true); + }); // Have a fallback in case Preload does nothing or is slow setTimeout(function() { @@ -185,54 +189,77 @@ // Save when the onload event happened, in case this is a non-NavigationTiming browser function boomerangSaveLoadTime(e) { - w.BOOMR_onload = (e && e.timeStamp) || new Date().getTime(); + window.BOOMR_onload = (e && e.timeStamp) || new Date().getTime(); } - if (w.addEventListener) { - w.addEventListener("load", boomerangSaveLoadTime, false); + if (window.addEventListener) { + window.addEventListener("load", boomerangSaveLoadTime, false); } - else if (w.attachEvent) { - w.attachEvent("onload", boomerangSaveLoadTime); + else if (window.attachEvent) { + window.attachEvent("onload", boomerangSaveLoadTime); } - } - - // Helper to build cookie attributes - function getCookieAttrs() { +})(); + /* END BASICRUM STANDARD LOADER */ + }; + + // 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 - 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 + // 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 Boomerang is loaded, disable it and remove its cookies 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..a7b7df9 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,2 @@ -(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 +/*! Basicrum consent wrapper: exposes OPT_IN_BASICRUM_LOADER_WRAPPER() and OPT_OUT_BASICRUM_LOADER_WRAPPER(). */ +(function(r){r.OPT_IN_BASICRUM_LOADER_WRAPPER=function(){(function(){if(window.BOOMR&&(window.BOOMR.version||window.BOOMR.snippetExecuted)){return}window.BOOMR=window.BOOMR||{};if(!Object.prototype.hasOwnProperty.call(window.BOOMR,"url")||!window.BOOMR.url){return}window.BOOMR.snippetStart=(new Date).getTime();window.BOOMR.snippetExecuted=true;window.BOOMR.snippetVersion=15;var e=document.currentScript||document.getElementsByTagName("script")[0],d=e.parentNode,O=false,t=3e3;function n(){if(O){return}var e=document.createElement("script");e.id="boomr-scr-as";e.src=window.BOOMR.url;e.async=true;d.appendChild(e);O=true}function i(e){O=true;var t,i=document,n,o,r,a=window;window.BOOMR.snippetMethod=e?"if":"i";n=function(e,t){var n=i.createElement("script");n.id=t||"boomr-if-as";n.src=window.BOOMR.url;BOOMR_lstart=(new Date).getTime();e=e||i.body;e.appendChild(n)};if(!window.addEventListener&&window.attachEvent&&navigator.userAgent.match(/MSIE [678]\./)){window.BOOMR.snippetMethod="s";n(d,"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";d.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){window.BOOMR.snippetMethod="p";o.href=window.BOOMR.url;o.rel="preload";o.as="script";o.addEventListener("load",n);o.addEventListener("error",function(){i(true)});setTimeout(function(){if(!O){i(true)}},t);BOOMR_lstart=(new Date).getTime();d.appendChild(o)}else{i(false)}function r(e){window.BOOMR_onload=e&&e.timeStamp||(new Date).getTime()}if(window.addEventListener){window.addEventListener("load",r,false)}else if(window.attachEvent){window.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=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..c9f3d58 --- /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:loaders": "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..10f9f1d --- /dev/null +++ b/tests/check-package.sh @@ -0,0 +1,58 @@ +#!/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)" +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 [[ "$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 + +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 + +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/Model/System/Config/Source + 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 URL|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)" +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/js/admin-consent-info.spec.js b/tests/js/admin-consent-info.spec.js new file mode 100644 index 0000000..495c1f4 --- /dev/null +++ b/tests/js/admin-consent-info.spec.js @@ -0,0 +1,90 @@ +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(` + +

+ + +

+ +

+ + +

+ `); +} + +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/js/build-loaders.js b/tests/js/build-loaders.js new file mode 100644 index 0000000..d51c741 --- /dev/null +++ b/tests/js/build-loaders.js @@ -0,0 +1,27 @@ +const fs = require("node:fs"); +const path = require("node:path"); +const UglifyJS = require("uglify-js"); + +const root = path.resolve(__dirname, "../.."); +const loaders = [ + "boomerang-loader-v15", + "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..1e138e1 --- /dev/null +++ b/tests/js/check-minified.js @@ -0,0 +1,33 @@ +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 [ + "boomerang-loader-v15", + "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..4794e17 --- /dev/null +++ b/tests/js/loaders.spec.js @@ -0,0 +1,285 @@ +const path = require("node:path"); +const { test: base, expect } = require("@playwright/test"); + +// Match the WordPress harness: no unrecognized request may leave a test page. +const test = base.extend({ + page: async ({ page }, use) => { + const unexpectedRequests = []; + await page.route("**/*", async (route) => { + unexpectedRequests.push(route.request().url()); + await route.abort("blockedbyclient"); + }); + await use(page); + expect(unexpectedRequests).toEqual([]); + } +}); + +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; + let boomerangRequests = 0; + 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) => { + boomerangRequests += 1; + 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, + boomerangRequests: () => boomerangRequests, + 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 }) => { + const harness = 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 }); + expect(harness.boomerangRequests()).toBe(1); + }); +} + +for (const loader of [ + "boomerang-loader-v15.js", + "boomerang-loader-v15.min.js", + "consent-boomerang-loader-v1-15.js", + "consent-boomerang-loader-v1-15.min.js" +]) { + test(`requires an own, nonempty Boomerang URL: ${loader}`, async ({ page }) => { + const harness = await preparePage(page); + for (const urlState of ["missing", "empty", "inherited"]) { + await page.evaluate(({ state, url }) => { + window.BOOMR = state === "inherited" ? Object.create({ url }) + : state === "empty" ? { url: "" } : {}; + }, { state: urlState, url: boomerangUrl }); + await page.addScriptTag({ path: loaderPath(loader) }); + if (loader.startsWith("consent-")) { + await page.evaluate(() => window.OPT_IN_BASICRUM_LOADER_WRAPPER()); + } + expect(await page.evaluate(() => ({ + executions: window.__bundleExecutions, + snippetExecuted: Boolean(window.BOOMR.snippetExecuted), + injectedScripts: document.querySelectorAll("#boomr-scr-as, #boomr-if-as, #boomr-async").length, + preloads: document.querySelectorAll('link[rel="preload"]').length + }))).toEqual({ executions: 0, snippetExecuted: false, injectedScripts: 0, preloads: 0 }); + expect(harness.boomerangRequests()).toBe(0); + } + }); +} + +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 }) => { + const harness = 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, + aliasesMatch: window.OPT_IN_BASIC_RUM === window.OPT_IN_BASICRUM_LOADER_WRAPPER + && window.OPT_OUT_BASIC_RUM === window.OPT_OUT_BASICRUM_LOADER_WRAPPER, + snippetExecuted: Boolean(window.BOOMR.snippetExecuted), + preloads: document.querySelectorAll('link[rel="preload"]').length + }))).toEqual({ + initCalls: 0, + executions: 0, + canonicalIn: "function", + canonicalOut: "function", + legacyIn: "function", + legacyOut: "function", + aliasesMatch: true, + snippetExecuted: false, + preloads: 0 + }); + expect(harness.boomerangRequests()).toBe(0); + }); + + test("repeated opt-in loads only once and persists no consent cookie", async ({ page }) => { + const harness = 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: "" }); + expect(harness.boomerangRequests()).toBe(1); + }); + + test("re-evaluating the wrapper does not load or reinitialize Boomerang", async ({ page }) => { + const harness = await preparePage(page); + await page.addScriptTag({ path: loaderPath(consentLoader) }); + await page.addScriptTag({ path: loaderPath(consentLoader) }); + expect(harness.boomerangRequests()).toBe(0); + await page.evaluate(() => window.OPT_IN_BASICRUM_LOADER_WRAPPER()); + await page.waitForFunction(() => window.__initCalls === 1); + await page.addScriptTag({ path: loaderPath(consentLoader) }); + await page.evaluate(() => window.OPT_IN_BASIC_RUM()); + expect(await page.evaluate(() => window.__initCalls)).toBe(1); + expect(harness.boomerangRequests()).toBe(1); + }); + + 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..6716b02 --- /dev/null +++ b/tests/js/real-boomerang.spec.js @@ -0,0 +1,193 @@ +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, 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({ + 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": "*" }, + 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(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, + stripQueryString: Boolean(options.stripQueryString) + }); + + return { + downloadStarted, + releaseDownload, + beaconRequests: () => beaconRequests, + beaconRequestData: () => beaconRequestData + }; +} + +async function waitForRealBoomerang(page) { + await expect.poll( + () => page.evaluate(() => window.BOOMR && window.BOOMR.version) + ).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" +]) { + 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/js/wordpress-parity.spec.js b/tests/js/wordpress-parity.spec.js new file mode 100644 index 0000000..3f408c8 --- /dev/null +++ b/tests/js/wordpress-parity.spec.js @@ -0,0 +1,120 @@ +const fs = require("node:fs"); +const path = require("node:path"); +const { createHash } = require("node:crypto"); +const { test, expect } = require("@playwright/test"); +const UglifyJS = require("uglify-js"); + +const root = path.resolve(__dirname, "../.."); +// Review changes in WordPress first, then update this baseline deliberately. +// https://github.com/basicrum/basicrum-wordpress/tree/64f19d9e5a9fbe580c12c19796e86e3ad0dd17ff +const revision = "64f19d9e5a9fbe580c12c19796e86e3ad0dd17ff"; +const hashes = { + "loaders/boomerang-loader-v15.js": "e22055fc1919b89ab8ba6530a415636c6d31df328c10f096a500ae5a37e93d6d", + "loaders/boomerang-loader-v15.min.js": "a9c283722d1d2eb97a7e1820d51ba3c317a5f2641f7358922931ae305aab0281", + "loaders/consent-boomerang-loader-v1-15.js": "23163a2f6b51db6010ae415762427105b21ca27da5ff6346a5ca6b9a5f8f6f4c", + "loaders/consent-boomerang-loader-v1-15.min.js": "2f8b929b49a7e72b9b7531385c3fd981395cc767bea0f3a21f0c3e2658ce8bb1", + "boomr/boomerang-1.815.60.cutting-edge.min.js": "90e8a1c85949b10d43e441efc3f0545f95e4384e26ee3042344a8b2b4110589c" +}; + +function sha256(contents) { + return createHash("sha256").update(contents).digest("hex"); +} + +function readMagentoAsset(asset) { + return fs.readFileSync(path.join(root, "js/basicrum", asset.replace(/^boomr\//, "boomerangs/")), "utf8"); +} + +// Exact, reviewed additions only. Do not strip arbitrary marked blocks: that +// would let unrelated edits evade the upstream hash check. These additions +// retain Magento's existing compatibility and delayed-beacon protections. +const magentoAdditions = [ + { + before: " mainWin.basicRumBoomerangConfig = null;\n", + addition: " mainWin.basicRumConsentWithdrawn = true;\n", + after: " }\n" + }, + { + before: " if (mainWin.BOOMR) {\n", + addition: ` var waitPlugin = mainWin.BOOMR.plugins && mainWin.BOOMR.plugins.WaitAfterOnload; + if (waitPlugin && waitPlugin.timer !== null) { + mainWin.clearTimeout(waitPlugin.timer); + waitPlugin.timer = null; + } + +`, + after: ' if (typeof mainWin.BOOMR.disable === "function") {\n' + }, + { + before: ' mainWin.BOOMR.utils.removeCookie("BA");\n', + addition: ` mainWin.BOOMR.utils.removeCookie("BRUM_CONSENT"); + mainWin.BOOMR.utils.removeCookie("BOOMR_CONSENT"); +`, + after: " }\n" + }, + { + before: ' removeCookie("BA");\n', + addition: ` removeCookie("BRUM_CONSENT"); + removeCookie("BOOMR_CONSENT"); +`, + after: " };\n" + }, + { + before: " };\n", + addition: ` + // 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; +`, + after: "})(window);\n" + } +]; + +for (const asset of [ + "loaders/boomerang-loader-v15.js", + "loaders/boomerang-loader-v15.min.js", + "boomr/boomerang-1.815.60.cutting-edge.min.js" +]) { + test(`WordPress baseline: ${asset}`, () => { + expect(sha256(readMagentoAsset(asset)), `WordPress ${revision}: ${asset}`).toBe(hashes[asset]); + }); +} + +test("consent wrapper embeds the unchanged WordPress standard loader", () => { + const consent = readMagentoAsset("loaders/consent-boomerang-loader-v1-15.js"); + const wrapped = consent.match( + /\/\* BEGIN BASICRUM STANDARD LOADER \*\/\n([\s\S]*?)\n \/\* END BASICRUM STANDARD LOADER \*\// + ); + expect(wrapped).not.toBeNull(); + expect(wrapped[1]).toBe(readMagentoAsset("loaders/boomerang-loader-v15.js")); +}); + +test("consent wrapper differs from WordPress only by reviewed Magento additions", () => { + let consent = readMagentoAsset("loaders/consent-boomerang-loader-v1-15.js"); + for (const { before, addition, after } of magentoAdditions) { + const parts = consent.split(before + addition + after); + expect(parts.length, `Expected exactly one Magento addition: ${addition}`).toBe(2); + consent = parts.join(before + after); + } + expect(sha256(consent)).toBe(hashes["loaders/consent-boomerang-loader-v1-15.js"]); + + const minified = UglifyJS.minify(consent, { + compress: false, + mangle: true, + output: { comments: /^!/ } + }); + expect(minified.error).toBeUndefined(); + expect(sha256(minified.code)).toBe(hashes["loaders/consent-boomerang-loader-v1-15.min.js"]); +}); + +// Optional local cross-check; ordinary CI needs neither a sibling repository +// nor network access. Point this at the reviewed WordPress checkout. +if (process.env.BASICRUM_WORDPRESS_ROOT) { + test("pinned baseline matches the supplied WordPress checkout", () => { + for (const [asset, hash] of Object.entries(hashes)) { + const contents = fs.readFileSync(path.join( + process.env.BASICRUM_WORDPRESS_ROOT, "plugins/basicrum/assets/js", asset + )); + expect(sha256(contents), `WordPress ${revision}: ${asset}`).toBe(hash); + } + }); +} diff --git a/tests/php/bootstrap.php b/tests/php/bootstrap.php new file mode 100644 index 0000000..0bb0f25 --- /dev/null +++ b/tests/php/bootstrap.php @@ -0,0 +1,510 @@ +getElementHtml(); + } + + public function render(Varien_Data_Form_Element_Abstract $element) + { + return '' + . $this->_getElementHtml($element) + . ''; + } +} + +class Basicrum_Test_Form +{ + private $elements = array(); + + public function addElement($id, Varien_Data_Form_Element_Abstract $element) + { + $this->elements[$id] = $element; + $element->setForm($this); + return $this; + } + + public function getElement($id) + { + return isset($this->elements[$id]) ? $this->elements[$id] : null; + } +} + +class Varien_Data_Form_Element_Abstract +{ + private $htmlId; + private $value; + private $form; + private $class = 'input-text'; + + public function __construct($htmlId, $value = '') + { + $this->htmlId = $htmlId; + $this->value = $value; + } + + public function getHtmlId() + { + return $this->htmlId; + } + + public function getValue() + { + return $this->value; + } + + public function setValue($value) + { + $this->value = $value; + return $this; + } + + public function getForm() + { + return $this->form; + } + + public function setForm($form) + { + $this->form = $form; + return $this; + } + + public function getClass() + { + return $this->class; + } + + public function setClass($class) + { + $this->class = $class; + return $this; + } + + public function addClass($class) + { + $this->class = trim($this->class . ' ' . $class); + return $this; + } + + public function getElementHtml() + { + return ''; + } +} + +class Mage_Core_Model_Config_Data +{ + private $value; + private $groups = array(); + private $storeCode; + private $websiteCode; + + public function setValue($value) + { + $this->value = $value; + return $this; + } + + public function getValue() + { + return $this->value; + } + + public function setGroups(array $groups) + { + $this->groups = $groups; + return $this; + } + + public function getGroups() + { + return $this->groups; + } + + public function setStoreCode($storeCode) + { + $this->storeCode = $storeCode; + return $this; + } + + public function getStoreCode() + { + return $this->storeCode; + } + + public function setWebsiteCode($websiteCode) + { + $this->websiteCode = $websiteCode; + return $this; + } + + public function getWebsiteCode() + { + return $this->websiteCode; + } + + 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 $fetchAllResults; + public $selects = array(); + + public function __construct(array $fetchResults, array $fetchAllResults = array()) + { + $this->fetchResults = $fetchResults; + $this->fetchAllResults = $fetchAllResults; + } + + 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); + } + + 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 +{ + public $saved = array(); + + public function getNode($path) + { + if (strpos($path, 'default/') !== 0) { + throw new RuntimeException('Unexpected configuration path: ' . $path); + } + + return Mage::getStoreConfig(substr($path, 8)); + } + + 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, array $fetchAllResults = array()) + { + $this->connection = new Basicrum_Test_Connection($fetchResults, $fetchAllResults); + } + + 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 $stores = array(); + public $websites = array(); + + public function __construct() + { + $this->request = new Basicrum_Test_Request(); + } + + public function getRequest() + { + return $this->request; + } + + public function getStore($code) + { + return $this->stores[$code]; + } + + public function getWebsite($code) + { + return $this->websites[$code]; + } +} + +class Basicrum_Test_Website +{ + public $config = array(); + + public function getConfig($path) + { + return array_key_exists($path, $this->config) + ? $this->config[$path] : Mage::getConfig()->getNode('default/' . $path); + } +} + +class Basicrum_Test_Store +{ + public $config = array(); + private $website; + + public function __construct(Basicrum_Test_Website $website) + { + $this->website = $website; + } + + public function getWebsite() + { + return $this->website; + } + + public function getConfig($path) + { + return array_key_exists($path, $this->config) + ? $this->config[$path] : $this->website->getConfig($path); + } +} + +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/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', + 'basicrum_analytics/developer/development_mode' => '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..bfcfa36 --- /dev/null +++ b/tests/php/run.php @@ -0,0 +1,955 @@ +_beforeSave(); + } +} + +class Basicrum_Test_BeaconBackend extends BasicRum_Analytics_Model_System_Config_Backend_BeaconEndpoint +{ + public function validate() + { + return $this->_beforeSave(); + } +} + +$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['general privacy controls preserve paths scopes and installation defaults'] = function () use ($root) { + $xml = simplexml_load_file($root . '/app/code/community/BasicRum/Analytics/etc/system.xml'); + $groups = $xml->sections->basicrum_analytics->groups; + basicrum_assert_true(!isset($groups->privacy), 'privacy must not have a separate admin accordion'); + foreach (array('strip_query_string', 'opt_in_required') as $name) { + $field = $groups->general->fields->{$name}; + basicrum_assert_same( + 'basicrum_analytics/privacy/' . $name, + (string) $field->config_path, + 'moving ' . $name . ' must preserve its stored configuration path' + ); + foreach (array('default', 'website', 'store') as $scope) { + basicrum_assert_same('1', (string) $field->{'show_in_' . $scope}, $name . ': missing scope ' . $scope); + } + } + $defaults = simplexml_load_file($root . '/app/code/community/BasicRum/Analytics/etc/config.xml') + ->default->basicrum_analytics; + basicrum_assert_same('0', (string) $defaults->general->enabled, 'monitoring must be disabled by default'); + basicrum_assert_same('1', (string) $defaults->privacy->opt_in_required, 'new installs must require consent'); + basicrum_assert_same('0', (string) $defaults->privacy->strip_query_string, 'query-string default must not change'); +}; + +$tests['admin consent choices preserve values and explain behavior'] = function () { + basicrum_test_reset(); + + $options = (new BasicRum_Analytics_Model_System_Config_Source_ConsentMode())->toOptionArray(); + + basicrum_assert_same('0', $options[0]['value'], 'immediate mode must retain its stored value'); + basicrum_assert_contains( + 'Monitor without consent', + $options[0]['label'], + 'immediate mode must explain that consent is not required' + ); + basicrum_assert_same('1', $options[1]['value'], 'consent-controlled mode must retain its stored value'); + basicrum_assert_contains( + 'Require consent before monitoring', + $options[1]['label'], + 'consent-controlled mode must explain that monitoring waits for consent' + ); +}; + +$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_general_consent_integration_info'; + $renderer = new BasicRum_Analytics_Block_Adminhtml_System_Config_Form_Field_ConsentInfo(); + $html = $renderer->render(new Varien_Data_Form_Element_Abstract($elementId)); + + basicrum_assert_contains('id="row_' . $elementId . '"', $html, 'guidance row must use Magento field row ID'); + basicrum_assert_contains('colspan="4"', $html, 'guidance must span the configuration table'); + basicrum_assert_contains( + 'OPT_IN_BASICRUM_LOADER_WRAPPER()', + $html, + 'guidance must retain the canonical opt-in callback' + ); + basicrum_assert_contains( + 'OPT_IN_BASIC_RUM()', + $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' + ); + 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, '', $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, + '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'); + $privacyFields = $xml->sections->basicrum_analytics->groups->general->fields; + basicrum_assert_same( + 'basicrum_analytics/system_config_source_consentMode', + (string) $privacyFields->opt_in_required->source_model, + 'consent control must use the plain-language source model' + ); + basicrum_assert_same( + '1', + (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' + ); + 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['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 = $generalFields; + $waitFields = $groups->wait_after_onload->fields; + $developerFields = $groups->developer->fields; + + basicrum_assert_same( + 'Basicrum', + (string) $xml->tabs->basicrum_analytics->label, + 'admin tab must use canonical product casing' + ); + basicrum_assert_same( + 'Basicrum Settings', + (string) $xml->sections->basicrum_analytics->label, + 'configuration page must clearly identify Basicrum' + ); + basicrum_assert_contains( + 'Basicrum — Real User Monitoring', + (string) $groups->general->comment, + 'General Settings introduction must identify the product' + ); + basicrum_assert_same('Enable Basicrum', (string) $generalFields->enabled->label, 'enable label must name Basicrum'); + basicrum_assert_same('Beacon Endpoint', (string) $generalFields->beacon_endpoint->label, 'Beacon label must match the Basicrum backoffice'); + basicrum_assert_same('Brum Site ID', (string) $generalFields->brum_site_id->label, 'Site ID label must match WordPress'); + basicrum_assert_same( + 'Boomerang Version', + (string) $generalFields->boomerang_version->label, + 'Boomerang label must match WordPress' + ); + $adminAcl = simplexml_load_file($root . '/app/code/community/BasicRum/Analytics/etc/adminhtml.xml'); + basicrum_assert_same( + 'Basicrum Settings', + (string) $adminAcl->acl->resources->admin->children->system->children->config + ->children->basicrum_analytics->title, + 'ACL title must use the visible settings-page name' + ); + + 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 Endpoint 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, 'general'), + 'query-string privacy must depend on monitoring being enabled' + ); + basicrum_assert_same( + $generalEnabledOnly, + basicrum_config_dependency_map($privacyFields->opt_in_required, 'general'), + 'consent mode must depend on monitoring being enabled' + ); + basicrum_assert_same( + array( + 'general/enabled' => '1', + 'general/opt_in_required' => '1', + ), + basicrum_config_dependency_map($privacyFields->consent_integration_info, 'general'), + 'consent guidance must require both enabled monitoring and consent-controlled mode' + ); + basicrum_assert_same( + $generalEnabledOnly, + 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/wait_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(); + + $form = new Basicrum_Test_Form(); + $enabled = new Varien_Data_Form_Element_Abstract('basicrum_analytics_general_enabled', '1'); + $beacon = new Varien_Data_Form_Element_Abstract('basicrum_analytics_general_beacon_endpoint', ''); + $siteId = new Varien_Data_Form_Element_Abstract('basicrum_analytics_general_brum_site_id', ''); + $form->addElement('basicrum_analytics_general_enabled', $enabled) + ->addElement('basicrum_analytics_general_beacon_endpoint', $beacon) + ->addElement('basicrum_analytics_general_brum_site_id', $siteId); + + $renderer = new BasicRum_Analytics_Block_Adminhtml_System_Config_Form_Field_RequiredSetting(); + $beaconHtml = $renderer->render($beacon); + $siteIdHtml = $renderer->render($siteId); + + basicrum_assert_contains('aria-required="true"', $beaconHtml, 'enabled Beacon Endpoint must be required'); + basicrum_assert_contains('aria-invalid="true"', $beaconHtml, 'missing Beacon Endpoint must be invalid'); + basicrum_assert_contains('validation-failed', $beaconHtml, 'missing Beacon Endpoint must be highlighted'); + basicrum_assert_contains( + 'Beacon Endpoint is required while monitoring is enabled', + $beaconHtml, + 'missing Beacon Endpoint must have field-level guidance' + ); + basicrum_assert_contains('aria-invalid="true"', $siteIdHtml, 'missing Site ID must be invalid'); + basicrum_assert_contains( + 'Brum Site ID is required while monitoring is enabled', + $siteIdHtml, + 'missing Site ID must have field-level guidance' + ); + basicrum_assert_contains( + 'Monitoring status: Blocked', + $siteIdHtml, + 'incomplete enabled configuration must identify its blocked state' + ); + basicrum_assert_contains( + 'Basicrum monitoring is enabled but inactive', + $siteIdHtml, + 'incomplete enabled configuration must display a page-level warning' + ); + basicrum_assert_contains( + 'Monitoring scripts are not emitted', + $siteIdHtml, + 'the warning must explain the runtime consequence' + ); + + $xml = simplexml_load_file($root . '/app/code/community/BasicRum/Analytics/etc/system.xml'); + $generalFields = $xml->sections->basicrum_analytics->groups->general->fields; + basicrum_assert_same( + 'basicrum_analytics/adminhtml_system_config_form_field_requiredSetting', + (string) $generalFields->beacon_endpoint->frontend_model, + 'Beacon Endpoint must use the required-setting renderer' + ); + basicrum_assert_same( + 'basicrum_analytics/adminhtml_system_config_form_field_requiredSetting', + (string) $generalFields->brum_site_id->frontend_model, + 'Site ID must use the required-setting renderer' + ); +}; + +$tests['admin required-setting feedback respects validity enabled state and resolved scope values'] = function () { + basicrum_test_reset(array( + 'basicrum_analytics/general/beacon_endpoint' => 'javascript:alert(1)', + 'basicrum_analytics/general/brum_site_id' => 'invalid', + )); + + $renderer = new BasicRum_Analytics_Block_Adminhtml_System_Config_Form_Field_RequiredSetting(); + + $validForm = new Basicrum_Test_Form(); + $validEnabled = new Varien_Data_Form_Element_Abstract('basicrum_analytics_general_enabled', '1'); + $validBeacon = new Varien_Data_Form_Element_Abstract( + 'basicrum_analytics_general_beacon_endpoint', + 'https://collector.example.test/beacon' + ); + $validSiteId = new Varien_Data_Form_Element_Abstract( + 'basicrum_analytics_general_brum_site_id', + '550e8400-e29b-41d4-a716-446655440000' + ); + $validForm->addElement('basicrum_analytics_general_enabled', $validEnabled) + ->addElement('basicrum_analytics_general_beacon_endpoint', $validBeacon) + ->addElement('basicrum_analytics_general_brum_site_id', $validSiteId) + ->addElement( + 'basicrum_analytics_general_opt_in_required', + new Varien_Data_Form_Element_Abstract('basicrum_analytics_general_opt_in_required', '0') + ); + + $validHtml = $renderer->render($validBeacon) . $renderer->render($validSiteId); + basicrum_assert_contains('aria-invalid="false"', $validHtml, 'valid required fields must not be invalid'); + basicrum_assert_not_contains('validation-advice', $validHtml, 'valid fields must not display advice'); + basicrum_assert_not_contains( + 'Basicrum monitoring is enabled but inactive', + $validHtml, + 'resolved valid scope values must suppress the inactive warning' + ); + basicrum_assert_contains( + 'Monitoring status: Active', + $validHtml, + 'valid immediate configuration must display active status' + ); + + $disabledForm = new Basicrum_Test_Form(); + $disabledEnabled = new Varien_Data_Form_Element_Abstract('basicrum_analytics_general_enabled', '0'); + $disabledBeacon = new Varien_Data_Form_Element_Abstract('basicrum_analytics_general_beacon_endpoint', ''); + $disabledSiteId = new Varien_Data_Form_Element_Abstract('basicrum_analytics_general_brum_site_id', ''); + $disabledForm->addElement('basicrum_analytics_general_enabled', $disabledEnabled) + ->addElement('basicrum_analytics_general_beacon_endpoint', $disabledBeacon) + ->addElement('basicrum_analytics_general_brum_site_id', $disabledSiteId); + + $disabledHtml = $renderer->render($disabledBeacon) . $renderer->render($disabledSiteId); + basicrum_assert_contains('aria-required="false"', $disabledHtml, 'disabled monitoring must make fields optional'); + basicrum_assert_contains('aria-invalid="false"', $disabledHtml, 'disabled empty fields must not be invalid'); + basicrum_assert_not_contains('validation-advice', $disabledHtml, 'disabled empty fields must not display advice'); + basicrum_assert_not_contains( + 'Basicrum monitoring is enabled but inactive', + $disabledHtml, + 'disabled monitoring must not display an inactive warning' + ); + basicrum_assert_contains( + 'Monitoring status: Disabled', + $disabledHtml, + 'disabled configuration must display disabled status' + ); + + $consentForm = new Basicrum_Test_Form(); + $consentEnabled = new Varien_Data_Form_Element_Abstract('basicrum_analytics_general_enabled', '1'); + $consentBeacon = new Varien_Data_Form_Element_Abstract( + 'basicrum_analytics_general_beacon_endpoint', + 'https://collector.example.test/beacon' + ); + $consentSiteId = new Varien_Data_Form_Element_Abstract( + 'basicrum_analytics_general_brum_site_id', + '550e8400-e29b-41d4-a716-446655440000' + ); + $consentRequired = new Varien_Data_Form_Element_Abstract( + 'basicrum_analytics_general_opt_in_required', + '1' + ); + $consentForm->addElement('basicrum_analytics_general_enabled', $consentEnabled) + ->addElement('basicrum_analytics_general_beacon_endpoint', $consentBeacon) + ->addElement('basicrum_analytics_general_brum_site_id', $consentSiteId) + ->addElement('basicrum_analytics_general_opt_in_required', $consentRequired); + $consentHtml = $renderer->render($consentSiteId); + basicrum_assert_contains( + 'Monitoring status: Waiting for consent', + $consentHtml, + 'valid consent-controlled configuration must display waiting status' + ); + + $invalidForm = new Basicrum_Test_Form(); + $invalidEnabled = new Varien_Data_Form_Element_Abstract('basicrum_analytics_general_enabled', '1'); + $invalidBeacon = new Varien_Data_Form_Element_Abstract('basicrum_analytics_general_beacon_endpoint', 'ftp://example.test'); + $invalidSiteId = new Varien_Data_Form_Element_Abstract( + 'basicrum_analytics_general_brum_site_id', + '550e8400-e29b-11d4-a716-446655440000' + ); + $invalidForm->addElement('basicrum_analytics_general_enabled', $invalidEnabled) + ->addElement('basicrum_analytics_general_beacon_endpoint', $invalidBeacon) + ->addElement('basicrum_analytics_general_brum_site_id', $invalidSiteId); + + $invalidHtml = $renderer->render($invalidBeacon) . $renderer->render($invalidSiteId); + basicrum_assert_contains( + 'Enter a valid HTTP or HTTPS Beacon Endpoint', + $invalidHtml, + 'invalid Beacon Endpoint must have field-level guidance' + ); + basicrum_assert_contains( + 'Enter a valid UUID v4 Brum Site ID', + $invalidHtml, + 'invalid Site ID must have field-level guidance' + ); + basicrum_assert_contains( + 'Monitoring status: Blocked', + $invalidHtml, + 'invalid enabled configuration must display blocked status' + ); +}; + +$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 Endpoint must be accepted' + ); + basicrum_assert_true( + BasicRum_Analytics_Helper_Data::isValidBeaconEndpoint('http://localhost:8080/beacon'), + 'HTTP Beacon Endpoint 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 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', + )); + + basicrum_assert_same( + 'https://collector.example.test/beacon', + $helper->getBeaconEndpoint(), + 'strict mode must upgrade the Beacon Endpoint 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'); + + 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'); + + 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 Endpoint' + ); +}; + +$tests['HTTPS storefronts never emit an HTTP collector even when HTTP is allowed'] = function () { + foreach (array('0', '1') as $allowHttp) { + foreach (array(false, true) as $secure) { + list($helper) = basicrum_test_reset(array( + 'basicrum_analytics/general/beacon_endpoint' => 'HTTP://collector.example.test/beacon?site=one', + 'basicrum_analytics/developer/development_mode' => $allowHttp, + )); + Mage::app()->getRequest()->secure = $secure; + $expected = $allowHttp === '1' && !$secure + ? 'HTTP://collector.example.test/beacon?site=one' + : 'https://collector.example.test/beacon?site=one'; + + basicrum_assert_same( + $expected, + $helper->getBeaconEndpoint(), + 'only an insecure storefront with HTTP explicitly allowed may use an HTTP collector' + ); + $snippet = (new BasicRum_Analytics_Block_Boomerang_Loader())->getBoomerangSnippet(); + basicrum_assert_contains( + json_encode($expected), + $snippet, + 'the rendered loader configuration must use the resolved transport policy' + ); + } + } +}; + +$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' + ); + + $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(); + }, Mage_Core_Exception::class, 'Beacon backend must reject non-HTTP schemes'); +}; + +$tests['Beacon backend resolves omitted and inherited HTTP policy at the edited scope'] = function () { + $path = 'basicrum_analytics/developer/development_mode'; + + foreach (array('0', '1') as $allowHttp) { + $opposite = $allowHttp === '1' ? '0' : '1'; + // Default, website, and store policy values; edited scope; submitted field. + $cases = array( + 'default omitted' => array($allowHttp, null, null, 'default', null), + 'website omitted' => array($opposite, $allowHttp, null, 'website', null), + 'store omitted with own value' => array($opposite, $opposite, $allowHttp, 'store', null), + 'store omitted with inherited value' => array($opposite, $allowHttp, null, 'store', null), + 'website now inherits default' => array( + $allowHttp, $opposite, null, 'website', array('inherit' => '1', 'value' => $opposite), + ), + 'store now inherits website' => array( + $opposite, $allowHttp, $opposite, 'store', array('inherit' => '1', 'value' => $opposite), + ), + 'store now inherits through website' => array( + $allowHttp, null, $opposite, 'store', array('inherit' => '1', 'value' => $opposite), + ), + ); + foreach (array('default', 'website', 'store') as $scope) { + $cases[$scope . ' explicit submission'] = array( + $opposite, $opposite, $opposite, $scope, array('value' => $allowHttp), + ); + } + + foreach ($cases as $name => $case) { + list($defaultPolicy, $websitePolicy, $storePolicy, $scope, $field) = $case; + basicrum_test_reset(array($path => $defaultPolicy)); + $website = new Basicrum_Test_Website(); + $store = new Basicrum_Test_Store($website); + if ($websitePolicy !== null) { + $website->config[$path] = $websitePolicy; + } + if ($storePolicy !== null) { + $store->config[$path] = $storePolicy; + } + Mage::app()->websites['selected_website'] = $website; + Mage::app()->stores['selected_store'] = $store; + + $beacon = new Basicrum_Test_BeaconBackend(); + if ($scope !== 'default') { + $beacon->setWebsiteCode('selected_website'); + } + if ($scope === 'store') { + $beacon->setStoreCode('selected_store'); + } + if ($field !== null) { + $beacon->setGroups(array('developer' => array('fields' => array('development_mode' => $field)))); + } + $beacon->setValue('http://collector.example.test/beacon?site=one')->validate(); + $scheme = $allowHttp === '1' ? 'http' : 'https'; + basicrum_assert_same( + $scheme . '://collector.example.test/beacon?site=one', + $beacon->getValue(), + $name . ' must resolve HTTP policy ' . $allowHttp . ' without using the admin store policy' + ); + } + } +}; + +$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 Endpoint must emit no scripts'); + + basicrum_test_reset(array('basicrum_analytics/general/beacon_endpoint' => 'javascript:alert(1)')); + basicrum_assert_same('', $block->getBoomerangSnippet(), 'invalid Beacon Endpoint 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 Endpoint 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', + '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('