权限模型


🌐 Permission Model

Node.js 权限模型是一种在执行期间限制访问特定资源的机制。API 位于标志 --permission 之后,当启用时,它将限制对所有可用权限的访问。

🌐 The Node.js Permission Model is a mechanism for restricting access to specific resources during execution. The API exists behind a flag --permission which when enabled, will restrict access to all available permissions.

可用的权限由 --permission 标志记录。

🌐 The available permissions are documented by the --permission flag.

权限模型有两种操作模式:

🌐 The Permission Model has two operational modes:

  • 执行模式(使用 --permission 时的默认模式):对于任何进程没有获得权限执行的操作,都将被拒绝访问,并抛出 ERR_ACCESS_DENIED 错误。
  • 审计模式(使用 --permission-audit 时):会进行权限检查,并通过诊断通道发布违规信息,但访问不会被拒绝。执行会正常继续。该模式对于在使用强制模式部署之前了解你的应用需要哪些权限非常有用。

当使用 --permission 启动 Node.js 时,通过 fs 模块访问文件系统、访问网络、生成进程、使用 node:worker_threads、使用本地插件、使用 WASI、使用 FFI 以及启用运行时检查器的能力将受到限制(不会创建 SIGUSR1 的监听器)。

🌐 When starting Node.js with --permission, the ability to access the file system through the fs module, access the network, spawn processes, use node:worker_threads, use native addons, use WASI, use FFI, and enable the runtime inspector will be restricted (the listener for SIGUSR1 won't be created).

$ node --permission index.js

Error: Access to this API has been restricted
    at node:internal/main/run_main_module:23:47 {
  code: 'ERR_ACCESS_DENIED',
  permission: 'FileSystemRead',
  resource: '/home/user/index.js'
} 

允许访问以生成进程和创建工作线程可以分别使用 --allow-child-process 和 --allow-worker 来实现。

🌐 Allowing access to spawning a process and creating worker threads can be done using the --allow-child-process and --allow-worker respectively.

要允许网络访问,使用 --allow-net;要在使用权限模型时允许本地插件,使用 --allow-addons 标志。对于 WASI,使用 --allow-wasi 标志。对于 FFI,使用 --allow-ffi 标志。node:ffi 模块仅在支持 FFI 的构建中可用。

🌐 To allow network access, use --allow-net and for allowing native addons when using permission model, use the --allow-addons flag. For WASI, use the --allow-wasi flag. For FFI, use the --allow-ffi flag. The node:ffi module is only available in builds with FFI support.

要允许使用 OpenSSL STORE 加载器,例如从传给 crypto.createPrivateKey() 的 <URL> 中加载私钥,请使用 --allow-openssl-store 标志。这个标志赋予配置好的 OpenSSL STORE 加载器广泛的权限,它们可能会访问文件、设备、令牌或网络。加载器执行的访问不受 fs.read、fs.write 或 net 权限范围的限制。

🌐 To allow use of OpenSSL STORE loaders, for example to load a private key from a <URL> passed to crypto.createPrivateKey(), use the --allow-openssl-store flag. This flag grants broad authority to configured OpenSSL STORE loaders, which may access files, devices, tokens, or the network. Access performed by a loader is not constrained by the fs.read, fs.write, or net permission scopes.