Files
bruno/packages/bruno-js/src/sandbox/quickjs/shims/local-module.js
Anoop M D 753a576c3c Feat/safe mode quickjs (#2848)
Safe Mode Sandbox using QuickJS
Co-authored-by: Anoop M D <anoop.md1421@gmail.com>
Co-authored-by: lohit <lohit.jiddimani@gmail.com>
2024-08-21 12:52:49 +05:30

32 lines
1.1 KiB
JavaScript

const path = require('path');
const fs = require('fs');
const { marshallToVm } = require('../utils');
const addLocalModuleLoaderShimToContext = (vm, collectionPath) => {
let loadLocalModuleHandle = vm.newFunction('loadLocalModule', function (module) {
const filename = vm.dump(module);
// Check if the filename has an extension
const hasExtension = path.extname(filename) !== '';
const resolvedFilename = hasExtension ? filename : `${filename}.js`;
// Resolve the file path and check if it's within the collectionPath
const filePath = path.resolve(collectionPath, resolvedFilename);
const relativePath = path.relative(collectionPath, filePath);
// Ensure the resolved file path is inside the collectionPath
if (relativePath.startsWith('..') || path.isAbsolute(relativePath)) {
throw new Error('Access to files outside of the collectionPath is not allowed.');
}
let code = fs.readFileSync(filePath).toString();
return marshallToVm(code, vm);
});
vm.setProp(vm.global, '__brunoLoadLocalModule', loadLocalModuleHandle);
loadLocalModuleHandle.dispose();
};
module.exports = addLocalModuleLoaderShimToContext;