241 lines
9.8 KiB
JavaScript
241 lines
9.8 KiB
JavaScript
import fs from 'node:fs/promises';
|
||
import { createReadStream } from 'node:fs';
|
||
import { spawn } from 'node:child_process';
|
||
import { createHash } from 'node:crypto';
|
||
import path from 'node:path';
|
||
import { createInterface } from 'node:readline';
|
||
import { fileURLToPath } from 'node:url';
|
||
|
||
export const UI_FONT_LICENSE = 'assets/ui-fonts/LICENSE-HarmonyOS-Sans.txt';
|
||
export const NATIVE_NOTICES = ['LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md', UI_FONT_LICENSE];
|
||
export const UI_FONT_FILES = [
|
||
'assets/ui-fonts/HarmonyOS_SansSC_Regular.ttf',
|
||
'assets/ui-fonts/HarmonyOS_SansSC_Medium.ttf',
|
||
'assets/ui-fonts/HarmonyOS_SansSC_Semibold.ttf',
|
||
];
|
||
|
||
export const NATIVE_FILES = [...NATIVE_NOTICES, ...UI_FONT_FILES];
|
||
export const LAUNCHER = '启动客户端.cmd';
|
||
export const BUILD_README = '本地构建说明.txt';
|
||
const MANIFEST = 'build-manifest.json';
|
||
const agentFiles = ['node.exe', 'LICENSE-Node.txt', 'package.json', 'package-lock.json'];
|
||
export const AGENT_DIRECTORIES = ['src', 'node_modules'];
|
||
export const PACKAGE_CHECK_SCRIPT = 'scripts/client-package-integrity.mjs';
|
||
|
||
export async function regularFile(file) {
|
||
const stat = await fs.lstat(file).catch(() => null);
|
||
if (!stat?.isFile() || stat.size === 0) throw Error('运行包缺少有效文件:' + file);
|
||
}
|
||
|
||
function sanitizeBootText(text) {
|
||
return String(text ?? '')
|
||
.replace(/(?:[A-Za-z]:\\|\/(?:Users|home|var|tmp|root)\/)[^\r\n"'`<>|*?]+?[\\/](?=[^\\/\r\n])/gi, '[path]/')
|
||
.replace(/\s+/g, ' ')
|
||
.trim()
|
||
.slice(0, 260);
|
||
}
|
||
|
||
/** Verify every direct and non-dev lockfile dependency is present with matching version in agent/node_modules. */
|
||
export async function verifyLockfileNodeModules(agentDir) {
|
||
const pkgPath = path.join(agentDir, 'package.json');
|
||
const lockPath = path.join(agentDir, 'package-lock.json');
|
||
const pkg = JSON.parse(await fs.readFile(pkgPath, 'utf8'));
|
||
const lock = JSON.parse(await fs.readFile(lockPath, 'utf8'));
|
||
const packages = lock && typeof lock === 'object' && lock.packages && typeof lock.packages === 'object' ? lock.packages : {};
|
||
const missing = [];
|
||
const mismatched = [];
|
||
const checked = new Set();
|
||
|
||
const verifyEntry = async (rel, expectedVersion) => {
|
||
if (checked.has(rel)) return;
|
||
checked.add(rel);
|
||
const manifestPath = path.join(agentDir, 'node_modules', ...rel.split('/'), 'package.json');
|
||
let raw;
|
||
try {
|
||
raw = await fs.readFile(manifestPath, 'utf8');
|
||
} catch {
|
||
missing.push(rel);
|
||
return;
|
||
}
|
||
if (expectedVersion) {
|
||
let actual;
|
||
try {
|
||
actual = JSON.parse(raw).version;
|
||
} catch {
|
||
mismatched.push(`${rel} (manifest invalid)`);
|
||
return;
|
||
}
|
||
if (actual !== expectedVersion) {
|
||
mismatched.push(`${rel} (expected ${expectedVersion}, got ${actual ?? 'unknown'})`);
|
||
}
|
||
}
|
||
};
|
||
|
||
for (const [key, meta] of Object.entries(packages)) {
|
||
if (!key.startsWith('node_modules/') || !meta || typeof meta !== 'object' || meta.dev === true) continue;
|
||
const rel = key.slice('node_modules/'.length);
|
||
if (!rel) continue;
|
||
await verifyEntry(rel, typeof meta.version === 'string' ? meta.version : undefined);
|
||
}
|
||
|
||
for (const dep of Object.keys(pkg?.dependencies ?? {})) {
|
||
const lockMeta = packages[`node_modules/${dep}`];
|
||
const expected = lockMeta && typeof lockMeta === 'object' && typeof lockMeta.version === 'string' ? lockMeta.version : undefined;
|
||
await verifyEntry(dep, expected);
|
||
}
|
||
|
||
if (missing.length || mismatched.length) {
|
||
const parts = [];
|
||
if (missing.length) parts.push(`缺失 ${missing.length} 项(${missing.slice(0, 8).join(', ')})`);
|
||
if (mismatched.length) parts.push(`版本不符 ${mismatched.length} 项(${mismatched.slice(0, 8).join(', ')})`);
|
||
throw Error(`运行包本地依赖与锁文件不一致:${parts.join(';')}`);
|
||
}
|
||
}
|
||
|
||
/** Smoke-boot agent desktop-host --daemon and verify ready + heartbeat_ack before shipping. */
|
||
export async function verifyDaemonBoot(agentDir, { nodeExe = path.join(agentDir, 'node.exe'), timeoutMs = 10_000 } = {}) {
|
||
const script = path.join(agentDir, 'src', 'desktop-host.mjs');
|
||
await regularFile(nodeExe);
|
||
await regularFile(script);
|
||
const env = { ...process.env };
|
||
delete env.NODE_OPTIONS;
|
||
delete env.NODE_PATH;
|
||
|
||
await new Promise((resolve, reject) => {
|
||
const child = spawn(nodeExe, [script, '--daemon'], {
|
||
cwd: agentDir,
|
||
env,
|
||
windowsHide: true,
|
||
stdio: ['pipe', 'pipe', 'pipe'],
|
||
});
|
||
let stderr = '';
|
||
let settled = false;
|
||
let ready = false;
|
||
let acked = false;
|
||
let exitTimer;
|
||
|
||
const fail = reason => {
|
||
if (settled) return;
|
||
settled = true;
|
||
clearTimeout(timer);
|
||
clearTimeout(exitTimer);
|
||
try { rl.close(); } catch { /* ignore */ }
|
||
try { child.kill(); } catch { /* ignore */ }
|
||
const detail = sanitizeBootText(stderr);
|
||
reject(Error(detail ? `${reason}:${detail}` : reason));
|
||
};
|
||
|
||
const succeed = () => {
|
||
if (settled) return;
|
||
settled = true;
|
||
clearTimeout(timer);
|
||
clearTimeout(exitTimer);
|
||
try { rl.close(); } catch { /* ignore */ }
|
||
resolve();
|
||
};
|
||
|
||
const timer = setTimeout(() => fail(!ready ? '本机Agent自检启动超时' : '本机Agent自检心跳超时'), timeoutMs);
|
||
child.stderr.on('data', chunk => {
|
||
if (stderr.length < 4096) stderr += chunk.toString('utf8').slice(0, 4096 - stderr.length);
|
||
});
|
||
child.on('error', err => fail(`本机Agent自检进程启动异常:${err.message}`));
|
||
|
||
const rl = createInterface({ input: child.stdout, crlfDelay: Infinity });
|
||
rl.on('line', line => {
|
||
if (settled) return;
|
||
let msg;
|
||
try { msg = JSON.parse(line); } catch { return; }
|
||
if (msg?.type === 'ready' && !ready) {
|
||
ready = true;
|
||
try { child.stdin.write(JSON.stringify({ type: 'heartbeat', id: 1 }) + '\n'); } catch { /* wait for exit */ }
|
||
} else if (msg?.type === 'heartbeat_ack' && msg?.id === 1 && ready && !acked) {
|
||
acked = true;
|
||
try {
|
||
child.stdin.write(JSON.stringify({ type: 'prepare_exit' }) + '\n');
|
||
child.stdin.end();
|
||
} catch { /* ignore */ }
|
||
exitTimer = setTimeout(() => {
|
||
try { child.kill(); } catch { /* ignore */ }
|
||
succeed();
|
||
}, 2000);
|
||
}
|
||
});
|
||
|
||
child.on('exit', (code, signal) => {
|
||
if (settled) return;
|
||
if (acked) {
|
||
succeed();
|
||
return;
|
||
}
|
||
const status = code !== null ? `退出码 ${code}` : `信号 ${signal ?? 'unknown'}`;
|
||
fail(!ready ? `本机Agent自检未就绪即退出(${status})` : `本机Agent自检未完成心跳即退出(${status})`);
|
||
});
|
||
});
|
||
}
|
||
|
||
export async function inventoryFiles(destination) {
|
||
const files = [];
|
||
async function visit(dir, prefix) {
|
||
for (const entry of await fs.readdir(dir, { withFileTypes: true })) {
|
||
const file = path.join(dir, entry.name);
|
||
const relative = prefix + entry.name;
|
||
if (entry.isDirectory()) {
|
||
await visit(file, relative + '/');
|
||
} else if (!entry.isFile()) {
|
||
throw Error('运行包不接受非普通文件:' + relative);
|
||
} else if (relative !== MANIFEST) {
|
||
let bytes = 0;
|
||
const hash = createHash('sha256');
|
||
for await (const chunk of createReadStream(file)) {
|
||
bytes += chunk.length;
|
||
hash.update(chunk);
|
||
}
|
||
files.push({ path: relative, bytes, sha256: hash.digest('hex') });
|
||
}
|
||
}
|
||
}
|
||
await visit(destination, '');
|
||
return files.sort((a, b) => a.path.localeCompare(b.path, 'en'));
|
||
}
|
||
|
||
async function directoryExists(directory) {
|
||
if (!(await fs.lstat(directory)).isDirectory()) throw Error('运行包目录无效:' + directory);
|
||
}
|
||
|
||
async function onlyEntries(directory, allowed) {
|
||
await directoryExists(directory);
|
||
for (const name of await fs.readdir(directory)) {
|
||
if (!allowed.includes(name)) throw Error('运行包含未批准文件:' + path.join(directory, name));
|
||
}
|
||
}
|
||
|
||
export async function checkClientPackage({ destination }) {
|
||
const rootFiles = ['photocraft.exe', LAUNCHER, BUILD_README, MANIFEST, ...NATIVE_NOTICES.filter(file => !file.includes('/'))];
|
||
await onlyEntries(destination, [...rootFiles, 'assets', 'agent']);
|
||
await onlyEntries(path.join(destination, 'assets'), ['ui-fonts']);
|
||
const uiAssets = [UI_FONT_LICENSE, ...UI_FONT_FILES];
|
||
await onlyEntries(path.join(destination, 'assets/ui-fonts'), uiAssets.map(file => path.posix.basename(file)));
|
||
const agent = path.join(destination, 'agent');
|
||
await onlyEntries(agent, [...agentFiles, ...AGENT_DIRECTORIES, 'scripts']);
|
||
await onlyEntries(path.join(agent, 'scripts'), [path.basename(PACKAGE_CHECK_SCRIPT)]);
|
||
for (const file of [...rootFiles, ...uiAssets]) await regularFile(path.join(destination, file));
|
||
for (const file of [...agentFiles, PACKAGE_CHECK_SCRIPT]) await regularFile(path.join(agent, file));
|
||
for (const dir of AGENT_DIRECTORIES) await directoryExists(path.join(agent, dir));
|
||
|
||
const manifest = JSON.parse(await fs.readFile(path.join(destination, MANIFEST), 'utf8'));
|
||
const files = await inventoryFiles(destination);
|
||
const expected = new Map(manifest.files.map(file => [file.path, file]));
|
||
if (manifest.files.length !== files.length || expected.size !== files.length) throw Error('运行包文件清单不匹配');
|
||
for (const file of files) {
|
||
const entry = expected.get(file.path);
|
||
if (entry?.bytes !== file.bytes || entry.sha256 !== file.sha256) throw Error('运行包文件校验失败:' + file.path);
|
||
}
|
||
if (manifest.bytes !== files.reduce((sum, file) => sum + file.bytes, 0)) throw Error('运行包文件清单总大小不匹配');
|
||
return { packageReady: true, files: files.length, bytes: manifest.bytes };
|
||
}
|
||
|
||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||
const destination = fileURLToPath(new URL('../../', import.meta.url));
|
||
console.log(JSON.stringify(await checkClientPackage({ destination })));
|
||
}
|