$view['phase'], 'values' => array(), 'read_only' => true ); if ( isset( $view['connected'] ) ) { $safe['connected'] = array( 'name' => $view['connected']['name'], 'sku' => $view['connected']['sku'] ); } return $safe; } /** * Whether the current user may change Connect state: true when no state exists or this user owns it. * * @return bool False on another owner or unreadable state (fail closed). */ public static function current_user_owns_state() { try { self::read_view( false ); return true; } catch ( Throwable $error ) { return false; } } /** * Build the view; the owner check is skipped only for the other-admin read-only view. * * @param bool $other_admin Skip the user check (profile match is still required). * @return array */ private static function read_view( $other_admin ) { $context = self::context(); $state = $context['repository']->with_lock( $context['identity'], function ( $db ) use ( $context ) { $raw = $db->read(); return null === $raw ? null : self::unpack( $raw, $context ); } ); if ( null === $state ) { return array( 'phase' => 'not_connected', 'values' => self::empty_values() ); } if ( $other_admin ) { if ( ! isset( $state['request']['environment'], $state['request']['authority'] ) || $state['request']['environment'] !== $context['profile']['environment'] || $state['request']['authority'] !== $context['profile']['authority'] ) { throw new RuntimeException( 'connect_attempt_bound_to_other_user' ); } } else { self::assert_owner( $state, $context['profile'] ); } $phase = $state['phase']; if ( ! in_array( $phase, array( 'prepared', 'pending_review', 'returning_pending_review', 'site_bound_to_other_account', 'reconnect_approved', 'connected', 'rejected', 'access_revoked', 'connection_lost' ), true ) && time() >= $state['local_deadline'] ) { $phase = 'expired_unresolved'; } $values = self::empty_values(); if ( in_array( $phase, array( 'consented', 'pending_review' ), true ) && isset( $state['pending_details'] ) && is_array( $state['pending_details'] ) && isset( $state['pending_details']['requested_target_kind'], $state['pending_details']['details'] ) && is_array( $state['pending_details']['details'] ) ) { $values = array_merge( $values, $state['pending_details']['details'] ); $values['requested_target_kind'] = $state['pending_details']['requested_target_kind']; } $view = array( 'phase' => $phase, 'values' => $values ); if ( 'rejected' === $phase ) { $view['reason'] = isset( $state['rejection_reason'] ) && is_string( $state['rejection_reason'] ) ? $state['rejection_reason'] : null; } if ( in_array( $phase, array( 'connected', 'pending_review' ), true ) ) { $name = ''; if ( isset( $state['store_display_name'] ) && is_string( $state['store_display_name'] ) ) { $name = $state['store_display_name']; } elseif ( isset( $state['pending_details']['details']['display_name'] ) && is_string( $state['pending_details']['details']['display_name'] ) ) { $name = $state['pending_details']['details']['display_name']; } elseif ( isset( $state['returning']['display_name'] ) && is_string( $state['returning']['display_name'] ) ) { $name = $state['returning']['display_name']; } $sku = ''; foreach ( array( 'store_sku', 'store_code', 'sku' ) as $field ) { if ( isset( $state[ $field ] ) && is_string( $state[ $field ] ) ) { $sku = $state[ $field ]; break; } } $view['connected'] = array( 'name' => $name, 'sku' => $sku ); if ( isset( $state['store_url'] ) && is_string( $state['store_url'] ) && '' !== $state['store_url'] ) { $view['connected']['url'] = $state['store_url']; } foreach ( array( 'store_state' => 'state', 'store_attention' => 'attention' ) as $field => $key ) { if ( isset( $state[ $field ] ) && is_string( $state[ $field ] ) ) { $view['connected'][ $key ] = $state[ $field ]; } } if ( isset( $state['store_last_product_sync'] ) && is_int( $state['store_last_product_sync'] ) ) { $view['connected']['last_product_sync'] = $state['store_last_product_sync']; } if ( 'pending_review' === $phase && isset( $state['submitted_at'] ) && is_int( $state['submitted_at'] ) && $state['submitted_at'] > 0 ) { $view['submitted_at'] = $state['submitted_at']; } } if ( in_array( $phase, array( 'reconnect_available', 'returning_pending_review', 'site_bound_to_other_account', 'reconnect_approved' ), true ) && isset( $state['returning'] ) && is_array( $state['returning'] ) ) { $view['returning'] = $state['returning']; } return $view; } /** * Validate the opaque callback state, poll Aha, and CAS consent under the lock. * * @param mixed $provided_state Opaque callback state. * @return string * @throws RuntimeException When the stored state or authority response is invalid. * @throws InvalidArgumentException When prerequisites, encrypted state, or authority response data is invalid. */ public static function handle_callback( $provided_state ) { $context = self::context(); $snapshot = self::snapshot( $context ); if ( null === $snapshot || ! is_string( $provided_state ) || ! isset( $snapshot['state']['local_state'] ) || ! hash_equals( $snapshot['state']['local_state'], $provided_state ) ) { return 'callback_invalid'; } self::assert_owner( $snapshot['state'], $context['profile'] ); $status = self::poll_status( $context, $snapshot['state'] ); return self::apply_status_with_reconnect( $context, $snapshot, $status ); } /** * Delete the current owner's local attempt unless review is already pending. * * @return bool * @throws RuntimeException When the stored state is invalid or belongs to another user. * @throws InvalidArgumentException When prerequisites, encrypted state, or authority response data is invalid. */ public static function reset() { $context = self::context(); $deleted = $context['repository']->with_lock( $context['identity'], function ( $db ) use ( $context ) { $raw = $db->read(); if ( null === $raw ) { return true; } $state = self::unpack( $raw, $context ); self::assert_owner( $state, $context['profile'] ); if ( in_array( $state['phase'], array( 'pending_review', 'reconnect_approved' ), true ) ) { return false; } Aha_Is_Woocommerce_Connect_Credentials::tombstone_catalog_keys( $db, $state, $context ); $db->delete( $raw ); Aha_Is_Woocommerce_Connect_Credentials::forget_contact(); return true; } ); if ( $deleted ) { Aha_Is_Woocommerce_Connect_Credentials::sweep_catalog_keys( $context ); } return $deleted; } /** * Delete saved state that can no longer be decrypted, so the merchant can connect again. * * No owner check: the owner is unknowable when the state cannot be decrypted; the admin handler * requires manage_woocommerce. Readable state is never touched; use reset() for it. * * @return bool True when unreadable state was deleted; false when there was nothing to discard. * @throws RuntimeException When the stored state cannot be read for another reason. * @throws InvalidArgumentException When prerequisites or the WordPress salts are invalid (state is kept). */ public static function discard_unreadable() { $context = self::context(); $discarded = $context['repository']->with_lock( $context['identity'], function ( $db ) use ( $context ) { $raw = $db->read(); if ( null === $raw ) { return false; } try { self::unpack( $raw, $context ); return false; } catch ( Throwable $error ) { if ( ! in_array( $error->getMessage(), array( 'invalid_connect_envelope', 'connect_state_corrupt' ), true ) ) { throw $error; } } $db->delete( $raw ); return true; } ); if ( $discarded ) { Aha_Is_Woocommerce_Connect_Credentials::forget_contact(); Aha_Is_Woocommerce_Connect_Credentials::sweep_catalog_keys( $context ); } return $discarded; } /** * Validate merchant input against the exact sync limits. * * @param array $input Merchant input. * @return array */ public static function validate_details( array $input ) { $values = self::empty_values(); foreach ( array_keys( $values ) as $field ) { $values[ $field ] = isset( $input[ $field ] ) && is_string( $input[ $field ] ) ? self::javascript_trim( 'description' === $field ? str_replace( array( "\r\n", "\r" ), "\n", $input[ $field ] ) : $input[ $field ] ) : ''; } $errors = array(); if ( ! in_array( $values['requested_target_kind'], array( 'store', 'restaurant' ), true ) ) { $errors['requested_target_kind'] = __( 'Choose Store or Restaurant.', 'aha-is-for-woocommerce' ); } $limits = array( 'display_name' => 120, 'street_address' => 200, 'postcode' => 16, 'city' => 100 ); foreach ( $limits as $field => $maximum ) { if ( '' === $values[ $field ] || 1 !== preg_match( '//u', $values[ $field ] ) || self::text_length( $values[ $field ] ) > $maximum || preg_match( '/[\x00-\x1F\x7F-\x9F]/u', $values[ $field ] ) ) { $errors[ $field ] = __( 'Enter a valid value within the allowed length.', 'aha-is-for-woocommerce' ); } } // 7 digits without "+" (Icelandic), 8 to 15 digits with a leading "+". $digits = strlen( preg_replace( '/\D/', '', $values['phone'] ) ); if ( 1 !== preg_match( '/^\+?[0-9 ()\-]+$/D', $values['phone'] ) || strlen( $values['phone'] ) > 32 || ( 0 === strpos( $values['phone'], '+' ) ? $digits < 8 || $digits > 15 : 7 !== $digits ) ) { $errors['phone'] = __( 'Enter a 7-digit Icelandic number, or an international number that starts with + (8–15 digits).', 'aha-is-for-woocommerce' ); } if ( '' !== $values['description'] && ( 1 !== preg_match( '//u', $values['description'] ) || self::text_length( $values['description'] ) > 1000 || preg_match( '/[\x00-\x09\x0B-\x1F\x7F]/', $values['description'] ) ) ) { $errors['description'] = __( 'Description can be at most 1000 characters.', 'aha-is-for-woocommerce' ); } return array( 'values' => $values, 'errors' => $errors ); } /** * Build the exact signed command body. * * @param string $bootstrap_id Bootstrap identifier. * @param array $values Merchant values. * @param string|null $command_id Command identifier. * @param string|null $issued_at Command issue time. * @return array * @throws InvalidArgumentException When the response or details are invalid. */ public static function build_details_body( $bootstrap_id, array $values, $command_id = null, $issued_at = null ) { if ( ! is_string( $bootstrap_id ) || '' === $bootstrap_id ) { throw new InvalidArgumentException( 'connect_response_missing' ); } $validated = self::validate_details( $values ); if ( $validated['errors'] ) { throw new InvalidArgumentException( 'invalid_connect_details' ); } $details = array( 'display_name' => $validated['values']['display_name'], 'street_address' => $validated['values']['street_address'], 'postcode' => $validated['values']['postcode'], 'city' => $validated['values']['city'], 'phone' => $validated['values']['phone'], ); if ( '' !== $validated['values']['description'] ) { $details['description'] = $validated['values']['description']; } return array( 'bootstrap_id' => $bootstrap_id, 'command_id' => null === $command_id ? self::uuid4() : $command_id, 'issued_at' => null === $issued_at ? self::now_utc() : $issued_at, 'requested_target_kind' => $validated['values']['requested_target_kind'], 'details' => $details, ); } /** * Build the exact signed reconnect command body. * * @param string $bootstrap_id Bootstrap identifier. * @param string $retained_pending_request_id Retained request identifier. * @param string|null $command_id Command identifier. * @param string|null $issued_at Command issue time. * @return array * @throws InvalidArgumentException When an identifier is invalid. */ public static function build_reconnect_body( $bootstrap_id, $retained_pending_request_id, $command_id = null, $issued_at = null ) { if ( ! is_string( $bootstrap_id ) || ! Aha_Is_Woocommerce_Connect_Crypto::is_b64url32( $bootstrap_id ) ) { throw new InvalidArgumentException( 'connect_response_missing' ); } if ( ! self::uuid( $retained_pending_request_id ) ) { throw new InvalidArgumentException( 'invalid_retained_pending_request_id' ); } $command_id = null === $command_id ? self::uuid4() : $command_id; $issued_at = null === $issued_at ? self::now_utc() : $issued_at; $date = is_string( $issued_at ) ? DateTimeImmutable::createFromFormat( '!Y-m-d\TH:i:s.v\Z', $issued_at, new DateTimeZone( 'UTC' ) ) : false; if ( ! self::uuid( $command_id ) || ! $date || $date->format( 'Y-m-d\TH:i:s.v\Z' ) !== $issued_at ) { throw new InvalidArgumentException( 'invalid_reconnect_command' ); } return array( 'bootstrap_id' => $bootstrap_id, 'command_id' => $command_id, 'issued_at' => $issued_at, 'retained_pending_request_id' => $retained_pending_request_id, ); } /** * Reuse an exact pending command for five minutes, inclusive. * * @param array $body Pending command body. * @param int|null $now Current Unix timestamp. * @return bool */ public static function pending_body_reusable( array $body, $now = null ) { if ( ! isset( $body['issued_at'] ) || ! is_string( $body['issued_at'] ) ) { return false; } $date = DateTimeImmutable::createFromFormat( '!Y-m-d\TH:i:s.v\Z', $body['issued_at'], new DateTimeZone( 'UTC' ) ); if ( ! $date || $date->format( 'Y-m-d\TH:i:s.v\Z' ) !== $body['issued_at'] ) { return false; } $age = ( null === $now ? time() : (int) $now ) - $date->getTimestamp(); return $age >= 0 && $age <= 300; } /** * Reuse an exact reconnect command inside its accepted clock window. * * @param array $body Pending command body. * @param int|null $now Current Unix timestamp. * @return bool */ public static function reconnect_body_reusable( array $body, $now = null ) { if ( ! isset( $body['issued_at'] ) || ! is_string( $body['issued_at'] ) ) { return false; } $date = DateTimeImmutable::createFromFormat( '!Y-m-d\TH:i:s.v\Z', $body['issued_at'], new DateTimeZone( 'UTC' ) ); if ( ! $date || $date->format( 'Y-m-d\TH:i:s.v\Z' ) !== $body['issued_at'] ) { return false; } $age = ( null === $now ? time() : (int) $now ) - $date->getTimestamp(); return $age >= -60 && $age <= 300; } /** * Persist-before-send details submission with deterministic retry handling. * * @param array $input Merchant details. * @return array * @throws RuntimeException When stored state or authority data is invalid. * @throws InvalidArgumentException When prerequisites, encrypted state, or authority response data is invalid. */ public static function submit_details( array $input ) { $validated = self::validate_details( $input ); if ( $validated['errors'] ) { return array( 'status' => 'validation_error', 'values' => $validated['values'], 'errors' => $validated['errors'] ); } $context = self::context(); $snapshot = self::snapshot( $context ); if ( null === $snapshot ) { return array( 'status' => 'neutral_error' ); } self::assert_owner( $snapshot['state'], $context['profile'] ); if ( 'consented' !== $snapshot['state']['phase'] ) { return array( 'status' => 'neutral_error' ); } if ( time() >= $snapshot['state']['local_deadline'] ) { $status = self::poll_status( $context, $snapshot['state'] ); $phase = self::apply_status_with_reconnect( $context, $snapshot, $status ); if ( 'consented' !== $phase ) { return array( 'status' => $phase ); } return array( 'status' => 'expired_unresolved' ); } $body = isset( $snapshot['state']['pending_details'] ) && is_array( $snapshot['state']['pending_details'] ) ? $snapshot['state']['pending_details'] : null; if ( null !== $body && ! self::pending_body_reusable( $body ) ) { $status = self::poll_status( $context, $snapshot['state'] ); $phase = self::apply_status_with_reconnect( $context, $snapshot, $status ); if ( 'consented' !== $phase ) { return array( 'status' => $phase ); } $body = null; } if ( null === $body ) { if ( ! isset( $snapshot['state']['response']['bootstrap_id'] ) ) { return array( 'status' => 'neutral_error' ); } $body = self::build_details_body( $snapshot['state']['response']['bootstrap_id'], $validated['values'] ); $snapshot = self::store_pending_details( $context, $snapshot, $body ); } $response = self::post_details( $context, $snapshot['state'], $body ); if ( 'network_error' === $response['kind'] || $response['code'] >= 500 ) { return array( 'status' => 'send_retry', 'values' => self::values_from_body( $body ) ); } if ( 200 === $response['code'] ) { $pending_request_id = self::pending_request_id( $response['body'] ); if ( null === $pending_request_id ) { return array( 'status' => 'neutral_error' ); } // Keep the merchant-entered store name (not sensitive) so the connected card survives later state rewrites. $extra = array( 'pending_request_id' => $pending_request_id, 'submitted_at' => time() ); if ( isset( $body['details']['display_name'] ) && is_string( $body['details']['display_name'] ) ) { $extra['store_display_name'] = $body['details']['display_name']; } self::transition( $context, $snapshot, 'pending_review', $extra ); if ( class_exists( 'Aha_Is_Woocommerce_Connect_Automation' ) ) { Aha_Is_Woocommerce_Connect_Automation::ensure_scheduled(); } return array( 'status' => 'pending_review' ); } if ( 409 === $response['code'] ) { $status = self::poll_status( $context, $snapshot['state'] ); $phase = self::apply_status_with_reconnect( $context, $snapshot, $status ); if ( 'consented' !== $phase ) { return array( 'status' => $phase ); } } if ( $response['code'] >= 400 && $response['code'] < 500 && 409 !== $response['code'] ) { self::clear_pending_details( $context, $snapshot ); } return array( 'status' => 'neutral_error' ); } /** * Edit the submitted details while the request waits for review. * * Installation-signed only: no status bearer, because that token expires soon after Connect starts. * * @param array $input Merchant details. * @return array * @throws RuntimeException When stored state or authority data is invalid. * @throws InvalidArgumentException When prerequisites or state are invalid. */ public static function edit_details( array $input ) { $context = self::context(); $snapshot = self::snapshot( $context ); if ( null === $snapshot ) { return array( 'status' => 'neutral_error' ); } self::assert_owner( $snapshot['state'], $context['profile'] ); if ( 'pending_review' !== $snapshot['state']['phase'] || ! isset( $snapshot['state']['response']['bootstrap_id'], $snapshot['state']['keys']['signing_private'] ) ) { return array( 'status' => 'neutral_error' ); } $validated = self::validate_details( $input ); if ( $validated['errors'] ) { return array( 'status' => 'validation_error', 'values' => $validated['values'], 'errors' => $validated['errors'] ); } $stored = self::build_details_body( $snapshot['state']['response']['bootstrap_id'], $validated['values'] ); $body = $stored; $body['nonce'] = Aha_Is_Woocommerce_Connect_Crypto::base64url( random_bytes( 32 ) ); $response = self::post_json( $context['profile']['authority'] . self::EDIT_PATH, array( 'Content-Type' => 'application/json', 'Accept' => 'application/json', 'X-Aha-Connect-Installation-Signature' => Aha_Is_Woocommerce_Connect_Crypto::sign( $body, $snapshot['state']['keys']['signing_private'] ), ), $body ); if ( 'network_error' === $response['kind'] || $response['code'] >= 500 ) { return array( 'status' => 'send_retry', 'values' => $validated['values'] ); } if ( 200 === $response['code'] ) { $ok = is_array( $response['body'] ) && isset( $response['body']['pending_request_id'] ) && self::uuid( $response['body']['pending_request_id'] ); if ( ! $ok ) { return array( 'status' => 'neutral_error' ); } self::transition( $context, $snapshot, 'pending_review', array( 'pending_details' => $stored, 'store_display_name' => $stored['details']['display_name'] ) ); return array( 'status' => 'edited' ); } if ( 409 === $response['code'] && is_array( $response['body'] ) && isset( $response['body']['error'] ) && 'not_reviewable' === $response['body']['error'] ) { // The request moved on at Aha. Reuse the waiting-screen poll to learn the real phase. try { $phase = Aha_Is_Woocommerce_Connect_Credentials::poll_request(); } catch ( Throwable $error ) { $phase = 'pending_review'; } return array( 'status' => 'pending_review' === $phase ? 'not_reviewable' : $phase ); } return array( 'status' => 'neutral_error' ); } /** * Persist-before-send reconnect submission with deterministic retry handling. * * @return array * @throws RuntimeException When stored state or authority data is invalid. * @throws InvalidArgumentException When prerequisites or response data is invalid. */ public static function submit_reconnect() { $context = self::context(); $snapshot = self::snapshot( $context ); if ( null === $snapshot ) { return array( 'status' => 'neutral_error' ); } self::assert_owner( $snapshot['state'], $context['profile'] ); if ( 'returning_pending_review' === $snapshot['state']['phase'] ) { // "Check status" reuses this action: poll the authority and apply the result. $status = self::poll_status( $context, $snapshot['state'] ); return array( 'status' => self::apply_status_with_reconnect( $context, $snapshot, $status ) ); } if ( 'reconnect_available' !== $snapshot['state']['phase'] || ! isset( $snapshot['state']['returning']['retained_pending_request_id'] ) ) { return array( 'status' => 'neutral_error' ); } if ( time() >= $snapshot['state']['local_deadline'] ) { $status = self::poll_status( $context, $snapshot['state'] ); $phase = self::apply_status( $context, $snapshot, $status ); return array( 'status' => 'reconnect_available' === $phase ? 'expired_unresolved' : $phase ); } $body = isset( $snapshot['state']['pending_reconnect'] ) && is_array( $snapshot['state']['pending_reconnect'] ) ? $snapshot['state']['pending_reconnect'] : null; if ( null !== $body && ( ! isset( $body['retained_pending_request_id'] ) || $body['retained_pending_request_id'] !== $snapshot['state']['returning']['retained_pending_request_id'] ) ) { $body = null; } if ( null !== $body && ! self::reconnect_body_reusable( $body ) ) { $status = self::poll_status( $context, $snapshot['state'] ); $phase = self::apply_status( $context, $snapshot, $status ); if ( 'reconnect_available' !== $phase ) { return array( 'status' => $phase ); } $snapshot = self::snapshot( $context ); $body = null; } if ( null === $body ) { if ( ! isset( $snapshot['state']['response']['bootstrap_id'] ) ) { return array( 'status' => 'neutral_error' ); } $body = self::build_reconnect_body( $snapshot['state']['response']['bootstrap_id'], $snapshot['state']['returning']['retained_pending_request_id'] ); $snapshot = self::store_pending_reconnect( $context, $snapshot, $body ); } $response = self::post_command( $context, $snapshot['state'], $body, self::RECONNECT_PATH ); if ( 'network_error' === $response['kind'] || $response['code'] >= 500 ) { return array( 'status' => 'send_retry' ); } if ( 200 === $response['code'] ) { $pending_request_id = self::approved_pending_request_id( $response['body'] ); if ( null === $pending_request_id ) { return array( 'status' => 'neutral_error' ); } $returning = array( 'state' => 'approved', 'pending_request_id' => $pending_request_id ); self::transition( $context, $snapshot, 'reconnect_approved', array( 'pending_request_id' => $pending_request_id, 'returning' => $returning ) ); if ( class_exists( 'Aha_Is_Woocommerce_Connect_Automation' ) ) { Aha_Is_Woocommerce_Connect_Automation::ensure_scheduled(); } return array( 'status' => 'reconnect_approved' ); } if ( 409 === $response['code'] && $response['body'] === array( 'error' => 'site_bound_to_other_account' ) ) { self::transition( $context, $snapshot, 'site_bound_to_other_account', array( 'returning' => array( 'state' => 'blocked', 'reason' => 'site_bound_to_other_account' ) ) ); return array( 'status' => 'site_bound_to_other_account' ); } if ( 409 === $response['code'] && $response['body'] === array( 'error' => 'returning_state_changed' ) ) { $status = self::poll_status( $context, $snapshot['state'] ); return array( 'status' => self::apply_status( $context, $snapshot, $status ) ); } if ( $response['code'] >= 400 && $response['code'] < 500 && 409 !== $response['code'] ) { self::clear_pending_reconnect( $context, $snapshot ); } return array( 'status' => 'neutral_error' ); } /** * Return empty merchant detail values. * * @return array */ private static function empty_values() { return array( 'requested_target_kind' => 'store', 'display_name' => '', 'street_address' => '', 'postcode' => '', 'city' => '', 'phone' => '', 'description' => '' ); } /** * Read merchant detail values from a command body. * * @param array $body Command body. * @return array */ private static function values_from_body( array $body ) { return array_merge( array( 'requested_target_kind' => $body['requested_target_kind'] ), $body['details'] ); } /** * Trim JavaScript whitespace from a value. * * @param string $value Value to trim. * @return string */ private static function javascript_trim( $value ) { if ( 1 !== preg_match( '//u', $value ) ) { return $value; } $whitespace = '\x{0009}-\x{000D}\x{0020}\x{00A0}\x{1680}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}\x{FEFF}'; return preg_replace( array( '/^[' . $whitespace . ']+/u', '/[' . $whitespace . ']+$/u' ), '', $value ); } /** * Count the UTF-16 code units in a value. * * @param string $value Value to count. * @return int|float */ private static function text_length( $value ) { if ( function_exists( 'mb_convert_encoding' ) ) { return strlen( mb_convert_encoding( $value, 'UTF-16LE', 'UTF-8' ) ) / 2; } $count = preg_match_all( '/./us', $value, $characters ); if ( false === $count ) { return strlen( $value ); } $length = 0; foreach ( $characters[0] as $character ) { $length += 4 === strlen( $character ) ? 2 : 1; } return $length; } /** * Build the current Connect context. * * @return array */ 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 a state snapshot under the repository lock. * * @param array $context Connect context. * @return array|null */ 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 ) ); } ); } /** * Decode and validate stored state. * * @param mixed $raw Stored state. * @param array $context Connect context. * @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( $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'], $state['local_state'], $state['user_id'], $state['local_deadline'] ) || ! array_key_exists( 'response', $state ) ) { throw new RuntimeException( 'connect_state_corrupt' ); } return $state; } /** * Encode state for storage. * * @param array $state Connect state. * @param array $context Connect context. * @return string */ 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 ); } /** * Require state ownership by the current user and profile. * * @param array $state Connect state. * @param array $profile Deployment profile. * @return void * @throws RuntimeException When the state belongs to another user or profile. */ private static function assert_owner( array $state, array $profile ) { if ( ( $state['user_id'] !== get_current_user_id() && ! ( Aha_Is_Woocommerce_Connect_Credentials::owner_lost( $state ) && current_user_can( 'manage_woocommerce' ) ) ) // Takeover: a lost owner leaves no one else able to act. || ! 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_user' ); } } /** * Store a pending details command. * * @param array $context Connect context. * @param array $snapshot State snapshot. * @param array $body Command body. * @return array * @throws RuntimeException When the state has changed. */ private static function store_pending_details( array $context, array $snapshot, array $body ) { $next_raw = $context['repository']->with_lock( $context['identity'], function ( $db ) use ( $context, $snapshot, $body ) { $current_raw = $db->read(); if ( ! is_string( $current_raw ) || ! hash_equals( $snapshot['raw'], $current_raw ) ) { throw new RuntimeException( 'connect_state_conflict' ); } $current = self::unpack( $current_raw, $context ); self::assert_owner( $current, $context['profile'] ); if ( 'consented' !== $current['phase'] ) { throw new RuntimeException( 'connect_state_conflict' ); } $current['pending_details'] = $body; $next_raw = self::pack( $current, $context ); $db->cas( $current_raw, $next_raw ); return $next_raw; } ); $next_state = $snapshot['state']; $next_state['pending_details'] = $body; return array( 'raw' => $next_raw, 'state' => $next_state ); } /** * Clear a pending details command. * * @param array $context Connect context. * @param array $snapshot State snapshot. * @return void * @throws RuntimeException When the state has changed. */ private static function clear_pending_details( array $context, array $snapshot ) { $context['repository']->with_lock( $context['identity'], function ( $db ) use ( $context, $snapshot ) { $current_raw = $db->read(); if ( ! is_string( $current_raw ) || ! hash_equals( $snapshot['raw'], $current_raw ) ) { throw new RuntimeException( 'connect_state_conflict' ); } $current = self::unpack( $current_raw, $context ); self::assert_owner( $current, $context['profile'] ); if ( 'consented' !== $current['phase'] || ! isset( $current['pending_details'] ) ) { throw new RuntimeException( 'connect_state_conflict' ); } unset( $current['pending_details'] ); $db->cas( $current_raw, self::pack( $current, $context ) ); } ); } /** * Store a pending reconnect command. * * @param array $context Connect context. * @param array $snapshot State snapshot. * @param array $body Command body. * @return array * @throws RuntimeException When the state has changed. */ private static function store_pending_reconnect( array $context, array $snapshot, array $body ) { $next_raw = $context['repository']->with_lock( $context['identity'], function ( $db ) use ( $context, $snapshot, $body ) { $current_raw = $db->read(); if ( ! is_string( $current_raw ) || ! hash_equals( $snapshot['raw'], $current_raw ) ) { throw new RuntimeException( 'connect_state_conflict' ); } $current = self::unpack( $current_raw, $context ); self::assert_owner( $current, $context['profile'] ); if ( 'reconnect_available' !== $current['phase'] ) { throw new RuntimeException( 'connect_state_conflict' ); } $current['pending_reconnect'] = $body; $next_raw = self::pack( $current, $context ); $db->cas( $current_raw, $next_raw ); return $next_raw; } ); $next_state = $snapshot['state']; $next_state['pending_reconnect'] = $body; return array( 'raw' => $next_raw, 'state' => $next_state ); } /** * Clear a definitively rejected reconnect command. * * @param array $context Connect context. * @param array $snapshot State snapshot. * @return void * @throws RuntimeException When the state has changed. */ private static function clear_pending_reconnect( array $context, array $snapshot ) { $context['repository']->with_lock( $context['identity'], function ( $db ) use ( $context, $snapshot ) { $current_raw = $db->read(); if ( ! is_string( $current_raw ) || ! hash_equals( $snapshot['raw'], $current_raw ) ) { throw new RuntimeException( 'connect_state_conflict' ); } $current = self::unpack( $current_raw, $context ); self::assert_owner( $current, $context['profile'] ); if ( 'reconnect_available' !== $current['phase'] || ! isset( $current['pending_reconnect'] ) ) { throw new RuntimeException( 'connect_state_conflict' ); } unset( $current['pending_reconnect'] ); $db->cas( $current_raw, self::pack( $current, $context ) ); } ); } /** * Transition a state snapshot to another phase. * * @param array $context Connect context. * @param array $snapshot State snapshot. * @param string $phase Next phase. * @param array $extra Additional state fields. * @param array $remove State fields to remove atomically. * @return void * @throws RuntimeException When the state has changed. */ private static function transition( array $context, array $snapshot, $phase, array $extra = array(), array $remove = array() ) { $context['repository']->with_lock( $context['identity'], function ( $db ) use ( $context, $snapshot, $phase, $extra, $remove ) { $current_raw = $db->read(); if ( ! is_string( $current_raw ) || ! hash_equals( $snapshot['raw'], $current_raw ) ) { throw new RuntimeException( 'connect_state_conflict' ); } $current = self::unpack( $current_raw, $context ); self::assert_owner( $current, $context['profile'] ); $current['phase'] = $phase; foreach ( $extra as $key => $value ) { $current[ $key ] = $value; } foreach ( $remove as $key ) { unset( $current[ $key ] ); } $db->cas( $current_raw, self::pack( $current, $context ) ); } ); } /** * Map an authority status to a local phase and persist returning metadata. * * @param array $context Connect context. * @param array $snapshot State snapshot. * @param array $status Validated authority status. * @return string */ private static function apply_status( array $context, array $snapshot, array $status ) { if ( 'pending_review' === $status['status'] ) { $remove = isset( $snapshot['state']['pending_reconnect'] ) ? array( 'pending_reconnect' ) : array(); if ( 'pending_review' !== $snapshot['state']['phase'] || $remove ) { self::transition( $context, $snapshot, 'pending_review', array(), $remove ); } return 'pending_review'; } if ( 'consented' !== $status['status'] ) { return $status['status']; } if ( ! isset( $status['returning'] ) ) { $remove = isset( $snapshot['state']['pending_reconnect'] ) ? array( 'pending_reconnect' ) : array(); if ( 'consented' !== $snapshot['state']['phase'] || $remove ) { self::transition( $context, $snapshot, 'consented', array(), $remove ); } return 'consented'; } $returning = $status['returning']; $phases = array( 'approved' => 'reconnect_approved', 'blocked' => 'site_bound_to_other_account', 'pending_review' => 'returning_pending_review', 'reconnect' => 'reconnect_available', ); $phase = $phases[ $returning['state'] ]; $old_retained_id = isset( $snapshot['state']['returning']['retained_pending_request_id'] ) ? $snapshot['state']['returning']['retained_pending_request_id'] : null; $new_retained_id = isset( $returning['retained_pending_request_id'] ) ? $returning['retained_pending_request_id'] : null; $remove = isset( $snapshot['state']['pending_reconnect'] ) && ( 'reconnect_available' !== $phase || $old_retained_id !== $new_retained_id ) ? array( 'pending_reconnect' ) : array(); $unchanged = $phase === $snapshot['state']['phase'] && isset( $snapshot['state']['returning'] ) && Aha_Is_Woocommerce_Connect_Crypto::canonical_json( $returning ) === Aha_Is_Woocommerce_Connect_Crypto::canonical_json( $snapshot['state']['returning'] ) && ! $remove; if ( ! $unchanged ) { $extra = array( 'returning' => $returning ); if ( 'approved' === $returning['state'] ) { $extra['pending_request_id'] = $returning['pending_request_id']; } self::transition( $context, $snapshot, $phase, $extra, $remove ); } return $phase; } /** * Persist a polled status and immediately submit a reconnect when offered. * * @param array $context Connect context. * @param array $snapshot State snapshot. * @param array $status Validated authority status. * @return string */ private static function apply_status_with_reconnect( array $context, array $snapshot, array $status ) { $phase = self::apply_status( $context, $snapshot, $status ); if ( 'reconnect_available' === $phase ) { return self::submit_reconnect()['status']; } return $phase; } /** * Poll the authority for Connect status. * * @param array $context Connect context. * @param array $state Connect state. * @return array * @throws RuntimeException When response data is missing or unavailable. * @throws InvalidArgumentException When the authority status body is invalid. */ private static function poll_status( array $context, array $state ) { if ( ! isset( $state['response']['status_token'] ) ) { throw new RuntimeException( 'connect_response_missing' ); } $result = self::post_json( $context['profile']['authority'] . '/connect/v1/bootstrap/status', array( 'Content-Type' => 'application/json', 'Accept' => 'application/json' ), array( 'status_token' => $state['response']['status_token'] ) ); if ( 'network_error' === $result['kind'] || 200 !== $result['code'] || ! is_array( $result['body'] ) ) { throw new RuntimeException( 'connect_authority_unavailable' ); } Aha_Is_Woocommerce_Connect_Proof::validate_status( $result['body'], $context['profile'] ); return $result['body']; } /** * Post a signed details command. * * @param array $context Connect context. * @param array $state Connect state. * @param array $body Command body. * @return array * @throws RuntimeException When response data is missing. */ private static function post_details( array $context, array $state, array $body ) { return self::post_command( $context, $state, $body, self::DETAILS_PATH ); } /** * Post a signed Connect command. * * @param array $context Connect context. * @param array $state Connect state. * @param array $body Command body. * @param string $path Trusted authority path. * @return array * @throws RuntimeException When response data is missing. */ private static function post_command( array $context, array $state, array $body, $path ) { if ( ! isset( $state['response']['status_token'], $state['keys']['signing_private'] ) ) { throw new RuntimeException( 'connect_response_missing' ); } return self::post_json( $context['profile']['authority'] . $path, array( 'Content-Type' => 'application/json', 'Accept' => 'application/json', 'Authorization' => 'Aha-Connect-Status ' . $state['response']['status_token'], 'X-Aha-Connect-Installation-Signature' => Aha_Is_Woocommerce_Connect_Crypto::sign( $body, $state['keys']['signing_private'] ), ), $body ); } /** * Post a JSON request. * * @param string $url Request URL. * @param array $headers Request headers. * @param array $body Request body. * @return array */ private static function post_json( $url, array $headers, array $body ) { // Safe mode sends nothing to Aha. Callers treat this as retry later. if ( Aha_Is_Woocommerce_Site_Identity::is_safe_mode() ) { return array( 'kind' => 'network_error', 'code' => 0, 'body' => null ); } $result = wp_remote_post( $url, 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 ); } /** * Read a pending request identifier from a response body. * * @param mixed $body Response body. * @return string|null */ private static function pending_request_id( $body ) { if ( ! is_array( $body ) ) { return null; } $keys = array_keys( $body ); sort( $keys, SORT_STRING ); if ( array( 'pending_request_id', 'status' ) !== $keys || 'pending_review' !== $body['status'] || ! is_string( $body['pending_request_id'] ) || '' === trim( $body['pending_request_id'] ) || preg_match( '/[\x00-\x1F\x7F]/', $body['pending_request_id'] ) ) { return null; } return $body['pending_request_id']; } /** * Read an approved request identifier from an exact reconnect response. * * @param mixed $body Response body. * @return string|null */ private static function approved_pending_request_id( $body ) { if ( ! is_array( $body ) ) { return null; } $keys = array_keys( $body ); sort( $keys, SORT_STRING ); if ( array( 'pending_request_id', 'status' ) !== $keys || 'approved' !== $body['status'] || ! self::uuid( $body['pending_request_id'] ) ) { return null; } return $body['pending_request_id']; } /** * Check a canonical UUID string. * * @param mixed $value Value to check. * @return bool */ private static function uuid( $value ) { return is_string( $value ) && 1 === preg_match( '/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/Di', $value ); } /** * Generate a UUID. * * @return string */ private static function uuid4() { return Aha_Is_Woocommerce_Site_Identity::generate_uuid(); } /** * Return the current UTC time in protocol format. * * @return string */ private static function now_utc() { return ( new DateTimeImmutable( 'now', new DateTimeZone( 'UTC' ) ) )->format( 'Y-m-d\TH:i:s.v\Z' ); } }