命令作用域
作用域(Scope)是一种定义 Tauri 命令允许或禁止行为的细粒度方式。
作用域分为 allow(允许)和 deny(禁止)两类,其中 deny 的优先级始终高于 allow。
作用域类型必须是任何可被 serde 序列化的类型。这些类型通常是特定于插件的。对于在 Tauri 应用中实现的受限命令,其作用域类型需要在应用中定义,并在命令实现中强制执行。
例如,Fs(文件系统)插件允许你使用作用域来允许或禁止对特定目录和文件的访问,而 http 插件则使用作用域来过滤允许访问的 URL。
作用域会被传递给命令,并由命令本身负责处理或进行妥善的强制执行。
以下示例摘自 Fs 插件的权限配置。
该插件中所有命令的作用域类型均为字符串,其中包含一个 glob 兼容的路径。
[[permission]]identifier = "scope-applocaldata-recursive"description = '''This scope recursive access to the complete `$APPLOCALDATA` folder,including sub directories and files.'''
[[permission.scope.allow]]path = "$APPLOCALDATA/**"[[permission]]identifier = "deny-webview-data-linux"description = '''This denies read access to the`$APPLOCALDATA` folder on linux as the webview data andconfiguration values are stored here.Allowing access can lead to sensitive information disclosure andshould be well considered.'''platforms = ["linux"]
[[scope.deny]]path = "$APPLOCALDATA/**"
[[permission]]identifier = "deny-webview-data-windows"description = '''This denies read access to the`$APPLOCALDATA/EBWebView` folder on windows as the webview data andconfiguration values are stored here.Allowing access can lead to sensitive information disclosure andshould be well considered.'''platforms = ["windows"]
[[scope.deny]]path = "$APPLOCALDATA/EBWebView/**"上述作用域可用于允许访问 APPLOCALDATA 文件夹,同时禁止访问 Windows 上包含敏感 webview 数据的 EBWebView 子文件夹。
这些作用域可以合并为一个集合,从而减少重复配置,使应用配置对于查阅者来说更易于理解。
首先将禁止作用域合并为 deny-default
[[set]]identifier = "deny-default"description = '''This denies access to dangerous Tauri relevant files andfolders by default.'''permissions = ["deny-webview-data-linux", "deny-webview-data-windows"]随后合并禁止和允许作用域
[[set]]identifier = "scope-applocaldata-reasonable"description = '''This scope set allows access to the `APPLOCALDATA` folder andsubfolders except for linux,while it denies access to dangerous Tauri relevant files andfolders by default on windows.'''permissions = ["scope-applocaldata-recursive", "deny-default"]这些作用域既可以通过扩展插件的全局作用域用于所有命令,也可以在权限中结合已启用的命令仅用于选定的命令。
针对 APPLOCALDATA 中文件的合理只读文件访问权限配置如下所示
[[set]]identifier = "read-files-applocaldata"description = '''This set allows file read access to the `APPLOCALDATA` folder andsubfolders except for linux,while it denies access to dangerous Tauri relevant files andfolders by default on windows.'''permissions = ["scope-applocaldata-reasonable", "allow-read-file"]这些示例仅强调了作用域功能本身。每位插件或应用开发者都需要根据其具体用例,考虑作用域的合理组合。
© 2026 Tauri 贡献者。CC-BY / MIT