self::bootstrap_id( $snapshot['state'] ) ) ); $result = self::post_signed( $context, $snapshot['state'], self::REQUEST_STATUS_PATH, $body ); if ( 200 !== $result['code'] || ! is_array( $result['body'] ) ) { return $snapshot['state']['phase']; } $status = self::validate_request_status( $result['body'] ); if ( 'pending_review' === $status['status'] ) { return $snapshot['state']['phase']; } if ( 'connected' === $status['status'] ) { $current = self::snapshot( $context ); if ( null !== $current && isset( $current['state']['credentials'] ) ) { return $current['state']['phase']; } if ( null !== $current && isset( $current['state']['pending_redeem'] ) ) { $pending = self::open_nested( $current['state']['pending_redeem'], $context ); if ( self::pending_reusable( $pending ) ) { return self::send_redeem( $context, $current, $pending ); } } $changed = self::mark_connection_lost( $context, self::bootstrap_id( $snapshot['state'] ) ); self::reconcile_schedules(); if ( $changed ) { return 'connection_lost'; } $current = self::snapshot( $context ); return null === $current ? 'not_connected' : $current['state']['phase']; } if ( 'superseded' === $status['status'] ) { self::delete_waiting( $context, $snapshot ); return 'not_connected'; } if ( 'rejected' === $status['status'] ) { self::replace_waiting( $context, $snapshot, function ( array $state ) use ( $status ) { $state['phase'] = 'rejected'; $state['rejection_reason'] = $status['reason']; return $state; } ); return 'rejected'; } $handoff = Aha_Is_Woocommerce_Connect_Crypto::open_envelope( $status['handoff'], 'handoff', self::bootstrap_id( $snapshot['state'] ), self::encryption_generation( $snapshot['state'] ), $snapshot['state']['keys']['encryption_private'] ); if ( ! Aha_Is_Woocommerce_Connect_Crypto::is_b64url32( $handoff ) ) { throw new InvalidArgumentException( 'invalid_connect_envelope' ); } $pending = array( 'command_id' => self::uuid4(), 'handoff_code' => $handoff, 'created_at' => time(), ); $snapshot = self::store_pending( $context, $snapshot, 'pending_redeem', $pending ); $pending = self::open_nested( $snapshot['state']['pending_redeem'], $context ); return self::send_redeem( $context, $snapshot, $pending ); } /** * Refresh credentials when forced or when access expires within one minute. * * @param bool $force Refresh even when the access token is still fresh. * @return string refreshed, current, retry, revoked, or not_connected. */ public static function refresh( $force = false ) { self::assert_not_safe_mode(); // Before prepare_refresh() stores a pending command. $context = self::context(); $prepared = self::prepare_refresh( $context, (bool) $force ); if ( 'not_connected' === $prepared['status'] ) { return 'not_connected'; } if ( 'current' === $prepared['status'] ) { Aha_Is_Woocommerce_Connect_Automation::clear_refresh_retry(); return 'current'; } if ( 'connection_lost' === $prepared['status'] ) { self::sweep_catalog_keys( $context ); self::reconcile_schedules(); return 'connection_lost'; } $snapshot = $prepared['snapshot']; $pending = $prepared['pending']; $body = self::fresh_body( array( 'bootstrap_id' => self::bootstrap_id( $snapshot['state'] ), 'command_id' => $pending['command_id'], 'refresh_token' => $pending['refresh_token'], ) ); $result = self::post_signed( $context, $snapshot['state'], self::REFRESH_PATH, $body ); // 403/404/408/429 are usually a WAF, proxy or rate limit, not Aha saying the link is gone. if ( 'network_error' === $result['kind'] || $result['code'] >= 500 || in_array( $result['code'], array( 403, 404, 408, 429 ), true ) ) { $elapsed = time() - self::refresh_failing_since( $context, true ); if ( $elapsed < self::TRANSIENT_REFRESH_WINDOW ) { // Backoff: the delay equals the time already spent failing, so it doubles, 60s to 3600s. Aha_Is_Woocommerce_Connect_Automation::schedule_refresh_retry( max( 60, min( 3600, $elapsed ) ) ); return 'retry'; } // Failing for the whole window: stop showing a link that no longer works. $changed = self::mark_connection_lost( $context, self::bootstrap_id( $snapshot['state'] ), 'pending_refresh', $pending['command_id'], (int) $snapshot['state']['credential_version'] ); self::reconcile_schedules(); return $changed ? 'connection_lost' : 'current'; } self::refresh_failing_since( $context, false, true ); if ( 401 === $result['code'] || self::is_error( $result['body'], 'unauthorized' ) ) { $revoked = self::mark_revoked( $context, self::bootstrap_id( $snapshot['state'] ), (int) $snapshot['state']['credential_version'], 'pending_refresh', $pending['command_id'] ); Aha_Is_Woocommerce_Connect_Automation::clear_refresh_retry(); self::reconcile_schedules(); return $revoked ? 'revoked' : 'current'; } if ( 409 === $result['code'] && self::is_error( $result['body'], 'refresh_conflict' ) ) { $status = self::resolve_refresh_conflict( $context, self::bootstrap_id( $snapshot['state'] ), (int) $snapshot['state']['credential_version'] ); Aha_Is_Woocommerce_Connect_Automation::clear_refresh_retry(); self::reconcile_schedules(); return $status; } if ( 200 !== $result['code'] ) { $changed = self::mark_connection_lost( $context, self::bootstrap_id( $snapshot['state'] ), 'pending_refresh', $pending['command_id'], (int) $snapshot['state']['credential_version'] ); self::reconcile_schedules(); return $changed ? 'connection_lost' : 'current'; } try { self::apply_credentials_response( $context, $result['body'], 'pending_refresh', $pending['command_id'] ); } catch ( Throwable $error ) { self::mark_connection_lost( $context, self::bootstrap_id( $snapshot['state'] ), 'pending_refresh', $pending['command_id'], (int) $snapshot['state']['credential_version'] ); self::reconcile_schedules(); throw $error; } Aha_Is_Woocommerce_Connect_Automation::clear_refresh_retry(); return 'refreshed'; } /** * Choose the refresh token and persist its command in one lock hold. * * @param array $context Connect context. * @param bool $force Whether a fresh access token must still rotate. * @return array Preparation result. */ private static function prepare_refresh( array $context, $force ) { return $context['repository']->with_lock( $context['identity'], function ( $db ) use ( $context, $force ) { $raw = $db->read(); if ( ! is_string( $raw ) ) { return array( 'status' => 'not_connected' ); } $state = self::unpack( $raw, $context ); if ( 'connected' !== $state['phase'] || ! isset( $state['credentials'] ) ) { return array( 'status' => 'not_connected' ); } self::assert_profile( $state, $context['profile'] ); $pending = isset( $state['pending_refresh'] ) ? self::open_nested( $state['pending_refresh'], $context ) : null; if ( is_array( $pending ) && self::pending_reusable( $pending ) ) { return array( 'status' => 'send', 'snapshot' => array( 'raw' => $raw, 'state' => $state ), 'pending' => $pending ); } if ( is_array( $pending ) ) { if ( ! isset( $pending['refresh_token'] ) || ! is_string( $pending['refresh_token'] ) || '' === $pending['refresh_token'] ) { self::tombstone_catalog_keys( $db, $state, $context ); $state = self::connection_lost_state( $state ); $db->cas( $raw, self::pack( $state, $context ) ); return array( 'status' => 'connection_lost' ); } // Stale command: replace it with ONE new command carrying the SAME refresh token. // Resending is safe: if the server never consumed the token it accepts it; if it did, // it answers 401 and the connection is honestly marked revoked. This intentionally // overrides "never resend the old refresh token" for the stale-command case only. $pending = array( 'command_id' => self::uuid4(), 'refresh_token' => $pending['refresh_token'], 'created_at' => time(), ); $state['pending_refresh'] = self::seal_nested( $pending, $context ); $next = self::pack( $state, $context ); $db->cas( $raw, $next ); return array( 'status' => 'send', 'snapshot' => array( 'raw' => $next, 'state' => $state ), 'pending' => $pending ); } $credentials = self::credentials( $state, $context ); if ( ! $force && self::date_timestamp( $credentials['access_expires_at'] ) > time() + 60 ) { if ( isset( $state['pending_refresh'] ) ) { unset( $state['pending_refresh'] ); $next = self::pack( $state, $context ); $db->cas( $raw, $next ); } return array( 'status' => 'current' ); } $pending = array( 'command_id' => self::uuid4(), 'refresh_token' => $credentials['refresh_token'], 'created_at' => time(), ); $state['pending_refresh'] = self::seal_nested( $pending, $context ); $next = self::pack( $state, $context ); $db->cas( $raw, $next ); return array( 'status' => 'send', 'snapshot' => array( 'raw' => $next, 'state' => $state ), 'pending' => $pending ); } ); } /** * Return a current access token, refreshing on demand when necessary. * * @return string|null Access token or null when unavailable. */ public static function access_token() { $current = self::current_access_credentials(); return null === $current ? null : $current['access_token']; } /** * Check the live connection using a current access token. * * @return string active, unavailable, or revoked. */ public static function connection_status() { $current = self::current_access_credentials(); if ( null === $current ) { return self::has_credentials() ? 'unavailable' : 'revoked'; } $context = $current['context']; $snapshot = $current['snapshot']; $body = self::fresh_body( array( 'product_sync_enabled' => Aha_Is_Woocommerce_Settings::is_product_sync_enabled() ) ); // Status call only; the server rejects it on every other command. $result = self::post_signed( $context, $snapshot['state'], self::CONNECTION_PATH, $body, array( 'Authorization' => 'Aha-Connect-Access ' . $current['access_token'] ) ); if ( 401 === $result['code'] || self::is_error( $result['body'], 'unauthorized' ) ) { $revoked = self::mark_revoked( $context, self::bootstrap_id( $snapshot['state'] ), $current['credential_version'] ); self::reconcile_schedules(); return $revoked ? 'revoked' : 'unavailable'; } if ( 200 !== $result['code'] || ! self::valid_connection_status( $result['body'] ) ) { return 'unavailable'; } // Plugin-local display only: when Aha last confirmed this connection. update_option( 'aha_is_woocommerce_connect_last_contact', time(), false ); self::record_paused( ! empty( $result['body']['paused'] ), $result['body']['paused_at'] ?? null ); if ( isset( $result['body']['store'] ) ) { self::persist_store( $context, $snapshot['state'], $result['body']['store'] ); } return 'active'; } /** Persist the Aha store name, SKU and URL when changed, only for the credentials that made the check. */ private static function persist_store( array $context, array $checked, array $store ) { $name = sanitize_text_field( $store['name'] ); $store_state = $store['state'] ?? ( ! empty( $store['live'] ) ? 'live' : 'waiting' ); $synced_at = isset( $store['last_product_sync_at'] ) ? self::date_timestamp( $store['last_product_sync_at'] ) : false; $context['repository']->with_lock( $context['identity'], function ( $db ) use ( $context, $checked, $store, $name, $store_state, $synced_at ) { $raw = $db->read(); if ( ! is_string( $raw ) ) { return; } $state = self::unpack( $raw, $context ); if ( 'connected' !== $state['phase'] || (int) ( $state['credential_version'] ?? 0 ) !== (int) ( $checked['credential_version'] ?? -1 ) || ( ( $state['store_display_name'] ?? null ) === $name && ( $state['store_sku'] ?? null ) === $store['sku'] && ( $state['store_url'] ?? null ) === ( $store['url'] ?? null ) && ( $state['store_state'] ?? null ) === $store_state && ( $state['store_attention'] ?? null ) === ( $store['attention'] ?? null ) && ( $state['store_last_product_sync'] ?? null ) === ( false === $synced_at ? null : $synced_at ) ) ) { return; } $state['store_display_name'] = $name; $state['store_sku'] = $store['sku']; if ( isset( $store['url'] ) ) { $state['store_url'] = $store['url']; } else { unset( $state['store_url'] ); } $state['store_state'] = $store_state; if ( isset( $store['attention'] ) ) { $state['store_attention'] = $store['attention']; } else { unset( $state['store_attention'] ); } if ( false !== $synced_at ) { $state['store_last_product_sync'] = $synced_at; } else { unset( $state['store_last_product_sync'] ); } $db->cas( $raw, self::pack( $state, $context ) ); } ); } /** * Create and register the integration-owned WooCommerce catalog key. * * @return string registered, retry, conflict, revoked, current, or not_set_up. */ public static function ensure_catalog_key() { self::assert_not_safe_mode(); // Before the sweep and the pending catalog key. $context = self::context(); self::sweep_catalog_keys( $context ); $current = self::current_access_credentials(); if ( null === $current ) { return 'not_set_up'; } try { $prepared = self::prepare_catalog_key( $current['context'] ); } catch ( Throwable $error ) { self::sweep_catalog_keys( $current['context'] ); self::reconcile_schedules(); throw $error; } if ( 'registered' === $prepared['status'] || 'not_set_up' === $prepared['status'] ) { return $prepared['status']; } $snapshot = $prepared['snapshot']; $pending = $prepared['pending']; $body = self::fresh_body( array( 'command_id' => $pending['command_id'], 'woo_key_id' => $pending['woo_key_id'], 'consumer_key' => $pending['consumer_key'], 'consumer_secret' => $pending['consumer_secret'], 'permissions' => 'read', ) ); $result = self::post_signed( $current['context'], $snapshot['state'], self::CATALOG_KEY_PATH, $body, array( 'Authorization' => 'Aha-Connect-Access ' . $current['access_token'] ) ); if ( 401 === $result['code'] || self::is_error( $result['body'], 'unauthorized' ) ) { $revoked = self::mark_revoked( $current['context'], $pending['bootstrap_id'], $current['credential_version'], 'pending_catalog_key', $pending['command_id'] ); self::reconcile_schedules(); return $revoked ? 'revoked' : 'current'; } if ( 409 === $result['code'] && self::is_error( $result['body'], 'conflict' ) ) { if ( self::remove_pending_catalog_key( $current['context'], $pending ) ) { self::sweep_catalog_keys( $current['context'] ); } self::reconcile_schedules(); return 'conflict'; } if ( 200 !== $result['code'] || ! self::valid_catalog_key_response( $result['body'], $pending['woo_key_id'] ) ) { self::reconcile_schedules(); return 'retry'; } $previous_key_id = self::record_catalog_key( $current['context'], $pending ); if ( false === $previous_key_id ) { return 'current'; } if ( $previous_key_id && $previous_key_id !== $pending['woo_key_id'] ) { self::sweep_catalog_keys( $current['context'] ); } self::reconcile_schedules(); return 'registered'; } /** Whether the current bootstrap has a registered managed catalog key. */ public static function catalog_key_registered() { try { $context = self::context(); $snapshot = self::snapshot( $context ); return null !== $snapshot && 'connected' === $snapshot['state']['phase'] && self::registered_catalog_key( $snapshot['state'], self::bootstrap_id( $snapshot['state'] ) ); } catch ( Throwable $error ) { return false; } } /** * Register the Connect order HMAC key once the catalog key is registered. * * @return string registered, retry, conflict, not_eligible, revoked, current, or not_set_up. */ public static function ensure_order_key() { $current = self::current_access_credentials(); if ( null === $current ) { return 'not_set_up'; } $prepared = self::prepare_order_key( $current['context'] ); if ( 'send' !== $prepared['status'] ) { return $prepared['status']; } $pending = $prepared['pending']; $body = self::fresh_body( array( 'command_id' => $pending['command_id'], 'bootstrap_id' => $pending['bootstrap_id'], 'order_key_id' => $pending['order_key_id'], 'order_secret' => $pending['order_secret'], ) ); $result = self::post_signed( $current['context'], $prepared['state'], self::ORDER_KEY_PATH, $body, array( 'Authorization' => 'Aha-Connect-Access ' . $current['access_token'] ) ); if ( 401 === $result['code'] || self::is_error( $result['body'], 'unauthorized' ) ) { $revoked = self::mark_revoked( $current['context'], $pending['bootstrap_id'], $current['credential_version'], 'pending_order_key', $pending['command_id'] ); self::reconcile_schedules(); return $revoked ? 'revoked' : 'current'; } if ( 403 === $result['code'] && self::is_error( $result['body'], 'account_not_eligible' ) ) { return 'not_eligible'; } if ( 409 === $result['code'] && self::is_error( $result['body'], 'conflict' ) ) { // A fresh command with a fresh key replaces this one on the next run. self::remove_pending_command( $current['context'], 'pending_order_key', $pending['command_id'] ); return 'conflict'; } if ( 200 !== $result['code'] || ! is_array( $result['body'] ) || ! self::exact_keys( $result['body'], array( 'status', 'order_key_id' ) ) || 'registered' !== $result['body']['status'] || $pending['order_key_id'] !== $result['body']['order_key_id'] ) { return 'retry'; } return self::record_order_key( $current['context'], $pending ) ? 'registered' : 'current'; } /** * Ask Aha to fetch this store's products now (one run per store per 10 minutes). * * With $product_ids (1..20 unique positive parent ids) Aha fetches only those products (event mode, * 30 s cooldown); without, it is the manual full sync, unchanged. * * @param int[]|null $product_ids Changed parent product ids, or null for a full sync. * @return array{status: string, retry_after_seconds?: int} status is queued, cooldown, unavailable, * not_set_up, revoked, not_eligible, paused, invalid (ids only), or retry. */ public static function request_product_sync( $product_ids = null ) { $current = self::current_access_credentials( $refreshed ); if ( null === $current && 'retry' === $refreshed ) { return array( 'status' => 'retry' ); // Refresh is failing temporarily; the caller keeps its work. } if ( null === $current || ! self::catalog_key_registered() ) { return array( 'status' => 'not_set_up' ); } $state = $current['snapshot']['state']; $bootstrap_id = self::bootstrap_id( $state ); $fields = array( 'command_id' => self::uuid4(), 'bootstrap_id' => $bootstrap_id, ); $by_ids = null !== $product_ids; if ( $by_ids ) { $product_ids = array_values( array_unique( array_map( 'intval', (array) $product_ids ) ) ); sort( $product_ids, SORT_NUMERIC ); if ( ! $product_ids || count( $product_ids ) > 20 || $product_ids[0] < 1 ) { return array( 'status' => 'invalid' ); } $fields['product_ids'] = $product_ids; } $result = self::post_signed( $current['context'], $state, self::PRODUCT_SYNC_PATH, self::fresh_body( $fields ), array( 'Authorization' => 'Aha-Connect-Access ' . $current['access_token'] ) ); if ( 401 === $result['code'] || self::is_error( $result['body'], 'unauthorized' ) ) { $revoked = self::mark_revoked( $current['context'], $bootstrap_id, $current['credential_version'] ); self::reconcile_schedules(); return array( 'status' => $revoked ? 'revoked' : 'retry' ); } if ( 403 === $result['code'] && self::is_error( $result['body'], 'account_not_eligible' ) ) { return array( 'status' => 'not_eligible' ); } // Paused by Aha is not a revoke: keep credentials and keys, only remember the pause. if ( 409 === $result['code'] && self::is_error( $result['body'], 'connection_paused' ) ) { if ( false === self::paused_at() ) { self::record_paused( true, null ); } return array( 'status' => 'paused' ); } if ( $by_ids && 400 === $result['code'] ) { return array( 'status' => 'invalid' ); } $body = $result['body']; if ( 200 !== $result['code'] || ! is_array( $body ) || ! isset( $body['status'] ) ) { return array( 'status' => 'retry' ); } // Event mode: retry_after_seconds is optional on queued and cooldown. if ( $by_ids && in_array( $body['status'], array( 'queued', 'cooldown' ), true ) && array() === array_diff( array_keys( $body ), array( 'status', 'retry_after_seconds' ) ) ) { if ( ! isset( $body['retry_after_seconds'] ) ) { return array( 'status' => $body['status'] ); } if ( is_int( $body['retry_after_seconds'] ) && $body['retry_after_seconds'] >= 0 ) { return array( 'status' => $body['status'], 'retry_after_seconds' => $body['retry_after_seconds'] ); } return array( 'status' => 'retry' ); } $seconds = isset( $body['retry_after_seconds'] ) && is_int( $body['retry_after_seconds'] ) && $body['retry_after_seconds'] >= 0 ? $body['retry_after_seconds'] : null; if ( 'unavailable' === $body['status'] && self::exact_keys( $body, array( 'status' ) ) ) { return array( 'status' => 'unavailable' ); } if ( in_array( $body['status'], array( 'queued', 'cooldown' ), true ) && null !== $seconds && self::exact_keys( $body, array( 'status', 'retry_after_seconds' ) ) ) { return array( 'status' => $body['status'], 'retry_after_seconds' => $seconds ); } return array( 'status' => 'retry' ); } /** Whether the current bootstrap has a registered Connect order key. */ public static function order_key_registered() { try { $context = self::context(); $snapshot = self::snapshot( $context ); return null !== $snapshot && 'connected' === $snapshot['state']['phase'] && null !== self::registered_order_key( $snapshot['state'], $context ); } catch ( Throwable $error ) { return false; } } /** * HMAC secret for a registered Connect order key id, or '' when there is none. * * @param string $key_id Key id from X-Aha-Key-Id. * @return string */ public static function order_secret( $key_id ) { if ( ! is_string( $key_id ) || 0 !== strpos( $key_id, 'cwa_' ) ) { return ''; } try { $context = self::context(); $snapshot = self::snapshot( $context ); if ( null === $snapshot || 'connected' !== $snapshot['state']['phase'] ) { return ''; } $registered = self::registered_order_key( $snapshot['state'], $context ); return null !== $registered && hash_equals( $registered['order_key_id'], $key_id ) ? $registered['order_secret'] : ''; } catch ( Throwable $error ) { return ''; } } /** Open the order key registered for the state's current bootstrap, or null. */ private static function registered_order_key( array $state, array $context ) { if ( ! isset( $state['order_key'] ) ) { return null; } $registered = self::open_nested( $state['order_key'], $context ); if ( ! self::valid_order_key( $registered, array( 'bootstrap_id', 'order_key_id', 'order_secret' ) ) ) { return null; } return hash_equals( self::bootstrap_id( $state ), $registered['bootstrap_id'] ) ? $registered : null; } /** Validate an opened order key entry with exactly $keys. */ private static function valid_order_key( $entry, array $keys ) { return is_array( $entry ) && self::exact_keys( $entry, $keys ) && ( ! isset( $entry['command_id'] ) || self::uuid( $entry['command_id'] ) ) && Aha_Is_Woocommerce_Connect_Crypto::is_b64url32( $entry['bootstrap_id'] ) && is_string( $entry['order_key_id'] ) && 1 === preg_match( '/^cwa_[A-Za-z0-9_-]{22}$/D', $entry['order_key_id'] ) && Aha_Is_Woocommerce_Connect_Crypto::is_b64url32( $entry['order_secret'] ); } /** Create or reuse the pending order key command while holding the state lock. */ private static function prepare_order_key( array $context ) { return $context['repository']->with_lock( $context['identity'], function ( $db ) use ( $context ) { $raw = $db->read(); if ( ! is_string( $raw ) ) { return array( 'status' => 'not_set_up' ); } $state = self::unpack( $raw, $context ); if ( 'connected' !== $state['phase'] || ! isset( $state['credentials'] ) ) { return array( 'status' => 'not_set_up' ); } self::assert_profile( $state, $context['profile'] ); $bootstrap_id = self::bootstrap_id( $state ); if ( ! self::catalog_key_marker( $state, $bootstrap_id ) ) { return array( 'status' => 'not_set_up' ); } if ( null !== self::registered_order_key( $state, $context ) ) { return array( 'status' => 'registered' ); } $keys = array( 'command_id', 'bootstrap_id', 'order_key_id', 'order_secret' ); if ( isset( $state['pending_order_key'] ) ) { $pending = self::open_nested( $state['pending_order_key'], $context ); if ( ! self::valid_order_key( $pending, $keys ) ) { throw new RuntimeException( 'connect_state_corrupt' ); } if ( hash_equals( $bootstrap_id, $pending['bootstrap_id'] ) ) { return array( 'status' => 'send', 'state' => $state, 'pending' => $pending ); } } $pending = array( 'command_id' => self::uuid4(), 'bootstrap_id' => $bootstrap_id, 'order_key_id' => 'cwa_' . Aha_Is_Woocommerce_Connect_Crypto::base64url( random_bytes( 16 ) ), 'order_secret' => Aha_Is_Woocommerce_Connect_Crypto::base64url( random_bytes( 32 ) ), ); $state['pending_order_key'] = self::seal_nested( $pending, $context ); $db->cas( $raw, self::pack( $state, $context ) ); return array( 'status' => 'send', 'state' => $state, 'pending' => $pending ); } ); } /** Promote the accepted pending order key if it is still the current command. */ private static function record_order_key( array $context, array $expected ) { return $context['repository']->with_lock( $context['identity'], function ( $db ) use ( $context, $expected ) { $raw = $db->read(); if ( ! is_string( $raw ) ) { return false; } $state = self::unpack( $raw, $context ); if ( 'connected' !== $state['phase'] || ! hash_equals( $expected['bootstrap_id'], self::bootstrap_id( $state ) ) || ! isset( $state['pending_order_key'] ) ) { return false; } $pending = self::open_nested( $state['pending_order_key'], $context ); if ( ! is_array( $pending ) || ! isset( $pending['command_id'] ) || ! hash_equals( $expected['command_id'], (string) $pending['command_id'] ) ) { return false; } $state['order_key'] = self::seal_nested( array( 'bootstrap_id' => $expected['bootstrap_id'], 'order_key_id' => $expected['order_key_id'], 'order_secret' => $expected['order_secret'], ), $context ); unset( $state['pending_order_key'] ); $db->cas( $raw, self::pack( $state, $context ) ); return true; } ); } /** Non-secret id of the current connection, '' when there is none, or null when the state cannot be read. */ public static function current_bootstrap_id() { try { $snapshot = self::snapshot( self::context() ); return null === $snapshot ? '' : self::bootstrap_id( $snapshot['state'] ); } catch ( Throwable $error ) { return null; } } /** Whether managed Woo keys still need deletion. */ public static function catalog_key_cleanup_pending() { try { $context = self::context(); return $context['repository']->with_lock( $context['identity'], function ( $db ) use ( $context ) { $cleanup = self::read_catalog_key_cleanup( $db ); $raw = $db->read(); if ( is_string( $raw ) ) { $state = self::unpack( $raw, $context ); $cleanup = array_merge( $cleanup, self::legacy_catalog_key_cleanup_ids( $state ) ); } return (bool) $cleanup; } ); } catch ( Throwable $error ) { return false; } } /** Create a Woo key and persist the retry command while holding the state lock. */ private static function prepare_catalog_key( array $context ) { return $context['repository']->with_lock( $context['identity'], function ( $db ) use ( $context ) { global $wpdb; $raw = $db->read(); if ( ! is_string( $raw ) ) { return array( 'status' => 'not_set_up' ); } $state = self::unpack( $raw, $context ); if ( 'connected' !== $state['phase'] || ! isset( $state['credentials'] ) ) { return array( 'status' => 'not_set_up' ); } self::assert_profile( $state, $context['profile'] ); $bootstrap_id = self::bootstrap_id( $state ); if ( self::registered_catalog_key( $state, $bootstrap_id ) ) { return array( 'status' => 'registered' ); } $user_id = isset( $state['user_id'] ) ? (int) $state['user_id'] : 0; if ( $user_id < 1 || ! user_can( $user_id, 'manage_woocommerce' ) ) { return array( 'status' => 'not_set_up' ); } if ( isset( $state['pending_catalog_key'] ) ) { $pending = self::open_nested( $state['pending_catalog_key'], $context ); self::validate_pending_catalog_key( $pending ); if ( isset( $pending['bootstrap_id'] ) && hash_equals( $bootstrap_id, $pending['bootstrap_id'] ) ) { return array( 'status' => 'send', 'snapshot' => array( 'raw' => $raw, 'state' => $state ), 'pending' => $pending, ); } return array( 'status' => 'not_set_up' ); } $consumer_key = 'ck_' . wc_rand_hash(); $consumer_secret = 'cs_' . wc_rand_hash(); $inserted = $wpdb->insert( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- creating the managed WooCommerce REST key row; WooCommerce has no API for it $wpdb->prefix . 'woocommerce_api_keys', array( 'user_id' => $user_id, 'description' => self::CATALOG_KEY_DESCRIPTION, 'permissions' => 'read', 'consumer_key' => wc_api_hash( $consumer_key ), 'consumer_secret' => $consumer_secret, 'truncated_key' => substr( $consumer_key, -7 ), ), array( '%d', '%s', '%s', '%s', '%s', '%s' ) ); $woo_key_id = (int) $wpdb->insert_id; if ( false === $inserted || $woo_key_id < 1 || $woo_key_id > 2147483647 ) { throw new RuntimeException( 'connect_catalog_key_create_failed' ); } $pending = array( 'command_id' => self::uuid4(), 'woo_key_id' => $woo_key_id, 'consumer_key' => $consumer_key, 'consumer_secret' => $consumer_secret, 'bootstrap_id' => $bootstrap_id, ); $state['pending_catalog_key'] = self::seal_nested( $pending, $context ); $next = self::pack( $state, $context ); $db->cas( $raw, $next ); return array( 'status' => 'send', 'snapshot' => array( 'raw' => $next, 'state' => $state ), 'pending' => $pending, ); } ); } /** * Persist and send a disconnect command. * * @return string disconnected, retry, or not_connected. */ public static function disconnect() { self::assert_not_safe_mode(); // Before the pending disconnect command is stored. $context = self::context(); $snapshot = self::snapshot( $context ); if ( null === $snapshot || 'connected' !== $snapshot['state']['phase'] ) { return 'not_connected'; } self::assert_profile( $snapshot['state'], $context['profile'] ); $credential_version = isset( $snapshot['state']['credential_version'] ) ? (int) $snapshot['state']['credential_version'] : 0; $pending = isset( $snapshot['state']['pending_disconnect'] ) ? self::open_nested( $snapshot['state']['pending_disconnect'], $context ) : null; if ( is_array( $pending ) && ! self::pending_reusable( $pending ) ) { self::remove_pending_command( $context, 'pending_disconnect', $pending['command_id'] ); $snapshot = self::snapshot( $context ); $pending = null; } if ( ! is_array( $pending ) ) { $pending = array( 'command_id' => self::uuid4(), 'created_at' => time() ); $snapshot = self::store_pending( $context, $snapshot, 'pending_disconnect', $pending ); $pending = self::open_nested( $snapshot['state']['pending_disconnect'], $context ); } $body = self::fresh_body( array( 'bootstrap_id' => self::bootstrap_id( $snapshot['state'] ), 'command_id' => $pending['command_id'], ) ); $result = self::post_signed( $context, $snapshot['state'], self::DISCONNECT_PATH, $body ); if ( 401 === $result['code'] || self::is_error( $result['body'], 'unauthorized' ) ) { $deleted = self::delete_connected( $context, self::bootstrap_id( $snapshot['state'] ), $pending['command_id'], $credential_version ); if ( $deleted ) { self::sweep_catalog_keys( $context ); } self::reconcile_schedules(); return $deleted ? 'disconnected' : 'current'; } if ( 200 === $result['code'] && $result['body'] === array( 'status' => 'disconnected' ) ) { $deleted = self::delete_connected( $context, self::bootstrap_id( $snapshot['state'] ), $pending['command_id'] ); if ( $deleted ) { self::sweep_catalog_keys( $context ); } self::reconcile_schedules(); return $deleted ? 'disconnected' : 'retry'; } return 'retry'; } /** * Whether readable, sealed Connect credentials are present. * * @return bool */ public static function has_credentials() { try { $context = self::context(); $snapshot = self::snapshot( $context ); if ( null === $snapshot || 'connected' !== $snapshot['state']['phase'] || ! isset( $snapshot['state']['credentials'] ) ) { return false; } self::credentials( $snapshot['state'], $context ); return true; } catch ( Throwable $error ) { return false; } } /** * Return the stored phase without exposing private state. * * @return string */ public static function phase() { try { $context = self::context(); $snapshot = self::snapshot( $context ); return null === $snapshot ? 'not_connected' : $snapshot['state']['phase']; } catch ( Throwable $error ) { return 'not_connected'; } } /** Whether a stored Connect option exists but cannot be safely read. */ public static function state_unreadable() { if ( null === get_option( Aha_Is_Woocommerce_Connect_State::OPTION, null ) ) { return false; } try { $context = self::context(); return $context['repository']->with_lock( $context['identity'], function ( $db ) use ( $context ) { $raw = $db->read(); if ( null === $raw ) { return false; } self::unpack( $raw, $context ); return false; } ); } catch ( Throwable $error ) { return true; } } /** Send a persisted handoff redemption. */ private static function send_redeem( array $context, array $snapshot, array $pending ) { $body = self::fresh_body( array( 'bootstrap_id' => self::bootstrap_id( $snapshot['state'] ), 'command_id' => $pending['command_id'], 'handoff_code' => $pending['handoff_code'], ) ); $result = self::post_signed( $context, $snapshot['state'], self::REDEEM_PATH, $body ); if ( 'network_error' === $result['kind'] || $result['code'] >= 500 ) { Aha_Is_Woocommerce_Connect_Automation::schedule_poll_retry(); return 'reconnect_approved'; } if ( 200 === $result['code'] ) { try { self::apply_credentials_response( $context, $result['body'], 'pending_redeem', $pending['command_id'] ); } catch ( Throwable $error ) { self::remove_pending_command( $context, 'pending_redeem', $pending['command_id'] ); self::mark_connection_lost( $context, self::bootstrap_id( $snapshot['state'] ) ); self::reconcile_schedules(); throw $error; } self::reconcile_schedules(); return 'connected'; } self::remove_pending_command( $context, 'pending_redeem', $pending['command_id'] ); return $snapshot['state']['phase']; } /** Validate and store a credential envelope under the lock. */ private static function apply_credentials_response( array $context, $response, $pending_field, $command_id ) { $outer = self::validate_credential_response( $response ); $snapshot = self::snapshot( $context ); if ( null === $snapshot ) { throw new RuntimeException( 'connect_state_conflict' ); } $bootstrap_id = self::bootstrap_id( $snapshot['state'] ); $plaintext = Aha_Is_Woocommerce_Connect_Crypto::open_envelope( $outer['credentials'], 'credentials', $bootstrap_id, self::encryption_generation( $snapshot['state'] ), $snapshot['state']['keys']['encryption_private'] ); $credentials = json_decode( $plaintext, true ); self::validate_credentials( $credentials, $outer ); $context['repository']->with_lock( $context['identity'], function ( $db ) use ( $context, $credentials, $pending_field, $command_id, $bootstrap_id ) { $raw = $db->read(); if ( ! is_string( $raw ) ) { throw new RuntimeException( 'connect_state_conflict' ); } $state = self::unpack( $raw, $context ); if ( ! hash_equals( $bootstrap_id, self::bootstrap_id( $state ) ) ) { throw new RuntimeException( 'connect_state_conflict' ); } $current = isset( $state['credential_version'] ) ? (int) $state['credential_version'] : 0; if ( $credentials['credential_version'] > $current ) { $state['credentials'] = self::seal_nested( $credentials, $context ); $state['connection_generation'] = $credentials['connection_generation']; $state['credential_version'] = $credentials['credential_version']; $state['phase'] = 'connected'; } if ( isset( $state[ $pending_field ] ) ) { $pending = self::open_nested( $state[ $pending_field ], $context ); if ( isset( $pending['command_id'] ) && hash_equals( $command_id, $pending['command_id'] ) ) { unset( $state[ $pending_field ] ); } } $next = self::pack( $state, $context ); if ( $next !== $raw ) { $db->cas( $raw, $next ); } } ); } /** Validate the outer credential response. */ private static function validate_credential_response( $response ) { if ( ! is_array( $response ) || ! self::exact_keys( $response, array( 'status', 'connection_generation', 'credential_version', 'credentials' ) ) ) { throw new InvalidArgumentException( 'invalid_connect_credentials' ); } if ( 'connected' !== $response['status'] || ! is_int( $response['connection_generation'] ) || $response['connection_generation'] < 1 || ! is_int( $response['credential_version'] ) || $response['credential_version'] < 1 || ! is_array( $response['credentials'] ) ) { throw new InvalidArgumentException( 'invalid_connect_credentials' ); } return $response; } /** Validate decrypted credential JSON against the outer response. */ private static function validate_credentials( $credentials, array $outer ) { $fields = array( 'access_token', 'access_expires_at', 'refresh_token', 'refresh_expires_at', 'connection_generation', 'credential_version', 'allowed_actions' ); if ( ! is_array( $credentials ) || ! self::exact_keys( $credentials, $fields ) ) { throw new InvalidArgumentException( 'invalid_connect_credentials' ); } if ( ! Aha_Is_Woocommerce_Connect_Crypto::is_b64url32( $credentials['access_token'] ) || ! Aha_Is_Woocommerce_Connect_Crypto::is_b64url32( $credentials['refresh_token'] ) || false === self::date_timestamp( $credentials['access_expires_at'] ) || false === self::date_timestamp( $credentials['refresh_expires_at'] ) || $credentials['connection_generation'] !== $outer['connection_generation'] || $credentials['credential_version'] !== $outer['credential_version'] || ! self::valid_actions( $credentials['allowed_actions'] ) ) { throw new InvalidArgumentException( 'invalid_connect_credentials' ); } } /** Validate request-status response variants exactly. */ private static function validate_request_status( $body ) { if ( ! is_array( $body ) || ! isset( $body['status'] ) || ! is_string( $body['status'] ) ) { throw new InvalidArgumentException( 'invalid_connect_status' ); } if ( in_array( $body['status'], array( 'pending_review', 'connected', 'superseded' ), true ) ) { if ( ! self::exact_keys( $body, array( 'status' ) ) ) { throw new InvalidArgumentException( 'invalid_connect_status' ); } return $body; } if ( 'rejected' === $body['status'] ) { if ( ! self::exact_keys( $body, array( 'status', 'reason' ) ) || ( null !== $body['reason'] && ! is_string( $body['reason'] ) ) ) { throw new InvalidArgumentException( 'invalid_connect_status' ); } return $body; } if ( 'approved' === $body['status'] && self::exact_keys( $body, array( 'status', 'handoff' ) ) && is_array( $body['handoff'] ) ) { return $body; } throw new InvalidArgumentException( 'invalid_connect_status' ); } /** Accept only an https aha.is store page URL (other hosts only when the dev-build class accepts them). */ private static function valid_store_url( $url, $environment ) { if ( ! is_string( $url ) || strlen( $url ) > 2048 ) { return false; } $parts = wp_parse_url( $url ); if ( ! is_array( $parts ) || ( $parts['scheme'] ?? '' ) !== 'https' || isset( $parts['user'] ) || isset( $parts['pass'] ) || isset( $parts['port'] ) ) { return false; } $host = $parts['host'] ?? ''; $path = $parts['path'] ?? ''; return ( in_array( $host, array( 'aha.is', 'www.aha.is' ), true ) || ( class_exists( 'Aha_Is_Woocommerce_Connect_Dev_Profiles', false ) && Aha_Is_Woocommerce_Connect_Dev_Profiles::valid_store_host( $host, $environment ) ) ) && ( 0 === strpos( $path, '/veitingar/' ) || 0 === strpos( $path, '/verslun/' ) ); } /** Validate a connection status response without retaining it. */ private static function valid_connection_status( $body ) { $keys = array( 'status', 'connection_generation', 'credential_version', 'access_expires_at', 'allowed_actions' ); // Optional pause fields (absent on older Sync): paused is a bool, paused_at an ISO date or null. if ( is_array( $body ) ) { foreach ( array( 'paused', 'paused_at' ) as $pause_key ) { if ( array_key_exists( $pause_key, $body ) ) { $keys[] = $pause_key; } } if ( ( array_key_exists( 'paused', $body ) && ! is_bool( $body['paused'] ) ) || ( array_key_exists( 'paused_at', $body ) && null !== $body['paused_at'] && ( ! is_string( $body['paused_at'] ) || false === self::date_timestamp( $body['paused_at'] ) ) ) ) { return false; } } if ( is_array( $body ) && array_key_exists( 'store', $body ) ) { $store = $body['store']; // Connect also sends `live` (bool); it is accepted and ignored. if ( is_array( $store ) && array_key_exists( 'live', $store ) ) { if ( ! is_bool( $store['live'] ) ) { return false; } unset( $store['live'] ); } // Optional last product sync (ISO date, not in the future beyond 300 s of clock skew). if ( is_array( $store ) && array_key_exists( 'last_product_sync_at', $store ) ) { $synced = self::date_timestamp( $store['last_product_sync_at'] ); if ( false === $synced || $synced > time() + 300 ) { return false; } unset( $store['last_product_sync_at'] ); } // Optional owner-store state from Aha; `attention` is only valid with needs_attention. if ( is_array( $store ) && array_key_exists( 'state', $store ) ) { if ( ! is_string( $store['state'] ) || ! in_array( $store['state'], array( 'live', 'waiting', 'needs_attention' ), true ) ) { return false; } if ( array_key_exists( 'attention', $store ) !== ( 'needs_attention' === $store['state'] ) || ( array_key_exists( 'attention', $store ) && ( ! is_string( $store['attention'] ) || ! in_array( $store['attention'], array( 'import_failed', 'no_products' ), true ) ) ) ) { return false; } unset( $store['state'], $store['attention'] ); } elseif ( is_array( $store ) && array_key_exists( 'attention', $store ) ) { return false; } if ( ! is_array( $store ) || ! ( self::exact_keys( $store, array( 'name', 'sku' ) ) || ( self::exact_keys( $store, array( 'name', 'sku', 'url' ) ) && self::valid_store_url( $store['url'], Aha_Is_Woocommerce_Connect_Profile::from_operator_config()['environment'] ) ) ) || ! is_string( $store['name'] ) || '' === $store['name'] || 1 !== preg_match( '//u', $store['name'] ) || ( function_exists( 'mb_strlen' ) ? mb_strlen( $store['name'], 'UTF-8' ) > 200 : strlen( $store['name'] ) > 800 ) || ! is_string( $store['sku'] ) || 1 !== preg_match( '/^[A-Za-z0-9_-]{1,64}$/D', $store['sku'] ) ) { return false; } $keys[] = 'store'; } if ( ! is_array( $body ) || ! self::exact_keys( $body, $keys ) ) { return false; } return 'active' === $body['status'] && is_int( $body['connection_generation']) && $body['connection_generation'] > 0 && is_int( $body['credential_version'] ) && $body['credential_version'] > 0 && false !== self::date_timestamp( $body['access_expires_at'] ) && self::valid_actions( $body['allowed_actions'] ); } /** Validate the exact catalog-key success response. */ private static function valid_catalog_key_response( $body, $woo_key_id ) { return is_array( $body ) && self::exact_keys( $body, array( 'status', 'woo_key_id' ) ) && 'registered' === $body['status'] && is_int( $body['woo_key_id'] ) && $body['woo_key_id'] === (int) $woo_key_id; } /** Build the current site-scoped context. */ private static function context() { $identity = Aha_Is_Woocommerce_Connect_Start::preflight(); return array( 'identity' => $identity, '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(), ); } /** Read one state snapshot under lock. */ private static function snapshot( array $context ) { return $context['repository']->with_lock( $context['identity'], function ( $db ) use ( $context ) { $raw = $db->read(); return null === $raw ? null : array( 'raw' => $raw, 'state' => self::unpack( $raw, $context ) ); } ); } /** Refresh when needed, then read the access token and its version from one locked snapshot. */ private static function current_access_credentials( &$refresh_result = null ) { $result = $refresh_result = self::refresh( false ); if ( in_array( $result, array( 'not_connected', 'connection_lost', 'retry', 'revoked' ), true ) ) { return null; } $context = self::context(); $snapshot = self::snapshot( $context ); if ( null === $snapshot || 'connected' !== $snapshot['state']['phase'] || ! isset( $snapshot['state']['credential_version'], $snapshot['state']['credentials'] ) ) { return null; } $credentials = self::credentials( $snapshot['state'], $context ); return array( 'context' => $context, 'snapshot' => $snapshot, 'access_token' => $credentials['access_token'], 'credential_version' => (int) $snapshot['state']['credential_version'], ); } /** Decode state. */ private static function unpack( $raw, array $context ) { $sealed = is_string( $raw ) ? json_decode( $raw, true ) : null; if ( ! is_array( $sealed ) ) { throw new RuntimeException( 'connect_state_corrupt' ); } $state = Aha_Is_Woocommerce_Connect_Crypto::open( $sealed, $context['derived'], $context['identity'] ); if ( ! isset( $state['phase'], $state['request'], $state['keys'] ) || ! array_key_exists( 'response', $state ) ) { throw new RuntimeException( 'connect_state_corrupt' ); } return $state; } /** Encode state. */ private static function pack( array $state, array $context ) { return json_encode( Aha_Is_Woocommerce_Connect_Crypto::seal( $state, $context['derived'], $context['identity'] ), JSON_THROW_ON_ERROR ); } /** Seal a sensitive nested operation or credential object. */ private static function seal_nested( array $value, array $context ) { return Aha_Is_Woocommerce_Connect_Crypto::seal( $value, $context['derived'], $context['identity'] ); } /** Open a sensitive nested object. */ private static function open_nested( $sealed, array $context ) { if ( ! is_array( $sealed ) ) { throw new InvalidArgumentException( 'invalid_connect_envelope' ); } return Aha_Is_Woocommerce_Connect_Crypto::open( $sealed, $context['derived'], $context['identity'] ); } /** Open and validate stored credentials. */ private static function credentials( array $state, array $context ) { $credentials = self::open_nested( $state['credentials'], $context ); if ( ! self::exact_keys( $credentials, array( 'access_token', 'access_expires_at', 'refresh_token', 'refresh_expires_at', 'connection_generation', 'credential_version', 'allowed_actions' ) ) ) { throw new InvalidArgumentException( 'invalid_connect_credentials' ); } self::validate_credentials( $credentials, array( 'connection_generation' => $credentials['connection_generation'], 'credential_version' => $credentials['credential_version'], ) ); return $credentials; } /** Persist a nested pending operation after re-reading under lock. */ private static function store_pending( array $context, array $snapshot, $field, array $pending ) { $next_raw = $context['repository']->with_lock( $context['identity'], function ( $db ) use ( $context, $snapshot, $field, $pending ) { $raw = $db->read(); if ( ! is_string( $raw ) ) { throw new RuntimeException( 'connect_state_conflict' ); } $state = self::unpack( $raw, $context ); if ( self::bootstrap_id( $state ) !== self::bootstrap_id( $snapshot['state'] ) ) { throw new RuntimeException( 'connect_state_conflict' ); } if ( isset( $state[ $field ] ) ) { return $raw; } $state[ $field ] = self::seal_nested( $pending, $context ); $next = self::pack( $state, $context ); $db->cas( $raw, $next ); return $next; } ); return array( 'raw' => $next_raw, 'state' => self::unpack( $next_raw, $context ) ); } /** Remove only the pending operation with the expected command id. */ private static function remove_pending_command( array $context, $field, $command_id ) { $context['repository']->with_lock( $context['identity'], function ( $db ) use ( $context, $field, $command_id ) { $raw = $db->read(); if ( ! is_string( $raw ) ) { return; } $state = self::unpack( $raw, $context ); if ( ! isset( $state[ $field ] ) ) { return; } $pending = self::open_nested( $state[ $field ], $context ); if ( ! isset( $pending['command_id'] ) || ! hash_equals( $command_id, $pending['command_id'] ) ) { return; } unset( $state[ $field ] ); $db->cas( $raw, self::pack( $state, $context ) ); } ); } /** Record an accepted catalog key and return the prior managed key id. */ private static function record_catalog_key( array $context, array $expected ) { return $context['repository']->with_lock( $context['identity'], function ( $db ) use ( $context, $expected ) { $raw = $db->read(); if ( ! is_string( $raw ) ) { return false; } $state = self::unpack( $raw, $context ); if ( 'connected' !== $state['phase'] || ! hash_equals( $expected['bootstrap_id'], self::bootstrap_id( $state ) ) || ! isset( $state['pending_catalog_key'] ) ) { return false; } $pending = self::open_nested( $state['pending_catalog_key'], $context ); self::validate_pending_catalog_key( $pending ); if ( ! hash_equals( $expected['command_id'], $pending['command_id'] ) || $expected['woo_key_id'] !== $pending['woo_key_id'] || ! hash_equals( $expected['bootstrap_id'], $pending['bootstrap_id'] ) ) { return false; } $previous_key_id = 0; if ( isset( $state['catalog_key'] ) && self::valid_registered_catalog_key( $state['catalog_key'] ) ) { $previous_key_id = $state['catalog_key']['woo_key_id']; } self::tombstone_catalog_keys( $db, $state, $context ); $state['catalog_key'] = array( 'bootstrap_id' => $expected['bootstrap_id'], 'woo_key_id' => $expected['woo_key_id'], 'truncated_key' => substr( $pending['consumer_key'], -7 ), ); unset( $state['pending_catalog_key'] ); $db->cas( $raw, self::pack( $state, $context ) ); return $previous_key_id; } ); } /** Remove one conflicted pending key only if it is still the current command. */ private static function remove_pending_catalog_key( array $context, array $expected ) { return $context['repository']->with_lock( $context['identity'], function ( $db ) use ( $context, $expected ) { $raw = $db->read(); if ( ! is_string( $raw ) ) { return false; } $state = self::unpack( $raw, $context ); if ( ! isset( $state['pending_catalog_key'] ) ) { return false; } $pending = self::open_nested( $state['pending_catalog_key'], $context ); self::validate_pending_catalog_key( $pending ); if ( ! hash_equals( $expected['command_id'], $pending['command_id'] ) || $expected['woo_key_id'] !== $pending['woo_key_id'] || ! hash_equals( $expected['bootstrap_id'], $pending['bootstrap_id'] ) ) { return false; } self::tombstone_catalog_keys( $db, $state, $context ); unset( $state['pending_catalog_key'] ); $db->cas( $raw, self::pack( $state, $context ) ); return true; } ); } /** Whether a registration marker belongs to the selected bootstrap. */ private static function catalog_key_marker( array $state, $bootstrap_id ) { return isset( $state['catalog_key'] ) && self::valid_registered_catalog_key( $state['catalog_key'] ) && hash_equals( $bootstrap_id, $state['catalog_key']['bootstrap_id'] ); } /** * Whether the admin who started this connection is gone, deleted or no longer holds manage_woocommerce. */ public static function owner_lost( array $state ) { $owner = isset( $state['user_id'] ) ? (int) $state['user_id'] : 0; return $owner < 1 || ! user_can( $owner, 'manage_woocommerce' ); } /** * Health of the managed catalog key: none (no marker), missing (row gone or wrong), owner_lost, or ok. * The row must belong to the connecting user, who must still hold manage_woocommerce. */ private static function catalog_key_health( array $state, $bootstrap_id ) { if ( ! self::catalog_key_marker( $state, $bootstrap_id ) ) { return 'none'; } // Owner first: WooCommerce deletes a deleted user's API key rows, so a missing row must not hide a lost owner. if ( self::owner_lost( $state ) ) { return 'owner_lost'; } global $wpdb; $row = $wpdb->get_row( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- reads the managed WooCommerce REST key table; must see the live rows $wpdb->prepare( "SELECT permissions, user_id FROM {$wpdb->prefix}woocommerce_api_keys WHERE key_id = %d AND BINARY description = BINARY %s LIMIT 1", $state['catalog_key']['woo_key_id'], self::CATALOG_KEY_DESCRIPTION ), ARRAY_A ); if ( '' !== (string) $wpdb->last_error ) { throw new RuntimeException( 'connect_storage_unavailable' ); } if ( ! is_array( $row ) || 'read' !== ( $row['permissions'] ?? null ) ) { return 'missing'; } return (int) $row['user_id'] === (int) $state['user_id'] ? 'ok' : 'missing'; } /** Whether the marker is present and the Woo key row is healthy: exists, read-only, managed, owner still allowed. */ private static function registered_catalog_key( array $state, $bootstrap_id ) { return 'ok' === self::catalog_key_health( $state, $bootstrap_id ); } /** Whether a registered marker exists but its Woo key is missing or wrong, so a new key is pending. */ public static function catalog_key_repairing() { try { $context = self::context(); $snapshot = self::snapshot( $context ); if ( null === $snapshot || 'connected' !== $snapshot['state']['phase'] ) { return false; } return 'missing' === self::catalog_key_health( $snapshot['state'], self::bootstrap_id( $snapshot['state'] ) ); } catch ( Throwable $error ) { return false; } } /** Whether the key exists but the WordPress user who connected the store lost manage_woocommerce (or was deleted). */ public static function catalog_key_owner_lost() { try { $context = self::context(); $snapshot = self::snapshot( $context ); if ( null === $snapshot || 'connected' !== $snapshot['state']['phase'] ) { return false; } return 'owner_lost' === self::catalog_key_health( $snapshot['state'], self::bootstrap_id( $snapshot['state'] ) ); } catch ( Throwable $error ) { return false; } } /** Validate the non-secret catalog registration marker. */ private static function valid_registered_catalog_key( $registered ) { return is_array( $registered ) && ( self::exact_keys( $registered, array( 'bootstrap_id', 'woo_key_id' ) ) || self::exact_keys( $registered, array( 'bootstrap_id', 'woo_key_id', 'truncated_key' ) ) ) && Aha_Is_Woocommerce_Connect_Crypto::is_b64url32( $registered['bootstrap_id'] ) && is_int( $registered['woo_key_id'] ) && $registered['woo_key_id'] >= 1 && $registered['woo_key_id'] <= 2147483647 && ( ! isset( $registered['truncated_key'] ) || self::valid_truncated_key( $registered['truncated_key'] ) ); } /** Validate a decrypted pending catalog command before use. */ private static function validate_pending_catalog_key( $pending ) { if ( ! is_array( $pending ) || ! self::exact_keys( $pending, array( 'bootstrap_id', 'command_id', 'consumer_key', 'consumer_secret', 'woo_key_id' ) ) || ! Aha_Is_Woocommerce_Connect_Crypto::is_b64url32( $pending['bootstrap_id'] ) || ! self::uuid( $pending['command_id'] ) || ! is_int( $pending['woo_key_id'] ) || $pending['woo_key_id'] < 1 || $pending['woo_key_id'] > 2147483647 || ! is_string( $pending['consumer_key'] ) || 1 !== preg_match( '/^ck_[0-9a-f]{40}$/D', $pending['consumer_key'] ) || ! is_string( $pending['consumer_secret'] ) || 1 !== preg_match( '/^cs_[0-9a-f]{40}$/D', $pending['consumer_secret'] ) ) { throw new InvalidArgumentException( 'invalid_connect_catalog_key' ); } } /** Add all catalog keys referenced by state to the independent cleanup queue. */ public static function tombstone_catalog_keys( $db, array $state, array $context ) { $cleanup = self::read_catalog_key_cleanup( $db ); foreach ( self::catalog_key_tombstones( $state, $context ) as $tombstone ) { $cleanup[] = $tombstone; } self::write_catalog_key_cleanup( $db, $cleanup ); } /** Reconcile all managed Woo keys from current state and the durable cleanup queue. */ public static function sweep_catalog_keys( $context = null ) { global $wpdb; $context = is_array( $context ) ? $context : self::context(); $incomplete = false; $remaining = $context['repository']->with_lock( $context['identity'], function ( $db ) use ( $context, $wpdb, &$incomplete ) { $raw = $db->read(); $state = is_string( $raw ) ? self::unpack( $raw, $context ) : null; $cleanup = self::read_catalog_key_cleanup( $db ); $managed = self::managed_catalog_key_tombstones(); if ( null === $managed ) { $incomplete = true; return $cleanup; } $managed_by_id = array(); foreach ( $managed as $tombstone ) { $managed_by_id[ $tombstone['key_id'] ] = $tombstone; } $cleanup = self::migrate_catalog_key_cleanup( $cleanup, $managed_by_id ); if ( is_array( $state ) && isset( $state['catalog_key_cleanup'] ) ) { $legacy = self::legacy_catalog_key_cleanup_ids( $state ); $cleanup = self::migrate_catalog_key_cleanup( array_merge( $cleanup, $legacy ), $managed_by_id ); self::write_catalog_key_cleanup( $db, $cleanup ); unset( $state['catalog_key_cleanup'] ); $db->cas( $raw, self::pack( $state, $context ) ); } $referenced = array(); if ( is_array( $state ) ) { if ( isset( $state['catalog_key'] ) && self::valid_registered_catalog_key( $state['catalog_key'] ) ) { $referenced[] = $state['catalog_key']['woo_key_id']; } if ( isset( $state['pending_catalog_key'] ) ) { $pending = self::open_nested( $state['pending_catalog_key'], $context ); self::validate_pending_catalog_key( $pending ); $referenced[] = $pending['woo_key_id']; } } $referenced = self::normalize_catalog_key_ids( $referenced ); $candidates = array_merge( $cleanup, $managed ); $candidates = self::normalize_catalog_key_tombstones( $candidates ); $failed = array(); foreach ( $candidates as $tombstone ) { if ( in_array( $tombstone['key_id'], $referenced, true ) ) { continue; } if ( ! self::delete_woo_key( $tombstone ) ) { $failed[] = $tombstone; $incomplete = true; } } self::write_catalog_key_cleanup( $db, $failed ); return $failed; } ); if ( ( $incomplete || $remaining ) && class_exists( 'Aha_Is_Woocommerce_Connect_Automation' ) ) { Aha_Is_Woocommerce_Connect_Automation::schedule_catalog_key_retry(); } return $remaining; } /** Read and validate the legacy in-state managed-key cleanup list. */ private static function legacy_catalog_key_cleanup_ids( array $state ) { if ( ! isset( $state['catalog_key_cleanup'] ) ) { return array(); } return self::validate_catalog_key_ids( $state['catalog_key_cleanup'] ); } /** Read and validate the independent managed-key cleanup option. */ private static function read_catalog_key_cleanup( $db ) { $value = $db->read_catalog_key_cleanup(); if ( null === $value ) { return array(); } $decoded = json_decode( $value, true ); return self::validate_catalog_key_cleanup( $decoded ); } /** Store the independent managed-key cleanup option with autoload disabled. */ private static function write_catalog_key_cleanup( $db, array $cleanup ) { $cleanup = self::normalize_catalog_key_cleanup( $cleanup ); $db->write_catalog_key_cleanup( $cleanup ? json_encode( $cleanup, JSON_THROW_ON_ERROR ) : null ); } /** Validate cleanup tombstones while accepting legacy plain ids for migration. */ private static function validate_catalog_key_cleanup( $cleanup ) { if ( ! is_array( $cleanup ) || array_values( $cleanup ) !== $cleanup ) { throw new InvalidArgumentException( 'invalid_connect_catalog_key_cleanup' ); } foreach ( $cleanup as $entry ) { if ( is_int( $entry ) ) { self::validate_catalog_key_ids( array( $entry ) ); continue; } if ( ! self::valid_catalog_key_tombstone( $entry ) ) { throw new InvalidArgumentException( 'invalid_connect_catalog_key_cleanup' ); } } return $cleanup; } /** Validate an exact list of unique positive Woo key ids. */ private static function validate_catalog_key_ids( $cleanup ) { if ( ! is_array( $cleanup ) || array_values( $cleanup ) !== $cleanup ) { throw new InvalidArgumentException( 'invalid_connect_catalog_key_cleanup' ); } $seen = array(); foreach ( $cleanup as $woo_key_id ) { if ( ! is_int( $woo_key_id ) || $woo_key_id < 1 || $woo_key_id > 2147483647 || isset( $seen[ $woo_key_id ] ) ) { throw new InvalidArgumentException( 'invalid_connect_catalog_key_cleanup' ); } $seen[ $woo_key_id ] = true; } return $cleanup; } /** Normalize trusted Woo key ids before persisting or comparing them. */ private static function normalize_catalog_key_ids( array $ids ) { return array_values( array_unique( array_map( 'intval', $ids ), SORT_NUMERIC ) ); } /** Read all managed rows with the identity needed for safe deletion. */ private static function managed_catalog_key_tombstones() { global $wpdb; $rows = $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- reads the managed WooCommerce REST key table; must see the live rows $wpdb->prepare( "SELECT key_id, truncated_key FROM {$wpdb->prefix}woocommerce_api_keys WHERE BINARY description = BINARY %s", self::CATALOG_KEY_DESCRIPTION ), ARRAY_A ); if ( null === $rows || '' !== (string) $wpdb->last_error ) { return null; } $tombstones = array(); foreach ( $rows as $row ) { $tombstone = array( 'key_id' => isset( $row['key_id'] ) ? (int) $row['key_id'] : 0, 'truncated_key' => isset( $row['truncated_key'] ) ? $row['truncated_key'] : null, ); if ( ! self::valid_catalog_key_tombstone( $tombstone ) ) { return null; } $tombstones[] = $tombstone; } return self::normalize_catalog_key_tombstones( $tombstones ); } /** Build durable identities for catalog keys referenced by one state snapshot. */ private static function catalog_key_tombstones( array $state, array $context ) { $tombstones = array(); if ( isset( $state['catalog_key'] ) && self::valid_registered_catalog_key( $state['catalog_key'] ) ) { if ( isset( $state['catalog_key']['truncated_key'] ) ) { $tombstones[] = array( 'key_id' => $state['catalog_key']['woo_key_id'], 'truncated_key' => $state['catalog_key']['truncated_key'], ); } else { $tombstone = self::managed_catalog_key_tombstone( $state['catalog_key']['woo_key_id'] ); if ( null !== $tombstone ) { $tombstones[] = $tombstone; } } } if ( isset( $state['pending_catalog_key'] ) ) { $pending = self::open_nested( $state['pending_catalog_key'], $context ); self::validate_pending_catalog_key( $pending ); $tombstones[] = array( 'key_id' => $pending['woo_key_id'], 'truncated_key' => substr( $pending['consumer_key'], -7 ), ); } return self::normalize_catalog_key_tombstones( $tombstones ); } /** Resolve a legacy registered id only while it still identifies a managed row. */ private static function managed_catalog_key_tombstone( $woo_key_id ) { global $wpdb; $truncated_key = $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- reads the managed WooCommerce REST key table; must see the live rows $wpdb->prepare( "SELECT truncated_key FROM {$wpdb->prefix}woocommerce_api_keys WHERE key_id = %d AND BINARY description = BINARY %s LIMIT 1", (int) $woo_key_id, self::CATALOG_KEY_DESCRIPTION ) ); if ( '' !== (string) $wpdb->last_error ) { throw new RuntimeException( 'connect_storage_unavailable' ); } if ( null === $truncated_key ) { return null; } $tombstone = array( 'key_id' => (int) $woo_key_id, 'truncated_key' => $truncated_key ); if ( ! self::valid_catalog_key_tombstone( $tombstone ) ) { throw new RuntimeException( 'connect_storage_unavailable' ); } return $tombstone; } /** Replace legacy ids with identities only when discovery still proves ownership. */ private static function migrate_catalog_key_cleanup( array $cleanup, array $managed_by_id ) { $migrated = array(); foreach ( $cleanup as $entry ) { if ( is_int( $entry ) ) { if ( isset( $managed_by_id[ $entry ] ) ) { $migrated[] = $managed_by_id[ $entry ]; } } else { $migrated[] = $entry; } } return self::normalize_catalog_key_tombstones( $migrated ); } /** Normalize trusted cleanup entries while preserving legacy ids until migration. */ private static function normalize_catalog_key_cleanup( array $cleanup ) { $ids = array(); $tombstones = array(); foreach ( $cleanup as $entry ) { if ( is_int( $entry ) ) { $ids[] = $entry; } else { $tombstones[] = $entry; } } return array_merge( self::normalize_catalog_key_ids( $ids ), self::normalize_catalog_key_tombstones( $tombstones ) ); } /** Normalize exact key identities without collapsing recycled ids. */ private static function normalize_catalog_key_tombstones( array $tombstones ) { $normalized = array(); foreach ( $tombstones as $tombstone ) { if ( ! self::valid_catalog_key_tombstone( $tombstone ) ) { throw new InvalidArgumentException( 'invalid_connect_catalog_key_cleanup' ); } $normalized[ $tombstone['key_id'] . ':' . $tombstone['truncated_key'] ] = $tombstone; } return array_values( $normalized ); } /** Validate one exact Woo key identity. */ private static function valid_catalog_key_tombstone( $tombstone ) { return is_array( $tombstone ) && self::exact_keys( $tombstone, array( 'key_id', 'truncated_key' ) ) && is_int( $tombstone['key_id'] ) && $tombstone['key_id'] >= 1 && $tombstone['key_id'] <= 2147483647 && self::valid_truncated_key( $tombstone['truncated_key'] ); } /** Validate WooCommerce's stored seven-character consumer-key suffix. */ private static function valid_truncated_key( $truncated_key ) { return is_string( $truncated_key ) && 1 === preg_match( '/^[0-9a-f]{7}$/D', $truncated_key ); } /** Delete one queued WooCommerce REST key only when its immutable identity matches. */ private static function delete_woo_key( array $tombstone ) { global $wpdb; $deleted = $wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- deletes the managed WooCommerce REST key row guarded by its immutable identity $wpdb->prepare( "DELETE FROM {$wpdb->prefix}woocommerce_api_keys WHERE key_id = %d AND truncated_key = %s AND BINARY description = BINARY %s", $tombstone['key_id'], $tombstone['truncated_key'], self::CATALOG_KEY_DESCRIPTION ) ); return false !== $deleted && '' === (string) $wpdb->last_error; } /** Replace a still-waiting state. */ private static function replace_waiting( array $context, array $snapshot, callable $replace ) { $context['repository']->with_lock( $context['identity'], function ( $db ) use ( $context, $snapshot, $replace ) { $raw = $db->read(); if ( ! is_string( $raw ) ) { return; } $state = self::unpack( $raw, $context ); if ( self::bootstrap_id( $state ) !== self::bootstrap_id( $snapshot['state'] ) || ! in_array( $state['phase'], array( 'pending_review', 'reconnect_approved' ), true ) ) { return; } $db->cas( $raw, self::pack( $replace( $state ), $context ) ); } ); } /** Delete a still-waiting superseded attempt. */ private static function delete_waiting( array $context, array $snapshot ) { $context['repository']->with_lock( $context['identity'], function ( $db ) use ( $context, $snapshot ) { $raw = $db->read(); if ( ! is_string( $raw ) ) { return; } $state = self::unpack( $raw, $context ); if ( self::bootstrap_id( $state ) === self::bootstrap_id( $snapshot['state'] ) && in_array( $state['phase'], array( 'pending_review', 'reconnect_approved' ), true ) ) { $db->delete( $raw ); } } ); } /** Mark access revoked only when the failing request used the current credentials. */ private static function mark_revoked( array $context, $bootstrap_id, $credential_version, $pending_field = null, $command_id = null ) { $changed = $context['repository']->with_lock( $context['identity'], function ( $db ) use ( $context, $bootstrap_id, $credential_version, $pending_field, $command_id ) { $raw = $db->read(); if ( ! is_string( $raw ) ) { return false; } $state = self::unpack( $raw, $context ); if ( 'connected' !== $state['phase'] || ! hash_equals( $bootstrap_id, self::bootstrap_id( $state ) ) || ! isset( $state['credential_version'] ) || (int) $state['credential_version'] !== (int) $credential_version ) { return false; } if ( null !== $pending_field ) { if ( ! isset( $state[ $pending_field ] ) ) { return false; } $pending = self::open_nested( $state[ $pending_field ], $context ); if ( ! isset( $pending['command_id'] ) || ! is_string( $command_id ) || ! hash_equals( $command_id, $pending['command_id'] ) ) { return false; } } self::tombstone_catalog_keys( $db, $state, $context ); $state['phase'] = 'access_revoked'; foreach ( array( 'credentials', 'credential_version', 'connection_generation', 'pending_refresh', 'pending_disconnect', 'pending_catalog_key', 'pending_order_key', 'order_key', 'store_display_name', 'store_sku', 'store_url', 'store_state', 'store_attention', 'store_last_product_sync', 'submitted_at', 'refresh_failing_since' ) as $field ) { unset( $state[ $field ] ); } $db->cas( $raw, self::pack( $state, $context ) ); self::forget_contact(); return true; } ); if ( $changed ) { self::sweep_catalog_keys( $context ); } return $changed; } /** Remember (or clear) the Aha pause. Plugin-local display state, like the last-contact date. */ private static function record_paused( $paused, $paused_at ) { if ( ! $paused ) { delete_option( 'aha_is_woocommerce_connect_paused' ); return; } $time = is_string( $paused_at ) ? self::date_timestamp( $paused_at ) : false; update_option( 'aha_is_woocommerce_connect_paused', false === $time ? 0 : $time, false ); } /** Whether Aha paused this connection. */ public static function is_paused() { return false !== self::paused_at(); } /** @return int|false Pause time (0 when unknown), or false when not paused. */ public static function paused_at() { $value = get_option( 'aha_is_woocommerce_connect_paused', false ); return false === $value ? false : (int) $value; } /** Drop the last-contact date and the cached status check. */ public static function forget_contact() { delete_option( 'aha_is_woocommerce_connect_last_contact' ); delete_option( 'aha_is_woocommerce_connect_paused' ); if ( function_exists( 'delete_transient' ) ) { delete_transient( 'aha_is_woocommerce_connect_status_' . get_current_blog_id() ); } } /** * Read, start or clear the continuous transient refresh failure marker. * * @return int First failure timestamp, or 0 when none is recorded. */ private static function refresh_failing_since( array $context, $start = false, $clear = false ) { return (int) $context['repository']->with_lock( $context['identity'], function ( $db ) use ( $context, $start, $clear ) { $raw = $db->read(); if ( ! is_string( $raw ) ) { return time(); } $state = self::unpack( $raw, $context ); $since = isset( $state['refresh_failing_since'] ) ? (int) $state['refresh_failing_since'] : 0; if ( $clear && $since ) { unset( $state['refresh_failing_since'] ); $db->cas( $raw, self::pack( $state, $context ) ); return 0; } if ( $start && ! $since ) { $since = time(); $state['refresh_failing_since'] = $since; $db->cas( $raw, self::pack( $state, $context ) ); } return $since; } ); } /** Move an unrecoverable credential command to the reconnectable lost state. */ private static function mark_connection_lost( array $context, $bootstrap_id, $pending_field = null, $command_id = null, $credential_version = null ) { $changed = $context['repository']->with_lock( $context['identity'], function ( $db ) use ( $context, $bootstrap_id, $pending_field, $command_id, $credential_version ) { $raw = $db->read(); if ( ! is_string( $raw ) ) { return false; } $state = self::unpack( $raw, $context ); if ( ! hash_equals( $bootstrap_id, self::bootstrap_id( $state ) ) ) { return false; } if ( isset( $state['pending_redeem'] ) ) { $pending_redeem = self::open_nested( $state['pending_redeem'], $context ); if ( self::pending_reusable( $pending_redeem ) ) { return false; } } if ( null !== $credential_version && ( ! isset( $state['credential_version'] ) || (int) $state['credential_version'] !== (int) $credential_version ) ) { return false; } if ( null !== $pending_field ) { if ( ! isset( $state[ $pending_field ] ) ) { return false; } $pending = self::open_nested( $state[ $pending_field ], $context ); if ( ! isset( $pending['command_id'] ) || ! is_string( $command_id ) || ! hash_equals( $command_id, $pending['command_id'] ) ) { return false; } } elseif ( isset( $state['credentials'] ) ) { return false; } self::tombstone_catalog_keys( $db, $state, $context ); $db->cas( $raw, self::pack( self::connection_lost_state( $state ), $context ) ); return true; } ); if ( $changed ) { self::sweep_catalog_keys( $context ); } return $changed; } /** Reconcile a refresh conflict without ever retrying the consumed refresh token. */ private static function resolve_refresh_conflict( array $context, $bootstrap_id, $credential_version ) { $status = $context['repository']->with_lock( $context['identity'], function ( $db ) use ( $context, $bootstrap_id, $credential_version ) { $raw = $db->read(); if ( ! is_string( $raw ) ) { return 'connection_lost'; } $state = self::unpack( $raw, $context ); if ( ! hash_equals( $bootstrap_id, self::bootstrap_id( $state ) ) ) { return $state['phase']; } if ( isset( $state['credential_version'] ) && (int) $state['credential_version'] > (int) $credential_version ) { return 'current'; } if ( isset( $state['pending_redeem'] ) ) { $pending_redeem = self::open_nested( $state['pending_redeem'], $context ); if ( self::pending_reusable( $pending_redeem ) ) { return $state['phase']; } } self::tombstone_catalog_keys( $db, $state, $context ); $db->cas( $raw, self::pack( self::connection_lost_state( $state ), $context ) ); return 'connection_lost'; } ); if ( 'connection_lost' === $status ) { self::sweep_catalog_keys( $context ); } return $status; } /** Remove all material that could accidentally retry a consumed command. */ private static function connection_lost_state( array $state ) { $state['phase'] = 'connection_lost'; foreach ( array( 'credentials', 'credential_version', 'connection_generation', 'pending_redeem', 'pending_refresh', 'pending_disconnect', 'pending_catalog_key', 'pending_order_key', 'order_key', 'store_display_name', 'store_sku', 'store_url', 'store_state', 'store_attention', 'store_last_product_sync', 'submitted_at', 'refresh_failing_since' ) as $field ) { unset( $state[ $field ] ); } self::forget_contact(); return $state; } /** Delete connected local state after disconnect. */ private static function delete_connected( array $context, $bootstrap_id, $command_id, $credential_version = null ) { return $context['repository']->with_lock( $context['identity'], function ( $db ) use ( $context, $bootstrap_id, $command_id, $credential_version ) { $raw = $db->read(); if ( is_string( $raw ) ) { $state = self::unpack( $raw, $context ); if ( 'connected' !== $state['phase'] || ! hash_equals( $bootstrap_id, self::bootstrap_id( $state ) ) || ! isset( $state['pending_disconnect'] ) || ( null !== $credential_version && ( ! isset( $state['credential_version'] ) || (int) $state['credential_version'] !== (int) $credential_version ) ) ) { return false; } $pending = self::open_nested( $state['pending_disconnect'], $context ); if ( isset( $pending['command_id'] ) && hash_equals( $command_id, $pending['command_id'] ) ) { self::tombstone_catalog_keys( $db, $state, $context ); $db->delete( $raw ); self::forget_contact(); return true; } } return false; } ); } /** Make a signed installation command body with fresh anti-replay fields. */ private static function fresh_body( array $fields = array() ) { $fields['nonce'] = Aha_Is_Woocommerce_Connect_Crypto::base64url( random_bytes( 32 ) ); $fields['issued_at'] = self::now_utc(); return $fields; } /** In safe mode the plugin sends nothing to Aha. */ private static function assert_not_safe_mode() { if ( Aha_Is_Woocommerce_Site_Identity::is_safe_mode() ) { throw new RuntimeException( 'connect_safe_mode' ); } } /** Send an installation-signed JSON command. */ private static function post_signed( array $context, array $state, $path, array $body, array $headers = array() ) { self::assert_not_safe_mode(); $headers = array_merge( array( 'Content-Type' => 'application/json', 'Accept' => 'application/json', 'X-Aha-Connect-Installation-Signature' => Aha_Is_Woocommerce_Connect_Crypto::sign( $body, $state['keys']['signing_private'] ), ), $headers ); $result = wp_remote_post( $context['profile']['authority'] . $path, array( 'headers' => $headers, 'body' => wp_json_encode( $body ), 'timeout' => 8, 'redirection' => 0, 'sslverify' => true, 'reject_unsafe_urls' => true, 'limit_response_size' => 8192, ) ); if ( is_wp_error( $result ) ) { return array( 'kind' => 'network_error', 'code' => 0, 'body' => null ); } $decoded = json_decode( wp_remote_retrieve_body( $result ), true ); return array( 'kind' => 'response', 'code' => wp_remote_retrieve_response_code( $result ), 'body' => is_array( $decoded ) ? $decoded : null, ); } /** Extract and validate bootstrap id. */ private static function bootstrap_id( array $state ) { if ( ! isset( $state['response']['bootstrap_id'] ) || ! Aha_Is_Woocommerce_Connect_Crypto::is_b64url32( $state['response']['bootstrap_id'] ) ) { throw new RuntimeException( 'connect_response_missing' ); } return $state['response']['bootstrap_id']; } /** Extract the installation encryption generation. */ private static function encryption_generation( array $state ) { if ( ! isset( $state['request']['encryption_key_generation'] ) || ! is_int( $state['request']['encryption_key_generation'] ) ) { throw new RuntimeException( 'connect_response_missing' ); } return $state['request']['encryption_key_generation']; } /** Require the state to belong to the selected deployment profile. */ private static function assert_profile( array $state, array $profile ) { if ( ! isset( $state['request']['environment'], $state['request']['authority'] ) || $state['request']['environment'] !== $profile['environment'] || $state['request']['authority'] !== $profile['authority'] ) { throw new RuntimeException( 'connect_attempt_bound_to_other_profile' ); } } /** Check a ten-minute persisted-command retry window. */ private static function pending_reusable( array $pending ) { return isset( $pending['created_at'], $pending['command_id'] ) && is_int( $pending['created_at'] ) && self::uuid( $pending['command_id'] ) && time() >= $pending['created_at'] && time() - $pending['created_at'] <= self::RETRY_SECONDS; } /** Parse one exact millisecond UTC timestamp. */ private static function date_timestamp( $value ) { if ( ! is_string( $value ) ) { return false; } $date = DateTimeImmutable::createFromFormat( '!Y-m-d\TH:i:s.v\Z', $value, new DateTimeZone( 'UTC' ) ); return $date && $date->format( 'Y-m-d\TH:i:s.v\Z' ) === $value ? $date->getTimestamp() : false; } /** Compare exact object keys. */ private static function exact_keys( array $value, array $expected ) { $actual = array_keys( $value ); sort( $actual, SORT_STRING ); sort( $expected, SORT_STRING ); return $actual === $expected; } /** Validate the exact WooCommerce grant. */ private static function valid_actions( $actions ) { return array( 'catalog' ) === $actions; } /** Check a one-field error response. */ private static function is_error( $body, $code ) { return is_array( $body ) && $body === array( 'error' => $code ); } /** Check a UUID accepted by the authority. */ private static function uuid( $value ) { return is_string( $value ) && 1 === preg_match( '/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/Di', $value ); } /** Generate a UUID v4. */ private static function uuid4() { return Aha_Is_Woocommerce_Site_Identity::generate_uuid(); } /** Current protocol timestamp. */ private static function now_utc() { return ( new DateTimeImmutable( 'now', new DateTimeZone( 'UTC' ) ) )->format( 'Y-m-d\TH:i:s.v\Z' ); } /** Reconcile background actions after a terminal credential transition. */ private static function reconcile_schedules() { if ( class_exists( 'Aha_Is_Woocommerce_Connect_Automation' ) ) { Aha_Is_Woocommerce_Connect_Automation::ensure_scheduled(); } } }