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. * * Sends no `Authorization` header, like the emailed-code pair below, 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 through `post_without_key()` rather than `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, status: int, retry_after: int, code?: string, data?: array } */ public static function exchange_code( string $base_url, string $code, string $site_url, string $code_verifier, string $plugin_version = '' ): array { return self::post_without_key( $base_url, '/connect/exchange', self::exchange_payload( $code, $site_url, $code_verifier ), $plugin_version ); } /** * POST a JSON body with no `Authorization` header: the calls that obtain a * key rather than use one. * * `retry_after` is a 429's wait in seconds, from the header, or 0. * * @param string $base_url API origin including the version prefix. * @param string $path Path under it, starting with `/`. * @param array $payload The JSON body. * @param string $plugin_version This plugin's version. * @return array{ ok: bool, status: int, retry_after: int, code?: string, data?: array } */ private static function post_without_key( string $base_url, string $path, array $payload, string $plugin_version ): array { $client = new self( $base_url, '', $plugin_version ); $args = $client->request_args( 'POST' ); // The key is what these calls are 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( $payload ); $response = wp_remote_request( rtrim( $base_url, '/' ) . $path, $args ); if ( is_wp_error( $response ) ) { return $client->map_response( 0, '' ) + array( 'status' => 0, 'retry_after' => 0, ); } $status = (int) wp_remote_retrieve_response_code( $response ); return $client->map_response( $status, (string) wp_remote_retrieve_body( $response ) ) + array( 'status' => $status, 'retry_after' => max( 0, (int) wp_remote_retrieve_header( $response, 'retry-after' ) ), ); } /** * POST /connect/otp/request — email this address a one-time code. * * The other way to obtain a key, beside `exchange_code()`: the administrator * types their AccessiBit email here in wp-admin and the code that arrives, * instead of leaving for the dashboard. The service answers the same * whether or not the address has an account. * * `code_challenge` binds the code to this install: only the verifier kept * here redeems it, so a code read from someone's inbox is worth nothing on * another site. * * @param string $base_url API origin including the version prefix. * @param string $email The address to send the code to. * @param string $site_url This WordPress site's own address. * @param string $code_challenge The PKCE challenge of the stored verifier. * @param string $locale The administrator's WordPress locale, for the email. * @param string $plugin_version This plugin's version. * @return array{ ok: bool, status: int, retry_after: int, code?: string, data?: array } */ public static function request_otp( string $base_url, string $email, string $site_url, string $code_challenge, string $locale = '', string $plugin_version = '' ): array { return self::post_without_key( $base_url, '/connect/otp/request', self::otp_request_payload( $email, $site_url, $code_challenge, $locale ), $plugin_version ); } /** * The body of POST /connect/otp/request. * * `lang` is the locale's language only (`it_IT` gives `it`), left out when * there is none: the service then writes the email in English. * * @param string $email The address to send the code to. * @param string $site_url This WordPress site's own address. * @param string $code_challenge The PKCE challenge. * @param string $locale A WordPress locale, or ''. * @return array */ public static function otp_request_payload( string $email, string $site_url, string $code_challenge, string $locale = '' ): array { $payload = array( 'email' => $email, 'site_url' => $site_url, 'code_challenge' => $code_challenge, ); $lang = strtolower( (string) preg_replace( '/[-_].*$/', '', trim( $locale ) ) ); if ( preg_match( '/^[a-z]{2,3}$/', $lang ) ) { $payload['lang'] = $lang; } return $payload; } /** * POST /connect/otp/verify — turn the emailed code into this site's API key. * * Answers what `exchange_code()` does, plus `created`: whether an account * or a site was made on the way. * * @param string $base_url API origin including the version prefix. * @param string $email The address the code was sent to. * @param string $code The six digits the administrator typed. * @param string $site_url This WordPress site's own address. * @param string $code_verifier The PKCE verifier stored when the code was requested. * @param string $plugin_version This plugin's version. * @param array|null $account The account to create, when the service asked who for. * @return array{ ok: bool, status: int, retry_after: int, code?: string, data?: array } */ public static function verify_otp( string $base_url, string $email, string $code, string $site_url, string $code_verifier, string $plugin_version = '', ?array $account = null ): array { return self::post_without_key( $base_url, '/connect/otp/verify', self::otp_verify_payload( $email, $code, $site_url, $code_verifier, $account ), $plugin_version ); } /** * The body of POST /connect/otp/verify. * * `account` goes with it only when the service asked for it * (`account_details_required`): who to create an AccessiBit account for, * and that they accepted the terms. * * @param string $email The address the code was sent to. * @param string $code The six digits. * @param string $site_url This WordPress site's own address. * @param string $code_verifier The PKCE verifier. * @param array|null $account `name`, `company_name`, `accepted_terms`, or null. * @return array */ public static function otp_verify_payload( string $email, string $code, string $site_url, string $code_verifier, ?array $account = null ): array { $payload = array( 'email' => $email, 'code' => $code, 'site_url' => $site_url, 'code_verifier' => $code_verifier, ); if ( null !== $account ) { $payload['account'] = $account; } return $payload; } /** * 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' ); } /** * POST /sites/{id}/verification/challenge — a token to answer from this * WordPress, so AccessiBit can see the domain is this install's. * * `data` is `{ verified: true }` for a site that is verified already, or * `{ verified: false, token, expiresAt, path }`. * * @param string $site_id The AccessiBit site to verify. * @return array */ public function verification_challenge( string $site_id ): array { return $this->request( 'POST', '/sites/' . rawurlencode( $site_id ) . '/verification/challenge' ); } /** * POST /sites/{id}/verification — have AccessiBit fetch this site's answer * and, when it is the challenge's, record the domain as verified. * * AccessiBit calls this WordPress back before it answers, so the wait is * longer than a plain read's. * * @param string $site_id The AccessiBit site to verify. * @return array */ public function verification_check( string $site_id ): array { return $this->request( 'POST', '/sites/' . rawurlencode( $site_id ) . '/verification', null, 30 ); } }