@nodesecure/js-x-ray
Version:
JavaScript AST XRay analysis
49 lines • 1.45 kB
JavaScript
import safeRegex from "safe-regex";
// Import Internal Dependencies
import { SourceFile } from "../SourceFile.js";
import { generateWarning } from "../warnings.js";
/**
* @description Search for Regex Object constructor.
* @see https://github.com/estree/estree/blob/master/es5.md#newexpression
* @example
* new RegExp("...");
*/
function validateNode(node) {
return [
isRegexConstructor(node) && node.arguments.length > 0
];
}
function main(node, options) {
const { sourceFile } = options;
const arg = node.arguments.at(0);
if (!arg) {
return;
}
/**
* Note: RegExp Object can contain a RegExpLiteral
* @see https://github.com/estree/estree/blob/master/es5.md#regexpliteral
*
* @example
* new RegExp(/^foo/)
*/
const pattern = arg.type === "Literal" && "regex" in arg ?
arg.regex.pattern :
arg.value;
// We use the safe-regex package to detect whether or not regex is safe!
if (!safeRegex(pattern)) {
sourceFile.warnings.push(generateWarning("unsafe-regex", { value: pattern, location: node.loc }));
}
}
function isRegexConstructor(node) {
if (node.type !== "NewExpression" || node.callee.type !== "Identifier") {
return false;
}
return node.callee.name === "RegExp";
}
export default {
name: "isRegexObject",
validateNode,
main,
breakOnMatch: false
};
//# sourceMappingURL=isRegexObject.js.map