Skip to content

Commit d61eda9

Browse files
committed
Implement safe config file tree editor
1 parent 56416da commit d61eda9

15 files changed

Lines changed: 893 additions & 109 deletions

File tree

‎.changeset/ten-poets-tickle.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
"@fraqjs/cli": patch
3+
"@fraqjs/cli-protocol": patch
4+
"@fraqjs/plugin-cli-integration": patch
5+
---
6+
7+
实现配置文件树编辑器

‎packages/cli-protocol/src/index.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ export const MAX_LOG_BYTES = 4 * 1024 * 1024;
44
export const MAX_LOG_LINE_BYTES = 16 * 1024;
55
export const MAX_LOG_BATCH_BYTES = 256 * 1024;
66
export const MAX_CONFIG_BYTES = 1024 * 1024;
7+
export const MAX_CONFIG_TOTAL_BYTES = 4 * 1024 * 1024;
8+
export const MAX_CONFIG_FILES = 128;
79
export const REQUEST_TIMEOUT_MS = 10_000;
810
export const LOG_POLL_MS = 250;
911

@@ -25,6 +27,25 @@ export interface ConfigDocument {
2527
revision: string;
2628
}
2729

30+
export type ConfigFile = {
31+
id: string;
32+
name: string;
33+
format: 'yaml' | 'json' | 'text';
34+
main: boolean;
35+
} & ({ editable: true; content: string } | { editable: false; reason: string });
36+
37+
export interface ConfigWorkspace {
38+
root: string;
39+
revision: string;
40+
files: ConfigFile[];
41+
error?: string;
42+
}
43+
44+
export interface ConfigChanges {
45+
revision: string;
46+
files: { id: string; content: string }[];
47+
}
48+
2849
export interface AppStatus {
2950
session: string;
3051
state: 'starting' | 'running' | 'restarting' | 'stopped';
@@ -62,6 +83,8 @@ export interface Methods {
6283
status: { input: undefined; output: AppStatus };
6384
config: { input: undefined; output: ConfigDocument };
6485
save: { input: { content: string; revision: string }; output: ConfigDocument };
86+
configFiles: { input: undefined; output: ConfigWorkspace };
87+
saveFiles: { input: ConfigChanges; output: ConfigWorkspace };
6588
restart: { input: undefined; output: { accepted: true } };
6689
logs: { input: LogCursor; output: LogBatch };
6790
}

‎packages/cli/src/app/control.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,14 +30,22 @@ export class CliControl {
3030
if (this.closed) throw new ControlError('unavailable', 'CLI 会话正在退出。');
3131
switch (request.method) {
3232
case 'hello':
33-
response.result = { version: PROTOCOL_VERSION, capabilities: ['config', 'restart', 'logs'] };
33+
response.result = { version: PROTOCOL_VERSION, capabilities: ['config', 'config-files', 'restart', 'logs'] };
3434
break;
3535
case 'status':
3636
response.result = this.getStatus();
3737
break;
3838
case 'config':
3939
response.result = this.editor.read();
4040
break;
41+
case 'configFiles':
42+
response.result = this.editor.list();
43+
break;
44+
case 'saveFiles':
45+
if (this.getStatus().busy) throw new ControlError('busy', '正在应用配置,请稍后保存。');
46+
response.result = this.editor.saveFiles(request.input);
47+
this.logs.message('Configuration files saved from WebUI; waiting for the watcher to apply them.');
48+
break;
4149
case 'logs':
4250
response.result = this.logs.read(request.input, MAX_LOG_BATCH_BYTES);
4351
break;

‎packages/cli/src/config/editor.ts‎

Lines changed: 124 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,145 @@
1-
import { type ConfigDocument, ControlError, MAX_CONFIG_BYTES } from '@fraqjs/cli-protocol';
1+
import { type ConfigChanges, type ConfigDocument, type ConfigWorkspace, ControlError } from '@fraqjs/cli-protocol';
22
import z from 'zod';
33

4+
import { type FileEdit, FileRegistry } from './files';
45
import { parseConfigText } from './references';
56
import { findConfigPath } from './shared';
67
import { ConfigV1 } from './v1';
78

8-
import { createHash, randomUUID } from 'node:crypto';
9-
import { readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
9+
import { randomUUID } from 'node:crypto';
10+
import { chmodSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
1011
import path from 'node:path';
1112

1213
export class ConfigEditor {
14+
constructor(private readonly replaceFile = renameSync) {}
15+
16+
private scan(): { registry: FileRegistry; workspace: ConfigWorkspace } {
17+
const registry = new FileRegistry(findConfigPath());
18+
let failed = false;
19+
try {
20+
const resolved = parseConfigText(registry.read(registry.mainPath), registry.mainPath, {
21+
onFileAccess: (file, kind) => registry.access(file, kind),
22+
readFile: (file) => registry.read(file),
23+
onError: () => {
24+
failed = true;
25+
},
26+
});
27+
if (!ConfigV1.safeParse(resolved).success) failed = true;
28+
} catch {
29+
failed = true;
30+
}
31+
return {
32+
registry,
33+
workspace: {
34+
root: registry.root,
35+
revision: registry.revision,
36+
files: registry.list(),
37+
...(failed ? { error: '配置或引用存在错误,请修复后保存。' } : {}),
38+
},
39+
};
40+
}
41+
42+
list(): ConfigWorkspace {
43+
return this.scan().workspace;
44+
}
45+
1346
read(): ConfigDocument {
14-
const file = findConfigPath();
15-
if (statSync(file).size > MAX_CONFIG_BYTES) throw new ControlError('invalid', '配置文件超过 1 MiB,无法在线编辑。');
16-
const content = readFileSync(file, 'utf8');
17-
const revision = createHash('sha256').update(realpathSync(file)).update('\0').update(content).digest('hex');
18-
return { name: path.basename(file), format: file.endsWith('.json') ? 'json' : 'yaml', content, revision };
47+
const workspace = this.list();
48+
const main = workspace.files.find((file) => file.main);
49+
if (!main?.editable || main.format === 'text') throw new ControlError('invalid', '主配置无法在线编辑。');
50+
return { name: main.name, format: main.format, content: main.content, revision: workspace.revision };
1951
}
2052

2153
save(content: string, revision: string): ConfigDocument {
22-
if (Buffer.byteLength(content) > MAX_CONFIG_BYTES) throw new ControlError('invalid', '配置文件不能超过 1 MiB。');
23-
if (this.read().revision !== revision)
24-
throw new ControlError('conflict', '配置已被其他操作修改,请重新读取后再保存。');
25-
const file = findConfigPath();
54+
const main = this.list().files.find((file) => file.main);
55+
if (!main) throw new ControlError('invalid', '找不到主配置。');
56+
this.saveFiles({ revision, files: [{ id: main.id, content }] });
57+
return this.read();
58+
}
59+
60+
saveFiles(changes: ConfigChanges): ConfigWorkspace {
61+
const { registry, workspace } = this.scan();
62+
if (workspace.revision !== changes.revision)
63+
throw new ControlError('conflict', '配置或引用文件已被修改,请重新读取后再保存。');
64+
const edits = registry.edits(changes.files);
65+
if (!edits.length) throw new ControlError('invalid', '没有需要保存的文件。');
66+
const overlays = new Map(edits.map((edit) => [edit.target, edit.content]));
67+
const validation = new FileRegistry(registry.mainPath);
68+
let resolved: unknown;
2669
try {
27-
const result = ConfigV1.safeParse(parseConfigText(content, file));
28-
if (!result.success) throw new Error(z.prettifyError(result.error));
29-
} catch (error) {
30-
throw new ControlError('invalid', error instanceof Error ? error.message : String(error));
70+
resolved = parseConfigText(
71+
overlays.get(realpathSync(registry.mainPath)) ?? registry.read(registry.mainPath),
72+
registry.mainPath,
73+
{
74+
onFileAccess: (file, kind) => validation.access(file, kind),
75+
readFile: (file) => overlays.get(realpathSync(file)) ?? validation.read(file),
76+
},
77+
);
78+
} catch {
79+
// Parser errors can contain excerpts from references outside the editable directory.
80+
throw new ControlError('invalid', '无法解析配置或引用文件,请检查语法、引用路径和环境变量。');
81+
}
82+
validation.validateBudget(overlays);
83+
const result = ConfigV1.safeParse(resolved);
84+
if (!result.success) {
85+
const outside = validation.list().some((file) => !file.editable && file.reason === '超出编辑范围');
86+
throw new ControlError('invalid', outside ? '配置字段类型或结构不符合要求。' : z.prettifyError(result.error));
3187
}
32-
const target = realpathSync(file);
33-
const temporary = path.join(path.dirname(target), `.${path.basename(target)}.${randomUUID()}.tmp`);
88+
89+
const staged: (FileEdit & { temporary: string; backup: string; committed: boolean })[] = [];
90+
let preserveBackups = false;
3491
try {
35-
writeFileSync(temporary, content, { mode: statSync(target).mode & 0o777, flag: 'wx' });
36-
if (this.read().revision !== revision || realpathSync(findConfigPath()) !== target) {
37-
throw new ControlError('conflict', '保存期间配置发生变化,请重新读取。');
92+
for (const edit of edits) {
93+
const prefix = path.join(path.dirname(edit.target), `.${path.basename(edit.target)}.${randomUUID()}`);
94+
const entry = {
95+
...edit,
96+
temporary: `${prefix}.tmp`,
97+
backup: `${prefix}.bak`,
98+
committed: false,
99+
};
100+
staged.push(entry);
101+
writeFileSync(entry.temporary, edit.content, { mode: edit.mode, flag: 'wx' });
102+
writeFileSync(entry.backup, edit.original, { mode: edit.mode, flag: 'wx' });
103+
chmodSync(entry.temporary, edit.mode);
104+
chmodSync(entry.backup, edit.mode);
105+
}
106+
if (findConfigPath() !== registry.mainPath || !registry.unchanged() || !validation.unchanged()) {
107+
throw new ControlError('conflict', '保存期间配置或引用文件发生变化。');
38108
}
39-
renameSync(temporary, target);
40-
return this.read();
109+
// No await: watcher callbacks cannot start a reload between these replacements.
110+
for (const edit of staged) {
111+
if (
112+
edit.paths.some((file) => realpathSync(file) !== edit.target) ||
113+
!readFileSync(edit.target).equals(edit.original)
114+
) {
115+
throw new ControlError('conflict', '保存期间文件或符号链接发生变化。');
116+
}
117+
this.replaceFile(edit.temporary, edit.target);
118+
edit.committed = true;
119+
}
120+
} catch (error) {
121+
for (const entry of staged.filter((entry) => entry.committed).reverse()) {
122+
try {
123+
if (realpathSync(entry.target) !== entry.target || readFileSync(entry.target, 'utf8') !== entry.content)
124+
throw new Error('changed');
125+
this.replaceFile(entry.backup, entry.target);
126+
} catch {
127+
preserveBackups = true;
128+
}
129+
}
130+
if (preserveBackups)
131+
throw new ControlError(
132+
'internal',
133+
'保存失败且无法完整恢复;原文件备份保留在同目录的 .bak 文件中,请通过终端处理。',
134+
);
135+
if (error instanceof ControlError) throw error;
136+
throw new ControlError('internal', '文件写入失败,已恢复原内容。');
41137
} finally {
42-
rmSync(temporary, { force: true });
138+
for (const entry of staged) {
139+
rmSync(entry.temporary, { force: true });
140+
if (!preserveBackups) rmSync(entry.backup, { force: true });
141+
}
43142
}
143+
return this.list();
44144
}
45145
}

0 commit comments

Comments
 (0)