How I exploited NPM downloads... and why you shouldn't trust them
Tags: javascript, node, security
Published: 2021-03-09 10:46:38

Over this past month, I've managed to get a [package, with little to no users](https://www.npmjs.com/package/is-introspection-query), to accumulate **over one million** downloads 🚀.

It didn't cost any money, no laws were broken (I think) and it took little to no effort.

Here's what you need to know about the downloads statistic on NPM.

## 🔮 The illusion of downloads

If you've ever looked at using a new package from NPM, the chances are you've considered the "Weekly Downloads" statistic. 

It's the first metric displayed on the page - so it must be useful information for the user... right?

<img width="500" alt="Twitter poll" src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m04m8hy4cy5szhh63hkf.png" />

A third of people who responded to [this poll](https://twitter.com/andyrichardsonn/status/1357629687619588097) seemed to think so and even go as far as to say it has a large influence in their decision to adopt a new package.

But here's the thing, it isn't a useful metric for the following two reasons:
 - there is a loose (at best) relationship between users and download counts
 - the system is easily exploitable 

### What is a download

This was pretty well [discussed on the NPM Blog](https://blog.npmjs.org/post/92574016600/numeric-precision-matters-how-npm-download-counts-work.html) but to summarise, it's any successful download of a package (tarball) from NPMs registry.

NPM have openly stated that this this statistic has no consideration for the source (IP, user agent, etc). Meaning all downloads are equal, whether it be from:
 - A user adding a new package to their project
 - A CI run installing dependencies
 - A bot downloading the package repeatedly to create the illusion of popularity _(there's some foreshadowing for you)_

As you can imagine, this means a project with frequent CI runs is likely to have more of an influence on download statistics than any set of individuals (especially when taking npm client caching into consideration).

### Registries

The abundance of registries is another reason why download counts aren't an accurate reflection of usage. NPM download counts only include downloads to the official NPM registry, and not registries such as [unpkg](https://www.unpkg.com/) and [github](https://github.com/features/packages).


## 🧑‍💻 Exploiting the system

---

**Disclaimer:** I've documented this to bring light to how easily exploitable download statistics are. However, I strongly advise that you don't do this as it is both dishonest an unnecessary drain on NPM Inc's resources.

---

If you've read everything up until this point, you'll know that there isn't a need for any kind of "genius hacker exploit". 

Instead, all we need is some way of downloading a package many times.

Running a script locally with some kind of cron job should do just fine - but that isn't too exciting... let's use serverless! 

You can check out the [full repo here](https://github.com/andyrichardson/exploiting-npm-downloads).

### Creating a script

For the Lambda, I created a function which takes the following arguments:
 - `package` - the package to download
 - `probability` - the likelihood of a download for a given run

The latter argument is intended to add noise - simulating the variable nature of downloads over time.

A "coin flip" takes place each run, with the `probability` argument being used to weight the chance of success. If the flip is successful, the package is downloaded.

```jsx
export const handler = async ({ package, probability }) => {
  // Simulate coin flip
  if (Math.random() > probability) {
    // Flip fail
    return;
  }
  
  // Flip success
  await downloadPackage({ package });
};
```

### Triggering the Lambda

To get this script running routinely, a CloudWatch event was set up that triggers at a rate of once a minute.

```tf
// Terraform example
resource "aws_cloudwatch_event_rule" "lambda_trigger_rule" {
  name = "trigger-npm-install"
  description = "Trigger an NPM install"
  schedule_expression = "rate(1 minute)"
}
```

_Example CloudWatch Event Rule in Terraform._

In order to do something when this event is triggered, an event target is set up, pointing to the Lambda with our required arguments. 

```tf
resource "aws_cloudwatch_event_target" "lambda" {
  arn = aws_lambda_function.install_package_lambda.arn
  rule = aws_cloudwatch_event_rule.lambda_trigger_rule.name
  input = jsonencode({
    package = "is-introspection-query"
    probability = 0.8
  })
}
```

_Example CloudWatch Event Target in Terraform._

## 🚀 The result

After deploying this for the duration of a week, the result is... well actually not that impressive; it turns out there aren't as many seconds in a week as I had expected 🤔.

But alas, after some tweaks, we hit just under 1 million downloads per week!

![Download counts](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c2szqfqgl7kqko2pporl.png)

Yes thats right, a package with **literally 0 users** has more downloads than the likes of `urql` and `mobx`. 

Are you seeing the problem now?

### Download stats don't work

Here's the thing, naive download statistics are useless at best and misleading at worst.

The large graph on NPM's site, the culture of [celebrating download](https://twitter.com/kentcdodds/status/1305634347202928641) [counts](https://twitter.com/andyrichardsonn/status/1263041838019227648) online, the third party sites which show [package download "trends](https://www.npmtrends.com/)". These all contribute to this narrative that NPM download counts provide some kind of insight into a packages popularity, and they just don't.

Even ignoring the potential for malicious actors (like myself) the abundance of registries and caching implementations make these statistics less than useful.

### "Popularity"

Fortunately, NPM has a saving grace - the _popularity_ statistic! Let's just replace the download count with some of the more useful statistics... right?

Well no - turns out the _popularity_ statistic seems to be the _downloads_ statistic in disguise. As you can see below, my package managed to surpass `@prisma/engines` in terms of popularity. 

![NPM search result](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b4kehp71mr3ynp51xgb7.png)

Here's a quick comparison of the two packages side-by-side.

|                  | @prisma/engines | is-introspection-query |
|------------------|-----------------|------------------------|
| weekly downloads | ~100,000        | ~800,000               |
| stars            | 264             | 0                      |
| forks            | 35              | 0                      |
| contributors     | 26              | 1                      |
| users            | probably not 0     | definitely 0                      |

## Conclusion

If there's one thing you take away from this discussion, it's that downloads alone aren't a useful metric.

While I've no doubt that NPM could create a popularity metric that aggregates a number of different attributes of a package ([npms.io](https://npms.io/) has already done it), from now on, I'm going to do a little more background research before trusting the _downloads_ and _popularity_ metrics on NPM 🕵️.

---

Hopefully, you found this interesting! If you have any thoughts or comments, feel free to drop them below or hit me up on twitter - [@andyrichardsonn](https://twitter.com/andyrichardsonn)

Disclaimer: All thoughts and opinions expressed in this article are my own.