bind = $bind ?? static fn( int $agent_id ): string => Api::bind_agent( $agent_id ); $this->authenticated = $authenticated ?? static fn(): ?object => self::woocommerce_key(); } /** * The key WooCommerce's REST authenticator accepted this request, or * null. */ public static function woocommerce_key(): ?object { if ( ! class_exists( \WC_REST_Authentication::class ) ) { return null; } $user = ( fn() => $this->user )->call( \WC_REST_Authentication::instance() ); return is_object( $user ) ? $user : null; } /** * Hook authentication. */ public function register(): void { add_filter( 'rest_authentication_errors', array( $this, 'authenticate' ), 25 ); add_filter( 'adaf_unclaimed_credential', array( $this, 'unclaimed' ), 10, 1 ); } /** * Bind the key's agent, or mark the request unclaimed. * * @param mixed $result Authentication result so far. * @return mixed The result, or a 401 for a refused binding. */ public function authenticate( $result ) { $this->unclaimed = false; if ( $result instanceof WP_Error ) { return $result; } $key = ( $this->authenticated )(); if ( null === $key || ! isset( $key->key_id ) || (int) ( $key->user_id ?? 0 ) !== get_current_user_id() ) { return $result; } $agent = $this->bindings->agent_for( (int) $key->key_id ); if ( null === $agent ) { $this->unclaimed = true; return $result; } switch ( ( $this->bind )( $agent ) ) { case 'mismatch': case 'inactive': case 'privileged': return new WP_Error( 'adafwc_key_binding_refused', __( 'This WooCommerce API key is bound to an agent that is disabled, linked to another user, or linked to an administrator without being confirmed as one. Ask a site administrator to fix the binding.', 'agentic-daisy-ai-agent-firewall-for-woocommerce' ), array( 'status' => 401 ) ); case 'unknown': // The agent was deleted: the key is unbound again. $this->unclaimed = true; return $result; default: return $result; } } /** * Tell the parent this request's key is unclaimed. * * @param mixed $unclaimed Whether an unclaimed credential is in use. * @return mixed */ public function unclaimed( $unclaimed ) { return $this->unclaimed ? true : $unclaimed; } }