host-deploy.mjs
8.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
/**
* 主壳(host)部署 —— 全仓唯一实现,release:spec 与 release:affected 共用。
*
* 为什么不各写一份:这条链路踩一次坑,两边必须同时修,否则「spec 发版正常、
* affected 发版白屏」。历史上清空时机、--no-clean 传递、主壳落点都已经分叉过一次。
*
* ── 落点:/mfe/host/<version>/,站点根只留一个指针 index.html ──────────────
* 站点根是整站唯一会被**原地覆盖**的地方。以前主壳 dist 直接摊在根上,一次发布要
* 逐个覆盖 index.html 和一批 assets;在「HTML 已落地、JS 还没到」的几百毫秒里,
* 线上是新页面配旧资产 → 白屏 404,而且这个窗口不可观测、不可复现。
*
* 版本化之后:
* - 资产进 /mfe/host/<version>/,整目录新增,天然原子;
* - 站点根只覆盖 index.html 一个文件,rsync/cp 都是「写临时文件再 rename」;
* - 旧主壳的 assets 不再散落在根目录,删一个版本就是删一个目录(见 release-prune)。
*
* 代价:主壳也要按版本号构建(SHELL_BASE 注入),所以 turbo 的 globalEnv 必须声明它,
* 否则换版本号会命中旧缓存,产物还指向上一个目录 —— 与 SUBAPP_BASE 同一类坑。
*/
import fs from 'node:fs';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
/** 主壳版本目录的部署相对路径(含末尾斜杠,可直接当 URL 前缀)。 */
export function hostRelOf(version) {
return `mfe/host/${version}/`;
}
/**
* 主壳产物的 base 校验 —— 与 release.mjs 里子应用那道同源,防同一类事故:
* 产物资源指向 /assets/xxx.js,而实际部署在 /mfe/host/1.0.0/assets/xxx.js,白屏零报错。
* --skip-build 复用旧 dist 时尤其必查(旧 dist 的 base 指向上一个版本目录)。
*/
export function assertShellBase(distDir, hostBase, die) {
const html = fs.readFileSync(path.join(distDir, 'index.html'), 'utf8');
const refs = [...html.matchAll(/\b(?:src|href)="([^"]+)"/g)]
.map((m) => m[1])
.filter((u) => !/^(?:data:|blob:|#)/.test(u));
if (refs.length === 0) return 0;
const bad = refs.filter((u) => {
if (/^https?:\/\//u.test(u)) return !u.includes(hostBase);
if (u.startsWith('/')) return !u.startsWith(hostBase);
return false; // 相对路径由页面自身位置解析,不会脱离版本目录
});
if (bad.length) {
die(
`主壳产物有 ${bad.length} 个资源路径未对齐 ${hostBase}:\n` +
bad
.slice(0, 5)
.map((u) => ` ${u}`)
.join('\n') +
'\n 部署到版本目录后会 404。构建时必须带 SHELL_BASE,且确认 turbo 未命中旧缓存。',
);
}
return refs.length;
}
/** 递归收集产物里的 .js:密钥可能落在任意 chunk,不写死 assets/ 目录。 */
function collectJs(dir, out = []) {
if (!fs.existsSync(dir)) return out;
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const p = path.join(dir, entry.name);
if (entry.isDirectory()) collectJs(p, out);
else if (entry.name.endsWith('.js')) out.push(p);
}
return out;
}
/**
* PEM 头后面必须跟着真实密钥体,只查「有没有 -----BEGIN PUBLIC KEY-----」会误判:
* wrapPublicKey 的模板字符串本身就带这个字面量,空 PEM 的坏产物照样能命中。
* 密钥体在 JS 源码里是 JSON.stringify 后的形态(换行转成字面量 \r\n),取头后 160
* 字符窗口、要求出现 >= 40 个连续 base64 字符即可,兼容 PKCS#8 / PKCS#1、2048/4096 位。
*/
function hasRealKey(text, header) {
let from = 0;
for (;;) {
const i = text.indexOf(header, from);
if (i < 0) return false;
const window = text.slice(i + header.length, i + header.length + 160);
if (/[A-Za-z0-9+/=]{40,}/.test(window)) return true;
from = i + header.length;
}
}
/**
* 主壳产物 PEM 校验 —— 发版前最后一道闸。
*
* vite 侧 uj:key-guard 拦的是「本次构建缺密钥」;这里拦的是「本次部署的产物没有密钥」,
* 覆盖 --skip-build 复用旧 dist、以及别的机器预先构建好 dist 再发的情况。
* 历史事故:CI 上 keys/*.pem 被 .gitignore 排除 → 虚拟模块注入空串 → 请求不加签、
* 响应验签全挂,却被 onTransportError 误报成「网络异常,请检查连接后重试」。
*/
export function assertShellKeys(distDir, die) {
if (process.env.VITE_SIGN_ENABLED === 'false') return 0;
const files = collectJs(distDir);
if (!files.length) die(`主壳产物 ${distDir} 里没有 .js,无法校验签名密钥;请先构建。`);
const text = files.map((f) => fs.readFileSync(f, 'utf8')).join('\n');
const pub = hasRealKey(text, '-----BEGIN PUBLIC KEY-----');
const pri =
hasRealKey(text, '-----BEGIN PRIVATE KEY-----') ||
hasRealKey(text, '-----BEGIN RSA PRIVATE KEY-----');
if (pub && pri) return files.length;
die(
`[keys] 主壳产物缺少完整签名密钥,已中止部署(${path.relative(process.cwd(), distDir)}):\n` +
` 服务端公钥 PEM: ${pub ? '✓ 已内嵌' : '❌ 缺失或只有 PEM 模板'}\n` +
` 客户端私钥 PEM: ${pri ? '✓ 已内嵌' : '❌ 缺失或只有 PEM 模板'}\n` +
` 构建机没有 apps/web/shell/keys/*.pem(.gitignore 已排除),或 --skip-build 复用了旧 dist。\n` +
` 修复:把密钥放进 keys/ 后重建;或注入 VITE_SERVER_PUBLIC_KEY / VITE_CLIENT_PRIVATE_KEY 重建;\n` +
` 确需关闭整条签名链路时,用 VITE_SIGN_ENABLED=false 显式声明(生产不推荐)。`,
);
}
/**
* 构建主壳并把产物摆到版本目录 + 站点根指针。
*
* @param {object} o
* @param {string} o.root 仓库根
* @param {string} o.outRoot 产物根(部署根镜像)
* @param {string} o.version 本次发布版本号
* @param {string} o.shellName 主壳包名(@uj/web-shell)
* @param {Map<string, any>} o.workspace scanWorkspace() 的 pkgs
* @param {boolean} o.skipBuild 复用已有 dist
* @param {string} o.pnpmBin pnpm 可执行名
* @param {boolean} o.isWin Windows 判定
* @param {(m: string) => void} o.info
* @param {(m: string) => never} o.die
* @returns {{ hostRel: string, fileCount: number }}
*/
export function deployHost(o) {
const { root, outRoot, version, shellName, workspace, skipBuild, pnpmBin, isWin, info, die } = o;
if (!shellName) die('未找到主壳包(apps/web/shell),无法部署 host。');
const shellMeta = workspace.get(shellName);
if (!shellMeta) die(`workspace 里没有 ${shellName},无法部署 host。`);
const shellDist = path.join(root, shellMeta.dir, 'dist');
const hostRel = hostRelOf(version);
const hostBase = `/${hostRel}`;
info(`构建主壳 ${shellName}(SHELL_BASE=${hostBase})...`);
if (skipBuild) {
if (!fs.existsSync(path.join(shellDist, 'index.html'))) {
die(
`--skip-build 但找不到 ${path.relative(root, shellDist)}/index.html;先构建或去掉 --skip-build。`,
);
}
} else {
const bres = spawnSync(pnpmBin, ['--filter', shellName, 'build'], {
cwd: root,
stdio: 'inherit',
shell: isWin,
env: { ...process.env, SHELL_BASE: hostBase },
});
if (bres.error) die(`启动 pnpm 失败:${bres.error.message}`);
if (bres.status !== 0) die(`主壳构建失败(exit ${bres.status}),未执行上传。`);
}
const refCount = assertShellBase(shellDist, hostBase, die);
// 密钥校验放在构建/复用 dist 之后、落盘之前:keyGuard 管构建,这里管部署,
// --skip-build 复用旧 dist 也拦得住,坏产物不会进版本目录、更不会上传。
assertShellKeys(shellDist, die);
info('主壳产物签名密钥校验通过(公钥 / 私钥 PEM 均已内嵌)');
const hostTarget = path.join(outRoot, 'mfe', 'host', version);
fs.mkdirSync(hostTarget, { recursive: true });
fs.cpSync(shellDist, hostTarget, { recursive: true });
info(`主壳产物已落到 ${hostRel}(整目录新增,不存在半截状态)`);
// 站点的 SPA 回落目标。内容与版本目录里那份相同,但它的资源指向前者;
// 只覆盖这一个文件,运维用 rsync 也是「写临时文件再 rename」,没有混合态。
fs.copyFileSync(path.join(shellDist, 'index.html'), path.join(outRoot, 'index.html'));
info(`站点根 index.html 已指向 ${hostRel}(本次唯一会被原地覆盖的文件)`);
// 旧结构升级提示:根目录残留的主壳 assets 不会再被引用,也不该继续躺着。
const legacyAssets = path.join(outRoot, 'assets');
if (fs.existsSync(legacyAssets) && fs.statSync(legacyAssets).isDirectory()) {
info(
`⚠ 产物根仍有旧结构的 assets/(升级前的遗留)。部署前请清掉部署根的 assets/,` +
`否则会永久累积无人引用的旧文件。`,
);
}
return { hostRel, fileCount: refCount };
}