diff --git a/src/core/desktop/app-installation.mjs b/src/core/desktop/app-installation.mjs index cf072cce..4e6a0cf8 100644 --- a/src/core/desktop/app-installation.mjs +++ b/src/core/desktop/app-installation.mjs @@ -1,8 +1,8 @@ import fs from 'node:fs'; import path from 'node:path'; import { createHash } from 'node:crypto'; -import { binaryIdentity } from './process-identity.mjs'; -import { ownedChild, readState, assertLocalTree } from './file-state.mjs'; +import { binaryIdentity, treeFileIdentity } from './process-identity.mjs'; +import { ownedChild, readState, assertLocalTree, treeFile, samePath } from './file-state.mjs'; import { canonicalHost, hostError } from '../../shared/contracts/desktop-host.mjs'; export function inspectHostInstallation(directory, { full = false, onProgress = null } = {}) { @@ -30,13 +30,17 @@ export function inspectHostInstallation(directory, { full = false, onProgress = let completedFiles = 0, completedBytes = 0; const report = currentPath => onProgress?.({ scope: full ? 'full-manifest' : 'loaded-inputs', root, totalFiles: selected.length, totalBytes: manifest ? totalBytes : null, completedFiles, completedBytes, currentPath }); report(null); + // The root chain is verified before and after the scan; each file is then + // checked with one native realpath instead of re-walking every ancestor. const inputs = selected.map(relative => { - const file = ownedChild(root, relative), identity = binaryIdentity(file), declared = names.get(relative); + const identity = treeFileIdentity(treeFile(root, relative)), declared = names.get(relative); if (manifest?.kind === 'portable' && !declared) throw hostError('实际宿主程序不在原发行清单中。'); if (declared && (identity.bytes !== declared.bytes || identity.sha256 !== declared.sha256)) throw hostError('实际宿主程序与原发行清单不一致。'); completedFiles++; completedBytes += identity.bytes; report(relative); return { path: relative, bytes: identity.bytes, sha256: identity.sha256 }; }); + assertLocalTree(root); + if (!samePath(fs.realpathSync.native(root), root)) throw hostError('宿主安装目录在核对期间发生变化。'); const result = { root, version, kind: manifest?.kind ?? 'development-build', manifestSha256: manifest ? digest(fs.readFileSync(manifestFile)) : null, inputs, verification: full ? 'full-manifest' : 'loaded-host-and-client-inputs' }; return { ...result, identitySha256: digest(JSON.stringify(canonicalHost(result))) }; diff --git a/src/core/desktop/file-state.mjs b/src/core/desktop/file-state.mjs index 95c5f333..166a372c 100644 --- a/src/core/desktop/file-state.mjs +++ b/src/core/desktop/file-state.mjs @@ -37,6 +37,22 @@ export function ownedChild(root, relative, { missing = false } = {}) { const stat = fs.statSync(existing); if (stat.isFile() && stat.nlink !== 1) throw hostError('本机状态文件具有多个路径。'); return assertLocalTree(target, { missing }); } +// Bulk-scan form of ownedChild for an existing regular file below a root that +// the caller already passed through assertLocalTree for this scan. One native +// realpath resolves every component; any link or reparse point in the chain +// makes it differ from the lexical path, so the per-ancestor walk is not repeated. +export function treeFile(base, relative) { + if (typeof relative !== 'string' || !relative || path.isAbsolute(relative) || path.win32.isAbsolute(relative) || relative.includes('\0') || relative.includes(':')) throw hostError('本机状态路径无效。'); + const target = path.resolve(base, relative); + if (!normalized(target).startsWith(normalized(base + path.sep))) throw hostError('本机状态路径超出所属目录。'); + let stat, real; + try { stat = fs.lstatSync(target); real = fs.realpathSync.native(target); } + catch (cause) { if (cause.code === 'ENOENT') throw hostError('本机状态文件不存在。', 'HOST_REGISTRATION_MISSING'); throw cause; } + if (stat.isSymbolicLink() || !samePath(target, real)) throw hostError('本机状态不接受链接或重解析目录。'); + if (!stat.isFile()) throw hostError('本机状态路径不是常规文件。'); + if (stat.nlink !== 1) throw hostError('本机状态文件具有多个路径。'); + return { path: target, stat }; +} export function readState(file, maximum = 4 * 1024 * 1024) { assertLocalTree(file); const stat = fs.lstatSync(file); diff --git a/src/core/desktop/install-manager.mjs b/src/core/desktop/install-manager.mjs index d1e597cf..c5f60652 100644 --- a/src/core/desktop/install-manager.mjs +++ b/src/core/desktop/install-manager.mjs @@ -21,8 +21,10 @@ export function validateInstalledVersion(directory, { onProgress = null } = {}) if (installation.kind !== 'portable') throw fail('安装候选需要完整便携发行清单。'); const manifest = readState(path.join(installation.root, 'MANIFEST.json'), 16 * 1024 * 1024), actual = []; const walk = relative => { for (const entry of fs.readdirSync(path.join(installation.root, relative), { withFileTypes: true })) { - const next = path.posix.join(relative, entry.name); ownedChild(installation.root, next); - if (entry.isDirectory()) walk(next); else if (entry.isFile()) { + // Directories keep the full ancestor check; files are reached only through + // those checked directories, and their bytes were verified by the manifest scan. + const next = path.posix.join(relative, entry.name); + if (entry.isDirectory()) { ownedChild(installation.root, next); walk(next); } else if (entry.isFile()) { actual.push(next); onProgress?.({ scope: 'directory-inventory', root: installation.root, completedFiles: actual.length, totalFiles: manifest.files.length + 1, completedBytes: null, totalBytes: null, currentPath: next }); } else throw fail('安装候选含有链接或非常规文件。'); } }; walk(''); diff --git a/src/core/desktop/process-identity.mjs b/src/core/desktop/process-identity.mjs index 71373233..7c1e0521 100644 --- a/src/core/desktop/process-identity.mjs +++ b/src/core/desktop/process-identity.mjs @@ -52,6 +52,13 @@ export function observeWindowsProcess(pid) { return { ...value, executable: fs.realpathSync.native(value.executable) }; } catch { throw hostError('无法核对Windows宿主创建、用户或可执行身份;不会复用或停止未知进程。', 'HOST_PROCESS_UNVERIFIED'); } } +// Same identity and limits as binaryIdentity for a file already checked by treeFile. +export function treeFileIdentity({ path: absolute, stat }) { + if (stat.size > 256 * 1024 * 1024) throw hostError('宿主可执行文件身份无效。'); + const bytes = fs.readFileSync(absolute); + if (bytes.length !== stat.size) throw hostError('宿主文件在核对期间发生变化。'); + return { path: absolute, bytes: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') }; +} export function binaryIdentity(file) { assertLocalTree(file); const absolute = fs.realpathSync.native(file), stat = fs.lstatSync(absolute); diff --git a/tests/desktop-install.test.mjs b/tests/desktop-install.test.mjs index 9f2c16b1..4e88b307 100644 --- a/tests/desktop-install.test.mjs +++ b/tests/desktop-install.test.mjs @@ -7,6 +7,7 @@ import { createHash } from 'node:crypto'; import { fixture, workspace } from './helpers.mjs'; import { InstallationManager, validateInstalledVersion, snapshotPersistentData } from '../src/core/desktop/install-manager.mjs'; import { inspectHostInstallation } from '../src/core/desktop/app-installation.mjs'; +import { treeFile } from '../src/core/desktop/file-state.mjs'; const hash = value => createHash('sha256').update(value).digest('hex'); function candidate(f, name = 'owned-a', bootstrapBytes = 'declared-static-unit-fixture') { @@ -29,6 +30,19 @@ test('full candidate validation returns the exact loaded-input host identity and fs.writeFileSync(path.join(root, 'extra.txt'), 'unknown'); assert.throws(() => validateInstalledVersion(root)); fs.unlinkSync(path.join(root, 'extra.txt')); fs.appendFileSync(path.join(root, 'dist-server/server.mjs'), '\nchanged'); assert.throws(() => validateInstalledVersion(root)); }); +test('fast per-file scan still rejects a junctioned subdirectory, a hard-linked file and a stream path with the original bytes intact', t => { + const f = fixture(t), root = candidate(f), identity = validateInstalledVersion(root); + const server = path.join(root, 'dist-server'), moved = path.join(f.root, 'outside-server'); + fs.renameSync(server, moved); fs.symlinkSync(moved, server, 'junction'); + assert.throws(() => validateInstalledVersion(root), /链接|重解析/); assert.throws(() => inspectHostInstallation(root), /链接|重解析/); + fs.rmdirSync(server); assert.ok(fs.existsSync(path.join(moved, 'server.mjs'))); fs.renameSync(moved, server); + assert.deepEqual(validateInstalledVersion(root), identity); + const original = path.join(root, 'dist-server/server.mjs'), alias = path.join(f.root, 'server-alias.mjs'); + fs.linkSync(original, alias); assert.throws(() => validateInstalledVersion(root), /多个路径/); fs.unlinkSync(alias); + assert.throws(() => treeFile(root, 'dist-server/server.mjs:stream'), /路径无效/); + assert.throws(() => treeFile(root, '../outside.txt'), /超出所属目录/); + assert.deepEqual(validateInstalledVersion(root), identity); +}); test('installation requires separate absolute program/data directories and a candidate in its own versions namespace', t => { const f = fixture(t), root = candidate(f); assert.throws(() => new InstallationManager({ installRoot: f.root, dataRoot: f.data }));