Q:

Compromise of a Public JS Library

I was listening to a podcast about cybersecurity, and I heard that a public JavaScript library was compromised by attackers who injected a credit card scraper into the library, and then every site that used that library was now a source of credit card info for the attackers. 
I was thinking, how would that even work? And if you did do it, wouldn't it be immediately noticed by the people running the library that there was JavaScript code sending data to someone? How could you protect against this attack?

A:

The attack you are referring to is known as Magecart, which targeted scripts for Magento. This attack compromised thousands of sites, including British Airways and Ticketmaster, and others. It was used to steal credit card information of hundreds of thousands of users of these sites. See https://www.csoonline.com/article/3400381/what-is-magecart-how-this-hacker-group-steals-payment-card-data.html for more info.
The attackers launched the attack by modifying javascript scripts hosted on third-party sites (such as Github and various CDN's) that the victim sites incorporated into their own sites.
Preventing this type of attack is rather simple. This is exactly the type of attack that Subresource Integrity is designed to defend against.  It works by including the hash of the javascript file, in the integrity attribute of the script tag that references the javascript file hosted  on the third-party server.  When the browser downloads the script file, it takes a hash of the downloaded file, and checks that it matches the reference hash in the integrity attribute.  If there is a mismatch, then that could mean that the script has been tampered with, and the browser aborts the loading of the script.

And if you did do it, wouldn't it be immediately noticed by the people
  running the library that there was JavaScript code sending data to
  someone?

Probably not. Many sites incorporate scripts that run in the user's browser, and send data to servers (via XHR, Ajax, etc.) routinely.  Unless users were using the developer tools function in the web browser to monitor the browser's network activity, or run some other network monitoring tool, it is unlikely that they would have noticed anything unusual.

