Skip to content

Commit

Permalink
Handle typosquat restrictions (#42)
Browse files Browse the repository at this point in the history
  • Loading branch information
bconnorwhite committed Apr 17, 2021
1 parent bf90794 commit 8a86ee6
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 3 deletions.
13 changes: 10 additions & 3 deletions index.js
Expand Up @@ -8,6 +8,7 @@ const zip = require('lodash.zip');
const validate = require('validate-npm-package-name');
const organizationRegex = require('org-regex')({exact: true});
const pMap = require('p-map');
const {isTaken} = require('is-name-taken');

class InvalidNameError extends Error {}

Expand All @@ -31,9 +32,10 @@ const request = async (name, options) => {
throw error;
}

let urlName = name;
const isScopedPackage = isScoped(name);
if (isScopedPackage) {
name = name.replace(/\//g, '%2f');
urlName = name.replace(/\//g, '%2f');
}

const authInfo = registryAuthToken(registryUrl, {recursive: true});
Expand All @@ -44,16 +46,21 @@ const request = async (name, options) => {

try {
if (isOrganization) {
await got.head(npmOrganizationUrl + name.toLowerCase(), {timeout: 10000});
await got.head(npmOrganizationUrl + urlName.toLowerCase(), {timeout: 10000});
} else {
await got.head(registryUrl + name.toLowerCase(), {timeout: 10000, headers});
await got.head(registryUrl + urlName.toLowerCase(), {timeout: 10000, headers});
}

return false;
} catch (error) {
const {statusCode} = error.response;

if (statusCode === 404) {
if (!isOrganization) {
const conflict = await isTaken(name.toLowerCase(), {maxAge: 60000});
return !conflict;
}

return true;
}

Expand Down
1 change: 1 addition & 0 deletions package.json
Expand Up @@ -33,6 +33,7 @@
],
"dependencies": {
"got": "^10.6.0",
"is-name-taken": "^2.0.0",
"is-scoped": "^2.1.0",
"is-url-superb": "^4.0.0",
"lodash.zip": "^4.2.0",
Expand Down
5 changes: 5 additions & 0 deletions test.js
Expand Up @@ -27,6 +27,11 @@ test('returns false when package name is taken', async t => {
t.false(await npmName('np', options));
});

test('returns false when package name is taken, regardless of punctuation', async t => {
t.false(await npmName('ch-alk'));
t.false(await npmName('recursivereaddir'));
});

test('returns false when organization name is taken', async t => {
t.false(await npmName('@ava'));
t.false(await npmName('@ava/'));
Expand Down

0 comments on commit 8a86ee6

Please sign in to comment.