Debian Codegraph @

extensions/ConfirmEdit/hCaptcha/includes/HCaptcha.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Extension\ConfirmEdit\hCaptcha;
4
5 use MediaWiki\Api\ApiBase;
6 use MediaWiki\Auth\AuthenticationRequest;
7 use MediaWiki\Config\Config;
8 use MediaWiki\Context\RequestContext;
9 use MediaWiki\Extension\ConfirmEdit\Auth\CaptchaAuthenticationRequest;
10 use MediaWiki\Extension\ConfirmEdit\Hooks;
11 use MediaWiki\Extension\ConfirmEdit\SimpleCaptcha\SimpleCaptcha;
12 use MediaWiki\Html\Html;
13 use MediaWiki\Json\FormatJson;
14 use MediaWiki\Language\RawMessage;
15 use MediaWiki\MediaWikiServices;
16 use MediaWiki\Message\Message;
17 use MediaWiki\Request\ContentSecurityPolicy;
18 use MediaWiki\Request\WebRequest;
19 use MediaWiki\Status\Status;
20
21 class HCaptcha extends SimpleCaptcha {
22 /**
23 * @var string used for hcaptcha-edit, hcaptcha-addurl, hcaptcha-badlogin, hcaptcha-createaccount,
24 * hcaptcha-create, hcaptcha-sendemail via getMessage()
25 */
26 protected static $messagePrefix = 'hcaptcha-';
27
28 /** @var string|null */
29 private $error = null;
30
31 /** @var Config */
32 private $hCaptchaConfig;
33
34 /** @var string */
35 private $siteKey;
36
37 public function __construct() {
38 $this->hCaptchaConfig = MediaWikiServices::getInstance()->getConfigFactory()
39 ->makeConfig( 'hcaptcha' );
40 $this->siteKey = $this->hCaptchaConfig->get( 'HCaptchaSiteKey' );
41 }
42
43 /**
44 * Get the captcha form.
45 * @param int $tabIndex
46 * @return array
47 */
48 public function getFormInformation( $tabIndex = 1 ) {
49 $output = Html::element( 'div', [
50 'class' => [
51 'h-captcha',
52 'mw-confirmedit-captcha-fail' => (bool)$this->error,
53 ],
54 'data-sitekey' => $this->siteKey
55 ] );
56
57 return [
58 'html' => $output,
59 'headitems' => [
60 "<script src=\"https://hcaptcha.com/1/api.js\" async defer></script>"
61 ]
62 ];
63 }
64
65 /**
66 * @return string[]
67 */
68 public static function getCSPUrls() {
69 return [ 'https://hcaptcha.com', 'https://*.hcaptcha.com' ];
70 }
71
72 /**
73 * Adds the CSP policies necessary for the captcha module to work in a CSP enforced
74 * setup.
75 *
76 * @param ContentSecurityPolicy $csp The CSP instance to add the policies to, usually
77 * obtained from {@link OutputPage::getCSP()}
78 */
79 public static function addCSPSources( ContentSecurityPolicy $csp ) {
80 foreach ( static::getCSPUrls() as $src ) {
81 // Since frame-src is not supported
82 $csp->addDefaultSrc( $src );
83 $csp->addScriptSrc( $src );
84 $csp->addStyleSrc( $src );
85 }
86 }
87
88 /**
89 * @param Status|array|string $info
90 */
91 protected function logCheckError( $info ) {
92 if ( $info instanceof Status ) {
93 $errors = $info->getErrorsArray();
94 $error = $errors[0][0];
95 } elseif ( is_array( $info ) ) {
96 $error = implode( ',', $info );
97 } else {
98 $error = $info;
99 }
100
101 \wfDebugLog( 'captcha', 'Unable to validate response: ' . $error );
102 }
103
104 /**
105 * @param WebRequest $request
106 * @return array
107 */
108 protected function getCaptchaParamsFromRequest( WebRequest $request ) {
109 $response = $request->getVal(
110 'h-captcha-response',
111 $request->getVal( 'captchaWord', $request->getVal( 'captchaword' ) )
112 );
113 return [ '', $response ];
114 }
115
116 /**
117 * Check, if the user solved the captcha.
118 *
119 * Based on reference implementation:
120 * https://github.com/google/recaptcha#php and https://docs.hcaptcha.com/
121 *
122 * @param mixed $_ Not used
123 * @param string $token token from the POST data
124 * @return bool
125 */
126 protected function passCaptcha( $_, $token ) {
127 $webRequest = RequestContext::getMain()->getRequest();
128
129 $secretKey = $this->hCaptchaConfig->get( 'HCaptchaSecretKey' );
130 $sendRemoteIp = $this->hCaptchaConfig->get( 'HCaptchaSendRemoteIP' );
131 $proxy = $this->hCaptchaConfig->get( 'HCaptchaProxy' );
132
133 $url = 'https://hcaptcha.com/siteverify';
134 $data = [
135 'secret' => $secretKey,
136 'response' => $token,
137 ];
138 if ( $sendRemoteIp ) {
139 $data['remoteip'] = $webRequest->getIP();
140 }
141
142 $options = [
143 'method' => 'POST',
144 'postData' => $data,
145 ];
146
147 if ( $proxy ) {
148 $options['proxy'] = $proxy;
149 }
150
151 $request = MediaWikiServices::getInstance()->getHttpRequestFactory()
152 ->create( $url, $options, __METHOD__ );
153
154 $status = $request->execute();
155 if ( !$status->isOK() ) {
156 $this->error = 'http';
157 $this->logCheckError( $status );
158 return false;
159 }
160 $response = FormatJson::decode( $request->getContent(), true );
161 if ( !$response ) {
162 $this->error = 'json';
163 $this->logCheckError( $this->error );
164 return false;
165 }
166 if ( isset( $response['error-codes'] ) ) {
167 $this->error = 'hcaptcha-api';
168 $this->logCheckError( $response['error-codes'] );
169 return false;
170 }
171
172 return $response['success'];
173 }
174
175 /**
176 * @param array &$resultArr
177 */
178 protected function addCaptchaAPI( &$resultArr ) {
179 $resultArr['captcha'] = $this->describeCaptchaType();
180 $resultArr['captcha']['error'] = $this->error;
181 }
182
183 /**
184 * @return array
185 */
186 public function describeCaptchaType() {
187 return [
188 'type' => 'hcaptcha',
189 'mime' => 'application/javascript',
190 'key' => $this->siteKey,
191 ];
192 }
193
194 /**
195 * Show a message asking the user to enter a captcha on edit
196 * The result will be treated as wiki text
197 *
198 * @param string $action Action being performed
199 * @return Message
200 */
201 public function getMessage( $action ) {
202 $msg = parent::getMessage( $action );
203 if ( $this->error ) {
204 $msg = new RawMessage( '<div class="error">$1</div>', [ $msg ] );
205 }
206 return $msg;
207 }
208
209 /**
210 * @param ApiBase $module
211 * @param array &$params
212 * @param int $flags
213 * @return bool
214 */
215 public function apiGetAllowedParams( ApiBase $module, &$params, $flags ) {
216 return true;
217 }
218
219 /**
220 * @inheritDoc
221 */
222 public function getError() {
223 return $this->error;
224 }
225
226 /**
227 * @inheritDoc
228 */
229 public function storeCaptcha( $info ) {
230 // hCaptcha is stored externally, the ID will be generated at that time as well, and
231 // the one returned here won't be used. Just pretend this worked.
232 return 'not used';
233 }
234
235 /**
236 * @inheritDoc
237 */
238 public function retrieveCaptcha( $index ) {
239 // just pretend it worked
240 return [ 'index' => $index ];
241 }
242
243 /**
244 * @inheritDoc
245 */
246 public function getCaptcha() {
247 // hCaptcha is handled by frontend code + an external provider; nothing to do here.
248 return [];
249 }
250
251 /**
252 * @return HCaptchaAuthenticationRequest
253 */
254 public function createAuthenticationRequest() {
255 return new HCaptchaAuthenticationRequest();
256 }
257
258 /**
259 * @param array $requests
260 * @param array $fieldInfo
261 * @param array &$formDescriptor
262 * @param string $action
263 */
264 public function onAuthChangeFormFields(
265 array $requests, array $fieldInfo, array &$formDescriptor, $action
266 ) {
267 $req = AuthenticationRequest::getRequestByClass(
268 $requests,
269 CaptchaAuthenticationRequest::class,
270 true
271 );
272 if ( !$req ) {
273 return;
274 }
275
276 // ugly way to retrieve error information
277 $captcha = Hooks::getInstance();
278
279 $formDescriptor['captchaWord'] = [
280 'class' => HTMLHCaptchaField::class,
281 'key' => $this->siteKey,
282 'error' => $captcha->getError(),
283 ] + $formDescriptor['captchaWord'];
284 }
285 }