Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
98.54% |
203 / 206 |
|
87.50% |
21 / 24 |
CRAP | |
0.00% |
0 / 1 |
| HCaptcha | |
98.54% |
203 / 206 |
|
87.50% |
21 / 24 |
64 | |
0.00% |
0 / 1 |
| __construct | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
1 | |||
| getFormInformation | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
2 | |||
| getCSPUrls | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| addCSPSources | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
2 | |||
| logCheckError | |
100.00% |
14 / 14 |
|
100.00% |
1 / 1 |
3 | |||
| getCaptchaParamsFromRequest | |
100.00% |
9 / 9 |
|
100.00% |
1 / 1 |
1 | |||
| shouldCheck | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
3 | |||
| showEditFormFields | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| setForceShowCaptcha | |
100.00% |
8 / 8 |
|
100.00% |
1 / 1 |
3 | |||
| passCaptcha | |
100.00% |
86 / 86 |
|
100.00% |
1 / 1 |
16 | |||
| addCaptchaAPI | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 | |||
| describeCaptchaType | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
1 | |||
| getMessage | |
88.89% |
8 / 9 |
|
0.00% |
0 / 1 |
5.03 | |||
| getConfirmEditMergedFatalStatusMessageKey | |
66.67% |
2 / 3 |
|
0.00% |
0 / 1 |
2.15 | |||
| apiGetAllowedParams | n/a |
0 / 0 |
n/a |
0 / 0 |
1 | |||||
| getError | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| storeCaptcha | n/a |
0 / 0 |
n/a |
0 / 0 |
1 | |||||
| storeSessionScore | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
2 | |||
| retrieveSessionScore | |
100.00% |
6 / 6 |
|
100.00% |
1 / 1 |
3 | |||
| getScoreCacheKey | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| retrieveCaptcha | n/a |
0 / 0 |
n/a |
0 / 0 |
1 | |||||
| getCaptcha | n/a |
0 / 0 |
n/a |
0 / 0 |
1 | |||||
| createAuthenticationRequest | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| onAuthChangeFormFields | |
100.00% |
12 / 12 |
|
100.00% |
1 / 1 |
2 | |||
| showHelp | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
| getSiteKeyForAction | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
2 | |||
| getAllowedSiteKeysForCurrentAction | |
100.00% |
10 / 10 |
|
100.00% |
1 / 1 |
3 | |||
| getPrimarySiteKey | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
2 | |||
| 1 | <?php |
| 2 | |
| 3 | namespace MediaWiki\Extension\ConfirmEdit\hCaptcha; |
| 4 | |
| 5 | use LogicException; |
| 6 | use MediaWiki\Api\ApiBase; |
| 7 | use MediaWiki\Auth\AuthenticationRequest; |
| 8 | use MediaWiki\Config\Config; |
| 9 | use MediaWiki\Context\RequestContext; |
| 10 | use MediaWiki\EditPage\EditPage; |
| 11 | use MediaWiki\Extension\ConfirmEdit\Auth\CaptchaAuthenticationRequest; |
| 12 | use MediaWiki\Extension\ConfirmEdit\CaptchaTriggers; |
| 13 | use MediaWiki\Extension\ConfirmEdit\hCaptcha\Services\HCaptchaEnterpriseHealthChecker; |
| 14 | use MediaWiki\Extension\ConfirmEdit\hCaptcha\Services\HCaptchaOutput; |
| 15 | use MediaWiki\Extension\ConfirmEdit\Hooks; |
| 16 | use MediaWiki\Extension\ConfirmEdit\SimpleCaptcha\SimpleCaptcha; |
| 17 | use MediaWiki\Json\FormatJson; |
| 18 | use MediaWiki\Language\RawMessage; |
| 19 | use MediaWiki\Logger\LoggerFactory; |
| 20 | use MediaWiki\MediaWikiServices; |
| 21 | use MediaWiki\Output\OutputPage; |
| 22 | use MediaWiki\Page\WikiPage; |
| 23 | use MediaWiki\Request\ContentSecurityPolicy; |
| 24 | use MediaWiki\Request\WebRequest; |
| 25 | use MediaWiki\Session\SessionManager; |
| 26 | use MediaWiki\Status\Status; |
| 27 | use MediaWiki\User\UserIdentity; |
| 28 | use Psr\Log\LoggerInterface; |
| 29 | use Wikimedia\ObjectCache\BagOStuff; |
| 30 | use Wikimedia\Stats\StatsFactory; |
| 31 | |
| 32 | class HCaptcha extends SimpleCaptcha { |
| 33 | /** |
| 34 | * @var string used for hcaptcha-edit, hcaptcha-addurl, hcaptcha-badlogin, hcaptcha-createaccount, |
| 35 | * hcaptcha-create, hcaptcha-sendemail via getMessage() |
| 36 | */ |
| 37 | protected static $messagePrefix = 'hcaptcha'; |
| 38 | |
| 39 | /** @var string|null */ |
| 40 | private $error = null; |
| 41 | |
| 42 | private ?bool $result = null; |
| 43 | |
| 44 | private Config $hCaptchaConfig; |
| 45 | private HCaptchaOutput $hCaptchaOutput; |
| 46 | private StatsFactory $statsFactory; |
| 47 | private LoggerInterface $logger; |
| 48 | private HCaptchaEnterpriseHealthChecker $healthChecker; |
| 49 | private BagOStuff $scoreCache; |
| 50 | |
| 51 | private const SCORE_CACHE_TTL = 300; |
| 52 | |
| 53 | public function __construct() { |
| 54 | $services = MediaWikiServices::getInstance(); |
| 55 | $this->hCaptchaConfig = $services->getMainConfig(); |
| 56 | $this->hCaptchaOutput = $services->get( 'HCaptchaOutput' ); |
| 57 | $this->statsFactory = $services->getStatsFactory(); |
| 58 | $this->healthChecker = $services->get( 'HCaptchaEnterpriseHealthChecker' ); |
| 59 | $this->logger = LoggerFactory::getInstance( 'captcha' ); |
| 60 | $this->scoreCache = $services->getObjectCacheFactory()->getLocalClusterInstance(); |
| 61 | } |
| 62 | |
| 63 | /** @inheritDoc */ |
| 64 | public function getFormInformation( $tabIndex = 1, ?OutputPage $out = null ) { |
| 65 | if ( $out === null ) { |
| 66 | $out = RequestContext::getMain()->getOutput(); |
| 67 | } |
| 68 | |
| 69 | return [ |
| 70 | 'html' => $this->hCaptchaOutput->addHCaptchaToForm( $out, (bool)$this->error ), |
| 71 | ]; |
| 72 | } |
| 73 | |
| 74 | /** @inheritDoc */ |
| 75 | public static function getCSPUrls() { |
| 76 | return RequestContext::getMain()->getConfig()->get( 'HCaptchaCSPRules' ); |
| 77 | } |
| 78 | |
| 79 | /** @inheritDoc */ |
| 80 | public static function addCSPSources( ContentSecurityPolicy $csp ) { |
| 81 | foreach ( static::getCSPUrls() as $src ) { |
| 82 | // Since frame-src is not supported |
| 83 | $csp->addDefaultSrc( $src ); |
| 84 | $csp->addScriptSrc( $src ); |
| 85 | $csp->addStyleSrc( $src ); |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | protected function logCheckError( Status|array|string $info, UserIdentity $userIdentity, string $token ): void { |
| 90 | if ( $info instanceof Status ) { |
| 91 | $errors = $info->getErrorsArray(); |
| 92 | $error = $errors[0][0]; |
| 93 | } elseif ( is_array( $info ) ) { |
| 94 | $error = implode( ',', $info ); |
| 95 | } else { |
| 96 | $error = $info; |
| 97 | } |
| 98 | |
| 99 | $this->logger->error( 'Unable to validate response. Error: {error}', [ |
| 100 | 'error' => $error, |
| 101 | 'user' => $userIdentity->getName(), |
| 102 | 'captcha_type' => self::$messagePrefix, |
| 103 | 'captcha_action' => $this->action ?? '-', |
| 104 | 'captcha_trigger' => $this->trigger ?? '-', |
| 105 | 'hcaptcha_token' => $token, |
| 106 | ] + RequestContext::getMain()->getRequest()->getSecurityLogContext( $userIdentity ) ); |
| 107 | } |
| 108 | |
| 109 | /** @inheritDoc */ |
| 110 | protected function getCaptchaParamsFromRequest( WebRequest $request ) { |
| 111 | $response = $request->getVal( |
| 112 | 'h-captcha-response', |
| 113 | // This is sad, but apparently all of these are valid |
| 114 | $request->getVal( 'captchaWord', |
| 115 | $request->getVal( 'captchaword', |
| 116 | $request->getVal( 'wpCaptchaWord' ) |
| 117 | ) |
| 118 | ) |
| 119 | ); |
| 120 | return [ '', $response ]; |
| 121 | } |
| 122 | |
| 123 | /** @inheritDoc */ |
| 124 | public function shouldCheck( WikiPage $page, $content, $section, $context, $oldtext = null ) { |
| 125 | // If the "showcaptcha" consequence has been invoked by AbuseFilter, and we have |
| 126 | // already attempted to verify the token, return early. This ensures that we're |
| 127 | // only going to verify the token once, because shouldCheck is invoked once in the EditFilterMergedContent |
| 128 | // hook by AbuseFilter, and once by ConfirmEdit |
| 129 | if ( $context->getRequest()->getVal( 'wgConfirmEditForceShowCaptcha' ) && |
| 130 | $this->result !== null ) { |
| 131 | return false; |
| 132 | } |
| 133 | return parent::shouldCheck( $page, $content, $section, $context, $oldtext ); |
| 134 | } |
| 135 | |
| 136 | /** |
| 137 | * Don't render hCaptcha form field at the top of the edit form, as we want it to be only |
| 138 | * ever at the bottom of the page. |
| 139 | * |
| 140 | * The default behaviour is to render the form fields both at the top and bottom of the edit field |
| 141 | * when in a 'addurl' trigger (which causes issues because we can only have one hCaptcha widget on the page). |
| 142 | * |
| 143 | * @inheritDoc |
| 144 | */ |
| 145 | public function showEditFormFields( EditPage $editPage, OutputPage $out ) { |
| 146 | } |
| 147 | |
| 148 | /** |
| 149 | * Sets the value returned by {@link self::shouldForceShowCaptcha}. |
| 150 | * |
| 151 | * Additionally, for edits with the flag set to true, the JS configuration |
| 152 | * variable wgHCaptchaTriggerFormSubmission is set cause the frontend |
| 153 | * to immediately submit the form. That is done to avoid the user needing to |
| 154 | * resubmit the form when an AbuseFilter requires a different site key to be |
| 155 | * used for the edit. |
| 156 | * |
| 157 | * @inheritDoc |
| 158 | */ |
| 159 | public function setForceShowCaptcha( bool $forceShowCaptcha ): void { |
| 160 | parent::setForceShowCaptcha( $forceShowCaptcha ); |
| 161 | |
| 162 | $isPageSubmission = in_array( $this->action, [ 'edit', 'create' ] ); |
| 163 | |
| 164 | if ( $isPageSubmission && $forceShowCaptcha ) { |
| 165 | $output = RequestContext::getMain()->getOutput(); |
| 166 | $output->addJsConfigVars( |
| 167 | 'wgHCaptchaTriggerFormSubmission', |
| 168 | true |
| 169 | ); |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | /** |
| 174 | * Check, if the user solved the captcha. |
| 175 | * |
| 176 | * Based on reference implementation: |
| 177 | * https://github.com/google/recaptcha#php and https://docs.hcaptcha.com/ |
| 178 | * |
| 179 | * @param mixed $_ Not used |
| 180 | * @param null|string $token token from the POST data |
| 181 | * @param UserIdentity $user |
| 182 | * @return bool |
| 183 | */ |
| 184 | protected function passCaptcha( $_, $token, $user ) { |
| 185 | $webRequest = RequestContext::getMain()->getRequest(); |
| 186 | // If we have a result, "showcaptcha" consequence has been invoked, but the submission |
| 187 | // is in the context of a request where the user wasn't yet required to complete a CAPTCHA, |
| 188 | // then return false to avoid making a duplicate API request, and to ensure that the user |
| 189 | // has to complete the "always challenge" CAPTCHA. |
| 190 | if ( $this->result && |
| 191 | $this->shouldForceShowCaptcha() && |
| 192 | $webRequest->getVal( 'wgConfirmEditForceShowCaptcha' ) === null ) { |
| 193 | // Set an error here, so that the page will display an appropriate |
| 194 | // message for the user to resubmit the form. |
| 195 | $this->error = 'forceshowcaptcha'; |
| 196 | return false; |
| 197 | } |
| 198 | |
| 199 | if ( !$token ) { |
| 200 | $this->error = 'missing-token'; |
| 201 | $this->logger->warning( |
| 202 | 'No hCaptcha token present in the request; skipping siteverify call.', |
| 203 | [ |
| 204 | 'error' => $this->error, |
| 205 | 'user' => $user->getName(), |
| 206 | 'captcha_type' => self::$messagePrefix, |
| 207 | 'captcha_action' => $this->action ?? '-', |
| 208 | 'captcha_trigger' => $this->trigger ?? '-', |
| 209 | ] + $webRequest->getSecurityLogContext( $user ) |
| 210 | ); |
| 211 | return false; |
| 212 | } |
| 213 | $data = [ |
| 214 | 'secret' => $this->hCaptchaConfig->get( 'HCaptchaSecretKey' ), |
| 215 | 'response' => $token, |
| 216 | ]; |
| 217 | $data['remoteip'] = '127.0.0.1'; |
| 218 | if ( $this->hCaptchaConfig->get( 'HCaptchaSendRemoteIP' ) ) { |
| 219 | $data['remoteip'] = $webRequest->getIP(); |
| 220 | } |
| 221 | |
| 222 | $options = [ |
| 223 | 'method' => 'POST', |
| 224 | 'postData' => $data, |
| 225 | 'timeout' => 5, |
| 226 | ]; |
| 227 | |
| 228 | $proxy = $this->hCaptchaConfig->get( 'HCaptchaProxy' ); |
| 229 | if ( $proxy ) { |
| 230 | $options['proxy'] = $proxy; |
| 231 | } |
| 232 | |
| 233 | $request = MediaWikiServices::getInstance()->getHttpRequestFactory() |
| 234 | ->create( $this->hCaptchaConfig->get( 'HCaptchaVerifyUrl' ), $options, __METHOD__ ); |
| 235 | |
| 236 | $timer = $this->statsFactory->withComponent( 'ConfirmEdit' ) |
| 237 | ->getTiming( 'hcaptcha_siteverify_call' ) |
| 238 | ->start(); |
| 239 | |
| 240 | $status = $request->execute(); |
| 241 | |
| 242 | $timer |
| 243 | ->setLabel( 'status', $status->isOK() ? 'ok' : 'failed' ) |
| 244 | ->stop(); |
| 245 | |
| 246 | if ( !$status->isOK() ) { |
| 247 | $this->error = 'http'; |
| 248 | $this->healthChecker->incrementSiteVerifyApiErrorCount(); |
| 249 | $this->logCheckError( $status, $user, $token ); |
| 250 | return false; |
| 251 | } |
| 252 | $json = FormatJson::decode( $request->getContent(), true ); |
| 253 | if ( !$json ) { |
| 254 | $this->error = 'json'; |
| 255 | $this->healthChecker->incrementSiteVerifyApiErrorCount(); |
| 256 | $this->logCheckError( $this->error, $user, $token ); |
| 257 | return false; |
| 258 | } |
| 259 | if ( isset( $json['error-codes'] ) ) { |
| 260 | $this->error = 'hcaptcha-api'; |
| 261 | $this->logCheckError( $json['error-codes'], $user, $token ); |
| 262 | return false; |
| 263 | } |
| 264 | |
| 265 | // Verify that the sitekey is among those allowed in order to prevent |
| 266 | // client-side tampering (T410024, T410657). |
| 267 | $siteKeyUsed = $json['sitekey'] ?? null; |
| 268 | |
| 269 | if ( !in_array( $siteKeyUsed, $this->getAllowedSiteKeysForCurrentAction() ) ) { |
| 270 | $this->error = 'sitekey-mismatch'; |
| 271 | $this->logCheckError( $this->error, $user, $token ); |
| 272 | return false; |
| 273 | } |
| 274 | |
| 275 | $debugLogContext = [ |
| 276 | 'event' => 'captcha.solve', |
| 277 | 'user' => $user->getName(), |
| 278 | 'hcaptcha_success' => $json['success'], |
| 279 | 'hcaptcha_token' => $token, |
| 280 | 'captcha_type' => self::$messagePrefix, |
| 281 | 'success_message' => $json['success'] ? 'Successful' : 'Failed', |
| 282 | 'captcha_action' => $this->action ?? '-', |
| 283 | 'captcha_trigger' => $this->trigger ?? '-', |
| 284 | 'hcaptcha_response_sitekey' => $json['sitekey'] ?? '-', |
| 285 | ] + $webRequest->getSecurityLogContext( $user ); |
| 286 | if ( $this->hCaptchaConfig->get( 'HCaptchaDeveloperMode' ) ) { |
| 287 | $debugLogContext = array_merge( [ |
| 288 | 'hcaptcha_score' => $json['score'] ?? null, |
| 289 | 'hcaptcha_score_reason' => $json['score_reason'] ?? null, |
| 290 | 'hcaptcha_blob' => $json, |
| 291 | ], $debugLogContext ); |
| 292 | } |
| 293 | $this->logger->info( '{success_message} captcha solution attempt for {user}', $debugLogContext ); |
| 294 | |
| 295 | if ( $this->hCaptchaConfig->get( 'HCaptchaDeveloperMode' ) |
| 296 | || $this->hCaptchaConfig->get( 'HCaptchaUseRiskScore' ) ) { |
| 297 | // T398333 |
| 298 | $this->storeSessionScore( 'hCaptcha-score', $json['score'] ?? null, $user->getName() ); |
| 299 | } |
| 300 | $this->result = $json['success']; |
| 301 | return $json['success']; |
| 302 | } |
| 303 | |
| 304 | /** @inheritDoc */ |
| 305 | protected function addCaptchaAPI( &$resultArr ) { |
| 306 | $resultArr['captcha'] = $this->describeCaptchaType( $this->action ); |
| 307 | $resultArr['captcha']['error'] = $this->error; |
| 308 | } |
| 309 | |
| 310 | /** @inheritDoc */ |
| 311 | public function describeCaptchaType( ?string $action = null ) { |
| 312 | return [ |
| 313 | 'type' => 'hcaptcha', |
| 314 | 'mime' => 'application/javascript', |
| 315 | 'key' => $this->getConfig()['HCaptchaSiteKey'] ?? $this->hCaptchaConfig->get( 'HCaptchaSiteKey' ), |
| 316 | ]; |
| 317 | } |
| 318 | |
| 319 | /** @inheritDoc */ |
| 320 | public function getMessage( $action ) { |
| 321 | if ( $this->error ) { |
| 322 | if ( $this->shouldForceShowCaptcha() && |
| 323 | in_array( $action, [ CaptchaTriggers::EDIT, CaptchaTriggers::CREATE ] ) ) { |
| 324 | $msg = wfMessage( 'hcaptcha-force-show-captcha-edit' ); |
| 325 | } else { |
| 326 | $msg = parent::getMessage( $action ); |
| 327 | } |
| 328 | return new RawMessage( '<div class="error">$1</div>', [ $msg ] ); |
| 329 | } |
| 330 | |
| 331 | // For edit action, hide the prompt if there's no error |
| 332 | if ( $action === CaptchaTriggers::EDIT ) { |
| 333 | return new RawMessage( '' ); |
| 334 | } |
| 335 | |
| 336 | return parent::getMessage( $action ); |
| 337 | } |
| 338 | |
| 339 | /** @inheritDoc */ |
| 340 | protected function getConfirmEditMergedFatalStatusMessageKey(): null|string { |
| 341 | if ( !$this->shouldForceShowCaptcha() ) { |
| 342 | return parent::getConfirmEditMergedFatalStatusMessageKey(); |
| 343 | } |
| 344 | |
| 345 | // If the hCaptcha captcha is being force shown, then this may cause the user to have to submit the form |
| 346 | // twice (so that the second attempt always shows a challenge). In this case, we need a clear message |
| 347 | // to show that the user needs to press submit again. |
| 348 | return 'hcaptcha-force-show-captcha-edit'; |
| 349 | } |
| 350 | |
| 351 | /** |
| 352 | * @inheritDoc |
| 353 | * @codeCoverageIgnore Merely declarative |
| 354 | */ |
| 355 | public function apiGetAllowedParams( ApiBase $module, &$params, $flags ) { |
| 356 | return true; |
| 357 | } |
| 358 | |
| 359 | /** @inheritDoc */ |
| 360 | public function getError() { |
| 361 | return $this->error; |
| 362 | } |
| 363 | |
| 364 | /** |
| 365 | * @inheritDoc |
| 366 | * @codeCoverageIgnore Merely declarative |
| 367 | */ |
| 368 | public function storeCaptcha( $info ) { |
| 369 | // hCaptcha is stored externally, the ID will be generated at that time as well, and |
| 370 | // the one returned here won't be used. Just pretend this worked. |
| 371 | return 'not used'; |
| 372 | } |
| 373 | |
| 374 | /** |
| 375 | * Store risk score in global session. If a username is provided, the score will be |
| 376 | * also recorded in the cache, so that any jobs can read from it. |
| 377 | * @param string $sessionKey |
| 378 | * @param mixed $score |
| 379 | * @param string|null $userName |
| 380 | * @return void |
| 381 | */ |
| 382 | public function storeSessionScore( $sessionKey, $score, $userName = null ) { |
| 383 | SessionManager::getGlobalSession()->set( $sessionKey, $score ); |
| 384 | if ( $userName !== null ) { |
| 385 | $this->scoreCache->set( |
| 386 | $this->getScoreCacheKey( $sessionKey, $userName ), |
| 387 | $score, |
| 388 | self::SCORE_CACHE_TTL |
| 389 | ); |
| 390 | } |
| 391 | } |
| 392 | |
| 393 | /** |
| 394 | * Retrieve session score from global session. If a username is provided, it will attempt |
| 395 | * to read the score from the cache, if it's not present in the session. |
| 396 | * |
| 397 | * @stable to call - This may be used by code not visible in codesearch |
| 398 | * @param string $sessionKey |
| 399 | * @param string|null $userName |
| 400 | * @return mixed |
| 401 | */ |
| 402 | public function retrieveSessionScore( $sessionKey, $userName = null ) { |
| 403 | $score = SessionManager::getGlobalSession()->get( $sessionKey ); |
| 404 | if ( $score !== null ) { |
| 405 | return $score; |
| 406 | } |
| 407 | if ( $userName !== null ) { |
| 408 | return $this->scoreCache->get( $this->getScoreCacheKey( $sessionKey, $userName ) ); |
| 409 | } |
| 410 | return null; |
| 411 | } |
| 412 | |
| 413 | private function getScoreCacheKey( string $sessionKey, string $userName ): string { |
| 414 | return $this->scoreCache->makeGlobalKey( 'hcaptcha-score', $sessionKey . '-' . $userName ); |
| 415 | } |
| 416 | |
| 417 | /** |
| 418 | * @inheritDoc |
| 419 | * @codeCoverageIgnore Merely declarative |
| 420 | */ |
| 421 | public function retrieveCaptcha( $index ) { |
| 422 | // Just pretend it worked |
| 423 | return [ 'index' => $index ]; |
| 424 | } |
| 425 | |
| 426 | /** |
| 427 | * @inheritDoc |
| 428 | * @codeCoverageIgnore Merely declarative |
| 429 | */ |
| 430 | public function getCaptcha() { |
| 431 | // hCaptcha is handled by frontend code, and an external provider; nothing to do here. |
| 432 | return []; |
| 433 | } |
| 434 | |
| 435 | /** |
| 436 | * @return HCaptchaAuthenticationRequest |
| 437 | */ |
| 438 | public function createAuthenticationRequest() { |
| 439 | return new HCaptchaAuthenticationRequest(); |
| 440 | } |
| 441 | |
| 442 | /** @inheritDoc */ |
| 443 | public function onAuthChangeFormFields( |
| 444 | array $requests, array $fieldInfo, array &$formDescriptor, $action |
| 445 | ) { |
| 446 | /** @var CaptchaAuthenticationRequest $req */ |
| 447 | $req = AuthenticationRequest::getRequestByClass( |
| 448 | $requests, |
| 449 | CaptchaAuthenticationRequest::class, |
| 450 | true |
| 451 | ); |
| 452 | if ( !$req ) { |
| 453 | return; |
| 454 | } |
| 455 | |
| 456 | // ugly way to retrieve error information |
| 457 | $captcha = Hooks::getInstance( $req->getAction() ); |
| 458 | |
| 459 | $formDescriptor['captchaWord'] = [ |
| 460 | 'class' => HTMLHCaptchaField::class, |
| 461 | 'error' => $captcha->getError(), |
| 462 | ] + $formDescriptor['captchaWord']; |
| 463 | } |
| 464 | |
| 465 | /** @inheritDoc */ |
| 466 | public function showHelp( OutputPage $out ) { |
| 467 | $out->addWikiMsg( 'hcaptcha-privacy-policy' ); |
| 468 | } |
| 469 | |
| 470 | /** |
| 471 | * Get the SiteKey for the instance. |
| 472 | * |
| 473 | * This returns a value from the following sources, in order of priority: |
| 474 | * - the HCaptchaAlwaysChallengeSiteKey from $wgCaptchaTriggers for the current action, |
| 475 | * if ::shouldForceShowCaptcha mode is enabled |
| 476 | * - the HCaptchaSiteKey config property from $wgCaptchaTriggers for the current action |
| 477 | * - the global $wgHCaptchaSiteKey |
| 478 | * |
| 479 | * @return string The hCaptcha SiteKey associated with this instance |
| 480 | */ |
| 481 | public function getSiteKeyForAction(): string { |
| 482 | $siteKey = $this->getPrimarySiteKey(); |
| 483 | if ( $this->shouldForceShowCaptcha() ) { |
| 484 | $siteKey = $this->getConfig()['HCaptchaAlwaysChallengeSiteKey'] ?? $siteKey; |
| 485 | } |
| 486 | |
| 487 | return $siteKey; |
| 488 | } |
| 489 | |
| 490 | /** |
| 491 | * Get a list of allowed SiteKeys for the current action. |
| 492 | * |
| 493 | * If Always Challenge Mode is enabled and HCaptchaAlwaysChallengeSiteKey is set, |
| 494 | * this method returns an array containing only that key. If Always Challenge |
| 495 | * Mode is enabled but HCaptchaAlwaysChallengeSiteKey is not set, this method |
| 496 | * falls back to normal mode behavior (primary key plus additional keys). |
| 497 | * |
| 498 | * Otherwise, this returns a list containing the primary SiteKey for the current |
| 499 | * action plus any additional key provided under the HCaptchaAdditionalValidSiteKeys |
| 500 | * configuration key for the current action. |
| 501 | * |
| 502 | * @return string[] A list of allowed hCaptcha SiteKeys allowed for this instance |
| 503 | */ |
| 504 | private function getAllowedSiteKeysForCurrentAction(): array { |
| 505 | $triggerConfig = $this->getConfig(); |
| 506 | |
| 507 | // In Always Challenge Mode, return only the Always Challenge SiteKey if set. |
| 508 | // If not set, fallback to normal mode behavior to avoid unexpected edge cases. |
| 509 | if ( $this->shouldForceShowCaptcha() ) { |
| 510 | if ( isset( $triggerConfig['HCaptchaAlwaysChallengeSiteKey'] ) ) { |
| 511 | return [ $triggerConfig['HCaptchaAlwaysChallengeSiteKey'] ]; |
| 512 | } |
| 513 | // Fall through to normal mode behavior |
| 514 | } |
| 515 | |
| 516 | // For normal mode, return the primary SiteKey for the current action |
| 517 | // as well as any additional keys listed as valid for it. |
| 518 | $allowedKeys = array_merge( |
| 519 | // Use getPrimarySiteKey() which handles fallback to global config |
| 520 | [ $this->getPrimarySiteKey() ], |
| 521 | // Include HCaptchaAlwaysChallengeSiteKey, because the second POST |
| 522 | // after an AbuseFilter challenge will be using this SiteKey |
| 523 | [ $triggerConfig['HCaptchaAlwaysChallengeSiteKey'] ?? '' ], |
| 524 | // Retrieve any additional key listed as allowed for the requested action |
| 525 | // (i.e. those at self::getConfig()['HCaptchaAdditionalValidSiteKeys']). |
| 526 | $triggerConfig['HCaptchaAdditionalValidSiteKeys'] ?? [] |
| 527 | ); |
| 528 | |
| 529 | // Remove duplicates and empty values, if any |
| 530 | return array_values( array_filter( array_unique( $allowedKeys ) ) ); |
| 531 | } |
| 532 | |
| 533 | /** |
| 534 | * Returns the hCaptcha primary SiteKey to be used by this instance. |
| 535 | * |
| 536 | * The primary SiteKey is either the value for HCaptchaSiteKey set in the |
| 537 | * trigger config for the current action or, if not set or empty, the HCaptchaSiteKey |
| 538 | * set in the root-level configuration. |
| 539 | * |
| 540 | * @return string |
| 541 | */ |
| 542 | private function getPrimarySiteKey(): string { |
| 543 | $key = $this->getConfig()['HCaptchaSiteKey'] ?? |
| 544 | $this->hCaptchaConfig->get( 'HCaptchaSiteKey' ); |
| 545 | |
| 546 | if ( $key === null ) { |
| 547 | throw new LogicException( 'wgHCaptchaSiteKey is not set' ); |
| 548 | } |
| 549 | |
| 550 | return $key; |
| 551 | } |
| 552 | } |