Skip to content

安全配置

Tauri 的安全重点是限制 WebView 能调用的核心能力。前端越接近普通网页,风险越低。

Capabilities

权限写在 src-tauri/capabilities/

json
{
  "$schema": "../gen/schemas/desktop-schema.json",
  "identifier": "main-capability",
  "description": "Capability for the main window",
  "windows": ["main"],
  "permissions": [
    "core:default",
    "core:window:allow-set-title",
    "fs:default"
  ]
}

要点:

  • 按窗口授予权限,不给全局放开。
  • 插件能力也要显式加入 permissions
  • capabilities 目录默认全部启用;一旦在 tauri.conf.json 里显式列出,就只启用列出的项。
  • 可用 platforms 区分桌面和移动权限。

默认情况下,自行注册的 Command 对所有窗口可用。需要收紧时,在 build.rs 里通过 AppManifest::commands 声明允许列表。

CSP

tauri.conf.json 中配置 CSP,构建时会自动补上本地脚本哈希和 nonce:

json
{
  "app": {
    "security": {
      "csp": {
        "default-src": "'self' customprotocol: asset:",
        "connect-src": "ipc: http://ipc.localhost",
        "img-src": "'self' asset: http://asset.localhost blob: data:",
        "style-src": "'unsafe-inline' 'self'"
      }
    }
  }
}

只允许加载受控来源。未配置 CSP 时,这项保护不会生效。

远程页面

打包后的本地资源才能默认调用 Tauri API。如果必须给远程页面开放部分能力,需要在 capability 中声明 remote.urls。生产环境优先加载本地构建产物。

开发环境通过 build.devUrl 连接本地开发服务器:

json
{
  "build": {
    "beforeDevCommand": "pnpm dev",
    "devUrl": "http://localhost:5173",
    "beforeBuildCommand": "pnpm build",
    "frontendDist": "../dist"
  }
}

边界

Capabilities 能缩小前端被攻破后的影响范围,不能保护:

  • 不可信或过于宽松的 Rust 代码
  • 权限 scope 配得过宽
  • 系统 WebView 未修复漏洞
  • 供应链或开发机被入侵

密钥、签名、数据库访问放在核心进程,并对 Command 参数做校验。

Checklist

  • [ ] 每个窗口只授予最小权限
  • [ ] 插件权限按需加入 capability
  • [ ] 配置尽量严格的 CSP
  • [ ] 不在生产环境加载不受控远程页面
  • [ ] 自定义 Command 校验参数和路径范围
  • [ ] 敏感状态保存在核心进程

基于 MIT 许可发布