fix: fixed_sandbox_bug

This commit is contained in:
ariesly 2021-06-25 11:57:19 +08:00
parent 8e1f6546d5
commit 37f7e55a07
4 changed files with 26 additions and 8 deletions

View File

@ -207,6 +207,6 @@ module.exports = function() {
// mock 脚本
let script = data.mock_script;
yapi.commons.handleMockScript(script, context);
await yapi.commons.handleMockScript(script, context);
});
};

View File

@ -74,16 +74,17 @@
"node-schedule": "^1.3.2",
"nodemailer": "4.0.1",
"os": "0.1.1",
"qs": "^6.7.0",
"request": "2.81.0",
"safeify": "^5.0.5",
"sha.js": "2.4.9",
"sha1": "1.1.1",
"swagger-client": "^3.5.1",
"tslib": "1.8.0",
"underscore": "1.8.3",
"url": "0.11.0",
"yapi-plugin-qsso": "^1.1.0",
"qs": "^6.7.0",
"vm2": "^3.8.4"
"vm2": "^3.8.4",
"yapi-plugin-qsso": "^1.1.0"
},
"devDependencies": {
"antd": "3.2.2",

View File

@ -13,6 +13,7 @@ const json5 = require('json5');
const _ = require('underscore');
const Ajv = require('ajv');
const Mock = require('mockjs');
const sandboxFn = require('./sandbox')
@ -576,7 +577,7 @@ ${JSON.stringify(schema, null, 2)}`)
// script 是断言
if (globalScript) {
logs.push('执行脚本:' + globalScript)
result = yapi.commons.sandbox(context, globalScript);
result = await sandboxFn(context, globalScript);
}
}
@ -585,7 +586,7 @@ ${JSON.stringify(schema, null, 2)}`)
// script 是断言
if (script) {
logs.push('执行脚本:' + script)
result = yapi.commons.sandbox(context, script);
result = await sandboxFn(context, script);
}
result.logs = logs;
return yapi.commons.resReturn(result);
@ -613,7 +614,7 @@ exports.getUserdata = async function getUserdata(uid, role) {
};
// 处理mockJs脚本
exports.handleMockScript = function (script, context) {
exports.handleMockScript = async function (script, context) {
let sandbox = {
header: context.ctx.header,
query: context.ctx.query,
@ -632,7 +633,7 @@ exports.handleMockScript = function (script, context) {
var parts = Cookie.split('=');
sandbox.cookie[parts[0].trim()] = (parts[1] || '').trim();
});
sandbox = yapi.commons.sandbox(sandbox, script);
sandbox = await sandboxFn(sandbox, script);
sandbox.delay = isNaN(sandbox.delay) ? 0 : +sandbox.delay;
context.mockJson = sandbox.mockJson;

16
server/utils/sandbox.js Normal file
View File

@ -0,0 +1,16 @@
const Safeify = require('safeify').default;
module.exports = async function sandboxFn(context, script) {
// 创建 safeify 实例
const safeVm = new Safeify({
timeout: 3000,
asyncTimeout: 60000
})
// 执行动态代码
const result = await safeVm.run(script, context)
// 释放资源
safeVm.destroy()
return result
}