Skip to content

更新器:保持应用新鲜

现代用户期望软件能够随着时间推移而改进,而无需手动下载安装程序。Tauri 内置了一个安全可靠的无线(Over-the-Air, OTA)更新系统,负责检查更新、验证签名和安装更新。

首先,你需要将更新器插件添加到你的项目(cargo add tauri-plugin-updater)并在你的 Rust 代码中初始化它。然后,配置 tauri.conf.json 来告诉应用程序在哪里查找更新。

tauri.conf.json
{
"plugins": {
"updater": {
"endpoints": [
"https://releases.myapp.com/latest.json"
],
"pubkey": "YOUR_PUBLIC_KEY_HERE"
}
}
}

Tauri 通过要求所有更新都进行数字签名(digitally signed)来强制执行安全性。这可以防止服务器被欺骗以提供恶意软件的“中间人”(Man-in-the-Middle)攻击。

你可以使用 Tauri CLI 生成密钥对:

Terminal window
tauri signer generate -w ~/.tauri/myapp.key

这将输出一个公钥(public key)(可以安全共享,用于配置)和一个私钥(private key)(务必保密!)。在你的构建过程(build process)(例如 GitHub Actions)中,你必须通过环境变量(environment variables)提供私钥:TAURI_SIGNING_PRIVATE_KEY 和 TAURI_SIGNING_PRIVATE_KEY_PASSWORD。

你的配置中定义的端点(endpoint)会查找一个包含版本信息、发布说明和针对不同平台(Windows、macOS、Linux)的下载链接的 JSON 文件。当你运行 tauri build 时,CLI 不仅会生成安装程序(installers),还会生成 .sig(签名)文件和一个 JSON 清单文件(manifest)。

你可以在任何地方托管这些文件:Amazon S3、GitHub Pages 或自定义 VPS。JSON 中的 URL 结构必须指向你的二进制文件(binaries)的实际位置。

最后,你需要告诉应用程序何时检查更新。这通常在应用程序启动时在前端完成。

import { check } from '@tauri-apps/plugin-updater';
import { relaunch } from '@tauri-apps/plugin-process';
async function checkForAppUpdates() {
const update = await check();
if (update) {
console.log(`found update ${update.version} from ${update.date} with notes ${update.body}`);
// 发现更新 ${update.version},发布于 ${update.date},发布说明:${update.body}
let downloaded = 0;
let contentLength = 0;
// Download and install the update
// 下载并安装更新
await update.downloadAndInstall((event) => {
switch (event.event) {
case 'Started':
contentLength = event.data.contentLength;
console.log(`started downloading ${contentLength} bytes`);
// 开始下载 ${contentLength} 字节
break;
case 'Progress':
downloaded += event.data.chunkLength;
console.log(`downloaded ${downloaded} from ${contentLength}`);
// 已下载 ${downloaded} / ${contentLength}
break;
case 'Finished':
console.log('download finished');
// 下载完成
break;
}
});
// Restart the app to apply changes
// 重启应用程序以应用更改
await relaunch();
}
}