kernel.mjs
13.2 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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
/**
* venus 内核底层库:清单生成 / 完整性校验 / 升级 / 项目生成共用的原语。
* 零依赖,纯 Node ESM。
*
* 工具已全部收编进内核(v2.1.0):cli/、githooks/、docs/ 都在 .kernel/ 内,
* 派生项目根目录只有 .kernel/ 与业务区(apps/ packages/ deploy/),心智负担最小。
* 工具随 .kernel/ 整体升级,不再有独立的"工具区同步"逻辑。
*
* 两个根,必须分清(全局 CLI 注册后这一点尤其关键):
* TEMPLATE_ROOT —— CLI 安装位置(venus.mjs 所在基座),create 从这里取模板。
* PROJECT_ROOT —— 命令执行目录向上找到的项目根(含 .kernel/kernel.json),
* check / manifest / upgrade 都作用于它,绝不是 TEMPLATE_ROOT。
*
* 核心不变式:
* 1. 内核 = PROJECT_ROOT/.kernel/ 下的一切(含 cli/ githooks/ docs/,除白名单);
* 业务 = apps/ 与 packages/ 与 deploy/。
* 2. manifest.json 是内核文件的 SHA-256 快照;额外保护根配置文件 pnpm-workspace.yaml
* (catalog 与 workspace glob 是内核与业务共享的依赖真源,被改会让内核跑不起来)。
* 3. 升级只写 .kernel/ + pnpm-workspace.yaml 的 catalog 段 + 根 package.json 的受管脚本,
* 绝不写 apps/ 与 packages/。
* 4. 根 package.json 的"内核约定脚本"由 kernel.json.managedScripts 单一真源驱动:
* create / upgrade 负责同步,manifest 存命令哈希快照,check 拦截漂移;
* 业务自己加的 scripts 不受管、不覆盖、不校验。
*/
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import { fileURLToPath } from 'node:url';
/** CLI 安装位置:<root>/.kernel/cli/lib/kernel.mjs 上溯三级 = 项目根 */
export const TEMPLATE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../..');
/** 根级受保护文件(相对项目根)。它们不在 .kernel/ 内,但被篡改会让内核依赖解析失效。 */
export const PROTECTED_ROOT_FILES = ['pnpm-workspace.yaml'];
/**
* 从 start 向上查找项目根:最近一个同时含 .kernel/kernel.json 的目录。
* 找不到时返回 null(调用方给出"不在 venus 项目中"的友好提示)。
*/
export function findProjectRoot(start = process.cwd()) {
let cur = path.resolve(start);
for (;;) {
if (fs.existsSync(path.join(cur, '.kernel', 'kernel.json'))) return cur;
const parent = path.dirname(cur);
if (parent === cur) return null;
cur = parent;
}
}
/** 要求必须在项目内,否则抛错 */
export function requireProjectRoot(start = process.cwd()) {
const root = findProjectRoot(start);
if (!root) {
throw new Error(
`当前目录 ${start} 不在 venus 项目内(向上未找到 .kernel/kernel.json)。\n` +
' 请先 cd 到项目目录,或用 venus create <name> 创建一个新项目。',
);
}
return root;
}
export function pathsOf(root) {
const kernelDir = path.join(root, '.kernel');
return {
root,
kernelDir,
manifestPath: path.join(kernelDir, 'manifest.json'),
kernelInfoPath: path.join(kernelDir, 'kernel.json'),
};
}
/**
* 受保护文件白名单(相对 .kernel/):
* 这些文件允许在派生应用中变化,不进哈希清单、不参与篡改判定。
* - manifest.json / kernel.json:升级时会重写,不能自己校验自己。
* - shell/.env*:每个应用的本地配置(域名、manifest URL),天然各家不同。
* - shell/keys/*.pem:签名密钥,由部署注入。
*/
const WRITE_EXEMPT = [
/^manifest\.json$/,
/^kernel\.json$/,
/(^|\/)keys\/[^/]+\.pem$/,
/(^|\/)\.env(\.|$)/,
];
const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', '.turbo', '.tmp', 'coverage', 'miniprogram_dist']);
function isExempt(rel) {
return WRITE_EXEMPT.some((re) => re.test(rel));
}
/** 递归收集 .kernel/ 下所有受保护文件的相对路径(POSIX 分隔) */
export function collectKernelFiles(kernelDir) {
const out = [];
function walk(dir) {
for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
if (ent.isDirectory()) {
if (SKIP_DIRS.has(ent.name)) continue;
walk(path.join(dir, ent.name));
} else {
const full = path.join(dir, ent.name);
const rel = path.relative(kernelDir, full).split(path.sep).join('/');
if (!isExempt(rel)) out.push(rel);
}
}
}
walk(kernelDir);
return out.sort();
}
export function sha256(file) {
return crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
}
/** 对脚本命令文本取哈希(用于受管脚本漂移校验,与文件哈希区分开) */
export function sha256Text(text) {
return crypto.createHash('sha256').update(String(text), 'utf8').digest('hex');
}
/** 从 kernel.json 读取受管脚本真源;老内核没有该字段时返回空对象(平滑兼容) */
export function readManagedScripts(kernelDir) {
try {
const info = JSON.parse(fs.readFileSync(path.join(kernelDir, 'kernel.json'), 'utf8'));
const m = info?.managedScripts;
return m && typeof m === 'object' && !Array.isArray(m)
? Object.fromEntries(Object.entries(m).filter(([, v]) => typeof v === 'string'))
: {};
} catch {
return {};
}
}
/**
* 同步根 package.json 中的受管脚本。
*
* @param {string} root 项目根
* @param {Record<string,string>} next 新版受管脚本(命令真源)
* @param {Record<string,string>|null} previous 上一版受管脚本(升级路径传 oldInfo 的副本,
* 用于清掉新版已移除的脚本);create / sync-scripts 传 null 表示不清理
* @returns {{added:string[],updated:string[],removed:string[],unchanged:string[]}|null}
* 根 package.json 不存在时返回 null;无变更时不写盘(保留业务手写的格式与空行)。
*/
export function syncManagedScripts(root, next = {}, previous = null) {
const pkgPath = path.join(root, 'package.json');
if (!fs.existsSync(pkgPath)) return null;
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
const scripts = { ...(pkg.scripts ?? {}) };
const prev = previous ?? {};
const result = { added: [], updated: [], removed: [], unchanged: [] };
// 内核新版已移除的脚本:从 scripts 中清掉(避免残留旧命令继续被执行)
for (const name of Object.keys(prev)) {
if (!(name in next) && name in scripts) {
delete scripts[name];
result.removed.push(name);
}
}
// 写入/覆盖受管脚本;命令相同则不动
for (const [name, command] of Object.entries(next)) {
if (scripts[name] === command) result.unchanged.push(name);
else {
const existed = name in scripts;
scripts[name] = command;
(existed ? result.updated : result.added).push(name);
}
}
if (result.added.length || result.updated.length || result.removed.length) {
pkg.scripts = scripts;
fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n');
}
return result;
}
/** 格式化受管脚本同步摘要,用于升级/自救命令输出 */
export function formatScriptSync(r) {
if (!r) return ' ! 根 package.json 不存在,跳过受管脚本同步';
const lines = [];
lines.push(
` 受管脚本:新增 ${r.added.length} / 更新 ${r.updated.length} / 移除 ${r.removed.length} / 未变 ${r.unchanged.length}(业务自定义 scripts 不动)`,
);
if (r.added.length) lines.push(` + ${r.added.join(', ')}`);
if (r.updated.length) lines.push(` ~ ${r.updated.join(', ')}`);
if (r.removed.length) lines.push(` - ${r.removed.join(', ')}`);
return lines.join('\n');
}
export function readKernelInfo(root = requireProjectRoot()) {
try {
return JSON.parse(fs.readFileSync(pathsOf(root).kernelInfoPath, 'utf8'));
} catch {
return { version: '0.0.0', name: 'venus-kernel' };
}
}
/**
* 对任意项目生成清单。
* @param {string} kernelDir 目标 .kernel/ 绝对路径
* @param {string} root 项目根(用于计算根级受保护文件哈希),默认 .kernel/ 的父目录
*/export function writeManifestAt(kernelDir, root = path.resolve(kernelDir, '..')) {
let info = { version: '0.0.0', name: 'venus-kernel' };
try {
info = JSON.parse(fs.readFileSync(path.join(kernelDir, 'kernel.json'), 'utf8'));
} catch { /* 用默认值 */ }
const files = collectKernelFiles(kernelDir);
const rootFiles = {};
for (const rel of PROTECTED_ROOT_FILES) {
const full = path.join(root, rel);
if (fs.existsSync(full)) rootFiles[rel] = sha256(full);
}
const manifest = {
kernel: info.name,
version: info.version,
generatedAt: new Date().toISOString(),
algorithm: 'sha256',
fileCount: files.length,
files: Object.fromEntries(files.map((rel) => [rel, sha256(path.join(kernelDir, rel))])),
rootFiles,
};
fs.writeFileSync(path.join(kernelDir, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\n');
return manifest;
}
/** 生成指定项目(或当前项目)的清单;仅内核维护者 / 升级流程调用。 */
export function generateManifest(root = requireProjectRoot()) {
return writeManifestAt(pathsOf(root).kernelDir, root);
}
/**
* 校验内核完整性。返回结构化结果,不直接退出进程(由调用方决定退出码)。
* 检测五类漂移:
* - modified:内核文件存在但哈希变了
* - deleted:内核文件清单里有、磁盘上没了
* - added:内核文件磁盘上有、清单里没有(防止绕过)
* - rootModified:受保护的根配置(pnpm-workspace.yaml)哈希变了
* - scriptDrift:根 package.json 里"内核受管脚本"的命令与 kernel.json 真源不一致
* (老内核没有 managedScripts 字段时自动跳过,平滑兼容)
*/
export function verifyIntegrity(root = requireProjectRoot()) {
const { kernelDir, manifestPath } = pathsOf(root);
if (!fs.existsSync(manifestPath)) {
return {
ok: false, reason: 'manifest_missing', root,
modified: [], deleted: [], added: [], rootModified: [], scriptDrift: [],
};
}
const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
const current = collectKernelFiles(kernelDir);
const recorded = Object.keys(manifest.files ?? {});
const currentSet = new Set(current);
const recordedSet = new Set(recorded);
const modified = [];
for (const rel of current) {
if (!recordedSet.has(rel)) continue;
if (sha256(path.join(kernelDir, rel)) !== manifest.files[rel]) modified.push(rel);
}
const deleted = recorded.filter((rel) => !currentSet.has(rel));
const added = current.filter((rel) => !recordedSet.has(rel));
const rootModified = [];
for (const [rel, hash] of Object.entries(manifest.rootFiles ?? {})) {
const full = path.join(root, rel);
if (!fs.existsSync(full) || sha256(full) !== hash) rootModified.push(rel);
}
// 受管脚本漂移:直接读当前内核的 kernel.json 真源(不依赖 manifest 生成时机,
// 保证老 CLI 升级后立刻生效);只校验真源列出的脚本名,业务自定义 scripts 完全不管
const scriptDrift = [];
const managed = readManagedScripts(kernelDir);
let pkgScripts = {};
try {
pkgScripts = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')).scripts ?? {};
} catch { /* package.json 缺失/损坏时按全部漂移处理 */ }
for (const [name, command] of Object.entries(managed)) {
const actual = pkgScripts[name];
if (typeof actual !== 'string' || sha256Text(actual) !== sha256Text(command)) scriptDrift.push(name);
}
const ok = modified.length === 0 && deleted.length === 0 && added.length === 0
&& rootModified.length === 0 && scriptDrift.length === 0;
return {
ok,
reason: ok ? 'clean' : 'tampered',
root,
modified,
deleted,
added,
rootModified,
scriptDrift,
managedCount: Object.keys(managed).length,
manifest,
};
}
/** 格式化校验结果用于终端输出 */
export function formatIntegrity(result) {
const lines = [];
if (result.reason === 'manifest_missing') {
lines.push(' ✗ .kernel/manifest.json 不存在 —— 内核未纳入门禁,先运行 pnpm kernel:manifest');
return lines.join('\n');
}
if (result.ok) {
lines.push(
` ✓ 内核完整:${result.manifest.fileCount} 个文件哈希一致(v${result.manifest.version})` +
`,根配置 ${Object.keys(result.manifest.rootFiles ?? {}).length} 项一致` +
`,受管脚本 ${result.managedCount ?? 0} 项一致`,
);
return lines.join('\n');
}
lines.push(` ✗ 内核/根配置/受管脚本被篡改(项目:${result.root}),提交已拦截:`);
for (const f of result.modified) lines.push(` [修改] .kernel/${f}`);
for (const f of result.deleted) lines.push(` [删除] .kernel/${f}`);
for (const f of result.added) lines.push(` [新增] .kernel/${f}`);
for (const f of result.rootModified) lines.push(` [根配置修改] ${f}`);
for (const s of result.scriptDrift ?? []) lines.push(` [受管脚本修改] package.json scripts.${s}`);
lines.push(' 内核由 CLI 统一升级(venus kernel upgrade),请勿直接修改 .kernel/、受保护的根配置与受管脚本。');
lines.push(' 误改受管脚本可用 venus kernel sync-scripts 按当前内核真源恢复;业务自定义 scripts 不受影响。');
return lines.join('\n');
}