configuring-tauri-scopes

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Tauri Command Scopes

Tauri 命令范围

This skill covers configuring scopes in Tauri v2 applications to control fine-grained access to commands and resources.
本技能涵盖在Tauri v2应用中配置范围,以对命令和资源进行细粒度的访问控制。

What Are Scopes?

什么是命令范围?

Scopes are a granular authorization mechanism in Tauri that controls what specific operations a command can perform. They function as fine-grained permission boundaries beyond basic command access.
命令范围是Tauri中的一种细粒度授权机制,用于控制命令可以执行的具体操作。它们是基础命令访问权限之外的细粒度权限边界。

Key Characteristics

核心特性

  • Allow scopes: Explicitly permit certain operations
  • Deny scopes: Explicitly restrict certain operations
  • Deny takes precedence: When both exist, deny rules always win
  • Command responsibility: The command implementation must validate and enforce scope restrictions
  • 允许范围:明确允许某些操作
  • 拒绝范围:明确限制某些操作
  • 拒绝优先:当同时存在允许和拒绝规则时,拒绝规则始终优先
  • 命令责任:命令实现必须验证并执行范围限制

How Scopes Work

命令范围的工作原理

The scope is passed to the command during execution. The command implementation is responsible for validating against the scope and enforcing restrictions. This means developers must carefully implement scope validation to prevent bypasses.
范围会在命令执行时传递给命令。命令实现负责验证范围并执行限制。这意味着开发者必须仔细实现范围验证,以防止绕过。

Scope Configuration Location

范围配置位置

Scopes are configured in capability files located at:
  • src-tauri/capabilities/default.json
    (primary)
  • src-tauri/capabilities/*.json
    (additional capability files)
范围在以下路径的权限文件中配置:
  • src-tauri/capabilities/default.json
    (主配置文件)
  • src-tauri/capabilities/*.json
    (其他权限文件)

Filesystem Scopes

文件系统范围

The filesystem plugin uses glob-compatible path patterns to define accessible paths.
文件系统插件使用兼容glob的路径模式来定义可访问路径。

Basic Filesystem Scope Configuration

基础文件系统范围配置

json
{
  "$schema": "../gen/schemas/desktop-schema.json",
  "identifier": "default",
  "description": "Default capability for the application",
  "windows": ["main"],
  "permissions": [
    {
      "identifier": "fs:scope",
      "allow": [{ "path": "$APPDATA" }, { "path": "$APPDATA/**" }]
    }
  ]
}
json
{
  "$schema": "../gen/schemas/desktop-schema.json",
  "identifier": "default",
  "description": "Default capability for the application",
  "windows": ["main"],
  "permissions": [
    {
      "identifier": "fs:scope",
      "allow": [{ "path": "$APPDATA" }, { "path": "$APPDATA/**" }]
    }
  ]
}

Command-Specific Scopes

命令特定范围

Restrict individual filesystem operations rather than global access:
json
{
  "permissions": [
    {
      "identifier": "fs:allow-read-text-file",
      "allow": [{ "path": "$DOCUMENT/**" }]
    },
    {
      "identifier": "fs:allow-write-text-file",
      "allow": [{ "path": "$HOME/notes.txt" }]
    }
  ]
}
限制单个文件系统操作而非全局访问:
json
{
  "permissions": [
    {
      "identifier": "fs:allow-read-text-file",
      "allow": [{ "path": "$DOCUMENT/**" }]
    },
    {
      "identifier": "fs:allow-write-text-file",
      "allow": [{ "path": "$HOME/notes.txt" }]
    }
  ]
}

Combined Allow and Deny Scopes

允许与拒绝范围组合

json
{
  "permissions": [
    {
      "identifier": "fs:allow-rename",
      "allow": [{ "path": "$HOME/**" }],
      "deny": [{ "path": "$HOME/.config/**" }]
    }
  ]
}
json
{
  "permissions": [
    {
      "identifier": "fs:allow-rename",
      "allow": [{ "path": "$HOME/**" }],
      "deny": [{ "path": "$HOME/.config/**" }]
    }
  ]
}

Available Path Variables

可用路径变量

Tauri provides runtime-injected variables for common system directories:
VariableDescription
$APPCONFIG
Application config directory
$APPDATA
Application data directory
$APPLOCALDATA
Application local data directory
$APPCACHE
Application cache directory
$APPLOG
Application log directory
$AUDIO
User audio directory
$CACHE
System cache directory
$CONFIG
System config directory
$DATA
System data directory
$DESKTOP
User desktop directory
$DOCUMENT
User documents directory
$DOWNLOAD
User downloads directory
$EXE
Application executable directory
$HOME
User home directory
$PICTURE
User pictures directory
$PUBLIC
Public directory
$RESOURCE
Application resource directory
$TEMP
Temporary directory
$VIDEO
User video directory
Tauri为常见系统目录提供运行时注入的变量:
变量描述
$APPCONFIG
应用配置目录
$APPDATA
应用数据目录
$APPLOCALDATA
应用本地数据目录
$APPCACHE
应用缓存目录
$APPLOG
应用日志目录
$AUDIO
用户音频目录
$CACHE
系统缓存目录
$CONFIG
系统配置目录
$DATA
系统数据目录
$DESKTOP
用户桌面目录
$DOCUMENT
用户文档目录
$DOWNLOAD
用户下载目录
$EXE
应用可执行文件目录
$HOME
用户主目录
$PICTURE
用户图片目录
$PUBLIC
公共目录
$RESOURCE
应用资源目录
$TEMP
临时目录
$VIDEO
用户视频目录

Scope Patterns

范围模式

Scopes support glob patterns for flexible path matching.
范围支持glob模式以实现灵活的路径匹配。

Pattern Examples

模式示例

json
{
  "permissions": [
    {
      "identifier": "fs:scope",
      "allow": [
        { "path": "$APPDATA/databases/*" },
        { "path": "$DOCUMENT/**/*.txt" },
        { "path": "$HOME/project/src/**" }
      ],
      "deny": [
        { "path": "$HOME/.ssh/**" },
        { "path": "$HOME/.gnupg/**" }
      ]
    }
  ]
}
json
{
  "permissions": [
    {
      "identifier": "fs:scope",
      "allow": [
        { "path": "$APPDATA/databases/*" },
        { "path": "$DOCUMENT/**/*.txt" },
        { "path": "$HOME/project/src/**" }
      ],
      "deny": [
        { "path": "$HOME/.ssh/**" },
        { "path": "$HOME/.gnupg/**" }
      ]
    }
  ]
}

Pattern Syntax

模式语法

PatternMeaning
*
Matches any characters except path separator
**
Matches any characters including path separator (recursive)
?
Matches a single character
[abc]
Matches any character in brackets
模式含义
*
匹配除路径分隔符外的任意字符
**
匹配包括路径分隔符在内的任意字符(递归匹配)
?
匹配单个字符
[abc]
匹配括号内的任意字符

Path Traversal Prevention

路径遍历防护

Tauri prevents path traversal attacks. These paths are NOT allowed:
  • /usr/path/to/../file
  • ../path/to/file
Tauri可防止路径遍历攻击。以下路径是不被允许的:
  • /usr/path/to/../file
  • ../path/to/file

HTTP Plugin Scopes

HTTP插件范围

The HTTP plugin uses URL patterns to control network access.
HTTP插件使用URL模式来控制网络访问。

URL Scope Configuration

URL范围配置

json
{
  "permissions": [
    {
      "identifier": "http:default",
      "allow": [{ "url": "https://*.tauri.app" }],
      "deny": [{ "url": "https://private.tauri.app" }]
    }
  ]
}
json
{
  "permissions": [
    {
      "identifier": "http:default",
      "allow": [{ "url": "https://*.tauri.app" }],
      "deny": [{ "url": "https://private.tauri.app" }]
    }
  ]
}

URL Pattern Examples

URL模式示例

json
{
  "permissions": [
    {
      "identifier": "http:default",
      "allow": [
        { "url": "https://api.example.com/*" },
        { "url": "https://*.cdn.example.com/**" }
      ]
    }
  ]
}
json
{
  "permissions": [
    {
      "identifier": "http:default",
      "allow": [
        { "url": "https://api.example.com/*" },
        { "url": "https://*.cdn.example.com/**" }
      ]
    }
  ]
}

Defining Custom Permissions with Scopes (TOML)

使用范围定义自定义权限(TOML)

For plugins or custom commands, define permissions in TOML files.
对于插件或自定义命令,可在TOML文件中定义权限。

Basic Permission with Scope

带范围的基础权限

toml
undefined
toml
undefined

permissions/my-permission.toml

permissions/my-permission.toml

[[permission]] identifier = "scope-appdata-recursive" description = "Recursive access to APPDATA folder"
[[permission.scope.allow]] path = "$APPDATA/**"
undefined
[[permission]] identifier = "scope-appdata-recursive" description = "Recursive access to APPDATA folder"
[[permission.scope.allow]] path = "$APPDATA/**"
undefined

Permission with Deny Scope

带拒绝范围的权限

toml
[[permission]]
identifier = "deny-sensitive-data"
description = "Denies access to sensitive directories"
platforms = ["linux", "macos"]

[[permission.scope.deny]]
path = "$HOME/.ssh/**"

[[permission.scope.deny]]
path = "$HOME/.gnupg/**"
toml
[[permission]]
identifier = "deny-sensitive-data"
description = "Denies access to sensitive directories"
platforms = ["linux", "macos"]

[[permission.scope.deny]]
path = "$HOME/.ssh/**"

[[permission.scope.deny]]
path = "$HOME/.gnupg/**"

Permission Sets

权限集合

Combine permissions into reusable sets:
toml
[[set]]
identifier = "safe-appdata-access"
description = "Allows APPDATA access while denying sensitive folders"
permissions = ["scope-appdata-recursive", "deny-sensitive-data"]
将权限组合为可复用的集合:
toml
[[set]]
identifier = "safe-appdata-access"
description = "Allows APPDATA access while denying sensitive folders"
permissions = ["scope-appdata-recursive", "deny-sensitive-data"]

Dynamic Scopes (Runtime Management)

动态范围(运行时管理)

Tauri allows runtime scope modification using the
FsExt
trait from Rust.
Tauri允许使用Rust中的
FsExt
trait在运行时修改范围。

Basic Runtime Scope Expansion

基础运行时范围扩展

rust
use tauri_plugin_fs::FsExt;

pub fn run() {
    tauri::Builder::default()
        .plugin(tauri_plugin_fs::init())
        .setup(|app| {
            let scope = app.fs_scope();
            // Allow a specific directory (non-recursive)
            scope.allow_directory("/path/to/directory", false)?;
            // Check what's currently allowed
            dbg!(scope.allowed());
            Ok(())
        })
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
rust
use tauri_plugin_fs::FsExt;

pub fn run() {
    tauri::Builder::default()
        .plugin(tauri_plugin_fs::init())
        .setup(|app| {
            let scope = app.fs_scope();
            // Allow a specific directory (non-recursive)
            scope.allow_directory("/path/to/directory", false)?;
            // Check what's currently allowed
            dbg!(scope.allowed());
            Ok(())
        })
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

Tauri Command for Scope Expansion

用于范围扩展的Tauri命令

rust
use tauri_plugin_fs::FsExt;

#[tauri::command]
fn expand_scope(
    app_handle: tauri::AppHandle,
    folder_path: std::path::PathBuf
) -> Result<(), String> {
    // Verify path before expanding scope
    if !folder_path.exists() {
        return Err("Path does not exist".to_string());
    }

    // true = allow inner directories recursively
    app_handle
        .fs_scope()
        .allow_directory(&folder_path, true)
        .map_err(|err| err.to_string())
}
rust
use tauri_plugin_fs::FsExt;

#[tauri::command]
fn expand_scope(
    app_handle: tauri::AppHandle,
    folder_path: std::path::PathBuf
) -> Result<(), String> {
    // Verify path before expanding scope
    if !folder_path.exists() {
        return Err("Path does not exist".to_string());
    }

    // true = allow inner directories recursively
    app_handle
        .fs_scope()
        .allow_directory(&folder_path, true)
        .map_err(|err| err.to_string())
}

Allow Specific File

允许特定文件

rust
#[tauri::command]
fn allow_file(
    app_handle: tauri::AppHandle,
    file_path: std::path::PathBuf
) -> Result<(), String> {
    app_handle
        .fs_scope()
        .allow_file(&file_path)
        .map_err(|err| err.to_string())
}
rust
#[tauri::command]
fn allow_file(
    app_handle: tauri::AppHandle,
    file_path: std::path::PathBuf
) -> Result<(), String> {
    app_handle
        .fs_scope()
        .allow_file(&file_path)
        .map_err(|err| err.to_string())
}

Security Warning

安全警告

Dynamic scope expansion should be used carefully:
  • Validate paths before expanding scope
  • Prefer static configuration when possible
  • Never expand scope based on unvalidated user input
动态范围扩展需谨慎使用:
  • 在扩展范围前验证路径
  • 尽可能优先使用静态配置
  • 切勿基于未验证的用户输入扩展范围

Remote URL Scopes (Capabilities)

远程URL范围(权限)

Control which remote URLs can access your application's commands.
json
{
  "identifier": "remote-api-access",
  "description": "Allow remote access from specific domains",
  "windows": ["main"],
  "remote": {
    "urls": ["https://*.mydomain.dev", "https://app.example.com"]
  },
  "permissions": ["core:default"]
}
控制哪些远程URL可以访问应用的命令。
json
{
  "identifier": "remote-api-access",
  "description": "Allow remote access from specific domains",
  "windows": ["main"],
  "remote": {
    "urls": ["https://*.mydomain.dev", "https://app.example.com"]
  },
  "permissions": ["core:default"]
}

Complete Capability File Example

完整权限文件示例

json
{
  "$schema": "../gen/schemas/desktop-schema.json",
  "identifier": "default",
  "description": "Default capability for desktop application",
  "windows": ["main", "settings"],
  "platforms": ["linux", "macos", "windows"],
  "permissions": [
    "core:default",
    "core:window:allow-set-title",
    {
      "identifier": "fs:default"
    },
    {
      "identifier": "fs:allow-read-text-file",
      "allow": [
        { "path": "$DOCUMENT/**/*.md" },
        { "path": "$DOCUMENT/**/*.txt" }
      ]
    },
    {
      "identifier": "fs:allow-write-text-file",
      "allow": [{ "path": "$APPDATA/notes/**" }],
      "deny": [{ "path": "$APPDATA/notes/.secret/**" }]
    },
    {
      "identifier": "http:default",
      "allow": [{ "url": "https://api.example.com/*" }]
    }
  ]
}
json
{
  "$schema": "../gen/schemas/desktop-schema.json",
  "identifier": "default",
  "description": "Default capability for desktop application",
  "windows": ["main", "settings"],
  "platforms": ["linux", "macos", "windows"],
  "permissions": [
    "core:default",
    "core:window:allow-set-title",
    {
      "identifier": "fs:default"
    },
    {
      "identifier": "fs:allow-read-text-file",
      "allow": [
        { "path": "$DOCUMENT/**/*.md" },
        { "path": "$DOCUMENT/**/*.txt" }
      ]
    },
    {
      "identifier": "fs:allow-write-text-file",
      "allow": [{ "path": "$APPDATA/notes/**" }],
      "deny": [{ "path": "$APPDATA/notes/.secret/**" }]
    },
    {
      "identifier": "http:default",
      "allow": [{ "url": "https://api.example.com/*" }]
    }
  ]
}

Security Best Practices

安全最佳实践

  1. Minimize scope: Only allow paths and URLs that are absolutely necessary
  2. Use deny rules: Explicitly block sensitive directories even within allowed paths
  3. Prefer command-specific scopes: Use
    fs:allow-read-text-file
    over global
    fs:scope
  4. Validate dynamic scopes: Always verify paths before runtime scope expansion
  5. Audit scope enforcement: Command developers must implement proper scope validation
  6. Use path variables: Prefer
    $APPDATA
    over hardcoded paths for portability
  1. 最小化范围:仅允许绝对必要的路径和URL
  2. 使用拒绝规则:即使在允许路径内,也要明确阻止敏感目录
  3. 优先使用命令特定范围:使用
    fs:allow-read-text-file
    而非全局
    fs:scope
  4. 验证动态范围:在运行时扩展范围前始终验证路径
  5. 审核范围执行:命令开发者必须实现正确的范围验证
  6. 使用路径变量:为了可移植性,优先使用
    $APPDATA
    而非硬编码路径

Common Scope Patterns

常见范围模式

Read-Only Application Data

只读应用数据

json
{
  "permissions": [
    {
      "identifier": "fs:allow-read-text-file",
      "allow": [{ "path": "$APPDATA/**" }]
    },
    {
      "identifier": "fs:allow-exists",
      "allow": [{ "path": "$APPDATA/**" }]
    }
  ]
}
json
{
  "permissions": [
    {
      "identifier": "fs:allow-read-text-file",
      "allow": [{ "path": "$APPDATA/**" }]
    },
    {
      "identifier": "fs:allow-exists",
      "allow": [{ "path": "$APPDATA/**" }]
    }
  ]
}

User Document Access

用户文档访问

json
{
  "permissions": [
    {
      "identifier": "fs:scope",
      "allow": [{ "path": "$DOCUMENT/**" }],
      "deny": [
        { "path": "$DOCUMENT/.hidden/**" },
        { "path": "$DOCUMENT/**/*.key" }
      ]
    }
  ]
}
json
{
  "permissions": [
    {
      "identifier": "fs:scope",
      "allow": [{ "path": "$DOCUMENT/**" }],
      "deny": [
        { "path": "$DOCUMENT/.hidden/**" },
        { "path": "$DOCUMENT/**/*.key" }
      ]
    }
  ]
}

API-Only HTTP Access

仅API的HTTP访问

json
{
  "permissions": [
    {
      "identifier": "http:default",
      "allow": [
        { "url": "https://api.myapp.com/v1/*" },
        { "url": "https://cdn.myapp.com/**" }
      ],
      "deny": [
        { "url": "https://api.myapp.com/v1/admin/*" }
      ]
    }
  ]
}
json
{
  "permissions": [
    {
      "identifier": "http:default",
      "allow": [
        { "url": "https://api.myapp.com/v1/*" },
        { "url": "https://cdn.myapp.com/**" }
      ],
      "deny": [
        { "url": "https://api.myapp.com/v1/admin/*" }
      ]
    }
  ]
}

Troubleshooting

故障排除

"Path not allowed on the configured scope"

"Path not allowed on the configured scope"

This error indicates the requested path is outside the configured scope. Solutions:
  1. Add the path to your capability's allow list
  2. Check for typos in path variables
  3. Verify glob patterns match the intended paths
  4. Check if a deny rule is blocking the path
该错误表示请求的路径在配置的范围之外。解决方案:
  1. 将路径添加到权限的允许列表中
  2. 检查路径变量是否有拼写错误
  3. 验证glob模式是否匹配预期路径
  4. 检查是否有拒绝规则阻止了该路径

Testing Scope Configuration

测试范围配置

Run in development mode to test permissions:
bash
pnpm tauri dev
在开发模式下运行以测试权限:
bash
pnpm tauri dev

or

or

cargo tauri dev

Permission errors will appear in the console indicating which permissions need configuration.
cargo tauri dev

权限错误会显示在控制台中,指示需要配置哪些权限。

References

参考资料