Files
Agent-Workbench/src/core/desktop/file-state.mjs
T
2026-11-06 08:35:07 +08:00

77 lines
5.0 KiB
JavaScript

import fs from 'node:fs';
import path from 'node:path';
import { randomUUID } from 'node:crypto';
import { hostError } from '../../shared/contracts/desktop-host.mjs';
const normalized = value => process.platform === 'win32' ? value.toLowerCase() : value;
export const samePath = (a, b) => normalized(path.resolve(a)) === normalized(path.resolve(b));
export function assertLocalTree(absolute, { missing = false } = {}) {
const resolved = path.resolve(absolute), parsed = path.parse(resolved);
let current = parsed.root;
const components = resolved.slice(parsed.root.length).split(path.sep).filter(Boolean);
for (const component of components) {
if (component.includes(':') || component.includes('\0')) throw hostError('本机状态路径格式无效。');
current = path.join(current, component);
let stat;
try { stat = fs.lstatSync(current); }
catch (cause) { if (missing && cause.code === 'ENOENT') return resolved; throw cause; }
if (stat.isSymbolicLink() || !samePath(current, fs.realpathSync.native(current))) throw hostError('本机状态不接受链接或重解析目录。');
if (stat.isFile() && stat.nlink !== 1) throw hostError('本机状态文件具有多个路径。');
}
return resolved;
}
export function ownedChild(root, relative, { missing = false } = {}) {
if (typeof relative !== 'string') throw hostError('本机状态路径无效。');
assertLocalTree(root);
const base = fs.realpathSync.native(root), target = path.resolve(base, relative);
if (path.isAbsolute(relative) || path.win32.isAbsolute(relative) || relative.includes('\0')
|| !normalized(target).startsWith(normalized(base + path.sep))) throw hostError('本机状态路径超出所属目录。');
let existing = target;
while (!fs.existsSync(existing)) {
if (!missing) throw hostError('本机状态文件不存在。', 'HOST_REGISTRATION_MISSING');
const parent = path.dirname(existing); if (parent === existing) throw hostError('本机状态路径无法核对。'); existing = parent;
}
const real = fs.realpathSync.native(existing);
if (!samePath(base, real) && !normalized(real).startsWith(normalized(base + path.sep))) throw hostError('本机状态链接超出所属目录。');
if (fs.lstatSync(existing).isSymbolicLink()) throw hostError('本机状态不接受链接或重解析目录。');
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 };
}
// Installation receipts contain hashes for every retained row and artifact.
// Their size grows with user data; a fixed read cap must not reject a receipt
// we just wrote when marking activation complete or recording its rollback.
export function readState(file, maximum = Infinity) {
assertLocalTree(file);
const stat = fs.lstatSync(file);
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > maximum) throw hostError('本机状态文件格式或作用范围无效。');
try { return JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, '')); }
catch { throw hostError('本机状态文件损坏,请核对原记录。'); }
}
export function writeState(file, value) {
assertLocalTree(file, { missing: true });
const directory = path.dirname(file), temporary = path.join(directory, '.' + path.basename(file) + '-' + randomUUID() + '.tmp');
if (fs.existsSync(file)) readState(file);
try {
const descriptor = fs.openSync(temporary, 'wx', 0o600);
try { fs.writeFileSync(descriptor, JSON.stringify(value, null, 2) + '\n'); fs.fsyncSync(descriptor); } finally { fs.closeSync(descriptor); }
assertLocalTree(file, { missing: true }); fs.renameSync(temporary, file);
}
finally { if (fs.existsSync(temporary)) fs.unlinkSync(temporary); }
}