This commit is contained in:
cheney
2026-08-07 09:49:26 +08:00
parent ac8a4b8cd2
commit dbe04b7da3
16 changed files with 795 additions and 13 deletions
+149
View File
@@ -0,0 +1,149 @@
#!/usr/bin/env node
// OTA 升级包生成脚本 (兼容 tauri-plugin-hotswap)
// 用法: node scripts/build-ota.mjs [--out <dir>] [--sequence <n>] [--min-binary <x>] [--notes <s>] [--no-sign]
// 流程:
// 1) 校验 dist/ 已构建
// 2) 生成 bundle.tar.gz (dist/ 内容)
// 3) minisign 签名 (除非 --no-sign)
// 4) 写 latest.json (manifest, 含 sequence/version/signature/bundle_size/notes/...)
// 5) 全部产物输出到 out 目录 (默认 ota-package/)
//
// minisign 安装: 见 readme "OTA 升级" 章节
import fs from 'node:fs'
import path from 'node:path'
import crypto from 'node:crypto'
import { fileURLToPath } from 'node:url'
import { spawnSync } from 'node:child_process'
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
const ROOT = path.resolve(__dirname, '..')
const args = process.argv.slice(2)
function getArg(name, def) {
const i = args.indexOf(name)
return i >= 0 && args[i + 1] ? args[i + 1] : def
}
const OUT_DIR = path.resolve(getArg('--out', 'ota-package'))
const SEQUENCE = Number(getArg('--sequence', String(Date.now()))) // 默认用时间戳做单调计数
const MIN_BINARY = getArg('--min-binary', '')
const NOTES = getArg('--notes', '')
const NO_SIGN = args.includes('--no-sign')
// minisign 私钥路径 (默认读 ./ota-package/hotswap.key; 也可显式 --key)
const KEY_PATH = path.resolve(getArg('--key', path.join(OUT_DIR, 'hotswap.key')))
// 旧版 tauri.conf.json 里的 pubkey (自动同步过去, 方便用户复制)
const TAURI_CONF = path.join(ROOT, 'src-tauri', 'tauri.conf.json')
const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'))
const APP_VERSION = pkg.version || '0.0.0'
const DIST = path.join(ROOT, 'dist')
if (!fs.existsSync(path.join(DIST, 'index.html'))) {
console.error('[build-ota] 错误: dist/index.html 不存在, 请先执行 npm run build')
process.exit(1)
}
// 准备输出目录
fs.mkdirSync(OUT_DIR, { recursive: true })
// 1) 生成 bundle.tar.gz
const BUNDLE_NAME = 'iboard-ota.tar.gz'
const BUNDLE_PATH = path.join(OUT_DIR, BUNDLE_NAME)
const r = spawnSync('tar', ['-czf', BUNDLE_PATH, '-C', DIST, '.'], { stdio: 'inherit' })
if (r.status !== 0) {
console.error('[build-ota] tar 打包失败')
process.exit(1)
}
const bundleStat = fs.statSync(BUNDLE_PATH)
const bundleSha256 = crypto.createHash('sha256').update(fs.readFileSync(BUNDLE_PATH)).digest('hex')
// 2) 签名 (minisign)
let signature = ''
let pubkey = ''
if (!NO_SIGN) {
if (!fs.existsSync(KEY_PATH)) {
console.error('[build-ota] 私钥不存在:', KEY_PATH)
console.error(' 生成方法: minisign -G -W -p ota-package/hotswap.pub -s ota-package/hotswap.key')
process.exit(1)
}
// minisign -Sm <file> -s <key> [-W] 生成 detached signature
const sigArgs = ['-Sm', BUNDLE_PATH, '-s', KEY_PATH]
// 私钥无密码时不需要 -W
const sigR = spawnSync('minisign', sigArgs, { stdio: 'inherit' })
if (sigR.status !== 0) {
console.error('[build-ota] minisign 签名失败')
process.exit(1)
}
const sigPath = BUNDLE_PATH + '.minisig'
signature = fs.readFileSync(sigPath, 'utf8').trim()
// 尝试同步 pubkey 到 tauri.conf.json (如果存在)
const PUB_PATH = path.join(path.dirname(KEY_PATH), 'hotswap.pub')
if (fs.existsSync(PUB_PATH)) {
pubkey = fs.readFileSync(PUB_PATH, 'utf8').trim()
// 提取 base64 部分 (第二行)
const lines = pubkey.split(/\r?\n/)
pubkey = (lines.find((l) => l.startsWith('RWR') || l.startsWith('RWT') || l.startsWith('RWQ')) || '').trim()
}
}
// 3) 写 latest.json
const minBinary = MIN_BINARY || (() => {
// 默认从 src-tauri/tauri.conf.json 读 version
try { return JSON.parse(fs.readFileSync(TAURI_CONF, 'utf8')).version || APP_VERSION }
catch { return APP_VERSION }
})()
const manifest = {
version: APP_VERSION + '-ota',
sequence: SEQUENCE,
min_binary_version: minBinary,
bundle: BUNDLE_NAME,
bundle_size: bundleStat.size,
bundle_sha256: bundleSha256,
signature,
notes: NOTES,
pub_date: new Date().toISOString(),
mandatory: false,
// 内部用: 前端 web 模式比对 build_id
build_id: 'seq-' + SEQUENCE,
}
fs.writeFileSync(path.join(OUT_DIR, 'latest.json'), JSON.stringify(manifest, null, 2))
// 4) 提示
console.log('\n=== OTA 包生成完成 ===')
console.log('输出目录: ', OUT_DIR)
console.log('版本: ', manifest.version)
console.log('sequence: ', manifest.sequence)
console.log('bundle 大小: ', (bundleStat.size / 1024).toFixed(1) + ' KB')
console.log('bundle sha256:', bundleSha256)
console.log('签名: ', signature ? '(已生成, 写入 latest.json)' : '(未签名, --no-sign)')
if (pubkey) {
console.log('\n请将下面这一行 pubkey 写到 src-tauri/tauri.conf.json -> plugins.hotswap.pubkey:')
console.log(' ' + pubkey)
// 自动同步 (可选, 注释掉默认行为; 用户自己粘更安全)
// syncTauriConf(pubkey)
}
console.log('\n下一步: 把这两个文件发布到 OTA 存储:')
console.log(' ' + BUNDLE_NAME)
console.log(' latest.json')
console.log('并确保 server 进程环境变量 OTA_PACKAGE_DIR 指向该目录。')
// 同步 tauri.conf.json pubkey 字段 (用户首次签名后手动确认)
// 注释: 启用此函数可自动写入, 但为安全默认关闭
function syncTauriConf(pub) {
if (!fs.existsSync(TAURI_CONF)) return
try {
const txt = fs.readFileSync(TAURI_CONF, 'utf8')
const newTxt = txt.replace(
/"pubkey":\s*"[^"]*"/,
'"pubkey": "' + pub + '"'
)
if (newTxt !== txt) {
fs.writeFileSync(TAURI_CONF, newTxt)
console.log('\n[build-ota] 已同步 pubkey 到 tauri.conf.json')
}
} catch (e) {
console.warn('[build-ota] 同步 pubkey 失败:', e.message)
}
}
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env node
// 生成 minisign 密钥对 (ota-package/hotswap.{key,pub})
// 首次跑一遍: node scripts/ota-genkey.mjs
// - hotswap.key: 私钥, 不要提交, 部署时由 CI 注入 (环境变量 / secret)
// - hotswap.pub: 公钥, 写到 src-tauri/tauri.conf.json 的 plugins.hotswap.pubkey
//
// 依赖: minisign (https://jedisct1.github.io/minisign/)
// - Windows: scoop install minisign 或 choco install minisign
// - macOS: brew install minisign
// - Linux: apt install minisign
import fs from 'node:fs'
import path from 'node:path'
import { spawnSync } from 'node:child_process'
import { fileURLToPath } from 'node:url'
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
const ROOT = path.resolve(__dirname, '..')
const OUT_DIR = path.join(ROOT, 'ota-package')
fs.mkdirSync(OUT_DIR, { recursive: true })
const KEY = path.join(OUT_DIR, 'hotswap.key')
const PUB = path.join(OUT_DIR, 'hotswap.pub')
if (fs.existsSync(KEY) || fs.existsSync(PUB)) {
console.error('[ota-genkey] 已存在密钥, 如需重新生成请先删除 ota-package/hotswap.{key,pub}')
console.error(' 注意: 重新生成密钥会导致旧 bundle 无法被客户端验证, 慎用!')
process.exit(1)
}
// 检查 minisign 是否存在
const which = spawnSync('minisign', ['-v'], { stdio: 'pipe' })
if (which.status !== 0 && which.error) {
console.error('[ota-genkey] 未找到 minisign 命令, 请先安装:')
console.error(' Windows: scoop install minisign')
console.error(' macOS: brew install minisign')
console.error(' Linux: apt install minisign')
process.exit(1)
}
// -G: 生成 -W: 无密码 -p: 公钥输出 -s: 私钥输出
const r = spawnSync('minisign', ['-G', '-W', '-p', PUB, '-s', KEY], { stdio: 'inherit' })
if (r.status !== 0) {
console.error('[ota-genkey] minisign 生成失败')
process.exit(1)
}
console.log('\n=== 密钥生成完成 ===')
console.log('私钥: ' + KEY + ' (不要提交到 git!)')
console.log('公钥: ' + PUB)
const pubText = fs.readFileSync(PUB, 'utf8')
const lines = pubText.split(/\r?\n/)
const pubB64 = lines.find((l) => l.startsWith('RWR') || l.startsWith('RWT') || l.startsWith('RWQ'))
console.log('\n请把下面这一行 pubkey 写到 src-tauri/tauri.conf.json -> plugins.hotswap.pubkey:')
console.log(' ' + (pubB64 || '').trim())
// 自动写 .gitignore 提醒
const gitignore = path.join(ROOT, '.gitignore')
if (fs.existsSync(gitignore)) {
let txt = fs.readFileSync(gitignore, 'utf8')
if (!txt.includes('ota-package/hotswap.key')) {
if (!txt.endsWith('\n')) txt += '\n'
txt += '\n# OTA 升级私钥, 不要提交\nota-package/hotswap.key\n'
fs.writeFileSync(gitignore, txt)
console.log('\n[ota-genkey] 已把 ota-package/hotswap.key 加入 .gitignore')
}
}