diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index bb8c3ca..d84a09c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -5,20 +5,33 @@ on: tags: ['v*'] permissions: - contents: write + contents: read jobs: + tests: + uses: ./.github/workflows/tests.yml + release: + needs: tests runs-on: ubuntu-latest + permissions: + contents: write + steps: - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Check the tag is on main + run: git merge-base --is-ancestor "$GITHUB_SHA" origin/main - name: Check the tag matches the plugin's version - run: grep -Fxq " * Version: ${GITHUB_REF_NAME#v}" altimiser.php + run: | + grep -Fxq " * Version: ${GITHUB_REF_NAME#v}" altimiser.php - name: Build the zip - run: git archive --prefix=altimiser/ -o altimiser.zip HEAD altimiser.php src README.md + run: git archive --prefix=altimiser/ -o altimiser.zip HEAD altimiser.php uninstall.php src README.md - name: Publish the release run: gh release create "$GITHUB_REF_NAME" altimiser.zip --generate-notes diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index c105f47..117f7e5 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -4,6 +4,7 @@ on: push: branches: [main] pull_request: + workflow_call: permissions: contents: read @@ -21,6 +22,11 @@ jobs: matrix: php: ['8.1', '8.2', '8.3', '8.4'] wordpress: ['6.8.*', '*'] + yoast: ['*'] + include: + - php: '8.1' + wordpress: '6.8.*' + yoast: '24.0' services: mysql: @@ -51,6 +57,7 @@ jobs: composer require --dev --no-interaction --no-progress --prefer-dist --with-all-dependencies "roots/wordpress:${{ matrix.wordpress }}" "wp-phpunit/wp-phpunit:${{ matrix.wordpress }}" + "wpackagist-plugin/wordpress-seo:${{ matrix.yoast }}" - name: Run tests run: vendor/bin/phpunit diff --git a/README.md b/README.md index 3d7c328..65f2677 100644 --- a/README.md +++ b/README.md @@ -1,30 +1,39 @@ # Altimiser for WordPress -Connects a WordPress site to Altimiser. It implements the [receiver protocol](https://github.com/alt-design/altimiser/blob/main/docs/receiver-protocol.md), and it is held to that document rather than to the [Statamic receiver](https://github.com/alt-design/altimiser-statamic), with which it shares no code. +Connects a WordPress site to Altimiser. It implements Altimiser's receiver protocol, which is kept with Altimiser itself, and it is held to that document rather than to the [Statamic receiver](https://github.com/alt-design/altimiser-statamic), with which it shares no code. -It applies the changes Altimiser sends to titles, meta descriptions and Open Graph text, by writing to Yoast SEO's own fields. Without Yoast SEO active a site can still connect, but `GET /health` advertises no checks, Altimiser reports the gap as `receiver.no_seo_plugin`, and nothing on the site is changed. +It applies the changes Altimiser sends to titles, meta descriptions and Open Graph text, by writing to Yoast SEO's own fields. Without Yoast SEO active a site can still connect, but `GET /health` advertises none of those checks, Altimiser reports the gap as `receiver.no_seo_plugin`, and none of those fields is changed. ## Requirements -WordPress 6.8 or newer, PHP 8.1 or newer, and Yoast SEO for anything to be applied. The plugin has no runtime Composer dependencies, because vendor classes in a plugin can collide with another plugin's copies. +WordPress 6.8 or newer, PHP 8.1 or newer, and Yoast SEO 24.0 or newer for titles, descriptions and Open Graph text. The tests run against Yoast SEO 24.0 as well as the latest release. The plugin has no runtime Composer dependencies, because vendor classes in a plugin can collide with another plugin's copies. ## Installing -Put this repository in `wp-content/plugins/altimiser` and activate the plugin. +Install from `altimiser.zip` on the latest GitHub release, through **Plugins > Add New > Upload Plugin**, and activate it. A clone in a folder not named `altimiser` gets a second copy on its first update. -Then add a shared secret to `wp-config.php`, above the line that says to stop editing: +Then give the site a shared secret of at least 32 characters. Every request is refused until there is one, and while it is shorter than that, so an install without one is inert rather than open. There are three places to put it, and the first one found wins: -```php -define('ALTIMISER_SECRET', 'a long random string'); -``` +1. A constant in `wp-config.php`, above the line that says to stop editing: -With WP-CLI, this generates one and writes it there: + ```php + define('ALTIMISER_SECRET', 'a long random string'); + ``` -```bash -wp config set ALTIMISER_SECRET "$(openssl rand -hex 32)" -``` + With WP-CLI, this generates one and writes it there: + + ```bash + wp config set ALTIMISER_SECRET "$(openssl rand -hex 32)" + ``` + +2. An `ALTIMISER_SECRET` environment variable, for hosts that manage configuration that way. +3. **Settings > Altimiser**, for administrators. The field never shows a saved secret, and leaving it blank keeps the one saved. -Every request is refused until the secret is set, so an install without one is inert rather than open. +The settings page also shows the receiver address to give Altimiser, and says whether the site will accept its requests. + +### Multisite + +Each site on a network has its own **Settings > Altimiser** page, and so its own secret and its own connection in Altimiser. A constant in `wp-config.php` or an environment variable applies to every site on the network at once, so use the settings page there. Multisite has not yet been tried on a running network. ## Connecting @@ -40,6 +49,8 @@ A successful connection shows the receiver as `wordpress` with the plugin's vers Connect again after activating Yoast SEO, so Altimiser reads what the site can now apply. +`GET /health` also reports two settings under `setup`, which Altimiser turns into findings because they stop fixes from counting: **Discourage search engines** under **Settings > Reading**, and plain permalinks. + ## What gets changed | Checks | Yoast SEO field | @@ -48,7 +59,7 @@ Connect again after activating Yoast SEO, so Altimiser reads what the site can n | `meta_description.missing`, `too_short`, `too_long`, `irrelevant`, `duplicate` | Meta description | | `open_graph.missing` for `og:title` and `og:description`, while Yoast SEO's social tags are switched on | Social title and description | -These are written to the post, page, custom post type or taxonomy term the URL belongs to. A shared template is never edited and a meta title is never written to `post_title`. +These are written to the post, page, custom post type or taxonomy term the URL belongs to, as long as its type has public pages. A shared template is never edited and a meta title is never written to `post_title`. `canonical.missing` is left to a developer. Yoast SEO prints a canonical itself except on noindex pages, so a missing one points to something else on the site. @@ -58,42 +69,51 @@ A change is refused rather than guessed at, and the finding goes to a person: | --- | --- | | `value_changed` | The field no longer holds what the scan saw, usually because an editor has been in since | | `ambiguous` | The page has no value of its own and its template does not produce what the scan saw. A renamed page does this, and so does a `wpseo_title` or `wpseo_metadesc` filter, so a site using those filters gets inherited values refused | -| `not_found` | Nothing editable answers to the URL. This covers a blog home listing latest posts, post type and author archives, term pages on plain permalinks, and a page's address with a query on the end, such as a search or a campaign link | +| `not_found` | Nothing editable answers to the URL. This covers a blog home listing latest posts, post type and author archives, term pages on plain permalinks, a type with no pages of its own such as a menu item, and a page's address with a query on the end, such as a search or a campaign link | | `no_suggestion` | There is no replacement value, as with `og:image` | | `no_field` | Yoast SEO has no text field for that tag | -If Yoast SEO is not active when a change arrives, nothing is attempted and the change comes back as `failed` with the reason `seo_plugin_inactive`. That keeps its approval, so it goes out again on the next apply. +If Yoast SEO is not active when one of its changes arrives, nothing is attempted and the change comes back as `failed` with the reason `seo_plugin_inactive`. That keeps its approval, so it goes out again on the next apply. -A page that inherits from a template goes back to inheriting when the change is reverted, rather than keeping a copy of the template's text. +A page that inherited from a template goes back to inheriting when the change is reverted, as long as the template still produces what the scan saw. A field that was empty with nothing to inherit is not reverted, because Altimiser has no earlier value to send back, so it keeps the new value until someone clears it in the editor. Each request attempts up to 10 changes within 45 seconds and hands the rest back as `deferred`, for Altimiser to send again. The `altimiser_batch_size` and `altimiser_time_budget` filters change those numbers. The time budget is also held to half of `max_execution_time`. ## Page caches -A request that applies something, or finds it already in place, purges the page cache once, during the request, after Yoast has rebuilt what the page prints. A dry run never does. +A request that applies something, or finds it already in place, purges the pages it changed, once, during the request, after Yoast has rebuilt what the page prints. A dry run never does. -| Plugin | How it was checked | -| --- | --- | -| Breeze 2.6.4 and 2.1.11 | Live: a cached page rendered afresh after an apply | -| W3 Total Cache 2.11.0 | Live: an apply carried out its page cache flush. A page coming back afresh was not observed, because it did not serve cached pages on the local install | -| WP Super Cache 3.1.5 | The purge function exists with the plugin active, and the call is tested. Purging was not observed, because it did not serve cached pages on the local install | -| WP Rocket, LiteSpeed Cache | From reading their source, and not from testing on a running site | +| Plugin | What is purged | How it was checked | +| --- | --- | --- | +| WP Rocket | Each changed page, with `rocket_clean_files()` | From reading its source | +| W3 Total Cache | Each changed page, with `w3tc_flush_url()` | From reading its source. 2.11.0 carried out a whole cache flush live on a local install | +| WP Super Cache | Each changed page, with `wpsc_delete_url_cache()`, and the whole cache for the home page or an address with a query, which it will not delete by address | From reading its source | +| LiteSpeed Cache | Each changed page, through its `litespeed_purge_url` action | From reading its source | +| Breeze | The whole cache, because it offers no purge by address | Live on 2.6.4 and 2.1.11: a cached page rendered afresh after an apply | -Any other page cache is not purged, so a change appears there once the cache expires. +Any other cache, including one run by the host or a CDN, is not purged, so a change appears there once it expires. To purge one, listen for the `altimiser_purge_urls` action, which receives the addresses and whether the whole site changed: + +```php +add_action('altimiser_purge_urls', function (array $urls, bool $everything): void { + // Purge $urls, or everything when $everything is true. +}, 10, 2); +``` `GET /health` is marked as uncacheable, because a cached copy would answer later requests without checking their signature. Breeze 2.1.11 ignores the usual signals on REST responses, so the plugin also makes the check that one version does make come out as not cacheable. Without that, a signed request left a cache file behind on a local install. ## The review queue in wp-admin -This is optional. Add Altimiser's address to `wp-config.php`, and an Altimiser item appears in the admin menu for editors and administrators: +This is optional. Add Altimiser's address on **Settings > Altimiser**, or in `wp-config.php`, and an Altimiser item appears in the admin menu for editors and administrators: ```php define('ALTIMISER_URL', 'https://altimiser.example.com'); ``` -The page shows the queue in a frame that fills the space beside the menu. Altimiser only allows framing by the origin of the site's URL, so the queue will not load for an admin served from another origin, or in a browser that refuses the frame. The frame's link is signed on the server, carries the email address of whoever is signed in, which is who an approval gets recorded against, and expires. Reloading the page gets a new one. +Each editor connects their own Altimiser account once, from that page. **Connect** opens Altimiser, which asks them to sign in and to approve the connection, then sends them back. Altimiser decides what they can do in the queue from their account, so an editor without an account, or whose account has not been given the site, gets no further than the **Connect** button. A connection lasts twelve hours for an agency account and thirty days for a client account, after which the page offers to connect again. **Disconnect** forgets it straight away. Connecting needs wp-admin to be on the same address as the site's URL. -The menu item and a dashboard widget show how many changes are waiting for review. The number is kept for five minutes, so it can lag behind the queue. If Altimiser cannot be reached the number is left out, and it is not asked again for five minutes, so one admin page waits at most five seconds rather than all of them. +Once connected, the page shows the queue in a frame that fills the space beside the menu. Altimiser only allows framing by the origin of the site's URL, so the queue will not load for an admin served from another origin, or in a browser that refuses the frame. The frame's link is signed on the server with the site secret and with the editor's connection, and expires. Reloading the page gets a new one. + +The menu item shows how many changes are waiting for review, to an editor who has connected. The dashboard widget shows the same, along with how many approved changes are waiting to be applied and how many of the site's open findings Altimiser can fix here. The counts are kept for five minutes, so they can lag behind the queue. Altimiser is given two seconds to answer, and only one admin page asks at a time. If it cannot be reached the counts are left out, and it is not asked again for five minutes. Two more constants are available: @@ -102,13 +122,27 @@ Two more constants are available: | `ALTIMISER_SITE_URL` | The address the site was added to Altimiser under, where that differs from WordPress's home URL | | `ALTIMISER_LINK_MINUTES` | How long a review link lasts. The default is 30 | +## What is sent where + +The plugin sends nothing on its own. Altimiser scans the site's public pages from outside, and what it does with them, including sending text and images to AI model providers to write suggestions, is covered by the agreement with the client rather than by this plugin. + +Altimiser sends the site the changes that were approved: page addresses, the values the scan saw, and the values to write. The site answers with what it did. + +With the review queue switched on, the site asks Altimiser for its counts, naming only the site. Connecting and the frame's link carry the signed in editor's email address to Altimiser, which shows it when they connect and keeps it with the connection. Approvals are recorded against the Altimiser account. The token Altimiser hands back is kept against the editor in the database, encrypted with a key drawn from the salts in `wp-config.php`, and never reaches the browser. Tell the client this before switching it on. + +Refused requests that carried a signature, and changes that could not be written, are logged to PHP's error log, which is `wp-content/debug.log` when `WP_DEBUG_LOG` is on. The log names the route or the page address, and holds no secrets or personal data. + ## Updates WordPress's own updater offers new versions, from the latest release on GitHub. The **View details** link in the update notice says the plugin was not found, because it is not in the WordPress directory. The update itself works. A site that keeps its plugins in git should commit the update instead, or the next deploy puts the old version back. -To publish a release, change `Version` in `altimiser.php`, then push a tag naming that version, such as `v0.2.0`. The release workflow builds `altimiser.zip` and publishes it, and fails if the tag and the version disagree. +To publish a release, change `Version` in `altimiser.php` on `main`, then push a tag naming that version, such as `v0.2.0`. The release workflow runs the tests, checks that the tag is on `main` and matches the version, and only then builds `altimiser.zip` and publishes it. A ruleset lets only repository admins create a `v` tag and stops anyone moving or deleting one, and published releases are immutable, so the zip of a release cannot be swapped once it is out. The updater trusts the latest release, so keep admin access to the repository to people who need it. + +## Uninstalling + +Deleting the plugin removes its settings, the counts it keeps and every editor's connection, on every site of a network. Changes it applied are the site's content by then, and stay. ## When the connection fails @@ -116,8 +150,9 @@ To publish a release, change `Version` in `altimiser.php`, then push a tag namin | What Altimiser reports | What it means | What to check | | --- | --- | --- | -| `401` Altimiser is not configured on this site | `ALTIMISER_SECRET` is missing, empty or not a string | That `wp-config.php` on this server defines the constant, with a non empty string as its value | -| `401` Signature does not match | The two ends hold different secrets | Connect again passing the value from `wp-config.php` | +| `401` Altimiser is not configured on this site | No secret is set, or it is empty or not a string | **Settings > Altimiser**, which says where the secret is expected and whether one is found | +| `401` The Altimiser secret on this site is shorter than 32 characters | A secret is set and too short to accept | Replace it with a longer one, in the same place, and connect again with the new value | +| `401` Signature does not match | The two ends hold different secrets | Connect again passing the value the site holds | | `401` Signature timestamp is outside the accepted window | The timestamp was more than five minutes out, or never arrived | The clocks on both servers. Something in front of the site may also be removing the `X-Altimiser-*` headers | | `404` `rest_no_route` | WordPress answered and has no such route | That the plugin is active, and that the receiver URL ends in `/altimiser/v1` | | `200` followed by HTML | The address is not reaching the REST API. On plain permalinks `/wp-json` is not routed, so WordPress answers with an ordinary page | Choose any other permalink structure, or use `https://example.com/?rest_route=/altimiser/v1` as the receiver URL | @@ -130,7 +165,7 @@ Two common security plugins need nothing doing. From reading their source, and n ## Testing -The tests run against a real WordPress, which Composer installs into `wordpress/`, and a real Yoast SEO from wpackagist, in `vendor/wp-plugins/`. They need MySQL at `127.0.0.1` as `root` with no password. +The tests run against a real WordPress, which Composer installs into `wordpress/`, and a real Yoast SEO from wpackagist, in `vendor/wp-plugins/`. They need MySQL as `root` with no password, at `127.0.0.1` unless `WP_TESTS_DB_HOST` says otherwise, in a database named `altimiser_wordpress_tests` unless `WP_TESTS_DB_NAME` says otherwise. ```bash composer install @@ -138,8 +173,8 @@ mysql -h127.0.0.1 -uroot -e "CREATE DATABASE IF NOT EXISTS altimiser_wordpress_t vendor/bin/phpunit ``` -GitHub Actions runs them on PHP 8.1 to 8.4, against WordPress 6.8 and the latest release. +GitHub Actions runs them on PHP 8.1 to 8.4, against WordPress 6.8 and the latest release, with the latest Yoast SEO, and once more on PHP 8.1 and WordPress 6.8 with Yoast SEO 24.0. Anything the plugin logs during the tests goes to `altimiser-tests.log` in the system's temporary directory. `SignatureTest` computes the signature from the protocol document rather than taking it from the plugin or from Altimiser, and checks that calculation against the document's worked examples. Requests go through WordPress's own REST server, so `permission_callback` is what is under test. -`NoSecretTest` runs each test in a process of its own, because a constant cannot be undefined or redefined. `PageCacheTest` does the same, and defines stand-ins for the cache plugins' purge functions in `tests/fixtures/page-cache-plugins.php`. +`NoSecretTest`, `SecretSourcesTest` and `SettingsPageTest` run each test in a process of its own, because a constant cannot be undefined or redefined. `PageCacheTest` does the same where it defines stand-ins for the cache plugins' purge functions, in `tests/fixtures/page-cache-plugins.php`. diff --git a/altimiser.php b/altimiser.php index 5b7e0ba..a67303e 100644 --- a/altimiser.php +++ b/altimiser.php @@ -10,37 +10,46 @@ * Author: Alt Design * Author URI: https://alt-design.net * Update URI: https://github.com/alt-design/altimiser-wordpress + * Text Domain: altimiser */ +use AltDesign\Altimiser\ConnectionFlow; use AltDesign\Altimiser\ControlPanel; use AltDesign\Altimiser\Receiver; use AltDesign\Altimiser\ReviewQueuePage; +use AltDesign\Altimiser\Settings; +use AltDesign\Altimiser\SettingsPage; use AltDesign\Altimiser\Updater; use AltDesign\Altimiser\Yoast; defined('ABSPATH') || exit; -require_once __DIR__.'/src/ChangeDispatcher.php'; -require_once __DIR__.'/src/ChangeRequest.php'; -require_once __DIR__.'/src/ChangeResult.php'; -require_once __DIR__.'/src/ContentResolver.php'; -require_once __DIR__.'/src/ControlPanel.php'; -require_once __DIR__.'/src/PageCache.php'; -require_once __DIR__.'/src/Receiver.php'; -require_once __DIR__.'/src/ReviewQueuePage.php'; -require_once __DIR__.'/src/Updater.php'; -require_once __DIR__.'/src/Yoast.php'; -require_once __DIR__.'/src/YoastApplier.php'; +spl_autoload_register(static function (string $class): void { + $namespace = 'AltDesign\\Altimiser\\'; + $file = __DIR__.'/src/'.str_replace('\\', '/', substr($class, strlen($namespace))).'.php'; + + if (str_starts_with($class, $namespace) && is_file($file)) { + require $file; + } +}); add_action('rest_api_init', static function (): void { (new Receiver(__FILE__, defined('WPSEO_VERSION') ? new Yoast() : null))->registerRoutes(); }); +add_action('add_option_'.Settings::$option, [Settings::class, 'keepOutOfAutoload']); +add_action('update_option_'.Settings::$option, [Settings::class, 'keepOutOfAutoload']); + add_action('plugins_loaded', static function (): void { + if (is_admin()) { + (new SettingsPage())->register(); + } + $controlPanel = ControlPanel::configured(); if ($controlPanel !== null) { (new ReviewQueuePage($controlPanel))->register(); + (new ConnectionFlow($controlPanel))->register(); } }); diff --git a/src/Applier.php b/src/Applier.php new file mode 100644 index 0000000..f25f8f4 --- /dev/null +++ b/src/Applier.php @@ -0,0 +1,20 @@ + + */ + public function checks(): array; + + public function supports(string $check): bool; + + /** + * @return array + */ + public function apply(ChangeRequest $change, bool $dryRun): array; +} diff --git a/src/ChangeDispatcher.php b/src/ChangeDispatcher.php index 3495a87..e1aca69 100644 --- a/src/ChangeDispatcher.php +++ b/src/ChangeDispatcher.php @@ -7,7 +7,7 @@ class ChangeDispatcher { /** - * @param array $appliers + * @param array $appliers */ public function __construct(private array $appliers, private PageCache $pageCache) {} @@ -18,8 +18,9 @@ public function __construct(private array $appliers, private PageCache $pageCach * * The purge happens here and not at the end of the request because W3 Total Cache * carries a flush out on the shutdown action, so one asked for later is not acted on. - * A change already in place purges too: the request that wrote it may have died before - * getting this far, and being sent the change again is the only chance left to do it. + * A change already in place purges its page too: the request that wrote it may have + * died before getting this far, and being sent the change again is the only chance + * left to do it. * * @param array $changes * @return array> @@ -31,6 +32,8 @@ public function dispatch(array $changes, bool $dryRun): array $budget = $this->timeBudget(); $results = []; + $landed = []; + foreach ($changes as $change) { if ($results !== [] && $this->outOfRoom(count($results), $batchSize, $startedAt, $budget)) { $results[] = ChangeResult::deferred($change->id); @@ -38,16 +41,44 @@ public function dispatch(array $changes, bool $dryRun): array continue; } - $results[] = $this->applyOne($change, $dryRun); + $result = $this->applyOne($change, $dryRun); + $results[] = $result; + + if (in_array($result['status'], ['applied', 'already_applied'], true)) { + $landed[] = [$change->url, $result['location'] ?? []]; + } } - if (! $dryRun && array_intersect(['applied', 'already_applied'], array_column($results, 'status')) !== []) { - $this->pageCache->purge(); + if (! $dryRun) { + $this->purge($landed); } return $results; } + /** + * A change stored as a default shows on every page of its kind, so it clears the + * whole cache. Anything else clears the page it was made for. + * + * @param array}> $landed + */ + private function purge(array $landed): void + { + if ($landed === []) { + return; + } + + foreach ($landed as [, $location]) { + if (($location['default'] ?? false) === true) { + $this->pageCache->purgeEverything(); + + return; + } + } + + $this->pageCache->purge(array_column($landed, 0)); + } + /** * Half the limit, because a request killed mid-change leaves it unrecorded, and * one change can take a while once it has been started. @@ -66,31 +97,26 @@ private function outOfRoom(int $attempted, int $batchSize, float $startedAt, flo } /** - * Failed rather than skipped with no applier, because Altimiser withdraws the - * approval on a skip, and this one comes out differently once Yoast SEO is back. - * * @return array */ private function applyOne(ChangeRequest $change, bool $dryRun): array { - if ($this->appliers === []) { - return ChangeResult::failed( - $change->id, - 'seo_plugin_inactive', - 'Yoast SEO is not active on this site, so nothing was attempted. The change stays approved for the next apply.', - ); - } - foreach ($this->appliers as $applier) { if (! $applier->supports($change->check)) { continue; } try { - return $applier->apply($change, $dryRun); + $result = $applier->apply($change, $dryRun); } catch (Throwable $exception) { - return ChangeResult::failed($change->id, 'write_failed', $exception->getMessage()); + $result = ChangeResult::failed($change->id, 'write_failed', $exception->getMessage()); } + + if (($result['reason'] ?? null) === 'write_failed') { + error_log("Altimiser could not apply {$change->check} to {$change->url}: {$result['message']}"); + } + + return $result; } return ChangeResult::skipped( diff --git a/src/ConnectionFlow.php b/src/ConnectionFlow.php new file mode 100644 index 0000000..e217588 --- /dev/null +++ b/src/ConnectionFlow.php @@ -0,0 +1,128 @@ + 'start', 'connected' => 'finish', 'disconnect' => 'disconnect'] as $action => $step) { + add_action("admin_post_altimiser_{$action}", function () use ($step): void { + wp_redirect($this->{$step}()); + exit; + }); + } + } + + public function start(): string + { + if (! $this->allowed('altimiser_connect')) { + return self::back('error', __('That link has expired. Try connecting again.', 'altimiser')); + } + + if (! $this->panel->isOnSiteOrigin(self::callbackUrl())) { + return self::back('error', __('Connecting needs wp-admin to be on the same address as the site itself. Open wp-admin at the site\'s own address and try again.', 'altimiser')); + } + + $state = wp_generate_password(40, false); + + set_transient(self::stateKey(), $state, 10 * MINUTE_IN_SECONDS); + + return $this->panel->connectUrl($state, self::callbackUrl(), wp_get_current_user()->user_email, time() + 5 * MINUTE_IN_SECONDS); + } + + public function finish(): string + { + $expected = get_transient(self::stateKey()); + $state = self::query('state'); + + delete_transient(self::stateKey()); + + if (! current_user_can(ReviewQueuePage::$capability) || ! is_string($expected) || $state === null || ! hash_equals($expected, $state)) { + return self::back('error', __('That connection attempt could not be checked. Try connecting again.', 'altimiser')); + } + + if (self::query('error') === 'access_denied') { + return self::back('error', __('Your Altimiser account was not connected. Either it was declined, or your account has not been given this site. Ask your agency if you expected it to be.', 'altimiser')); + } + + $code = self::query('code'); + + if ($code === null) { + return self::back('error', __('Altimiser did not send back a code. Try connecting again.', 'altimiser')); + } + + $connection = $this->panel->exchange($code, self::callbackUrl()); + + if (is_wp_error($connection)) { + /* translators: %s: Altimiser's reason, in English */ + return self::back('error', sprintf(__('Your Altimiser account could not be connected: %s', 'altimiser'), $connection->get_error_message())); + } + + Connections::put(get_current_user_id(), $connection); + + return self::back('success', __('Your Altimiser account is connected.', 'altimiser')); + } + + public function disconnect(): string + { + if (! $this->allowed('altimiser_disconnect')) { + return self::back('error', __('That link has expired. Try again.', 'altimiser')); + } + + Connections::forget(get_current_user_id()); + + return self::back('success', __('Your Altimiser account is disconnected.', 'altimiser')); + } + + /** + * The message the last step left for the review queue page, read once. + * + * @return ?array{level: string, message: string} + */ + public static function takeNotice(): ?array + { + $key = 'altimiser_notice_'.get_current_user_id(); + $notice = get_transient($key); + + delete_transient($key); + + return is_array($notice) ? $notice : null; + } + + private function allowed(string $action): bool + { + return current_user_can(ReviewQueuePage::$capability) + && wp_verify_nonce(sanitize_text_field(wp_unslash($_REQUEST['_wpnonce'] ?? '')), $action) !== false; + } + + private static function back(string $level, string $message): string + { + set_transient('altimiser_notice_'.get_current_user_id(), ['level' => $level, 'message' => $message], MINUTE_IN_SECONDS); + + return admin_url('admin.php?page=altimiser'); + } + + private static function callbackUrl(): string + { + return admin_url('admin-post.php?action=altimiser_connected'); + } + + private static function stateKey(): string + { + return 'altimiser_connect_state_'.get_current_user_id(); + } + + private static function query(string $key): ?string + { + $value = $_GET[$key] ?? null; + + return is_string($value) && $value !== '' ? sanitize_text_field(wp_unslash($value)) : null; + } +} diff --git a/src/Connections.php b/src/Connections.php new file mode 100644 index 0000000..3a16830 --- /dev/null +++ b/src/Connections.php @@ -0,0 +1,72 @@ + base64_encode($nonce.sodium_crypto_secretbox($connection['token'], $nonce, self::key())), + ]); + } + + /** + * The editor's connection, or null when there is none, it has expired, or its token + * can no longer be read. + * + * @return ?array{connection: string, token: string, expires_at: int, account_email: string} + */ + public static function live(int $userId): ?array + { + $stored = get_user_option(self::$option, $userId); + + if (! is_array($stored) || ($stored['expires_at'] ?? 0) <= time()) { + return null; + } + + $token = self::open((string) ($stored['token'] ?? '')); + + return $token === null ? null : [...$stored, 'token' => $token]; + } + + public static function forget(int $userId): void + { + delete_user_option($userId, self::$option); + } + + private static function open(string $sealed): ?string + { + $sealed = (string) base64_decode($sealed, true); + + if (strlen($sealed) <= SODIUM_CRYPTO_SECRETBOX_NONCEBYTES) { + return null; + } + + $token = sodium_crypto_secretbox_open( + substr($sealed, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES), + substr($sealed, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES), + self::key(), + ); + + return $token === false ? null : $token; + } + + private static function key(): string + { + return hash_hmac('sha256', 'altimiser connection', wp_salt('auth'), true); + } +} diff --git a/src/ContentResolver.php b/src/ContentResolver.php index ef9e988..59a707e 100644 --- a/src/ContentResolver.php +++ b/src/ContentResolver.php @@ -22,7 +22,8 @@ public function find(string $url): WP_Post|WP_Term|null * url_to_postid() answers for unpublished records and revisions, for the addresses * beneath a page, such as its feed or its second page, and ignores the query, so * /?s=anything answers as a static home page. A suggestion made for one of those - * does not belong on the page itself. + * does not belong on the page itself. Under plain permalinks it also answers + * ?p=N for a menu item or any other type with no page of its own. */ private function isPublishedAt(string $url, int $postId): bool { @@ -30,6 +31,10 @@ private function isPublishedAt(string $url, int $postId): bool return false; } + if (! is_post_type_viewable((string) get_post_type($postId))) { + return false; + } + return $this->address(get_permalink($postId)) === $this->address($url); } diff --git a/src/ControlPanel.php b/src/ControlPanel.php index 02ac0be..3116dc6 100644 --- a/src/ControlPanel.php +++ b/src/ControlPanel.php @@ -2,6 +2,8 @@ namespace AltDesign\Altimiser; +use WP_Error; + class ControlPanel { public function __construct( @@ -13,19 +15,19 @@ public function __construct( public static function configured(): ?self { - $altimiserUrl = defined('ALTIMISER_URL') ? constant('ALTIMISER_URL') : null; - $secret = defined('ALTIMISER_SECRET') ? constant('ALTIMISER_SECRET') : null; + $altimiserUrl = Settings::altimiserUrl(); + $secret = Settings::secret(); - if (! is_string($altimiserUrl) || trim($altimiserUrl) === '') { + if ($altimiserUrl === null || $secret === null) { return null; } - if (! is_string($secret) || trim($secret) === '') { + if (! Settings::secretIsLongEnough($secret)) { return null; } return new self( - rtrim($altimiserUrl, '/'), + $altimiserUrl, rtrim(defined('ALTIMISER_SITE_URL') ? (string) constant('ALTIMISER_SITE_URL') : home_url(), '/'), $secret, defined('ALTIMISER_LINK_MINUTES') ? (int) constant('ALTIMISER_LINK_MINUTES') : 30, @@ -37,47 +39,158 @@ public function linkExpiry(): int return time() + $this->linkMinutes * MINUTE_IN_SECONDS; } - public function reviewUrl(string $user, int $expires): string + /** + * Signed twice: with the site secret, which proves the site, and with the editor's + * own token, which proves their Altimiser account. + * + * @param array{connection: string, token: string} $connection + */ + public function reviewUrl(string $user, int $expires, array $connection): string { - $url = "{$this->altimiserUrl}/review?".http_build_query(array_filter([ + $url = $this->unsignedUrl('/review', [ + 'connection' => $connection['connection'], 'embedded' => '1', 'expires' => $expires, 'site' => $this->siteUrl, 'user' => $user, - ])); + ]); + + return "{$url}&signature=".hash_hmac('sha256', $url, $this->secret) + .'&connection_signature='.hash_hmac('sha256', $url, $connection['token']); + } + + public function connectUrl(string $state, string $redirectUri, string $user, int $expires): string + { + $url = $this->unsignedUrl('/connect', [ + 'expires' => $expires, + 'redirect_uri' => $redirectUri, + 'site' => $this->siteUrl, + 'state' => $state, + 'user' => $user, + ]); return "{$url}&signature=".hash_hmac('sha256', $url, $this->secret); } /** - * Read on every admin page, so an unreachable Altimiser is remembered as well. - * Asking again each time would put the timeout in front of every screen. + * Trades the code Altimiser sent the editor back with for their connection. Redirects + * are not followed, because the signature would be sent on to wherever they lead. + * + * @return array{connection: string, token: string, expires_at: int, account_email: string}|WP_Error + */ + public function exchange(string $code, string $redirectUri): array|WP_Error + { + $body = (string) wp_json_encode(['site' => $this->siteUrl, 'code' => $code, 'redirect_uri' => $redirectUri], JSON_UNESCAPED_SLASHES); + $timestamp = time(); + + $response = wp_remote_post("{$this->altimiserUrl}/api/connections", [ + 'timeout' => 15, + 'redirection' => 0, + 'headers' => [ + 'X-Altimiser-Timestamp' => (string) $timestamp, + 'X-Altimiser-Signature' => 'sha256='.hash_hmac('sha256', "{$timestamp}\n{$body}", $this->secret), + 'Content-Type' => 'application/json', + 'Accept' => 'application/json', + ], + 'body' => $body, + ]); + + if (is_wp_error($response)) { + return new WP_Error('unreachable', __('Altimiser could not be reached.', 'altimiser')); + } + + $answer = json_decode(wp_remote_retrieve_body($response), true); + + if (wp_remote_retrieve_response_code($response) !== 201) { + return new WP_Error('refused', is_string($answer['message'] ?? null) ? $answer['message'] : __('Altimiser refused the connection.', 'altimiser')); + } + + $expiresAt = strtotime((string) ($answer['expires_at'] ?? '')); + + if (! is_string($answer['connection'] ?? null) || ! is_string($answer['token'] ?? null) || $expiresAt === false) { + return new WP_Error('unreadable', __('Altimiser sent an answer that could not be read.', 'altimiser')); + } + + return [ + 'connection' => $answer['connection'], + 'token' => $answer['token'], + 'expires_at' => $expiresAt, + 'account_email' => (string) ($answer['account']['email'] ?? ''), + ]; + } + + public function isOnSiteOrigin(string $url): bool + { + return self::origin($url) === self::origin($this->siteUrl); + } + + private static function origin(string $url): string + { + $parts = (array) parse_url($url); + $scheme = strtolower($parts['scheme'] ?? ''); + $port = $parts['port'] ?? ($scheme === 'https' ? 443 : 80); + + return "{$scheme}://".strtolower($parts['host'] ?? '').":{$port}"; + } + + /** + * @param array $query */ + private function unsignedUrl(string $path, array $query): string + { + $query = array_filter($query); + + ksort($query); + + return "{$this->altimiserUrl}{$path}?".http_build_query($query); + } + public function awaitingReview(): ?int { - $cached = get_transient('altimiser_awaiting_review'); + return $this->summary()['awaiting_review'] ?? null; + } + + /** + * Read on every admin page, so an unreachable Altimiser is remembered as well. + * Asking again each time would put the timeout in front of every screen, and the + * lock keeps the screens opened while one request waits from asking as well. + * + * @return ?array + */ + public function summary(): ?array + { + $cached = get_transient('altimiser_summary'); if (is_array($cached)) { - return $cached['count']; + return $cached['summary']; } - $count = $this->fetchAwaitingReview(); + if (get_transient('altimiser_summary_lock') !== false) { + return null; + } + + set_transient('altimiser_summary_lock', true, 30); + + $summary = $this->fetchSummary(); - set_transient('altimiser_awaiting_review', ['count' => $count], 5 * MINUTE_IN_SECONDS); + set_transient('altimiser_summary', ['summary' => $summary], 5 * MINUTE_IN_SECONDS); + delete_transient('altimiser_summary_lock'); - return $count; + return $summary; } /** * Redirects are not followed, because the signature would be sent on to wherever - * they lead. + * they lead. Only whole numbers are kept, and the badge's count has to be one of them. + * + * @return ?array */ - private function fetchAwaitingReview(): ?int + private function fetchSummary(): ?array { $timestamp = time(); $response = wp_remote_get("{$this->altimiserUrl}/api/summary?".http_build_query(['site' => $this->siteUrl]), [ - 'timeout' => 5, + 'timeout' => 2, 'redirection' => 0, 'headers' => [ 'X-Altimiser-Timestamp' => (string) $timestamp, @@ -90,8 +203,12 @@ private function fetchAwaitingReview(): ?int return null; } - $count = json_decode(wp_remote_retrieve_body($response), true)['awaiting_review'] ?? null; + $body = json_decode(wp_remote_retrieve_body($response), true); + + if (! is_int($body['awaiting_review'] ?? null)) { + return null; + } - return is_int($count) ? $count : null; + return array_filter($body, 'is_int'); } } diff --git a/src/InactiveSeoPlugin.php b/src/InactiveSeoPlugin.php new file mode 100644 index 0000000..26ab61a --- /dev/null +++ b/src/InactiveSeoPlugin.php @@ -0,0 +1,30 @@ +id, + 'seo_plugin_inactive', + 'Yoast SEO is not active on this site, so nothing was attempted. The change stays approved for the next apply.', + ); + } +} diff --git a/src/PageCache.php b/src/PageCache.php index bdea2c8..751f8a3 100644 --- a/src/PageCache.php +++ b/src/PageCache.php @@ -4,32 +4,80 @@ use Throwable; +/** + * Altimiser scans again a few minutes after applying, and a cached page would hand a + * fix that landed back as one that did not. A failure here is logged and not returned, + * because the changes it follows have already been written. + * + * Each plugin's function was checked in its own source: WP Rocket's rocket_clean_files(), + * W3 Total Cache's w3tc_flush_url(), WP Super Cache's wpsc_delete_url_cache() and + * LiteSpeed's litespeed_purge_url action. Breeze offers no purge by address, so it is + * cleared whole. A host or edge cache can listen for altimiser_purge_urls. + */ class PageCache { /** - * Altimiser scans again a few minutes after applying, and a cached page would - * hand a fix that landed back as one that did not. A failure here is logged and - * not returned, because the changes it follows have already been written. + * @param array $urls */ - public function purge(): void + public function purge(array $urls): void { - try { - if (function_exists('rocket_clean_domain')) { - rocket_clean_domain(); - } + $urls = array_values(array_unique($urls)); - if (function_exists('w3tc_flush_all')) { - w3tc_flush_all(); - } + if ($urls === []) { + return; + } + + $this->eachQuietly([ + static fn () => function_exists('rocket_clean_files') && rocket_clean_files($urls), + static fn () => function_exists('w3tc_flush_url') && array_map('w3tc_flush_url', $urls), + static fn () => self::purgeSuperCache($urls), + static fn () => array_map(static fn (string $url) => do_action('litespeed_purge_url', $url), $urls), + static fn () => do_action('breeze_clear_all_cache'), + static fn () => do_action('altimiser_purge_urls', $urls, false), + ]); + } + + /** + * For a change that shows on every page of a kind, such as a default for a post type. + */ + public function purgeEverything(): void + { + $this->eachQuietly([ + static fn () => function_exists('rocket_clean_domain') && rocket_clean_domain(), + static fn () => function_exists('w3tc_flush_all') && w3tc_flush_all(), + static fn () => function_exists('wp_cache_clear_cache') && wp_cache_clear_cache(), + static fn () => do_action('litespeed_purge_all'), + static fn () => do_action('breeze_clear_all_cache'), + static fn () => do_action('altimiser_purge_urls', [home_url('/')], true), + ]); + } - if (function_exists('wp_cache_clear_cache')) { - wp_cache_clear_cache(); + /** + * One cache plugin failing is no reason to leave the others holding the old page. + * + * @param array $purges + */ + private function eachQuietly(array $purges): void + { + foreach ($purges as $purge) { + try { + $purge(); + } catch (Throwable $exception) { + error_log("Altimiser could not purge the page cache: {$exception->getMessage()}"); } + } + } - do_action('litespeed_purge_all'); - do_action('breeze_clear_all_cache'); - } catch (Throwable $exception) { - error_log("Altimiser could not purge the page cache: {$exception->getMessage()}"); + /** + * WP Super Cache will not delete its home page or an address with a query by + * address, and says so by returning false, so it is cleared whole for those. + * + * @param array $urls + */ + private static function purgeSuperCache(array $urls): void + { + if (function_exists('wpsc_delete_url_cache') && in_array(false, array_map('wpsc_delete_url_cache', $urls), true)) { + wp_cache_clear_cache(); } } } diff --git a/src/Receiver.php b/src/Receiver.php index 751db70..28882ff 100644 --- a/src/Receiver.php +++ b/src/Receiver.php @@ -2,6 +2,7 @@ namespace AltDesign\Altimiser; +use Throwable; use WP_Error; use WP_REST_Request; use WP_REST_Response; @@ -28,47 +29,115 @@ public function registerRoutes(): void ]); } + /** + * A refused request that carried a signature is logged, because it is most likely + * Altimiser with the wrong secret or a clock out of step. Ones without are left out, + * since anything probing the route would fill the log. + */ public function verifySignature(WP_REST_Request $request): bool|WP_Error { - $secret = defined('ALTIMISER_SECRET') ? constant('ALTIMISER_SECRET') : null; + $refusal = $this->refusal($request); + + if ($refusal === null) { + return true; + } + + if ($request->get_header('X-Altimiser-Signature') !== null) { + error_log("Altimiser refused a signed request to {$request->get_route()}: {$refusal}"); + } + + return new WP_Error('altimiser_refused', $refusal, ['status' => 401]); + } + + private function refusal(WP_REST_Request $request): ?string + { + $secret = Settings::secret(); - if (! is_string($secret) || trim($secret) === '') { - return $this->refuse('Altimiser is not configured on this site.'); + if ($secret === null) { + return 'Altimiser is not configured on this site.'; + } + + if (! Settings::secretIsLongEnough($secret)) { + return 'The Altimiser secret on this site is shorter than 32 characters, so requests are refused until it is replaced with a longer one.'; } $timestamp = (int) $request->get_header('X-Altimiser-Timestamp'); if (abs(time() - $timestamp) > $this->toleranceInSeconds) { - return $this->refuse('Signature timestamp is outside the accepted window.'); + return 'Signature timestamp is outside the accepted window.'; } $expected = 'sha256='.hash_hmac('sha256', "{$timestamp}\n{$request->get_body()}", $secret); if (! hash_equals($expected, (string) $request->get_header('X-Altimiser-Signature'))) { - return $this->refuse('Signature does not match.'); + return 'Signature does not match.'; } - return true; + return null; } public function health(): WP_REST_Response { - $checks = array_merge([], ...array_map( - static fn (YoastApplier $applier): array => $applier->checks(), - $this->appliers(), - )); + $checks = $this->advertisedChecks(); return $this->uncached([ 'receiver' => 'wordpress', 'receiver_version' => get_file_data($this->pluginFile, ['version' => 'Version'])['version'], 'cms_version' => get_bloginfo('version'), - 'capabilities' => $checks === [] ? [] : ['content.update'], + 'capabilities' => $this->capabilities($checks), 'checks' => $checks, 'integrations' => ['yoast' => $this->yoastState()], + 'setup' => $this->setup(), 'site_url' => home_url(), ]); } + /** + * An applier that throws is left out rather than stopping the answer, so a fault + * in Yoast costs its own checks and not the connection. + * + * @return array + */ + private function advertisedChecks(): array + { + $checks = []; + + foreach ($this->appliers() as $applier) { + try { + $checks = [...$checks, ...$applier->checks()]; + } catch (Throwable $exception) { + error_log("Altimiser left out the checks of one applier: {$exception->getMessage()}"); + } + } + + return array_values(array_unique($checks)); + } + + /** + * @param array $checks + * @return array + */ + private function capabilities(array $checks): array + { + return array_keys(array_filter([ + 'content.update' => $checks !== [], + 'content.link' => in_array('link.opportunity', $checks, true), + ])); + } + + /** + * Settings that stop fixes from counting, which Altimiser reports as findings. + * + * @return array + */ + private function setup(): array + { + return [ + 'search_engines_discouraged' => (string) get_option('blog_public', '1') === '0', + 'plain_permalinks' => (string) get_option('permalink_structure') === '', + ]; + } + public function changes(WP_REST_Request $request): WP_REST_Response|WP_Error { $payload = json_decode($request->get_body(), true); @@ -105,11 +174,15 @@ public function changes(WP_REST_Request $request): WP_REST_Response|WP_Error } /** - * @return array + * @return array */ private function appliers(): array { - return $this->yoast === null ? [] : [new YoastApplier($this->yoast, new ContentResolver())]; + $content = new ContentResolver(); + + return [ + $this->yoast === null ? new InactiveSeoPlugin() : new YoastApplier($this->yoast, $content), + ]; } /** @@ -146,9 +219,4 @@ private function uncached(array $body): WP_REST_Response return new WP_REST_Response($body, 200, array_filter(wp_get_nocache_headers())); } - - private function refuse(string $message): WP_Error - { - return new WP_Error('altimiser_refused', $message, ['status' => 401]); - } } diff --git a/src/ReviewQueuePage.php b/src/ReviewQueuePage.php index e120214..e8320a0 100644 --- a/src/ReviewQueuePage.php +++ b/src/ReviewQueuePage.php @@ -4,7 +4,7 @@ class ReviewQueuePage { - private string $capability = 'edit_others_posts'; + public static string $capability = 'edit_others_posts'; public function __construct(private ControlPanel $panel) {} @@ -12,15 +12,23 @@ public function register(): void { add_action('admin_menu', [$this, 'addMenuItem']); add_action('wp_dashboard_setup', [$this, 'addDashboardWidget']); + add_action('admin_enqueue_scripts', [$this, 'addStyles']); } public function addMenuItem(): void { - if (! current_user_can($this->capability)) { + if (! current_user_can(self::$capability)) { return; } - add_menu_page('Altimiser', 'Altimiser'.$this->badge(), $this->capability, 'altimiser', [$this, 'render'], $this->icon()); + add_menu_page( + __('Altimiser', 'altimiser'), + __('Altimiser', 'altimiser').$this->badge(), + self::$capability, + 'altimiser', + [$this, 'render'], + $this->icon(), + ); } /** @@ -40,53 +48,201 @@ private function icon(): string public function addDashboardWidget(): void { - if (! current_user_can($this->capability)) { + if (! current_user_can(self::$capability)) { + return; + } + + wp_add_dashboard_widget('altimiser', __('Altimiser', 'altimiser'), [$this, 'renderWidget']); + } + + /** + * The queue fills the screen below the admin bar, with WordPress's own padding and + * footer taken away around it. + */ + public function addStyles(string $hook): void + { + if ($hook !== 'toplevel_page_altimiser') { return; } - wp_add_dashboard_widget('altimiser', 'Altimiser', [$this, 'renderWidget']); + wp_register_style('altimiser-review-queue', false, [], null); + wp_enqueue_style('altimiser-review-queue'); + wp_add_inline_style( + 'altimiser-review-queue', + '.wp-admin #wpcontent{padding:0}#wpbody-content{padding-bottom:0}#wpfooter{display:none}' + .'.altimiser-layout{display:flex;flex-direction:column;height:calc(100vh - var(--wp-admin--admin-bar--height,32px))}' + .'.altimiser-layout .notice{margin:12px}' + .'.altimiser-connection{padding:6px 12px}.altimiser-connection form{display:inline}' + .'.altimiser-connect{max-width:32rem;margin:4rem auto;padding:0 20px;text-align:center}' + .'.altimiser-review-queue{display:block;flex:1;min-height:0;width:100%;border:0}', + ); } public function render(): void + { + $notice = ConnectionFlow::takeNotice(); + $connection = Connections::live(get_current_user_id()); + + echo '
'; + + if ($notice !== null) { + printf('

%s

', esc_attr($notice['level']), esc_html($notice['message'])); + } + + $connection === null ? $this->renderConnect() : $this->renderQueue($connection); + + echo '
'; + } + + /** + * Opened as a page of its own rather than in the frame, so the editor can sign in to + * Altimiser with their own session. + */ + private function renderConnect(): void + { + printf( + '

%s

%s

%s

', + esc_html__('Connect your Altimiser account', 'altimiser'), + esc_html__('The review queue is on Altimiser. Connect your Altimiser account to use it. Your agency gives you an account.', 'altimiser'), + esc_url(wp_nonce_url(admin_url('admin-post.php?action=altimiser_connect'), 'altimiser_connect')), + esc_html__('Connect', 'altimiser'), + ); + } + + /** + * @param array{connection: string, token: string, expires_at: int, account_email: string} $connection + */ + private function renderQueue(array $connection): void { printf( - '' - .'', - esc_url($this->panel->reviewUrl(wp_get_current_user()->user_email, $this->panel->linkExpiry())), + esc_url($this->panel->reviewUrl(wp_get_current_user()->user_email, $this->panel->linkExpiry(), $connection)), + esc_attr__('Altimiser review queue', 'altimiser'), ); } + /** + * Counts are shown only once the editor has connected their account, so nothing about + * the queue appears to someone Altimiser has not given the site. + */ public function renderWidget(): void + { + if (Connections::live(get_current_user_id()) === null) { + printf('

%s

', esc_html__('Connect your Altimiser account to see what is waiting for review.', 'altimiser')); + $this->renderOpenButton(__('Connect your account', 'altimiser')); + + return; + } + + $summary = $this->panel->summary(); + + printf('

%s

', esc_html($this->describe($summary['awaiting_review'] ?? null))); + + $details = array_filter([$this->pending($summary), $this->handled($summary)]); + + if ($details !== []) { + printf('
    %s
', implode('', array_map( + static fn (string $detail): string => '
  • '.esc_html($detail).'
  • ', + $details, + ))); + } + + $this->renderOpenButton(__('Open the review queue', 'altimiser')); + } + + private function renderOpenButton(string $label): void { printf( - '

    %s

    Open the review queue

    ', - esc_html($this->describe($this->panel->awaitingReview())), + '

    %s

    ', esc_url(admin_url('admin.php?page=altimiser')), + esc_html($label), ); } private function badge(): string { - $count = $this->panel->awaitingReview(); + $count = Connections::live(get_current_user_id()) === null ? null : $this->panel->awaitingReview(); if (! $count) { return ''; } return sprintf( - ' %1$d waiting for review', + ' %2$s', $count, + esc_html(sprintf( + /* translators: %d: how many changes are waiting for review */ + _n('%d waiting for review', '%d waiting for review', $count, 'altimiser'), + $count, + )), ); } private function describe(?int $count): string { - return match ($count) { - null => 'The count is not available right now, but the review queue should still open.', - 0 => 'Nothing is waiting for review.', - 1 => '1 change is waiting for review.', - default => "{$count} changes are waiting for review.", - }; + if ($count === null) { + return __('The count is not available right now, but the review queue should still open.', 'altimiser'); + } + + if ($count === 0) { + return __('Nothing is waiting for review.', 'altimiser'); + } + + return sprintf( + /* translators: %d: how many changes are waiting for review */ + _n('%d change is waiting for review.', '%d changes are waiting for review.', $count, 'altimiser'), + $count, + ); + } + + /** + * @param ?array $summary + */ + private function pending(?array $summary): ?string + { + $pending = $summary['pending'] ?? 0; + + if ($pending === 0) { + return null; + } + + return sprintf( + /* translators: %d: how many approved changes have not been applied yet */ + _n('%d approved change is waiting to be applied.', '%d approved changes are waiting to be applied.', $pending, 'altimiser'), + $pending, + ); + } + + /** + * @param ?array $summary + */ + private function handled(?array $summary): ?string + { + $outstanding = $summary['outstanding'] ?? 0; + + if ($outstanding === 0) { + return null; + } + + return sprintf( + /* translators: 1: findings this plugin can fix, 2: all open findings */ + _n('Altimiser can apply fixes for %1$d of the %2$d open finding on this site.', 'Altimiser can apply fixes for %1$d of the %2$d open findings on this site.', $outstanding, 'altimiser'), + $summary['handled'] ?? 0, + $outstanding, + ); } } diff --git a/src/Settings.php b/src/Settings.php new file mode 100644 index 0000000..ed79808 --- /dev/null +++ b/src/Settings.php @@ -0,0 +1,74 @@ += self::$minimumSecretLength; + } + + /** + * Whether a value is fixed outside the settings page, which then shows it as set + * elsewhere rather than offering a field that would be ignored. + */ + public static function definedOutsideSettings(string $constant): bool + { + return self::fromCode($constant) !== null; + } + + /** + * @return array{secret?: string, altimiser_url?: string} + */ + public static function stored(): array + { + $stored = get_option(self::$option, []); + + return is_array($stored) ? $stored : []; + } + + /** + * The secret is needed only when a request arrives, so it stays out of the options + * WordPress loads and caches for every page. + */ + public static function keepOutOfAutoload(): void + { + wp_set_option_autoload(self::$option, false); + } + + private static function read(string $constant, string $key): ?string + { + $value = self::fromCode($constant) ?? (self::stored()[$key] ?? null); + + return is_string($value) && trim($value) !== '' ? trim($value) : null; + } + + private static function fromCode(string $constant): ?string + { + $value = defined($constant) ? constant($constant) : getenv($constant); + + return is_string($value) && trim($value) !== '' ? $value : null; + } +} diff --git a/src/SettingsPage.php b/src/SettingsPage.php new file mode 100644 index 0000000..6ea6ae1 --- /dev/null +++ b/src/SettingsPage.php @@ -0,0 +1,142 @@ +page, + [$this, 'render'], + ); + } + + public function registerSetting(): void + { + register_setting($this->page, Settings::$option, [ + 'type' => 'object', + 'sanitize_callback' => [$this, 'sanitise'], + 'show_in_rest' => false, + 'default' => [], + ]); + } + + /** + * A blank secret keeps the one saved, because the field never shows it, and a short + * one is turned away with the saved one kept, since saving it would stop the site + * accepting anything from Altimiser. + * + * @return array + */ + public function sanitise(mixed $input): array + { + $input = is_array($input) ? $input : []; + $saved = Settings::stored()['secret'] ?? ''; + $secret = trim((string) ($input['secret'] ?? '')); + + if ($secret !== '' && ! Settings::secretIsLongEnough($secret)) { + add_settings_error(Settings::$option, 'altimiser_secret_too_short', sprintf( + /* translators: %d: the minimum number of characters */ + __('The secret needs at least %d characters, so the one already saved was kept.', 'altimiser'), + Settings::$minimumSecretLength, + )); + + $secret = ''; + } + + return array_filter([ + 'altimiser_url' => esc_url_raw(trim((string) ($input['altimiser_url'] ?? '')), ['https', 'http']), + 'secret' => $secret === '' ? $saved : $secret, + ]); + } + + public function render(): void + { + if (! current_user_can('manage_options')) { + return; + } + + $stored = Settings::stored(); + + echo '

    '.esc_html__('Altimiser', 'altimiser').'

    '; + printf('

    %s

    ', esc_html($this->status())); + printf( + '

    %s %s

    ', + esc_html__('Give Altimiser this receiver address when adding the site:', 'altimiser'), + esc_html(rest_url('altimiser/v1')), + ); + + echo '
    '; + settings_fields($this->page); + echo ''; + + $this->row('altimiser_url', __('Altimiser address', 'altimiser'), 'ALTIMISER_URL', sprintf( + '', + esc_attr(Settings::$option), + esc_attr($stored['altimiser_url'] ?? ''), + ), __('Where the review queue and its count come from.', 'altimiser')); + + $this->row('altimiser_secret', __('Secret', 'altimiser'), 'ALTIMISER_SECRET', sprintf( + '', + esc_attr(Settings::$option), + esc_attr(isset($stored['secret']) ? __('A secret is saved. Leave blank to keep it.', 'altimiser') : ''), + ), sprintf( + /* translators: %d: the minimum number of characters */ + __('The secret Altimiser shows when the site is added, at least %d characters.', 'altimiser'), + Settings::$minimumSecretLength, + )); + + echo ''; + submit_button(); + echo '
    '; + } + + private function row(string $id, string $label, string $constant, string $field, string $description): void + { + $control = Settings::definedOutsideSettings($constant) + ? '

    '.esc_html(sprintf( + /* translators: %s: the name of a PHP constant */ + __('Set by %s in wp-config.php or the server environment.', 'altimiser'), + $constant, + )).'

    ' + : $field.'

    '.esc_html($description).'

    '; + + printf( + '%s', + esc_attr($id), + esc_html($label), + $control, + ); + } + + private function status(): string + { + $secret = Settings::secret(); + + if ($secret === null) { + return __('No secret is set, so this site turns away every request from Altimiser.', 'altimiser'); + } + + if (! Settings::secretIsLongEnough($secret)) { + return sprintf( + /* translators: %d: the minimum number of characters */ + __('The secret is shorter than %d characters, so this site turns away every request from Altimiser until it is replaced.', 'altimiser'), + Settings::$minimumSecretLength, + ); + } + + return __('A secret is set, and this site accepts signed requests from Altimiser.', 'altimiser'); + } +} diff --git a/src/YoastApplier.php b/src/YoastApplier.php index 6be249c..b94f958 100644 --- a/src/YoastApplier.php +++ b/src/YoastApplier.php @@ -5,13 +5,10 @@ use WP_Post; use WP_Term; -class YoastApplier +class YoastApplier implements Applier { public function __construct(private Yoast $yoast, private ContentResolver $content) {} - /** - * @return array - */ public function checks(): array { $checks = [ @@ -35,9 +32,6 @@ public function supports(string $check): bool return in_array($check, $this->checks(), true); } - /** - * @return array - */ public function apply(ChangeRequest $change, bool $dryRun): array { if (trim($change->suggestedValue ?? '') === '') { diff --git a/tests/ChangeRequestHandlingTest.php b/tests/ChangeRequestHandlingTest.php index 3132ae5..2a3364b 100644 --- a/tests/ChangeRequestHandlingTest.php +++ b/tests/ChangeRequestHandlingTest.php @@ -127,6 +127,19 @@ public function test_skips_a_url_that_maps_to_nothing_editable(): void $this->assertSame('not_found', $result['reason']); } + public function test_skips_a_published_post_of_a_type_with_no_page_of_its_own(): void + { + $this->set_permalink_structure(''); + + $menuItem = self::factory()->post->create(['post_type' => 'nav_menu_item', 'post_status' => 'publish']); + + $result = $this->sendOne(['url' => home_url("/?p={$menuItem}")]); + + $this->assertSame('skipped', $result['status']); + $this->assertSame('not_found', $result['reason']); + $this->assertSame('', get_post_meta($menuItem, '_yoast_wpseo_metadesc', true)); + } + public function test_reports_a_write_that_threw_as_failed_and_carries_on(): void { $failOnce = static function (): void { diff --git a/tests/ConnectionFlowTest.php b/tests/ConnectionFlowTest.php new file mode 100644 index 0000000..4b7dd23 --- /dev/null +++ b/tests/ConnectionFlowTest.php @@ -0,0 +1,200 @@ +}> */ + private array $requests = []; + + private WP_User $editor; + + public function set_up(): void + { + parent::set_up(); + + $this->editor = self::factory()->user->create_and_get(['role' => 'editor', 'user_email' => 'editor@example.com']); + + wp_set_current_user($this->editor->ID); + } + + public function tear_down(): void + { + $_GET = $_REQUEST = []; + + parent::tear_down(); + } + + private function flow(string $siteUrl = ''): ConnectionFlow + { + return new ConnectionFlow(new ControlPanel('https://altimiser.example.com', $siteUrl ?: home_url(), 'shared-secret')); + } + + private function altimiserAnswers(int $status, string $body): void + { + add_filter('pre_http_request', function ($preempt, array $args, string $url) use ($status, $body) { + $this->requests[] = ['url' => $url, 'args' => $args]; + + return ['headers' => [], 'body' => $body, 'response' => ['code' => $status, 'message' => ''], 'cookies' => [], 'filename' => null]; + }, 10, 3); + } + + /** + * @return array + */ + private function queryOf(string $url): array + { + parse_str((string) parse_url($url, PHP_URL_QUERY), $query); + + return $query; + } + + private function startConnecting(): string + { + $_GET['_wpnonce'] = $_REQUEST['_wpnonce'] = wp_create_nonce('altimiser_connect'); + + return $this->flow()->start(); + } + + /** + * @param array $query + */ + private function comeBackWith(array $query): string + { + $_GET = $_REQUEST = $query; + + return $this->flow()->finish(); + } + + public function test_sends_the_editor_to_a_signed_connect_link_that_returns_to_wp_admin(): void + { + $url = $this->startConnecting(); + $query = $this->queryOf($url); + + $this->assertStringStartsWith('https://altimiser.example.com/connect?', $url); + $this->assertSame(admin_url('admin-post.php?action=altimiser_connected'), $query['redirect_uri']); + $this->assertSame('editor@example.com', $query['user']); + $this->assertSame(40, strlen($query['state'])); + $this->assertEqualsWithDelta(time() + 300, (int) $query['expires'], 2); + + [$signed, $signature] = explode('&signature=', $url); + + $this->assertSame(hash_hmac('sha256', $signed, 'shared-secret'), $signature); + } + + public function test_will_not_start_without_the_nonce_from_its_own_page(): void + { + $url = $this->flow()->start(); + + $this->assertSame(admin_url('admin.php?page=altimiser'), $url); + $this->assertSame('error', ConnectionFlow::takeNotice()['level']); + } + + public function test_will_not_start_for_someone_who_cannot_review(): void + { + wp_set_current_user(self::factory()->user->create(['role' => 'author'])); + + $this->assertSame(admin_url('admin.php?page=altimiser'), $this->startConnecting()); + } + + public function test_says_why_when_wp_admin_is_on_another_address_from_the_site(): void + { + $_GET['_wpnonce'] = $_REQUEST['_wpnonce'] = wp_create_nonce('altimiser_connect'); + + $url = $this->flow('https://www.client.example.com')->start(); + + $this->assertSame(admin_url('admin.php?page=altimiser'), $url); + $this->assertStringContainsString('same address as the site itself', ConnectionFlow::takeNotice()['message']); + } + + public function test_keeps_the_connection_altimiser_hands_back(): void + { + $state = $this->queryOf($this->startConnecting())['state']; + $this->altimiserAnswers(201, '{"connection":"01jcz6r4s8x2m0v3q9k7t5w1yd","token":"'.str_repeat('ab', 32).'","expires_at":"'.gmdate('c', time() + HOUR_IN_SECONDS).'","account":{"email":"sam@agency.example"}}'); + + $url = $this->comeBackWith(['action' => 'altimiser_connected', 'code' => 'the-code', 'state' => $state]); + + $this->assertSame(admin_url('admin.php?page=altimiser'), $url); + $this->assertSame(['level' => 'success', 'message' => 'Your Altimiser account is connected.'], ConnectionFlow::takeNotice()); + $this->assertSame(str_repeat('ab', 32), Connections::live($this->editor->ID)['token']); + $this->assertStringContainsString('"code":"the-code"', $this->requests[0]['args']['body']); + $this->assertStringContainsString('"redirect_uri":"'.admin_url('admin-post.php?action=altimiser_connected').'"', $this->requests[0]['args']['body']); + } + + public function test_keeps_the_token_encrypted_and_against_this_site_only(): void + { + global $wpdb; + + Connections::put($this->editor->ID, ['connection' => 'c', 'token' => str_repeat('ab', 32), 'expires_at' => time() + 60, 'account_email' => '']); + + $stored = get_user_meta($this->editor->ID, $wpdb->get_blog_prefix().Connections::$option, true); + + $this->assertIsArray($stored); + $this->assertStringNotContainsString(str_repeat('ab', 32), (string) wp_json_encode($stored)); + $this->assertSame('', get_user_meta($this->editor->ID, Connections::$option, true)); + } + + public function test_refuses_a_return_whose_state_does_not_match_and_asks_altimiser_nothing(): void + { + $this->startConnecting(); + $this->altimiserAnswers(201, '{}'); + + $this->comeBackWith(['code' => 'the-code', 'state' => str_repeat('x', 40)]); + + $this->assertStringContainsString('could not be checked', ConnectionFlow::takeNotice()['message']); + $this->assertSame([], $this->requests); + $this->assertNull(Connections::live($this->editor->ID)); + } + + public function test_uses_a_state_once(): void + { + $state = $this->queryOf($this->startConnecting())['state']; + $this->altimiserAnswers(422, '{"message":"That code has already been used."}'); + + $this->comeBackWith(['code' => 'the-code', 'state' => $state]); + $this->comeBackWith(['code' => 'the-code', 'state' => $state]); + + $this->assertCount(1, $this->requests); + } + + public function test_explains_a_declined_connection_without_blaming_the_editor(): void + { + $state = $this->queryOf($this->startConnecting())['state']; + + $this->comeBackWith(['error' => 'access_denied', 'state' => $state]); + + $this->assertStringContainsString('Either it was declined, or your account has not been given this site.', ConnectionFlow::takeNotice()['message']); + } + + public function test_passes_on_altimisers_reason_for_refusing_a_code(): void + { + $state = $this->queryOf($this->startConnecting())['state']; + $this->altimiserAnswers(422, '{"message":"That code has expired."}'); + + $this->comeBackWith(['code' => 'the-code', 'state' => $state]); + + $this->assertSame(['level' => 'error', 'message' => 'Your Altimiser account could not be connected: That code has expired.'], ConnectionFlow::takeNotice()); + } + + public function test_forgets_the_connection_on_disconnecting(): void + { + Connections::put($this->editor->ID, ['connection' => 'c', 'token' => 't', 'expires_at' => time() + 60, 'account_email' => '']); + $_REQUEST['_wpnonce'] = wp_create_nonce('altimiser_disconnect'); + + $this->flow()->disconnect(); + + $this->assertNull(Connections::live($this->editor->ID)); + $this->assertSame('success', ConnectionFlow::takeNotice()['level']); + } + + public function test_keeps_the_connection_when_disconnecting_without_the_nonce(): void + { + Connections::put($this->editor->ID, ['connection' => 'c', 'token' => 't', 'expires_at' => time() + 60, 'account_email' => '']); + + $this->flow()->disconnect(); + + $this->assertNotNull(Connections::live($this->editor->ID)); + } +} diff --git a/tests/ControlPanelTest.php b/tests/ControlPanelTest.php index 89cb259..8030088 100644 --- a/tests/ControlPanelTest.php +++ b/tests/ControlPanelTest.php @@ -32,17 +32,112 @@ private function answer(int $status, string $body): array return ['headers' => [], 'body' => $body, 'response' => ['code' => $status, 'message' => ''], 'cookies' => [], 'filename' => null]; } - public function test_signs_the_worked_example_in_the_protocol_document(): void + /** + * @return array{connection: string, token: string} + */ + private function connection(): array + { + return ['connection' => '01jcz6r4s8x2m0v3q9k7t5w1yd', 'token' => str_repeat('ab', 32)]; + } + + public function test_signs_the_worked_review_link_in_the_protocol_document(): void { $this->assertSame( - 'https://altimiser.example.com/review?embedded=1&expires=1769558400&site=https%3A%2F%2Fexample.com&user=editor%40example.com&signature=56424ced69568825952d43fb40de622e730610712898c7ecc35cd1b0d1dd2347', - $this->panel()->reviewUrl('editor@example.com', 1769558400), + 'https://altimiser.example.com/review?connection=01jcz6r4s8x2m0v3q9k7t5w1yd&embedded=1&expires=1769558400&site=https%3A%2F%2Fexample.com&user=editor%40example.com' + .'&signature=d747d7461ab0bd482ca2c63dbfdba805272879161a55b85294b1bfbc254d670f' + .'&connection_signature=05f7d157967aa7d78326438cc32082256bd12016a9f6eb3de2145b6e931d7cba', + $this->panel()->reviewUrl('editor@example.com', 1769558400, $this->connection()), + ); + } + + public function test_signs_the_worked_connect_link_in_the_protocol_document(): void + { + $this->assertSame( + 'https://altimiser.example.com/connect?expires=1769558400&redirect_uri=https%3A%2F%2Fexample.com%2Fcp%2Faltimiser%2Fconnect%2Fcallback&site=https%3A%2F%2Fexample.com&state=s7Kq2wX9pL4mN8vR3tY6uZ1aB5cD0eFg&user=editor%40example.com' + .'&signature=43e86c386c1c7fd4f94ffcd47fc0ea4ca48e14631ab991cf3f6d10bbd7cbc271', + $this->panel()->connectUrl('s7Kq2wX9pL4mN8vR3tY6uZ1aB5cD0eFg', 'https://example.com/cp/altimiser/connect/callback', 'editor@example.com', 1769558400), ); } public function test_leaves_out_a_user_with_no_email(): void { - $this->assertStringNotContainsString('user=', $this->panel()->reviewUrl('', 1769558400)); + $this->assertStringNotContainsString('user=', $this->panel()->reviewUrl('', 1769558400, $this->connection())); + } + + public function test_exchanges_the_code_with_a_request_signed_over_its_body(): void + { + $this->altimiserAnswers($this->answer(201, '{"connection":"01jcz6r4s8x2m0v3q9k7t5w1yd","token":"'.str_repeat('ab', 32).'","expires_at":"2026-11-12T10:00:00+00:00","account":{"name":"Sam Example","email":"sam@agency.example"}}')); + + $connection = $this->panel()->exchange('the-code', 'https://example.com/wp-admin/admin-post.php?action=altimiser_connected'); + + $this->assertSame([ + 'connection' => '01jcz6r4s8x2m0v3q9k7t5w1yd', + 'token' => str_repeat('ab', 32), + 'expires_at' => 1794477600, + 'account_email' => 'sam@agency.example', + ], $connection); + + ['url' => $url, 'args' => $args] = $this->requests[0]; + $timestamp = $args['headers']['X-Altimiser-Timestamp']; + + $this->assertSame('https://altimiser.example.com/api/connections', $url); + $this->assertSame('POST', $args['method']); + $this->assertSame('{"site":"https://example.com","code":"the-code","redirect_uri":"https://example.com/wp-admin/admin-post.php?action=altimiser_connected"}', $args['body']); + $this->assertSame('sha256='.hash_hmac('sha256', "{$timestamp}\n{$args['body']}", 'shared-secret'), $args['headers']['X-Altimiser-Signature']); + $this->assertSame(0, $args['redirection']); + } + + /** + * @dataProvider failedExchanges + * + * @param array|WP_Error $response + */ + public function test_says_why_a_code_could_not_be_exchanged(array|WP_Error $response, string $reason): void + { + $this->altimiserAnswers($response); + + $connection = $this->panel()->exchange('the-code', 'https://example.com/wp-admin/admin-post.php'); + + $this->assertInstanceOf(WP_Error::class, $connection); + $this->assertSame($reason, $connection->get_error_message()); + } + + /** + * @return array|WP_Error, string}> + */ + public static function failedExchanges(): array + { + $answer = static fn (int $status, string $body): array => ['headers' => [], 'body' => $body, 'response' => ['code' => $status, 'message' => ''], 'cookies' => [], 'filename' => null]; + + return [ + 'unreachable' => [new WP_Error('http_request_failed', 'Connection timed out'), 'Altimiser could not be reached.'], + 'a used code' => [$answer(422, '{"message":"That code has already been used."}'), 'That code has already been used.'], + 'a server error' => [$answer(500, 'Server error'), 'Altimiser refused the connection.'], + 'no token' => [$answer(201, '{"connection":"01jcz6r4s8x2m0v3q9k7t5w1yd","expires_at":"2026-11-12T10:00:00+00:00"}'), 'Altimiser sent an answer that could not be read.'], + 'no expiry' => [$answer(201, '{"connection":"01jcz6r4s8x2m0v3q9k7t5w1yd","token":"abc"}'), 'Altimiser sent an answer that could not be read.'], + ]; + } + + /** + * @dataProvider origins + */ + public function test_knows_whether_an_address_is_on_the_sites_own_origin(string $address, bool $same): void + { + $this->assertSame($same, $this->panel()->isOnSiteOrigin($address)); + } + + /** + * @return array + */ + public static function origins(): array + { + return [ + 'wp-admin on the same host' => ['https://example.com/wp-admin/admin-post.php?action=altimiser_connected', true], + 'the default port written out' => ['https://EXAMPLE.com:443/wp-admin/', true], + 'another host' => ['https://admin.example.com/wp-admin/', false], + 'plain http' => ['http://example.com/wp-admin/', false], + 'another port' => ['https://example.com:8443/wp-admin/', false], + ]; } public function test_expires_a_link_after_the_configured_minutes(): void @@ -64,7 +159,7 @@ public function test_reads_the_count_with_a_request_signed_over_the_empty_body() $this->assertSame('https://altimiser.example.com/api/summary?site=https%3A%2F%2Fexample.com', $url); $this->assertSame('sha256='.hash_hmac('sha256', "{$timestamp}\n", 'shared-secret'), $args['headers']['X-Altimiser-Signature']); $this->assertEqualsWithDelta(time(), (int) $timestamp, 2); - $this->assertSame(5, $args['timeout']); + $this->assertSame(2, $args['timeout']); $this->assertSame(0, $args['redirection']); } @@ -124,7 +219,7 @@ public function test_remembers_altimiser_being_unreachable_so_only_one_page_wait */ public function test_needs_altimisers_address_before_it_can_link_to_it(): void { - define('ALTIMISER_SECRET', 'shared-secret'); + define('ALTIMISER_SECRET', 'a-shared-secret-of-at-least-32-characters'); $this->assertNull(ControlPanel::configured()); } @@ -149,10 +244,10 @@ public function test_needs_the_secret_before_it_can_sign_anything(): void public function test_names_the_site_by_its_own_address_with_no_trailing_slash(): void { define('ALTIMISER_URL', 'https://altimiser.example.com/'); - define('ALTIMISER_SECRET', 'shared-secret'); + define('ALTIMISER_SECRET', 'a-shared-secret-of-at-least-32-characters'); add_filter('home_url', static fn (): string => 'https://client.example.com/'); - $url = ControlPanel::configured()->reviewUrl('', 1769558400); + $url = ControlPanel::configured()->reviewUrl('', 1769558400, ['connection' => 'c', 'token' => 't']); $this->assertStringStartsWith('https://altimiser.example.com/review?', $url); $this->assertStringContainsString('site=https%3A%2F%2Fclient.example.com&', $url); @@ -166,13 +261,13 @@ public function test_names_the_site_by_its_own_address_with_no_trailing_slash(): public function test_takes_the_sites_address_from_a_constant_where_the_two_disagree(): void { define('ALTIMISER_URL', 'https://altimiser.example.com'); - define('ALTIMISER_SECRET', 'shared-secret'); + define('ALTIMISER_SECRET', 'a-shared-secret-of-at-least-32-characters'); define('ALTIMISER_SITE_URL', 'https://www.client.example.com/'); define('ALTIMISER_LINK_MINUTES', 10); $panel = ControlPanel::configured(); - $this->assertStringContainsString('site=https%3A%2F%2Fwww.client.example.com&', $panel->reviewUrl('', 1769558400)); + $this->assertStringContainsString('site=https%3A%2F%2Fwww.client.example.com&', $panel->reviewUrl('', 1769558400, ['connection' => 'c', 'token' => 't'])); $this->assertEqualsWithDelta(time() + 600, $panel->linkExpiry(), 2); } } diff --git a/tests/HealthTest.php b/tests/HealthTest.php index e5d2213..d792f98 100644 --- a/tests/HealthTest.php +++ b/tests/HealthTest.php @@ -149,6 +149,47 @@ public function test_sends_no_header_without_a_value(): void $this->assertNotContains(false, $this->dispatch($this->signedRequest())->get_headers()); } + public function test_reports_settings_that_stop_fixes_from_counting(): void + { + update_option('blog_public', '0'); + $this->set_permalink_structure(''); + + $setup = $this->dispatch($this->signedRequest())->get_data()['setup']; + + update_option('blog_public', '1'); + + $this->assertSame(['search_engines_discouraged' => true, 'plain_permalinks' => true], $setup); + } + + public function test_reports_a_site_set_up_to_be_found(): void + { + $this->set_permalink_structure('/%postname%/'); + + $setup = $this->dispatch($this->signedRequest())->get_data()['setup']; + + $this->assertSame(['search_engines_discouraged' => false, 'plain_permalinks' => false], $setup); + } + + public function test_still_answers_when_yoast_throws_and_leaves_out_only_its_checks(): void + { + $failing = static function (): never { + throw new RuntimeException('Yoast could not read its options.'); + }; + + add_filter('pre_option_wpseo_social', $failing); + WPSEO_Options::clear_cache(); + + $logged = ini_set('error_log', '/dev/null'); + $response = $this->dispatch($this->signedRequest()); + + ini_set('error_log', (string) $logged); + remove_filter('pre_option_wpseo_social', $failing); + WPSEO_Options::clear_cache(); + + $this->assertSame(200, $response->get_status()); + $this->assertNotContains('title.too_long', $response->get_data()['checks']); + } + public function test_says_nothing_about_the_site_to_an_unsigned_request(): void { $response = $this->dispatch($this->request()); diff --git a/tests/PageCacheTest.php b/tests/PageCacheTest.php index 1a8fd6f..0413286 100644 --- a/tests/PageCacheTest.php +++ b/tests/PageCacheTest.php @@ -24,11 +24,11 @@ public function set_up(): void private function purges(callable $request): int { - $before = did_action('litespeed_purge_all'); + $before = did_action('altimiser_purge_urls'); $request(); - return did_action('litespeed_purge_all') - $before; + return did_action('altimiser_purge_urls') - $before; } private function descriptionYoastPrints(): ?string @@ -49,11 +49,11 @@ public function test_purges_once_yoast_has_rebuilt_what_the_page_prints(): void $printedAtPurge = $this->descriptionYoastPrints(); }; - add_action('litespeed_purge_all', $recordWhatIsPrinted); + add_action('litespeed_purge_url', $recordWhatIsPrinted); $this->sendOne(); - remove_action('litespeed_purge_all', $recordWhatIsPrinted); + remove_action('litespeed_purge_url', $recordWhatIsPrinted); $this->assertSame('How our studio works, and who we build for.', $printedAtPurge); } @@ -104,32 +104,107 @@ public function test_purges_when_the_fix_was_already_in_place_because_the_reques * * @preserveGlobalState disabled */ - public function test_reaches_each_plugin_that_is_active(): void + public function test_reaches_each_plugin_that_is_active_by_address(): void { require __DIR__.'/fixtures/page-cache-plugins.php'; + $page = home_url('/about/'); $beforeBreeze = did_action('breeze_clear_all_cache'); + $beforeLiteSpeed = did_action('litespeed_purge_url'); - (new AltDesign\Altimiser\PageCache())->purge(); + (new AltDesign\Altimiser\PageCache())->purge([$page, $page]); - $this->assertSame(['rocket', 'w3tc', 'super-cache'], $GLOBALS['altimiser_purged']); + $this->assertSame([['rocket', [$page]], ['w3tc', $page], ['super-cache', $page]], $GLOBALS['altimiser_purged']); + $this->assertSame($beforeLiteSpeed + 1, did_action('litespeed_purge_url')); $this->assertSame($beforeBreeze + 1, did_action('breeze_clear_all_cache')); } + /** + * @runInSeparateProcess + * + * @preserveGlobalState disabled + */ + public function test_clears_wp_super_cache_whole_for_the_home_page_it_will_not_delete_by_address(): void + { + require __DIR__.'/fixtures/page-cache-plugins.php'; + + (new AltDesign\Altimiser\PageCache())->purge([home_url('/')]); + + $this->assertContains('super-cache', $GLOBALS['altimiser_purged']); + } + + /** + * @runInSeparateProcess + * + * @preserveGlobalState disabled + */ + public function test_clears_everything_on_request(): void + { + require __DIR__.'/fixtures/page-cache-plugins.php'; + + $beforeLiteSpeed = did_action('litespeed_purge_all'); + + (new AltDesign\Altimiser\PageCache())->purgeEverything(); + + $this->assertSame(['rocket', 'w3tc', 'super-cache'], $GLOBALS['altimiser_purged']); + $this->assertSame($beforeLiteSpeed + 1, did_action('litespeed_purge_all')); + } + + public function test_purges_only_the_page_the_change_was_made_for(): void + { + $purged = []; + + $record = static function (array $urls, bool $everything) use (&$purged): void { + $purged[] = [$urls, $everything]; + }; + + add_action('altimiser_purge_urls', $record, 10, 2); + + $this->sendOne(); + + remove_action('altimiser_purge_urls', $record); + + $this->assertSame([[[home_url('/about/')], false]], $purged); + } + public function test_reports_success_even_when_the_purge_fails_because_the_changes_have_landed(): void { $failing = static function (): void { throw new RuntimeException('The cache directory is read only.'); }; - add_action('litespeed_purge_all', $failing); + add_action('litespeed_purge_url', $failing); $logged = ini_set('error_log', '/dev/null'); $result = $this->sendOne(); ini_set('error_log', (string) $logged); - remove_action('litespeed_purge_all', $failing); + remove_action('litespeed_purge_url', $failing); $this->assertSame('applied', $result['status']); } + + public function test_still_reaches_the_other_caches_when_one_of_them_throws(): void + { + $failing = static function (): void { + throw new RuntimeException('The cache directory is read only.'); + }; + + add_action('litespeed_purge_url', $failing); + add_action('litespeed_purge_all', $failing); + + $logged = ini_set('error_log', '/dev/null'); + $beforeBreeze = did_action('breeze_clear_all_cache'); + $beforeOwn = did_action('altimiser_purge_urls'); + + (new AltDesign\Altimiser\PageCache())->purge([home_url('/about/')]); + (new AltDesign\Altimiser\PageCache())->purgeEverything(); + + ini_set('error_log', (string) $logged); + remove_action('litespeed_purge_url', $failing); + remove_action('litespeed_purge_all', $failing); + + $this->assertSame($beforeBreeze + 2, did_action('breeze_clear_all_cache')); + $this->assertSame($beforeOwn + 2, did_action('altimiser_purge_urls')); + } } diff --git a/tests/ReceiverTestCase.php b/tests/ReceiverTestCase.php index b04644a..6798a01 100644 --- a/tests/ReceiverTestCase.php +++ b/tests/ReceiverTestCase.php @@ -9,7 +9,7 @@ */ abstract class ReceiverTestCase extends WP_UnitTestCase { - protected static string $secret = 'shared-secret'; + protected static string $secret = 'a-shared-secret-of-at-least-32-characters'; protected static function configureSecret(): void { diff --git a/tests/ReviewQueuePageTest.php b/tests/ReviewQueuePageTest.php index 19c0b07..fa74b90 100644 --- a/tests/ReviewQueuePageTest.php +++ b/tests/ReviewQueuePageTest.php @@ -1,5 +1,7 @@ user->create_and_get(['role' => $role, 'user_email' => "{$role}@example.com"]); wp_set_current_user($user->ID); + if ($connected) { + $this->connect($user, time() + HOUR_IN_SECONDS); + } + return $user; } + private function connect(WP_User $user, int $expiresAt): void + { + Connections::put($user->ID, [ + 'connection' => '01jcz6r4s8x2m0v3q9k7t5w1yd', + 'token' => str_repeat('ab', 32), + 'expires_at' => $expiresAt, + 'account_email' => 'sam@agency.example', + ]); + } + private function altimiserCounts(int|WP_Error $count): void { add_filter('pre_http_request', function () use ($count) { @@ -186,14 +202,15 @@ public function test_frames_a_link_signed_for_whoever_is_signed_in(): void $html = html_entity_decode($this->renderedPage(), ENT_QUOTES); - preg_match('/