packServer/backend/scripts/deploy/publish-desktop.cjs
liufumingren 11ebb33966 feat(extension): 插件配置集中管理 + 桌面端策略安装 + 跨网下载修复
- 后端:sys_config 存插件配置(识别前缀/生效站点/模板),平台管理员 GET/PUT /api/web/admin/extension;
  插件读取 GET /api/web/extension/config(Redis 缓存 1 小时,保存即失效)
- 前端:平台管理 → 插件配置页(只维护前缀,单号正则由服务端生成)
- 插件:改为只拉取执行(每 5 分钟 + 手动同步),移除规则编辑/试跑/导入导出;安装包地址自动取最新发布
- 桌面端:工具 → 安装/卸载谷歌插件(生成 .reg + reg import 写 HKLM 策略,读注册表验证);
  跨网下载改走云端中转;局域网探测补排障日志;自动更新按包类型取 md5Exe/sizeExe
- 发布:npm run extension:publish(crx + updates.xml)、extension:zip(商店上传包),
  nginx 对 /download/extension/updates.xml 关缓存

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-01 03:16:26 +08:00

288 lines
10 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
/**
* 桌面端正式包:构建 MSI + EXE + version.json,并单独发布到 nginx 静态目录
*
* 特点:
* - 只动桌面端产物,不重新发布后端、不重启 Egg、不跑数据库迁移;
* - 构建复用 desktop/installer/build.ps1(Production 环境,默认同时出 MSI 和 EXE);
* - 安装包上传到 deploy.config.local.cjs 里的 desktopDownloadDir(deployRoot/download/desktop);
* - version.json 上传到 desktopVersionDir(默认 deployRoot/download,nginx 对 /download/version.json 关缓存);
* - 同时刷新 front.conf 里的 /download/ 静态托管配置并 reload nginx。
*
* 为什么两个包都要传:老客户端只认 downloadUrl(MSI);新客户端优先 downloadUrlExe(EXE,
* 不依赖 Windows Installer,现场装不了 MSI 的机器靠它)。少传任何一个都会让对应客户端 404。
*
* 用法:
* npm run desktop:publish # 自动递增补丁版本并发布
* npm run desktop:publish -- --version=1.0.90
* npm run desktop:publish -- --notes="修复 xxx" --keep=10
* npm run desktop:build # 只构建,不上传(--dry-run)
* npm run desktop:publish -- --skip-nginx # 不改 nginx
*/
const fs = require('node:fs');
const path = require('node:path');
const {
ROOT,
ensureCommandAvailable,
getNowStamp,
loadDeployConfig,
quoteForBash,
refreshNginx,
runCommand,
runScp,
runSsh,
} = require('./deploy-lib.cjs');
function parseArgs(argv) {
const options = {
envName: 'production',
version: '',
notes: '',
keep: 0,
target: '',
dryRun: false,
skipNginx: false,
};
for (const item of argv) {
if (!item) continue;
if (!item.startsWith('--') && !options.envNameExplicit) {
options.envName = item;
options.envNameExplicit = true;
continue;
}
if (item === '--dry-run') {
options.dryRun = true;
} else if (item === '--skip-nginx') {
options.skipNginx = true;
} else if (item.startsWith('--version=')) {
options.version = item.slice('--version='.length).trim().replace(/^v/i, '');
} else if (item.startsWith('--notes=')) {
options.notes = item.slice('--notes='.length);
} else if (item.startsWith('--keep=')) {
options.keep = Number(item.slice('--keep='.length)) || 0;
} else if (item.startsWith('--target=')) {
options.target = item.slice('--target='.length).trim();
const allowed = [ 'Both', 'Msi', 'Exe' ];
if (!allowed.includes(options.target)) {
throw new Error(`--target 只能是 ${allowed.join(' / ')}:${options.target}`);
}
}
}
if (options.version && !/^\d+\.\d+\.\d+$/.test(options.version)) {
throw new Error(`版本号格式应为 x.y.z:${options.version}`);
}
return options;
}
function compareVersion(a, b) {
const pa = a.split('.').map(Number);
const pb = b.split('.').map(Number);
for (let i = 0; i < 3; i++) {
if (pa[i] !== pb[i]) return pa[i] - pb[i];
}
return 0;
}
/** 取本地已有安装包 / version.json 中最高的版本,并默认 +1 补丁号 */
function nextVersion(outDir) {
const versions = [];
if (fs.existsSync(outDir)) {
for (const name of fs.readdirSync(outDir)) {
const match = name.match(/^YuncangTraceSetup-(\d+\.\d+\.\d+)\.(?:msi|exe)$/);
if (match) versions.push(match[1]);
}
}
const versionFile = path.join(outDir, 'version.json');
if (fs.existsSync(versionFile)) {
try {
const data = JSON.parse(fs.readFileSync(versionFile, 'utf8'));
if (data && /^\d+\.\d+\.\d+$/.test(String(data.version || ''))) {
versions.push(String(data.version));
}
} catch (error) {
// 忽略损坏的本地 version.json
}
}
if (!versions.length) return '1.0.0';
versions.sort(compareVersion);
const [ major, minor, patch ] = versions[versions.length - 1].split('.').map(Number);
return `${major}.${minor}.${patch + 1}`;
}
/** 用 build.ps1 构建 Production 包 */
function buildDesktop(config, { version, notes, baseUrl, target }) {
const buildScript = path.resolve(ROOT, config.desktopBuildScript);
if (!fs.existsSync(buildScript)) {
throw new Error(`找不到桌面端构建脚本: ${buildScript}`);
}
const shell = process.platform === 'win32' ? 'powershell.exe' : 'pwsh';
const args = [
'-NoProfile',
'-ExecutionPolicy', 'Bypass',
'-File', buildScript,
'-Environment', 'Production',
'-Version', version,
'-ServerBaseUrl', baseUrl,
];
if (notes) {
args.push('-ReleaseNotes', notes);
}
// 只出某一种包(例如老客户端 MD5 校验有 bug 时,先发一个「只有 MSI」的版本把它们拉上来)
if (target) {
args.push('-Target', target);
}
console.log(`构建桌面端正式包: ${version}(${baseUrl})`);
runCommand(shell, args, { cwd: path.dirname(buildScript), stdio: 'inherit' });
}
/** 写 front.conf(静态 /download + /api 反代)并 reload nginx */
function main() {
const options = parseArgs(process.argv.slice(2));
const config = loadDeployConfig(options.envName);
const outDir = path.resolve(ROOT, config.desktopOutDir);
const remoteDir = config.desktopDownloadDir;
// version.json 不放安装包目录里:nginx 对 /download/version.json 单独关缓存,安装包目录走长缓存
const remoteVersionDir = config.desktopVersionDir || path.posix.dirname(String(remoteDir || ''));
const baseUrl = String(config.desktopBaseUrl || `http://${config.serverName}`).replace(/\/+$/, '');
const keep = options.keep > 0 ? options.keep : Number(config.desktopKeepVersions || 5);
const version = options.version || nextVersion(outDir);
if (!remoteDir) {
throw new Error('未配置 desktopDownloadDir(桌面安装包发布目录)。');
}
if (!remoteVersionDir || remoteVersionDir === '.' || remoteVersionDir === '/') {
throw new Error('未配置 desktopVersionDir(version.json 发布目录)。');
}
buildDesktop(config, { version, notes: options.notes, baseUrl, target: options.target });
const msiName = `YuncangTraceSetup-${version}.msi`;
const exeName = `YuncangTraceSetup-${version}.exe`;
const msiPath = path.join(outDir, msiName);
const exePath = path.join(outDir, exeName);
const versionPath = path.join(outDir, 'version.json');
if (!fs.existsSync(versionPath)) {
throw new Error(`构建完成但 version.json 不存在: ${versionPath}`);
}
const versionJson = JSON.parse(fs.readFileSync(versionPath, 'utf8'));
// version.json 里有 downloadUrlExe 就必须把 EXE 一起传上去,否则新客户端拿到的是 404
const packages = [];
if (fs.existsSync(msiPath)) packages.push(msiPath);
if (versionJson.downloadUrlExe) {
if (!fs.existsSync(exePath)) {
throw new Error(`version.json 指向 EXE,但文件不存在: ${exePath}`);
}
packages.push(exePath);
}
if (!packages.length) {
throw new Error(`构建完成但没找到安装包(${msiName} / ${exeName})`);
}
for (const pkg of packages) {
console.log(`安装包: ${pkg}(${(fs.statSync(pkg).size / 1024 / 1024).toFixed(1)} MB)`);
}
console.log(`版本文件: ${versionPath}`);
console.log(`下载地址: ${versionJson.downloadUrl}`);
if (versionJson.downloadUrlExe) {
console.log(`下载地址(EXE): ${versionJson.downloadUrlExe}`);
}
console.log(`发布目录: ${config.username}@${config.host}:${remoteDir}`);
console.log(`版本目录: ${config.username}@${config.host}:${remoteVersionDir}`);
if (options.dryRun) {
console.log('DRY-RUN:只构建,不上传。');
return;
}
ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。');
ensureCommandAvailable('scp', '请先安装 OpenSSH Client 并确保 scp 在 PATH 中。');
const stamp = getNowStamp();
const remoteVersionTmp = `${remoteVersionDir}/.version.json.upload-${stamp}`;
runSsh(config, [
'set -euo pipefail',
`DIR=${quoteForBash(remoteDir)}`,
`VDIR=${quoteForBash(remoteVersionDir)}`,
'mkdir -p "$DIR" "$VDIR"',
// 清理上次中断留下的隐藏临时文件
'find "$DIR" "$VDIR" -maxdepth 1 -type f -name ".*.upload-*" -delete',
].join('\n'), { stdio: 'pipe' });
for (const pkg of packages) {
const name = path.basename(pkg);
const remoteTmp = `${remoteDir}/.${name}.upload-${stamp}`;
console.log(`上传安装包 ${name}(${(fs.statSync(pkg).size / 1024 / 1024).toFixed(1)} MB)…`);
runScp(config, pkg, remoteTmp);
runSsh(config, [
'set -euo pipefail',
`TMP=${quoteForBash(remoteTmp)}`,
`FINAL=${quoteForBash(`${remoteDir}/${name}`)}`,
'mv "$TMP" "$FINAL"',
'chmod 644 "$FINAL"',
`chown ${quoteForBash(config.desktopOwner || 'www:www')} "$FINAL" || true`,
`echo "PACKAGE_UPLOADED ${name}"`,
].join('\n'), { stdio: 'pipe' });
console.log(`安装包已发布: ${remoteDir}/${name}`);
}
// 所有安装包就位后再更新 version.json,避免客户端拿到指向不存在文件的版本信息
runScp(config, versionPath, remoteVersionTmp);
runSsh(config, [
'set -euo pipefail',
`DIR=${quoteForBash(remoteDir)}`,
`VDIR=${quoteForBash(remoteVersionDir)}`,
`TMP=${quoteForBash(remoteVersionTmp)}`,
'mv "$TMP" "$VDIR/version.json"',
'chmod 644 "$VDIR/version.json"',
`chown ${quoteForBash(config.desktopOwner || 'www:www')} "$VDIR/version.json" || true`,
'echo "VERSION_JSON_UPLOADED"',
// 只保留最近 N 个安装包(MSI / EXE 分别计算)
'COUNT=0',
`for FILE in $(ls -1t "$DIR"/YuncangTraceSetup-*.msi 2>/dev/null || true); do`,
' COUNT=$((COUNT + 1))',
` if [ "$COUNT" -gt ${Number(keep)} ]; then rm -f "$FILE"; fi`,
'done',
'COUNT=0',
`for FILE in $(ls -1t "$DIR"/YuncangTraceSetup-*.exe 2>/dev/null || true); do`,
' COUNT=$((COUNT + 1))',
` if [ "$COUNT" -gt ${Number(keep)} ]; then rm -f "$FILE"; fi`,
'done',
'ls -1t "$DIR" | head -20',
].join('\n'), { stdio: 'pipe' });
if (!options.skipNginx) {
refreshNginx(config);
}
console.log('');
console.log('桌面端发布完成:');
console.log(` 版本: ${version}`);
for (const pkg of packages) {
console.log(` 安装包: ${baseUrl}/download/desktop/${path.basename(pkg)}`);
}
console.log(` 更新信息: ${baseUrl}/download/version.json`);
}
try {
main();
} catch (err) {
console.error(`[DESKTOP] ${err && err.message ? err.message : err}`);
process.exit(1);
}