As far as I'm aware, in general there are very limited assurances around the code available from online code repositories (e.g. rubygems, npm, nuget, PyPI etc). In a lot of cases they don't support or enforce things like signed code or other integrity based security measures and authentication to the sites to deploy is, in some case, just a username/password combination, so you're reliant not only on the developers not deliberately placing malware in their code but also that those developers have good operational security practices.
An even larger problem is that in a lot of cases the libraries you install have dependencies, in some cases a large number of dependences, so you are reliant that the developers of those dependencies also are not malicious and have good security practices.
As Terry says with many code libs there are hooks to execute arbitrary code on installation (before the library is even used) so just the act of installing can have bad consequences, especially if done as a privileged user.
In terms of historical instances of compromise, well there was the Rubygems compromise in 2013 as an example of a repository being attacked.
In terms of fixing the problem, well there's the Update Framework initiative to try and improve the situation.