PluginProbe
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN / 1.3.2
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN v1.3.2
1.3.5 1.3.4 1.3.3 1.3.2 1.3.1 1.3.0 1.2.4 trunk 1.0.0 1.0.1 1.0.2 1.0.3 1.0.4 1.0.5 1.0.6 1.0.7 1.0.8 1.0.9 1.1.0 1.1.1 1.1.2 1.1.3 1.1.4 1.1.5 1.1.6 All 31 releases
← All changes | includes/modules/Mcp/Mcp_Hub.php +379 -8 1.1.3 → 1.3.2 View file →
@@ -32,8 +32,10 @@
32 32 namespace XSpeed\Modules\Mcp;
33 33
34 34 defined( 'ABSPATH' ) || exit;
35 35
36 +use XSpeed\Score_Store;
37 +
36 38 final class Mcp_Hub {
37 39
38 40 /** Option key holding hub-link state (separate from pairing state). */
39 41 public const OPTION = 'xspeed_module_mcp_hub';
@@ -42,8 +44,15 @@
42 44 * can have many admins, each managing it from their own hub account, so
43 45 * the connection is per-user, not site-wide. */
44 46 public const USER_META = 'xspeed_hub_link';
45 47
48 + /**
49 + * Site-level mirror of "any admin attached" — '1'/'0'. Maintained by
50 + * every attach/detach path so the public scan-signals route answers from
51 + * one option row instead of scanning users. See site_attached().
52 + */
53 + public const SITE_ATTACHED_OPTION = 'xspeed_hub_site_attached';
54 +
46 55 /** Default hub dashboard base — where the user manages their account. */
47 56 public const DEFAULT_HUB_URL = 'https://app.xspeedcache.com';
48 57
49 58 /**
@@ -87,8 +96,93 @@
87 96 );
88 97 }
89 98
90 99 /**
100 + * Site-level Hub answer: is ANY admin on this site attached?
101 + *
102 + * `state()` is per-user because the attach credential belongs to the
103 + * admin who approved it — but "is this SITE managed through the Hub" is
104 + * a site-level fact, and it is what the public scan-signals route
105 + * reports. The answer is a mirror option maintained by every attach and
106 + * detach path, so the unauthenticated route reads one option row and
107 + * never scans users. A bounded user scan was the first implementation
108 + * and it answered WRONGLY: WP_User_Query orders by user_login, so an
109 + * attached admin sorting past the bound was invisible.
110 + *
111 + * Sites attached before the mirror existed have no option row yet; that
112 + * one absent-row case recomputes (over only the users carrying the
113 + * hub-link meta — a handful of admins, never the whole user table) and
114 + * writes the mirror, so the scan runs once per site ever.
115 + *
116 + * @return bool
117 + */
118 + public static function site_attached(): bool {
119 + $legacy = get_option( self::OPTION, array() );
120 + if ( is_array( $legacy ) && ! empty( $legacy['attached'] ) ) {
121 + return true;
122 + }
123 + $mirror = get_option( self::SITE_ATTACHED_OPTION, false );
124 + if ( false !== $mirror ) {
125 + return '1' === $mirror;
126 + }
127 + return self::refresh_site_attached();
128 + }
129 +
130 + /**
131 + * Recompute the site-level attached mirror from the per-user records and
132 + * persist it. Called by every path that changes attachment state, and
133 + * lazily by site_attached() for pre-mirror installs.
134 + *
135 + * @return bool The recomputed answer.
136 + */
137 + public static function refresh_site_attached(): bool {
138 + $attached = false;
139 + $legacy = get_option( self::OPTION, array() );
140 + if ( is_array( $legacy ) && ! empty( $legacy['attached'] ) ) {
141 + $attached = true;
142 + } else {
143 + // Unbounded over users CARRYING the hub-link meta (the JOIN
144 + // restricts to those rows — a handful of admins, not the user
145 + // table). Deliberately no 'number' cap: a cap plus WP_User_Query's
146 + // user_login ordering is exactly the wrong-answer bug this mirror
147 + // replaced.
148 + $user_ids = get_users(
149 + array(
150 + 'meta_key' => self::USER_META, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- runs only on attach/detach and once for pre-mirror installs; scans only rows carrying this meta.
151 + 'fields' => 'ids',
152 + )
153 + );
154 + foreach ( $user_ids as $user_id ) {
155 + $stored = get_user_meta( (int) $user_id, self::USER_META, true );
156 + if ( is_array( $stored ) && ! empty( $stored['attached'] ) ) {
157 + $attached = true;
158 + break;
159 + }
160 + }
161 + }
162 + update_option( self::SITE_ATTACHED_OPTION, $attached ? '1' : '0', false );
163 + return $attached;
164 + }
165 +
166 + /**
167 + * A user is being removed from this site (multisite Users → Remove).
168 + *
169 + * remove_user_from_blog is core's ONLY removal action and it fires
170 + * BEFORE WP drops the user — there is no post-removal hook — so a plain
171 + * recompute here would still count the departing admin and keep the
172 + * mirror stale. Clear their own hub-link record first (the right
173 + * cleanup regardless: their attachment to this site is ending), then
174 + * recompute over whoever remains, so a second attached admin keeps the
175 + * site reading attached.
176 + *
177 + * @param int $user_id The user being removed from the site.
178 + */
179 + public static function handle_user_removed( $user_id ): void {
180 + delete_user_meta( (int) $user_id, self::USER_META );
181 + self::refresh_site_attached();
182 + }
183 +
184 + /**
91 185 * Public snapshot for the dashboard "xSpeed Hub" card.
92 186 *
93 187 * Includes the paste-in values for Method 1 (this site's URL + token)
94 188 * and a link to the hub dashboard. The token is admin-only (the whole
@@ -173,12 +267,8 @@
173 267 * True when WP reports a local environment, or the host is a well-known dev
174 268 * TLD / localhost / a private or loopback IP.
175 269 */
176 270 public static function is_local_site(): bool {
177 - if ( function_exists( 'wp_get_environment_type' ) && 'local' === wp_get_environment_type() ) {
178 - return true;
179 - }
180 -
181 271 $host = wp_parse_url( home_url( '/' ), PHP_URL_HOST );
182 272 if ( ! is_string( $host ) || '' === $host ) {
183 273 return false;
184 274 }
@@ -201,8 +291,30 @@
201 291 FILTER_VALIDATE_IP,
202 292 FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE
203 293 );
204 294 }
295 +
296 + /*
297 + * WP_ENVIRONMENT_TYPE is deliberately NOT trusted on its own.
298 + *
299 + * It describes a WORKFLOW — local / development / staging /
300 + * production — not whether the internet can reach this site. Plenty
301 + * of real, publicly served sites are marked 'local' by their stack:
302 + * our own xsdev.1wp.site does exactly that, and told every visitor
303 + * "this site looks local" on a public HTTPS domain.
304 + *
305 + * The hostname above is the honest signal. This only corroborates it,
306 + * for a site whose name gives nothing away (an IP-less internal
307 + * hostname on a private network, say) — and only when the name is
308 + * also not a public FQDN.
309 + */
310 + if ( function_exists( 'wp_get_environment_type' ) && 'local' === wp_get_environment_type() ) {
311 + // A dotted name that resolves publicly is reachable whatever the
312 + // environment type claims; a bare hostname ("wordpress", "web")
313 + // is not resolvable from outside and genuinely is local.
314 + return false === strpos( $host, '.' );
315 + }
316 +
205 317 return false;
206 318 }
207 319
208 320 /**
@@ -212,12 +324,26 @@
212 324 * callback can record the connection PER-USER — each admin sees their own
213 325 * "Connected via <their account>" status.
214 326 */
215 327 public static function mint_attach_nonce(): string {
216 - // Ensure a site_token exists to hand over on the callback.
217 - if ( '' === Mcp_Pairing::site_token() ) {
218 - Mcp_Pairing::connect( false );
219 - }
328 + /*
329 + * Deliberately does NOT create a credential.
330 + *
331 + * This used to call Mcp_Pairing::connect( false ) here so a site_token
332 + * would exist "to hand over on the callback". But this runs on a READ:
333 + * public_status() embeds attach_url(), attach_url() mints a nonce, and
334 + * public_status() is what the dashboard bootstrap, the Overview, the
335 + * MCP drawer and GET /mcp/hub all call. The result was that merely
336 + * opening xSpeed established a live read-write MCP connection nobody
337 + * asked for — the site reported `connected` before the user had gone
338 + * anywhere near an AI client.
339 + *
340 + * The token is only ever CONSUMED in verify_attach_nonce(), which runs
341 + * when the Hub calls back after the user has clicked through, signed in
342 + * and approved. Minting it there keeps this function pure and keeps
343 + * credential creation on a path the user actually walked. The nonce
344 + * itself needs no token: nonce_secret() is derived from the site URL.
345 + */
220 346 $ts = time();
221 347 $uid = get_current_user_id();
222 348 $hmac = hash_hmac( 'sha256', $ts . '.' . $uid, self::nonce_secret() );
223 349 return $ts . '.' . $uid . '.' . $hmac;
@@ -246,8 +372,24 @@
246 372 $expected = hash_hmac( 'sha256', $ts . '.' . $uid, self::nonce_secret() );
247 373 if ( ! hash_equals( $expected, (string) $hmac ) ) {
248 374 return null; // bad signature
249 375 }
376 +
377 + /*
378 + * Only NOW mint the credential the callback hands over — after a valid,
379 + * unexpired, correctly-signed nonce has proved the user went through the
380 + * Hub and approved. This is the one point in the attach flow where the
381 + * user has unambiguously asked to connect, so it is where the token is
382 + * created; minting it earlier (at nonce time) meant a page render could
383 + * do it. An invalid nonce returns above without minting.
384 + *
385 + * connect() reuses an existing token, so a re-attach or a duplicate
386 + * callback is idempotent and never rotates a paired client's secret.
387 + */
388 + if ( '' === Mcp_Pairing::site_token() ) {
389 + Mcp_Pairing::connect( false );
390 + }
391 +
250 392 return array(
251 393 'site_url' => self::site_url_canonical(),
252 394 'site_token' => Mcp_Pairing::site_token(),
253 395 'user_id' => (int) $uid,
@@ -313,8 +455,9 @@
313 455 // any stale local "connected" so the badge doesn't lie.
314 456 $state = self::state( $uid );
315 457 if ( ! empty( $state['attached'] ) ) {
316 458 delete_user_meta( $uid, self::USER_META );
459 + self::refresh_site_attached();
317 460 }
318 461 }
319 462 }
320 463
@@ -395,8 +538,10 @@
395 538 'attached_at' => time(),
396 539 )
397 540 );
398 541 }
542 + // Attaching makes the site-level answer unconditionally yes.
543 + update_option( self::SITE_ATTACHED_OPTION, '1', false );
399 544 // Bust the reconcile cache so a reconnect reflects immediately (not the
400 545 // stale 'not attached' cached during the disconnected window).
401 546 delete_transient( 'xspeed_hub_reconcile' );
402 547 return self::public_status( $user_id );
@@ -453,10 +598,236 @@
453 598 * is what scopes multi-admin, and each admin's own meta is untouched.
454 599 */
455 600 delete_option( self::OPTION );
456 601
602 + // Other admins may still be attached — recompute rather than assume no.
603 + self::refresh_site_attached();
604 +
457 605 // Bust the reconcile cache so the next status read reflects reality
458 606 // immediately (not the stale 'attached' cached before disconnect).
459 607 delete_transient( 'xspeed_hub_reconcile' );
460 608 return self::public_status( $user_id );
609 + }
610 +
611 + /**
612 + * Ask the Hub to run a GTmetrix test for this site.
613 + *
614 + * The Hub owns the GTmetrix account, the credits and the quota — this site
615 + * only proves who it is, with the same site_token it uses everywhere else.
616 + * That is the whole point of the feature: the site owner needs no GTmetrix
617 + * account and no API key.
618 + *
619 + * Returns the Hub's decoded body on success (a run row plus the remaining
620 + * allowance). On failure returns a WP_Error whose CODE is stable and
621 + * machine-readable, so the UI can respond to "you're out of tests this
622 + * month" differently from "this site isn't verified" instead of printing
623 + * whatever sentence came back.
624 + *
625 + * @return array<string,mixed>|\WP_Error
626 + */
627 + public static function gtmetrix_test() {
628 + return self::hub_request( 'POST', '/api/site/gtmetrix/test' );
629 + }
630 +
631 + /**
632 + * Ask the Hub to run a PageSpeed Insights audit for this site.
633 + *
634 + * The PSI twin of gtmetrix_test(): the Hub holds a real Google API key, so
635 + * routing the audit through it is what makes a keyless site's test work —
636 + * an unkeyed call straight to Google shares one anonymous per-IP pool with
637 + * every other unkeyed caller and refuses with "Quota exceeded" under any
638 + * real load (issue #426).
639 + *
640 + * The Hub answers 202 with a run row and audits in the background; the
641 + * result arrives via psi_runs().
642 + *
643 + * @param string $strategy 'mobile', 'desktop' or 'both'.
644 + * @return array<string,mixed>|\WP_Error
645 + */
646 + public static function psi_test( string $strategy = 'mobile' ) {
647 + $strategy = in_array( $strategy, array( 'mobile', 'desktop', 'both' ), true ) ? $strategy : 'mobile';
648 + return self::hub_request( 'POST', '/api/site/psi/test', array( 'strategy' => $strategy ) );
649 + }
650 +
651 + /**
652 + * PSI runs for this site, finished ones copied into the local history.
653 + *
654 + * The polling half of psi_test() — that route answers before the audit
655 + * runs, so without this the plugin would never learn the score.
656 + *
657 + * @return array<string,mixed>|\WP_Error
658 + */
659 + public static function psi_runs() {
660 + $result = self::hub_request( 'GET', '/api/site/psi/runs' );
661 + if ( ! is_wp_error( $result ) ) {
662 + self::store_hub_results( $result );
663 + }
664 + return $result;
665 + }
666 +
667 + /**
668 + * Recent Hub-run tests for this site, plus the remaining allowance.
669 + *
670 + * Polled while a run is in flight, and read once on load so the button can
671 + * show the count before anyone presses anything.
672 + *
673 + * @return array<string,mixed>|\WP_Error
674 + */
675 + public static function gtmetrix_runs() {
676 + $result = self::hub_request( 'GET', '/api/site/gtmetrix/runs' );
677 + if ( ! is_wp_error( $result ) ) {
678 + self::store_hub_results( $result );
679 + }
680 + return $result;
681 + }
682 +
683 + /**
684 + * Copy any finished Hub runs into THIS SITE's own score history.
685 + *
686 + * The Hub stores the result too, but that is its copy, not ours. Without
687 + * this the plugin would have to ask the Hub every time it wanted to draw
688 + * a score it already paid for — and a site that later disconnects would
689 + * lose its history entirely. The run belongs to the site.
690 + *
691 + * Idempotent: the Hub reports a finished run on every poll after it
692 + * completes, so each result is matched on provider + timestamp and stored
693 + * once.
694 + *
695 + * @param array<string,mixed> $payload Decoded /site/gtmetrix/runs body.
696 + */
697 + private static function store_hub_results( array $payload ): void {
698 + $runs = isset( $payload['runs'] ) && is_array( $payload['runs'] ) ? $payload['runs'] : array();
699 + if ( empty( $runs ) ) {
700 + return;
701 + }
702 +
703 + foreach ( $runs as $run ) {
704 + if ( ! is_array( $run ) || 'done' !== ( $run['status'] ?? '' ) ) {
705 + continue;
706 + }
707 + $r = isset( $run['result'] ) && is_array( $run['result'] ) ? $run['result'] : array();
708 + if ( empty( $r ) ) {
709 + continue;
710 + }
711 +
712 + // The Hub works in milliseconds; the plugin's history is seconds.
713 + $ts = isset( $r['ran_at'] ) ? (int) round( ( (int) $r['ran_at'] ) / 1000 ) : 0;
714 + $remote_id = isset( $run['id'] ) ? (string) $run['id'] : '';
715 + // Keyed on the Hub's run id, not the timestamp: a retry and the
716 + // original delivery can differ by milliseconds and both looked
717 + // new, so one test appeared twice in the history.
718 + if ( $ts <= 0 || '' === $remote_id || Score_Store::exists_remote( $remote_id ) ) {
719 + continue;
720 + }
721 +
722 + // The runs table is shared between providers on the Hub too — a
723 + // PSI run must not be recorded as a GTmetrix row.
724 + $provider = 'psi' === ( $run['provider'] ?? '' ) ? 'psi' : 'gtmetrix';
725 +
726 + Score_Store::insert(
727 + array(
728 + 'ok' => true,
729 + 'provider' => $provider,
730 + 'ts' => $ts,
731 + 'url' => (string) ( $r['url'] ?? '' ),
732 + 'strategy' => (string) ( $r['strategy'] ?? ( 'psi' === $provider ? 'mobile' : 'desktop' ) ),
733 + 'score' => $r['score'] ?? null,
734 + 'metrics' => array(
735 + 'lcp' => $r['lcp'] ?? null,
736 + 'fcp' => $r['fcp'] ?? null,
737 + 'cls' => $r['cls'] ?? null,
738 + 'tbt' => $r['tbt'] ?? null,
739 + 'si' => $r['si'] ?? null,
740 + 'ttfb' => $r['ttfb'] ?? null,
741 + ),
742 + 'report_url' => $r['report_url'] ?? null,
743 + 'remote_id' => $remote_id,
744 + // What the report said to fix — stored here so the panel
745 + // can show it without sending anyone to GTmetrix's page.
746 + 'opportunities' => $r['opportunities'] ?? null,
747 + ),
748 + 'hub'
749 + );
750 + }
751 + }
752 +
753 + /**
754 + * Shared transport for the two calls above.
755 + *
756 + * Kept private and shared because the interesting part — turning an HTTP
757 + * failure into a stable error code — must behave identically for both. A
758 + * divergence there would show up as the UI handling a quota error on one
759 + * path and not the other.
760 + *
761 + * @param string $method HTTP method.
762 + * @param string $path Path under the hub base URL.
763 + * @param array<string,mixed> $body Extra POST body fields beside site_url.
764 + * @return array<string,mixed>|\WP_Error
765 + */
766 + private static function hub_request( string $method, string $path, array $body = array() ) {
767 + $token = Mcp_Pairing::site_token();
768 + if ( '' === $token ) {
769 + return new \WP_Error(
770 + 'not_connected',
771 + __( 'Connect this site to xSpeed Hub to run a free speed test.', 'xspeed' )
772 + );
773 + }
774 +
775 + $site_url = self::site_url_canonical();
776 + $args = array(
777 + // A test takes a minute, but the Hub answers as soon as it has
778 + // ACCEPTED the job — this waits for that handshake only.
779 + 'timeout' => 15,
780 + 'headers' => array( 'X-XSpeed-Site-Token' => $token ),
781 + );
782 +
783 + if ( 'POST' === $method ) {
784 + $args['headers']['Content-Type'] = 'application/json';
785 + $args['body'] = wp_json_encode( array_merge( array( 'site_url' => $site_url ), $body ) );
786 + $resp = wp_remote_post( self::hub_url() . $path, $args );
787 + } else {
788 + $resp = wp_remote_get(
789 + add_query_arg( array( 'site_url' => rawurlencode( $site_url ) ), self::hub_url() . $path ),
790 + $args
791 + );
792 + }
793 +
794 + if ( is_wp_error( $resp ) ) {
795 + return new \WP_Error(
796 + 'hub_unreachable',
797 + __( 'Could not reach xSpeed Hub. Please try again.', 'xspeed' )
798 + );
799 + }
800 +
801 + $code = (int) wp_remote_retrieve_response_code( $resp );
802 + $body = json_decode( (string) wp_remote_retrieve_body( $resp ), true );
803 + $body = is_array( $body ) ? $body : array();
804 +
805 + if ( $code >= 200 && $code < 300 ) {
806 + return $body;
807 + }
808 +
809 + // Prefer the Hub's own error code — it is already stable and specific
810 + // (site_not_verified, gtmetrix_quota_exceeded, gtmetrix_run_active,
811 + // gtmetrix_not_configured). Fall back to the status class so an
812 + // unexpected response still produces something the UI can branch on.
813 + $code_key = isset( $body['error'] ) && is_string( $body['error'] ) ? $body['error'] : '';
814 + if ( '' === $code_key ) {
815 + $code_key = 401 === $code ? 'not_connected' : 'hub_error';
816 + }
817 +
818 + $message = isset( $body['message'] ) && is_string( $body['message'] ) && '' !== $body['message']
819 + ? $body['message']
820 + : __( 'The test could not be started.', 'xspeed' );
821 +
822 + // Carry the quota numbers through on a 429 so the panel can say
823 + // "0 of 5 left" rather than just refusing.
824 + $data = array( 'status' => $code );
825 + foreach ( array( 'used', 'limit', 'quota', 'run' ) as $key ) {
826 + if ( isset( $body[ $key ] ) ) {
827 + $data[ $key ] = $body[ $key ];
828 + }
829 + }
830 +
831 + return new \WP_Error( $code_key, $message, $data );
461 832 }
462 833 }