base_url = rtrim( $base_url, '/' ); $this->api_key = $api_key; $this->plugin_version = $plugin_version; } /** * Client bound to the stored credentials and this plugin's version. * * @return self */ public static function from_settings(): self { return new self( ACCESSIBIT_API_BASE_URL, Accessibit_Settings::get_api_key(), ACCESSIBIT_VERSION ); } /** * Pure builder: the wp_remote_request() args for one call. * * X-AccessiBit-Plugin lets the API tell plugin traffic from other API-key * clients and see which plugin versions are still in the wild. * * `user-agent` is set rather than left to WordPress, which defaults it to * "WordPress/; " and would therefore put the site's own * address on every call we make. readme.txt's External services section * tells users that their WordPress site URL is not transmitted — this is * what makes that true. Overriding it here keeps the change to our own * requests; the `http_headers_useragent` filter would reach every other * plugin's traffic too. The version still travels, in X-AccessiBit-Plugin. * * @param string $method HTTP verb. * @param array|null $body Optional JSON-encodable request body. * @return array The args for wp_remote_request(). */ public function request_args( string $method, ?array $body = null ): array { $args = array( 'method' => $method, 'timeout' => 20, // No redirects, where WordPress would allow five. `handle_redirects()` // re-issues the request with the SAME args, and it strips nothing from // `headers` — it tests cookies against the new location and leaves // `Authorization` alone. So a 3xx pointing anywhere would hand this // install's API key to that host. Our own API never redirects, the key // is shown to the administrator exactly once, and `sslverify` is left // at its default so the hop itself is verified; this closes the last // way the token could travel somewhere we did not send it. 'redirection' => 0, 'user-agent' => 'AccessiBit-Plugin/' . $this->plugin_version, 'headers' => array( 'Authorization' => 'Bearer ' . $this->api_key, 'Content-Type' => 'application/json', 'X-AccessiBit-Plugin' => $this->plugin_version, ), ); if ( null !== $body ) { $args['body'] = wp_json_encode( $body ); } return $args; } /** * Pure mapper: (HTTP status, raw body) -> normalized result array. * * @param int $status HTTP status code, or 0 for a network-level error. * @param string $body Raw response body. * @return array{ ok: bool, code?: string, data?: array } */ public function map_response( int $status, string $body ): array { if ( 0 === $status ) { return array( 'ok' => false, 'code' => 'network_error', ); } $decoded = json_decode( $body, true ); if ( $status >= 200 && $status < 300 ) { return array( 'ok' => true, 'data' => is_array( $decoded ) ? $decoded : array(), ); } $code = is_array( $decoded ) && isset( $decoded['error']['code'] ) ? $decoded['error']['code'] : 'request_failed'; return array( 'ok' => false, 'code' => $code, 'data' => is_array( $decoded ) ? $decoded : array(), ); } /** * Make an authenticated HTTP request and return a normalized result. * * @param string $method HTTP verb. * @param string $path Path relative to $base_url (must start with /). * @param array|null $body Optional JSON-encodable request body. * @param int $timeout Seconds to wait; `request_args()`'s 20 by default. * @return array{ ok: bool, code?: string, data?: array } */ private function request( string $method, string $path, ?array $body = null, int $timeout = 0 ): array { $args = $this->request_args( $method, $body ); if ( $timeout > 0 ) { $args['timeout'] = $timeout; } $response = wp_remote_request( $this->base_url . $path, $args ); if ( is_wp_error( $response ) ) { return $this->map_response( 0, '' ); } return $this->map_response( (int) wp_remote_retrieve_response_code( $response ), (string) wp_remote_retrieve_body( $response ) ); } /** * Make an authenticated request and return the status and body as they came. * * For the admin bundle's REST proxy (ACC-404), which hands audit-api's answer * to the browser unchanged: the bundle reads the status (202, 409, 428) and * the nested `error` itself, so `map_response()`'s ok/code summary would * throw away what it needs. * * Both bodies are JSON text, not arrays: decoding into an array and encoding * again turns every empty object into an empty list. `status` is 0 when the * request never got out; `retry_after` is a 429's header. * * @param string $method HTTP verb. * @param string $path Path relative to $base_url (must start with /). * @param string|null $json The request body, JSON-encoded, or null for none. * @param int $timeout Seconds to wait; `request_args()`'s 20 by default. * @return array{ status: int, body: string, retry_after: string } */ public function forward( string $method, string $path, ?string $json = null, int $timeout = 0 ): array { $args = $this->request_args( $method ); if ( null !== $json ) { $args['body'] = $json; } if ( $timeout > 0 ) { $args['timeout'] = $timeout; } $response = wp_remote_request( $this->base_url . $path, $args ); if ( is_wp_error( $response ) ) { return array( 'status' => 0, 'body' => '', 'retry_after' => '', ); } return array( 'status' => (int) wp_remote_retrieve_response_code( $response ), 'body' => (string) wp_remote_retrieve_body( $response ), 'retry_after' => (string) wp_remote_retrieve_header( $response, 'retry-after' ), ); } /** * GET /account — the company and the sites this key can see. * * With a key from the connect flow that is exactly one site, and `scope` * names it. With a legacy pasted key it is every site of the company, which * is why `Accessibit_Admin::match_site()` still exists. * * @param int $timeout Seconds to wait; `request_args()`'s 20 by default. * @return array */ public function account( int $timeout = 0 ): array { return $this->request( 'GET', '/account', null, $timeout ); } /** * POST /connect/exchange — turn a one-time code into this site's API key. * * The ONE call in this client that sends no `Authorization` header, because * it is how the key is obtained in the first place (ACC-402). The code is * the credential: the administrator's browser carried it back from the * dashboard, and it is redeemed from here, server to server, so the key * itself never travels through a browser, a URL or a redirect. * * `site_url` goes with it so the service can check the redeemer is the * install the code was approved for. * * Static, and building its own args rather than going through `request()`: * there is no instance to build yet, and a client constructed with an empty * key would send `Authorization: Bearer ` — a malformed header on the one * route that must not carry one. * * `code_verifier` is the PKCE verifier this install stored when it started * the flow: the service redeems the code only with it, so a code read * from the return URL is worth nothing elsewhere (PR #1162 review). * * @param string $base_url API origin including the version prefix. * @param string $code The one-time code from the approval redirect. * @param string $site_url This WordPress site's own address. * @param string $code_verifier The PKCE verifier stored with the state. * @param string $plugin_version This plugin's version. * @return array{ ok: bool, code?: string, data?: array } */ public static function exchange_code( string $base_url, string $code, string $site_url, string $code_verifier, string $plugin_version = '' ): array { $client = new self( $base_url, '', $plugin_version ); $args = $client->request_args( 'POST' ); // The key is what this call is FOR; there is nothing to authenticate // with, and sending the header empty would look like a failed attempt. unset( $args['headers']['Authorization'] ); $args['body'] = wp_json_encode( self::exchange_payload( $code, $site_url, $code_verifier ) ); $response = wp_remote_request( rtrim( $base_url, '/' ) . '/connect/exchange', $args ); if ( is_wp_error( $response ) ) { return $client->map_response( 0, '' ); } return $client->map_response( (int) wp_remote_retrieve_response_code( $response ), (string) wp_remote_retrieve_body( $response ) ); } /** * The body of POST /connect/exchange. * * @param string $code The one-time code. * @param string $site_url This WordPress site's own address. * @param string $code_verifier The PKCE verifier. * @return array{ code: string, site_url: string, code_verifier: string } */ public static function exchange_payload( string $code, string $site_url, string $code_verifier ): array { return array( 'code' => $code, 'site_url' => $site_url, 'code_verifier' => $code_verifier, ); } /** * DELETE /connection — revoke the key this client is holding. * * Called by Disconnect and, best effort, by `uninstall.php`. A site that * stops using its key should be able to say so: otherwise the only way to * retire one is for an administrator to find it in the dashboard, and a * plugin deleted from a site nobody administers any more never gets that * far. * * Answers 200 either way. `revoked: false` means the stored key was a legacy * company-wide one, which the service deliberately leaves alone — the same * string may be pasted into something else, and disconnecting one site must * not take that down with it. * * @param int $timeout Seconds to wait; `request_args()`'s 20 by default. * @return array{ ok: bool, code?: string, data?: array } */ public function disconnect( int $timeout = 0 ): array { return $this->request( 'DELETE', '/connection', null, $timeout ); } /** * Whether uninstall should revoke the next key (ACC-613). * * It stops after a few revokes in a row went unanswered — a firewall, or * AccessiBit down — rather than at the first, which may only be a blip. * In a web request it also stops once the budget is spent: deleting the * plugin is one request, and a gateway timing it out shows the admin an * error. WP-CLI has no such limit. The keys left are revocable from the * dashboard; the options are already gone. * * Pure, for the unit suite. * * @param int $unanswered Revokes in a row that got no answer. * @param float $elapsed Seconds since the request started. * @param bool $web_request False under WP-CLI. * @return bool */ public static function keep_revoking( int $unanswered, float $elapsed, bool $web_request ): bool { return $unanswered < self::REVOKE_GIVE_UP_AFTER && ( ! $web_request || $elapsed < self::REVOKE_BUDGET ); } /** * The language to ask the scanner for, from a WordPress locale. * * The scanner localizes its issue messages, and sending nothing did not mean * English — the engine's default is Italian, so every admin on earth got * Italian issue text next to an English WCAG reference. The API * narrows whatever it is given to a language it has strings for, so this * passes the locale through and lets it decide. * * A locale is not the site address: `readme.txt`'s External services section * promises that the WordPress site URL is not transmitted, and this keeps * that true. It is disclosed there in its own right. * * @param string $locale A WordPress locale such as `it_IT`, or ''. * @return array A request body, or an empty array to send none. */ public static function language_body( string $locale ): array { return '' === $locale ? array() : array( 'language' => $locale ); } // `run_scan()` (POST /sites/{id}/scans) and `scan_status()` (GET /scans/{id}) // are not here, and their absence is deliberate rather than an oversight: the // paid scan came out of v1 because it spends an audit credit and credits are // retired at launch. Leaving the pair in place would ship a credit-spending // call in every installed copy with nothing calling it. // // Both SERVER routes are gone too, not just these clients. `POST /scans` went // with the credits; `GET /scans/{id}` went because it was the only way to read // a job and `POST /scans` was the only endpoint that ever handed out a job id, // so nothing could reach it. Removed before 1.0.0, while the contract could // still change. They come back in v2 with the screen that needs them. /** * GET /sites/{id}/summary — the site's latest scores. * * @param string $site_id The AccessiBit site to report on. * @return array */ public function summary( string $site_id ): array { return $this->request( 'GET', '/sites/' . rawurlencode( $site_id ) . '/summary' ); } /** * POST /sites/{id}/free-scan — start the domain's one free homepage scan. * * Safe to call more than once. A domain that has already used its free scan * comes back 200 with status "already_used" rather than an error, so the * caller has a single path: start, then read the result. * * @param string $site_id The AccessiBit site whose homepage to scan. * @param string $locale The reader's WordPress locale, for the issue text. * @return array */ public function start_free_scan( string $site_id, string $locale = '' ): array { $body = self::language_body( $locale ); return $this->request( 'POST', '/sites/' . rawurlencode( $site_id ) . '/free-scan', array() === $body ? null : $body ); } /** * GET /sites/{id}/free-scan — progress, and once finished the capped preview. * * The service decides how many issues come back. This client does no * trimming and the admin screen renders whatever arrives: WordPress.org * forbids shipping a plugin that holds back functionality it was given, so * the limit has to live on the server and nowhere else. * * @param string $site_id The AccessiBit site whose free scan to read. * @return array */ public function free_scan( string $site_id ): array { return $this->request( 'GET', '/sites/' . rawurlencode( $site_id ) . '/free-scan' ); } }