packServer/backend/scripts/deploy/publish-extension.cjs
liufumingren 6818da707e build(extension): 分发用压缩产物(esbuild minify,不混淆)
MV3 没有编译产物,桌面安装包会把插件源码装在 <安装目录>\extension,用户能直接看到
带注释的代码并随手改。这里加一层「压缩」:去注释、压空白、缩短标识符,体积 71KB → 30KB。

- backend/scripts/deploy/build-extension.cjs(新):esbuild 逐文件 minify 输出 extension/dist,
  不做 bundle(importScripts('lib/rules.js') 与各处路径原样有效),无 eval/Function,
  满足 MV3 的 CSP 与商店「代码可读」要求;
- publish-extension.cjs:打包/压缩包一律从 dist 取源;商店 zip 改用自写的
  zip-util.cjs —— PowerShell 5.1 的 Compress-Archive 会把条目名写成 `src\x.js`,
  8.3 短路径下还会多出前导 `/`,商店会当成怪文件名;
- desktop csproj 改为打 ..\extension\dist\**,installer/build.ps1 在 dotnet publish 前
  自动跑一次 bundle(找不到 node/esbuild 明确报错,避免打进上次的旧 dist);
- extension:rules.js 的兜底 urlTemplate/fallback 从 localhost:7301 改为线上站点
  (和服务端默认值保持一致),版本 1.1.2;
- backend 增加 esbuild devDependency 与 npm run extension:bundle;文档同步。

验证:5 个 js 全部 node --check 通过;dist 里 manifest 引用的 14 个文件都在;
Chrome --pack-extension 成功(扩展 ID 不变);zip 条目全部是标准 `/` 且 manifest.json 在根目录、
可正常解压;desktop Debug 编译 0 警告 0 错误,输出目录里是指向 dist 的压缩版(无 keys/README/test)。

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

302 lines
12 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');
const { build: buildExtension } = require('./build-extension.cjs');
const { zipDirectory } = require('./zip-util.cjs');
/** 仓库根(backend 的上一级) */
const REPO_ROOT = path.resolve(ROOT, '..');
const EXT_DIR = path.join(REPO_ROOT, 'extension');
/** 正式包一律用压缩后的产物(`npm run extension:bundle` 生成,体积约为源码 1/3) */
const DIST_DIR = path.join(EXT_DIR, 'dist');
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/dist 不进包) */
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(DIST_DIR, name);
if (!fs.existsSync(from)) throw new Error(`插件打包产物缺少:${from}(先跑 npm run extension:bundle)`);
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'));
}
async 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, DIST_DIR)},已压缩)`);
await buildExtension({ log: true });
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 });
// 条目名一律 `/`(PowerShell 的 Compress-Archive 会写反斜杠,商店不认)
const result = zipDirectory(srcDir, zipPath);
console.log(`商店上传包: ${zipPath}(${result.files} 个文件,${(result.bytes / 1024).toFixed(0)} KB)`);
return;
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().catch(err => {
console.error(err.message);
process.exit(1);
});