unpkg/modules/middleware/validatePackageName.js

33 lines
732 B
JavaScript
Raw Normal View History

2019-01-06 00:50:05 +00:00
import validateNpmPackageName from 'validate-npm-package-name';
2018-05-19 15:34:36 +00:00
2018-09-03 16:19:24 +00:00
const hexValue = /^[a-f0-9]+$/i;
function isHash(value) {
return value.length === 32 && hexValue.test(value);
}
2018-05-19 15:34:36 +00:00
/**
* Reject requests for invalid npm package names.
*/
2019-01-06 00:50:05 +00:00
export default function validatePackageName(req, res, next) {
2018-09-03 16:19:24 +00:00
if (isHash(req.packageName)) {
return res
.status(403)
2018-12-17 17:38:05 +00:00
.type('text')
2018-09-03 16:19:24 +00:00
.send(`Invalid package name "${req.packageName}" (cannot be a hash)`);
}
2018-05-26 00:25:04 +00:00
const errors = validateNpmPackageName(req.packageName).errors;
if (errors) {
2018-12-17 17:38:05 +00:00
const reason = errors.join(', ');
2018-05-19 15:34:36 +00:00
return res
.status(403)
2018-12-17 17:38:05 +00:00
.type('text')
2018-05-19 15:34:36 +00:00
.send(`Invalid package name "${req.packageName}" (${reason})`);
}
next();
}