Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

能否添加禁用 evalFunction 这类动态执行代码的选项 #87

Open
lyswhut opened this issue Nov 24, 2024 · 6 comments
Open

Comments

@lyswhut
Copy link

lyswhut commented Nov 24, 2024

你好,请问能否添加禁用 evalFunction 这类动态执行代码的选项,类似 Node.js vm.createContext 选项中的 codeGeneration.strings

https://nodejs.org/docs/v22.11.0/api/vm.html#vmcreatecontextcontextobject-options

image

@HarlonWang
Copy link
Owner

你可以在执行代码前,前置执行一段代码,来代理掉 eval Function,类似下面:
image

@lyswhut
Copy link
Author

lyswhut commented Dec 6, 2024

现在我确实尝试这样做:

globalThis.eval = function() {
  throw new Error('eval is not available')
}
const proxyFunctionConstructor = new Proxy(Function.prototype.constructor, {
  apply() {
    throw new Error('Dynamic code execution is not allowed.')
  },
  construct() {
    throw new Error('Dynamic code execution is not allowed.')
  },
})
Object.defineProperty(Function.prototype, 'constructor', {
  value: proxyFunctionConstructor,
  writable: false,
  configurable: false,
  enumerable: false,
})
globalThis.Function = proxyFunctionConstructor

但这样的做法没完全搞清楚还有没有其他方式绕过,所以想请教一下能不能在底层禁用,如果加起来麻烦那就继续用这种方式先 :)

@HarlonWang
Copy link
Owner

好的,下个版本我会支持

@HarlonWang
Copy link
Owner

会透出这些能力的禁用选项
image

@lyswhut
Copy link
Author

lyswhut commented Dec 9, 2024

我想了解下,eval 选项会禁用 Function 的动态执行能力吗?
可以试试以下用例:

try {
  console.log(eval('2 + 3'))
} catch (err) {
  console.log(err)
}
try {
  const add2 = new Function('a', 'b', 'return a + b')
  console.log(add2(2, 3))
} catch (err) {
  console.log(err)
}
try {
  const Fn = function () {}.constructor
  const add = new Fn('a', 'b', 'return a + b')
  console.log(add(2, 3))
} catch (err) {
  console.log(err)
}

@HarlonWang
Copy link
Owner

好的,有空我试试

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants