array( 'GET' => 'rest_state', 'DELETE' => 'rest_disconnect', ), '/connection/recheck' => array( 'POST' => 'rest_recheck' ), '/connection/otp/request' => array( 'POST' => 'rest_request_code' ), '/connection/otp/verify' => array( 'POST' => 'rest_verify_code' ), '/connection/widget' => array( 'PUT' => 'rest_set_widget' ), '/connection/verify-domain' => array( 'POST' => 'rest_verify_domain' ), ); foreach ( $routes as $route => $methods ) { $endpoints = array(); foreach ( $methods as $verb => $handler ) { $endpoints[] = array( 'methods' => $verb, 'permission_callback' => array( 'Accessibit_Rest', 'permission' ), 'callback' => array( __CLASS__, $handler ), ); } register_rest_route( Accessibit_Rest::NAMESPACE_V1, $route, $endpoints ); } // The one route anybody may read: AccessiBit asks it, from outside, // whether this WordPress holds the challenge it handed this site's key. // It answers a digest and nothing else, and only while a verification // is under way. register_rest_route( Accessibit_Rest::NAMESPACE_V1, '/verification', array( 'methods' => 'GET', 'permission_callback' => '__return_true', 'callback' => array( __CLASS__, 'rest_verification_answer' ), ) ); } /** * `GET /verification`, public: the digest of the pending challenge, or 404. * * @return WP_REST_Response */ public static function rest_verification_answer(): WP_REST_Response { $digest = self::pending_digest(); return self::respond( '' === $digest ? self::failure( 404, 'no_verification_pending', 'No domain verification is under way' ) : array( 'status' => 200, 'body' => array( 'digest' => $digest ), ) ); } /** * `POST /connection/verify-domain`. * * @return WP_REST_Response */ public static function rest_verify_domain(): WP_REST_Response { return self::respond( self::verify_domain() ); } /** * `GET /connection`. * * @return WP_REST_Response */ public static function rest_state(): WP_REST_Response { return self::respond( array( 'status' => 200, 'body' => self::state(), ) ); } /** * `DELETE /connection`. * * @return WP_REST_Response */ public static function rest_disconnect(): WP_REST_Response { $outcome = self::disconnect(); return self::respond( array( 'status' => 200, 'body' => array( 'outcome' => $outcome, 'connection' => self::state(), ), ) ); } /** * `POST /connection/recheck`. * * @return WP_REST_Response */ public static function rest_recheck(): WP_REST_Response { return self::respond( self::recheck_answer( self::recheck() ) ); } /** * `POST /connection/otp/request`. * * @param WP_REST_Request $request The request. * @return WP_REST_Response */ public static function rest_request_code( WP_REST_Request $request ): WP_REST_Response { return self::respond( self::request_code( self::field( $request, 'email' ) ) ); } /** * `POST /connection/otp/verify`. * * @param WP_REST_Request $request The request. * @return WP_REST_Response */ public static function rest_verify_code( WP_REST_Request $request ): WP_REST_Response { return self::respond( self::verify_code( self::field( $request, 'code' ), self::field( $request, 'account' ) ) ); } /** * `PUT /connection/widget`. * * @param WP_REST_Request $request The request. * @return WP_REST_Response */ public static function rest_set_widget( WP_REST_Request $request ): WP_REST_Response { return self::respond( self::set_widget( self::field( $request, 'enabled' ) ) ); } /** * One field of a request's JSON body, or null. * * @param WP_REST_Request $request The request. * @param string $name The field. * @return mixed */ private static function field( WP_REST_Request $request, string $name ) { $body = $request->get_json_params(); return is_array( $body ) && array_key_exists( $name, $body ) ? $body[ $name ] : null; } /** * An answer as a REST response nothing in between should keep. * * @param array{status: int, body: array, retry_after?: int} $answer From one of the handlers below. * @return WP_REST_Response */ private static function respond( array $answer ): WP_REST_Response { $response = new WP_REST_Response( $answer['body'], $answer['status'] ); $response->header( 'Cache-Control', 'no-store' ); if ( ! empty( $answer['retry_after'] ) ) { $response->header( 'Retry-After', (string) $answer['retry_after'] ); } return $response; } /** * Email a one-time code to an address, for this install to redeem. * * The attempt (the address and the PKCE verifier) is kept per user, like * the browser flow's state: two administrators connecting at once must not * overwrite each other's. A second code to the same address reuses the * verifier, so the service replaces the first code instead of leaving two * alive; another address starts a new attempt. * * The attempt is also kept when no answer came back: the email may have * left all the same, and its code must then be redeemable. * * @param mixed $email The address, as the browser sent it. * @return array{status: int, body: array, retry_after?: int} */ public static function request_code( $email ): array { $email = self::normalize_email( $email ); if ( '' === $email ) { return self::failure( 400, 'invalid_email', 'Enter a valid email address' ); } $pending = self::pending(); $verifier = null !== $pending && $pending['email'] === $email ? $pending['verifier'] : Accessibit_Admin::new_pkce_verifier(); $result = Accessibit_Api_Client::request_otp( ACCESSIBIT_API_BASE_URL, $email, home_url(), Accessibit_Admin::pkce_challenge( $verifier ), determine_locale(), ACCESSIBIT_VERSION ); // A 2xx that is not AccessiBit's own answer (a captive portal's page) // sent no code. $sent = $result['ok'] && true === ( $result['data']['ok'] ?? null ); if ( $result['ok'] && ! $sent ) { return self::failure( 400, 'unexpected_response', 'Something other than AccessiBit answered' ); } if ( $sent || 0 === $result['status'] ) { set_transient( self::OTP_ATTEMPT_PREFIX . get_current_user_id(), array( 'email' => $email, 'verifier' => $verifier, ), self::OTP_ATTEMPT_TTL ); } if ( ! $sent ) { return self::failure_of( $result ); } return array( 'status' => 200, 'body' => array( 'ok' => true, 'email' => $email, ), ); } /** * Redeem the emailed code and store the connection it buys. * * A refused code leaves the attempt in place: the service counts wrong * guesses per code, and the administrator may simply have mistyped. * * An address without an AccessiBit account is answered * `account_details_required`, with the attempt kept: the Setup screen asks * who the account is for and sends the same code again with `account`. * * @param mixed $code The code, as the browser sent it. * @param mixed $account The account to create, as the browser sent it, or null. * @return array{status: int, body: array, retry_after?: int} */ public static function verify_code( $code, $account = null ): array { $code = self::normalize_code( $code ); if ( '' === $code ) { return self::failure( 400, 'invalid_code', 'The code is six digits' ); } $pending = self::pending(); if ( null === $pending ) { // Never requested here, or older than the code itself. return self::failure( 409, 'no_pending_code', 'Request a new code' ); } $result = Accessibit_Api_Client::verify_otp( ACCESSIBIT_API_BASE_URL, $pending['email'], $code, home_url(), $pending['verifier'], ACCESSIBIT_VERSION, self::account_details( $account ) ); if ( ! $result['ok'] ) { return self::failure_of( $result ); } $data = is_array( $result['data'] ?? null ) ? $result['data'] : array(); if ( ! self::store( $data ) ) { return self::failure( 400, 'unexpected_response', 'Something other than AccessiBit answered' ); } delete_transient( self::OTP_ATTEMPT_PREFIX . get_current_user_id() ); $created = is_array( $data['created'] ?? null ) ? $data['created'] : array(); return array( 'status' => 200, 'body' => array( 'connection' => self::state(), 'created' => array( 'account' => ! empty( $created['account'] ), 'site' => ! empty( $created['site'] ), ), ), ); } /** * The account details as the service takes them, or null when the browser * sent none. The service decides whether they are acceptable and names * the field that is not (`invalid_account`): this only gives them its * shape, and never turns anything but the administrator's own `true` into * an acceptance of the terms. * * Pure, for the unit suite. * * @param mixed $account What the browser sent. * @return array{name: string, company_name: string, accepted_terms: bool}|null */ public static function account_details( $account ): ?array { if ( ! is_array( $account ) ) { return null; } $text = static function ( $value ): string { return is_string( $value ) ? trim( $value ) : ''; }; return array( 'name' => $text( $account['name'] ?? null ), 'company_name' => $text( $account['companyName'] ?? null ), 'accepted_terms' => true === ( $account['acceptedTerms'] ?? null ), ); } /** * Turn the public widget on or off. * * @param mixed $enabled The switch, as the browser sent it. * @return array{status: int, body: array} */ public static function set_widget( $enabled ): array { if ( ! is_bool( $enabled ) ) { return self::failure( 400, 'invalid_request', 'enabled must be true or false' ); } Accessibit_Settings::update( array( 'widget_enabled' => $enabled ) ); return array( 'status' => 200, 'body' => array( 'connection' => self::state() ), ); } /** * The digest AccessiBit is about to ask for, or '' when none is pending. * * @return string */ public static function pending_digest(): string { $pending = get_transient( self::VERIFICATION_TRANSIENT ); if ( ! is_array( $pending ) || ! isset( $pending['digest'], $pending['expires'] ) ) { return ''; } // The transient's own expiry is not relied on: an object cache may // keep an entry longer than asked. if ( ! is_string( $pending['digest'] ) || 1 !== preg_match( '/^[0-9a-f]{64}$/', $pending['digest'] ) || (int) $pending['expires'] <= time() ) { return ''; } return $pending['digest']; } /** * Whether this WordPress is the site at the root of its domain. One in a * subdirectory is not: AccessiBit verifies a domain, and asks at its root, * where another site answers. * * @return bool */ public static function at_domain_root(): bool { return '' === trim( (string) ( wp_parse_url( home_url(), PHP_URL_PATH ) ?? '' ), '/' ); } /** * Verify the site's domain from here: take a challenge from AccessiBit, * hold its digest where AccessiBit can read it, and ask for the check. * AccessiBit fetches the digest from this site's public address, which only * the WordPress at that address can make answer. * * The token itself is never stored: the digest is all the public route * serves. It is forgotten as soon as the check has answered. * * Refusals are 400, 409 or 429, never 401 or 403 (on a REST route those * say the administrator's own WordPress session failed) nor a 5xx (whose * body some hosts replace with their own error page), as * `Accessibit_Scan::rest_answer()` answers. * * @return array{status: int, body: array} */ public static function verify_domain(): array { if ( ! Accessibit_Settings::is_site_linked() ) { return self::failure( 409, 'accessibit_not_connected', 'This site is not connected to AccessiBit' ); } if ( Accessibit_Settings::is_binding_stale() ) { return self::failure( 409, 'binding_stale', 'The connection belongs to another address' ); } $verified = array( 'status' => 200, 'body' => array( 'connection' => self::state() ), ); if ( Accessibit_Settings::is_site_verified() ) { return $verified; } if ( ! self::at_domain_root() ) { return self::failure( 409, 'not_domain_root', 'This WordPress is not at the root of its domain' ); } $client = Accessibit_Api_Client::from_settings(); $site_id = Accessibit_Settings::get_site_id(); $challenge = $client->verification_challenge( $site_id ); if ( empty( $challenge['ok'] ) ) { return self::verification_failure( $challenge ); } $data = $challenge['data']; if ( empty( $data['verified'] ) ) { $token = isset( $data['token'] ) && is_string( $data['token'] ) ? $data['token'] : ''; if ( '' === $token ) { // A 2xx that is not the service's: nothing to answer with. return self::failure( 400, 'request_failed', 'AccessiBit sent no challenge' ); } // Long enough for the check below, and counted on this site's own // clock: AccessiBit's expiry, read against a clock that runs ahead, // would end the answer before it was asked for. $ttl = self::VERIFICATION_TTL; set_transient( self::VERIFICATION_TRANSIENT, array( 'digest' => hash( 'sha256', $token ), 'expires' => time() + $ttl, ), $ttl ); $check = $client->verification_check( $site_id ); delete_transient( self::VERIFICATION_TRANSIENT ); if ( empty( $check['ok'] ) || empty( $check['data']['verified'] ) ) { return self::verification_failure( $check ); } } // The settings as they are now: the wait was long enough for a // Disconnect or a Reconnect to have replaced them. $now = Accessibit_Settings::reload(); if ( (string) $now['site_id'] === $site_id && '' !== (string) $now['api_key'] ) { Accessibit_Settings::update( array( 'site_verified' => true ) ); } $verified['body']['connection'] = self::state(); return $verified; } /** * The answer for a verification call AccessiBit refused or never answered. * * Pure, for the unit suite. * * @param array $result An `Accessibit_Api_Client` result that is not a success. * @return array{status: int, body: array} */ public static function verification_failure( array $result ): array { $code = self::code_shaped( is_string( $result['code'] ?? null ) ? $result['code'] : '' ); if ( ! empty( $result['ok'] ) ) { $code = 'request_failed'; } $status = 409; if ( in_array( $code, array( 'network_error', 'service_unavailable', 'request_failed', 'internal_error' ), true ) ) { $status = 400; } elseif ( 'rate_limited' === $code ) { $status = 429; } return self::failure( $status, $code, 'The domain could not be verified from here' ); } /** * The answer to a Check again, from `recheck()`'s outcome. * * Never 401 or 403 for a key AccessiBit refused (on a REST route those say * the administrator's own WordPress session failed), nor a 5xx for a * service that failed: see `failure_of()`. * * Pure, for the unit suite. * * @param array{ok: bool, reason: string, linked: bool} $outcome From `recheck()`. * @return array{status: int, body: array} */ public static function recheck_answer( array $outcome ): array { if ( $outcome['ok'] ) { return array( 'status' => 200, 'body' => array( 'connection' => self::state() ), ); } $reason = self::code_shaped( $outcome['reason'] ); $status = 400; if ( in_array( $reason, array( 'binding_stale', 'invalid_api_key', 'account_not_found' ), true ) ) { $status = 409; } elseif ( 'rate_limited' === $reason ) { $status = 429; } return self::failure( $status, $reason, 'Could not re-read the connection' ); } /** * Store what a successful connect answered: the key, the company, the site * and what the site may use. False, with nothing written, when the answer * is not one. * * A 2xx whose body is not our JSON is NOT a successful connect. A captive * portal or a misconfigured proxy answering 200 with an HTML page used to * land here with an empty slug and no site, which was then stored — wiping * a working connection and, with it, the company slug the public widget tag * is built from. * * @param array $data The decoded body of `/connect/exchange` or `/connect/otp/verify`. * @return bool */ public static function store( array $data ): bool { $api_key = isset( $data['apiKey'] ) && is_string( $data['apiKey'] ) ? $data['apiKey'] : ''; $slug = $data['company']['slug'] ?? ''; $site = is_array( $data['site'] ?? null ) ? $data['site'] : array(); $site_id = isset( $site['id'] ) && ( is_string( $site['id'] ) || is_int( $site['id'] ) ) ? (string) $site['id'] : ''; if ( '' === $api_key || ! is_string( $slug ) || '' === $slug || '' === $site_id ) { return false; } Accessibit_Settings::set_account( $api_key, $slug, $site_id, ! empty( $site['isPro'] ) || ! empty( $site['isTrial'] ), // Absent on an older API than this plugin: treat it as verified // rather than warning about something we cannot know. ! array_key_exists( 'verified', $site ) || ! empty( $site['verified'] ) ); // The connect answer reports what `/account` would (ACC-412), so the // Tracker menu is there from the first screen after connecting. Accessibit_Settings::update( Accessibit_Settings::capability_flags( $data ) + array( 'plan' => self::plan_of( $site ), 'company_name' => self::company_name_of( $data ), ) ); return true; } /** * Re-read `/account` with the key already stored, so an admin who has just * bought a licence or verified their domain can tell this plugin about it * without connecting again. * * `reason` is a code `Accessibit_Admin::connect_error_notice()` words, or * `binding_stale`. * * @return array{ok: bool, reason: string, linked: bool} */ public static function recheck(): array { $refused = static function ( string $reason ): array { return array( 'ok' => false, 'reason' => $reason, 'linked' => false, ); }; // A copy of another site's database holds that site's key, whose scope // names that site. Re-reading it would re-bind this copy to the // original and switch the stale-binding guard off, letting it edit the // original's widget and statement (ACC-411). Only a new connection, // which checks this address on the server, may re-bind. if ( Accessibit_Settings::is_binding_stale() ) { return $refused( 'binding_stale' ); } $api_key = Accessibit_Settings::get_api_key(); if ( '' === $api_key ) { return $refused( 'invalid_api_key' ); } $result = ( new Accessibit_Api_Client( ACCESSIBIT_API_BASE_URL, $api_key, ACCESSIBIT_VERSION ) )->account(); if ( ! $result['ok'] ) { // A string or nothing: a proxy's own error body can carry anything. return $refused( is_string( $result['code'] ?? null ) ? $result['code'] : 'error' ); } $data = is_array( $result['data'] ) ? $result['data'] : array(); $slug = $data['company']['slug'] ?? ''; if ( ! is_string( $slug ) || '' === $slug ) { return $refused( 'unexpected_response' ); } // The answer may have taken a while. A Disconnect, or another // administrator's connect, in the meantime must not be written over // with the key this request started with. if ( Accessibit_Settings::reload()['api_key'] !== $api_key ) { return $refused( 'connection_changed' ); } $matched = Accessibit_Admin::resolve_site( $data, home_url() ); $site_id = null === $matched ? '' : $matched['id']; Accessibit_Settings::set_account( $api_key, $slug, $site_id, null !== $matched && $matched['licensed'], null !== $matched && $matched['verified'] ); Accessibit_Settings::update( Accessibit_Settings::capability_flags( $data ) + array( 'plan' => self::plan_of( self::site_entry( $data, $site_id ) ), 'company_name' => self::company_name_of( $data ), ) ); return array( 'ok' => true, 'reason' => '', 'linked' => '' !== $site_id, ); } /** * End the connection: revoke the key where that is this install's to do, * then forget everything. Returns what became of the key (`none`, `copy`, * or a `Accessibit_Admin::disconnect_outcome()`). * * The widget is turned off in the same write, so disconnecting can never * leave a public page loading a bundle this site can no longer configure. * * `bound_domain` goes too. It is the address this install connected as, and * the stale-binding notice compares it with the current one — so a staging * clone that followed that notice's own advice and disconnected was still * told that it was "connected under a different address". * * The key is revoked SERVER-side first (ACC-402). A key this site has * stopped using but AccessiBit still honours is a live credential for the * site, sitting in a database nobody is looking at. A connect-flow key * belongs to this install and nothing else, so disconnecting can end it — * except on a copy whose binding is stale, which holds the original site's * key. * * Best effort, and deliberately not a gate: the local state is cleared * whether or not the call succeeded. An administrator disconnecting a site * whose network cannot reach us must still end up disconnected. The outcome * is still reported, so the notice only claims a revocation that happened * (ACC-583). * * @return string */ public static function disconnect(): string { $outcome = 'none'; if ( Accessibit_Settings::is_binding_stale() ) { // A copy of another site's database (a staging clone) holds that // site's key, and revoking it would cut the original site off. // Forgetting it here is all this copy may do (ACC-411). $outcome = 'copy'; } elseif ( '' !== Accessibit_Settings::get_api_key() ) { $outcome = Accessibit_Admin::disconnect_outcome( Accessibit_Api_Client::from_settings()->disconnect() ); } Accessibit_Settings::update( array( 'api_key' => '', 'company_slug' => '', 'site_id' => '', 'widget_enabled' => false, 'widget_licensed' => false, 'site_verified' => false, 'bound_domain' => '', 'statement_id' => '', 'statement_published' => false, 'tracker_available' => false, 'plan' => array(), 'company_name' => '', ) ); // The literal, not a class constant: `Accessibit_Scan::RUNNING_JOB_OPTION` // went with the paid scan, and referencing one that no longer exists is // a fatal on every supported PHP. `uninstall.php` spells the same key // out for the same reason. // // Still deleted rather than ignored: an install that ran an earlier // build may hold the row, and disconnecting is where this plugin's // stored state is meant to go away completely. delete_option( 'accessibit_running_job' ); return $outcome; } /** * What the Setup screen shows: the connection as stored, and the address a * requested code is waiting for. * * @return array */ public static function state(): array { $pending = self::pending(); return self::state_of( Accessibit_Settings::reload(), Accessibit_Settings::is_binding_stale(), Accessibit_Admin::sanitize_domain( home_url() ), Accessibit_Admin::connect_origin_matches(), null === $pending ? '' : $pending['email'], self::at_domain_root() ); } /** * The state, from its parts. The key is not one of them. * * Pure, for the unit suite. * * @param array $settings `Accessibit_Settings::get()`. * @param bool $stale Whether the binding is another address's. * @param string $domain This install's address, as the platform spells it. * @param bool $browser_ok Whether the browser flow can start here. * @param string $pending_email The address a code was sent to, or ''. * @param bool $at_root Whether this WordPress is at the root of its domain. * @return array */ public static function state_of( array $settings, bool $stale, string $domain, bool $browser_ok, string $pending_email, bool $at_root = true ): array { $connected = '' !== (string) $settings['api_key'] && '' !== (string) $settings['company_slug']; $linked = $connected && '' !== (string) $settings['site_id']; $plan = isset( $settings['plan'] ) && is_array( $settings['plan'] ) && array() !== $settings['plan'] ? $settings['plan'] : null; return array( 'connected' => $connected, 'siteLinked' => $linked, 'stale' => $stale, 'domain' => $domain, 'boundDomain' => (string) $settings['bound_domain'], 'canConnectInBrowser' => $browser_ok, 'companySlug' => (string) $settings['company_slug'], 'companyName' => (string) ( $settings['company_name'] ?? '' ), 'siteId' => (string) $settings['site_id'], 'siteVerified' => (bool) $settings['site_verified'], // Whether the domain can be verified from here: see `verify_domain()`. 'canVerifyDomain' => $linked && ! $stale && $at_root && ! $settings['site_verified'], 'widgetLicensed' => (bool) $settings['widget_licensed'], 'widgetEnabled' => (bool) $settings['widget_enabled'], 'trackerAvailable' => (bool) $settings['tracker_available'], 'plan' => $plan, 'pendingEmail' => $pending_email, ); } /** * A site's `plan`, reduced to what the screens read: per product a status, * the plan's name and when the period ends. Empty when the answer has none * (an API older than the field). * * Pure, for the unit suite. * * @param array $site A site entry from a connect answer or `/account`. * @return array */ public static function plan_of( array $site ): array { $plan = isset( $site['plan'] ) && is_array( $site['plan'] ) ? $site['plan'] : array(); $out = array(); foreach ( self::PRODUCTS as $product ) { $entry = $plan[ $product ] ?? null; if ( ! is_array( $entry ) ) { continue; } $status = $entry['status'] ?? ''; $name = $entry['name'] ?? null; $end = $entry['periodEnd'] ?? null; $out[ $product ] = array( 'status' => in_array( $status, array( 'none', 'trial', 'active' ), true ) ? $status : 'none', // By characters, not bytes: a name cut inside one would not be UTF-8. 'name' => is_string( $name ) && '' !== trim( $name ) ? mb_substr( trim( $name ), 0, 100 ) : null, 'periodEnd' => is_string( $end ) && preg_match( '/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/', $end ) ? $end : null, // A subscription that renews has no end to show. 'renews' => true === ( $entry['renews'] ?? null ), ); } return $out; } /** * The company's name in a connect answer or `/account`, or '' when it * carries none. * * @param array $data The decoded body. * @return string */ private static function company_name_of( array $data ): string { $name = $data['company']['name'] ?? null; // By characters, not bytes: a name cut inside one would not be UTF-8. return is_string( $name ) ? mb_substr( trim( $name ), 0, 200 ) : ''; } /** * The entry of `sites` with an id, or an empty one. * * @param array $data The decoded `/account` body. * @param string $site_id The site to find. * @return array */ private static function site_entry( array $data, string $site_id ): array { $sites = isset( $data['sites'] ) && is_array( $data['sites'] ) ? $data['sites'] : array(); foreach ( $sites as $site ) { $raw_id = is_array( $site ) ? ( $site['id'] ?? null ) : null; if ( '' !== $site_id && ( is_string( $raw_id ) || is_int( $raw_id ) ) && (string) $raw_id === $site_id ) { return $site; } } return array(); } /** * The current user's pending attempt, or null. * * @return array{email: string, verifier: string}|null */ private static function pending(): ?array { $attempt = get_transient( self::OTP_ATTEMPT_PREFIX . get_current_user_id() ); if ( ! is_array( $attempt ) || ! isset( $attempt['email'], $attempt['verifier'] ) || ! is_string( $attempt['email'] ) || ! is_string( $attempt['verifier'] ) || '' === $attempt['email'] || '' === $attempt['verifier'] ) { return null; } return array( 'email' => $attempt['email'], 'verifier' => $attempt['verifier'], ); } /** * An address as the service stores it (trimmed, lowercase), or '' when it * is not one. The service validates again; this spares it a call. * * Pure, for the unit suite. * * @param mixed $email What the browser sent. * @return string */ public static function normalize_email( $email ): string { if ( ! is_string( $email ) ) { return ''; } $email = strtolower( trim( $email ) ); return strlen( $email ) <= 254 && false !== filter_var( $email, FILTER_VALIDATE_EMAIL ) ? $email : ''; } /** * The six digits of a code, or '' when it is not one. Spaces and dashes are * dropped: mail clients and password managers add them. * * Pure, for the unit suite. * * @param mixed $code What the browser sent. * @return string */ public static function normalize_code( $code ): string { if ( ! is_string( $code ) && ! is_int( $code ) ) { return ''; } $code = (string) preg_replace( '/[\s-]+/', '', (string) $code ); return 1 === preg_match( '/^\d{6}$/', $code ) ? $code : ''; } /** * The answer to the browser for a call AccessiBit refused or never got. * * Never 401 or 403 (on a REST route those say the administrator's own * WordPress session failed) nor a 5xx (whose body some hosts replace with * their own error page), as `Accessibit_Scan::rest_answer()` answers: the * bundle words every refusal by its code. * * - No answer: 400 `network_error`. * - A refusal keeps its code and its 4xx status, but a 401 or 403 becomes * 409; a 5xx becomes 400. * - A 429's wait travels in the body and the `Retry-After` header, with * its `kind` when AccessiBit gave one: `cooldown` (the minute after a * code was sent) or `cap` (the codes allowed per hour). * * Pure, for the unit suite. * * @param array $result An `Accessibit_Api_Client` keyless-call result. * @return array{status: int, body: array, retry_after?: int} */ public static function failure_of( array $result ): array { $status = (int) ( $result['status'] ?? 0 ); if ( 0 === $status ) { return self::failure( 400, 'network_error', 'Could not reach AccessiBit' ); } $data = is_array( $result['data'] ?? null ) ? $result['data'] : array(); $message = $data['error']['message'] ?? null; if ( 401 === $status || 403 === $status ) { $status = 409; } elseif ( $status < 400 || $status >= 500 ) { $status = 400; } $answer = self::failure( $status, self::code_shaped( (string) ( $result['code'] ?? '' ) ), // By characters, not bytes: a message cut inside one would not be UTF-8. is_string( $message ) && '' !== $message ? mb_substr( $message, 0, 200 ) : 'AccessiBit refused the request' ); // Which of the account's details was refused (`invalid_account`). if ( isset( $data['field'] ) && is_string( $data['field'] ) && preg_match( '/^[a-z_]{1,32}$/', $data['field'] ) ) { $answer['body']['error']['field'] = $data['field']; } $wait = (int) ( $result['retry_after'] ?? 0 ); if ( $wait <= 0 && isset( $data['retryAfterSeconds'] ) && is_numeric( $data['retryAfterSeconds'] ) ) { $wait = (int) $data['retryAfterSeconds']; } if ( $wait > 0 ) { // Beside `error`, as audit-api puts it, and inside it, where the // bundle reads a refusal's details. $answer['body']['error']['retryAfterSeconds'] = $wait; $answer['body']['retryAfterSeconds'] = $wait; $answer['retry_after'] = $wait; // Beside the wait, as audit-api puts it, or inside `error`. $kind = $data['kind'] ?? ( $data['error']['kind'] ?? null ); if ( 'cooldown' === $kind || 'cap' === $kind ) { $answer['body']['error']['kind'] = $kind; $answer['body']['kind'] = $kind; } } return $answer; } /** * A code as AccessiBit spells them, or `request_failed`. * * @param string $code A code from an answer. * @return string */ private static function code_shaped( string $code ): string { return 1 === preg_match( '/^[a-z0-9_]{1,64}$/', $code ) ? $code : 'request_failed'; } /** * A failure in audit-api's error shape. * * @param int $status HTTP status. * @param string $code Machine-readable code. * @param string $message English, for logs; the bundle words it by code. * @return array{status: int, body: array} */ private static function failure( int $status, string $code, string $message ): array { return array( 'status' => $status, 'body' => array( 'error' => array( 'code' => $code, 'message' => $message, ), ), ); } }