@lumesync/studio 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +229 -2
- package/bin/lumesync-studio.js +7 -0
- package/package.json +33 -4
- package/skills/courseware-authoring/SKILL.md +226 -0
- package/skills/courseware-authoring/references/tools.md +133 -0
- package/src/chat/mailbox.js +307 -0
- package/src/cli/main.js +669 -0
- package/src/core/document.js +349 -0
- package/src/core/errors.js +44 -0
- package/src/core/exporter.js +272 -0
- package/src/core/model.js +305 -0
- package/src/core/rules.js +288 -0
- package/src/core/storage.js +616 -0
- package/src/core/transaction.js +250 -0
- package/src/core/validate.js +503 -0
- package/src/core/zip.js +251 -0
- package/src/editing/operations.js +671 -0
- package/src/editing/session.js +838 -0
- package/src/server/http.js +944 -0
- package/src/server/ws.js +128 -0
- package/src/templates/courseware.js +48 -0
- package/src/templates/init.js +374 -0
- package/src/tools/registry.js +487 -0
- package/ui/app.js +2671 -0
- package/ui/home.html +32 -0
- package/ui/home.js +148 -0
- package/ui/index.html +210 -0
- package/ui/shared/edit-model.js +105 -0
- package/ui/shared/quiz-view.js +455 -0
- package/ui/style.css +1161 -0
|
@@ -0,0 +1,616 @@
|
|
|
1
|
+
// 课件包读写:目录成分、真实路径校验、原子写入、校验和、快照与操作日志。
|
|
2
|
+
// 所有路径都相对授权 root 解析,拒绝穿越与符号链接逃逸;
|
|
3
|
+
// 最终读写目标必须是 root 真实目录内的普通文件。
|
|
4
|
+
|
|
5
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import fsp from 'node:fs/promises';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { isSafeRelative } from '../core/rules.js';
|
|
10
|
+
import { ERROR_CODES, StudioError } from './errors.js';
|
|
11
|
+
|
|
12
|
+
export const STUDIO_DIR = '.studio';
|
|
13
|
+
export const SESSION_FILE = 'session.json';
|
|
14
|
+
export const OPERATION_LOG = 'operations.jsonl';
|
|
15
|
+
const OPERATION_LOG_MAX_BYTES = 2 * 1024 * 1024;
|
|
16
|
+
const OPERATION_LOG_KEEP_LINES = 1000;
|
|
17
|
+
|
|
18
|
+
export function sha256Hex(content) {
|
|
19
|
+
return createHash('sha256').update(content).digest('hex');
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function answerHash(salt, normalized) {
|
|
23
|
+
return createHash('sha256').update(`${salt}${normalized}`).digest('hex');
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function createSalt() {
|
|
27
|
+
return randomBytes(16).toString('hex');
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function assertRelative(relative, code = ERROR_CODES.ROOT_FORBIDDEN) {
|
|
31
|
+
if (!isSafeRelative(relative)) {
|
|
32
|
+
throw new StudioError(code, `路径不在课件包允许范围内:${String(relative)}`, { path: String(relative) }, 400);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// 词法路径解析:只保证字符串解析结果位于 root 内,不跟随符号链接。
|
|
37
|
+
// 需要读写真实文件时必须使用 resolveRealFile。
|
|
38
|
+
export function resolveInside(root, relative, code) {
|
|
39
|
+
assertRelative(relative, code);
|
|
40
|
+
const absolute = path.resolve(root, relative);
|
|
41
|
+
const rootAbsolute = path.resolve(root);
|
|
42
|
+
const relativeCheck = path.relative(rootAbsolute, absolute);
|
|
43
|
+
if (relativeCheck.startsWith('..') || path.isAbsolute(relativeCheck)) {
|
|
44
|
+
throw new StudioError(code ?? ERROR_CODES.ROOT_FORBIDDEN, `路径解析到课件包之外:${relative}`, { path: relative }, 400);
|
|
45
|
+
}
|
|
46
|
+
return absolute;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function realRoot(root, code) {
|
|
50
|
+
try {
|
|
51
|
+
return fs.realpathSync(path.resolve(root));
|
|
52
|
+
} catch {
|
|
53
|
+
throw new StudioError(code ?? ERROR_CODES.ROOT_FORBIDDEN, `课件根目录不可用:${root}`, { root: String(root) }, 400);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// 逐级 lstat + realpath 校验:
|
|
58
|
+
// - 任何一段是符号链接都拒绝;
|
|
59
|
+
// - 最终目标必须是 root 真实目录内的普通文件;
|
|
60
|
+
// - allowMissing 仅允许最后一段不存在(用于创建新文件)。
|
|
61
|
+
export function resolveRealFile(root, relative, { code = ERROR_CODES.ROOT_FORBIDDEN, allowMissing = false } = {}) {
|
|
62
|
+
assertRelative(relative, code);
|
|
63
|
+
const rootReal = realRoot(root, code);
|
|
64
|
+
let current = rootReal;
|
|
65
|
+
const segments = relative.split('/');
|
|
66
|
+
for (let index = 0; index < segments.length; index += 1) {
|
|
67
|
+
const segment = segments[index];
|
|
68
|
+
const candidate = path.join(current, segment);
|
|
69
|
+
let stat;
|
|
70
|
+
try {
|
|
71
|
+
stat = fs.lstatSync(candidate);
|
|
72
|
+
} catch {
|
|
73
|
+
if (allowMissing && index === segments.length - 1) {
|
|
74
|
+
// 父目录已逐级校验;最后一段允许稍后创建。
|
|
75
|
+
return candidate;
|
|
76
|
+
}
|
|
77
|
+
throw new StudioError(code, `课件文件不存在:${relative}`, { path: relative }, 404);
|
|
78
|
+
}
|
|
79
|
+
if (stat.isSymbolicLink()) {
|
|
80
|
+
throw new StudioError(code, `拒绝访问符号链接:${relative}`, { path: relative }, 403);
|
|
81
|
+
}
|
|
82
|
+
if (index < segments.length - 1) {
|
|
83
|
+
if (!stat.isDirectory()) {
|
|
84
|
+
throw new StudioError(code, `路径中间段不是目录:${relative}`, { path: relative }, 400);
|
|
85
|
+
}
|
|
86
|
+
} else if (!stat.isFile()) {
|
|
87
|
+
throw new StudioError(code, `目标不是普通文件:${relative}`, { path: relative }, 400);
|
|
88
|
+
}
|
|
89
|
+
current = candidate;
|
|
90
|
+
}
|
|
91
|
+
const finalReal = fs.realpathSync(current);
|
|
92
|
+
const relativeCheck = path.relative(rootReal, finalReal);
|
|
93
|
+
if (relativeCheck.startsWith('..') || path.isAbsolute(relativeCheck)) {
|
|
94
|
+
throw new StudioError(code, `路径解析到课件包之外:${relative}`, { path: relative }, 403);
|
|
95
|
+
}
|
|
96
|
+
return current;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function relativeFromRoot(root, absolute) {
|
|
100
|
+
return path.relative(path.resolve(root), path.resolve(absolute)).split(path.sep).join('/');
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function existsSync(target) {
|
|
104
|
+
try {
|
|
105
|
+
return fs.lstatSync(target).isFile();
|
|
106
|
+
} catch {
|
|
107
|
+
return false;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// 创建目录时逐级拒绝符号链接,防止把写入引到 root 之外。
|
|
112
|
+
export async function ensureRealDir(root, relative) {
|
|
113
|
+
if (!relative || relative === '.') return realRoot(root);
|
|
114
|
+
assertRelative(relative);
|
|
115
|
+
const rootReal = realRoot(root);
|
|
116
|
+
let current = rootReal;
|
|
117
|
+
for (const segment of relative.split('/')) {
|
|
118
|
+
const candidate = path.join(current, segment);
|
|
119
|
+
let stat = null;
|
|
120
|
+
try {
|
|
121
|
+
stat = await fsp.lstat(candidate);
|
|
122
|
+
} catch {
|
|
123
|
+
stat = null;
|
|
124
|
+
}
|
|
125
|
+
if (stat) {
|
|
126
|
+
if (stat.isSymbolicLink()) {
|
|
127
|
+
throw new StudioError(ERROR_CODES.ROOT_FORBIDDEN, `拒绝访问符号链接目录:${relative}`, { path: relative }, 403);
|
|
128
|
+
}
|
|
129
|
+
if (!stat.isDirectory()) {
|
|
130
|
+
throw new StudioError(ERROR_CODES.ROOT_FORBIDDEN, `路径中间段不是目录:${relative}`, { path: relative }, 400);
|
|
131
|
+
}
|
|
132
|
+
} else {
|
|
133
|
+
await fsp.mkdir(candidate, { mode: 0o755 });
|
|
134
|
+
}
|
|
135
|
+
current = candidate;
|
|
136
|
+
}
|
|
137
|
+
return current;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export async function readJson(absolutePath) {
|
|
141
|
+
const text = await fsp.readFile(absolutePath, 'utf8');
|
|
142
|
+
return { text, value: JSON.parse(text) };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export function jsonText(value) {
|
|
146
|
+
return `${JSON.stringify(value, null, 2)}\n`;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// 先写临时文件再 rename,避免中断产生半份 JSON。
|
|
150
|
+
export async function writeFileAtomic(absolutePath, content, { mode = 0o644 } = {}) {
|
|
151
|
+
const directory = path.dirname(absolutePath);
|
|
152
|
+
await fsp.mkdir(directory, { recursive: true });
|
|
153
|
+
const temporary = path.join(directory, `.${path.basename(absolutePath)}.tmp-${process.pid}-${Date.now()}-${randomBytes(3).toString('hex')}`);
|
|
154
|
+
try {
|
|
155
|
+
const handle = await fsp.open(temporary, 'w', mode);
|
|
156
|
+
try {
|
|
157
|
+
await handle.writeFile(content);
|
|
158
|
+
await handle.sync();
|
|
159
|
+
} finally {
|
|
160
|
+
await handle.close();
|
|
161
|
+
}
|
|
162
|
+
await fsp.rename(temporary, absolutePath);
|
|
163
|
+
await fsp.chmod(absolutePath, mode).catch(() => {});
|
|
164
|
+
} catch (error) {
|
|
165
|
+
await fsp.rm(temporary, { force: true }).catch(() => {});
|
|
166
|
+
throw new StudioError(ERROR_CODES.STORAGE_WRITE_FAILED, `写入失败:${path.basename(absolutePath)}`, { reason: error.message }, 500);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export async function writeJsonAtomic(absolutePath, value, options) {
|
|
171
|
+
await writeFileAtomic(absolutePath, jsonText(value), options);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// 包内可枚举文件:排除 .studio、点文件、符号链接与 checksums.json。
|
|
175
|
+
// includeChecksums 供快照与导出使用;符号链接永远不进入清单。
|
|
176
|
+
export function listPackageFiles(root, { includeChecksums = false } = {}) {
|
|
177
|
+
const result = [];
|
|
178
|
+
const walk = (directory) => {
|
|
179
|
+
let entries;
|
|
180
|
+
try {
|
|
181
|
+
entries = fs.readdirSync(directory, { withFileTypes: true });
|
|
182
|
+
} catch {
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
for (const entry of entries) {
|
|
186
|
+
if (entry.name.startsWith('.')) continue;
|
|
187
|
+
const absolute = path.join(directory, entry.name);
|
|
188
|
+
if (entry.isSymbolicLink()) continue;
|
|
189
|
+
if (entry.isDirectory()) walk(absolute);
|
|
190
|
+
else if (entry.isFile()) {
|
|
191
|
+
const relative = relativeFromRoot(root, absolute);
|
|
192
|
+
if (relative === 'checksums.json' && !includeChecksums) continue;
|
|
193
|
+
result.push(relative);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
walk(path.resolve(root));
|
|
198
|
+
return result.sort();
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export async function computeChecksums(root) {
|
|
202
|
+
const files = {};
|
|
203
|
+
for (const relative of listPackageFiles(root)) {
|
|
204
|
+
const content = await fsp.readFile(resolveRealFile(root, relative));
|
|
205
|
+
files[relative] = sha256Hex(content);
|
|
206
|
+
}
|
|
207
|
+
return { algorithm: 'sha256', files };
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
export function readChecksumFile(root, name = 'checksums.json') {
|
|
211
|
+
let absolute;
|
|
212
|
+
try {
|
|
213
|
+
absolute = resolveRealFile(root, name);
|
|
214
|
+
} catch {
|
|
215
|
+
return null;
|
|
216
|
+
}
|
|
217
|
+
try {
|
|
218
|
+
const value = JSON.parse(fs.readFileSync(absolute, 'utf8'));
|
|
219
|
+
return value && typeof value === 'object' ? value : null;
|
|
220
|
+
} catch {
|
|
221
|
+
return null;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
export function verifyChecksums(root, manifest, checksums) {
|
|
226
|
+
const diagnostics = [];
|
|
227
|
+
const declared = manifest.checksums;
|
|
228
|
+
if (!declared) return diagnostics;
|
|
229
|
+
if (declared !== 'checksums.json') {
|
|
230
|
+
diagnostics.push({ code: 'S027', level: 'error', path: 'manifest.json#checksums', message: 'checksums 只能指向 checksums.json' });
|
|
231
|
+
return diagnostics;
|
|
232
|
+
}
|
|
233
|
+
if (!checksums) {
|
|
234
|
+
diagnostics.push({ code: 'K001', level: 'error', path: declared, message: 'checksums.json 缺失或不可读' });
|
|
235
|
+
return diagnostics;
|
|
236
|
+
}
|
|
237
|
+
if (checksums.algorithm !== 'sha256') {
|
|
238
|
+
diagnostics.push({ code: 'K002', level: 'error', path: declared, message: `不支持的校验算法 ${checksums.algorithm}` });
|
|
239
|
+
return diagnostics;
|
|
240
|
+
}
|
|
241
|
+
const files = checksums.files && typeof checksums.files === 'object' ? checksums.files : {};
|
|
242
|
+
for (const [relative, expected] of Object.entries(files)) {
|
|
243
|
+
if (!isSafeRelative(relative)) {
|
|
244
|
+
diagnostics.push({ code: 'K006', level: 'error', path: relative, message: '校验清单中的路径必须位于课件包内' });
|
|
245
|
+
continue;
|
|
246
|
+
}
|
|
247
|
+
let absolute;
|
|
248
|
+
try {
|
|
249
|
+
absolute = resolveRealFile(root, relative);
|
|
250
|
+
} catch {
|
|
251
|
+
diagnostics.push({ code: 'K003', level: 'error', path: relative, message: '校验清单中的文件缺失或不可安全读取' });
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
const actual = sha256Hex(fs.readFileSync(absolute));
|
|
255
|
+
if (actual !== expected) {
|
|
256
|
+
diagnostics.push({ code: 'K004', level: 'error', path: relative, message: `SHA-256 不匹配:期望 ${expected},实际 ${actual}` });
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
for (const relative of listPackageFiles(root)) {
|
|
260
|
+
if (!Object.hasOwn(files, relative)) {
|
|
261
|
+
diagnostics.push({ code: 'K007', level: 'warning', path: relative, message: '文件未纳入 checksums.json,包可能被篡改或遗漏' });
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
return diagnostics;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
export function contentType(relative) {
|
|
268
|
+
const extension = String(relative).split('.').pop().toLowerCase();
|
|
269
|
+
switch (extension) {
|
|
270
|
+
case 'html': return 'text/html; charset=utf-8';
|
|
271
|
+
case 'css': return 'text/css; charset=utf-8';
|
|
272
|
+
case 'js': case 'mjs': return 'text/javascript; charset=utf-8';
|
|
273
|
+
case 'json': return 'application/json; charset=utf-8';
|
|
274
|
+
case 'md': return 'text/markdown; charset=utf-8';
|
|
275
|
+
case 'svg': return 'image/svg+xml';
|
|
276
|
+
case 'png': return 'image/png';
|
|
277
|
+
case 'jpg': case 'jpeg': return 'image/jpeg';
|
|
278
|
+
case 'gif': return 'image/gif';
|
|
279
|
+
case 'webp': return 'image/webp';
|
|
280
|
+
case 'mp3': return 'audio/mpeg';
|
|
281
|
+
case 'mp4': return 'video/mp4';
|
|
282
|
+
case 'woff': return 'font/woff';
|
|
283
|
+
case 'woff2': return 'font/woff2';
|
|
284
|
+
default: return 'application/octet-stream';
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
export const COURSEWARE_CSP =
|
|
289
|
+
"default-src 'none'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; " +
|
|
290
|
+
"img-src 'self' data: blob:; media-src 'self' data: blob:; font-src 'self' data:; " +
|
|
291
|
+
"connect-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'";
|
|
292
|
+
|
|
293
|
+
export async function ensureStudioDir(root) {
|
|
294
|
+
const rootReal = realRoot(root);
|
|
295
|
+
const studioDir = path.join(rootReal, STUDIO_DIR);
|
|
296
|
+
try {
|
|
297
|
+
const stat = await fsp.lstat(studioDir);
|
|
298
|
+
if (stat.isSymbolicLink()) {
|
|
299
|
+
throw new StudioError(ERROR_CODES.ROOT_FORBIDDEN, '拒绝使用符号链接形式的 .studio 目录', { path: STUDIO_DIR }, 403);
|
|
300
|
+
}
|
|
301
|
+
if (!stat.isDirectory()) {
|
|
302
|
+
throw new StudioError(ERROR_CODES.ROOT_FORBIDDEN, '.studio 不是目录', { path: STUDIO_DIR }, 403);
|
|
303
|
+
}
|
|
304
|
+
} catch (error) {
|
|
305
|
+
if (error instanceof StudioError) throw error;
|
|
306
|
+
if (error.code !== 'ENOENT') throw error;
|
|
307
|
+
await fsp.mkdir(studioDir, { recursive: true, mode: 0o700 });
|
|
308
|
+
}
|
|
309
|
+
const history = path.join(studioDir, 'history');
|
|
310
|
+
try {
|
|
311
|
+
const stat = await fsp.lstat(history);
|
|
312
|
+
if (stat.isSymbolicLink()) {
|
|
313
|
+
throw new StudioError(ERROR_CODES.ROOT_FORBIDDEN, '拒绝使用符号链接形式的历史目录', { path: `${STUDIO_DIR}/history` }, 403);
|
|
314
|
+
}
|
|
315
|
+
if (!stat.isDirectory()) {
|
|
316
|
+
throw new StudioError(ERROR_CODES.ROOT_FORBIDDEN, '.studio/history 不是目录', { path: `${STUDIO_DIR}/history` }, 403);
|
|
317
|
+
}
|
|
318
|
+
} catch (error) {
|
|
319
|
+
if (error instanceof StudioError) throw error;
|
|
320
|
+
if (error.code !== 'ENOENT') throw error;
|
|
321
|
+
await fsp.mkdir(history, { recursive: true, mode: 0o700 });
|
|
322
|
+
}
|
|
323
|
+
await fsp.chmod(studioDir, 0o700).catch(() => {});
|
|
324
|
+
return studioDir;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
async function assertRegularOrMissing(target, pathLabel) {
|
|
328
|
+
try {
|
|
329
|
+
const stat = await fsp.lstat(target);
|
|
330
|
+
if (stat.isSymbolicLink()) {
|
|
331
|
+
throw new StudioError(ERROR_CODES.ROOT_FORBIDDEN, `拒绝访问符号链接:${pathLabel}`, { path: pathLabel }, 403);
|
|
332
|
+
}
|
|
333
|
+
if (!stat.isFile()) {
|
|
334
|
+
throw new StudioError(ERROR_CODES.ROOT_FORBIDDEN, `目标不是普通文件:${pathLabel}`, { path: pathLabel }, 403);
|
|
335
|
+
}
|
|
336
|
+
} catch (error) {
|
|
337
|
+
if (error instanceof StudioError) throw error;
|
|
338
|
+
if (error.code !== 'ENOENT') throw error;
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
// 日志脱敏:编辑计划写入前删除所有答案材料,只保留是否需要配置/是否变化。
|
|
343
|
+
export function sanitizeOperationsForLog(value) {
|
|
344
|
+
const visit = (node, key = '') => {
|
|
345
|
+
if (Array.isArray(node)) return node.map((item) => visit(item));
|
|
346
|
+
if (!node || typeof node !== 'object') return node;
|
|
347
|
+
const result = {};
|
|
348
|
+
for (const [childKey, childValue] of Object.entries(node)) {
|
|
349
|
+
if (['answer', 'answerHash', 'answerSalt', 'referenceAnswer'].includes(childKey)) {
|
|
350
|
+
continue;
|
|
351
|
+
}
|
|
352
|
+
if (childKey === 'answerKeys') {
|
|
353
|
+
result.answerKeysCount = Array.isArray(childValue) ? childValue.length : 0;
|
|
354
|
+
continue;
|
|
355
|
+
}
|
|
356
|
+
if (childKey === 'explain') {
|
|
357
|
+
result.explainConfigured = childValue !== undefined && childValue !== null && childValue !== '';
|
|
358
|
+
continue;
|
|
359
|
+
}
|
|
360
|
+
if (childKey === 'rubric' && Array.isArray(childValue)) {
|
|
361
|
+
result.rubricCount = childValue.length;
|
|
362
|
+
continue;
|
|
363
|
+
}
|
|
364
|
+
result[childKey] = visit(childValue, childKey);
|
|
365
|
+
}
|
|
366
|
+
if (key === 'value' && node.answer !== undefined) result.answerConfigured = true;
|
|
367
|
+
if (key === 'grading' && node.referenceAnswer !== undefined) result.referenceConfigured = true;
|
|
368
|
+
return result;
|
|
369
|
+
};
|
|
370
|
+
return visit(value);
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
async function rotateOperationLog(file) {
|
|
374
|
+
await assertRegularOrMissing(file, `${STUDIO_DIR}/${OPERATION_LOG}`);
|
|
375
|
+
try {
|
|
376
|
+
const stat = await fsp.stat(file);
|
|
377
|
+
if (stat.size <= OPERATION_LOG_MAX_BYTES) return;
|
|
378
|
+
const text = await fsp.readFile(file, 'utf8').catch(() => '');
|
|
379
|
+
const lines = text.split('\n').filter(Boolean).slice(-OPERATION_LOG_KEEP_LINES);
|
|
380
|
+
await fsp.rm(`${file}.1`, { force: true }).catch(() => {});
|
|
381
|
+
await fsp.rename(file, `${file}.1`).catch(() => {});
|
|
382
|
+
await writeFileAtomic(file, `${lines.join('\n')}${lines.length ? '\n' : ''}`, { mode: 0o600 });
|
|
383
|
+
} catch (error) {
|
|
384
|
+
if (error instanceof StudioError) throw error;
|
|
385
|
+
// 日志轮转失败不阻塞编辑事务;写日志本身仍会在调用方检查失败。
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
export async function appendOperationLog(root, record) {
|
|
390
|
+
const studioDir = await ensureStudioDir(root);
|
|
391
|
+
const file = path.join(studioDir, OPERATION_LOG);
|
|
392
|
+
await assertRegularOrMissing(file, `${STUDIO_DIR}/${OPERATION_LOG}`);
|
|
393
|
+
await rotateOperationLog(file);
|
|
394
|
+
try {
|
|
395
|
+
await fsp.appendFile(file, `${JSON.stringify(record)}\n`, { mode: 0o600 });
|
|
396
|
+
await fsp.chmod(file, 0o600).catch(() => {});
|
|
397
|
+
} catch (error) {
|
|
398
|
+
throw new StudioError(ERROR_CODES.STORAGE_WRITE_FAILED, '操作日志写入失败', { reason: error.message }, 500);
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
// 事务开始前准备日志:先轮转,再返回当前大小作为回滚截断点。
|
|
403
|
+
export async function prepareOperationLog(root) {
|
|
404
|
+
const studioDir = await ensureStudioDir(root);
|
|
405
|
+
const file = path.join(studioDir, OPERATION_LOG);
|
|
406
|
+
await assertRegularOrMissing(file, `${STUDIO_DIR}/${OPERATION_LOG}`);
|
|
407
|
+
await rotateOperationLog(file);
|
|
408
|
+
return fsp.stat(file).then((stat) => stat.size).catch(() => 0);
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
export async function truncateOperationLog(file, size) {
|
|
412
|
+
try {
|
|
413
|
+
await assertRegularOrMissing(file, `${STUDIO_DIR}/${OPERATION_LOG}`);
|
|
414
|
+
await fsp.truncate(file, size);
|
|
415
|
+
} catch {
|
|
416
|
+
// 回滚时的尽力而为;日志损坏不应掩盖主错误。
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
export async function readOperationLog(root, limit = 200) {
|
|
421
|
+
let file;
|
|
422
|
+
try {
|
|
423
|
+
file = resolveRealFile(root, `${STUDIO_DIR}/${OPERATION_LOG}`);
|
|
424
|
+
} catch {
|
|
425
|
+
return [];
|
|
426
|
+
}
|
|
427
|
+
let text;
|
|
428
|
+
try {
|
|
429
|
+
text = await fsp.readFile(file, 'utf8');
|
|
430
|
+
} catch {
|
|
431
|
+
return [];
|
|
432
|
+
}
|
|
433
|
+
const lines = text.split('\n').filter(Boolean);
|
|
434
|
+
return lines.slice(-limit).map((line) => {
|
|
435
|
+
try {
|
|
436
|
+
return JSON.parse(line);
|
|
437
|
+
} catch {
|
|
438
|
+
return { malformed: true, line };
|
|
439
|
+
}
|
|
440
|
+
});
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
// 快照:保存可恢复的正式文件(含 checksums.json),不含 .studio。
|
|
444
|
+
export async function createSnapshot(root, revision) {
|
|
445
|
+
const studioDir = await ensureStudioDir(root);
|
|
446
|
+
const target = path.join(studioDir, 'history', String(revision).padStart(6, '0'));
|
|
447
|
+
const snapshotPath = path.join(target, 'snapshot.json');
|
|
448
|
+
if (existsSync(snapshotPath)) return revision;
|
|
449
|
+
|
|
450
|
+
const files = {};
|
|
451
|
+
const contents = new Map();
|
|
452
|
+
for (const relative of listPackageFiles(root, { includeChecksums: true })) {
|
|
453
|
+
const content = await fsp.readFile(resolveRealFile(root, relative));
|
|
454
|
+
contents.set(relative, content);
|
|
455
|
+
files[relative] = sha256Hex(content);
|
|
456
|
+
}
|
|
457
|
+
const staging = path.join(studioDir, 'history', `.${String(revision).padStart(6, '0')}-staging`);
|
|
458
|
+
await fsp.rm(staging, { recursive: true, force: true }).catch(() => {});
|
|
459
|
+
for (const [relative, content] of contents) {
|
|
460
|
+
const destination = path.join(staging, 'files', relative);
|
|
461
|
+
await fsp.mkdir(path.dirname(destination), { recursive: true, mode: 0o700 });
|
|
462
|
+
await fsp.writeFile(destination, content);
|
|
463
|
+
}
|
|
464
|
+
await writeJsonAtomic(path.join(staging, 'snapshot.json'), {
|
|
465
|
+
revision,
|
|
466
|
+
createdAt: new Date().toISOString(),
|
|
467
|
+
files,
|
|
468
|
+
});
|
|
469
|
+
await fsp.rm(target, { recursive: true, force: true }).catch(() => {});
|
|
470
|
+
await fsp.rename(staging, target);
|
|
471
|
+
return revision;
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
export async function listSnapshots(root) {
|
|
475
|
+
const studioDir = await ensureStudioDir(root);
|
|
476
|
+
const directory = path.join(studioDir, 'history');
|
|
477
|
+
try {
|
|
478
|
+
const entries = await fsp.readdir(directory, { withFileTypes: true });
|
|
479
|
+
return entries
|
|
480
|
+
.filter((entry) => entry.isDirectory() && /^\d{6}$/.test(entry.name))
|
|
481
|
+
.map((entry) => Number(entry.name))
|
|
482
|
+
.sort((left, right) => right - left);
|
|
483
|
+
} catch {
|
|
484
|
+
return [];
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
export async function readSnapshot(root, revision) {
|
|
489
|
+
if (!Number.isInteger(revision) || revision < 0) {
|
|
490
|
+
throw new StudioError(ERROR_CODES.OPERATION_INVALID, 'revision 必须是非负整数', { revision }, 400);
|
|
491
|
+
}
|
|
492
|
+
const studioDir = await ensureStudioDir(root);
|
|
493
|
+
const directory = path.join(studioDir, 'history', String(revision).padStart(6, '0'));
|
|
494
|
+
const snapshotPath = path.join(directory, 'snapshot.json');
|
|
495
|
+
if (!existsSync(snapshotPath)) {
|
|
496
|
+
throw new StudioError(ERROR_CODES.OPERATION_INVALID, `找不到修订快照 ${revision}`, { revision }, 404);
|
|
497
|
+
}
|
|
498
|
+
const snapshot = JSON.parse(await fsp.readFile(snapshotPath, 'utf8'));
|
|
499
|
+
const files = new Map();
|
|
500
|
+
for (const [relative, expected] of Object.entries(snapshot.files ?? {})) {
|
|
501
|
+
const source = path.join(directory, 'files', relative);
|
|
502
|
+
let stat;
|
|
503
|
+
try {
|
|
504
|
+
stat = await fsp.lstat(source);
|
|
505
|
+
} catch {
|
|
506
|
+
throw new StudioError(ERROR_CODES.STORAGE_WRITE_FAILED, `快照文件缺失:${relative}`, { path: relative, revision }, 500);
|
|
507
|
+
}
|
|
508
|
+
if (!stat.isFile() || stat.isSymbolicLink()) {
|
|
509
|
+
throw new StudioError(ERROR_CODES.STORAGE_WRITE_FAILED, `快照文件不可安全读取:${relative}`, { path: relative, revision }, 500);
|
|
510
|
+
}
|
|
511
|
+
const content = await fsp.readFile(source);
|
|
512
|
+
if (sha256Hex(content) !== expected) {
|
|
513
|
+
throw new StudioError(ERROR_CODES.STORAGE_WRITE_FAILED, `快照文件损坏:${relative}`, { path: relative, revision }, 500);
|
|
514
|
+
}
|
|
515
|
+
files.set(relative, content);
|
|
516
|
+
}
|
|
517
|
+
return { revision, createdAt: snapshot.createdAt, files };
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
export async function restoreSnapshot(root, revision) {
|
|
521
|
+
const snapshot = await readSnapshot(root, revision);
|
|
522
|
+
const current = listPackageFiles(root, { includeChecksums: true });
|
|
523
|
+
for (const relative of current) {
|
|
524
|
+
if (!snapshot.files.has(relative)) {
|
|
525
|
+
await fsp.rm(resolveRealFile(root, relative), { force: true }).catch(() => {});
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
for (const [relative, content] of snapshot.files) {
|
|
529
|
+
await writeFileAtomic(resolveRealFile(root, relative, { allowMissing: true }), content);
|
|
530
|
+
}
|
|
531
|
+
return revision;
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
// 历史容量策略:数量与总字节双上限,并始终保留最近两份。
|
|
535
|
+
export async function pruneSnapshots(root, { keep = 30, maxBytes = 200 * 1024 * 1024 } = {}) {
|
|
536
|
+
let studioDir;
|
|
537
|
+
try {
|
|
538
|
+
studioDir = await ensureStudioDir(root);
|
|
539
|
+
} catch {
|
|
540
|
+
return;
|
|
541
|
+
}
|
|
542
|
+
const directory = path.join(studioDir, 'history');
|
|
543
|
+
let entries = [];
|
|
544
|
+
try {
|
|
545
|
+
entries = await fsp.readdir(directory, { withFileTypes: true });
|
|
546
|
+
} catch {
|
|
547
|
+
return;
|
|
548
|
+
}
|
|
549
|
+
const revisions = entries
|
|
550
|
+
.filter((entry) => entry.isDirectory() && /^\d{6}$/.test(entry.name))
|
|
551
|
+
.map((entry) => Number(entry.name))
|
|
552
|
+
.sort((left, right) => right - left);
|
|
553
|
+
let totalBytes = 0;
|
|
554
|
+
for (const [index, revision] of revisions.entries()) {
|
|
555
|
+
const target = path.join(directory, String(revision).padStart(6, '0'));
|
|
556
|
+
let size = 0;
|
|
557
|
+
try {
|
|
558
|
+
size = await directorySize(target);
|
|
559
|
+
} catch {
|
|
560
|
+
size = 0;
|
|
561
|
+
}
|
|
562
|
+
const overCount = index >= keep;
|
|
563
|
+
const overBytes = index >= 2 && totalBytes + size > maxBytes;
|
|
564
|
+
if (overCount || overBytes) {
|
|
565
|
+
await fsp.rm(target, { recursive: true, force: true }).catch(() => {});
|
|
566
|
+
continue;
|
|
567
|
+
}
|
|
568
|
+
totalBytes += size;
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
async function directorySize(directory) {
|
|
573
|
+
let total = 0;
|
|
574
|
+
const entries = await fsp.readdir(directory, { withFileTypes: true });
|
|
575
|
+
for (const entry of entries) {
|
|
576
|
+
const absolute = path.join(directory, entry.name);
|
|
577
|
+
if (entry.isDirectory()) total += await directorySize(absolute);
|
|
578
|
+
else if (entry.isFile()) total += (await fsp.stat(absolute)).size;
|
|
579
|
+
}
|
|
580
|
+
return total;
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
export async function readSessionFile(root) {
|
|
584
|
+
try {
|
|
585
|
+
const absolute = resolveRealFile(root, `${STUDIO_DIR}/${SESSION_FILE}`);
|
|
586
|
+
const text = await fsp.readFile(absolute, 'utf8');
|
|
587
|
+
return JSON.parse(text);
|
|
588
|
+
} catch {
|
|
589
|
+
return null;
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
export async function writeSessionFile(root, value) {
|
|
594
|
+
const studioDir = await ensureStudioDir(root);
|
|
595
|
+
const absolute = path.join(studioDir, SESSION_FILE);
|
|
596
|
+
await assertRegularOrMissing(absolute, `${STUDIO_DIR}/${SESSION_FILE}`);
|
|
597
|
+
await writeJsonAtomic(absolute, value, { mode: 0o600 });
|
|
598
|
+
await fsp.chmod(absolute, 0o600).catch(() => {});
|
|
599
|
+
return absolute;
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
export async function removeSessionFile(root, predicate = null) {
|
|
603
|
+
const studioDir = path.join(realRoot(root), STUDIO_DIR);
|
|
604
|
+
const absolute = path.join(studioDir, SESSION_FILE);
|
|
605
|
+
try {
|
|
606
|
+
await assertRegularOrMissing(absolute, `${STUDIO_DIR}/${SESSION_FILE}`);
|
|
607
|
+
if (predicate) {
|
|
608
|
+
const value = JSON.parse(await fsp.readFile(absolute, 'utf8'));
|
|
609
|
+
if (!predicate(value)) return false;
|
|
610
|
+
}
|
|
611
|
+
await fsp.rm(absolute, { force: true });
|
|
612
|
+
return true;
|
|
613
|
+
} catch {
|
|
614
|
+
return false;
|
|
615
|
+
}
|
|
616
|
+
}
|