| 1 |
<?php |
| 2 |
|
| 3 |
// phpcs:disable Yoast.NamingConventions.NamespaceName.TooLong -- Needed in the folder structure. |
| 4 |
|
| 5 |
namespace Yoast\WP\SEO\AI\Authorization\Application; |
| 6 |
|
| 7 |
use RuntimeException; |
| 8 |
use WP_User; |
| 9 |
use WPSEO_Utils; |
| 10 |
use Yoast\WP\SEO\AI\Authorization\Infrastructure\Access_Token_User_Meta_Repository_Interface; |
| 11 |
use Yoast\WP\SEO\AI\Authorization\Infrastructure\Code_Verifier_User_Meta_Repository; |
| 12 |
use Yoast\WP\SEO\AI\Authorization\Infrastructure\Refresh_Token_User_Meta_Repository_Interface; |
| 13 |
use Yoast\WP\SEO\AI\Generator\Infrastructure\WordPress_URLs; |
| 14 |
use Yoast\WP\SEO\AI\HTTP_Request\Application\Request_Handler; |
| 15 |
use Yoast\WP\SEO\AI\HTTP_Request\Domain\Exceptions\Bad_Request_Exception; |
| 16 |
use Yoast\WP\SEO\AI\HTTP_Request\Domain\Exceptions\Forbidden_Exception; |
| 17 |
use Yoast\WP\SEO\AI\HTTP_Request\Domain\Exceptions\Internal_Server_Error_Exception; |
| 18 |
use Yoast\WP\SEO\AI\HTTP_Request\Domain\Exceptions\Not_Found_Exception; |
| 19 |
use Yoast\WP\SEO\AI\HTTP_Request\Domain\Exceptions\Payment_Required_Exception; |
| 20 |
use Yoast\WP\SEO\AI\HTTP_Request\Domain\Exceptions\Request_Timeout_Exception; |
| 21 |
use Yoast\WP\SEO\AI\HTTP_Request\Domain\Exceptions\Service_Unavailable_Exception; |
| 22 |
use Yoast\WP\SEO\AI\HTTP_Request\Domain\Exceptions\Too_Many_Requests_Exception; |
| 23 |
use Yoast\WP\SEO\AI\HTTP_Request\Domain\Exceptions\Unauthorized_Exception; |
| 24 |
use Yoast\WP\SEO\AI\HTTP_Request\Domain\Request; |
| 25 |
use Yoast\WP\SEO\Helpers\User_Helper; |
| 26 |
|
| 27 |
/** |
| 28 |
* Class Token_Manager |
| 29 |
* Handles the management of JWT tokens used in the authorization process. |
| 30 |
* |
| 31 |
* @makePublic |
| 32 |
*/ |
| 33 |
class Token_Manager implements Token_Manager_Interface { |
| 34 |
|
| 35 |
/** |
| 36 |
* The access token repository. |
| 37 |
* |
| 38 |
* @var Access_Token_User_Meta_Repository_Interface |
| 39 |
*/ |
| 40 |
private $access_token_repository; |
| 41 |
|
| 42 |
/** |
| 43 |
* The code verifier service. |
| 44 |
* |
| 45 |
* @var Code_Verifier_Handler |
| 46 |
*/ |
| 47 |
private $code_verifier; |
| 48 |
|
| 49 |
/** |
| 50 |
* The refresh token repository. |
| 51 |
* |
| 52 |
* @var Refresh_Token_User_Meta_Repository_Interface |
| 53 |
*/ |
| 54 |
private $refresh_token_repository; |
| 55 |
|
| 56 |
/** |
| 57 |
* The user helper. |
| 58 |
* |
| 59 |
* @var User_Helper |
| 60 |
*/ |
| 61 |
private $user_helper; |
| 62 |
|
| 63 |
/** |
| 64 |
* The code verifier repository. |
| 65 |
* |
| 66 |
* @var Code_Verifier_User_Meta_Repository |
| 67 |
*/ |
| 68 |
private $code_verifier_repository; |
| 69 |
|
| 70 |
/** |
| 71 |
* The URLs service. |
| 72 |
* |
| 73 |
* @var WordPress_URLs |
| 74 |
*/ |
| 75 |
private $urls; |
| 76 |
|
| 77 |
/** |
| 78 |
* The request handler. |
| 79 |
* |
| 80 |
* @var Request_Handler |
| 81 |
*/ |
| 82 |
private $request_handler; |
| 83 |
|
| 84 |
/** |
| 85 |
* Token_Manager constructor. |
| 86 |
* |
| 87 |
* @param Access_Token_User_Meta_Repository_Interface $access_token_repository The access token repository. |
| 88 |
* @param Code_Verifier_Handler $code_verifier The code verifier service. |
| 89 |
* @param Refresh_Token_User_Meta_Repository_Interface $refresh_token_repository The refresh token repository. |
| 90 |
* @param User_Helper $user_helper The user helper. |
| 91 |
* @param Request_Handler $request_handler The request handler. |
| 92 |
* @param Code_Verifier_User_Meta_Repository $code_verifier_repository The code verifier repository. |
| 93 |
* @param WordPress_URLs $urls The URLs service. |
| 94 |
*/ |
| 95 |
public function __construct( |
| 96 |
Access_Token_User_Meta_Repository_Interface $access_token_repository, |
| 97 |
Code_Verifier_Handler $code_verifier, |
| 98 |
Refresh_Token_User_Meta_Repository_Interface $refresh_token_repository, |
| 99 |
User_Helper $user_helper, |
| 100 |
Request_Handler $request_handler, |
| 101 |
Code_Verifier_User_Meta_Repository $code_verifier_repository, |
| 102 |
WordPress_URLs $urls |
| 103 |
) { |
| 104 |
$this->access_token_repository = $access_token_repository; |
| 105 |
$this->code_verifier = $code_verifier; |
| 106 |
$this->refresh_token_repository = $refresh_token_repository; |
| 107 |
$this->user_helper = $user_helper; |
| 108 |
$this->request_handler = $request_handler; |
| 109 |
$this->code_verifier_repository = $code_verifier_repository; |
| 110 |
$this->urls = $urls; |
| 111 |
} |
| 112 |
|
| 113 |
// phpcs:disable Squiz.Commenting.FunctionCommentThrowTag.WrongNumber -- PHPCS doesn't take into account exceptions thrown in called methods. |
| 114 |
|
| 115 |
/** |
| 116 |
* Invalidates the access token. |
| 117 |
* |
| 118 |
* The locally stored JWTs are always cleared, even when the remote invalidation fails — the |
| 119 |
* remote exception still propagates to the caller, but no credentials are left behind. |
| 120 |
* |
| 121 |
* @param int $user_id The user ID. |
| 122 |
* |
| 123 |
* @return void |
| 124 |
* |
| 125 |
* @throws Bad_Request_Exception Bad_Request_Exception. |
| 126 |
* @throws Internal_Server_Error_Exception Internal_Server_Error_Exception. |
| 127 |
* @throws Not_Found_Exception Not_Found_Exception. |
| 128 |
* @throws Payment_Required_Exception Payment_Required_Exception. |
| 129 |
* @throws Request_Timeout_Exception Request_Timeout_Exception. |
| 130 |
* @throws Service_Unavailable_Exception Service_Unavailable_Exception. |
| 131 |
* @throws Too_Many_Requests_Exception Too_Many_Requests_Exception. |
| 132 |
* @throws RuntimeException Unable to retrieve the access token. |
| 133 |
*/ |
| 134 |
public function token_invalidate( int $user_id ): void { |
| 135 |
try { |
| 136 |
$access_jwt = $this->access_token_repository->get_token( $user_id ); |
| 137 |
} catch ( RuntimeException $e ) { |
| 138 |
$access_jwt = ''; |
| 139 |
} |
| 140 |
|
| 141 |
$request_headers = [ |
| 142 |
'Authorization' => "Bearer $access_jwt", |
| 143 |
]; |
| 144 |
|
| 145 |
try { |
| 146 |
// The endpoint takes no request body; the user is identified by the access token. |
| 147 |
$this->request_handler->handle( |
| 148 |
new Request( |
| 149 |
'/token/invalidate', |
| 150 |
[], |
| 151 |
$request_headers, |
| 152 |
), |
| 153 |
); |
| 154 |
} catch ( Unauthorized_Exception |Forbidden_Exception $e ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch -- Reason: Ignored on purpose. |
| 155 |
// If the credentials in our request were already invalid, our job is done and we continue to remove the tokens client-side. |
| 156 |
} finally { |
| 157 |
// Always clear the local tokens, even when the remote invalidation fails with an exception |
| 158 |
// that propagates: leaving credentials behind would contradict the intent of invalidating. |
| 159 |
$this->clear_tokens( $user_id ); |
| 160 |
} |
| 161 |
} |
| 162 |
|
| 163 |
/** |
| 164 |
* Clears the user meta tokens for a specific user. |
| 165 |
* |
| 166 |
* @param int $user_id The user id to delete this for. |
| 167 |
* |
| 168 |
* @return void |
| 169 |
*/ |
| 170 |
public function clear_tokens( int $user_id ): void { |
| 171 |
$this->access_token_repository->delete_token( $user_id ); |
| 172 |
$this->refresh_token_repository->delete_token( $user_id ); |
| 173 |
} |
| 174 |
|
| 175 |
/** |
| 176 |
* Checks whether any JWT (access or refresh) is stored locally for the user. |
| 177 |
* |
| 178 |
* @param int $user_id The user ID. |
| 179 |
* |
| 180 |
* @return bool Whether a locally stored JWT exists. |
| 181 |
*/ |
| 182 |
public function has_local_tokens( int $user_id ): bool { |
| 183 |
try { |
| 184 |
$this->access_token_repository->get_token( $user_id ); |
| 185 |
|
| 186 |
return true; |
| 187 |
} catch ( RuntimeException $e ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch -- Reason: Ignored on purpose. |
| 188 |
// No access token; fall through to the refresh token check. |
| 189 |
} |
| 190 |
|
| 191 |
try { |
| 192 |
$this->refresh_token_repository->get_token( $user_id ); |
| 193 |
|
| 194 |
return true; |
| 195 |
} catch ( RuntimeException $e ) { |
| 196 |
return false; |
| 197 |
} |
| 198 |
} |
| 199 |
|
| 200 |
/** |
| 201 |
* Requests a new set of JWT tokens. |
| 202 |
* |
| 203 |
* Requests a new JWT access and refresh token for a user from the Yoast AI Service and stores it in the database |
| 204 |
* under usermeta. The storing of the token happens in a HTTP callback that is triggered by this request. |
| 205 |
* |
| 206 |
* @param WP_User $user The WP user. |
| 207 |
* |
| 208 |
* @return void |
| 209 |
* |
| 210 |
* @throws Bad_Request_Exception Bad_Request_Exception. |
| 211 |
* @throws Forbidden_Exception Forbidden_Exception. |
| 212 |
* @throws Internal_Server_Error_Exception Internal_Server_Error_Exception. |
| 213 |
* @throws Not_Found_Exception Not_Found_Exception. |
| 214 |
* @throws Payment_Required_Exception Payment_Required_Exception. |
| 215 |
* @throws Request_Timeout_Exception Request_Timeout_Exception. |
| 216 |
* @throws Service_Unavailable_Exception Service_Unavailable_Exception. |
| 217 |
* @throws Too_Many_Requests_Exception Too_Many_Requests_Exception. |
| 218 |
* @throws Unauthorized_Exception Unauthorized_Exception. |
| 219 |
*/ |
| 220 |
public function token_request( WP_User $user ): void { |
| 221 |
// Generate a code verifier and store it in the database. |
| 222 |
$code_verifier = $this->code_verifier->generate( $user->user_email ); |
| 223 |
$this->code_verifier_repository->store_code_verifier( $user->ID, $code_verifier->get_code(), $code_verifier->get_created_at() ); |
| 224 |
|
| 225 |
$callback_url = $this->urls->get_callback_url(); |
| 226 |
$refresh_callback_url = $this->urls->get_refresh_callback_url(); |
| 227 |
|
| 228 |
$request_body = [ |
| 229 |
'service' => 'openai', |
| 230 |
'code_challenge' => \hash( 'sha256', $code_verifier->get_code() ), |
| 231 |
'license_site_url' => WPSEO_Utils::get_home_url(), |
| 232 |
'user_id' => (string) $user->ID, |
| 233 |
'callback_url' => $callback_url, |
| 234 |
'refresh_callback_url' => $refresh_callback_url, |
| 235 |
]; |
| 236 |
|
| 237 |
$this->request_handler->handle( new Request( '/token/request', $request_body ) ); |
| 238 |
|
| 239 |
// Store a per-user hash of the callback URL to detect future site URL changes. |
| 240 |
$this->user_helper->update_meta( $user->ID, '_yoast_wpseo_ai_generator_callback_url_hash', \md5( $callback_url ) ); |
| 241 |
|
| 242 |
// The callback saves the metadata. Because that is in another session, we need to delete the current cache here. Or we may get the old token. |
| 243 |
\wp_cache_delete( $user->ID, 'user_meta' ); |
| 244 |
} |
| 245 |
|
| 246 |
/** |
| 247 |
* Refreshes the JWT access token. |
| 248 |
* |
| 249 |
* Refreshes a stored JWT access token for a user with the Yoast AI Service and stores it in the database under |
| 250 |
* usermeta. The storing of the token happens in a HTTP callback that is triggered by this request. |
| 251 |
* |
| 252 |
* @param WP_User $user The WP user. |
| 253 |
* |
| 254 |
* @return void |
| 255 |
* |
| 256 |
* @throws Bad_Request_Exception Bad_Request_Exception. |
| 257 |
* @throws Forbidden_Exception Forbidden_Exception. |
| 258 |
* @throws Internal_Server_Error_Exception Internal_Server_Error_Exception. |
| 259 |
* @throws Not_Found_Exception Not_Found_Exception. |
| 260 |
* @throws Payment_Required_Exception Payment_Required_Exception. |
| 261 |
* @throws Request_Timeout_Exception Request_Timeout_Exception. |
| 262 |
* @throws Service_Unavailable_Exception Service_Unavailable_Exception. |
| 263 |
* @throws Too_Many_Requests_Exception Too_Many_Requests_Exception. |
| 264 |
* @throws Unauthorized_Exception Unauthorized_Exception. |
| 265 |
* @throws RuntimeException Unable to retrieve the refresh token. |
| 266 |
*/ |
| 267 |
public function token_refresh( WP_User $user ): void { |
| 268 |
$refresh_jwt = $this->refresh_token_repository->get_token( $user->ID ); |
| 269 |
|
| 270 |
// Generate a code verifier and store it in the database. |
| 271 |
$code_verifier = $this->code_verifier->generate( $user->user_email ); |
| 272 |
$this->code_verifier_repository->store_code_verifier( $user->ID, $code_verifier->get_code(), $code_verifier->get_created_at() ); |
| 273 |
|
| 274 |
$request_body = [ |
| 275 |
'code_challenge' => \hash( 'sha256', $code_verifier->get_code() ), |
| 276 |
]; |
| 277 |
$request_headers = [ |
| 278 |
'Authorization' => "Bearer $refresh_jwt", |
| 279 |
]; |
| 280 |
|
| 281 |
$this->request_handler->handle( new Request( '/token/refresh', $request_body, $request_headers ) ); |
| 282 |
|
| 283 |
// The callback saves the metadata. Because that is in another session, we need to delete the current cache here. Or we may get the old token. |
| 284 |
\wp_cache_delete( $user->ID, 'user_meta' ); |
| 285 |
} |
| 286 |
|
| 287 |
/** |
| 288 |
* Checks whether the token has expired. |
| 289 |
* |
| 290 |
* @param string $jwt The JWT. |
| 291 |
* |
| 292 |
* @return bool Whether the token has expired. |
| 293 |
*/ |
| 294 |
public function has_token_expired( string $jwt ): bool { |
| 295 |
$parts = \explode( '.', $jwt ); |
| 296 |
if ( \count( $parts ) !== 3 ) { |
| 297 |
// Headers, payload and signature parts are not detected. |
| 298 |
return true; |
| 299 |
} |
| 300 |
|
| 301 |
// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode -- Reason: Decoding the payload of the JWT. |
| 302 |
$payload = \base64_decode( $parts[1] ); |
| 303 |
$json = \json_decode( $payload ); |
| 304 |
if ( $json === null || ! isset( $json->exp ) ) { |
| 305 |
return true; |
| 306 |
} |
| 307 |
|
| 308 |
// Ensure exp is a valid numeric value. |
| 309 |
if ( ! \is_numeric( $json->exp ) ) { |
| 310 |
return true; |
| 311 |
} |
| 312 |
|
| 313 |
return $json->exp < \time(); |
| 314 |
} |
| 315 |
|
| 316 |
/** |
| 317 |
* Retrieves the access token. |
| 318 |
* |
| 319 |
* @param WP_User $user The WP user. |
| 320 |
* |
| 321 |
* @return string The access token. |
| 322 |
* |
| 323 |
* @throws Bad_Request_Exception Bad_Request_Exception. |
| 324 |
* @throws Forbidden_Exception Forbidden_Exception. |
| 325 |
* @throws Internal_Server_Error_Exception Internal_Server_Error_Exception. |
| 326 |
* @throws Not_Found_Exception Not_Found_Exception. |
| 327 |
* @throws Payment_Required_Exception Payment_Required_Exception. |
| 328 |
* @throws Request_Timeout_Exception Request_Timeout_Exception. |
| 329 |
* @throws Service_Unavailable_Exception Service_Unavailable_Exception. |
| 330 |
* @throws Too_Many_Requests_Exception Too_Many_Requests_Exception. |
| 331 |
* @throws Unauthorized_Exception Unauthorized_Exception. |
| 332 |
* @throws RuntimeException Unable to retrieve the access or refresh token. |
| 333 |
*/ |
| 334 |
public function get_or_request_access_token( WP_User $user ): string { |
| 335 |
// If the site URL has changed since callback URLs were registered, delete stale tokens. |
| 336 |
if ( $this->have_callback_urls_changed( $user ) ) { |
| 337 |
$this->clear_tokens( $user->ID ); |
| 338 |
} |
| 339 |
|
| 340 |
$access_jwt = $this->user_helper->get_meta( $user->ID, '_yoast_wpseo_ai_generator_access_jwt', true ); |
| 341 |
if ( ! \is_string( $access_jwt ) || $access_jwt === '' ) { |
| 342 |
$this->token_request( $user ); |
| 343 |
$access_jwt = $this->access_token_repository->get_token( $user->ID ); |
| 344 |
} |
| 345 |
elseif ( $this->has_token_expired( $access_jwt ) ) { |
| 346 |
try { |
| 347 |
$this->token_refresh( $user ); |
| 348 |
} catch ( Unauthorized_Exception $exception ) { |
| 349 |
$this->token_request( $user ); |
| 350 |
} |
| 351 |
$access_jwt = $this->access_token_repository->get_token( $user->ID ); |
| 352 |
} |
| 353 |
|
| 354 |
return $access_jwt; |
| 355 |
} |
| 356 |
|
| 357 |
// phpcs:enable Squiz.Commenting.FunctionCommentThrowTag.WrongNumber |
| 358 |
|
| 359 |
/** |
| 360 |
* Checks whether the callback URLs have changed since the last token request. |
| 361 |
* |
| 362 |
* Detects site URL changes (e.g., migrating from a staging URL to a production domain) |
| 363 |
* that would leave stale callback URLs registered with the Yoast AI service. |
| 364 |
* Uses a per-user hash so each user independently detects the change and re-registers. |
| 365 |
* The hash is immune to wp search-replace operations. |
| 366 |
* |
| 367 |
* When no hash is stored (first run after upgrade), returns true to force a fresh |
| 368 |
* token_request(). This ensures existing sites with stale callback URLs self-heal |
| 369 |
* without manual intervention. |
| 370 |
* |
| 371 |
* @param WP_User $user The current user. |
| 372 |
* |
| 373 |
* @return bool Whether the callback URLs may have changed. |
| 374 |
*/ |
| 375 |
private function have_callback_urls_changed( WP_User $user ): bool { |
| 376 |
$registered_hash = $this->user_helper->get_meta( $user->ID, '_yoast_wpseo_ai_generator_callback_url_hash', true ); |
| 377 |
|
| 378 |
if ( ! \is_string( $registered_hash ) || $registered_hash === '' ) { |
| 379 |
return true; |
| 380 |
} |
| 381 |
|
| 382 |
return $registered_hash !== \md5( $this->urls->get_callback_url() ); |
| 383 |
} |
| 384 |
} |
| 385 |
|