PluginProbe
Yoast SEO – Advanced SEO with real-time guidance and built-in AI / 27.5
Yoast SEO – Advanced SEO with real-time guidance and built-in AI v27.5
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 27.5, at src/ai/authorization/application/token-manager.php

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