Codexta Assistant admin page. */ class Codexta_Connect { const DEFAULT_BASE_URL = 'https://codexta.codectaapps.com'; const PAGE = 'codexta-assistant'; const OPTIONS = array( 'codexta_site_uuid', 'codexta_base_url', 'codexta_server_url', 'codexta_shared_secret', 'codexta_nonce_hash', 'codexta_orders_send', 'codexta_orders_assisted_only', 'codexta_orders_minimal' ); /** * Register hooks. */ public static function init() { add_action( 'admin_menu', array( __CLASS__, 'menu' ) ); add_action( 'admin_post_codexta_save_settings', array( __CLASS__, 'save_settings' ) ); add_action( 'admin_post_codexta_connect', array( __CLASS__, 'connect' ) ); add_action( 'admin_post_codexta_disconnect', array( __CLASS__, 'disconnect' ) ); add_action( 'admin_post_codexta_open', array( __CLASS__, 'open' ) ); add_action( 'admin_enqueue_scripts', array( __CLASS__, 'admin_scripts' ) ); } /** * The admin page's hook suffix, set when the menu is registered. * * @var string */ private static $hook_suffix = ''; /* ------------------------------------------------------------------ state */ /** * The site id (lowercase uuid v4): created on first use, normally at activation. * * @return string */ public static function site_uuid() { $uuid = (string) get_option( 'codexta_site_uuid', '' ); if ( '' === $uuid ) { $uuid = strtolower( wp_generate_uuid4() ); update_option( 'codexta_site_uuid', $uuid, false ); } return $uuid; } /** * Codexta origin as the visitor's browser reaches it. * * @return string */ public static function base_url() { return self::clean_origin( (string) get_option( 'codexta_base_url', self::DEFAULT_BASE_URL ) ); } /** * Codexta origin as this server reaches it (differs from base_url() only in container setups). * * @return string */ public static function server_url() { $url = (string) get_option( 'codexta_server_url', '' ); return '' !== $url ? self::clean_origin( $url ) : self::base_url(); } /** * The origin (scheme://host[:port]) of the browser-facing Codexta URL. * * @return string */ public static function base_origin() { $parts = wp_parse_url( self::base_url() ); if ( empty( $parts['scheme'] ) || empty( $parts['host'] ) ) { return ''; } return $parts['scheme'] . '://' . $parts['host'] . ( isset( $parts['port'] ) ? ':' . $parts['port'] : '' ); } /** * Whether the handshake completed. * * @return bool */ public static function is_connected() { return self::has_valid_urls() && '' !== self::shared_secret(); } private static function has_valid_urls() { return '' !== self::base_url() && '' !== self::server_url(); } /** * The shared secret, decrypted. Empty when not connected. * * @return string */ public static function shared_secret() { $stored = (string) get_option( 'codexta_shared_secret', '' ); if ( '' === $stored ) { return ''; } $raw = base64_decode( $stored, true ); if ( false === $raw || strlen( $raw ) < 29 ) { return ''; } $plain = openssl_decrypt( substr( $raw, 28 ), 'aes-256-gcm', self::key(), OPENSSL_RAW_DATA, substr( $raw, 0, 12 ), substr( $raw, 12, 16 ) ); return false === $plain ? '' : $plain; } /** * Encrypt and store the shared secret (AES-256-GCM, key derived from wp_salt('auth')). * * @param string $secret Plain secret. */ private static function store_secret( $secret ) { $iv = random_bytes( 12 ); $tag = ''; $ciphertext = openssl_encrypt( $secret, 'aes-256-gcm', self::key(), OPENSSL_RAW_DATA, $iv, $tag ); update_option( 'codexta_shared_secret', base64_encode( $iv . $tag . $ciphertext ), false ); } /** * Encryption key derived from the site's salt. * * @return string */ private static function key() { return hash( 'sha256', wp_salt( 'auth' ), true ); } /* ------------------------------------------------------------------ admin page */ /** * URL of this plugin's admin page. * * @return string */ public static function page_url() { return admin_url( 'admin.php?page=' . self::PAGE ); } /** * Register the page under WooCommerce. */ public static function menu() { $hook = add_submenu_page( 'woocommerce', __( 'Codexta Assistant', 'codexta-assistant' ), __( 'Codexta Assistant', 'codexta-assistant' ), 'manage_woocommerce', self::PAGE, array( __CLASS__, 'render' ) ); add_action( 'load-' . $hook, array( __CLASS__, 'handle_return' ) ); self::$hook_suffix = $hook; } /** * Remember a message for the next page view of this user. * * @param string $type success or error. * @param string $message Text. */ private static function flash( $type, $message ) { set_transient( 'codexta_notice_' . get_current_user_id(), array( $type, $message ), MINUTE_IN_SECONDS ); } /** * Redirect back to the admin page. */ private static function back() { wp_safe_redirect( self::page_url() ); exit; } /** * Gate for the admin-post handlers. * * @param string $action Nonce action. */ private static function guard( $action ) { if ( ! current_user_can( 'manage_woocommerce' ) ) { wp_die( esc_html__( 'You do not have permission to do this.', 'codexta-assistant' ), '', array( 'response' => 403 ) ); } check_admin_referer( $action ); } /** * Normalise a settings URL to an allowed origin. Empty when invalid. * * @param string $url Raw input. * @return string */ public static function clean_origin( $url ) { $schemes = in_array( wp_get_environment_type(), array( 'local', 'development' ), true ) ? array( 'https', 'http' ) : array( 'https' ); $parts = wp_parse_url( trim( $url ) ); if ( empty( $parts['scheme'] ) || empty( $parts['host'] ) || ! in_array( strtolower( $parts['scheme'] ), $schemes, true ) || isset( $parts['user'] ) || isset( $parts['pass'] ) ) { return ''; } $origin = strtolower( $parts['scheme'] ) . '://' . $parts['host'] . ( isset( $parts['port'] ) ? ':' . $parts['port'] : '' ); return $origin === esc_url_raw( $origin, $schemes ) ? $origin : ''; } /** * Save the settings; the two Codexta URLs only for an administrator. */ public static function save_settings() { if ( ! current_user_can( 'manage_woocommerce' ) ) { wp_die( esc_html__( 'You do not have permission to do this.', 'codexta-assistant' ), '', array( 'response' => 403 ) ); } check_admin_referer( 'codexta_save_settings' ); // The two URLs decide where the script loaded on every storefront page (checkout included) comes from: administrators only. // For a shop manager they are shown read-only and not posted, so what is stored stays as it is. if ( current_user_can( 'manage_options' ) ) { $base = isset( $_POST['codexta_base_url'] ) && is_string( $_POST['codexta_base_url'] ) ? self::clean_origin( sanitize_text_field( wp_unslash( $_POST['codexta_base_url'] ) ) ) : ''; $raw_server = isset( $_POST['codexta_server_url'] ) && is_string( $_POST['codexta_server_url'] ) ? sanitize_text_field( wp_unslash( $_POST['codexta_server_url'] ) ) : ''; $server = self::clean_origin( $raw_server ); if ( '' === $base || ( isset( $_POST['codexta_server_url'] ) && ! is_string( $_POST['codexta_server_url'] ) ) || ( '' !== $raw_server && '' === $server ) ) { self::flash( 'error', __( 'Enter valid HTTPS URLs for Codexta. HTTP is allowed only on local and development sites.', 'codexta-assistant' ) ); self::back(); } update_option( 'codexta_base_url', $base, false ); update_option( 'codexta_server_url', $server, false ); } $send = isset( $_POST['codexta_orders_send'] ); update_option( Codexta_Orders::OPT_SEND, $send ? 'yes' : 'no', false ); if ( $send ) { // With sending off the two limits are greyed out, not posted: keep what they were. update_option( Codexta_Orders::OPT_ASSISTED_ONLY, isset( $_POST['codexta_orders_assisted_only'] ) ? 'yes' : 'no', false ); update_option( Codexta_Orders::OPT_MINIMAL, isset( $_POST['codexta_orders_minimal'] ) ? 'yes' : 'no', false ); } self::flash( 'success', __( 'Settings saved.', 'codexta-assistant' ) ); self::back(); } /** * Start the connection: remember a one-time nonce and send the admin to WooCommerce's authorize screen. */ public static function connect() { self::guard( 'codexta_connect' ); if ( ! self::has_valid_urls() ) { self::flash( 'error', __( 'Save valid Codexta URLs in Settings before connecting.', 'codexta-assistant' ) ); self::back(); } $nonce = bin2hex( random_bytes( 16 ) ); update_option( 'codexta_nonce_hash', hash( 'sha256', $nonce ), false ); set_transient( 'codexta_nonce', $nonce, 15 * MINUTE_IN_SECONDS ); // WooCommerce url-decodes the callback again before it posts, so a character that needs encoding in `site` arrives // decoded; a home URL has none that matter ("&", "#"), so the callback keeps its two query values apart. $callback = self::server_url() . '/integrations/woocommerce/callback?' . http_build_query( array( 'site' => home_url(), 'n' => $nonce, ), '', '&', PHP_QUERY_RFC3986 ); $authorize = home_url( '/wc-auth/v1/authorize' ) . '?' . http_build_query( array( 'app_name' => 'Codexta Assistant', 'scope' => 'read_write', 'user_id' => self::site_uuid(), 'return_url' => add_query_arg( array( 'codexta_return' => '1', '_wpnonce' => wp_create_nonce( 'codexta_return' ), ), self::page_url() ), 'callback_url' => $callback, ), '', '&', PHP_QUERY_RFC3986 ); wp_safe_redirect( $authorize ); exit; } /** * Back from WooCommerce's authorize screen (?codexta_return=1): finish with the server-side handshake. */ public static function handle_return() { if ( ! isset( $_GET['codexta_return'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- only decides whether this is the return; the nonce is checked next. return; } // The return URL handed to WooCommerce carries a nonce of the admin who clicked Connect; WooCommerce adds success and user_id to it. if ( ! current_user_can( 'manage_woocommerce' ) || ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'codexta_return' ) ) { self::flash( 'error', __( 'The connection attempt expired. Please click Connect again.', 'codexta-assistant' ) ); self::back(); } $success = isset( $_GET['success'] ) && '1' === sanitize_text_field( wp_unslash( $_GET['success'] ) ); $user_id = isset( $_GET['user_id'] ) ? sanitize_text_field( wp_unslash( $_GET['user_id'] ) ) : ''; $nonce = (string) get_transient( 'codexta_nonce' ); delete_transient( 'codexta_nonce' ); if ( ! $success ) { self::flash( 'error', __( 'The connection was cancelled.', 'codexta-assistant' ) ); } elseif ( $user_id !== self::site_uuid() || '' === $nonce || ! hash_equals( (string) get_option( 'codexta_nonce_hash', '' ), hash( 'sha256', $nonce ) ) ) { self::flash( 'error', __( 'The connection attempt expired. Please click Connect again.', 'codexta-assistant' ) ); } else { $error = self::handshake( $nonce ); if ( '' === $error ) { Codexta_Lifecycle::revoke_api_keys( true ); // The keys of earlier connections are of no use any more. self::flash( 'success', __( 'Connected to Codexta.', 'codexta-assistant' ) ); } else { self::flash( 'error', $error ); } } delete_option( 'codexta_nonce_hash' ); self::back(); } /** * Trade the nonce for the shared secret. * * @param string $nonce The plain nonce. * @return string Error message, empty on success. */ private static function handshake( $nonce ) { if ( ! self::has_valid_urls() ) { return __( 'Save valid Codexta URLs in Settings before connecting.', 'codexta-assistant' ); } $response = wp_remote_post( self::server_url() . '/integrations/woocommerce/handshake', array( 'timeout' => 15, 'redirection' => 0, 'headers' => array( 'Content-Type' => 'application/json' ), 'body' => wp_json_encode( array( 'uuid' => self::site_uuid(), 'nonce' => $nonce, ) ), ) ); if ( is_wp_error( $response ) ) { /* translators: %s: error message */ return sprintf( __( 'Could not reach Codexta: %s', 'codexta-assistant' ), $response->get_error_message() ); } $code = wp_remote_retrieve_response_code( $response ); $data = json_decode( wp_remote_retrieve_body( $response ), true ); if ( 200 !== $code || ! is_array( $data ) || empty( $data['sharedSecret'] ) || ! is_string( $data['sharedSecret'] ) || ! preg_match( '/^[A-Za-z0-9_-]{32,128}$/', $data['sharedSecret'] ) ) { /* translators: %d: HTTP status */ return sprintf( __( 'Codexta did not accept the connection (HTTP %d). Please try again.', 'codexta-assistant' ), $code ); } self::store_secret( $data['sharedSecret'] ); return ''; } /** * Disconnect: tell Codexta, drop the secret and the WooCommerce key. */ public static function disconnect() { self::guard( 'codexta_disconnect' ); Codexta_Lifecycle::ping( 'uninstalled' ); Codexta_Lifecycle::remove_webhooks(); Codexta_Lifecycle::revoke_api_keys(); delete_option( 'codexta_shared_secret' ); delete_option( 'codexta_nonce_hash' ); self::flash( 'success', __( 'Disconnected from Codexta.', 'codexta-assistant' ) ); self::back(); } /** * Open Codexta: send the staff member to Codexta's admin with a one-minute, single-use token of who they are. */ public static function open() { self::guard( 'codexta_open' ); if ( ! self::has_valid_urls() ) { self::flash( 'error', __( 'Save valid Codexta URLs in Settings before opening the dashboard.', 'codexta-assistant' ) ); self::back(); } $token = Codexta_Token::launch(); if ( '' === $token ) { self::flash( 'error', __( 'Connect to Codexta first.', 'codexta-assistant' ) ); self::back(); } $url = self::base_url() . '/integrations/woocommerce/admin?' . http_build_query( array( 'codexta_launch' => $token ) ); // A link into one page of the admin (the weekly demand mail opens Unanswered): codexta_page= becomes #/. $page = isset( $_POST['codexta_page'] ) ? sanitize_key( wp_unslash( $_POST['codexta_page'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- checked in guard(). if ( '' !== $page && preg_match( '/^[a-z-]{1,32}$/', $page ) ) { $url .= '#/' . $page; } $host = wp_parse_url( self::base_url(), PHP_URL_HOST ); add_filter( 'allowed_redirect_hosts', function ( $hosts ) use ( $host ) { $hosts[] = $host; return $hosts; } ); wp_safe_redirect( $url ); exit; } /** * Render the page. */ public static function render() { $notice = get_transient( 'codexta_notice_' . get_current_user_id() ); delete_transient( 'codexta_notice_' . get_current_user_id() ); $connected = '' !== self::shared_secret(); echo '

' . esc_html__( 'Codexta Assistant', 'codexta-assistant' ) . '

'; if ( is_array( $notice ) ) { printf( '

%s

', esc_attr( 'success' === $notice[0] ? 'success' : 'error' ), esc_html( $notice[1] ) ); } if ( ! self::has_valid_urls() ) { echo '

' . esc_html__( 'Codexta needs valid URLs. Update them in Settings to restore the storefront assistant and dashboard access.', 'codexta-assistant' ) . '

'; } if ( $connected ) { self::render_connected(); } else { self::render_disconnected(); } self::render_settings(); echo '
'; } /** * Not connected: explain, then the Connect button. */ private static function render_disconnected() { echo '

' . esc_html__( 'Connect your store to the Codexta service to add an AI shopping assistant to your storefront and an assistant to this dashboard.', 'codexta-assistant' ) . '

'; echo '

' . wp_kses( sprintf( /* translators: %s: Codexta URL */ __( 'Clicking Connect asks you to approve a WooCommerce REST API key for Codexta (%s). Nothing is sent to Codexta before that, and the assistant is not shown on your storefront until the connection is made.', 'codexta-assistant' ), '' . esc_html( self::base_url() ) . '' ), array( 'code' => array() ) ) . '

'; echo '
'; echo ''; wp_nonce_field( 'codexta_connect' ); submit_button( __( 'Connect to Codexta', 'codexta-assistant' ), 'primary', 'submit', false ); echo '
'; } /** * On this plugin's page only: grey out the two order limits while sending orders is off. * * @param string $hook_suffix The admin page being loaded. */ public static function admin_scripts( $hook_suffix ) { if ( '' === self::$hook_suffix || self::$hook_suffix !== $hook_suffix ) { return; } wp_register_script( 'codexta-settings', false, array(), CODEXTA_ASSISTANT_VERSION, true ); wp_enqueue_script( 'codexta-settings' ); wp_add_inline_script( 'codexta-settings', '( function () { var send = document.getElementById( "codexta_orders_send" ), box = document.getElementById( "codexta-order-limits" ); if ( ! send || ! box ) { return; } function sync() { box.style.opacity = send.checked ? "" : "0.5"; box.querySelectorAll( "input" ).forEach( function ( i ) { i.disabled = ! send.checked; } ); } send.addEventListener( "change", sync ); sync(); } )();' ); } /** * Connected: status, the button that opens Codexta's admin in a new tab, and Disconnect. */ private static function render_connected() { // A link into one page of the admin (the weekly demand mail opens Unanswered): ?codexta_page= goes along with the button. $page = isset( $_GET['codexta_page'] ) ? sanitize_key( wp_unslash( $_GET['codexta_page'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- only pre-fills a hidden field of the nonce-protected Open form. echo '

' . esc_html__( 'Status: Connected', 'codexta-assistant' ) . '

'; echo '

' . wp_kses( sprintf( /* translators: %s: Codexta URL */ __( 'Your assistant\'s conversations, knowledge, team and settings are managed on the Codexta website (%s). The button opens it in a new tab and signs you in as this WordPress user; nothing is loaded from Codexta until you click it.', 'codexta-assistant' ), '' . esc_html( self::base_url() ) . '' ), array( 'code' => array() ) ) . '

'; echo '
'; echo ''; if ( '' !== $page ) { echo ''; } wp_nonce_field( 'codexta_open' ); submit_button( __( 'Open Codexta dashboard', 'codexta-assistant' ), 'primary', 'submit', false ); echo '
'; echo '
'; echo ''; wp_nonce_field( 'codexta_disconnect' ); submit_button( __( 'Disconnect', 'codexta-assistant' ), 'secondary', 'submit', false ); echo '
'; } /** * The two Codexta URLs. */ private static function render_settings() { echo '

' . esc_html__( 'Settings', 'codexta-assistant' ) . '

'; echo '
'; wp_nonce_field( 'codexta_save_settings' ); $can_urls = current_user_can( 'manage_options' ); // Others see the URLs but cannot change them. $locked = $can_urls ? '' : ' readonly'; echo ''; printf( '', esc_html__( 'Codexta URL', 'codexta-assistant' ), esc_attr( (string) get_option( 'codexta_base_url', self::DEFAULT_BASE_URL ) ), esc_attr( $locked ), esc_html__( 'Where your visitors\' browsers reach Codexta.', 'codexta-assistant' ) . ( $can_urls ? '' : ' ' . esc_html__( 'Only an administrator can change this.', 'codexta-assistant' ) ) ); printf( '', esc_html__( 'Server URL', 'codexta-assistant' ), esc_attr( (string) get_option( 'codexta_server_url', '' ) ), esc_attr( $locked ), esc_html__( 'Optional. Where this server reaches Codexta, if different from the URL above (for example inside a container).', 'codexta-assistant' ) ); printf( '', esc_html__( 'Order attribution', 'codexta-assistant' ), checked( Codexta_Orders::enabled( Codexta_Orders::OPT_SEND ), true, false ), esc_html__( 'Send order attribution webhooks', 'codexta-assistant' ), esc_html__( 'These webhooks let Codexta credit orders that came from a chat. Turning them off stops attribution webhooks. The assistant can still look up orders through the WooCommerce API while connected. Customer deletion notifications are handled separately.', 'codexta-assistant' ), checked( Codexta_Orders::enabled( Codexta_Orders::OPT_ASSISTED_ONLY ), true, false ), esc_html__( 'Only orders the assistant helped with', 'codexta-assistant' ), esc_html__( 'Send attribution webhooks only for orders containing a product the assistant added to the cart. Turning this limit off sends an attribution webhook for every new order.', 'codexta-assistant' ), checked( Codexta_Orders::enabled( Codexta_Orders::OPT_MINIMAL ), true, false ), esc_html__( 'Only the details needed to credit the order', 'codexta-assistant' ), esc_html__( 'Codexta receives the order number, total, currency, date, customer number and the amounts of each line, and no name, address, phone number or email.', 'codexta-assistant' ) ); echo ''; submit_button( __( 'Save settings', 'codexta-assistant' ), 'secondary' ); echo '
'; } }