packServer/backend/scripts/deploy/publish-extension.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

293 lines
11 KiB
JavaScript
Raw 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';
/**
* Chrome 插件正式包:打包 .crx + 生成 updates.xml,并发布到 nginx 静态目录
*
* 为什么需要它:
* - 浏览器只认**已签名**的扩展包,`chrome://extensions` 里「加载已解压」没法被策略/安装包注入;
* - 企业策略 `ExtensionInstallForcelist` 只接受 `<扩展ID>;<update_url>`,update_url 必须是一个
* 可访问的 XML(不是本地目录);
* - 所以这里把仓库里的 `extension/` 打成 `.crx`,连同 `updates.xml` 一起放到
* `deployRoot/download/extension/`(nginx 对 updates.xml 关缓存,.crx 长缓存)。
*
* 产物(extension/out/):
* - `YuncangTraceExtension-<version>.crx` 扩展包(文件名带版本号,可以长缓存)
* - `updates.xml` 更新清单(`<app appid>` 就是扩展 ID)
* - `extension-id.txt` 扩展 ID(给安装/排障用)
*
* 扩展 ID 由**私钥**决定:`extension/keys/key.pem`(首次运行自动生成,**务必备份**;
* 换私钥 = 换 ID = 已下发到客户机的策略全部失效)。
*
* 用法:
* npm run extension:publish # 打包 + 上传 + 刷新 nginx
* npm run extension:publish -- --dry-run # 只打包,不上传
* npm run extension:publish -- --version=1.2.0
* npm run extension:publish -- --skip-nginx # 不改 nginx
* npm run extension:publish -- --browser="C:\Program Files\Microsoft\Edge\Application\msedge.exe"
*/
const crypto = require('node:crypto');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const {
ROOT,
ensureCommandAvailable,
getNowStamp,
loadDeployConfig,
quoteForBash,
refreshNginx,
runCommand,
runScp,
runSsh,
} = require('./deploy-lib.cjs');
/** 仓库根(backend 的上一级) */
const REPO_ROOT = path.resolve(ROOT, '..');
const EXT_DIR = path.join(REPO_ROOT, 'extension');
const KEY_FILE = path.join(EXT_DIR, 'keys', 'key.pem');
const OUT_DIR = path.join(EXT_DIR, 'out');
const PACKAGE_NAME = 'YuncangTraceExtension';
/** 打进 crx 的内容(其余 README/test/tools/out/keys 不进包) */
const INCLUDE = [ 'manifest.json', 'icons', 'src' ];
function parseArgs(argv) {
const options = {
envName: 'production',
version: '',
baseUrl: '',
browser: '',
dryRun: false,
zipOnly: 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 === '--zip') {
// 只打「商店上传用的 zip」,不打包 crx、不上传
options.zipOnly = 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('--base-url=')) {
options.baseUrl = item.slice('--base-url='.length).trim();
} else if (item.startsWith('--browser=')) {
options.browser = item.slice('--browser='.length).trim();
}
}
if (options.version && !/^\d+(\.\d+){1,3}$/.test(options.version)) {
throw new Error(`版本号格式应为 x.y.z:${options.version}`);
}
return options;
}
/** 读 manifest 里的版本号(没传 --version 时用) */
function manifestVersion() {
const data = JSON.parse(fs.readFileSync(path.join(EXT_DIR, 'manifest.json'), 'utf8'));
const version = String(data.version || '').trim();
if (!/^\d+(\.\d+){1,3}$/.test(version)) {
throw new Error(`manifest.json 里的 version 不合法:${version}`);
}
return version;
}
/** 找本机可用的 Chromium 内核浏览器(打包用;Chrome/Edge 都支持 --pack-extension) */
function resolveBrowser(explicit) {
const candidates = [
explicit,
process.env.CHROME_PATH,
process.env.EDGE_PATH,
'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
process.env.LOCALAPPDATA && path.join(process.env.LOCALAPPDATA, 'Google', 'Chrome', 'Application', 'chrome.exe'),
'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe',
'C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe',
].filter(Boolean);
for (const item of candidates) {
if (fs.existsSync(item)) return item;
}
throw new Error('找不到 chrome.exe / msedge.exe(打包 crx 要用)。可用 --browser=<路径> 指定。');
}
/** 把扩展源码复制到临时目录(只带 INCLUDE 里的东西) */
function stageSources(workDir) {
const target = path.join(workDir, PACKAGE_NAME);
fs.mkdirSync(target, { recursive: true });
for (const name of INCLUDE) {
const from = path.join(EXT_DIR, name);
if (!fs.existsSync(from)) throw new Error(`扩展源码缺少:${from}`);
fs.cpSync(from, path.join(target, name), { recursive: true });
}
return target;
}
/**
* 用浏览器命令行打包 crx
*
* - 不给 `--pack-extension-key` 时浏览器会在同级生成 `.pem`(第一次运行用这个拿私钥);
* - 必须给独立的 `--user-data-dir`:否则命令会被**已经在运行的 Chrome** 接走,不会真的打包。
*/
function packCrx(browser, srcDir, keyPath, workDir) {
const baseArgs = [
`--pack-extension=${srcDir}`,
`--user-data-dir=${path.join(workDir, 'profile')}`,
'--no-first-run',
'--no-default-browser-check',
'--disable-gpu',
];
const crxPath = `${srcDir}.crx`;
const pemPath = `${srcDir}.pem`;
if (!fs.existsSync(keyPath)) {
console.log('没有私钥,先生成一个(决定扩展 ID,生成后请备份):', keyPath);
runCommand(browser, baseArgs, { stdio: 'inherit' });
if (!fs.existsSync(pemPath)) throw new Error('浏览器没有生成 .pem,打包失败');
fs.mkdirSync(path.dirname(keyPath), { recursive: true });
fs.copyFileSync(pemPath, keyPath);
if (fs.existsSync(crxPath)) fs.rmSync(crxPath);
}
runCommand(browser, [ ...baseArgs, `--pack-extension-key=${keyPath}` ], { stdio: 'inherit' });
if (!fs.existsSync(crxPath)) throw new Error(`打包失败:没有生成 ${crxPath}`);
return crxPath;
}
/**
* 由私钥算扩展 ID
*
* Chrome 的规则:公钥 DER(SPKI)→ SHA256 → 取前 16 字节 → 每个十六进制位映射成 a~p。
*/
function extensionIdFromKey(pem) {
const publicKey = crypto.createPublicKey(crypto.createPrivateKey(pem));
const spki = publicKey.export({ type: 'spki', format: 'der' });
const hex = crypto.createHash('sha256').update(spki).digest('hex').slice(0, 32);
return hex.split('').map(ch => String.fromCharCode(97 + parseInt(ch, 16))).join('');
}
/** updates.xml:浏览器靠它判断有没有新版本 */
function writeUpdatesXml({ id, version, codebase }) {
return [
'<?xml version=\'1.0\' encoding=\'UTF-8\'?>',
'<gupdate xmlns=\'http://www.google.com/update2/response\' protocol=\'2.0\'>',
` <app appid='${id}'>`,
` <updatecheck codebase='${codebase}' version='${version}' />`,
' </app>',
'</gupdate>',
'',
].join('\n');
}
/** 上传一个文件到远端目录(先传临时名再 mv,避免中途被下到半个文件) */
function uploadFile(config, localPath, remoteDir, name, stamp) {
const remoteTmp = `${remoteDir}/.${name}.upload-${stamp}`;
runScp(config, localPath, remoteTmp);
runSsh(config, [
'set -euo pipefail',
`mv ${quoteForBash(remoteTmp)} ${quoteForBash(`${remoteDir}/${name}`)}`,
`chmod 644 ${quoteForBash(`${remoteDir}/${name}`)}`,
...(config.desktopOwner ? [ `chown ${quoteForBash(config.desktopOwner)} ${quoteForBash(`${remoteDir}/${name}`)}` ] : []),
`echo "UPLOADED ${name}"`,
].join('\n'));
}
function main() {
const options = parseArgs(process.argv.slice(2));
const config = loadDeployConfig(options.envName);
const version = options.version || manifestVersion();
const baseUrl = String(options.baseUrl || config.desktopBaseUrl || (config.serverName ? `https://${config.serverName}` : ''))
.replace(/\/+$/, '');
// --zip 只出商店上传包,不需要后端地址
if (!options.zipOnly && !baseUrl) {
throw new Error('拿不到后端地址:请在 deploy.config.local.cjs 里配 desktopBaseUrl 或 serverName');
}
// --dry-run 也要真的打包(只是不上传):本机得有 Chrome/Edge;--zip 不需要浏览器
const browser = options.zipOnly ? '' : resolveBrowser(options.browser);
// 打包在临时目录里做,仓库里只留 out/ 产物
const workDir = fs.mkdtempSync(path.join(os.tmpdir(), 'yuncang-ext-'));
try {
console.log(`打包 Chrome 插件 ${version}(${path.relative(REPO_ROOT, EXT_DIR)})`);
const srcDir = stageSources(workDir);
// 商店上传用的是 zip(manifest.json 必须在压缩包根目录)
if (options.zipOnly) {
const zipName = `${PACKAGE_NAME}-${version}.zip`;
const zipPath = path.join(OUT_DIR, zipName);
fs.mkdirSync(OUT_DIR, { recursive: true });
fs.rmSync(zipPath, { force: true });
runCommand('powershell.exe', [
'-NoProfile', '-Command',
`Compress-Archive -Path '${path.join(srcDir, '*')}' -DestinationPath '${zipPath}' -Force`,
], { stdio: 'inherit' });
console.log(`商店上传包: ${zipPath}(${(fs.statSync(zipPath).size / 1024).toFixed(0)} KB)`);
return;
}
const crxPath = packCrx(browser, srcDir, KEY_FILE, workDir);
const id = extensionIdFromKey(fs.readFileSync(KEY_FILE, 'utf8'));
const crxName = `${PACKAGE_NAME}-${version}.crx`;
const codebase = `${baseUrl}/download/extension/${crxName}`;
const updateUrl = `${baseUrl}/download/extension/updates.xml`;
fs.mkdirSync(OUT_DIR, { recursive: true });
fs.copyFileSync(crxPath, path.join(OUT_DIR, crxName));
fs.writeFileSync(path.join(OUT_DIR, 'updates.xml'), writeUpdatesXml({ id, version, codebase }));
fs.writeFileSync(path.join(OUT_DIR, 'extension-id.txt'), `${id}\n`);
console.log(`扩展 ID : ${id}`);
console.log(`CRX : ${path.join(OUT_DIR, crxName)}`);
console.log(`更新清单: ${updateUrl}`);
if (options.dryRun) {
console.log('--dry-run:只打包,不上传。');
return;
}
const remoteDir = config.extensionDownloadDir;
if (!remoteDir) throw new Error('未配置 extensionDownloadDir(插件发布目录)');
ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。');
ensureCommandAvailable('scp', '请先安装 OpenSSH Client 并确保 scp 在 PATH 中。');
const stamp = getNowStamp();
runSsh(config, [
'set -euo pipefail',
`mkdir -p ${quoteForBash(remoteDir)}`,
`find ${quoteForBash(remoteDir)} -maxdepth 1 -type f -name ".upload-*" -delete`,
].join('\n'));
uploadFile(config, path.join(OUT_DIR, crxName), remoteDir, crxName, stamp);
// 最后传 updates.xml:新包先就位,浏览器再看到新版本号
uploadFile(config, path.join(OUT_DIR, 'updates.xml'), remoteDir, 'updates.xml', stamp);
if (!options.skipNginx) refreshNginx(config);
console.log('');
console.log('发布完成。客户机「工具 → 安装谷歌插件」会写入策略:');
console.log(` ExtensionInstallForcelist = ${id};${updateUrl}`);
console.log(` ExtensionInstallSources = ${baseUrl}/download/extension/*`);
} finally {
fs.rmSync(workDir, { recursive: true, force: true });
}
}
main();