$gateway ) { add_action( 'wc_ajax_' . $action, array( __CLASS__, 'gateway_ajax' ), -999 ); } } /** * Gateway AJAX actions that start a payment, and the gateway each belongs to. * * @return array Action name (the part after "wc_ajax_") => gateway id. */ public static function gateway_ajax_actions() { /** * Filters the gateway AJAX actions Brickmoat guards. * * @param array $actions wc-ajax action name => gateway id. */ $actions = apply_filters( 'brickmoat_gateway_ajax_actions', array( // PayPal Payments: creates the PayPal order when the button is pressed. 'ppc-create-order' => 'ppcp-gateway', ) ); $clean = array(); foreach ( (array) $actions as $action => $gateway ) { if ( is_string( $action ) && '' !== $action ) { $clean[ sanitize_text_field( $action ) ] = sanitize_key( (string) $gateway ); } } return $clean; } /** * Remembers that this visitor needs the "I'm human" check, so the storefront script can * show it whichever way the payment was started. * * @param array $decision Result of brickmoat_decide(). */ private static function note_challenge( array $decision ) { if ( Score::CHALLENGE === $decision['decision'] && ! headers_sent() ) { Storefront::set_cookie( 'bm_need', '1', time() + 10 * MINUTE_IN_SECONDS ); } } /** * Reads fields of one of WooCommerce's own forms, after checking that form's nonce. * * WooCommerce checks the same nonce before it acts on the form. It is checked here as well so * that nothing in the form is read, and nothing is decided, for a request that did not come * from the shop's own page. Like WooCommerce, the nonce is accepted in the form's own field * or in _wpnonce. * * @param string $nonce_field Name of the form's nonce field. * @param string $action The nonce action WooCommerce uses for the form. * @param string[] $fields Names of the fields to read. * @param string $trigger A field that must be present for the form to count as sent, or ''. * @return array|null Field name => cleaned value, or null when the nonce is missing or wrong. */ private static function posted( $nonce_field, $action, array $fields, $trigger = '' ) { if ( '' !== $trigger && ! isset( $_POST[ $trigger ] ) ) { return null; } $verified = ( isset( $_REQUEST[ $nonce_field ] ) && false !== wp_verify_nonce( sanitize_text_field( wp_unslash( $_REQUEST[ $nonce_field ] ) ), $action ) ) || ( isset( $_REQUEST['_wpnonce'] ) && false !== wp_verify_nonce( sanitize_text_field( wp_unslash( $_REQUEST['_wpnonce'] ) ), $action ) ); if ( ! $verified ) { return null; } $out = array(); foreach ( $fields as $field ) { $out[ $field ] = isset( $_POST[ $field ] ) && is_string( $_POST[ $field ] ) ? substr( sanitize_text_field( wp_unslash( $_POST[ $field ] ) ), 0, 400 ) : ''; } return $out; } /** * What the cart holds, when there is one. * * @return array{total:float|null,items:int} */ private static function cart_facts() { if ( function_exists( 'WC' ) && WC()->cart && did_action( 'woocommerce_cart_loaded_from_session' ) ) { return array( 'total' => (float) WC()->cart->get_total( 'edit' ), 'items' => (int) WC()->cart->get_cart_contents_count(), ); } return array( 'total' => null, 'items' => 0, ); } /** * Classic checkout. * * @param array $data Posted checkout data. * @param \WP_Error $errors Validation errors; adding one stops the order. */ public static function classic_checkout( $data, $errors ) { try { // Already failing validation: no order will be placed, so there is nothing to decide. if ( ! ( $errors instanceof \WP_Error ) || $errors->has_errors() ) { return; } $data = is_array( $data ) ? $data : array(); $get = static function ( $key ) use ( $data ) { return isset( $data[ $key ] ) && is_scalar( $data[ $key ] ) ? (string) $data[ $key ] : ''; }; $posted = self::posted( 'woocommerce-process-checkout-nonce', 'woocommerce-process_checkout', array( 'bm_token', 'bm_pass', 'bm_hp', 'wc_order_attribution_source_type' ) ); $context = array_merge( self::cart_facts(), array( 'route' => 'checkout_classic', 'posted' => null === $posted ? array() : $posted, 'email' => $get( 'billing_email' ), 'billing_country' => $get( 'billing_country' ), 'first_name' => $get( 'billing_first_name' ), 'last_name' => $get( 'billing_last_name' ), 'address_1' => $get( 'billing_address_1' ), 'postcode' => $get( 'billing_postcode' ), 'gateway' => $get( 'payment_method' ), 'order_id' => WC()->session ? absint( WC()->session->get( 'order_awaiting_payment' ) ) : 0, ) ); if ( null !== $posted && Context::attribution_enabled() ) { $context['origin_unknown'] = Context::origin_is_unknown( '' !== $posted['wc_order_attribution_source_type'] ? $posted['wc_order_attribution_source_type'] : null ); } $decision = brickmoat_decide( $context ); if ( Score::ALLOW !== $decision['decision'] ) { self::note_challenge( $decision ); $errors->add( $decision['code'], esc_html( $decision['message'] ), array( 'id' => Score::CHALLENGE === $decision['decision'] ? 'brickmoat-challenge' : 'brickmoat-notice' ) ); } } catch ( \Throwable $error ) { Util::log_error( 'Classic checkout guard failed, order allowed', $error ); } } /** * Which Store API payment route a REST path is, if any. * * @param string $path REST route or URL path. * @param string $method HTTP method. * @return array{route:string,order_id:int}|null */ public static function match_store_route( $path, $method ) { if ( 'POST' !== strtoupper( (string) $method ) ) { return null; } $path = '/' . ltrim( (string) $path, '/' ); $rest = '/' . trim( rest_get_url_prefix(), '/' ); if ( 0 === strpos( $path, $rest . '/' ) ) { $path = substr( $path, strlen( $rest ) ); } if ( ! preg_match( '#^/wc/store(?:/v1)?/checkout(?:/(\d+))?/?$#', $path, $m ) ) { return null; } return array( 'route' => isset( $m[1] ) ? 'order_pay' : 'checkout_block', 'order_id' => isset( $m[1] ) ? (int) $m[1] : 0, ); } /** * Builds the context for a Store API checkout from its request body. * * @param array $matched Result of match_store_route(). * @param array $body Request parameters. * @return array */ private static function store_context( array $matched, array $body ) { $billing = isset( $body['billing_address'] ) && is_array( $body['billing_address'] ) ? $body['billing_address'] : array(); $get = static function ( $key ) use ( $billing ) { return isset( $billing[ $key ] ) && is_scalar( $billing[ $key ] ) ? sanitize_text_field( (string) $billing[ $key ] ) : ''; }; $context = array( 'route' => $matched['route'], 'order_id' => $matched['order_id'], 'email' => $get( 'email' ), 'billing_country' => $get( 'country' ), 'first_name' => $get( 'first_name' ), 'last_name' => $get( 'last_name' ), 'address_1' => $get( 'address_1' ), 'postcode' => $get( 'postcode' ), 'gateway' => isset( $body['payment_method'] ) && is_string( $body['payment_method'] ) ? $body['payment_method'] : '', ); if ( 'checkout_block' === $matched['route'] && Context::attribution_enabled() ) { $source = isset( $body['extensions']['woocommerce/order-attribution']['source_type'] ) ? $body['extensions']['woocommerce/order-attribution']['source_type'] : null; $context['origin_unknown'] = Context::origin_is_unknown( $source ); } return $context; } /** * Store API, first look: rejects obvious bots before WooCommerce loads the cart or creates an order. * * @param mixed $result Response to send instead of dispatching, normally null. * @param \WP_REST_Server $server Server. * @param \WP_REST_Request $request Request. * @return mixed */ public static function store_api_early( $result, $server, $request ) { if ( null !== $result || ! ( $request instanceof \WP_REST_Request ) ) { return $result; } try { $route = (string) $request->get_route(); if ( 0 !== strpos( $route, '/wc/store' ) ) { return $result; } $found = array(); $match = self::match_store_route( $route, $request->get_method() ); if ( $match ) { $found[] = array( $match, (array) $request->get_params() ); } elseif ( preg_match( '#^/wc/store(?:/v1)?/batch/?$#', $route ) && 'POST' === $request->get_method() ) { // A batch can carry a checkout inside it. foreach ( (array) $request->get_param( 'requests' ) as $sub ) { if ( ! is_array( $sub ) || empty( $sub['path'] ) || ! is_string( $sub['path'] ) ) { continue; } $path = (string) wp_parse_url( $sub['path'], PHP_URL_PATH ); $match = self::match_store_route( $path, isset( $sub['method'] ) ? $sub['method'] : 'POST' ); if ( $match ) { $found[] = array( $match, isset( $sub['body'] ) && is_array( $sub['body'] ) ? $sub['body'] : array() ); } } } if ( empty( $found ) ) { return $result; } // A real checkout never places more than one order per request. if ( count( $found ) > 1 ) { return new \WP_Error( 'brickmoat_blocked', __( 'Sorry, we could not process your order. Please try again later or contact us for help.', 'brickmoat' ), array( 'status' => 403 ) ); } $context = self::store_context( $found[0][0], $found[0][1] ); $context['stage'] = 'early'; $decision = brickmoat_decide( $context ); if ( Score::ALLOW !== $decision['decision'] ) { self::note_challenge( $decision ); return new \WP_Error( $decision['code'], $decision['message'], array( 'status' => 403 ) ); } } catch ( \Throwable $error ) { Util::log_error( 'Store API guard failed, request allowed', $error ); } return $result; } /** * Store API, second look: the order now exists, so its total and items are known. * * @param \WC_Order $order Order. * @param \WP_REST_Request $request Request. * @throws \Automattic\WooCommerce\StoreApi\Exceptions\RouteException When the attempt is stopped. */ public static function store_api_order( $order, $request ) { $decision = null; try { if ( ! ( $order instanceof \WC_Order ) || ! ( $request instanceof \WP_REST_Request ) ) { return; } $match = self::match_store_route( (string) $request->get_route(), $request->get_method() ); if ( ! $match ) { return; } $context = array_merge( self::store_context( $match, (array) $request->get_params() ), array( 'order_id' => $order->get_id(), 'total' => (float) $order->get_total(), 'items' => (int) $order->get_item_count(), ) ); if ( '' === $context['email'] ) { $context['email'] = (string) $order->get_billing_email(); } if ( '' === $context['billing_country'] ) { $context['billing_country'] = (string) $order->get_billing_country(); } $decision = brickmoat_decide( $context ); self::note_challenge( $decision ); } catch ( \Throwable $error ) { Util::log_error( 'Store API order guard failed, order allowed', $error ); return; } if ( is_array( $decision ) && Score::ALLOW !== $decision['decision'] && class_exists( '\Automattic\WooCommerce\StoreApi\Exceptions\RouteException' ) ) { throw new \Automattic\WooCommerce\StoreApi\Exceptions\RouteException( esc_html( $decision['code'] ), esc_html( $decision['message'] ), 403 ); } } /** * Pay for an existing order. * * @param \WC_Order $order Order being paid. */ public static function order_pay( $order ) { try { if ( ! ( $order instanceof \WC_Order ) ) { return; } $posted = self::posted( 'woocommerce-pay-nonce', 'woocommerce-pay', array( 'payment_method', 'bm_token', 'bm_pass' ) ); $gateway = null === $posted ? '' : sanitize_key( $posted['payment_method'] ); $decision = brickmoat_decide( array( 'route' => 'order_pay', 'posted' => null === $posted ? array() : $posted, 'order_id' => $order->get_id(), 'email' => (string) $order->get_billing_email(), 'billing_country' => (string) $order->get_billing_country(), 'first_name' => (string) $order->get_billing_first_name(), 'last_name' => (string) $order->get_billing_last_name(), 'address_1' => (string) $order->get_billing_address_1(), 'postcode' => (string) $order->get_billing_postcode(), 'total' => (float) $order->get_total(), 'items' => (int) $order->get_item_count(), 'gateway' => $gateway, ) ); if ( Score::ALLOW !== $decision['decision'] ) { self::note_challenge( $decision ); // WooCommerce only takes the payment when there are no error notices. wc_add_notice( esc_html( $decision['message'] ), 'error', array( 'id' => Score::CHALLENGE === $decision['decision'] ? 'brickmoat-challenge' : 'brickmoat-notice' ) ); } } catch ( \Throwable $error ) { Util::log_error( 'Pay-for-order guard failed, payment allowed', $error ); } } /** * Add payment method: runs before WooCommerce's form handler and withdraws the form when stopped. */ public static function add_payment_method() { // Only the "add payment method" form, and only with the nonce WooCommerce put in it. Without // that nonce WooCommerce ignores the form too, so there is nothing to decide. $posted = self::posted( 'woocommerce-add-payment-method-nonce', 'woocommerce-add-payment-method', array( 'payment_method', 'bm_token', 'bm_pass' ), 'woocommerce_add_payment_method' ); if ( null === $posted || '' === $posted['payment_method'] ) { return; } try { $user = wp_get_current_user(); $decision = brickmoat_decide( array( 'route' => 'add_payment_method', 'email' => $user && $user->exists() ? (string) $user->user_email : '', 'gateway' => sanitize_key( $posted['payment_method'] ), 'posted' => $posted, ) ); if ( Score::ALLOW !== $decision['decision'] ) { self::note_challenge( $decision ); self::withdraw_add_payment_method(); if ( function_exists( 'wc_add_notice' ) ) { wc_add_notice( esc_html( $decision['message'] ), 'error', array( 'id' => Score::CHALLENGE === $decision['decision'] ? 'brickmoat-challenge' : 'brickmoat-notice' ) ); } } } catch ( \Throwable $error ) { Util::log_error( 'Add-payment-method guard failed, request allowed', $error ); } } /** * Takes the "add payment method" form out of the request, so WooCommerce's own handler, which * runs later, does not send the card to the gateway. Called only after the form's nonce was * checked in add_payment_method(). */ private static function withdraw_add_payment_method() { unset( $_POST['woocommerce_add_payment_method'] ); } /** * A gateway's own AJAX call that starts a payment (for example the PayPal button). */ public static function gateway_ajax() { $decision = null; try { $action = substr( (string) current_action(), 8 ); $actions = self::gateway_ajax_actions(); $customer = function_exists( 'WC' ) && WC()->customer ? WC()->customer : null; $decision = brickmoat_decide( array_merge( self::cart_facts(), array( 'route' => 'gateway_ajax', 'gateway' => isset( $actions[ $action ] ) ? $actions[ $action ] : '', 'email' => $customer ? (string) $customer->get_billing_email() : '', 'billing_country' => $customer ? (string) $customer->get_billing_country() : '', ) ) ); self::note_challenge( $decision ); } catch ( \Throwable $error ) { Util::log_error( 'Gateway guard failed, request allowed', $error ); return; } if ( is_array( $decision ) && Score::ALLOW !== $decision['decision'] ) { wp_send_json_error( array( 'name' => 'CHECKOUT_ERROR', 'message' => $decision['message'], 'code' => 0, 'details' => array(), ) ); } } }