codexmate 0.1.32 → 0.1.34
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 +18 -2
- package/README.vi.md +18 -2
- package/README.zh.md +18 -2
- package/cli/claude-proxy.js +2 -2
- package/cli/local-bridge.js +10 -6
- package/cli/openai-chat-routing.js +38 -0
- package/cli/prompt-history.js +2 -0
- package/cli/routing-bridge.js +143 -0
- package/cli/system-prompt-files.js +75 -53
- package/cli.js +325 -215
- package/lib/cli-config-engine.js +6 -1
- package/lib/cli-file-utils.js +6 -1
- package/lib/config-change-fs.js +132 -0
- package/lib/config-changes.js +293 -0
- package/lib/file-sharing-lan.js +111 -0
- package/lib/file-sharing.js +196 -0
- package/lib/handoff-mcp.js +18 -2
- package/lib/local-feature-store.js +39 -0
- package/lib/model-test-client.js +61 -0
- package/lib/model-test.js +126 -0
- package/lib/routing-groups.js +161 -0
- package/lib/session-bookmarks.js +72 -0
- package/lib/session-context-health.js +23 -3
- package/lib/session-diagnostics.js +75 -0
- package/lib/session-feature-settings.js +21 -0
- package/lib/session-features.js +63 -0
- package/lib/session-handoff-draft.js +43 -0
- package/lib/session-projects.js +76 -0
- package/lib/session-search-index.js +188 -0
- package/lib/thread-handoff.js +8 -0
- package/lib/web-server.js +216 -0
- package/package.json +1 -1
- package/plugins/file-sharing/manifest.mjs +10 -0
- package/plugins/file-sharing/methods.mjs +101 -0
- package/plugins/file-sharing/overview.mjs +3 -0
- package/plugins/file-sharing/ownership.mjs +5 -0
- package/plugins/registry.mjs +3 -0
- package/web-ui/app.js +22 -3
- package/web-ui/index.html +4 -2
- package/web-ui/logic.context-window.mjs +15 -0
- package/web-ui/modules/api.mjs +72 -39
- package/web-ui/modules/app.computed.main-tabs.mjs +3 -0
- package/web-ui/modules/app.methods.agents.mjs +17 -0
- package/web-ui/modules/app.methods.claude-config.mjs +2 -0
- package/web-ui/modules/app.methods.codex-config.mjs +9 -0
- package/web-ui/modules/app.methods.config-changes.mjs +124 -0
- package/web-ui/modules/app.methods.install.mjs +23 -3
- package/web-ui/modules/app.methods.kilocode-config.mjs +2 -0
- package/web-ui/modules/app.methods.navigation.mjs +2 -0
- package/web-ui/modules/app.methods.openclaw-persist.mjs +2 -0
- package/web-ui/modules/app.methods.opencode-config.mjs +2 -0
- package/web-ui/modules/app.methods.pi-config.mjs +12 -3
- package/web-ui/modules/app.methods.prompts-editor.mjs +7 -4
- package/web-ui/modules/app.methods.provider-cache.mjs +9 -3
- package/web-ui/modules/app.methods.providers.mjs +6 -0
- package/web-ui/modules/app.methods.session-actions.mjs +2 -2
- package/web-ui/modules/app.methods.startup-claude.mjs +8 -47
- package/web-ui/modules/app.methods.system-prompt.mjs +88 -17
- package/web-ui/modules/app.methods.theme.mjs +4 -3
- package/web-ui/modules/app.methods.web-ui-preferences.mjs +7 -0
- package/web-ui/modules/config-change-actions.mjs +9 -0
- package/web-ui/modules/i18n/locales/en.mjs +254 -8
- package/web-ui/modules/i18n/locales/ja.mjs +254 -8
- package/web-ui/modules/i18n/locales/vi.mjs +254 -8
- package/web-ui/modules/i18n/locales/zh-tw.mjs +254 -8
- package/web-ui/modules/i18n/locales/zh.mjs +254 -8
- package/web-ui/modules/model-test.mjs +82 -0
- package/web-ui/modules/plugins.methods.mjs +3 -1
- package/web-ui/modules/prompt-ecosystem.methods.mjs +4 -3
- package/web-ui/modules/request-deadline.mjs +33 -0
- package/web-ui/modules/routing.mjs +206 -0
- package/web-ui/modules/session-features.mjs +279 -0
- package/web-ui/modules/thread-handoff.mjs +1 -1
- package/web-ui/partials/index/config-changes.html +25 -0
- package/web-ui/partials/index/context-window-reference.html +17 -0
- package/web-ui/partials/index/layout-header.html +40 -42
- package/web-ui/partials/index/modal-openclaw-config.html +0 -2
- package/web-ui/partials/index/modal-skills.html +0 -1
- package/web-ui/partials/index/modals-basic.html +15 -8
- package/web-ui/partials/index/modals-pi-provider.html +0 -1
- package/web-ui/partials/index/panel-config-codex.html +0 -3
- package/web-ui/partials/index/panel-config-openclaw.html +16 -13
- package/web-ui/partials/index/panel-dashboard.html +0 -2
- package/web-ui/partials/index/panel-plugins.html +3 -10
- package/web-ui/partials/index/panel-prompts.html +13 -8
- package/web-ui/partials/index/panel-routing.html +3 -0
- package/web-ui/partials/index/panel-sessions.html +9 -0
- package/web-ui/partials/index/panel-settings.html +12 -13
- package/web-ui/partials/index/panel-trash.html +0 -1
- package/web-ui/partials/index/plugin-file-sharing.html +47 -0
- package/web-ui/partials/index/routing-model-test.html +53 -0
- package/web-ui/partials/index/session-diagnostics.html +32 -0
- package/web-ui/partials/index/session-features.html +107 -0
- package/web-ui/partials/index/thread-handoff.html +6 -3
- package/web-ui/res/web-ui-render.precompiled.js +1689 -246
- package/web-ui/styles/base-theme.css +1 -1
- package/web-ui/styles/config-changes.css +30 -0
- package/web-ui/styles/modals-core.css +6 -5
- package/web-ui/styles/navigation-panels.css +4 -0
- package/web-ui/styles/openclaw-structured.css +205 -189
- package/web-ui/styles/plugins-panel.css +40 -1
- package/web-ui/styles/responsive.css +10 -5
- package/web-ui/styles/routing.css +78 -0
- package/web-ui/styles/session-features.css +258 -0
- package/web-ui/styles/settings-panel.css +30 -0
- package/web-ui/styles/system-prompt.css +8 -7
- package/web-ui/styles/theme-violet-tokens.css +52 -0
- package/web-ui/styles/theme-violet.css +1736 -0
- package/web-ui/styles.css +5 -1
package/lib/cli-config-engine.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
const crypto = require('crypto');
|
|
2
|
-
const fs = require('fs');
|
|
2
|
+
const { fs, isConfigStaging } = require('./config-change-fs');
|
|
3
3
|
const path = require('path');
|
|
4
4
|
const toml = require('@iarna/toml');
|
|
5
5
|
|
|
@@ -144,6 +144,7 @@ function writeBufferAtomically(filePath, buffer, mode, fsImpl) {
|
|
|
144
144
|
const tmpPath = `${filePath}.tmp-${process.pid}-${Date.now()}-${crypto.randomBytes(4).toString('hex')}`;
|
|
145
145
|
try {
|
|
146
146
|
fsImpl.writeFileSync(tmpPath, buffer, { encoding: 'utf-8', mode });
|
|
147
|
+
fsImpl.chmodSync(tmpPath, mode);
|
|
147
148
|
syncFile(tmpPath, fsImpl);
|
|
148
149
|
fsImpl.renameSync(tmpPath, filePath);
|
|
149
150
|
} catch (error) {
|
|
@@ -177,6 +178,10 @@ function writeTextAtomicWithBackup(filePath, content, options = {}) {
|
|
|
177
178
|
const fsImpl = options.fs || fs;
|
|
178
179
|
const now = options.now instanceof Date ? options.now : new Date();
|
|
179
180
|
const text = typeof content === 'string' ? content : String(content || '');
|
|
181
|
+
if (isConfigStaging() && fsImpl === fs) {
|
|
182
|
+
fsImpl.writeFileSync(filePath, text, 'utf8');
|
|
183
|
+
return { path: filePath, backupPath: '', backupCreated: false };
|
|
184
|
+
}
|
|
180
185
|
fsImpl.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
181
186
|
const targetExists = fsImpl.existsSync(filePath);
|
|
182
187
|
const originalBuffer = targetExists ? fsImpl.readFileSync(filePath) : null;
|
package/lib/cli-file-utils.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const fs = require('fs');
|
|
1
|
+
const { fs, isConfigStaging } = require('./config-change-fs');
|
|
2
2
|
const path = require('path');
|
|
3
3
|
|
|
4
4
|
function ensureDir(dirPath) {
|
|
@@ -85,6 +85,7 @@ function formatTimestampForFileName(value) {
|
|
|
85
85
|
}
|
|
86
86
|
|
|
87
87
|
function backupFileIfNeededOnce(filePath, backupPrefix = 'codexmate-backup') {
|
|
88
|
+
if (isConfigStaging()) return '';
|
|
88
89
|
if (!fs.existsSync(filePath)) {
|
|
89
90
|
return '';
|
|
90
91
|
}
|
|
@@ -106,6 +107,10 @@ function backupFileIfNeededOnce(filePath, backupPrefix = 'codexmate-backup') {
|
|
|
106
107
|
}
|
|
107
108
|
|
|
108
109
|
function writeJsonAtomic(filePath, data) {
|
|
110
|
+
if (isConfigStaging()) {
|
|
111
|
+
fs.writeFileSync(filePath, JSON.stringify(data, null, 2) + '\n', 'utf8');
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
109
114
|
const dirPath = path.dirname(filePath);
|
|
110
115
|
ensureDir(dirPath);
|
|
111
116
|
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const nativeFs = require('fs');
|
|
4
|
+
const path = require('path');
|
|
5
|
+
const crypto = require('crypto');
|
|
6
|
+
const { AsyncLocalStorage } = require('async_hooks');
|
|
7
|
+
|
|
8
|
+
const storage = new AsyncLocalStorage();
|
|
9
|
+
const hash = (buffer) => crypto.createHash('sha256').update(buffer).digest('hex');
|
|
10
|
+
|
|
11
|
+
function snapshot(filePath, fs = nativeFs, options = {}) {
|
|
12
|
+
try {
|
|
13
|
+
const stat = options.allowSymlinks ? fs.statSync(filePath) : fs.lstatSync(filePath);
|
|
14
|
+
if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`配置目标不是普通文件: ${filePath}`);
|
|
15
|
+
const buffer = fs.readFileSync(filePath);
|
|
16
|
+
return { exists: true, buffer, hash: hash(buffer), mode: stat.mode & 0o777 };
|
|
17
|
+
} catch (error) {
|
|
18
|
+
if (error.code !== 'ENOENT') throw error;
|
|
19
|
+
return { exists: false, buffer: null, hash: '', mode: 0o600 };
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function getEntry(store, filePath) {
|
|
24
|
+
const key = path.resolve(filePath);
|
|
25
|
+
if (!store.files.has(key)) {
|
|
26
|
+
if (nativeFs.existsSync(key) && nativeFs.statSync(key).size > store.maxFileBytes) throw new Error('配置文件超过预览容量');
|
|
27
|
+
const before = snapshot(key, nativeFs, { allowSymlinks: store.allowSymlinks });
|
|
28
|
+
store.files.set(key, { path: key, before, after: before.buffer, mode: before.mode, written: false });
|
|
29
|
+
}
|
|
30
|
+
return store.files.get(key);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function missing(filePath) {
|
|
34
|
+
const error = new Error(`ENOENT: ${filePath}`);
|
|
35
|
+
error.code = 'ENOENT';
|
|
36
|
+
throw error;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const stagedMethods = {
|
|
40
|
+
existsSync(store, filePath) {
|
|
41
|
+
const key = path.resolve(filePath);
|
|
42
|
+
if (store.directories.has(key)) return true;
|
|
43
|
+
if (nativeFs.existsSync(key) && nativeFs.statSync(key).isDirectory()) return true;
|
|
44
|
+
return getEntry(store, key).after !== null;
|
|
45
|
+
},
|
|
46
|
+
readFileSync(store, filePath, options) {
|
|
47
|
+
const entry = getEntry(store, filePath);
|
|
48
|
+
if (entry.after === null) return missing(filePath);
|
|
49
|
+
const encoding = typeof options === 'string' ? options : options && options.encoding;
|
|
50
|
+
return encoding ? entry.after.toString(encoding) : Buffer.from(entry.after);
|
|
51
|
+
},
|
|
52
|
+
writeFileSync(store, filePath, content, options) {
|
|
53
|
+
const entry = getEntry(store, filePath);
|
|
54
|
+
const encoding = typeof options === 'string' ? options : options && options.encoding;
|
|
55
|
+
const buffer = Buffer.isBuffer(content) ? Buffer.from(content) : Buffer.from(String(content), encoding || 'utf8');
|
|
56
|
+
if (buffer.length > store.maxFileBytes) throw new Error('配置文件超过预览容量');
|
|
57
|
+
entry.after = buffer;
|
|
58
|
+
if (!entry.before.exists && options && typeof options === 'object' && options.mode !== undefined) entry.mode = options.mode;
|
|
59
|
+
entry.written = true;
|
|
60
|
+
},
|
|
61
|
+
mkdirSync(store, filePath) {
|
|
62
|
+
let dir = path.resolve(filePath);
|
|
63
|
+
while (!nativeFs.existsSync(dir)) {
|
|
64
|
+
store.directories.add(dir);
|
|
65
|
+
const observed = store.files.get(dir);
|
|
66
|
+
if (observed && !observed.written && !observed.before.exists) store.files.delete(dir);
|
|
67
|
+
const parent = path.dirname(dir);
|
|
68
|
+
if (parent === dir) break;
|
|
69
|
+
dir = parent;
|
|
70
|
+
}
|
|
71
|
+
},
|
|
72
|
+
statSync(store, filePath) {
|
|
73
|
+
const key = path.resolve(filePath);
|
|
74
|
+
if (nativeFs.existsSync(key) && !store.files.has(key)) return nativeFs.statSync(key);
|
|
75
|
+
if (store.directories.has(key)) return { isDirectory: () => true, isFile: () => false, mode: 0o700 };
|
|
76
|
+
const entry = getEntry(store, key);
|
|
77
|
+
if (entry.after === null) return missing(filePath);
|
|
78
|
+
return { isFile: () => true, isDirectory: () => false, mode: entry.mode, size: entry.after.length, mtimeMs: Date.now() };
|
|
79
|
+
},
|
|
80
|
+
readdirSync(store, filePath, options) {
|
|
81
|
+
const key = path.resolve(filePath);
|
|
82
|
+
if (!nativeFs.existsSync(key) && !store.directories.has(key)) return missing(filePath);
|
|
83
|
+
if (options && options.withFileTypes) throw new Error('配置预览不支持目录对象读取');
|
|
84
|
+
const names = new Set(nativeFs.existsSync(key) ? nativeFs.readdirSync(key) : []);
|
|
85
|
+
for (const entry of store.files.values()) {
|
|
86
|
+
if (path.dirname(entry.path) !== key) continue;
|
|
87
|
+
if (entry.after === null) names.delete(path.basename(entry.path));
|
|
88
|
+
else names.add(path.basename(entry.path));
|
|
89
|
+
}
|
|
90
|
+
return [...names];
|
|
91
|
+
},
|
|
92
|
+
chmodSync(store, filePath, mode) {
|
|
93
|
+
const entry = getEntry(store, filePath);
|
|
94
|
+
// Existing user permissions are never broadened by a previewed write.
|
|
95
|
+
if (!entry.before.exists) entry.mode = mode;
|
|
96
|
+
},
|
|
97
|
+
unlinkSync(store, filePath) {
|
|
98
|
+
const entry = getEntry(store, filePath);
|
|
99
|
+
entry.after = null;
|
|
100
|
+
entry.written = true;
|
|
101
|
+
},
|
|
102
|
+
copyFileSync(store, source, target) {
|
|
103
|
+
stagedMethods.writeFileSync(store, target, stagedMethods.readFileSync(store, source));
|
|
104
|
+
},
|
|
105
|
+
renameSync(store, source, target) {
|
|
106
|
+
stagedMethods.copyFileSync(store, source, target);
|
|
107
|
+
stagedMethods.unlinkSync(store, source);
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
const mutationPattern = /^(write|append|copy|rename|unlink|mkdir|rmdir|rm|chmod|chown|truncate|open|createWrite|symlink|link|utimes)/;
|
|
111
|
+
|
|
112
|
+
const fs = new Proxy(nativeFs, {
|
|
113
|
+
get(target, name) {
|
|
114
|
+
const original = target[name];
|
|
115
|
+
if (typeof original !== 'function') return original;
|
|
116
|
+
return (...args) => {
|
|
117
|
+
const store = storage.getStore();
|
|
118
|
+
if (!store) return original.apply(target, args);
|
|
119
|
+
if (stagedMethods[name]) return stagedMethods[name](store, ...args);
|
|
120
|
+
if (mutationPattern.test(name)) throw new Error(`配置预览不支持文件操作: ${name}`);
|
|
121
|
+
return original.apply(target, args);
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
async function stageConfigWrites(callback, options = {}) {
|
|
127
|
+
const store = { files: new Map(), directories: new Set(), maxFileBytes: options.maxFileBytes === undefined ? 4 * 1024 * 1024 : options.maxFileBytes, allowSymlinks: options.allowSymlinks === true };
|
|
128
|
+
const result = await storage.run(store, callback);
|
|
129
|
+
return { result, files: [...store.files.values()] };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
module.exports = { fs, snapshot, hash, stageConfigWrites, isConfigStaging: () => !!storage.getStore() };
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const path = require('path');
|
|
5
|
+
const crypto = require('crypto');
|
|
6
|
+
const JSON5 = require('json5');
|
|
7
|
+
const toml = require('@iarna/toml');
|
|
8
|
+
const { snapshot, hash, stageConfigWrites } = require('./config-change-fs');
|
|
9
|
+
const { writeTextAtomicWithBackup } = require('./cli-config-engine');
|
|
10
|
+
const { buildLineDiff } = require('./text-diff');
|
|
11
|
+
|
|
12
|
+
const PREVIEW_TTL_MS = 5 * 60 * 1000;
|
|
13
|
+
const MAX_PREVIEWS = 20;
|
|
14
|
+
const MAX_PLAN_BYTES = 16 * 1024 * 1024;
|
|
15
|
+
const SECRET_KEY = /api.?key|auth.?token|authorization|password|passwd|secret|credential|bearer|cookie|session|private.?key|preferred_auth_method|(^|_)(access|refresh|id)[_-]?token$|^(key|token|access|refresh)$/i;
|
|
16
|
+
|
|
17
|
+
function parseConfig(buffer) {
|
|
18
|
+
const text = buffer ? buffer.toString('utf8').replace(/^\uFEFF/, '') : '';
|
|
19
|
+
if (!text.trim()) return {};
|
|
20
|
+
try { return JSON5.parse(text); } catch (_) { return toml.parse(text); }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function redactConfig(value, secrets) {
|
|
24
|
+
if (Array.isArray(value)) return value.map(item => redactConfig(item, secrets));
|
|
25
|
+
if (typeof value === 'string') {
|
|
26
|
+
if (/^(?:bearer\s+|sk[-_]|gsk_|AIza|xox[baprs]-|gh[pousr]_)/i.test(value)) { secrets.add(value); return '[REDACTED]'; }
|
|
27
|
+
if (/^https?:\/\//i.test(value)) {
|
|
28
|
+
const url = new URL(value);
|
|
29
|
+
if (url.username) url.username = '[REDACTED]';
|
|
30
|
+
if (url.password) url.password = '[REDACTED]';
|
|
31
|
+
for (const key of [...url.searchParams.keys()]) if (SECRET_KEY.test(key)) url.searchParams.set(key, '[REDACTED]');
|
|
32
|
+
return url.toString();
|
|
33
|
+
}
|
|
34
|
+
return value;
|
|
35
|
+
}
|
|
36
|
+
if (!value || typeof value !== 'object') return value;
|
|
37
|
+
return Object.fromEntries(Object.entries(value).map(([key, item]) => {
|
|
38
|
+
if (SECRET_KEY.test(key)) {
|
|
39
|
+
const collect = (entry) => {
|
|
40
|
+
if (typeof entry === 'string' && entry) secrets.add(entry);
|
|
41
|
+
else if (entry && typeof entry === 'object') Object.values(entry).forEach(collect);
|
|
42
|
+
};
|
|
43
|
+
collect(item);
|
|
44
|
+
return [key, '[REDACTED]'];
|
|
45
|
+
}
|
|
46
|
+
return [key, redactConfig(item, secrets)];
|
|
47
|
+
}));
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function buildPreviewFile(entry) {
|
|
51
|
+
const secrets = new Set();
|
|
52
|
+
let before;
|
|
53
|
+
let after;
|
|
54
|
+
let hidden = false;
|
|
55
|
+
try {
|
|
56
|
+
before = JSON.stringify(redactConfig(parseConfig(entry.before.buffer), secrets), null, 2);
|
|
57
|
+
after = JSON.stringify(redactConfig(parseConfig(entry.after), secrets), null, 2);
|
|
58
|
+
} catch (_) {
|
|
59
|
+
before = after = '[内容无法安全解析,已隐藏]';
|
|
60
|
+
hidden = true;
|
|
61
|
+
}
|
|
62
|
+
// Also remove a credential repeated in a URL, comment or a non-secret field.
|
|
63
|
+
for (const secret of [...secrets].sort((a, b) => b.length - a.length)) {
|
|
64
|
+
const escaped = JSON.stringify(secret).slice(1, -1);
|
|
65
|
+
before = before.split(escaped).join('[REDACTED]');
|
|
66
|
+
after = after.split(escaped).join('[REDACTED]');
|
|
67
|
+
}
|
|
68
|
+
return {
|
|
69
|
+
path: entry.path,
|
|
70
|
+
operation: !entry.before.exists ? 'create' : (entry.after === null ? 'delete' : 'modify'),
|
|
71
|
+
hidden,
|
|
72
|
+
maskedOnly: before === after,
|
|
73
|
+
diff: buildLineDiff(before, after)
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function configChangeError(code, message, extra = {}) {
|
|
78
|
+
return { error: message, errorCode: code, ...extra };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function atomicBuffer(filePath, buffer, mode, fsImpl) {
|
|
82
|
+
fsImpl.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
83
|
+
const temp = `${filePath}.tmp-config-change-${crypto.randomBytes(8).toString('hex')}`;
|
|
84
|
+
try {
|
|
85
|
+
fsImpl.writeFileSync(temp, buffer, { mode, flag: 'wx' });
|
|
86
|
+
fsImpl.chmodSync(temp, mode);
|
|
87
|
+
fsImpl.renameSync(temp, filePath);
|
|
88
|
+
if (hash(fsImpl.readFileSync(filePath)) !== hash(buffer)) throw new Error('写入校验失败');
|
|
89
|
+
} finally {
|
|
90
|
+
if (fsImpl.existsSync(temp)) fsImpl.unlinkSync(temp);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function createConfigChanges(options) {
|
|
95
|
+
const fsImpl = options.fs || fs;
|
|
96
|
+
const plans = new Map();
|
|
97
|
+
let busy = false;
|
|
98
|
+
const now = options.now || Date.now;
|
|
99
|
+
const journalPath = options.journalPath;
|
|
100
|
+
|
|
101
|
+
function readJournal() {
|
|
102
|
+
if (!fsImpl.existsSync(journalPath)) return {};
|
|
103
|
+
const data = JSON.parse(fsImpl.readFileSync(journalPath, 'utf8'));
|
|
104
|
+
if (!data || data.version !== 1 || !data.changes || typeof data.changes !== 'object') throw new Error('变更记录无效');
|
|
105
|
+
return data.changes;
|
|
106
|
+
}
|
|
107
|
+
function writeJournal(changes) {
|
|
108
|
+
atomicBuffer(journalPath, Buffer.from(JSON.stringify({ version: 1, changes }, null, 2) + '\n'), 0o600, fsImpl);
|
|
109
|
+
}
|
|
110
|
+
function publicChange(change) {
|
|
111
|
+
if (!change) return null;
|
|
112
|
+
return { id: change.id, target: change.target, action: change.action, createdAt: change.createdAt, files: change.files.map(item => ({ path: item.path })) };
|
|
113
|
+
}
|
|
114
|
+
function publicBaseline(entries) {
|
|
115
|
+
return entries.map(entry => {
|
|
116
|
+
const current = snapshot(entry.path, fsImpl);
|
|
117
|
+
return { path: entry.path, exists: current.exists, hash: current.hash, mode: current.mode };
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
function permission(target) {
|
|
121
|
+
return options.isAllowed(target) ? null : configChangeError('tool-config-write-disabled', '配置写入权限未开启', { target });
|
|
122
|
+
}
|
|
123
|
+
function checkFile(entry, expected) {
|
|
124
|
+
if (!options.isPathAllowed(entry.path)) throw new Error('配置路径超出允许范围');
|
|
125
|
+
const current = snapshot(entry.path, fsImpl);
|
|
126
|
+
if (current.exists !== expected.exists || current.hash !== expected.hash || (current.exists && current.mode !== expected.mode)) {
|
|
127
|
+
const error = new Error('配置已被外部修改,请刷新后重新预览');
|
|
128
|
+
error.code = 'config-change-conflict';
|
|
129
|
+
error.path = entry.path;
|
|
130
|
+
throw error;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
function prunePlans() {
|
|
134
|
+
for (const [id, plan] of plans) if (plan.expiresAt <= now()) plans.delete(id);
|
|
135
|
+
while (plans.size >= MAX_PREVIEWS) plans.delete(plans.keys().next().value);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async function preview(params = {}) {
|
|
139
|
+
if (busy) return configChangeError('config-change-busy', '已有配置变更正在执行');
|
|
140
|
+
const action = params.action;
|
|
141
|
+
const target = options.getTarget(action);
|
|
142
|
+
if (!target) return configChangeError('config-change-unsupported', '该操作不支持配置预览');
|
|
143
|
+
const denied = permission(target);
|
|
144
|
+
if (denied) return denied;
|
|
145
|
+
try {
|
|
146
|
+
const staged = await stageConfigWrites(() => options.execute(action, params.params || {}));
|
|
147
|
+
if (!staged.result || staged.result.error || staged.result.success === false) return configChangeError('config-change-invalid', '配置校验失败,请检查输入格式与必填字段');
|
|
148
|
+
for (const entry of staged.files) if (entry.written && !options.isPathAllowed(entry.path)) throw new Error('配置路径超出允许范围');
|
|
149
|
+
if (Array.isArray(params.baseline)) {
|
|
150
|
+
for (const entry of staged.files) {
|
|
151
|
+
const expected = params.baseline.find(item => item.path === entry.path);
|
|
152
|
+
if (expected) checkFile(entry, expected);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
const bytes = staged.files.reduce((total, entry) => total + (entry.before.buffer ? entry.before.buffer.length : 0) + (entry.after ? entry.after.length : 0), 0);
|
|
156
|
+
if (bytes > MAX_PLAN_BYTES) return configChangeError('config-change-too-large', '配置变更超过预览容量');
|
|
157
|
+
const files = staged.files.filter(entry => entry.written && (entry.after === null ? entry.before.exists : (!entry.before.exists || hash(entry.after) !== entry.before.hash)));
|
|
158
|
+
const plan = { id: crypto.randomBytes(24).toString('hex'), action, target, files, reads: staged.files.filter(entry => options.isPathAllowed(entry.path)), result: staged.result, expiresAt: now() + PREVIEW_TTL_MS };
|
|
159
|
+
prunePlans();
|
|
160
|
+
plan.bytes = bytes;
|
|
161
|
+
while ([...plans.values()].reduce((total, item) => total + item.bytes, bytes) > MAX_PLAN_BYTES) plans.delete(plans.keys().next().value);
|
|
162
|
+
plans.set(plan.id, plan);
|
|
163
|
+
return { previewId: plan.id, target, action, expiresAt: plan.expiresAt, hasChanges: files.length > 0, files: files.map(buildPreviewFile) };
|
|
164
|
+
} catch (error) {
|
|
165
|
+
if (error.code === 'config-change-conflict') return configChangeError(error.code, error.message, { path: error.path });
|
|
166
|
+
return configChangeError('config-change-invalid', '无法预览配置,请检查文件与输入格式');
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function restoreEntries(entries) {
|
|
171
|
+
const failed = [];
|
|
172
|
+
for (const entry of [...entries].reverse()) {
|
|
173
|
+
try {
|
|
174
|
+
// Never roll back a subsequent external edit.
|
|
175
|
+
checkFile(entry, entry.writtenState);
|
|
176
|
+
if (entry.before.exists) atomicBuffer(entry.path, entry.before.buffer, entry.before.mode, fsImpl);
|
|
177
|
+
else if (fsImpl.existsSync(entry.path)) fsImpl.unlinkSync(entry.path);
|
|
178
|
+
} catch (_) { failed.push(entry.path); }
|
|
179
|
+
}
|
|
180
|
+
return failed;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
async function apply(params = {}) {
|
|
184
|
+
if (busy) return configChangeError('config-change-busy', '已有配置变更正在执行');
|
|
185
|
+
const plan = plans.get(params.previewId);
|
|
186
|
+
if (!plan || plan.expiresAt <= now()) return configChangeError('config-change-expired', '预览已失效,请重新预览');
|
|
187
|
+
const denied = permission(plan.target);
|
|
188
|
+
if (denied) return denied;
|
|
189
|
+
busy = true;
|
|
190
|
+
const applied = [];
|
|
191
|
+
let runtimeState;
|
|
192
|
+
let runtimeTouched = false;
|
|
193
|
+
try {
|
|
194
|
+
const changes = readJournal();
|
|
195
|
+
for (const entry of plan.reads) checkFile(entry, entry.before);
|
|
196
|
+
if (!plan.files.length) { plans.delete(plan.id); return { ...plan.result, success: true, noChanges: true }; }
|
|
197
|
+
runtimeState = options.runtimeState ? options.runtimeState(plan) : null;
|
|
198
|
+
for (const entry of plan.files) {
|
|
199
|
+
checkFile(entry, entry.before);
|
|
200
|
+
if (options.beforeWrite) options.beforeWrite(plan, entry);
|
|
201
|
+
const result = writeTextAtomicWithBackup(entry.path, (entry.after || entry.before.buffer).toString('utf8'), { fs: fsImpl });
|
|
202
|
+
if (entry.after === null) fsImpl.unlinkSync(entry.path);
|
|
203
|
+
applied.push({ ...entry, backupPath: result ? result.backupPath : '', writtenState: snapshot(entry.path, fsImpl) });
|
|
204
|
+
}
|
|
205
|
+
if (options.reconcileRuntime) {
|
|
206
|
+
runtimeTouched = true;
|
|
207
|
+
await options.reconcileRuntime(plan, false, runtimeState);
|
|
208
|
+
}
|
|
209
|
+
for (const entry of applied) checkFile(entry, entry.writtenState);
|
|
210
|
+
const change = {
|
|
211
|
+
id: crypto.randomBytes(24).toString('hex'), target: plan.target, action: plan.action,
|
|
212
|
+
createdAt: new Date(now()).toISOString(), runtimeState,
|
|
213
|
+
files: applied.map(entry => ({ path: entry.path, backupPath: entry.backupPath, before: { exists: entry.before.exists, hash: entry.before.hash, mode: entry.before.mode }, after: entry.writtenState.exists ? { exists: true, hash: entry.writtenState.hash, mode: entry.writtenState.mode } : { exists: false, hash: '', mode: 0o600 } }))
|
|
214
|
+
};
|
|
215
|
+
const baseline = publicBaseline(plan.reads);
|
|
216
|
+
changes[plan.target] = change;
|
|
217
|
+
writeJournal(changes);
|
|
218
|
+
plans.delete(plan.id);
|
|
219
|
+
return { ...plan.result, success: true, change: publicChange(change), configChangeTarget: plan.target, configChangeBaseline: baseline };
|
|
220
|
+
} catch (error) {
|
|
221
|
+
const rollbackFailed = restoreEntries(applied);
|
|
222
|
+
if (error.rollbackFailed) rollbackFailed.push(error.path || 'config-write');
|
|
223
|
+
if (runtimeTouched && options.reconcileRuntime) {
|
|
224
|
+
try { await options.reconcileRuntime(plan, true, runtimeState); } catch (_) { rollbackFailed.push('claude-runtime'); }
|
|
225
|
+
}
|
|
226
|
+
return configChangeError(error.code === 'config-change-conflict' ? error.code : 'config-change-write-failed', error.code === 'config-change-conflict' ? error.message : '配置变更失败,已尝试恢复原内容', { path: error.path || '', rollbackFailed, rolledBack: rollbackFailed.length === 0 });
|
|
227
|
+
} finally { busy = false; }
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function last(params = {}) {
|
|
231
|
+
if (!options.isTarget(params.target)) return configChangeError('config-change-invalid', '配置目标无效');
|
|
232
|
+
try { return { change: publicChange(readJournal()[params.target]) }; }
|
|
233
|
+
catch (_) { return configChangeError('config-change-history-invalid', '无法读取最近一次变更记录'); }
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
async function undo(params = {}) {
|
|
237
|
+
if (busy) return configChangeError('config-change-busy', '已有配置变更正在执行');
|
|
238
|
+
if (!options.isTarget(params.target)) return configChangeError('config-change-invalid', '配置目标无效');
|
|
239
|
+
const denied = permission(params.target);
|
|
240
|
+
if (denied) return denied;
|
|
241
|
+
busy = true;
|
|
242
|
+
const restored = [];
|
|
243
|
+
let change;
|
|
244
|
+
let runtimeState;
|
|
245
|
+
let runtimeTouched = false;
|
|
246
|
+
try {
|
|
247
|
+
const changes = readJournal();
|
|
248
|
+
change = changes[params.target];
|
|
249
|
+
if (!change || change.id !== params.changeId) return configChangeError('config-change-expired', '撤销记录已失效,请刷新');
|
|
250
|
+
const entries = change.files.map(item => {
|
|
251
|
+
checkFile(item, item.after);
|
|
252
|
+
let buffer = null;
|
|
253
|
+
if (item.before.exists) {
|
|
254
|
+
if (!item.backupPath || path.dirname(item.backupPath) !== path.dirname(item.path) || !path.basename(item.backupPath).startsWith(path.basename(item.path) + '.codexmate-backup-')) throw new Error('备份路径无效');
|
|
255
|
+
buffer = fsImpl.readFileSync(item.backupPath);
|
|
256
|
+
if (hash(buffer) !== item.before.hash) throw new Error('备份校验失败');
|
|
257
|
+
}
|
|
258
|
+
return { ...item, buffer, current: snapshot(item.path, fsImpl) };
|
|
259
|
+
});
|
|
260
|
+
runtimeState = options.runtimeState ? options.runtimeState(change) : null;
|
|
261
|
+
for (const entry of entries) {
|
|
262
|
+
checkFile(entry, entry.after);
|
|
263
|
+
const restoreEntry = { path: entry.path, before: entry.current, writtenState: { exists: entry.buffer !== null, hash: entry.buffer ? hash(entry.buffer) : '', mode: entry.before.mode } };
|
|
264
|
+
try {
|
|
265
|
+
if (entry.buffer === null) fsImpl.unlinkSync(entry.path);
|
|
266
|
+
else atomicBuffer(entry.path, entry.buffer, entry.before.mode, fsImpl);
|
|
267
|
+
} finally {
|
|
268
|
+
const current = snapshot(entry.path, fsImpl);
|
|
269
|
+
if (current.exists === restoreEntry.writtenState.exists && current.hash === restoreEntry.writtenState.hash) restored.push(restoreEntry);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
if (options.reconcileRuntime) {
|
|
273
|
+
runtimeTouched = true;
|
|
274
|
+
await options.reconcileRuntime(change, true, change.runtimeState);
|
|
275
|
+
}
|
|
276
|
+
for (const entry of restored) checkFile(entry, entry.writtenState);
|
|
277
|
+
const baseline = publicBaseline(change.files);
|
|
278
|
+
delete changes[params.target];
|
|
279
|
+
writeJournal(changes);
|
|
280
|
+
return { success: true, target: params.target, configChangeTarget: params.target, configChangeBaseline: baseline };
|
|
281
|
+
} catch (error) {
|
|
282
|
+
const rollbackFailed = restoreEntries(restored);
|
|
283
|
+
if (runtimeTouched && options.reconcileRuntime) {
|
|
284
|
+
try { await options.reconcileRuntime(change, true, runtimeState); } catch (_) { rollbackFailed.push('claude-runtime'); }
|
|
285
|
+
}
|
|
286
|
+
return configChangeError(error.code || 'config-change-undo-failed', error.code === 'config-change-conflict' ? error.message : '撤销失败,已保留当前配置', { path: error.path || '', rollbackFailed, rolledBack: rollbackFailed.length === 0 });
|
|
287
|
+
} finally { busy = false; }
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
return { preview, apply, last, undo, isBusy: () => busy };
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
module.exports = { createConfigChanges, buildPreviewFile, PREVIEW_TTL_MS };
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const http = require('http');
|
|
4
|
+
const os = require('os');
|
|
5
|
+
const { createHmac, randomBytes, timingSafeEqual } = require('crypto');
|
|
6
|
+
const { isIpAllowed, parseAllowedIps } = require('./http-access-control');
|
|
7
|
+
|
|
8
|
+
const PRIVATE_SUBNETS = ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16'];
|
|
9
|
+
const DOWNLOAD_PATH = /^\/download\/([a-f0-9]{32})\/(0|[1-9]\d*)$/;
|
|
10
|
+
const TOKEN_PATTERN = /^(\d{13})\.([a-f0-9]{32})\.([a-f0-9]{64})$/;
|
|
11
|
+
const LINK_TTL_MS = 60 * 60 * 1000;
|
|
12
|
+
const MAX_REQUEST_HEADER_BYTES = 8 * 1024;
|
|
13
|
+
const HEADER_TIMEOUT_MS = 10 * 1000;
|
|
14
|
+
|
|
15
|
+
function findLanInterface(localAddress) {
|
|
16
|
+
const interfaces = Object.values(os.networkInterfaces()).flat().filter(entry =>
|
|
17
|
+
!entry.internal && entry.cidr && isIpAllowed(entry.address, PRIVATE_SUBNETS));
|
|
18
|
+
return interfaces.find(entry => entry.address === localAddress) || interfaces[0];
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function rejectDownload(res, status) {
|
|
22
|
+
res.writeHead(status, {
|
|
23
|
+
'Content-Type': 'text/plain; charset=utf-8',
|
|
24
|
+
'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer', 'X-Content-Type-Options': 'nosniff'
|
|
25
|
+
});
|
|
26
|
+
res.end(http.STATUS_CODES[status]);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function createLanDownloads(sendFile) {
|
|
30
|
+
const secret = randomBytes(32);
|
|
31
|
+
const allowedIps = parseAllowedIps(process.env.CODEXMATE_ALLOWED_IPS || '');
|
|
32
|
+
const signature = (resource, stamp, nonce) => createHmac('sha256', secret)
|
|
33
|
+
.update(`${resource}\n${stamp}\n${nonce}`).digest();
|
|
34
|
+
const sockets = new Set();
|
|
35
|
+
let listener;
|
|
36
|
+
let server;
|
|
37
|
+
|
|
38
|
+
function authorizeLink(resource, query) {
|
|
39
|
+
const token = TOKEN_PATTERN.exec(new URLSearchParams(query).get('token') || '');
|
|
40
|
+
if (!token || Number(token[1]) <= Date.now()) return false;
|
|
41
|
+
return timingSafeEqual(signature(resource, token[1], token[2]), Buffer.from(token[3], 'hex'));
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async function start(iface) {
|
|
45
|
+
const { address, cidr } = iface;
|
|
46
|
+
server = http.createServer({ maxHeaderSize: MAX_REQUEST_HEADER_BYTES }, (req, res) => {
|
|
47
|
+
const remote = req.socket.remoteAddress;
|
|
48
|
+
if (!isIpAllowed(remote, [cidr]) || (allowedIps.length && !isIpAllowed(remote, allowedIps))) {
|
|
49
|
+
return rejectDownload(res, 403);
|
|
50
|
+
}
|
|
51
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') return rejectDownload(res, 405);
|
|
52
|
+
const authority = `${address}:${server.address().port}`;
|
|
53
|
+
if (req.headers.host !== authority) return rejectDownload(res, 404);
|
|
54
|
+
const queryStart = req.url.indexOf('?');
|
|
55
|
+
const resource = queryStart === -1 ? req.url : req.url.slice(0, queryStart);
|
|
56
|
+
const match = DOWNLOAD_PATH.exec(resource);
|
|
57
|
+
if (!match) return rejectDownload(res, 404);
|
|
58
|
+
if (!authorizeLink(resource, queryStart === -1 ? '' : req.url.slice(queryStart + 1))) return rejectDownload(res, 403);
|
|
59
|
+
void sendFile(req, res, match[1], Number(match[2])).catch(error => {
|
|
60
|
+
if (res.headersSent || res.destroyed) return;
|
|
61
|
+
rejectDownload(res, error.status || 500);
|
|
62
|
+
});
|
|
63
|
+
});
|
|
64
|
+
server.headersTimeout = HEADER_TIMEOUT_MS;
|
|
65
|
+
server.on('connection', socket => {
|
|
66
|
+
sockets.add(socket);
|
|
67
|
+
socket.once('close', () => sockets.delete(socket));
|
|
68
|
+
});
|
|
69
|
+
await new Promise((resolve, reject) => {
|
|
70
|
+
server.once('error', reject);
|
|
71
|
+
server.listen(0, address, () => {
|
|
72
|
+
server.removeListener('error', reject);
|
|
73
|
+
resolve();
|
|
74
|
+
});
|
|
75
|
+
});
|
|
76
|
+
return `http://${address}:${server.address().port}`;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
return {
|
|
80
|
+
async issue(id, index, localAddress) {
|
|
81
|
+
if (!listener) {
|
|
82
|
+
const iface = findLanInterface(localAddress);
|
|
83
|
+
if (!iface) return null;
|
|
84
|
+
listener = start(iface).catch(error => {
|
|
85
|
+
listener = null;
|
|
86
|
+
server = null;
|
|
87
|
+
console.warn('! LAN download listener failed:', error.code || 'error');
|
|
88
|
+
return null;
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
const origin = await listener;
|
|
92
|
+
if (!origin) return null;
|
|
93
|
+
const resource = `/download/${id}/${index}`;
|
|
94
|
+
const expiresAt = Date.now() + LINK_TTL_MS;
|
|
95
|
+
const nonce = randomBytes(16).toString('hex');
|
|
96
|
+
const token = `${expiresAt}.${nonce}.${signature(resource, expiresAt, nonce).toString('hex')}`;
|
|
97
|
+
return { url: `${origin}${resource}?token=${token}`, expiresAt };
|
|
98
|
+
},
|
|
99
|
+
async close() {
|
|
100
|
+
if (!listener) return;
|
|
101
|
+
await listener;
|
|
102
|
+
if (!server) return;
|
|
103
|
+
await new Promise(resolve => {
|
|
104
|
+
server.close(resolve);
|
|
105
|
+
for (const socket of sockets) socket.destroy();
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
module.exports = { createLanDownloads };
|