Tauri 桌面端集成

为 Tauri 2 桌面应用提供类型化 Procedure 调用桥接、系统钥匙串凭据托管与内嵌 kxed 进程管理。前端代码统一调用 createRpc({ transport: tauriTransport(..) }),无需关心请求是在本机嵌入进程执行还是转发至远端服务器,且 Bearer token 全程留在 Rust 与系统钥匙串中,绝不经 IPC 暴露给 Webview。

三种部署模式#

同一份前端与业务契约支持三种桌面端形态,仅通过 [rpc] 配置切换(放置校验见 产品规格第 4.3 节):

模式[rpc] 配置本机执行的契约身份与鉴权来源
纯本机不配置 remote全部 Procedure本机 AuthPlugin,登录后调 Desktop::set_local_credential
混合模式配 remote 加 local = ["fs."]local 前缀契约与 internal 契约周期同步远端 session.current 的本地身份快照(SnapshotPlugin)
纯远程只配 remote仅 internal 契约Rust 转发时自动附加钥匙串 Bearer token,远端统一鉴权
架构图示

desktop/ 为独立 Cargo workspace,通过 cargo xtask desktop lock 从根锁同步版本,由门禁 desktop-check 独立校验。

接入#

第 1 步:配置宿主工程依赖与构建脚本#

TOML
[dependencies]
kxed = { version = "0.0.5-alpha", features = ["procedure-client"] }
kxed-tauri = { git = "https://github.com/StringKe/kxed.git" }
tauri = "2"

[build-dependencies]
kxed-tauri = { git = "https://github.com/StringKe/kxed.git" }
tauri-build = "2"

在宿主工程的构建脚本中向 Tauri 声明桥接命令,纳入 capability 权限管控(漏声明会导致命令对所有窗口无差别开放):

Rust
fn main() {
    let manifest = tauri_build::AppManifest::new().commands(&kxed_tauri::COMMANDS);
    tauri_build::try_build(tauri_build::Attributes::new().app_manifest(manifest)).unwrap();
}

将 kxed-tauri/capabilities/kxed.json 复制到应用的 src-tauri/capabilities/ 目录。该文件仅授权主窗口 main 调用桥接命令,隔离外部网页与 loopback 子窗口。

第 2 步:启动内嵌运行时与主窗口#

Rust
use kxed::prelude::*;
use kxed_tauri::{DesktopOptions, Keychain, SnapshotPlugin};

fn main() {
    let mut context = tauri::generate_context!();
    kxed_tauri::init_tracing("info");
    kxed_tauri::install(tauri::Builder::default(), &mut context, "main")
        .expect("capabilities/kxed.json is installed")
        .plugin(kxed_tauri::single_instance("main"))
        .setup(|app| {
            let handle = app.handle().clone();
            let kxed = App::builder()
                .plugin(SnapshotPlugin::new().trust_guard(GuardName::new("user")?))
                .build();
            let keychain = Keychain::system("dev.example.desk")?;
            let options = DesktopOptions::new().login("account.login").logout("account.logout");
            tauri::async_runtime::block_on(kxed_tauri::start_embedded(kxed, &handle, keychain, options))?;
            kxed_tauri::open_page(&handle, "sd")?;
            Ok(())
        })
        .build(context)
        .expect("tauri builds")
        .run(|handle, event| {
            if let tauri::RunEvent::ExitRequested { api, .. } = &event {
                kxed_tauri::exit_requested(handle, api);
            }
        });
}

关键生命周期约定:

  • ACL 启动自检:install 启动前校验 capability 配置,若桥接命令未严格限制在主窗口名下则直接报错拒启。
  • 单实例保护:single_instance("main") 须作为首个 Tauri 插件注册,确保单进程内仅运行一个嵌入 App 并自动聚焦已有窗口。
  • 固定本地端口与目录:start_embedded 仅绑定 127.0.0.1,在 app_local_data_dir/kxed-port 持久化端口供下次启动复用(保留按 origin 存储的前端状态),Task 库默认落于同目录 tasks.sqlite。
  • 优雅停机:必须在 RunEvent::ExitRequested 中调用 kxed_tauri::exit_requested(handle, api),等待内嵌 kxed 排空任务与连接后再退出进程。
  • macOS 最低版本:使用 open_page 多窗口数据隔离要求 macOS >= 14.0,请在 tauri.conf.json 设置 bundle.macOS.minimumSystemVersion = "14.0"(参考 example/tauri.conf.json)。

第 3 步:前端调用与 CSP 配置#

执行 ./app rpc ts --target desktop 生成 kxed-rpc.ts,在前端直接调用查询、变更与流式订阅:

TypeScript
import { invoke, Channel } from '@tauri-apps/api/core'
import { createRpc, tauriTransport } from './kxed-rpc'

const rpc = createRpc({ transport: tauriTransport({ invoke, Channel }) })
await rpc.account.login({ username, password })   // 返回剥离 token 后的账户信息
for await (const tick of rpc.orders.watch({ id: 7 })) render(tick)

CSP 与 isolation pattern#

tauri.conf.json 中的安全策略字段 csp 严禁设为 null,并在 connect-src 中放行 Tauri IPC 协议(无需填写远端服务器域名,因网络请求均由 Rust 侧发出):

JSON
{
  "app": {
    "security": {
      "csp": "default-src 'self'; connect-src ipc: http://ipc.localhost; object-src 'none'; base-uri 'none'"
    }
  }
}

若打包前端引入了复杂的第三方 npm 依赖,建议同时启用 Tauri Isolation 模式(开启 Tauri 依赖自身的隔离模式开关,并在独立沙箱目录的 index.html 中挂载 window.__TAURI_ISOLATION_HOOK__):

JSON
{
  "app": {
    "security": {
      "pattern": { "use": "isolation", "options": { "dir": "../dist-isolation" } }
    }
  }
}

Livecell 窗口(sd 页面)与身份离线机制#

sd 页面#

桌面端打开内嵌或远端 Livecell 页面统一调用 kxed_tauri::open_page(&handle, "sd"),不要直接用 WebviewWindowBuilder 裸开窗口:

  • 独立窗口存储:按窗口 label 分配独立 Webview 数据目录(macOS 14+ 使用 data_store_identifier),Cookie 跨窗口互不串号,localStorage 跨重启保留。
  • 混合模式 kxed_page 句柄鉴权:混合模式下内嵌进程不装 AuthPlugin;open_page 自动签发随机 HttpOnly、SameSite=Strict 的 kxed_page Cookie,由 SnapshotPlugin 为 HTTP 与 WebSocket 注入远端身份快照(关窗即刻作废,伪造或跨窗口句柄一律返 401)。
  • 纯本机与纯远程行为:纯本机走 AuthPlugin Cookie 会话;纯远程直接导航至 Desktop::remote_page 返回的远端地址。默认情况下 sd 页面无权调用 Tauri IPC(kxed_rpc 始终只放行打包主前端)。

身份与离线#

  • 钥匙串托管凭据:登录调用 DesktopOptions::login 指定的远端契约后,Rust 拦截响应中的 token 存入系统钥匙串(macOS Keychain / Windows Credential Manager),前端只收到其余业务字段;钥匙串不可用时直接报错,绝不降级存明文文件。logout 先撤销远端再清本地。
  • 放置冲突自检:首次连通远端时拉取 /_rpc/_describe 核对契约归属,若本机前缀与远端重名或存在无归属契约,立即报错 500 rpc_placement_conflict 并清空登录态。
  • 快照续期与断网容错:混合模式下 SnapshotPlugin::trust_guard 采用远端快照的角色与权限(与 AuthPlugin 二选一),快照在 idle_timeout(默认 30 分钟)内有效。后台每半个周期执行 Desktop::recheck:遇网络闪断改为 1/8 周期重试并保留未到期本机快照;收到远端 401 则立即清除本机快照与钥匙串凭据。离线期间转发远端的请求立即返回 503 unavailable(reason = "offline"),不隐式排队重发变更。

IPC 命令、流控与来源核对#

Tauri 命令参数行为与返回语义
kxed_rpcname、input、callId、idempotencyKey、onFrame普通调用直接 resolve/reject;流式调用通过 Channel 推送 item、error、done 帧(缺 onFrame 返 400 rpc_channel_required)
kxed_rpc_cancelcallId置位取消令牌(前端 AbortSignal 自动触发):流停止下发,在途非流式调用在下一个 await 点中止并以 499 rpc_cancelled 结束
kxed_rpc_ackcallId、n归还 n 帧流控窗口(前端每消费 32 帧自动发送一次)

运行期防护细节:

  • 双重来源核对:每次调用核验窗口 label 等于 main_label 且页面 origin 为打包前端(或显式登记的 dev_origin),否则返回 403 forbidden。窗口刷新、导航或关闭时自动取消该窗口名下全部在途调用。
  • 256 帧背压窗口与身份实时失效:每个流维护 256 帧未确认上限,满窗挂起生产者,订阅流连续 30 秒无确认则报 topic_lagged 关闭;本机流复用 GuardedStream,登出或快照过期 1 秒内推送 authentication_expired 终止流。
  • 幂等键与本机配额:idempotencyKey 原样透传至本机流水线或远端 Idempotency-Key 头(非法 ASCII 返 400 task_invalid_idempotency_key);本机契约的 rate_limit 与 recent_auth 照常生效。

发布与签名#

kxed-tauri 作为纯 Rust 库不读取也不存储开发者证书,应用安装包由发布方通过 Tauri Bundler 签名与公证(macOS 配置 APPLE_CERTIFICATE、APPLE_SIGNING_IDENTITY 等环境变量,Windows 配置 bundle.windows.signCommand)。

内嵌 kxed 与 WKWebView 完全兼容 macOS Hardened Runtime,无需开启 allow-jit 或 disable-library-validation 等高危 entitlement。

验证范围与外部条件#

  • 自动化验证覆盖:desktop/kxed-tauri/tests/ipc 覆盖三种部署、断网复查、流背压、取消与页面句柄隔离;cargo xtask desktop example 在启用 Hardened Runtime 签名与 CSP 核验下驱动真实 wry 窗口跑通全链路,并在 macOS 14.8、15.7 与 27 GUI 虚拟机验收通过。
未覆盖项当前保证边界升级条件
Windows 真机运行与安装包签名门禁保证 x86_64-pc-windows-msvc 目标 cargo check 通过(见 容量与限制第 3 节)接入 Windows 测试主机后补充端到端窗口验收