示例工程 13-project-file-explorer
13-project-file-explorer/app/.tsc/main/services/workspace-service.js
import { randomUUID } from "node:crypto";
import fs from "node:fs/promises";
import path from "node:path";
import { WorkspaceError, } from "../../shared/ipc";
const ALLOWED_EXT = new Set([".md", ".txt", ".json"]);
const MAX_BYTES = 128 * 1024;
const MAX_ENTRIES = 200;
const MAX_DEPTH = 4;
function toPosix(value) {
return value.split(path.sep).join("/");
}
function assertRelative(rel) {
if (rel.includes("\0") || path.isAbsolute(rel)) {
throw new WorkspaceError("PATH_OUTSIDE_WORKSPACE", "只允许工作区内的相对路径", "path");
}
}
function resolveInside(root, rel) {
assertRelative(rel);
const resolved = path.resolve(root, rel);
const relative = path.relative(root, resolved);
if (relative.length === 0 ||
relative.startsWith("..") ||
path.isAbsolute(relative)) {
throw new WorkspaceError("PATH_OUTSIDE_WORKSPACE", "路径越出工作区", "path");
}
return resolved;
}
async function assertRealInside(root, target) {
const realRoot = await fs.realpath(root);
let realTarget;
try {
realTarget = await fs.realpath(target);
}
catch {
realTarget = await fs.realpath(path.dirname(target));
}
const relative = path.relative(realRoot, realTarget);
if (relative.startsWith("..") || path.isAbsolute(relative)) {
throw new WorkspaceError("PATH_OUTSIDE_WORKSPACE", "符号链接指向工作区外", "path");
}
}
function assertExtension(file) {
if (!ALLOWED_EXT.has(path.extname(file).toLowerCase())) {
throw new WorkspaceError("EXTENSION_NOT_ALLOWED", "只允许 .md / .txt / .json", "path");
}
}
async function seed(root) {
await fs.mkdir(path.join(root, "notes"), { recursive: true });
await fs.mkdir(path.join(root, "data"), { recursive: true });
const files = {
"README.md": "# 工作区\n\n这是文件浏览器的演示工作区。\n",
"notes/welcome.md": "# 欢迎\n\n点击左侧文件查看内容,修改后保存。\n",
"notes/todo.md": "- [ ] 阅读第 13 章\n- [ ] 跑一遍越权测试\n",
"data/config.json": '{\n "theme": "light",\n "limit": 50\n}\n',
};
for (const [rel, content] of Object.entries(files)) {
const target = path.join(root, rel);
await fs.mkdir(path.dirname(target), { recursive: true });
await fs.writeFile(target, content, "utf8");
}
// 造一个指向工作区外的符号链接,供越权测试使用。
const outside = path.join(root, "..", "outside-secret.txt");
await fs.writeFile(outside, "SECRET", "utf8");
const link = path.join(root, "escape-link.md");
try {
await fs.rm(link, { force: true });
await fs.symlink(outside, link);
}
catch {
// 某些平台/权限不允许创建符号链接;越权测试会得到 NOT_FOUND。
}
}
export function createWorkspaceService(options) {
const root = options.root;
async function walk(dir, depth, out) {
if (depth > MAX_DEPTH || out.length >= MAX_ENTRIES)
return;
const entries = await fs.readdir(dir, { withFileTypes: true });
for (const entry of entries) {
if (out.length >= MAX_ENTRIES)
return;
if (entry.name.startsWith("."))
continue;
if (entry.isSymbolicLink())
continue;
const full = path.join(dir, entry.name);
const rel = toPosix(path.relative(root, full));
if (entry.isDirectory()) {
out.push({
path: rel,
name: entry.name,
type: "dir",
depth,
sizeBytes: 0,
});
await walk(full, depth + 1, out);
}
else if (entry.isFile()) {
const stat = await fs.stat(full);
out.push({
path: rel,
name: entry.name,
type: "file",
depth,
sizeBytes: stat.size,
});
}
}
}
return {
async ensure() {
await fs.mkdir(root, { recursive: true });
const entries = await fs.readdir(root);
if (entries.length === 0)
await seed(root);
},
async tree() {
await fs.mkdir(root, { recursive: true });
const out = [];
await walk(root, 0, out);
return out;
},
async read(rel) {
const target = resolveInside(root, rel);
assertExtension(target);
await assertRealInside(root, target);
let stat;
try {
stat = await fs.stat(target);
}
catch {
throw new WorkspaceError("NOT_FOUND", "文件不存在", "path");
}
if (!stat.isFile()) {
throw new WorkspaceError("NOT_A_FILE", "目标不是文件", "path");
}
if (stat.size > MAX_BYTES) {
throw new WorkspaceError("TOO_LARGE", "文件超过 128KB 上限", "path");
}
return {
path: toPosix(rel),
content: await fs.readFile(target, "utf8"),
sizeBytes: stat.size,
updatedAt: stat.mtimeMs,
};
},
async save(rel, content) {
const target = resolveInside(root, rel);
assertExtension(target);
await fs.mkdir(path.dirname(target), { recursive: true });
await assertRealInside(root, target);
if (Buffer.byteLength(content, "utf8") > MAX_BYTES) {
throw new WorkspaceError("TOO_LARGE", "文件超过 128KB 上限", "path");
}
const temp = path.join(path.dirname(target), `.${randomUUID()}.tmp`);
await fs.writeFile(temp, content, "utf8");
await fs.rename(temp, target);
const stat = await fs.stat(target);
return {
path: toPosix(rel),
sizeBytes: stat.size,
updatedAt: stat.mtimeMs,
};
},
async reset() {
await fs.rm(root, { recursive: true, force: true });
await fs.mkdir(root, { recursive: true });
await seed(root);
},
};
}
//# sourceMappingURL=workspace-service.js.map