$methods, 'callback' => $callback, 'permission_callback' => array( __CLASS__, 'can_manage' ), 'args' => $args, ) ); } /** * Registers the routes. */ public static function routes() { Public_Rest::routes(); $id = array( 'id' => array( 'type' => 'integer', 'required' => true, 'minimum' => 1, 'sanitize_callback' => 'absint', ), ); $decision = array( 'decision' => array( 'type' => 'string', 'enum' => array( '', 'all', 'allow', 'challenge', 'block' ), 'default' => '', ), 'search' => array( 'type' => 'string', 'default' => '', 'sanitize_callback' => 'sanitize_text_field', ), ); $attack = array( 'attackId' => array( 'type' => 'integer', 'default' => 0, 'minimum' => 0, 'sanitize_callback' => 'absint', ), ); self::route( '/status', 'GET', array( __CLASS__, 'status' ) ); self::route( '/state', 'GET', array( __CLASS__, 'state' ) ); self::route( '/overview', 'GET', array( __CLASS__, 'overview' ), array( 'range' => array( 'type' => 'string', 'enum' => array( '24h', '7d', '30d' ), 'default' => '24h', ), ) ); self::route( '/events', 'GET', array( __CLASS__, 'events' ), array_merge( $decision, array( 'page' => array( 'type' => 'integer', 'default' => 1, 'minimum' => 1, 'sanitize_callback' => 'absint', ), 'perPage' => array( 'type' => 'integer', 'default' => 25, 'minimum' => 1, 'maximum' => 100, 'sanitize_callback' => 'absint', ), 'format' => array( 'type' => 'string', 'enum' => array( 'json', 'csv' ), 'default' => 'json', ), ) ) ); self::route( '/events/export', 'GET', array( __CLASS__, 'events_export' ), $decision ); self::route( '/events/(?P\d+)', 'GET', array( __CLASS__, 'event' ), $id ); self::route( '/events/(?P\d+)/mark-real', 'POST', array( __CLASS__, 'event_mark_real' ), $id ); self::route( '/events/(?P\d+)/always-block', 'POST', array( __CLASS__, 'event_always_block' ), $id ); self::route( '/attacks', 'GET', array( __CLASS__, 'attacks' ) ); self::route( '/attacks/(?P\d+)', 'GET', array( __CLASS__, 'attack' ), $id ); self::route( '/attacks/(?P\d+)/report', 'GET', array( __CLASS__, 'attack_report' ), $id ); self::route( '/lockdown', 'POST', array( __CLASS__, 'lockdown' ), array( 'on' => array( 'type' => 'boolean', 'required' => true, ), ) ); self::route( '/network/warning/dismiss', 'POST', array( __CLASS__, 'network_warning_dismiss' ) ); self::route( '/cleanup', 'GET', array( __CLASS__, 'cleanup' ), $attack ); self::route( '/cleanup/run', 'POST', array( __CLASS__, 'cleanup_run' ), $attack ); self::route( '/cleanup/undo', 'POST', array( __CLASS__, 'cleanup_undo' ), array( 'batchId' => array( 'type' => 'string', 'required' => true, 'sanitize_callback' => 'sanitize_text_field', ), ) ); self::route( '/cleanup/accounts', 'GET', array( __CLASS__, 'cleanup_accounts' ), $attack ); self::route( '/cleanup/accounts/delete', 'POST', array( __CLASS__, 'cleanup_accounts_delete' ), array( 'userIds' => array( 'type' => 'array', 'required' => true, 'items' => array( 'type' => 'integer' ), 'maxItems' => 500, ), ) ); self::route( '/settings', 'GET', array( __CLASS__, 'settings' ) ); self::route( '/settings', 'POST', array( __CLASS__, 'settings_save' ), self::settings_args() ); self::route( '/licence', 'POST', array( __CLASS__, 'licence_activate' ), array( 'key' => array( 'type' => 'string', 'required' => true, // Not sanitize_text_field: it would strip parts of keys that contain % or <. 'sanitize_callback' => array( __CLASS__, 'clean_licence_key' ), ), ) ); self::route( '/licence', 'DELETE', array( __CLASS__, 'licence_deactivate' ) ); self::route( '/licence/refresh', 'POST', array( __CLASS__, 'licence_refresh' ) ); self::route( '/onboarding', 'POST', array( __CLASS__, 'onboarding' ), array( 'alertEmail' => array( 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', ), 'level' => array( 'type' => 'string', 'enum' => array( 'relaxed', 'balanced', 'strict' ), ), 'done' => array( 'type' => 'boolean' ), ) ); } /** * The schema of POST /settings. Values are checked again, with plain-English errors, in Settings::update(). * * @return array */ private static function settings_args() { $bool = array( 'type' => 'boolean' ); $list = array( 'type' => 'array', 'items' => array( 'type' => 'string' ), ); $text = array( 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', ); return array( 'level' => array( 'type' => 'string', 'enum' => array( 'relaxed', 'balanced', 'strict' ), ), 'autoLockdown' => $bool, 'challengeGuestsInLockdown' => $bool, 'blockUnknownInLockdown' => $bool, 'guestMinimumInLockdown' => array( 'type' => array( 'number', 'null' ) ), 'allowReturningCustomers' => $bool, 'allowStaff' => $bool, 'allowEmails' => $list, 'allowIps' => $list, 'alertEmails' => $list, 'alertOnStart' => $bool, 'alertOnEnd' => $bool, 'dailyDigest' => $bool, 'turnstileSiteKey' => $text, 'turnstileSecret' => $text, 'proxy' => array( 'type' => 'string', 'enum' => array( 'auto', 'direct', 'cloudflare', 'forwarded' ), ), 'historyDays' => array( 'type' => 'integer', 'enum' => array( 7, 30, 90 ), ), 'slackWebhook' => array( 'type' => 'string', 'sanitize_callback' => 'esc_url_raw', ), 'removeBlockedVisitor' => array( 'type' => 'integer', 'sanitize_callback' => 'absint', ), ); } /** * Only people who run the store may see or change anything. * * @return bool */ public static function can_manage() { return current_user_can( 'manage_woocommerce' ); } /** * A "not found" error. * * @param string $message Plain-English message. * @return \WP_Error */ private static function not_found( $message ) { return new \WP_Error( 'brickmoat_not_found', $message, array( 'status' => 404 ) ); } /** * GET /status: what the plugin is and, when a licence key is saved, whether it can reach the * Brickmoat API. Without a key nothing is sent anywhere: the free plugin never calls out. * * @return \WP_REST_Response */ public static function status() { return rest_ensure_response( array( 'version' => BRICKMOAT_VERSION, 'woocommerce' => defined( 'WC_VERSION' ) ? WC_VERSION : '', 'apiBase' => Config::api_base(), 'development' => Config::is_development(), 'api' => '' !== Licence::key() ? Api_Client::health() : null, ) ); } /** * GET /state. * * @return \WP_REST_Response */ public static function state() { return rest_ensure_response( Views::state() ); } /** * GET /overview. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response */ public static function overview( $request ) { return rest_ensure_response( Views::overview( (string) $request['range'] ) ); } /** * The decision filter of a request ('' for all). * * @param \WP_REST_Request $request Request. * @return string */ private static function decision_filter( $request ) { $decision = (string) $request['decision']; return 'all' === $decision ? '' : $decision; } /** * GET /events. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response */ public static function events( $request ) { if ( 'csv' === $request['format'] ) { return self::events_export( $request ); } $page = max( 1, (int) $request['page'] ); $per_page = max( 1, min( 100, (int) $request['perPage'] ) ); $result = Events::query( self::decision_filter( $request ), (string) $request['search'], $page, $per_page ); return rest_ensure_response( array( 'rows' => $result['rows'], 'total' => $result['total'], 'page' => $page, 'perPage' => $per_page, 'counts' => $result['counts'], ) ); } /** * GET /events/export: the filtered event log as a CSV file. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response */ public static function events_export( $request ) { $lines = array( self::csv_line( array( __( 'Time (UTC)', 'brickmoat' ), __( 'Decision', 'brickmoat' ), __( 'Bot chance (%)', 'brickmoat' ), __( 'Main reason', 'brickmoat' ), __( 'Country', 'brickmoat' ), __( 'Tried to pay on', 'brickmoat' ), __( 'Visitor address', 'brickmoat' ), __( 'Order', 'brickmoat' ), __( 'What happened next', 'brickmoat' ), ) ), ); $words = array( 'allow' => __( 'Allowed', 'brickmoat' ), 'challenge' => __( 'Checked', 'brickmoat' ), 'block' => __( 'Blocked', 'brickmoat' ), ); $after = array( 'paid' => __( 'Paid', 'brickmoat' ), 'declined' => __( 'Card declined', 'brickmoat' ), 'blocked' => __( 'Stopped', 'brickmoat' ), 'challenge_passed' => __( 'Passed the check', 'brickmoat' ), 'challenge_failed' => __( 'Did not pass the check', 'brickmoat' ), ); foreach ( Events::export_rows( self::decision_filter( $request ), (string) $request['search'] ) as $row ) { $lines[] = self::csv_line( array( gmdate( 'Y-m-d H:i:s', (int) $row['ts'] ), isset( $words[ $row['decision'] ] ) ? $words[ $row['decision'] ] : $row['decision'], (int) $row['score'], Events::reason_label( $row ), Geo::name( (string) $row['country'] ), Signals::route_label( (string) $row['route'] ), \Brickmoat\Engine\Ip::mask( (string) $row['ip'] ), (int) $row['order_id'] > 0 ? (int) $row['order_id'] : '', isset( $after[ $row['outcome'] ] ) ? $after[ $row['outcome'] ] : '', ) ); } $response = new \WP_REST_Response( implode( "\r\n", $lines ) . "\r\n" ); $response->header( 'Content-Type', 'text/csv; charset=utf-8' ); $response->header( 'Content-Disposition', 'attachment; filename="brickmoat-events-' . gmdate( 'Y-m-d' ) . '.csv"' ); $response->header( 'X-Brickmoat-File', '1' ); return $response; } /** * One CSV line. Cells that a spreadsheet would run as a formula are made plain text. * * @param array $cells Cell values. * @return string */ private static function csv_line( array $cells ) { $out = array(); foreach ( $cells as $cell ) { $cell = (string) $cell; if ( '' !== $cell && in_array( $cell[0], array( '=', '+', '-', '@', "\t", "\r" ), true ) ) { $cell = "'" . $cell; } $out[] = '"' . str_replace( '"', '""', $cell ) . '"'; } return implode( ',', $out ); } /** * Sends a file made by this plugin (the CSV export, an attack report) as it is, not as JSON. * * @param bool $served Whether the request was already served. * @param \WP_HTTP_Response $result Response. * @param \WP_REST_Request $request Request. * @param \WP_REST_Server $server Server. * @return bool */ public static function serve_file( $served, $result, $request, $server ) { unset( $request, $server ); if ( $served || ! ( $result instanceof \WP_HTTP_Response ) ) { return $served; } $headers = $result->get_headers(); if ( empty( $headers['X-Brickmoat-File'] ) || ! is_string( $result->get_data() ) ) { return $served; } // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- A file download: CSV built cell by cell in csv_line(), or the report escaped value by value in Report::html(). echo $result->get_data(); return true; } /** * Loads the event a route is about. * * @param \WP_REST_Request $request Request. * @return array|\WP_Error */ private static function event_row( $request ) { $row = Events::get( (int) $request['id'] ); return $row ? $row : self::not_found( __( 'That event is no longer in the log.', 'brickmoat' ) ); } /** * GET /events/{id}. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public static function event( $request ) { $row = self::event_row( $request ); return is_wp_error( $row ) ? $row : rest_ensure_response( Events::to_detail( $row ) ); } /** * POST /events/{id}/mark-real: this visitor is a real customer. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public static function event_mark_real( $request ) { $row = self::event_row( $request ); if ( is_wp_error( $row ) ) { return $row; } $id = (int) $row['id']; $keys = array( 'email' => (string) $row['email_hash'], 'device' => (string) $row['device_hash'], ); if ( '' === $keys['email'] && '' === $keys['device'] ) { // Nothing else is known about this visitor, so their address has to do. $keys = array( 'ip' => (string) $row['ip'] ); } foreach ( $keys as $type => $value ) { Blocks::mark( 'allow', $type, $value, $id ); } // Lift anything that is blocking them now. Blocks::remove( 'block', array( 'ip' => (string) $row['ip'], 'email' => (string) $row['email_hash'], 'device' => (string) $row['device_hash'], ) ); Reporter::report_cleared( $row ); return rest_ensure_response( Events::to_detail( Events::get( $id ) ) ); } /** * POST /events/{id}/always-block: never let this visitor pay. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public static function event_always_block( $request ) { $row = self::event_row( $request ); if ( is_wp_error( $row ) ) { return $row; } $id = (int) $row['id']; $masked = \Brickmoat\Engine\Ip::mask( (string) $row['ip'] ); $country = Geo::name( (string) $row['country'] ); $label = '' !== $country /* translators: 1: country name, 2: partly hidden internet address. */ ? sprintf( __( 'Visitor from %1$s (%2$s)', 'brickmoat' ), $country, $masked ) /* translators: %s: partly hidden internet address. */ : sprintf( __( 'Visitor at %s', 'brickmoat' ), $masked ); Blocks::remove( 'allow', array( 'ip' => (string) $row['ip'], 'email' => (string) $row['email_hash'], 'device' => (string) $row['device_hash'], ) ); Blocks::mark( 'block', 'ip', (string) $row['ip'], $id, $label ); Blocks::mark( 'block', 'device', (string) $row['device_hash'], $id, $label ); return rest_ensure_response( Events::to_detail( Events::get( $id ) ) ); } /** * GET /attacks. * * @return \WP_REST_Response */ public static function attacks() { $active = null; $past = array(); foreach ( Attacks::all( 50 ) as $attack ) { if ( 0 === (int) $attack['ended'] ) { if ( null === $active ) { $active = Attacks::summary( $attack ); } } else { $past[] = Attacks::summary( $attack ); } } return rest_ensure_response( array( 'active' => $active, 'past' => $past, ) ); } /** * GET /attacks/{id}. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public static function attack( $request ) { $attack = Attacks::get( (int) $request['id'] ); if ( ! $attack ) { return self::not_found( __( 'That attack could not be found.', 'brickmoat' ) ); } return rest_ensure_response( Attacks::detail( $attack ) ); } /** * GET /attacks/{id}/report: the attack report as a file to download. Written on this site. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public static function attack_report( $request ) { $attack = Attacks::get( (int) $request['id'] ); if ( ! $attack ) { return self::not_found( __( 'That attack could not be found.', 'brickmoat' ) ); } $response = new \WP_REST_Response( Report::html( $attack ) ); $response->header( 'Content-Type', 'text/html; charset=utf-8' ); $response->header( 'Content-Disposition', 'attachment; filename="' . Report::filename( $attack ) . '"' ); $response->header( 'X-Brickmoat-File', '1' ); return $response; } /** * POST /lockdown. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response */ public static function lockdown( $request ) { if ( rest_sanitize_boolean( $request['on'] ) ) { Lockdown::start(); } else { Lockdown::stop(); } return rest_ensure_response( Views::state() ); } /** * POST /network/warning/dismiss: puts away the notice about an attack on other stores. * * @return \WP_REST_Response */ public static function network_warning_dismiss() { Network::dismiss_warning(); return rest_ensure_response( Views::state() ); } /** * GET /cleanup. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public static function cleanup( $request ) { $attack_id = (int) $request['attackId']; if ( $attack_id > 0 && ! Attacks::get( $attack_id ) ) { return self::not_found( __( 'That attack could not be found.', 'brickmoat' ) ); } return rest_ensure_response( Cleanup::view( $attack_id ) ); } /** * POST /cleanup/run. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public static function cleanup_run( $request ) { $attack_id = (int) $request['attackId']; $started = Cleanup::run( $attack_id ); return is_wp_error( $started ) ? $started : rest_ensure_response( Cleanup::view( $attack_id ) ); } /** * POST /cleanup/undo. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public static function cleanup_undo( $request ) { $started = Cleanup::undo( (string) $request['batchId'] ); return is_wp_error( $started ) ? $started : rest_ensure_response( Cleanup::view() ); } /** * GET /cleanup/accounts. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response */ public static function cleanup_accounts( $request ) { return rest_ensure_response( array( 'accounts' => Cleanup::accounts( Cleanup::target( (int) $request['attackId'] ) ) ) ); } /** * POST /cleanup/accounts/delete. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public static function cleanup_accounts_delete( $request ) { if ( ! current_user_can( 'delete_users' ) ) { return new \WP_Error( 'brickmoat_cannot_delete_users', __( 'Your account is not allowed to delete customer accounts. Please ask an administrator.', 'brickmoat' ), array( 'status' => 403 ) ); } return rest_ensure_response( array( 'deleted' => Cleanup::delete_accounts( array_map( 'absint', (array) $request['userIds'] ) ) ) ); } /** * GET /settings. * * @return \WP_REST_Response */ public static function settings() { return rest_ensure_response( Settings::to_rest() ); } /** * POST /settings: saves any subset and answers with the full settings. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public static function settings_save( $request ) { $params = (array) $request->get_params(); $slack_before = (string) Settings::value( 'slackWebhook' ); $saved = Settings::update( $params ); if ( is_wp_error( $saved ) ) { return $saved; } if ( ! empty( $params['removeBlockedVisitor'] ) ) { Blocks::remove_manual( absint( $params['removeBlockedVisitor'] ) ); } // A newly pasted Slack address gets one message straight away, so a mistyped address is // noticed now and not during an attack. $slack_now = (string) Settings::value( 'slackWebhook' ); if ( '' !== $slack_now && $slack_now !== $slack_before && ! Alerts::slack_connected_message() ) { Settings::update( array( 'slackWebhook' => $slack_before ) ); return new \WP_Error( 'brickmoat_invalid_setting', __( 'Your other settings were saved, but Slack did not accept that webhook address. Copy it again from Slack and paste it here.', 'brickmoat' ), array( 'status' => 400 ) ); } delete_transient( 'brickmoat_protected_routes' ); return rest_ensure_response( Settings::to_rest() ); } /** * A licence key as pasted: surrounding spaces and anything that is not a printable character * removed, every symbol inside the key kept. * * @param mixed $value Raw value. * @return string */ public static function clean_licence_key( $value ) { return (string) preg_replace( '/[^\x21-\x7e]/', '', is_scalar( $value ) ? (string) $value : '' ); } /** * POST /licence: saves and activates a key. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public static function licence_activate( $request ) { $done = Licence::activate( (string) $request['key'] ); if ( is_wp_error( $done ) ) { return $done; } if ( Licence::service_on() ) { // Fetch the shared list straight away, so protection from other stores is on when the page redraws. Pro_Sync::run(); } return rest_ensure_response( Views::state() ); } /** * DELETE /licence. * * @return \WP_REST_Response */ public static function licence_deactivate() { Licence::deactivate(); return rest_ensure_response( Views::state() ); } /** * POST /licence/refresh. * * @return \WP_REST_Response */ public static function licence_refresh() { Licence::refresh( true ); if ( Licence::service_on() ) { Pro_Sync::run(); } return rest_ensure_response( Views::state() ); } /** * POST /onboarding. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public static function onboarding( $request ) { $flags = array(); if ( null !== $request['alertEmail'] ) { $saved = Settings::update( array( 'alertEmails' => array( (string) $request['alertEmail'] ) ) ); if ( is_wp_error( $saved ) ) { return $saved; } $flags['alertEmailSet'] = true; } if ( null !== $request['level'] ) { $saved = Settings::update( array( 'level' => (string) $request['level'] ) ); if ( is_wp_error( $saved ) ) { return $saved; } $flags['levelSet'] = true; } if ( null !== $request['done'] ) { $flags['done'] = (bool) rest_sanitize_boolean( $request['done'] ); } if ( ! empty( $flags ) ) { Settings::set_onboarding( $flags ); } return rest_ensure_response( Views::state() ); } }