From 4f05dcd9123f4b6dd0d65e38160689133647b73d Mon Sep 17 00:00:00 2001 From: Barry Kooij Date: Tue, 3 Nov 2026 21:48:54 +0100 Subject: [PATCH 1/5] Added: the plugin connects through Scanfully's OAuth server with a choice of what Scanfully may do, moves an existing connection there by itself, and takes requests Scanfully signs for the site --- readme.txt | 6 +- src/Connect/Buttons.php | 22 +++ src/Connect/Controller.php | 168 ++++++++++++++---- src/Connect/OAuth.php | 197 +++++++++++++++++++++ src/Connect/Page.php | 25 +++ src/Cron/Controller.php | 35 +++- src/Main.php | 22 +++ src/Options/Controller.php | 3 + src/Sync/Controller.php | 18 +- src/Sync/SignedRequest.php | 240 ++++++++++++++++++++++++++ tests/Unit/API/RequestTlsTest.php | 3 + tests/Unit/Connect/OAuthTest.php | 156 +++++++++++++++++ tests/Unit/Cron/TokenRefreshTest.php | 65 ++++++- tests/Unit/Sync/SignedRequestTest.php | 209 ++++++++++++++++++++++ 14 files changed, 1129 insertions(+), 40 deletions(-) create mode 100644 src/Connect/OAuth.php create mode 100644 src/Sync/SignedRequest.php create mode 100644 tests/Unit/Connect/OAuthTest.php create mode 100644 tests/Unit/Sync/SignedRequestTest.php diff --git a/readme.txt b/readme.txt index e40c5ac..a980f40 100644 --- a/readme.txt +++ b/readme.txt @@ -109,7 +109,7 @@ Yes. This plugin connects your site to Scanfully's external monitoring service. = Where do I connect my site? = -Open Settings > Scanfully in WordPress and click "Connect your Scanfully account". Authorize the connection in Scanfully. You will then return to WordPress with your site connected. +Open Settings > Scanfully in WordPress and click "Connect your Scanfully account". In Scanfully, pick the site, choose what Scanfully may do on it, and approve the connection. You will then return to WordPress with your site connected. To change what Scanfully may do later, click "Change what Scanfully may do" and approve again. = Can I monitor several WordPress sites? = @@ -129,7 +129,9 @@ Use the [Scanfully documentation](https://docs.scanfully.com/) or email [support == External services == -This plugin connects to the Scanfully service at [scanfully.com](https://scanfully.com/) and its API at `api.scanfully.com`. It does not send monitoring data until you connect your site. Starting the connection passes your site URL and return URL to Scanfully. +This plugin connects to the Scanfully service at [scanfully.com](https://scanfully.com/) and its API at `api.scanfully.com`. It does not send monitoring data until you connect your site. Starting the connection passes your site URL and return URL to Scanfully's authorization server, where you choose what Scanfully may do on the site; reading site data is always included. The plugin then holds tokens that work for this site only. + +When Scanfully asks the plugin to sync, it signs the request, and the plugin checks the signature against Scanfully's public keys, which it fetches from `api.scanfully.com` and keeps for a day. This uses PHP's OpenSSL extension. Once connected, the plugin sends the following data to provide monitoring, diagnostics, and WordPress activity context: diff --git a/src/Connect/Buttons.php b/src/Connect/Buttons.php index 58e7e28..7cffa58 100644 --- a/src/Connect/Buttons.php +++ b/src/Connect/Buttons.php @@ -37,6 +37,28 @@ public static function connect(): void { 'scanfully', + 'scanfully-reconnect' => 1, + 'scanfully-reconnect-nonce' => wp_create_nonce( 'scanfully-reconnect' ), + ], + admin_url( 'options-general.php' ) + ); + ?> + + + + rawurlencode( Page::get_page_url() ), - 'site' => rawurlencode( home_url() ), - 'state' => self::generate_state(), - 'code_challenge' => self::code_challenge( self::generate_code_verifier() ), - 'code_challenge_method' => 'S256', - ], - Main::get_connect_url() - ); - - wp_redirect( $connect_url ); + // the admin approves on Scanfully's OAuth server what Scanfully may do + // on this site, and comes back with a code. + wp_redirect( OAuth::authorize_url() ); // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect -- Scanfully's own OAuth server, on another host. exit; } @@ -156,22 +149,103 @@ private static function handle_reconnect(): void { self::revoke_tokens(); OptionsController::clear(); - // build the connect URL and redirect directly into the connect flow. - $connect_url = add_query_arg( - [ - 'redirect_uri' => rawurlencode( Page::get_page_url() ), - 'site' => rawurlencode( home_url() ), - 'state' => self::generate_state(), - 'code_challenge' => self::code_challenge( self::generate_code_verifier() ), - 'code_challenge_method' => 'S256', - ], - Main::get_connect_url() + // straight into a new connection, where the admin can choose again + // what Scanfully may do. + wp_redirect( OAuth::authorize_url() ); // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect -- Scanfully's own OAuth server, on another host. + exit; + } + + /** + * Handle the OAuth server's answer: an error (the admin cancelled), or a + * code to exchange for the site's tokens. + * + * @return void + */ + private static function handle_oauth_answer(): void { + if ( ! self::user_has_access() ) { + wp_die( 'You do not have permission to do this.' ); + } + + // the state is single use: deleted before comparing, and an empty + // value never matches. It also ends a cancelled request. + $expected_state = self::get_state(); + $given_state = isset( $_GET['state'] ) ? sanitize_text_field( wp_unslash( $_GET['state'] ) ) : ''; + self::delete_state(); + $verifier = self::get_code_verifier(); + self::delete_code_verifier(); + + if ( isset( $_GET['error'] ) ) { + $error = sanitize_key( wp_unslash( $_GET['error'] ) ); + self::print_notice( 'access_denied' === $error ? __( 'The connection was cancelled.', 'scanfully' ) : __( 'An unknown error occurred.', 'scanfully' ), 'error' ); + return; + } + if ( '' === $expected_state || '' === $given_state || ! hash_equals( $expected_state, $given_state ) ) { + wp_die( 'Invalid Scanfully connect state' ); + } + // the answer names who issued it (RFC 9207): Scanfully's own server only. + if ( isset( $_GET['iss'] ) && untrailingslashit( esc_url_raw( wp_unslash( $_GET['iss'] ) ) ) !== untrailingslashit( Main::get_oauth_url() ) ) { + wp_die( 'Invalid Scanfully connect issuer' ); + } + if ( ! isset( $_GET['code'] ) || '' === $verifier ) { + wp_die( 'Invalid Scanfully connect parameters' ); + } + + $tokens = OAuth::exchange_code( sanitize_text_field( wp_unslash( $_GET['code'] ) ), $verifier ); + // the site ID ends up in API URL paths, so only allow plain ID characters. + if ( empty( $tokens ) || 1 !== preg_match( '/^[A-Za-z0-9_-]{1,64}\z/', (string) $tokens['site_id'] ) ) { + wp_die( 'Could not complete Scanfully connection: invalid response from the Scanfully API. Please try again or contact support.' ); + } + + $now = gmdate( self::DATE_FORMAT ); + OptionsController::set_options( + new Options( true, $tokens['site_id'], $tokens['access_token'], $tokens['refresh_token'], gmdate( self::DATE_FORMAT, strtotime( $tokens['expires'] ) ), '', $now ) ); + self::store_grant( $tokens['scopes'] ); + self::schedule_first_syncs(); - wp_redirect( $connect_url ); + wp_redirect( add_query_arg( [ 'scanfully-connect-done' => '1' ], Page::get_page_url() ) ); exit; } + /** + * Remember what Scanfully may do on the site, and that the connection + * lives on the OAuth server. + * + * @param string[] $scopes The granted scopes. + * + * @return void + */ + public static function store_grant( array $scopes ): void { + OptionsController::set_option( 'scopes', implode( ' ', $scopes ) ); + OptionsController::set_option( 'flow', 'oauth' ); + } + + /** + * The scopes of the site's connection; for a connection from before this + * version, what it always allowed. + * + * @return string[] + */ + public static function granted_scopes(): array { + $scopes = array_values( array_filter( explode( ' ', OptionsController::get_option( 'scopes' ) ) ) ); + + return [] === $scopes ? [ OAuth::SCOPE_READ ] : $scopes; + } + + /** + * Run the first syncs at once, so the dashboard does not wait for the next job. + * + * @return void + */ + private static function schedule_first_syncs(): void { + as_schedule_single_action( time(), \Scanfully\Cron\Controller::ACTION_SYNC_DIRECTORIES, [], 'scanfully' ); + as_schedule_single_action( time(), \Scanfully\Cron\Controller::ACTION_SYNC_SITE_HEALTH, [], 'scanfully' ); + if ( \Scanfully\WooCheckout\Controller::is_woocommerce_active() ) { + // fetches the probe secret, which is cleared on disconnect. + as_schedule_single_action( time(), \Scanfully\Cron\Controller::ACTION_SYNC_WOOCHECKOUT_CONFIG, [], 'scanfully' ); + } + } + /** * Catch the request that is returned from the connect process on success. * @@ -371,12 +445,48 @@ private static function exchange_authorization_code( string $code, string $site, /** * Use the refresh token to get a new access and refresh token * + * @param string $refresh_token The refresh token. + * @param string $site The Scanfully site ID. + * @param bool $legacy_fallback Whether an API without the plugin's + * client gets the refresh on the legacy route. + * + * @return array + */ + public static function refresh_access_token( string $refresh_token, string $site, bool $legacy_fallback = true ): array { + if ( false === get_transient( self::OAUTH_UNAVAILABLE_TRANSIENT ) ) { + $tokens = OAuth::refresh( $refresh_token, $site ); + if ( null !== $tokens ) { + if ( ! empty( $tokens ) ) { + self::store_grant( $tokens['scopes'] ); + } + return $tokens; + } + // an API that does not connect sites on its OAuth server yet: the + // OAuth server again tomorrow. + set_transient( self::OAUTH_UNAVAILABLE_TRANSIENT, 1, DAY_IN_SECONDS ); + } + if ( ! $legacy_fallback ) { + return []; + } + + return self::refresh_on_legacy_route( $refresh_token, $site ); + } + + /** + * Transient set while the API's OAuth server does not take the plugin's client. + */ + public const OAUTH_UNAVAILABLE_TRANSIENT = 'scanfully_oauth_unavailable'; + + /** + * Refresh the tokens on the legacy connect route, for an API without the + * plugin's client on its OAuth server. + * * @param string $refresh_token The refresh token. * @param string $site The Scanfully site ID. * * @return array */ - public static function refresh_access_token( string $refresh_token, string $site ): array { + private static function refresh_on_legacy_route( string $refresh_token, string $site ): array { // request arguments for the requests. $request_args = [ diff --git a/src/Connect/OAuth.php b/src/Connect/OAuth.php new file mode 100644 index 0000000..3b4b607 --- /dev/null +++ b/src/Connect/OAuth.php @@ -0,0 +1,197 @@ + self::CLIENT_ID, + 'redirect_uri' => self::redirect_uri(), + 'response_type' => 'code', + 'state' => Controller::generate_state(), + 'code_challenge' => Controller::code_challenge( Controller::generate_code_verifier() ), + 'code_challenge_method' => 'S256', + 'resource' => Main::get_site_resource(), + 'scope' => implode( ' ', self::SCOPES ), + // home_url() is the public-facing address (Bedrock keeps WordPress in a subdirectory). + 'site' => home_url(), + ]; + + return Main::get_oauth_url() . '/oauth/authorize?' . http_build_query( $params, '', '&', PHP_QUERY_RFC3986 ); + } + + /** + * Exchange an authorization code for the site's tokens. + * + * @param string $code The code from the OAuth server's answer. + * @param string $verifier The PKCE verifier of the request. + * + * @return array The tokens (see normalize()), or an empty array on failure. + */ + public static function exchange_code( string $code, string $verifier ): array { + $answer = self::post_token( + [ + 'grant_type' => 'authorization_code', + 'code' => $code, + 'code_verifier' => $verifier, + 'redirect_uri' => self::redirect_uri(), + 'client_id' => self::CLIENT_ID, + ], + 60 + ); + + return null === $answer ? [] : self::normalize( $answer ); + } + + /** + * Refresh the site's tokens at the token endpoint. A refresh token of the + * legacy routes (from before this version) works there too. + * + * @param string $refresh_token The refresh token. + * @param string $site_id The Scanfully site id, which keys the API's limit on failed attempts. + * + * @return array|null The tokens (see normalize()), an empty array on + * failure, or null when the API does not know the + * plugin's client (an older API): refresh on the + * legacy route then. + */ + public static function refresh( string $refresh_token, string $site_id ): ?array { + $unknown_client = false; + $answer = self::post_token( + [ + 'grant_type' => 'refresh_token', + 'refresh_token' => $refresh_token, + 'client_id' => self::CLIENT_ID, + 'site_id' => $site_id, + ], + 15, + $unknown_client + ); + if ( $unknown_client ) { + return null; + } + + return null === $answer ? [] : self::normalize( $answer ); + } + + /** + * The tokens of a token answer, in the shape the plugin stores: the + * access and refresh token, when the access token expires (a date), the + * site id and the granted scopes. Missing parts make it an empty array. + * + * @param array $answer The decoded token answer. + * + * @return array + */ + public static function normalize( array $answer ): array { + foreach ( [ 'access_token', 'refresh_token' ] as $key ) { + if ( ! isset( $answer[ $key ] ) || ! is_string( $answer[ $key ] ) || '' === $answer[ $key ] ) { + return []; + } + } + if ( ! isset( $answer['expires_in'] ) || ! is_numeric( $answer['expires_in'] ) || (int) $answer['expires_in'] <= 0 ) { + return []; + } + $scopes = isset( $answer['scope'] ) && is_string( $answer['scope'] ) ? array_values( array_filter( explode( ' ', $answer['scope'] ) ) ) : []; + + return [ + 'access_token' => $answer['access_token'], + 'refresh_token' => $answer['refresh_token'], + 'expires' => gmdate( 'c', time() + (int) $answer['expires_in'] ), + 'site_id' => isset( $answer['site_id'] ) && is_string( $answer['site_id'] ) ? $answer['site_id'] : '', + 'scopes' => $scopes, + ]; + } + + /** + * Post a form to the token endpoint. + * + * @param array $form The form. + * @param int $timeout The timeout in seconds. + * @param bool $unknown_client Set when the API does not know the plugin's client. + * + * @return array|null The decoded answer of a 200, or null. + */ + private static function post_token( array $form, int $timeout, bool &$unknown_client = false ): ?array { + $resp = wp_remote_post( + Main::get_oauth_url() . '/oauth/token', + [ + 'headers' => [ 'Content-Type' => 'application/x-www-form-urlencoded' ], + 'body' => $form, + 'timeout' => $timeout, + 'blocking' => true, + 'httpversion' => '1.0', + 'sslverify' => Main::get_sslverify(), + ] + ); + if ( is_wp_error( $resp ) ) { + return null; + } + + $status = (int) wp_remote_retrieve_response_code( $resp ); + $body = json_decode( (string) wp_remote_retrieve_body( $resp ), true ); + if ( 200 !== $status ) { + // an API from before the plugin's client: no OAuth server, or one + // that does not connect sites. + $unknown_client = 404 === $status || ( is_array( $body ) && isset( $body['error'] ) && 'invalid_client' === $body['error'] ); + return null; + } + + return is_array( $body ) ? $body : null; + } +} diff --git a/src/Connect/Page.php b/src/Connect/Page.php index 301d79b..7668238 100644 --- a/src/Connect/Page.php +++ b/src/Connect/Page.php @@ -144,12 +144,21 @@ public static function render_page(): void {
+
  • +
    +
    + + + +
    +
  • is_connected ) : ?>

    +

    @@ -194,4 +203,20 @@ private static function format_stored_date( string $value ): string { return $date->format( get_option( 'date_format' ) . ' @ ' . get_option( 'time_format' ) ); } + + /** + * What a scope lets Scanfully do, as the settings page says it. + * + * @param string $scope The scope. + * + * @return string + */ + public static function scope_label( string $scope ): string { + switch ( $scope ) { + case OAuth::SCOPE_READ: + return __( 'Read site data: health, plugins and themes, and activity', 'scanfully' ); + default: + return $scope; + } + } } diff --git a/src/Cron/Controller.php b/src/Cron/Controller.php index 78a3574..5b5ee0b 100644 --- a/src/Cron/Controller.php +++ b/src/Cron/Controller.php @@ -420,6 +420,30 @@ private static function refresh_access_token_if_needed(): void { } } + /** + * Whether the access token expires within two days, or the connection is + * still a legacy one. An expiry date that cannot be parsed also needs a + * refresh, which stores a fresh one. + * + * @param Options\Options $options The current options. + * + * @return bool + */ + private static function token_needs_refresh( Options\Options $options ): bool { + return self::moves_to_oauth() || self::token_expires_soon( $options ); + } + + /** + * Whether a connection from before 1.11 moves to the OAuth server now: + * one refresh there, whatever its expiry. After a failure there, the next + * try is a day later. + * + * @return bool + */ + private static function moves_to_oauth(): bool { + return 'oauth' !== Options\Controller::get_option( 'flow' ) && false === get_transient( Connect\Controller::OAUTH_UNAVAILABLE_TRANSIENT ); + } + /** * Whether the access token expires within two days. An expiry date that * cannot be parsed also needs a refresh, which stores a fresh one. @@ -428,7 +452,7 @@ private static function refresh_access_token_if_needed(): void { * * @return bool */ - private static function token_needs_refresh( Options\Options $options ): bool { + private static function token_expires_soon( Options\Options $options ): bool { try { $refresh_after = new \DateTime( $options->expires, new \DateTimeZone( 'UTC' ) ); } catch ( \Exception $e ) { @@ -447,8 +471,15 @@ private static function token_needs_refresh( Options\Options $options ): bool { * @return void */ private static function refresh_access_token( Options\Options $options ): void { - $tokens = Connect\Controller::refresh_access_token( $options->refresh_token, $options->site_id ); + // a move to the OAuth server of tokens that still work: a failure is + // no broken connection, the move is tried again tomorrow. + $moving = ! self::token_expires_soon( $options ); + $tokens = Connect\Controller::refresh_access_token( $options->refresh_token, $options->site_id, ! $moving ); + if ( $moving && ! self::is_valid_token_response( $tokens ) ) { + set_transient( Connect\Controller::OAUTH_UNAVAILABLE_TRANSIENT, 1, DAY_IN_SECONDS ); + return; + } if ( ! self::is_valid_token_response( $tokens ) ) { self::record_refresh_failure( 'Token refresh request failed. The Scanfully API may be unreachable or the refresh token may be invalid.' ); return; diff --git a/src/Main.php b/src/Main.php index 2e095c1..2d8e739 100644 --- a/src/Main.php +++ b/src/Main.php @@ -88,6 +88,28 @@ public static function get_connect_url(): string { return apply_filters( 'scanfully_connect_url', self::CONNECT_URL ); } + /** + * Get the address of Scanfully's OAuth server: the origin of the API URL, + * such as https://api.scanfully.com. + * + * @return string + */ + public static function get_oauth_url(): string { + $parts = wp_parse_url( self::get_api_url() ); + $origin = ( $parts['scheme'] ?? 'https' ) . '://' . ( $parts['host'] ?? '' ) . ( isset( $parts['port'] ) ? ':' . $parts['port'] : '' ); + + return apply_filters( 'scanfully_oauth_url', $origin ); + } + + /** + * Get the resource the plugin's tokens are for on the OAuth server. + * + * @return string + */ + public static function get_site_resource(): string { + return self::get_oauth_url() . '/v1/sites'; + } + /** * Set up the plugin. * diff --git a/src/Options/Controller.php b/src/Options/Controller.php index d6f2752..2376e03 100644 --- a/src/Options/Controller.php +++ b/src/Options/Controller.php @@ -144,6 +144,9 @@ public static function clear() { delete_option( self::$db_prefix . 'last_used' ); delete_option( self::$db_prefix . 'date_connected' ); delete_option( self::$db_prefix . 'last_request_error' ); + delete_option( self::$db_prefix . 'scopes' ); + delete_option( self::$db_prefix . 'flow' ); + delete_transient( 'scanfully_oauth_unavailable' ); // Email deliverability sub-feature: per-site secret + cached state. delete_option( self::$db_prefix . 'email_deliverability_enabled' ); diff --git a/src/Sync/Controller.php b/src/Sync/Controller.php index d175dac..9c76ad3 100644 --- a/src/Sync/Controller.php +++ b/src/Sync/Controller.php @@ -75,9 +75,11 @@ public static function register_routes(): void { } /** - * Only the Scanfully API may trigger a sync: the request must carry the - * site's current access token. Unauthenticated requests are rejected - * before they can consume the rate-limit budget. + * Only the Scanfully API may trigger a sync: the request carries a token + * Scanfully signed for this site (SignedRequest), or, from an API that + * still keeps the plugin's tokens, the site's current access token. + * Unauthenticated requests are rejected before they can consume the + * rate-limit budget. * * @param \WP_REST_Request $request The request. * @@ -85,13 +87,19 @@ public static function register_routes(): void { */ public static function check_permission( \WP_REST_Request $request ): bool { $options = Options\Controller::get_options(); - if ( ! $options->is_connected || '' === $options->access_token ) { + if ( ! $options->is_connected ) { return false; } $token = self::get_request_token( $request ); + if ( '' === $token ) { + return false; + } + if ( SignedRequest::looks_signed( $token ) ) { + return SignedRequest::verify( $token, $options->site_id, 'sync', \Scanfully\Connect\OAuth::SCOPE_READ ); + } - return '' !== $token && hash_equals( $options->access_token, $token ); + return '' !== $options->access_token && hash_equals( $options->access_token, $token ); } /** diff --git a/src/Sync/SignedRequest.php b/src/Sync/SignedRequest.php new file mode 100644 index 0000000..aed1b6c --- /dev/null +++ b/src/Sync/SignedRequest.php @@ -0,0 +1,240 @@ + $now + self::LEEWAY ) + || ! isset( $claims['jti'] ) || ! is_string( $claims['jti'] ) || '' === $claims['jti'] ) { + return false; + } + + // each request once: a copy of it, seen in a log, does nothing. + $seen = 'scanfully_jti_' . md5( $claims['jti'] ); + if ( false !== get_transient( $seen ) ) { + return false; + } + set_transient( $seen, 1, max( 60, (int) $claims['exp'] - $now + self::LEEWAY ) ); + + return true; + } + + /** + * The public key with the id, as PEM, from the cached key set, or from a + * fresh one when the cache does not have it. + * + * @param string $kid The key id. + * + * @return string|null + */ + private static function key( string $kid ): ?string { + $keys = get_transient( self::KEYS_TRANSIENT ); + if ( is_array( $keys ) && isset( $keys[ $kid ] ) ) { + return $keys[ $kid ]; + } + if ( is_array( $keys ) && false !== get_transient( self::REFETCH_TRANSIENT ) ) { + return null; + } + $keys = self::fetch_keys(); + if ( null === $keys ) { + return null; + } + set_transient( self::KEYS_TRANSIENT, $keys, DAY_IN_SECONDS ); + set_transient( self::REFETCH_TRANSIENT, 1, 5 * MINUTE_IN_SECONDS ); + + return $keys[ $kid ] ?? null; + } + + /** + * Fetch Scanfully's public keys. + * + * @return array|null The keys by id, as PEM, or null when they could not be read. + */ + private static function fetch_keys(): ?array { + $resp = wp_remote_get( + Main::get_oauth_url() . self::KEYS_PATH, + [ + 'timeout' => 5, + 'sslverify' => Main::get_sslverify(), + ] + ); + if ( is_wp_error( $resp ) || 200 !== (int) wp_remote_retrieve_response_code( $resp ) ) { + return null; + } + + return self::parse_keys( (string) wp_remote_retrieve_body( $resp ) ); + } + + /** + * The RSA signing keys of a JWK set, by id, as PEM. + * + * @param string $json The key set. + * + * @return array|null + */ + public static function parse_keys( string $json ): ?array { + $set = json_decode( $json, true ); + if ( ! is_array( $set ) || ! isset( $set['keys'] ) || ! is_array( $set['keys'] ) ) { + return null; + } + $keys = []; + foreach ( $set['keys'] as $jwk ) { + if ( ! is_array( $jwk ) || ( $jwk['kty'] ?? '' ) !== 'RSA' || ! isset( $jwk['kid'], $jwk['n'], $jwk['e'] ) + || ! is_string( $jwk['kid'] ) || ! is_string( $jwk['n'] ) || ! is_string( $jwk['e'] ) ) { + continue; + } + $keys[ $jwk['kid'] ] = self::rsa_pem( self::b64url_decode( $jwk['n'] ), self::b64url_decode( $jwk['e'] ) ); + } + + return $keys; + } + + /** + * A public key as PEM from its modulus and exponent (a SubjectPublicKeyInfo in DER). + * + * @param string $modulus The modulus, big-endian bytes. + * @param string $exponent The exponent, big-endian bytes. + * + * @return string + */ + public static function rsa_pem( string $modulus, string $exponent ): string { + $rsa = self::der( 0x30, self::der_integer( $modulus ) . self::der_integer( $exponent ) ); + $algorithm = "\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01\x05\x00"; // rsaEncryption, no parameters. + $spki = self::der( 0x30, $algorithm . self::der( 0x03, "\x00" . $rsa ) ); + + return "-----BEGIN PUBLIC KEY-----\n" . chunk_split( base64_encode( $spki ), 64, "\n" ) . "-----END PUBLIC KEY-----\n"; // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- PEM is base64. + } + + /** + * A DER integer: positive, so a leading 0 when the high bit is set. + * + * @param string $bytes Big-endian bytes. + * + * @return string + */ + private static function der_integer( string $bytes ): string { + $bytes = ltrim( $bytes, "\x00" ); + if ( '' === $bytes || ord( $bytes[0] ) > 0x7f ) { + $bytes = "\x00" . $bytes; + } + + return self::der( 0x02, $bytes ); + } + + /** + * A DER element of a tag and its content. + * + * @param int $tag The tag. + * @param string $content The content. + * + * @return string + */ + private static function der( int $tag, string $content ): string { + $length = strlen( $content ); + if ( $length < 0x80 ) { + return chr( $tag ) . chr( $length ) . $content; + } + $encoded = ltrim( pack( 'N', $length ), "\x00" ); + + return chr( $tag ) . chr( 0x80 | strlen( $encoded ) ) . $encoded . $content; + } + + /** + * Decode base64url without padding. + * + * @param string $value The encoded value. + * + * @return string The bytes, or an empty string when it is not base64url. + */ + private static function b64url_decode( string $value ): string { + $decoded = base64_decode( strtr( $value, '-_', '+/' ), true ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode -- JWTs are base64url. + + return false === $decoded ? '' : $decoded; + } +} diff --git a/tests/Unit/API/RequestTlsTest.php b/tests/Unit/API/RequestTlsTest.php index 2123834..f8144f2 100644 --- a/tests/Unit/API/RequestTlsTest.php +++ b/tests/Unit/API/RequestTlsTest.php @@ -29,6 +29,9 @@ final class RequestTlsTest extends TestCase { protected function setUp(): void { parent::setUp(); + Functions\when( 'get_transient' )->justReturn( false ); + Functions\when( 'set_transient' )->justReturn( true ); + Functions\when( 'wp_parse_url' )->alias( 'parse_url' ); $this->captured = []; $capture = function ( string $url, array $args ) { diff --git a/tests/Unit/Connect/OAuthTest.php b/tests/Unit/Connect/OAuthTest.php new file mode 100644 index 0000000..9efaa93 --- /dev/null +++ b/tests/Unit/Connect/OAuthTest.php @@ -0,0 +1,156 @@ + + */ + private array $transients = []; + + /** + * The token requests sent, with their arguments. + * + * @var array}> + */ + private array $posts = []; + + /** + * The next answer of the token endpoint: status and body. + * + * @var array{int, string} + */ + private array $answer = [ 200, '' ]; + + protected function setUp(): void { + parent::setUp(); + Functions\when( 'wp_parse_url' )->alias( 'parse_url' ); + Functions\when( 'admin_url' )->alias( static fn( $path = '' ) => 'https://wp.scanfully.com/wp-admin/' . $path ); + Functions\when( 'home_url' )->justReturn( 'https://wp.scanfully.com' ); + Functions\when( 'add_query_arg' )->alias( + static function ( $key, $value, $url ) { + return $url . ( false === strpos( $url, '?' ) ? '?' : '&' ) . $key . '=' . $value; + } + ); + Functions\when( 'get_current_user_id' )->justReturn( 3 ); + Functions\when( 'wp_generate_password' )->alias( static fn( $length ) => str_repeat( 'v', $length ) ); + Functions\when( 'set_transient' )->alias( + function ( string $key, $value ) { + $this->transients[ $key ] = $value; + return true; + } + ); + Functions\when( 'get_transient' )->alias( fn( string $key ) => $this->transients[ $key ] ?? false ); + Functions\when( 'is_wp_error' )->justReturn( false ); + Functions\when( 'wp_remote_post' )->alias( + function ( string $url, array $args ) { + $this->posts[] = [ $url, $args ]; + return $this->answer; + } + ); + Functions\when( 'wp_remote_retrieve_response_code' )->alias( static fn( $response ) => $response[0] ); + Functions\when( 'wp_remote_retrieve_body' )->alias( static fn( $response ) => $response[1] ); + } + + public function test_a_connection_starts_on_scanfully_oauth_server(): void { + $url = OAuth::authorize_url(); + $this->assertStringStartsWith( 'https://api.scanfully.com/oauth/authorize?', $url ); + parse_str( (string) parse_url( $url, PHP_URL_QUERY ), $query ); + + $this->assertSame( 'wordpress-plugin', $query['client_id'] ); + $this->assertSame( 'code', $query['response_type'] ); + $this->assertSame( 'https://api.scanfully.com/v1/sites', $query['resource'] ); + $this->assertSame( 'wordpress:read', $query['scope'] ); + $this->assertSame( 'https://wp.scanfully.com', $query['site'] ); + $this->assertSame( OAuth::redirect_uri(), $query['redirect_uri'] ); + $this->assertStringStartsWith( 'https://wp.scanfully.com/wp-admin/', $query['redirect_uri'] ); + $this->assertStringContainsString( 'scanfully-oauth=1', $query['redirect_uri'] ); + $this->assertSame( 'S256', $query['code_challenge_method'] ); + $this->assertSame( Controller::code_challenge( Controller::get_code_verifier() ), $query['code_challenge'] ); + $this->assertSame( Controller::get_state(), $query['state'] ); + } + + public function test_a_code_is_exchanged_with_its_verifier_and_return_address(): void { + $this->answer = [ + 200, + (string) json_encode( + [ + 'access_token' => 'sfy_sat_a', + 'refresh_token' => 'sfy_srt_r', + 'expires_in' => 2419200, + 'scope' => 'wordpress:read', + 'site_id' => 'site-1', + ] + ), + ]; + + $tokens = OAuth::exchange_code( 'the-code', 'the-verifier' ); + + [ $url, $args ] = $this->posts[0]; + $this->assertSame( 'https://api.scanfully.com/oauth/token', $url ); + $this->assertSame( 'application/x-www-form-urlencoded', $args['headers']['Content-Type'] ); + $this->assertSame( 'authorization_code', $args['body']['grant_type'] ); + $this->assertSame( 'the-verifier', $args['body']['code_verifier'] ); + $this->assertSame( OAuth::redirect_uri(), $args['body']['redirect_uri'] ); + $this->assertSame( 'site-1', $tokens['site_id'] ); + $this->assertSame( [ 'wordpress:read' ], $tokens['scopes'] ); + $this->assertEqualsWithDelta( time() + 2419200, strtotime( $tokens['expires'] ), 5 ); + } + + public function test_an_answer_without_tokens_or_expiry_is_nothing(): void { + $this->assertSame( + [], + OAuth::normalize( + [ + 'access_token' => 'a', + 'refresh_token' => 'r', + ] + ) + ); + $this->assertSame( + [], + OAuth::normalize( + [ + 'access_token' => 'a', + 'expires_in' => 60, + ] + ) + ); + $this->assertSame( + [], + OAuth::normalize( + [ + 'access_token' => 'a', + 'refresh_token' => 'r', + 'expires_in' => 0, + ] + ) + ); + } + + public function test_a_refresh_tells_an_api_without_the_plugin_client_from_a_failure(): void { + $this->answer = [ 400, '{"error":"invalid_client"}' ]; + $this->assertNull( OAuth::refresh( 'r', 'site-1' ) ); + $this->answer = [ 404, '' ]; + $this->assertNull( OAuth::refresh( 'r', 'site-1' ) ); + $this->answer = [ 400, '{"error":"invalid_grant"}' ]; + $this->assertSame( [], OAuth::refresh( 'r', 'site-1' ) ); + $this->assertSame( 'site-1', $this->posts[2][1]['body']['site_id'] ); + } +} diff --git a/tests/Unit/Cron/TokenRefreshTest.php b/tests/Unit/Cron/TokenRefreshTest.php index ad613b5..2b9e19f 100644 --- a/tests/Unit/Cron/TokenRefreshTest.php +++ b/tests/Unit/Cron/TokenRefreshTest.php @@ -49,6 +49,13 @@ final class TokenRefreshTest extends TestCase { */ private array $api_response = [ 200, '' ]; + /** + * The addresses of the token requests. + * + * @var string[] + */ + private array $urls = []; + /** * Runs inside the fake API call, to simulate another process. * @@ -77,6 +84,8 @@ protected function setUp(): void { 'scanfully_connect_expires' => gmdate( 'Y-m-d H:i:s', time() + HOUR_IN_SECONDS ), 'scanfully_connect_last_used' => '', 'scanfully_connect_date_connected' => '', + // a connection on the OAuth server; the move from a legacy one has tests of its own. + 'scanfully_connect_flow' => 'oauth', ]; $this->api_response = [ 200, $this->token_body( 'new-access', 'new-refresh' ) ]; $this->token_requests = 0; @@ -90,6 +99,7 @@ function ( string $name, $value ) { } ); Functions\when( 'wp_cache_delete' )->justReturn( true ); + Functions\when( 'wp_parse_url' )->alias( 'parse_url' ); Functions\when( 'get_transient' )->alias( fn( string $key ) => $this->transients[ $key ] ?? false ); Functions\when( 'set_transient' )->alias( function ( string $key, $value ) { @@ -106,8 +116,9 @@ function ( string $key ) { Functions\when( 'wp_json_encode' )->alias( static fn( $data ) => json_encode( $data ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode -- WordPress is not loaded in unit tests. Functions\when( 'is_wp_error' )->justReturn( false ); Functions\when( 'wp_remote_post' )->alias( - function () { + function ( string $url ) { ++$this->token_requests; + $this->urls[] = $url; if ( null !== $this->during_request ) { ( $this->during_request )(); } @@ -136,6 +147,9 @@ private function token_body( string $access, string $refresh ): string { [ 'access_token' => $access, 'refresh_token' => $refresh, + // the OAuth server's answer, and the legacy route's expiry. + 'expires_in' => 28 * DAY_IN_SECONDS, + 'scope' => 'wordpress:read', 'expires' => gmdate( 'Y-m-d\TH:i:s\Z', time() + 28 * DAY_IN_SECONDS ), 'site_id' => 'site-1', ] @@ -253,7 +267,7 @@ public function provide_failed_responses(): array { } public function test_the_site_id_falls_back_to_the_stored_one(): void { - $this->api_response = [ 200, '{"access_token":"a","refresh_token":"r","expires":"2030-01-01T00:00:00Z"}' ]; + $this->api_response = [ 200, '{"access_token":"a","refresh_token":"r","expires_in":2419200,"expires":"2030-01-01T00:00:00Z"}' ]; $this->refresh(); @@ -269,6 +283,53 @@ public function test_an_unparsable_stored_expiry_triggers_a_refresh(): void { $this->assertSame( 1, $this->token_requests ); $this->assertSame( 'new-access', $this->options['scanfully_connect_access_token'] ); } + + public function test_a_legacy_connection_moves_to_the_oauth_server_once(): void { + unset( $this->options['scanfully_connect_flow'] ); + $this->options['scanfully_connect_expires'] = gmdate( 'Y-m-d H:i:s', time() + 10 * DAY_IN_SECONDS ); + + $this->refresh(); + + $this->assertSame( 1, $this->token_requests ); + $this->assertStringEndsWith( '/oauth/token', $this->urls[0] ); + $this->assertSame( 'new-access', $this->options['scanfully_connect_access_token'] ); + $this->assertSame( 'oauth', $this->options['scanfully_connect_flow'] ); + $this->assertSame( 'wordpress:read', $this->options['scanfully_connect_scopes'] ); + + $this->refresh(); + $this->assertSame( 1, $this->token_requests, 'moved: no refresh until the token expires' ); + } + + public function test_a_failed_move_keeps_the_tokens_and_is_no_broken_connection(): void { + unset( $this->options['scanfully_connect_flow'] ); + $this->options['scanfully_connect_expires'] = gmdate( 'Y-m-d H:i:s', time() + 10 * DAY_IN_SECONDS ); + $this->api_response = [ 502, '' ]; + + $this->refresh(); + + $this->assertSame( 'old-access', $this->options['scanfully_connect_access_token'] ); + $this->assertArrayNotHasKey( 'scanfully_refresh_failures', $this->transients ); + $this->assertArrayHasKey( 'scanfully_oauth_unavailable', $this->transients ); + + $this->refresh(); + $this->assertSame( 1, $this->token_requests, 'the move waits a day' ); + } + + public function test_an_api_without_the_plugin_client_refreshes_an_expiring_token_on_the_legacy_route(): void { + unset( $this->options['scanfully_connect_flow'] ); + $replies = [ [ 400, '{"error":"invalid_client"}' ], [ 200, $this->token_body( 'legacy-access', 'legacy-refresh' ) ] ]; + $this->during_request = function () use ( &$replies ) { + $this->api_response = array_shift( $replies ); + }; + + $this->refresh(); + + $this->assertSame( 2, $this->token_requests ); + $this->assertStringEndsWith( '/oauth/token', $this->urls[0] ); + $this->assertStringEndsWith( '/connect/token', $this->urls[1] ); + $this->assertSame( 'legacy-access', $this->options['scanfully_connect_access_token'] ); + $this->assertArrayNotHasKey( 'scanfully_connect_flow', $this->options ); + } } /** diff --git a/tests/Unit/Sync/SignedRequestTest.php b/tests/Unit/Sync/SignedRequestTest.php new file mode 100644 index 0000000..f72676a --- /dev/null +++ b/tests/Unit/Sync/SignedRequestTest.php @@ -0,0 +1,209 @@ + + */ + private array $transients = []; + + /** + * How often the key set was fetched. + * + * @var int + */ + private int $fetches = 0; + + public static function setUpBeforeClass(): void { + parent::setUpBeforeClass(); + self::$key = openssl_pkey_new( + [ + 'private_key_bits' => 2048, + 'private_key_type' => OPENSSL_KEYTYPE_RSA, + ] + ); + $details = openssl_pkey_get_details( self::$key ); + self::$jwks = (string) json_encode( + [ + 'keys' => [ + [ + 'kty' => 'RSA', + 'use' => 'sig', + 'alg' => 'RS256', + 'kid' => 'key-1', + 'n' => self::b64url( $details['rsa']['n'] ), + 'e' => self::b64url( $details['rsa']['e'] ), + ], + ], + ] + ); + } + + protected function setUp(): void { + parent::setUp(); + Functions\when( 'wp_parse_url' )->alias( 'parse_url' ); + Functions\when( 'get_transient' )->alias( fn( string $key ) => $this->transients[ $key ] ?? false ); + Functions\when( 'set_transient' )->alias( + function ( string $key, $value ) { + $this->transients[ $key ] = $value; + return true; + } + ); + Functions\when( 'is_wp_error' )->justReturn( false ); + Functions\when( 'wp_remote_get' )->alias( + function ( string $url ) { + $this->assertSame( self::ISSUER . SignedRequest::KEYS_PATH, $url ); + ++$this->fetches; + return [ 'body' => self::$jwks ]; + } + ); + Functions\when( 'wp_remote_retrieve_response_code' )->justReturn( 200 ); + Functions\when( 'wp_remote_retrieve_body' )->alias( fn( $resp ) => $resp['body'] ); + } + + private static function b64url( string $bytes ): string { + return rtrim( strtr( base64_encode( $bytes ), '+/', '-_' ), '=' ); + } + + /** + * A request signed as the API signs it, with claims changed. + * + * @param array $claims Claims to change. + * @param string $kid The key id. + */ + private function signed( array $claims = [], string $kid = 'key-1' ): string { + $now = time(); + $header = self::b64url( + (string) json_encode( + [ + 'alg' => 'RS256', + 'typ' => 'JWT', + 'kid' => $kid, + ] + ) + ); + $payload = self::b64url( + (string) json_encode( + array_merge( + [ + 'iss' => self::ISSUER, + 'sub' => 'sync', + 'aud' => [ self::SITE ], + 'iat' => $now, + 'nbf' => $now - 60, + 'exp' => $now + 300, + 'jti' => bin2hex( random_bytes( 8 ) ), + 'scope' => 'wordpress:read', + ], + $claims + ) + ) + ); + openssl_sign( $header . '.' . $payload, $signature, self::$key, OPENSSL_ALGO_SHA256 ); + + return $header . '.' . $payload . '.' . self::b64url( $signature ); + } + + private function verify( string $token ): bool { + return SignedRequest::verify( $token, self::SITE, 'sync', 'wordpress:read' ); + } + + public function test_a_request_scanfully_signed_for_the_site_passes_once(): void { + $token = $this->signed(); + $this->assertTrue( SignedRequest::looks_signed( $token ) ); + $this->assertTrue( $this->verify( $token ) ); + $this->assertFalse( $this->verify( $token ), 'a replayed request' ); + $this->assertTrue( $this->verify( $this->signed() ) ); + $this->assertSame( 1, $this->fetches, 'the key set is cached' ); + } + + public function test_a_request_for_another_site_action_or_scope_fails(): void { + $this->assertFalse( $this->verify( $this->signed( [ 'aud' => [ 'site-2' ] ] ) ) ); + $this->assertFalse( $this->verify( $this->signed( [ 'sub' => 'login' ] ) ) ); + $this->assertFalse( $this->verify( $this->signed( [ 'scope' => 'wordpress:update' ] ) ) ); + $this->assertFalse( $this->verify( $this->signed( [ 'iss' => 'https://evil.scanfully.dev' ] ) ) ); + $this->assertTrue( $this->verify( $this->signed( [ 'aud' => self::SITE ] ) ), 'a single audience' ); + } + + public function test_times_allow_some_clock_skew_only(): void { + $this->assertTrue( $this->verify( $this->signed( [ 'exp' => time() - 60 ] ) ) ); + $this->assertFalse( $this->verify( $this->signed( [ 'exp' => time() - SignedRequest::LEEWAY - 60 ] ) ) ); + $this->assertFalse( $this->verify( $this->signed( [ 'nbf' => time() + SignedRequest::LEEWAY + 60 ] ) ) ); + $this->assertFalse( $this->verify( $this->signed( [ 'jti' => '' ] ) ) ); + } + + public function test_a_forged_or_tampered_request_fails(): void { + $token = $this->signed(); + [ $header, $payload, $signature ] = explode( '.', $token ); + $other = self::b64url( + (string) json_encode( + [ + 'iss' => self::ISSUER, + 'sub' => 'sync', + 'aud' => self::SITE, + 'exp' => time() + 60, + 'jti' => 'x', + 'scope' => 'wordpress:read', + ] + ) + ); + $this->assertFalse( $this->verify( $header . '.' . $other . '.' . $signature ), 'another payload' ); + $none = self::b64url( + (string) json_encode( + [ + 'alg' => 'none', + 'kid' => 'key-1', + ] + ) + ); + $this->assertFalse( $this->verify( $none . '.' . $payload . '.' ), 'alg none' ); + $this->assertFalse( $this->verify( 'not.a.token' ) ); + } + + public function test_an_unknown_key_is_fetched_again_a_few_minutes_apart(): void { + $this->assertTrue( $this->verify( $this->signed() ) ); + $this->assertFalse( $this->verify( $this->signed( [], 'key-2' ) ) ); + $this->assertFalse( $this->verify( $this->signed( [], 'key-3' ) ) ); + $this->assertSame( 1, $this->fetches, 'one fetch, then the refetch waits' ); + } + + public function test_the_key_set_becomes_pem_keys(): void { + $keys = SignedRequest::parse_keys( self::$jwks ); + $this->assertArrayHasKey( 'key-1', $keys ); + $this->assertNotFalse( openssl_pkey_get_public( $keys['key-1'] ) ); + $this->assertNull( SignedRequest::parse_keys( 'not json' ) ); + } +} From 7caf192f89b744dca37206a60b71d1489413cb32 Mon Sep 17 00:00:00 2001 From: Barry Kooij Date: Tue, 3 Nov 2026 22:01:58 +0100 Subject: [PATCH 2/5] Fixed: a connection the OAuth server cannot take over yet keeps refreshing on the legacy route before its token expires --- src/Connect/Controller.php | 11 +++++++---- tests/Unit/API/RequestTlsTest.php | 3 ++- tests/Unit/Cron/TokenRefreshTest.php | 22 ++++++++++++++++++++++ 3 files changed, 31 insertions(+), 5 deletions(-) diff --git a/src/Connect/Controller.php b/src/Connect/Controller.php index 9f1d50f..6e57ec0 100644 --- a/src/Connect/Controller.php +++ b/src/Connect/Controller.php @@ -455,10 +455,13 @@ private static function exchange_authorization_code( string $code, string $site, public static function refresh_access_token( string $refresh_token, string $site, bool $legacy_fallback = true ): array { if ( false === get_transient( self::OAUTH_UNAVAILABLE_TRANSIENT ) ) { $tokens = OAuth::refresh( $refresh_token, $site ); - if ( null !== $tokens ) { - if ( ! empty( $tokens ) ) { - self::store_grant( $tokens['scopes'] ); - } + if ( ! empty( $tokens ) ) { + self::store_grant( $tokens['scopes'] ); + return $tokens; + } + // a connection that has not moved yet keeps the legacy route when + // the OAuth server refuses it (the API could not move it yet). + if ( null !== $tokens && ( 'oauth' === OptionsController::get_option( 'flow' ) || ! $legacy_fallback ) ) { return $tokens; } // an API that does not connect sites on its OAuth server yet: the diff --git a/tests/Unit/API/RequestTlsTest.php b/tests/Unit/API/RequestTlsTest.php index f8144f2..305e6eb 100644 --- a/tests/Unit/API/RequestTlsTest.php +++ b/tests/Unit/API/RequestTlsTest.php @@ -93,7 +93,8 @@ private function send_all(): void { public function test_every_api_request_verifies_tls_by_default(): void { $this->send_all(); - $this->assertCount( 4, $this->captured ); + // the refresh of a connection that has not moved tries the OAuth server, then the legacy route. + $this->assertCount( 5, $this->captured ); foreach ( $this->captured as $args ) { $this->assertTrue( $args['sslverify'] ); } diff --git a/tests/Unit/Cron/TokenRefreshTest.php b/tests/Unit/Cron/TokenRefreshTest.php index 2b9e19f..93d9539 100644 --- a/tests/Unit/Cron/TokenRefreshTest.php +++ b/tests/Unit/Cron/TokenRefreshTest.php @@ -315,6 +315,28 @@ public function test_a_failed_move_keeps_the_tokens_and_is_no_broken_connection( $this->assertSame( 1, $this->token_requests, 'the move waits a day' ); } + public function test_a_legacy_connection_the_oauth_server_refuses_refreshes_on_the_legacy_route_when_expiring(): void { + unset( $this->options['scanfully_connect_flow'] ); + $replies = [ [ 400, '{"error":"invalid_grant"}' ], [ 200, $this->token_body( 'legacy-access', 'legacy-refresh' ) ] ]; + $this->during_request = function () use ( &$replies ) { + $this->api_response = array_shift( $replies ); + }; + + $this->refresh(); + + $this->assertSame( 2, $this->token_requests ); + $this->assertSame( 'legacy-access', $this->options['scanfully_connect_access_token'] ); + } + + public function test_a_moved_connection_the_oauth_server_refuses_is_a_failure(): void { + $this->api_response = [ 400, '{"error":"invalid_grant"}' ]; + + $this->refresh(); + + $this->assertSame( 1, $this->token_requests ); + $this->assertSame( 1, $this->transients['scanfully_refresh_failures'] ?? 0 ); + } + public function test_an_api_without_the_plugin_client_refreshes_an_expiring_token_on_the_legacy_route(): void { unset( $this->options['scanfully_connect_flow'] ); $replies = [ [ 400, '{"error":"invalid_client"}' ], [ 200, $this->token_body( 'legacy-access', 'legacy-refresh' ) ] ]; From 69db3be6a0dcefd7bd79b84a8016efd9fb25c779 Mon Sep 17 00:00:00 2001 From: Barry Kooij Date: Tue, 3 Nov 2026 22:24:32 +0100 Subject: [PATCH 3/5] Fixed: Change what Scanfully may do keeps the current connection until the new one is approved, so cancelling leaves the site connected --- src/Connect/Buttons.php | 11 ++++++----- src/Connect/Controller.php | 24 ++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/src/Connect/Buttons.php b/src/Connect/Buttons.php index 7cffa58..4805896 100644 --- a/src/Connect/Buttons.php +++ b/src/Connect/Buttons.php @@ -38,17 +38,18 @@ public static function connect(): void { } /** - * Change what Scanfully may do: a new connection, on whose page in - * Scanfully the admin chooses again. It replaces the current one. + * Change what Scanfully may do: a new connection request, on whose page + * in Scanfully the admin chooses again. Approving it replaces the current + * connection; cancelling keeps it. * * @return void */ public static function change_access(): void { $url = add_query_arg( [ - 'page' => 'scanfully', - 'scanfully-reconnect' => 1, - 'scanfully-reconnect-nonce' => wp_create_nonce( 'scanfully-reconnect' ), + 'page' => 'scanfully', + 'scanfully-change-access' => 1, + 'scanfully-change-access-nonce' => wp_create_nonce( 'scanfully-change-access' ), ], admin_url( 'options-general.php' ) ); diff --git a/src/Connect/Controller.php b/src/Connect/Controller.php index 6e57ec0..def3d20 100644 --- a/src/Connect/Controller.php +++ b/src/Connect/Controller.php @@ -58,6 +58,11 @@ public static function catch_connect_requests(): void { self::handle_reconnect(); } + // a new connection request that keeps the current one until approved. + if ( isset( $_GET['scanfully-change-access'] ) ) { + self::handle_change_access(); + } + // the OAuth server's answer to a connection request. if ( isset( $_GET[ OAuth::CALLBACK_PARAM ] ) ) { self::handle_oauth_answer(); @@ -129,6 +134,25 @@ private static function handle_disconnect_start(): void { exit; } + /** + * Handle a request to change what Scanfully may do: a new connection + * request, while the current connection keeps working. Scanfully ends it + * when the admin approves the new one; a cancel leaves it as it was. + * + * @return void + */ + private static function handle_change_access(): void { + if ( ! isset( $_GET['scanfully-change-access-nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['scanfully-change-access-nonce'] ) ), 'scanfully-change-access' ) ) { + wp_die( 'Invalid Scanfully nonce' ); + } + if ( ! self::user_has_access() ) { + wp_die( 'You do not have permission to do this.' ); + } + + wp_redirect( OAuth::authorize_url() ); // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect -- Scanfully's own OAuth server, on another host. + exit; + } + /** * Handle a reconnect request: disconnect the current account and immediately start a new connect flow. * From aff85fa5120b06c05d44215201f4fc976f473b9e Mon Sep 17 00:00:00 2001 From: Barry Kooij Date: Wed, 4 Nov 2026 19:45:09 +0100 Subject: [PATCH 4/5] Changed: the readme describes WooCommerce checkout monitoring as an add-on instead of a beta --- readme.txt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/readme.txt b/readme.txt index a980f40..3d80f61 100644 --- a/readme.txt +++ b/readme.txt @@ -67,13 +67,13 @@ Connect supported AI apps through [MCP](https://docs.scanfully.com/account/mcp/) Protect your Scanfully account with authenticator-based two-factor sign-in, including when you use a social sign-in provider. -= WooCommerce checkout monitoring: beta = += WooCommerce checkout monitoring = A working homepage does not tell you whether a shopper can reach checkout. -For accounts with beta access, Scanfully can test a configured purchase flow through the product, cart, and checkout steps. Tests stop at the payment step without completing a payment. Review the failed step and available screenshots when a test fails. +With the WooCommerce add-on on a site, Scanfully can test a configured purchase flow through the product, cart, and checkout steps. Tests stop at the payment step without completing a payment. Review the failed step and available screenshots when a test fails. -See the [WooCommerce monitoring documentation](https://docs.scanfully.com/woocommerce/) for requirements and beta access. +See the [WooCommerce monitoring documentation](https://docs.scanfully.com/woocommerce/) for requirements and pricing. = How the plugin and service work together = From e28311308cf513aee03802c18dcca7f5369fdc15 Mon Sep 17 00:00:00 2001 From: Barry Kooij Date: Thu, 12 Nov 2026 12:04:15 +0100 Subject: [PATCH 5/5] Changed: version 1.11.0, with its changelog in the readme --- readme.txt | 9 ++++++++- scanfully.php | 4 ++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/readme.txt b/readme.txt index 3d80f61..d70fdef 100644 --- a/readme.txt +++ b/readme.txt @@ -4,7 +4,7 @@ Donate link: https://scanfully.com Tags: monitoring, site health, broken links, user activity, activity log Requires at least: 6.0 Tested up to: 7.1.3 -Stable tag: 1.10.0 +Stable tag: 1.11.0 License: GPLv3 or later License URI: https://www.gnu.org/licenses/gpl-3.0.html Requires PHP: 7.4 @@ -153,6 +153,13 @@ Read Scanfully's [terms and conditions](https://docs.scanfully.com/general/terms == Changelog == += 1.11.0: November 12, 2026 = +* Added: connecting a site goes through Scanfully's authorization server, where you pick the site and choose what Scanfully may do on it +* Added: "Change what Scanfully may do" on the settings page changes those permissions later, and cancelling keeps the current connection +* Changed: an existing connection moves to the new connection by itself, without reconnecting +* Security: when Scanfully asks the site to sync, it signs the request, and the plugin checks the signature against Scanfully's public keys +* Changed: the readme describes WooCommerce checkout monitoring as an add-on instead of a beta + = 1.10.0: November 2, 2026 = * Added: the plugin tells Scanfully when it is deactivated, disconnected or deleted, and by whom, so Scanfully can say why a site stopped reporting * Added: when Scanfully asks the plugin to sync, the plugin answers with its version and how its last requests to Scanfully went diff --git a/scanfully.php b/scanfully.php index 5204d34..c7f2c52 100644 --- a/scanfully.php +++ b/scanfully.php @@ -8,7 +8,7 @@ * * @wordpress-plugin * Plugin Name: Scanfully - * Version: 1.10.0 + * Version: 1.11.0 * Plugin URI: https://scanfully.com/wp-plugin * Description: Scanfully is your favorite WordPress performance and health monitoring tool. * Author: Scanfully @@ -68,7 +68,7 @@ function Scanfully(): \Scanfully\Main { // phpcs:ignore WordPress.NamingConventi function () { // meta. define( 'SCANFULLY_PLUGIN_FILE', __FILE__ ); - define( 'SCANFULLY_VERSION', '1.10.0' ); + define( 'SCANFULLY_VERSION', '1.11.0' ); // boot. require __DIR__ . '/vendor/autoload.php';