~ 2 min read

Fighting npm typosquatting attacks and naming rules for npm modules

share this story on
I guess naming is a hard task in general, and for the npm registry, the naming rules have evolved from what they were to begin with, much…

I guess naming is a hard task in general, and for the npm registry, the naming rules have evolved from what they were to begin with, much of which was about mitigating typosquatting attacks.

Uppercase vs Lowercase

In the beginning, the npm repository was case-sensitive and allowed to publish the same package names with different cases.

This lead to the fact that we now have the following two different modules in the repository:

While the latter has been deprecated in favor of the first, they are still different packages.

The registry maintains any existing package names with upper case to not break dependency chains in the ecosystem, but it doesn’t allow anymore (for quite some time) to submit any packages with an uppercase.

Fighting Typosquatting

Another stance that triggered naming rules updates on the npm registry has been the typosqautting attacks we’ve been seeing for a while.

With typosquatting, bad actors could publish malicious modules to the npm registry with names that look much like existing popular modules. The intent being to fool users into installing them, either by driving them to do so through targeted actions or just by mistake — a typo.

You might have heard about the cross-env horror story where a package called crossenv (notice the typo), mimicked the original one but was also kind enough to send all of your environment variables and the passwords and API keys you have in them, to a remote server.

This prompted the npm registry folks to fight typosquatting attacks at the naming level and establish the following:

No new modules are allowed to be published that their names are an exact match with an existing module given that you strip off any punctuation chars.

The npm blog explains this easily with a react-native example — all of the following module names will be disallowed:

  • react_native
  • react.native
  • re.a_ct-native

Further reading:

New Package Moniker rules
_We’ve recently made some changes to how package naming works to better fight typosquatting, and help package authors…_blog.npmjs.org

Naming rules you should follow:

  1. Can’t start with a .
  2. Can’t start with a _
  3. Can’t have leading or trailing spaces
  4. It can’t be node_modules and it can’t be favicon.ico
  5. It is limited to 214 characters
  6. No capital letters allowed, only lowercase.
  7. These special characters are not allowed: “~\’!()*”)’
  8. Module names must adhere to the typosquatting rules mentioned above

The above rules are largely based off of validate-npm-package-name which is used internally by npm itself:

_validate-npm-package-name - Is the given string an acceptable npm package name?_github.com