Debian Codegraph @

extensions/ConfirmEdit/Turnstile/includes/Turnstile.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Extension\ConfirmEdit\Turnstile;
4
5 use MediaWiki\Api\ApiBase;
6 use MediaWiki\Auth\AuthenticationRequest;
7 use MediaWiki\Extension\ConfirmEdit\Auth\CaptchaAuthenticationRequest;
8 use MediaWiki\Extension\ConfirmEdit\Hooks;
9 use MediaWiki\Extension\ConfirmEdit\SimpleCaptcha\SimpleCaptcha;
10 use MediaWiki\Html\Html;
11 use MediaWiki\Json\FormatJson;
12 use MediaWiki\Language\RawMessage;
13 use MediaWiki\MediaWikiServices;
14 use MediaWiki\Message\Message;
15 use MediaWiki\Request\WebRequest;
16 use MediaWiki\Status\Status;
17
18 class Turnstile extends SimpleCaptcha {
19 /**
20 * @var string used for turnstile-edit, turnstile-addurl, turnstile-badlogin, turnstile-createaccount,
21 * turnstile-create, turnstile-sendemail via getMessage()
22 */
23 protected static $messagePrefix = 'turnstile-';
24
25 /** @var string|null */
26 private $error = null;
27
28 /**
29 * Get the captcha form.
30 * @param int $tabIndex
31 * @return array
32 */
33 public function getFormInformation( $tabIndex = 1 ) {
34 global $wgTurnstileSiteKey, $wgLang;
35 $lang = htmlspecialchars( urlencode( $wgLang->getCode() ) );
36
37 $output = Html::element( 'div', [
38 'class' => [
39 'cf-turnstile',
40 'mw-confirmedit-captcha-fail' => (bool)$this->error,
41 ],
42 'data-sitekey' => $wgTurnstileSiteKey
43 ] );
44 return [
45 'html' => $output,
46 'headitems' => [
47 // Insert Turnstile script, in display language, if available.
48 // Language falls back to the browser's display language.
49 // See https://developers.cloudflare.com/turnstile/reference/supported-languages/
50 "<script src=\"https://challenges.cloudflare.com/turnstile/v0/api.js?language={$lang}\" async defer>
51 </script>"
52 ]
53 ];
54 }
55
56 /**
57 * @return string[]
58 */
59 public static function getCSPUrls() {
60 return [ 'https://challenges.cloudflare.com/turnstile/v0/api.js' ];
61 }
62
63 /**
64 * @param Status|array|string $info
65 */
66 protected function logCheckError( $info ) {
67 if ( $info instanceof Status ) {
68 $errors = $info->getErrorsArray();
69 $error = $errors[0][0];
70 } elseif ( is_array( $info ) ) {
71 $error = implode( ',', $info );
72 } else {
73 $error = $info;
74 }
75
76 wfDebugLog( 'captcha', 'Unable to validate response: ' . $error );
77 }
78
79 /**
80 * @param WebRequest $request
81 * @return array
82 */
83 protected function getCaptchaParamsFromRequest( WebRequest $request ) {
84 // Turnstile combines captcha ID + solution into a single value
85 // API is hardwired to return captchaWord, so use that if the standard isempty
86 // "captchaWord" is sent as "captchaword" by visual editor
87 $index = 'not used';
88 $response = $request->getVal(
89 'cf-turnstile-response',
90 $request->getVal( 'captchaWord', $request->getVal( 'captchaword' ) )
91 );
92 return [ $index, $response ];
93 }
94
95 /**
96 * Check if the user solved the captcha.
97 *
98 * Based on reference implementation:
99 * https://developers.cloudflare.com/turnstile/get-started/server-side-validation/
100 *
101 * @param mixed $_ Not used
102 * @param string $word captcha solution
103 * @return bool
104 */
105 protected function passCaptcha( $_, $word ) {
106 global $wgRequest, $wgTurnstileSecretKey, $wgTurnstileSendRemoteIP;
107
108 $url = 'https://challenges.cloudflare.com/turnstile/v0/siteverify';
109 // Build data to append to request
110 $data = [
111 'secret' => $wgTurnstileSecretKey,
112 'response' => $word,
113 ];
114 if ( $wgTurnstileSendRemoteIP ) {
115 $data['remoteip'] = $wgRequest->getIP();
116 }
117 $request = MediaWikiServices::getInstance()->getHttpRequestFactory()
118 ->create( $url, [ 'method' => 'POST' ], __METHOD__ );
119 $request->setData( $data );
120 $status = $request->execute();
121 if ( !$status->isOK() ) {
122 $this->error = 'http';
123 $this->logCheckError( $status );
124 return false;
125 }
126 $response = FormatJson::decode( $request->getContent(), true );
127 if ( !$response ) {
128 $this->error = 'json';
129 $this->logCheckError( $this->error );
130 return false;
131 }
132 // Turnstile always returns the "error-codes" array, so we should just
133 // check whether it is empty or not.
134 if ( !empty( $response['error-codes'] ) ) {
135 $this->error = 'turnstile-api';
136 $this->logCheckError( $response['error-codes'] );
137 return false;
138 }
139
140 return $response['success'];
141 }
142
143 /**
144 * @param array &$resultArr
145 */
146 protected function addCaptchaAPI( &$resultArr ) {
147 $resultArr['captcha'] = $this->describeCaptchaType();
148 $resultArr['captcha']['error'] = $this->error;
149 }
150
151 /**
152 * @return array
153 */
154 public function describeCaptchaType() {
155 global $wgTurnstileSiteKey;
156 return [
157 'type' => 'turnstile',
158 'mime' => 'application/javascript',
159 'key' => $wgTurnstileSiteKey,
160 ];
161 }
162
163 /**
164 * Show a message asking the user to enter a captcha on edit
165 * The result will be treated as wiki text
166 *
167 * @param string $action Action being performed
168 * @return Message
169 */
170 public function getMessage( $action ) {
171 $msg = parent::getMessage( $action );
172 if ( $this->error ) {
173 $msg = new RawMessage( '<div class="error">$1</div>', [ $msg ] );
174 }
175 return $msg;
176 }
177
178 /**
179 * @param ApiBase $module
180 * @param array &$params
181 * @param int $flags
182 * @return bool
183 */
184 public function apiGetAllowedParams( ApiBase $module, &$params, $flags ) {
185 if ( $flags && $this->isAPICaptchaModule( $module ) ) {
186 $params['cf-turnstile-response'] = [
187 ApiBase::PARAM_HELP_MSG => 'turnstile-apihelp-param-cf-turnstile-response',
188 ];
189 }
190
191 return true;
192 }
193
194 /**
195 * @inheritDoc
196 */
197 public function getError() {
198 return $this->error;
199 }
200
201 /**
202 * @inheritDoc
203 */
204 public function storeCaptcha( $info ) {
205 return 'not used';
206 }
207
208 /**
209 * @inheritDoc
210 */
211 public function retrieveCaptcha( $index ) {
212 // just pretend it worked
213 return [ 'index' => $index ];
214 }
215
216 /**
217 * @inheritDoc
218 */
219 public function getCaptcha() {
220 // Turnstile is handled by frontend code + an external provider; nothing to do here.
221 return [];
222 }
223
224 /**
225 * @return TurnstileAuthenticationRequest
226 */
227 public function createAuthenticationRequest() {
228 return new TurnstileAuthenticationRequest();
229 }
230
231 /**
232 * @param array $requests
233 * @param array $fieldInfo
234 * @param array &$formDescriptor
235 * @param string $action
236 */
237 public function onAuthChangeFormFields(
238 array $requests, array $fieldInfo, array &$formDescriptor, $action
239 ) {
240 global $wgTurnstileSiteKey;
241
242 $req = AuthenticationRequest::getRequestByClass( $requests,
243 CaptchaAuthenticationRequest::class, true );
244 if ( !$req ) {
245 return;
246 }
247
248 // ugly way to retrieve error information
249 $captcha = Hooks::getInstance();
250
251 $formDescriptor['captchaWord'] = [
252 'class' => HTMLTurnstileField::class,
253 'key' => $wgTurnstileSiteKey,
254 'error' => $captcha->getError(),
255 ] + $formDescriptor['captchaWord'];
256 }
257 }