[A-Za-z0-9_-]{43})', array( 'methods' => 'GET', 'permission_callback' => '__return_true', 'callback' => function ( $request ) { $proof = self::proof( $request->get_param( 'attempt' ) ); $response = new WP_REST_Response( null === $proof ? array( 'error' => 'not_found' ) : $proof, null === $proof ? 404 : 200 ); $response->header( 'Cache-Control', 'no-store' ); $response->header( 'Referrer-Policy', 'no-referrer' ); $response->header( 'Content-Type', 'application/json' ); return $response; }, ) ); } ); } /** * Start or retry one local attempt. * * The sole network destinations come from the operator profile. * * @return array * @throws InvalidArgumentException When the current user or environment is invalid. * @throws RuntimeException When state or authority operations fail. */ public static function run() { if ( ! current_user_can( 'manage_woocommerce' ) ) { throw new InvalidArgumentException( 'connect_admin_required' ); } $identity = self::preflight(); $profile = Aha_Is_Woocommerce_Connect_Profile::from_operator_config(); $derived = Aha_Is_Woocommerce_Connect_Crypto::derive_kek( Aha_Is_Woocommerce_Connect_Crypto::wp_secrets(), $identity ); $repository = new Aha_Is_Woocommerce_Connect_State(); $sweep = false; $context = compact( 'identity', 'profile', 'derived', 'repository' ); $state = $repository->with_lock( $identity, function ( $db ) use ( $identity, $profile, $derived, $context, &$sweep ) { $old = $db->read(); if ( null !== $old ) { $state = self::unpack( $old, $derived, $identity ); if ( ( $state['user_id'] !== get_current_user_id() && ! ( Aha_Is_Woocommerce_Connect_Credentials::owner_lost( $state ) && current_user_can( 'manage_woocommerce' ) ) ) || $state['request']['environment'] !== $profile['environment'] || $state['request']['authority'] !== $profile['authority'] ) { throw new RuntimeException( 'connect_attempt_bound_to_other_user' ); } if ( in_array( $state['phase'], array( 'proof_failed', 'attempt_expired', 'rejected', 'access_revoked', 'connection_lost' ), true ) ) { Aha_Is_Woocommerce_Connect_Credentials::tombstone_catalog_keys( $db, $state, $context ); $db->delete( $old ); // Only the bound owner may replace a proven terminal attempt. $sweep = true; } elseif ( $state['phase'] === 'proof_ready' && time() >= $state['local_deadline'] ) { $reconciled = self::reconcile_expired_proof_ready( $state, $profile, // Owner/takeover was checked above; pass the effective owner so the helper's own check holds. $state['user_id'], function ( $url, $body ) { return self::post_json( $url, $body, 200 ); }, function( $terminal ) use ( $db, $old, $state, $derived, $identity ) { $current = self::unpack( $db->read(), $derived, $identity ); if ( $current['phase'] !== 'proof_ready' || Aha_Is_Woocommerce_Connect_Crypto::canonical_json( $current['request'] ) !== Aha_Is_Woocommerce_Connect_Crypto::canonical_json( $state['request'] ) ) { throw new RuntimeException( 'connect_state_conflict' ); } $current['phase'] = $terminal; $db->cas( $old, self::pack( $current, $derived, $identity ) ); } ); return array_merge( $state, array( 'phase' => $reconciled ) ); } elseif ( $state['phase'] === 'origin_verified' && time() >= $state['local_deadline'] ) { $reconciled = self::reconcile_expired_origin_verified( $state, $profile, // Owner/takeover was checked above; pass the effective owner so the helper's own check holds. $state['user_id'], function ( $url, $body ) { return self::post_json( $url, $body, 200 ); }, function () use ( $db, $old, $state, $derived, $identity ) { $current = self::unpack( $db->read(), $derived, $identity ); if ( $current['phase'] !== 'origin_verified' || Aha_Is_Woocommerce_Connect_Crypto::canonical_json( $current['request'] ) !== Aha_Is_Woocommerce_Connect_Crypto::canonical_json( $state['request'] ) || ! hash_equals( $current['local_state'], $state['local_state'] ) ) { throw new RuntimeException( 'connect_state_conflict' ); } $db->delete( $old ); } ); if ( 'attempt_expired' !== $reconciled ) { return array_merge( $state, array( 'phase' => $reconciled ) ); } } elseif ( $state['phase'] !== 'prepared' && time() >= $state['local_deadline'] ) { return array_merge( $state, array( 'phase' => 'expired_unresolved' ) ); } else { return $state; } } $keys = Aha_Is_Woocommerce_Connect_Crypto::generate_keys(); $local_state = Aha_Is_Woocommerce_Connect_Crypto::base64url( random_bytes( 32 ) ); $attempt = Aha_Is_Woocommerce_Connect_Crypto::base64url( random_bytes( 32 ) ); $version = function_exists( 'WC' ) && WC() && isset( WC()->version ) ? WC()->version : ''; $request = Aha_Is_Woocommerce_Connect_Bootstrap::build( array( 'integration_type' => 'woocommerce', 'protocol_version' => '1.0', 'adapter_version' => AHA_IS_WOOCOMMERCE_PLUGIN_VERSION, 'client_attempt_id' => $attempt, 'origin' => $identity['origin'], 'installation_signing_public_key_jwk' => $keys['signing_public'], 'signing_key_generation' => 1, 'installation_encryption_public_key_jwk' => $keys['encryption_public'], 'encryption_key_generation' => 1, 'local_state_hash' => self::local_state_hash( $local_state ), 'adapter_claims' => array( 'local_source_claim_id' => $identity['installation_uuid'] ), 'versions' => array( 'plugin' => AHA_IS_WOOCOMMERCE_PLUGIN_VERSION, 'wordpress' => get_bloginfo( 'version' ), 'woocommerce' => $version ), ), $profile ); $state = array( 'phase' => 'prepared', 'request' => $request, 'response' => null, 'keys' => $keys, 'local_state' => $local_state, 'user_id' => get_current_user_id(), 'local_deadline' => time() + 600, 'login_uri' => null ); $db->insert( self::pack( $state, $derived, $identity ) ); return $state; } ); if ( $sweep ) { Aha_Is_Woocommerce_Connect_Credentials::sweep_catalog_keys( $context ); } if ( in_array( $state['phase'], array( 'expired_unresolved', 'proof_failed', 'attempt_expired' ), true ) ) { return array( 'status' => $state['phase'] ); } if ( $state['phase'] === 'origin_verified' ) { if ( self::login_handle_used( $state, $profile ) ) { return array( 'status' => 'login_used' ); } return array( 'status' => 'origin_verified', 'login_uri' => $state['login_uri'], 'local_state' => $state['local_state'] ); } if ( $state['phase'] === 'prepared' ) { $response = self::post_json( $profile['authority'] . '/connect/v1/bootstrap', $state['request'], 201, true ); if ( $response === array( 'error' => 'attempt_expired' ) ) { $repository->with_lock( $identity, function( $db ) use ( $identity, $derived, $state ) { $old = $db->read(); $current = self::unpack( $old, $derived, $identity ); self::assert_prepared_retry( $current, $state ); $current['phase'] = 'attempt_expired'; $db->cas( $old, self::pack( $current, $derived, $identity ) ); } ); throw new RuntimeException( 'connect_attempt_expired' ); } $expiry = Aha_Is_Woocommerce_Connect_Proof::validate_response( $response, $profile )->getTimestamp(); if ( $expiry <= time() || $expiry > time() + 660 ) { throw new RuntimeException( 'connect_invalid_authority_response' ); } $repository->with_lock( $identity, function ( $db ) use ( $identity, $derived, $state, $response, $expiry ) { $old = $db->read(); $current = self::unpack( $old, $derived, $identity ); self::assert_prepared_retry( $current, $state ); $current['response'] = $response; $current['phase'] = 'proof_ready'; $current['local_deadline'] = $expiry; $db->cas( $old, self::pack( $current, $derived, $identity ) ); } ); $state['response'] = $response; } if ( ! isset( $state['response']['status_token'] ) ) { throw new RuntimeException( 'connect_response_missing' ); } // Arm the anonymous proof route for exactly this attempt; proof() only uses it to reject early. set_transient( self::PROOF_GATE . get_current_blog_id(), hash( 'sha256', $state['request']['client_attempt_id'] ), max( 1, min( 660, strtotime( $state['response']['expires_at'] ) - time() ) ) ); $status = self::post_json( $profile['authority'] . '/connect/v1/bootstrap/status', array( 'status_token' => $state['response']['status_token'] ), 200 ); $login_uri = Aha_Is_Woocommerce_Connect_Proof::validate_status( $status, $profile ); if ( null !== $login_uri ) { $repository->with_lock( $identity, function ( $db ) use ( $identity, $derived, $state, $login_uri ) { $old = $db->read(); $current = self::unpack( $old, $derived, $identity ); if ( $current['phase'] !== 'proof_ready' || Aha_Is_Woocommerce_Connect_Crypto::canonical_json( $current['request'] ) !== Aha_Is_Woocommerce_Connect_Crypto::canonical_json( $state['request'] ) ) { throw new RuntimeException( 'connect_state_conflict' ); } $current['phase'] = 'origin_verified'; $current['login_uri'] = $login_uri; $db->cas( $old, self::pack( $current, $derived, $identity ) ); } ); return array( 'status' => 'origin_verified', 'login_uri' => $login_uri, 'local_state' => $state['local_state'] ); } if ( in_array( $status['status'], array( 'proof_failed', 'attempt_expired' ), true ) ) { $repository->with_lock( $identity, function ( $db ) use ( $identity, $derived, $state, $status ) { $old = $db->read(); $current = self::unpack( $old, $derived, $identity ); if ( $current['phase'] !== 'proof_ready' || $current['request']['client_attempt_id'] !== $state['request']['client_attempt_id'] ) { throw new RuntimeException( 'connect_state_conflict' ); } $current['phase'] = $status['status']; $db->cas( $old, self::pack( $current, $derived, $identity ) ); } ); } return array( 'status' => $status['status'] ); } /** * Reconcile under the caller's storage lock. * * Only an exact remote terminal permits a retry. * * @param array $state Connect state. * @param array $profile Deployment profile. * @param int $user_id User identifier. * @param callable $poll Status poll callback. * @param callable $terminal_cas Terminal transition callback. * @return string * @throws InvalidArgumentException When the polled status response is invalid. * @throws RuntimeException When state ownership or response data is invalid. */ public static function reconcile_expired_proof_ready( array $state, array $profile, $user_id, callable $poll, callable $terminal_cas ) { if ( $state['phase'] !== 'proof_ready' || $state['user_id'] !== $user_id || $state['request']['environment'] !== $profile['environment'] || $state['request']['authority'] !== $profile['authority'] ) { throw new RuntimeException( 'connect_attempt_bound_to_other_user' ); } if ( ! isset( $state['response']['status_token'] ) ) { throw new RuntimeException( 'connect_response_missing' ); } $status = $poll( $profile['authority'] . '/connect/v1/bootstrap/status', array( 'status_token' => $state['response']['status_token'] ) ); Aha_Is_Woocommerce_Connect_Proof::validate_status( $status, $profile ); if ( in_array( $status['status'], array( 'proof_failed', 'attempt_expired' ), true ) ) { $terminal_cas( $status['status'] ); return $status['status']; } return 'expired_unresolved'; } /** * Reconcile an expired origin-verified attempt. * * The only positive reset proof is the authority's exact expired-and-unsubmitted result. * * @param array $state Connect state. * @param array $profile Deployment profile. * @param int $user_id User identifier. * @param callable $poll Status poll callback. * @param callable $remove State removal callback. * @return string * @throws RuntimeException When state ownership or response data is invalid. */ public static function reconcile_expired_origin_verified( array $state, array $profile, $user_id, callable $poll, callable $remove ) { if ( $state['phase'] !== 'origin_verified' || $state['user_id'] !== $user_id || $state['request']['environment'] !== $profile['environment'] || $state['request']['authority'] !== $profile['authority'] ) { throw new RuntimeException( 'connect_attempt_bound_to_other_user' ); } if ( ! isset( $state['response']['status_token'] ) ) { throw new RuntimeException( 'connect_response_missing' ); } $status = $poll( $profile['authority'] . '/connect/v1/bootstrap/status', array( 'status_token' => $state['response']['status_token'] ) ); if ( $status !== array( 'status' => 'attempt_expired_unsubmitted' ) ) { return 'expired_unresolved'; } $remove( 'attempt_expired' ); return 'attempt_expired'; } /** * Whether Aha already used this attempt's one-time sign-in link. * A failed status call answers false so the user is never blocked. * * @param array $state Connect state in phase origin_verified. * @param array $profile Deployment profile. * @return bool */ private static function login_handle_used( array $state, array $profile ) { try { $status = self::post_json( $profile['authority'] . '/connect/v1/bootstrap/status', array( 'status_token' => $state['response']['status_token'] ), 200 ); Aha_Is_Woocommerce_Connect_Proof::validate_status( $status, $profile ); return 'origin_verified' !== $status['status']; } catch ( Throwable $e ) { return false; } } /** * Read the current attempt and report whether its sign-in link was already used. * * @return bool */ public static function login_used() { try { $identity = self::preflight(); $derived = Aha_Is_Woocommerce_Connect_Crypto::derive_kek( Aha_Is_Woocommerce_Connect_Crypto::wp_secrets(), $identity ); $state = ( new Aha_Is_Woocommerce_Connect_State() )->with_lock( $identity, function ( $db ) use ( $derived, $identity ) { $old = $db->read(); return null === $old ? null : self::unpack( $old, $derived, $identity ); } ); return is_array( $state ) && 'origin_verified' === $state['phase'] && self::login_handle_used( $state, Aha_Is_Woocommerce_Connect_Profile::from_operator_config() ); } catch ( Throwable $e ) { return false; } } /** * Hash an encoded local state value. * * @param string $state Encoded local state. * @return string * @throws InvalidArgumentException When the local state is invalid. */ public static function local_state_hash( $state ) { if ( ! Aha_Is_Woocommerce_Connect_Crypto::is_b64url32( $state ) ) { throw new InvalidArgumentException( 'invalid_local_state' ); } $raw = base64_decode( strtr( $state, '-_', '+/' ) . '=', true ); return Aha_Is_Woocommerce_Connect_Crypto::base64url( hash( 'sha256', $raw, true ) ); } /** * Build the validated login redirect URL. * * @param string $login_uri Login URI. * @param string $local_state Encoded local state. * @param array $profile Deployment profile. * @return string */ public static function login_redirect( $login_uri, $local_state, array $profile ) { self::local_state_hash( $local_state ); $login = Aha_Is_Woocommerce_Connect_Proof::validate_status( array( 'status' => 'origin_verified', 'login_uri' => $login_uri ), $profile ); return $login . '&state=' . $local_state; } /** * Read only the exact high-entropy attempt path; failure reveals no state. * * @param mixed $attempt Attempt path value. * @return array|null */ public static function proof( $attempt ) { try { if ( ! is_string( $attempt ) || ! preg_match( '/^[A-Za-z0-9_-]{43}$/D', $attempt ) ) { return null; } // Anonymous hits must stay cheap (preflight does DNS and DB work, the state lock waits up to 3 s). // The gate only rejects; every full check below still runs when it passes. $gate = get_transient( self::PROOF_GATE . get_current_blog_id() ); if ( ! is_string( $gate ) || ! hash_equals( $gate, hash( 'sha256', $attempt ) ) ) { return null; } $identity = self::preflight(); $derived = Aha_Is_Woocommerce_Connect_Crypto::derive_kek( Aha_Is_Woocommerce_Connect_Crypto::wp_secrets(), $identity ); $repository = new Aha_Is_Woocommerce_Connect_State(); return $repository->with_lock( $identity, function ( $db ) use ( $attempt, $identity, $derived ) { $old = $db->read(); if ( null === $old ) { return null; } $state = self::unpack( $old, $derived, $identity ); if ( ! in_array( $state['phase'], array( 'proof_ready', 'origin_verified' ), true ) || ! hash_equals( $state['request']['client_attempt_id'], $attempt ) || ! isset( $state['response']['expires_at'] ) || strtotime( $state['response']['expires_at'] ) <= time() || time() >= $state['local_deadline'] ) { return null; } return Aha_Is_Woocommerce_Connect_Proof::build( $state['request'], $state['response'], Aha_Is_Woocommerce_Connect_Profile::from_operator_config(), $state['keys']['signing_private'] ); } ); } catch ( Throwable $e ) { return null; } } /** * Encode Connect state for storage. * * @param array $state Connect state. * @param array $derived Derived key material. * @param array $identity Site identity. * @return string */ private static function pack( array $state, array $derived, array $identity ) { return json_encode( Aha_Is_Woocommerce_Connect_Crypto::seal( $state, $derived, $identity ), JSON_THROW_ON_ERROR ); } /** * Decode Connect state from storage. * * @param mixed $value Stored state. * @param array $derived Derived key material. * @param array $identity Site identity. * @return array * @throws RuntimeException When the stored JSON or decoded state shape is corrupt. * @throws InvalidArgumentException When the sealed state envelope is invalid. */ private static function unpack( $value, array $derived, array $identity ) { if ( ! is_string( $value ) ) { throw new RuntimeException( 'connect_state_corrupt' ); } $sealed = json_decode( $value, true ); if ( ! is_array( $sealed ) ) { throw new RuntimeException( 'connect_state_corrupt' ); } $state = Aha_Is_Woocommerce_Connect_Crypto::open( $sealed, $derived, $identity ); if ( ! isset( $state['phase'], $state['request'], $state['keys'], $state['user_id'], $state['local_deadline'] ) ) { throw new RuntimeException( 'connect_state_corrupt' ); } return $state; } /** * Require an unchanged prepared attempt for retry. * * @param array $current Current stored state. * @param array $state Expected state. * @return void * @throws RuntimeException When the states conflict. */ private static function assert_prepared_retry( array $current, array $state ) { if ( $current['phase'] !== 'prepared' || $current['user_id'] !== $state['user_id'] || ! hash_equals( $current['local_state'], $state['local_state'] ) || ! hash_equals( $current['request']['local_state_hash'], self::local_state_hash( $current['local_state'] ) ) || Aha_Is_Woocommerce_Connect_Crypto::canonical_json( $current['keys'] ) !== Aha_Is_Woocommerce_Connect_Crypto::canonical_json( $state['keys'] ) || Aha_Is_Woocommerce_Connect_Crypto::canonical_json( $current['request'] ) !== Aha_Is_Woocommerce_Connect_Crypto::canonical_json( $state['request'] ) ) { throw new RuntimeException( 'connect_state_conflict' ); } } /** * Post JSON to the Connect authority. * * @param string $url Request URL. * @param array $body Request body. * @param int $expected Expected response code. * @param bool $bootstrap Whether this is a bootstrap request. * @return array * @throws RuntimeException When the authority response is unavailable or invalid. */ private static function post_json( $url, array $body, $expected, $bootstrap = false ) { // Safe mode sends nothing to Aha. if ( Aha_Is_Woocommerce_Site_Identity::is_safe_mode() ) { throw new RuntimeException( 'connect_safe_mode' ); } $result = wp_remote_post( $url, array( 'headers' => array( 'Content-Type' => 'application/json', 'Accept' => 'application/json' ), 'body' => wp_json_encode( $body ), 'timeout' => 8, 'redirection' => 0, 'sslverify' => true, 'reject_unsafe_urls' => true, 'limit_response_size' => 8192 ) ); if ( is_wp_error( $result ) ) { throw new RuntimeException( 'connect_authority_unavailable' ); } $code = wp_remote_retrieve_response_code( $result ); if ( $bootstrap && $code === 410 ) { $terminal = json_decode( wp_remote_retrieve_body( $result ), true ); if ( $terminal === array( 'error' => 'attempt_expired' ) ) { return $terminal; } } if ( $code !== $expected ) { throw new RuntimeException( 'connect_authority_unavailable' ); } $value = json_decode( wp_remote_retrieve_body( $result ), true ); if ( ! is_array( $value ) ) { throw new RuntimeException( 'connect_invalid_authority_response' ); } return $value; } /** * Site URL built with the stored siteurl scheme; site_url() alone follows the request scheme (http in cron/CLI). * * @return string Empty when the stored scheme is not http/https (callers then fail closed). */ private static function stored_site_url() { $scheme = wp_parse_url( (string) get_option( 'siteurl' ), PHP_URL_SCHEME ); return in_array( $scheme, array( 'http', 'https' ), true ) ? (string) site_url( '/', $scheme ) : ''; } /** * Validate runtime prerequisites and return the site identity. * * @return array * @throws InvalidArgumentException When a runtime prerequisite is unavailable. */ public static function preflight() { global $wpdb; $origin = home_url( '/' ); if ( ! function_exists( 'is_ssl' ) // is_ssl() describes the current HTTP request; WP-CLI and cron have none, so rely on the https home_url check below. || ! ( is_ssl() || ( function_exists( 'wp_doing_cron' ) && wp_doing_cron() ) || ( defined( 'WP_CLI' ) && WP_CLI ) ) || ! is_string( $origin ) || substr( $origin, 0, 8 ) !== 'https://' ) { throw new InvalidArgumentException( 'connect_https_public_origin_required' ); } $origin = rtrim( $origin, '/' ); if ( $origin !== Aha_Is_Woocommerce_Connect_Uri::canonical_origin( $origin ) || $origin !== rtrim( self::stored_site_url(), '/' ) ) { throw new InvalidArgumentException( 'connect_https_public_origin_required' ); } $host = wp_parse_url( $origin, PHP_URL_HOST ); if ( ! is_string( $host ) || ! filter_var( $host, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME ) || ! strpos( $host, '.' ) || filter_var( $host, FILTER_VALIDATE_IP ) ) { throw new InvalidArgumentException( 'connect_https_public_origin_required' ); } // An operator-listed local origin (dev builds only) may have no public DNS or resolve to loopback. $local_test_proof = home_url( '/' ) === $origin . '/' && self::stored_site_url() === $origin . '/' && class_exists( 'Aha_Is_Woocommerce_Connect_Dev_Profiles', false ) && Aha_Is_Woocommerce_Connect_Dev_Profiles::local_test_proof( $origin ); if ( ! $local_test_proof ) { $records = dns_get_record( $host, DNS_A | DNS_AAAA ); if ( ! is_array( $records ) || ! $records ) { throw new InvalidArgumentException( 'connect_https_public_origin_required' ); } foreach ( $records as $record ) { $ip = isset( $record['ip'] ) ? $record['ip'] : ( isset( $record['ipv6'] ) ? $record['ipv6'] : '' ); if ( ! filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE ) ) { throw new InvalidArgumentException( 'connect_https_public_origin_required' ); } } } if ( ! function_exists( 'sodium_crypto_aead_xchacha20poly1305_ietf_encrypt' ) || ! function_exists( 'openssl_pkey_new' ) || ! function_exists( 'hash_hkdf' ) ) { throw new InvalidArgumentException( 'connect_crypto_unavailable' ); } Aha_Is_Woocommerce_Connect_Crypto::wp_secrets(); if ( ! isset( $wpdb->options, $wpdb->dbname ) || ! preg_match( '/^[A-Za-z0-9_]+$/D', $wpdb->options ) ) { throw new InvalidArgumentException( 'connect_storage_unavailable' ); } $engine = $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- storage engine probe on the options table; must be live $wpdb->prepare( 'SELECT ENGINE FROM information_schema.TABLES WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s', $wpdb->dbname, $wpdb->options ) ); if ( $engine !== 'InnoDB' ) { throw new InvalidArgumentException( 'connect_storage_unavailable' ); } $uuid = get_option( 'aha_is_woocommerce_identity_install_uuid' ); if ( ! is_string( $uuid ) || ! preg_match( '/^[a-f0-9-]{36}$/D', $uuid ) ) { throw new InvalidArgumentException( 'connect_identity_unavailable' ); } return array( 'network_id' => (int) get_current_network_id(), 'blog_id' => (int) get_current_blog_id(), 'origin' => $origin, 'installation_uuid' => $uuid ); } }