diff --git a/.distignore b/.distignore index aa8df5b..7259877 100644 --- a/.distignore +++ b/.distignore @@ -14,3 +14,21 @@ composer.lock package.json pnpm-lock.yaml release.sh + +/tests +/scripts +/bin +/test-results +/playwright-report +/blob-report +Caddyfile +rector.php +.wp-env*.json +playwright.config.* +tailwind.config.* +pnpm-workspace.yaml +.editorconfig +.prettierrc.json +README.md +AGENTS.md +CLAUDE.md diff --git a/.gitattributes b/.gitattributes index 26a8e94..d5cb685 100644 --- a/.gitattributes +++ b/.gitattributes @@ -7,3 +7,6 @@ /.gitattributes export-ignore /.gitignore export-ignore /README.md export-ignore + +# SRI hashes depend on exact bytes, including line endings. +/resources/js/pinned/** text eol=lf diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 41d1983..3a9fc82 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,9 +1,14 @@ name: Release on: - schedule: - - cron: "0 8 * * 1" # At 08:00 on Monday. - workflow_dispatch: # Allows manual triggering + workflow_dispatch: # Releases require an explicit manual trigger on main. + +concurrency: + group: wordpress-release + cancel-in-progress: false + +permissions: + contents: read jobs: e2e: @@ -11,6 +16,7 @@ jobs: update: name: Update version + if: github.ref == 'refs/heads/main' needs: e2e runs-on: ubuntu-latest timeout-minutes: 10 @@ -20,7 +26,7 @@ jobs: steps: - name: Create release app token id: release-app - uses: actions/create-github-app-token@v3 + uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3 with: client-id: ${{ vars.RELEASE_APP_CLIENT_ID }} private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }} @@ -30,10 +36,11 @@ jobs: id: release-app-user env: GH_TOKEN: ${{ steps.release-app.outputs.token }} - run: echo "user-id=$(gh api "/users/${{ steps.release-app.outputs.app-slug }}[bot]" --jq .id)" >> "$GITHUB_OUTPUT" + APP_SLUG: ${{ steps.release-app.outputs.app-slug }} + run: echo "user-id=$(gh api "/users/${APP_SLUG}[bot]" --jq .id)" >> "$GITHUB_OUTPUT" - name: Check out repository - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 with: token: ${{ steps.release-app.outputs.token }} persist-credentials: true # Required to push the release commit as the app @@ -41,29 +48,30 @@ jobs: fetch-tags: true # Ensure tags are fetched - name: Install pnpm - uses: pnpm/action-setup@v5 + uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5 with: version: 10 - name: Install Node.js LTS - uses: actions/setup-node@v6 + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 with: node-version: lts/* cache: "pnpm" - name: Install dependencies - run: pnpm install + run: pnpm install --frozen-lockfile - name: Build assets run: pnpm build - name: Install PHP - uses: shivammathur/setup-php@v2 + uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # v2 with: php-version: "latest" + tools: composer:v2 - - name: Install Composer - uses: ramsey/composer-install@v4 + - name: Install Composer dependencies + run: composer install --no-interaction --prefer-dist --no-progress - name: Downgrade PHP code to the minimum version WordPress requires run: vendor/bin/rector --ansi @@ -83,18 +91,23 @@ jobs: - name: Commit and push changes if: steps.script.outputs.has-changed == 'true' + env: + RELEASE_NAME: ${{ steps.script.outputs.release-name }} + RELEASE_REF: ${{ github.ref_name }} + APP_SLUG: ${{ steps.release-app.outputs.app-slug }} + APP_USER_ID: ${{ steps.release-app-user.outputs.user-id }} run: | - git config user.name "${{ steps.release-app.outputs.app-slug }}[bot]" - git config user.email "${{ steps.release-app-user.outputs.user-id }}+${{ steps.release-app.outputs.app-slug }}[bot]@users.noreply.github.com" + git config user.name "${APP_SLUG}[bot]" + git config user.email "${APP_USER_ID}+${APP_SLUG}[bot]@users.noreply.github.com" git add . - git commit -m "${{ steps.script.outputs.release-name }}" - # Push changes, handling potential conflicts - git push || git pull --rebase origin ${{ github.ref_name }} && git push + git commit -m "$RELEASE_NAME" + # Stop if main changed instead of deploying an untested rebase. + git push origin "HEAD:$RELEASE_REF" - name: WordPress Plugin Deploy if: steps.script.outputs.has-changed == 'true' id: deploy - uses: 10up/action-wordpress-plugin-deploy@2.3.0 + uses: 10up/action-wordpress-plugin-deploy@54bd289b8525fd23a5c365ec369185f2966529c2 # 2.3.0 with: generate-zip: true env: @@ -107,13 +120,16 @@ jobs: - name: Name release zip like repository if: steps.script.outputs.has-changed == 'true' id: release_zip + env: + ZIP_PATH: ${{ steps.deploy.outputs.zip-path }} + REPOSITORY_NAME: ${{ github.event.repository.name }} run: | - cp "${{ steps.deploy.outputs.zip-path }}" "${{ github.workspace }}/${{ github.event.repository.name }}.zip" - echo "path=${{ github.workspace }}/${{ github.event.repository.name }}.zip" >> "$GITHUB_OUTPUT" + cp -- "$ZIP_PATH" "$GITHUB_WORKSPACE/$REPOSITORY_NAME.zip" + echo "path=$GITHUB_WORKSPACE/$REPOSITORY_NAME.zip" >> "$GITHUB_OUTPUT" - name: Create GitHub release if: steps.script.outputs.has-changed == 'true' - uses: softprops/action-gh-release@v3 + uses: softprops/action-gh-release@8a0cd651e5b2365bd640854a3fa5dfc70e4875f3 # v3 with: tag_name: ${{ steps.script.outputs.stable-tag }} name: ${{ steps.script.outputs.release-name }} diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 9de793f..5e57506 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -11,6 +11,9 @@ concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true +permissions: + contents: read + jobs: prepare-matrix: name: Prepare test matrix @@ -19,7 +22,7 @@ jobs: matrix: ${{ steps.build-matrix.outputs.matrix }} steps: - name: Checkout plugin - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 with: persist-credentials: false @@ -43,27 +46,27 @@ jobs: steps: - name: Checkout plugin - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 with: persist-credentials: false - name: Install pnpm - uses: pnpm/action-setup@v6 + uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6 with: version: 10 - name: Setup Node - uses: actions/setup-node@v6 + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 with: node-version: lts/* cache: "pnpm" - name: Install pnpm dependencies - run: pnpm install + run: pnpm install --frozen-lockfile - name: Restore Playwright browsers cache id: playwright-cache - uses: actions/cache/restore@v5 + uses: actions/cache/restore@caa296126883cff596d87d8935842f9db880ef25 # v5 with: path: ~/.cache/ms-playwright key: ${{ runner.os }}-playwright-${{ hashFiles('pnpm-lock.yaml') }} @@ -108,7 +111,7 @@ jobs: - name: Save Playwright browsers cache if: steps.playwright-cache.outputs.cache-hit != 'true' - uses: actions/cache/save@v5 + uses: actions/cache/save@caa296126883cff596d87d8935842f9db880ef25 # v5 continue-on-error: true with: path: ~/.cache/ms-playwright @@ -119,7 +122,7 @@ jobs: - name: Upload test results if: always() - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: test-results-php${{ matrix.php }}-wp${{ matrix.wp }} path: test-results diff --git a/README.md b/README.md index e0b072d..74df1aa 100644 --- a/README.md +++ b/README.md @@ -12,3 +12,15 @@ You need a Simple Analytics account. Start with the [free plan](https://www.simp - [WordPress plugin page](https://wordpress.org/plugins/simpleanalytics/) - [Create a Simple Analytics account](https://www.simpleanalytics.com/signup) + +## Script pinning + +Enable **Pin analytics scripts** under **Settings → Simple Analytics → Advanced** to run the v12 analytics and automated-events scripts bundled with the plugin, instead of the latest scripts from the CDN. Every script tag carries a Subresource Integrity (SRI) hash, so a browser refuses changed bytes. Pinning is off by default. Script updates arrive with plugin releases. Clear page caches after changing this setting or updating the plugin, so visitors receive the new script tags, and exclude pinned files from JavaScript rewriting or minification. + +With a custom domain, the plugin fills the domain into the bundled custom-domain build, as the custom-domain server does for `https://YOUR.DOMAIN/sri/v12.js`, and saves it as `wp-content/uploads/simpleanalytics/v12-YOUR.DOMAIN.js`. That script sends data to the custom domain. If the uploads folder is not writable, visitors get the bundled script for the default domain and administrators see a warning. + +### Updating pinned scripts + +- Pinned scripts follow the releases of [simpleanalytics/scripts](https://github.com/simpleanalytics/scripts). `VERSION` in `src/Support/ScriptPinning.php` is the release tag (`v12`), and `resources/js/pinned/v12/` holds `dist/v12/app.js`, `dist/v12/custom/app.js` and `dist/v12/auto-events.js` from that release's `scripts-v12.tar.gz`, unmodified. `app.js` equals `https://scripts.simpleanalyticscdn.com/sri/v12.js` except for its source map comment. The MIT license is retained in `resources/js/pinned/LICENSE`. +- For a new release such as `v13`: review the upstream changes, put the same three files from `scripts-v13.tar.gz` in `resources/js/pinned/v13/`, remove `v12/`, and change `VERSION`, `INTEGRITY`, `CUSTOM_DOMAIN_INTEGRITY` and `EVENTS_INTEGRITY` together. Calculate each hash with `echo "sha384-$(openssl dgst -sha384 -binary FILE | openssl base64 -A)"`. Never calculate the expected hashes at runtime. +- Run the PHP regressions and browser checks, including altered script responses, a custom domain, and event collection. diff --git a/readme.txt b/readme.txt index 52a3ea3..b01fb05 100644 --- a/readme.txt +++ b/readme.txt @@ -112,6 +112,10 @@ Installing "Simple Analytics" can be done in multiple ways. == Frequently Asked Questions == += Can I pin the analytics scripts? = + +Yes. Enable "Pin analytics scripts" under Settings > Simple Analytics > Advanced. The plugin then runs the v12 analytics and automated-events scripts bundled with it, with Subresource Integrity, instead of the latest scripts from our CDN. Pinning is off by default. Script updates arrive with plugin releases. Clear page caches after enabling pinning or updating the plugin, and exclude pinned files from JavaScript rewriting or minification. With a custom domain, the plugin saves a copy of the script for that domain in the uploads folder. The readable source of the bundled scripts is at https://github.com/simpleanalytics/scripts/tree/v12/src. + = Is Simple Analytics free? = Yes. You can use Simple Analytics for free forever. You only need to create an account at [Simple Analytics](https://simpleanalytics.com/?ref=wordpress). diff --git a/resources/css/settings.css b/resources/css/settings.css index b63e5db..b5c61c9 100644 --- a/resources/css/settings.css +++ b/resources/css/settings.css @@ -1,5 +1,3 @@ -@import url(https://fonts.bunny.net/css?family=space-grotesk:500,600); - @tailwind base; @tailwind components; @tailwind utilities; diff --git a/resources/js/pinned/LICENSE b/resources/js/pinned/LICENSE new file mode 100644 index 0000000..2a16dae --- /dev/null +++ b/resources/js/pinned/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018-2026 Simple Analytics + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/resources/js/pinned/v12/app.js b/resources/js/pinned/v12/app.js new file mode 100644 index 0000000..cf571c4 --- /dev/null +++ b/resources/js/pinned/v12/app.js @@ -0,0 +1,4 @@ +/* Simple Analytics - Privacy-first analytics (docs.simpleanalytics.com/script; 2026-10-22; 549d; SRI-version; v12) */ + +!function(g,e,n,y){var r,a,t;if(g)try{var _=undefined,w=!0,b=!1,i="true",o="https:",E="pageview",l="event",c="error",x="/",s=g.console,u="doNotTrack",O=g.navigator,f=g.location,M=f.host,p=g.document,d=O.userAgent,h="Not sending request ",v=h+"when ",S=b,m=encodeURIComponent,k=decodeURIComponent,q=JSON.stringify,A=g.addEventListener,C="https://queue."+e,D=p.documentElement||{},$="language",L="Height",R="scroll",T=O.userAgentData,j=R+L,H="offset"+L,N="client"+L,P="platform",U="platformVersion",I="https://docs.simpleanalytics.com",V=0,B=/(bot|spider|crawl)/i.test(d)&&!/(cubot)/i.test(d),F=g.screen,z=p.currentScript||p.querySelector('script[src*="'+e+'"]');y=function(){var t=[].slice.call(arguments);return t.unshift("Simple Analytics:"),Function.prototype.apply.call(s.warn,s,t)};var W=function(t,e){y("Error in your "+t+" function:",e)},G=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},J=function(t){return"string"==typeof t},X=function(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")},Y=function(t,e){return t&&t.getAttribute("data-"+e)},Z=function(t){return Array.isArray(t)?t:J(t)&&t.length?t.split(/, ?/):[]},K=function(t){return t&&t.constructor===Object},Q=function(){for(var t={},e=arguments,n=0;n>t/4).toString(16)})}catch(r){return t.replace(n,function(t){var e=16*Math.random()|0;return(t<2?e:3&e|8).toString(16)})}},ct=function(t){return"function"==typeof t},st="namespace",ut=et[st]||Y(z,st)||"sa",lt=function(t,e){var n=g[ut+"_metadata"];K(n)&&(t=Q(t,n));var r=g[qt];if(!ct(r))return qt&&y(qt+" not found, set window."+qt),t;try{return Q(t,r.call(g,Q(t,e)))}catch(a){W("metadata",a)}},ft=et.strictUtm||Y(z,"strict-utm")==i,pt=function(i,t){nt=!i&&at("q")?"":b;var e=(t||f.search).slice(1).split("&").filter(function(t){var e=t.indexOf("=");nt!==b&&0>t/4).toString(16)})}catch(r){return t.replace(n,function(t){var e=16*Math.random()|0;return(t<2?e:3&e|8).toString(16)})}},ct=function(t){return"function"==typeof t},st="namespace",ut=et[st]||Y(z,st)||"sa",lt=function(t,e){var n=g[ut+"_metadata"];K(n)&&(t=Q(t,n));var r=g[At];if(!ct(r))return At&&y(At+" not found, set window."+At),t;try{return Q(t,r.call(g,Q(t,e)))}catch(a){W("metadata",a)}},ft=et.strictUtm||Y(z,"strict-utm")==i,pt=function(i,t){nt=!i&&at("q")?"":b;var e=(t||f.search).slice(1).split("&").filter(function(t){var e=t.indexOf("=");nt!==b&&0"); +//# sourceMappingURL=app.js.map \ No newline at end of file diff --git a/simple-analytics.php b/simple-analytics.php index 1321b59..a410e79 100644 --- a/simple-analytics.php +++ b/simple-analytics.php @@ -49,6 +49,8 @@ require __DIR__ . '/src/Actions/AddPluginSettingsLink.php'; require __DIR__ . '/src/Support/Str.php'; require __DIR__ . '/src/Support/OnloadCallback.php'; +require __DIR__ . '/src/Support/CustomDomain.php'; +require __DIR__ . '/src/Support/ScriptPinning.php'; require __DIR__ . '/src/Settings/Block.php'; require __DIR__ . '/src/Settings/Blocks/CalloutBlock.php'; require __DIR__ . '/src/Settings/Concerns/HasDocs.php'; @@ -92,7 +94,13 @@ $tab->multiCheckbox(SettingName::EXCLUDED_ROLES, 'Specific User Roles to Exclude') ->description('When none selected, all authenticated users will be excluded from tracking.') ->options(function () { - return wp_roles()->get_names(); + $roles = wp_roles()->get_names(); + + if (is_multisite()) { + $roles[SimpleAnalytics\TrackingRules::SUPER_ADMIN] = 'Network administrator (Super Admin)'; + } + + return $roles; }); $tab->ipList(SettingName::EXCLUDED_IP_ADDRESSES, 'Exclude IP Addresses') @@ -104,9 +112,13 @@ $tab->input(SettingName::CUSTOM_DOMAIN, 'Custom Domain') ->placeholder('Enter your custom domain or leave it empty.') - ->description('E.g. api.example.com. Leave empty to use the default domain (most users).') + ->description('E.g. api.example.com. Requires permission to save unfiltered HTML. Leave empty to use the default domain.') ->docs('https://docs.simpleanalytics.com/bypass-ad-blockers'); + $tab->checkbox(SettingName::PIN_SCRIPTS, 'Pin analytics scripts') + ->description('Run the ' . SimpleAnalytics\Support\ScriptPinning::VERSION . ' scripts bundled with this plugin, checked with Subresource Integrity, instead of the latest scripts from our CDN. Script updates arrive with plugin releases. With a custom domain, its script is saved in the uploads folder. Clear your page cache after changing this setting.') + ->docs('https://docs.simpleanalytics.com/sri'); + $tab->checkbox(SettingName::COLLECT_DNT, 'Collect Do Not Track') ->description('If you want to collect visitors with Do Not Track enabled, turn this on.') ->docs('https://docs.simpleanalytics.com/dnt'); diff --git a/src/Actions/Action.php b/src/Actions/Action.php index ba3a02f..8e3f12f 100644 --- a/src/Actions/Action.php +++ b/src/Actions/Action.php @@ -2,6 +2,8 @@ namespace SimpleAnalytics\Actions; +defined('ABSPATH') || exit; + trait Action { protected function hook(): string diff --git a/src/Actions/AddInactiveComment.php b/src/Actions/AddInactiveComment.php index 4d91ca2..be18093 100644 --- a/src/Actions/AddInactiveComment.php +++ b/src/Actions/AddInactiveComment.php @@ -2,6 +2,8 @@ namespace SimpleAnalytics\Actions; +defined('ABSPATH') || exit; + class AddInactiveComment { use Action; diff --git a/src/Actions/AddNoScriptTag.php b/src/Actions/AddNoScriptTag.php index 71832ab..fbb0d8c 100644 --- a/src/Actions/AddNoScriptTag.php +++ b/src/Actions/AddNoScriptTag.php @@ -2,8 +2,9 @@ namespace SimpleAnalytics\Actions; -use SimpleAnalytics\Setting; -use SimpleAnalytics\SettingName; +defined('ABSPATH') || exit; + +use SimpleAnalytics\Support\CustomDomain; class AddNoScriptTag { @@ -21,6 +22,6 @@ public function handle(): void public function getCustomDomain(): string { - return esc_url('https://' . Setting::get(SettingName::CUSTOM_DOMAIN, 'queue.simpleanalyticscdn.com') . '/noscript.gif'); + return esc_url('https://' . CustomDomain::get('queue.simpleanalyticscdn.com') . '/noscript.gif'); } } diff --git a/src/Actions/AddPluginSettingsLink.php b/src/Actions/AddPluginSettingsLink.php index 664b469..ac1f6b3 100644 --- a/src/Actions/AddPluginSettingsLink.php +++ b/src/Actions/AddPluginSettingsLink.php @@ -2,6 +2,8 @@ namespace SimpleAnalytics\Actions; +defined('ABSPATH') || exit; + use const SimpleAnalytics\PLUGIN_BASENAME; /** diff --git a/src/Plugin.php b/src/Plugin.php index 73313e2..9a37372 100644 --- a/src/Plugin.php +++ b/src/Plugin.php @@ -2,6 +2,8 @@ namespace SimpleAnalytics; +defined('ABSPATH') || exit; + use SimpleAnalytics\Actions\AddInactiveComment; use SimpleAnalytics\Actions\AddNoScriptTag; use SimpleAnalytics\Actions\AddPluginSettingsLink; @@ -9,6 +11,7 @@ use SimpleAnalytics\Scripts\AutomatedEventsScript; use SimpleAnalytics\Scripts\InactiveScript; use SimpleAnalytics\Settings\AdminPage; +use SimpleAnalytics\Support\ScriptPinning; final class Plugin { @@ -34,17 +37,22 @@ public function __construct( public function boot(): void { - $this->hooks->addAction('init', \Closure::fromCallable([$this, 'onInit'])); + $this->hooks->addAction('wp_enqueue_scripts', \Closure::fromCallable([$this, 'enqueueScripts'])); $this->hooks->onActivation(\Closure::fromCallable([$this, 'onActivation'])); if ($this->hooks->isAdmin()) { + $this->hooks->addAction('admin_notices', [ScriptPinning::class, 'notice']); $this->adminPage->register(); AddPluginSettingsLink::register(); } } - public function onInit(): void + public function enqueueScripts(): void { + if ($this->hooks->isAdmin() || ($GLOBALS['pagenow'] ?? '') === 'wp-login.php') { + return; + } + $hasExcludedIp = $this->trackingRules->hasExcludedIp(); $hasExcludedUserRole = $this->trackingRules->hasExcludedUserRole(); $tracking = ! $hasExcludedIp && ! $hasExcludedUserRole; @@ -61,7 +69,7 @@ public function onInit(): void AddNoScriptTag::register(); } - if ($this->settings->boolean(SettingName::AUTOMATED_EVENTS)) { + if ($tracking && $this->settings->boolean(SettingName::AUTOMATED_EVENTS)) { $this->scripts->push(new AutomatedEventsScript); } diff --git a/src/ScriptRegistry.php b/src/ScriptRegistry.php index 6cce314..f3bd445 100644 --- a/src/ScriptRegistry.php +++ b/src/ScriptRegistry.php @@ -2,6 +2,8 @@ namespace SimpleAnalytics; +defined('ABSPATH') || exit; + use SimpleAnalytics\Scripts\Contracts\HasAttributes; use SimpleAnalytics\Scripts\Contracts\HideScriptId; use SimpleAnalytics\Scripts\Contracts\Script; diff --git a/src/Scripts/AnalyticsScript.php b/src/Scripts/AnalyticsScript.php index 11638ad..efff591 100644 --- a/src/Scripts/AnalyticsScript.php +++ b/src/Scripts/AnalyticsScript.php @@ -2,18 +2,25 @@ namespace SimpleAnalytics\Scripts; +defined('ABSPATH') || exit; + use SimpleAnalytics\Scripts\Contracts\HasAttributes; use SimpleAnalytics\Scripts\Contracts\HideScriptId; use SimpleAnalytics\Scripts\Contracts\Script; use SimpleAnalytics\Setting; use SimpleAnalytics\SettingName; +use SimpleAnalytics\Support\CustomDomain; use SimpleAnalytics\Support\OnloadCallback; +use SimpleAnalytics\Support\ScriptPinning; class AnalyticsScript implements Script, HasAttributes, HideScriptId { public function path(): string { - return sprintf("https://%s/latest.js", Setting::get(SettingName::CUSTOM_DOMAIN, 'scripts.simpleanalyticscdn.com')); + if (ScriptPinning::enabled()) { + return ScriptPinning::analyticsScript()['src']; + } + return sprintf("https://%s/latest.js", CustomDomain::get('scripts.simpleanalyticscdn.com')); } public function handle(): string @@ -23,7 +30,7 @@ public function handle(): string public function attributes(): array { - return array_filter([ + return array_merge(array_filter([ // Never remove or rename data-platform="wordpress". Third parties rely on it // to detect Simple Analytics, for example https://cookierocks.com/. 'data-platform' => 'wordpress', @@ -34,6 +41,9 @@ public function attributes(): array 'onload' => OnloadCallback::get(), 'data-sa-global' => Setting::get(SettingName::SA_GLOBAL), 'data-hostname' => Setting::get(SettingName::HOSTNAME), - ]); + ]), ScriptPinning::enabled() ? [ + 'integrity' => ScriptPinning::analyticsScript()['integrity'], + 'crossorigin' => 'anonymous', + ] : []); } } diff --git a/src/Scripts/AutomatedEventsScript.php b/src/Scripts/AutomatedEventsScript.php index 5688986..4268aa7 100644 --- a/src/Scripts/AutomatedEventsScript.php +++ b/src/Scripts/AutomatedEventsScript.php @@ -2,17 +2,24 @@ namespace SimpleAnalytics\Scripts; +defined('ABSPATH') || exit; + use SimpleAnalytics\Scripts\Contracts\HasAttributes; use SimpleAnalytics\Scripts\Contracts\HideScriptId; use SimpleAnalytics\Scripts\Contracts\Script; use SimpleAnalytics\Setting; use SimpleAnalytics\SettingName; +use SimpleAnalytics\Support\CustomDomain; +use SimpleAnalytics\Support\ScriptPinning; class AutomatedEventsScript implements Script, HasAttributes, HideScriptId { public function path(): string { - return sprintf("https://%s/auto-events.js", Setting::get(SettingName::CUSTOM_DOMAIN, 'scripts.simpleanalyticscdn.com')); + if (ScriptPinning::enabled()) { + return ScriptPinning::eventsScript()['src']; + } + return sprintf("https://%s/auto-events.js", CustomDomain::get('scripts.simpleanalyticscdn.com')); } public function handle(): string @@ -22,12 +29,15 @@ public function handle(): string public function attributes(): array { - return array_filter([ + return array_merge(array_filter([ 'data-collect' => Setting::get(SettingName::EVENT_COLLECT_DOWNLOADS), 'data-extensions' => Setting::get(SettingName::EVENT_EXTENSIONS), 'data-use-title' => Setting::boolean(SettingName::EVENT_USE_TITLE) ? 'true' : 'false', 'data-full-urls' => Setting::boolean(SettingName::EVENT_FULL_URLS) ? 'true' : 'false', 'data-sa-global' => Setting::get(SettingName::EVENT_SA_GLOBAL), - ]); + ]), ScriptPinning::enabled() ? [ + 'integrity' => ScriptPinning::eventsScript()['integrity'], + 'crossorigin' => 'anonymous', + ] : []); } } diff --git a/src/Scripts/Contracts/HasAttributes.php b/src/Scripts/Contracts/HasAttributes.php index 1c2bb90..58f8eb7 100644 --- a/src/Scripts/Contracts/HasAttributes.php +++ b/src/Scripts/Contracts/HasAttributes.php @@ -2,6 +2,8 @@ namespace SimpleAnalytics\Scripts\Contracts; +defined('ABSPATH') || exit; + interface HasAttributes { public function attributes(): array; diff --git a/src/Scripts/Contracts/HideScriptId.php b/src/Scripts/Contracts/HideScriptId.php index 0e6998a..836b2f9 100644 --- a/src/Scripts/Contracts/HideScriptId.php +++ b/src/Scripts/Contracts/HideScriptId.php @@ -2,6 +2,8 @@ namespace SimpleAnalytics\Scripts\Contracts; +defined('ABSPATH') || exit; + interface HideScriptId { } diff --git a/src/Scripts/Contracts/Script.php b/src/Scripts/Contracts/Script.php index 1d710e4..552caba 100644 --- a/src/Scripts/Contracts/Script.php +++ b/src/Scripts/Contracts/Script.php @@ -2,6 +2,8 @@ namespace SimpleAnalytics\Scripts\Contracts; +defined('ABSPATH') || exit; + interface Script { public function path(): string; diff --git a/src/Scripts/InactiveScript.php b/src/Scripts/InactiveScript.php index b9cb74f..bd82318 100644 --- a/src/Scripts/InactiveScript.php +++ b/src/Scripts/InactiveScript.php @@ -2,6 +2,8 @@ namespace SimpleAnalytics\Scripts; +defined('ABSPATH') || exit; + use SimpleAnalytics\Scripts\Contracts\Script; use const SimpleAnalytics\PLUGIN_URL; diff --git a/src/Setting.php b/src/Setting.php index c6d66f2..17052c0 100644 --- a/src/Setting.php +++ b/src/Setting.php @@ -2,6 +2,8 @@ namespace SimpleAnalytics; +defined('ABSPATH') || exit; + class Setting { /** diff --git a/src/SettingName.php b/src/SettingName.php index b1cc789..88aecd4 100644 --- a/src/SettingName.php +++ b/src/SettingName.php @@ -9,6 +9,8 @@ */ class SettingName { + const PIN_SCRIPTS = 'simpleanalytics_pin_scripts'; + /** * @var string */ diff --git a/src/Settings/AdminPage.php b/src/Settings/AdminPage.php index 22c6058..5fb371e 100644 --- a/src/Settings/AdminPage.php +++ b/src/Settings/AdminPage.php @@ -2,6 +2,8 @@ namespace SimpleAnalytics\Settings; +defined('ABSPATH') || exit; + use SimpleAnalytics\Settings\Concerns\WordPressPageIntegration; use SimpleAnalytics\Support\Str; diff --git a/src/Settings/Block.php b/src/Settings/Block.php index 49aef3a..ddad45f 100644 --- a/src/Settings/Block.php +++ b/src/Settings/Block.php @@ -2,6 +2,8 @@ namespace SimpleAnalytics\Settings; +defined('ABSPATH') || exit; + interface Block { public function render(): void; diff --git a/src/Settings/Blocks/CalloutBlock.php b/src/Settings/Blocks/CalloutBlock.php index fa63b8c..5017f35 100644 --- a/src/Settings/Blocks/CalloutBlock.php +++ b/src/Settings/Blocks/CalloutBlock.php @@ -2,6 +2,8 @@ namespace SimpleAnalytics\Settings\Blocks; +defined('ABSPATH') || exit; + use SimpleAnalytics\Settings\Block; use function SimpleAnalytics\get_icon; diff --git a/src/Settings/Blocks/Fields/Checkbox.php b/src/Settings/Blocks/Fields/Checkbox.php index 9595e0d..d873b7c 100644 --- a/src/Settings/Blocks/Fields/Checkbox.php +++ b/src/Settings/Blocks/Fields/Checkbox.php @@ -2,6 +2,8 @@ namespace SimpleAnalytics\Settings\Blocks\Fields; +defined('ABSPATH') || exit; + use SimpleAnalytics\Setting; use SimpleAnalytics\Settings\Concerns\HasDocs; use SimpleAnalytics\UI\LabelComponent; diff --git a/src/Settings/Blocks/Fields/Checkboxes.php b/src/Settings/Blocks/Fields/Checkboxes.php index d22a7f9..eaef0b6 100644 --- a/src/Settings/Blocks/Fields/Checkboxes.php +++ b/src/Settings/Blocks/Fields/Checkboxes.php @@ -2,6 +2,8 @@ namespace SimpleAnalytics\Settings\Blocks\Fields; +defined('ABSPATH') || exit; + use Closure; use SimpleAnalytics\Setting; use SimpleAnalytics\Settings\Concerns\HasDocs; diff --git a/src/Settings/Blocks/Fields/Field.php b/src/Settings/Blocks/Fields/Field.php index 0b2d223..cc9a882 100644 --- a/src/Settings/Blocks/Fields/Field.php +++ b/src/Settings/Blocks/Fields/Field.php @@ -2,6 +2,8 @@ namespace SimpleAnalytics\Settings\Blocks\Fields; +defined('ABSPATH') || exit; + use SimpleAnalytics\Settings\Block; abstract class Field implements Block diff --git a/src/Settings/Blocks/Fields/Input.php b/src/Settings/Blocks/Fields/Input.php index 93705ca..277eda5 100644 --- a/src/Settings/Blocks/Fields/Input.php +++ b/src/Settings/Blocks/Fields/Input.php @@ -2,9 +2,12 @@ namespace SimpleAnalytics\Settings\Blocks\Fields; +defined('ABSPATH') || exit; + use SimpleAnalytics\Setting; use SimpleAnalytics\SettingName; use SimpleAnalytics\Support\OnloadCallback; +use SimpleAnalytics\Support\CustomDomain; use SimpleAnalytics\Settings\Concerns\HasDocs; use SimpleAnalytics\Settings\Concerns\HasPlaceholder; use SimpleAnalytics\UI\LabelComponent; @@ -34,6 +37,9 @@ public function getValueSanitizer(): callable if ($this->getKey() === SettingName::ONLOAD_CALLBACK) { return [OnloadCallback::class, 'sanitize']; } + if ($this->getKey() === SettingName::CUSTOM_DOMAIN) { + return [CustomDomain::class, 'sanitize']; + } return 'sanitize_text_field'; } @@ -75,6 +81,27 @@ class="mt-2 block w-full rounded-md border-0 placeholder:text-gray-400 text-gray description); ?>

messages() as $message): ?> + + getKey()), 'message'); + + if ($this->getKey() === SettingName::CUSTOM_DOMAIN && $messages === []) { + $messages[] = CustomDomain::problem(); + } + + return array_values(array_unique(array_filter($messages))); } public function type(string $type): self diff --git a/src/Settings/Blocks/Fields/IpList.php b/src/Settings/Blocks/Fields/IpList.php index ceb34e0..77000d0 100644 --- a/src/Settings/Blocks/Fields/IpList.php +++ b/src/Settings/Blocks/Fields/IpList.php @@ -2,6 +2,8 @@ namespace SimpleAnalytics\Settings\Blocks\Fields; +defined('ABSPATH') || exit; + use SimpleAnalytics\Setting; use SimpleAnalytics\Settings\Concerns\HasDocs; use SimpleAnalytics\Settings\Concerns\HasPlaceholder; diff --git a/src/Settings/Concerns/HasDocs.php b/src/Settings/Concerns/HasDocs.php index cad8b8c..eba7a41 100644 --- a/src/Settings/Concerns/HasDocs.php +++ b/src/Settings/Concerns/HasDocs.php @@ -2,6 +2,8 @@ namespace SimpleAnalytics\Settings\Concerns; +defined('ABSPATH') || exit; + trait HasDocs { /** diff --git a/src/Settings/Concerns/HasPlaceholder.php b/src/Settings/Concerns/HasPlaceholder.php index 750a3ed..19ad479 100644 --- a/src/Settings/Concerns/HasPlaceholder.php +++ b/src/Settings/Concerns/HasPlaceholder.php @@ -2,6 +2,8 @@ namespace SimpleAnalytics\Settings\Concerns; +defined('ABSPATH') || exit; + trait HasPlaceholder { /** diff --git a/src/Settings/Concerns/ManagesBlocks.php b/src/Settings/Concerns/ManagesBlocks.php index 87b0517..4603b69 100644 --- a/src/Settings/Concerns/ManagesBlocks.php +++ b/src/Settings/Concerns/ManagesBlocks.php @@ -2,6 +2,8 @@ namespace SimpleAnalytics\Settings\Concerns; +defined('ABSPATH') || exit; + use SimpleAnalytics\Settings\Block; use SimpleAnalytics\Settings\Blocks\CalloutBlock; use SimpleAnalytics\Settings\Blocks\Fields\Checkbox; diff --git a/src/Settings/Concerns/WordPressPageIntegration.php b/src/Settings/Concerns/WordPressPageIntegration.php index 391d7a1..beefe9d 100644 --- a/src/Settings/Concerns/WordPressPageIntegration.php +++ b/src/Settings/Concerns/WordPressPageIntegration.php @@ -2,6 +2,8 @@ namespace SimpleAnalytics\Settings\Concerns; +defined('ABSPATH') || exit; + use SimpleAnalytics\Settings\Blocks\Fields\Field; use SimpleAnalytics\Settings\Tab; use SimpleAnalytics\UI\PageLayoutComponent; diff --git a/src/Settings/Tab.php b/src/Settings/Tab.php index 04a1d15..45666be 100644 --- a/src/Settings/Tab.php +++ b/src/Settings/Tab.php @@ -2,6 +2,8 @@ namespace SimpleAnalytics\Settings; +defined('ABSPATH') || exit; + use SimpleAnalytics\Support\SvgIcon; class Tab diff --git a/src/Support/CustomDomain.php b/src/Support/CustomDomain.php new file mode 100644 index 0000000..2392de3 --- /dev/null +++ b/src/Support/CustomDomain.php @@ -0,0 +1,78 @@ +'; + // Scripts written for a custom domain, inside the uploads folder. + const UPLOADS_DIRECTORY = 'simpleanalytics'; + + public static function enabled(): bool + { + return Setting::boolean(SettingName::PIN_SCRIPTS, false) === true; + } + + /** + * @return array{src: string, integrity: string} + */ + public static function analyticsScript(): array + { + return self::customDomainScript() ?? [ + 'src' => PLUGIN_URL . self::DIRECTORY . 'app.js', + 'integrity' => self::INTEGRITY, + ]; + } + + /** + * @return array{src: string, integrity: string} + */ + public static function eventsScript(): array + { + return [ + 'src' => PLUGIN_URL . self::DIRECTORY . 'auto-events.js', + 'integrity' => self::EVENTS_INTEGRITY, + ]; + } + + /** + * Explains why pinned scripts cannot use the custom domain, for administrators. + */ + public static function problem(): ?string + { + if (! self::enabled() || CustomDomain::get('') === '' || self::customDomainScript() !== null) { + return null; + } + + return 'Simple Analytics could not save the pinned script for your custom domain in the uploads folder, so visitors load the pinned script for the default domain. Make sure WordPress can write to its uploads folder.'; + } + + public static function notice(bool $inSettings = false): void + { + // The settings page uses a shadow root, which hides ordinary WP notices. + $settingsPage = isset($_GET['page']) && $_GET['page'] === 'simpleanalytics'; + if ($settingsPage !== $inSettings || ! current_user_can('manage_options')) return; + $problem = self::problem(); + if ($problem !== null) { + echo ''; + } + } + + /** + * Writes the custom-domain build with the saved domain filled in, as the + * custom-domain server would serve it, to the uploads folder. + * + * @return array{src: string, integrity: string}|null + */ + private static function customDomainScript(): ?array + { + $domain = CustomDomain::get(''); + if ($domain === '') return null; + + $template = file_get_contents(PLUGIN_PATH . self::DIRECTORY . 'custom/app.js'); + if (! is_string($template) || 'sha384-' . base64_encode(hash('sha384', $template, true)) !== self::CUSTOM_DOMAIN_INTEGRITY) { + return null; + } + $code = str_replace(self::HOST_PLACEHOLDER, $domain, $template); + + $uploads = wp_upload_dir(null, false); + if (! empty($uploads['error'])) return null; + $directory = $uploads['basedir'] . '/' . self::UPLOADS_DIRECTORY; + // The domain and version are in the name, so browsers can cache it for good. + $file = self::VERSION . '-' . $domain . '.js'; + + if (! is_file("$directory/$file") || file_get_contents("$directory/$file") !== $code) { + if (! wp_mkdir_p($directory) || file_put_contents("$directory/$file", $code, LOCK_EX) !== strlen($code)) { + return null; + } + foreach (glob("$directory/*.js") ?: [] as $old) { + if (basename($old) !== $file) wp_delete_file($old); + } + } + + return [ + 'src' => $uploads['baseurl'] . '/' . self::UPLOADS_DIRECTORY . '/' . $file, + 'integrity' => 'sha384-' . base64_encode(hash('sha384', $code, true)), + ]; + } +} diff --git a/src/Support/Str.php b/src/Support/Str.php index 5a65ec3..293f595 100644 --- a/src/Support/Str.php +++ b/src/Support/Str.php @@ -2,6 +2,8 @@ namespace SimpleAnalytics\Support; +defined('ABSPATH') || exit; + class Str { public static function slug(string $value): string diff --git a/src/Support/SvgIcon.php b/src/Support/SvgIcon.php index 96cbfe0..b81170a 100644 --- a/src/Support/SvgIcon.php +++ b/src/Support/SvgIcon.php @@ -2,6 +2,8 @@ namespace SimpleAnalytics\Support; +defined('ABSPATH') || exit; + class SvgIcon { /** diff --git a/src/TrackingRules.php b/src/TrackingRules.php index 9e09f84..6f5ee86 100644 --- a/src/TrackingRules.php +++ b/src/TrackingRules.php @@ -2,8 +2,15 @@ namespace SimpleAnalytics; +defined('ABSPATH') || exit; + class TrackingRules { + /** + * Pseudo-role in the excluded roles setting for multisite network administrators. + */ + const SUPER_ADMIN = 'super_admin'; + protected $settings; public function __construct(WordPressSettings $settings) @@ -34,6 +41,11 @@ public function hasExcludedUserRole(): bool return true; } + // Network administrators may have no role on the site they visit. + if (in_array(self::SUPER_ADMIN, $needle, true) && is_multisite() && is_super_admin()) { + return true; + } + $current = wp_get_current_user()->roles; return array_intersect($needle, $current) !== []; diff --git a/src/UI/LabelComponent.php b/src/UI/LabelComponent.php index 8cb6272..b72c158 100644 --- a/src/UI/LabelComponent.php +++ b/src/UI/LabelComponent.php @@ -2,6 +2,8 @@ namespace SimpleAnalytics\UI; +defined('ABSPATH') || exit; + use SimpleAnalytics\Support\Str; class LabelComponent diff --git a/src/UI/PageLayoutComponent.php b/src/UI/PageLayoutComponent.php index 586d108..8bb37e3 100644 --- a/src/UI/PageLayoutComponent.php +++ b/src/UI/PageLayoutComponent.php @@ -2,6 +2,8 @@ namespace SimpleAnalytics\UI; +defined('ABSPATH') || exit; + use SimpleAnalytics\Settings\{AdminPage, Tab}; use function SimpleAnalytics\get_icon; use const SimpleAnalytics\PLUGIN_URL; @@ -35,7 +37,6 @@ public function __invoke(): void }