PluginProbe
Yoast SEO – Advanced SEO with real-time guidance and built-in AI / 28.3
Yoast SEO – Advanced SEO with real-time guidance and built-in AI v28.3
28.5 28.4 28.3 28.2 28.1 28.0 27.9 27.8 27.7 27.6 27.5 trunk 18.0 18.1 18.2 18.3 18.4 18.4.1 18.5 18.5.1 18.6 18.7 18.8 18.9 19.0 All 129 releases
wordpress-seo / src / ai-authorization / application / token-manager.php

token-manager.php in Yoast SEO – Advanced SEO with real-time guidance and built-in AI 28.3, at src/ai-authorization/application/token-manager.php

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