- 工具菜单去掉「安装浏览器插件(企业策略:Chrome / Edge)」「卸载浏览器插件(企业策略)」, 删除 Services/ExtensionInstaller.cs(.reg 生成 + 提权导入 + 注册表校验) - 只保留「安装浏览器插件(Edge 应用商店)」与「复制插件路径(Chrome / 开发者模式)」; 商店弹窗去掉「审核中会 404」的说法,Chrome 用户直接引导到开发者模式 - 文档同步(桌面 README / 后端 README / extension README / STORE-SUBMISSION / keys README): 写清老机器上残留的 HKLM 策略怎么手工清理,避免和商店版同时注入 - extension:publish(.crx + updates.xml)保留,仅给内网/离线分发用 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
305 lines
12 KiB
JavaScript
305 lines
12 KiB
JavaScript
'use strict';
|
||
|
||
/**
|
||
* Chrome 插件正式包:打包 .crx + 生成 updates.xml,并发布到 nginx 静态目录
|
||
*
|
||
* 为什么还需要它:
|
||
* - 浏览器只认**已签名**的扩展包,需要给内网/离线机器一个可双击安装或自行加载的 `.crx`;
|
||
* - `updates.xml` 让这些机器能按 `<扩展ID>;<update_url>` 自动升级(
|
||
* 企业策略 `ExtensionInstallForcelist` 用的就是这个组合,客户端已不再写策略,改由 IT 自行下发);
|
||
* - 所以这里把仓库里的 `extension/` 打成 `.crx`,连同 `updates.xml` 一起放到
|
||
* `deployRoot/download/extension/`(nginx 对 updates.xml 关缓存,.crx 长缓存)。
|
||
*
|
||
* ⚠️ 正式分发早已改成:Edge 走加载项商店(已上架)、Chrome 走开发者模式加载安装目录里的 `extension/`。
|
||
*
|
||
* 产物(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(` 扩展 ID = ${id}`);
|
||
console.log(` 更新地址 = ${updateUrl}`);
|
||
console.log(` .crx = ${baseUrl}/download/extension/`);
|
||
} finally {
|
||
fs.rmSync(workDir, { recursive: true, force: true });
|
||
}
|
||
}
|
||
|
||
main().catch(err => {
|
||
console.error(err.message);
|
||
process.exit(1);
|
||
});
|