@aikidosec/firewall
Version:
Zen by Aikido is an embedded Web Application Firewall that autonomously protects Node.js apps against common and critical attacks
74 lines (73 loc) • 2.68 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.isMainJsFile = isMainJsFile;
const path_1 = require("path");
const isPlainObject_1 = require("../../helpers/isPlainObject");
/**
* This function checks if the required file is the main file of the package.
* It does this by checking the package.json file of the package.
*/
function isMainJsFile(pathInfo, requireId, filename, packageJson) {
// If the name of the package is the same as the requireId (the argument passed to require), then it is the main file
if (pathInfo.name === requireId) {
return true;
}
// Check package.json main field
if (typeof packageJson.main === "string" &&
(0, path_1.resolve)(pathInfo.base, packageJson.main) === filename) {
return true;
}
// Defaults to index.js if main field is not set
if (packageJson.main === undefined) {
if ((0, path_1.resolve)(pathInfo.base, "index.js") === filename) {
return true;
}
}
// Check exports field
return doesMainExportMatchFilename(packageJson.exports, pathInfo.base, filename);
}
const allowedExportConditions = [
"default",
"node",
"node-addons",
"require",
];
/**
* This function checks if the main package exported js file is the same as the passed file.
*/
function doesMainExportMatchFilename(exportsField, base, filename) {
if (!exportsField) {
return false;
}
if (typeof exportsField === "string") {
if ((0, path_1.resolve)(base, exportsField) === filename) {
return true;
}
}
if (Array.isArray(exportsField)) {
for (const value of exportsField) {
if (typeof value === "string" && (0, path_1.resolve)(base, value) === filename) {
return true;
}
}
}
else if ((0, isPlainObject_1.isPlainObject)(exportsField)) {
for (const [key, value] of Object.entries(exportsField)) {
if ([".", "./", "./index.js"].includes(key)) {
if (typeof value === "string" && (0, path_1.resolve)(base, value) === filename) {
return true;
}
if ((0, isPlainObject_1.isPlainObject)(value)) {
for (const condition of allowedExportConditions) {
if (condition in value &&
typeof value[condition] === "string" &&
(0, path_1.resolve)(base, value[condition]) === filename) {
return true;
}
}
}
}
}
}
return false;
}