@gluztm/dsh-guard 2.4.1 → 2.4.2
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.en.md +38 -56
- package/README.md +38 -60
- package/bin/dsh-guard.mjs +112 -47
- package/lib/client.js +1459 -1079
- package/lib/index.mjs +209 -40
- package/lib/inspector.mjs +1478 -441
- package/package.json +2 -2
- package/screenshots.json +1 -1
package/lib/inspector.mjs
CHANGED
|
@@ -1,571 +1,1608 @@
|
|
|
1
|
-
import
|
|
2
|
-
import
|
|
3
|
-
import
|
|
4
|
-
import
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import crypto from 'node:crypto';
|
|
5
|
+
import { execFileSync, spawn } from 'node:child_process';
|
|
5
6
|
|
|
6
|
-
export const PACKAGE_VERSION = '2.4.
|
|
7
|
-
export const REPO_URL = 'https://github.com/gluztm/DSHGuard'
|
|
8
|
-
export const RELEASE_URL =
|
|
9
|
-
export const INSTALLER_URL =
|
|
7
|
+
export const PACKAGE_VERSION = '2.4.2';
|
|
8
|
+
export const REPO_URL = 'https://github.com/gluztm/DSHGuard';
|
|
9
|
+
export const RELEASE_URL = `https://github.com/gluztm/DSHGuard/releases/tag/${PACKAGE_VERSION}`;
|
|
10
|
+
export const INSTALLER_URL = `https://github.com/gluztm/DSHGuard/releases/download/${PACKAGE_VERSION}/DSHGuard-Setup-${PACKAGE_VERSION}.exe`;
|
|
10
11
|
|
|
11
|
-
const
|
|
12
|
-
const
|
|
12
|
+
const SELF_PLUGIN_NAME = '@gluztm/dsh-guard';
|
|
13
|
+
const SELF_LOADER_IDS = new Set(['dsh-guard', SELF_PLUGIN_NAME]);
|
|
14
|
+
const MCP_CLIENT_PKG = '@deepseek-ai/dsh-mcp-client';
|
|
15
|
+
const LLM_PLUGIN_IDS = new Set(['llm-pi-ai', '@deepseek-ai/dsh-llm-pi-ai']);
|
|
16
|
+
const RESTORABLE_REL_RE = /^(?:profiles\/(?:web|desktop|headless)\/(?:cordis\.patch\.yml|cordis\.yml|package\.json)|settings\.yaml)$/;
|
|
17
|
+
const SNAPSHOT_SAFE_EXT_RE = /\.(?:ya?ml|json)$/i;
|
|
18
|
+
const CRED_SKIP_RE = /(?:cred|secret|token|auth|\.pem$|\.key$)/i;
|
|
13
19
|
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
return
|
|
20
|
+
function safeReadText(filePath) {
|
|
21
|
+
try {
|
|
22
|
+
return fs.readFileSync(filePath, 'utf8');
|
|
23
|
+
} catch {
|
|
24
|
+
return null;
|
|
17
25
|
}
|
|
18
|
-
|
|
19
|
-
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function safeReadJson(filePath) {
|
|
29
|
+
const raw = safeReadText(filePath);
|
|
30
|
+
if (!raw) return null;
|
|
31
|
+
try {
|
|
32
|
+
return JSON.parse(raw);
|
|
33
|
+
} catch {
|
|
34
|
+
return null;
|
|
20
35
|
}
|
|
21
|
-
return join(homedir(), '.dsh')
|
|
22
36
|
}
|
|
23
37
|
|
|
24
|
-
function
|
|
25
|
-
|
|
38
|
+
function sha256Text(text) {
|
|
39
|
+
return crypto.createHash('sha256').update(text, 'utf8').digest('hex');
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function sha256File(filePath) {
|
|
26
43
|
try {
|
|
27
|
-
const
|
|
28
|
-
|
|
29
|
-
timeout: 2000,
|
|
30
|
-
windowsHide: true,
|
|
31
|
-
stdio: ['ignore', 'pipe', 'ignore'],
|
|
32
|
-
})
|
|
33
|
-
for (const rawLine of out.split(/\r?\n/)) {
|
|
34
|
-
const m = rawLine.trim().match(new RegExp(`^${valueName}\\s+REG_\\w+\\s+(.+)$`, 'i'))
|
|
35
|
-
if (m && m[1]) return m[1].trim()
|
|
36
|
-
}
|
|
44
|
+
const buf = fs.readFileSync(filePath);
|
|
45
|
+
return crypto.createHash('sha256').update(buf).digest('hex');
|
|
37
46
|
} catch {
|
|
38
|
-
return null
|
|
47
|
+
return null;
|
|
39
48
|
}
|
|
40
|
-
return null
|
|
41
49
|
}
|
|
42
50
|
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
const
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
51
|
+
function atomicWriteText(filePath, content, secureMode = false) {
|
|
52
|
+
const dir = path.dirname(filePath);
|
|
53
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
54
|
+
const tmpPath = `${filePath}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`;
|
|
55
|
+
const opts = secureMode && process.platform !== 'win32' ? { encoding: 'utf8', mode: 0o600 } : 'utf8';
|
|
56
|
+
fs.writeFileSync(tmpPath, content, opts);
|
|
57
|
+
fs.renameSync(tmpPath, filePath);
|
|
58
|
+
if (secureMode && process.platform !== 'win32') {
|
|
59
|
+
try {
|
|
60
|
+
fs.chmodSync(filePath, 0o600);
|
|
61
|
+
} catch {
|
|
62
|
+
// Ignore chmod failures on restricted filesystems.
|
|
53
63
|
}
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
if (ptrDir) candidates.push(resolve(ptrDir))
|
|
64
|
+
}
|
|
65
|
+
}
|
|
57
66
|
|
|
58
|
-
|
|
59
|
-
|
|
67
|
+
export function resolveDshHome(overrideHome) {
|
|
68
|
+
if (overrideHome && String(overrideHome).trim()) {
|
|
69
|
+
return path.resolve(String(overrideHome).trim());
|
|
70
|
+
}
|
|
71
|
+
if (process.env.DSH_HOME && process.env.DSH_HOME.trim()) {
|
|
72
|
+
return path.resolve(process.env.DSH_HOME.trim());
|
|
73
|
+
}
|
|
74
|
+
return path.join(os.homedir(), '.dsh');
|
|
75
|
+
}
|
|
60
76
|
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
77
|
+
function readRegistryInstallLocation() {
|
|
78
|
+
if (process.platform !== 'win32') return null;
|
|
79
|
+
const regKeys = [
|
|
80
|
+
'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\DSHGuard',
|
|
81
|
+
'HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\DSHGuard',
|
|
82
|
+
];
|
|
83
|
+
for (const key of regKeys) {
|
|
84
|
+
try {
|
|
85
|
+
const out = execFileSync('reg.exe', ['query', key, '/v', 'InstallLocation'], {
|
|
86
|
+
encoding: 'utf8',
|
|
87
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
88
|
+
timeout: 1500,
|
|
89
|
+
});
|
|
90
|
+
const match = /InstallLocation\s+REG_\w+\s+(.+)/i.exec(out);
|
|
91
|
+
if (match && match[1]) {
|
|
92
|
+
const dir = match[1].trim();
|
|
93
|
+
if (dir) return dir;
|
|
94
|
+
}
|
|
95
|
+
} catch {
|
|
96
|
+
// Registry key absent on this machine.
|
|
64
97
|
}
|
|
65
98
|
}
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
66
101
|
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
102
|
+
export function locateGuardInstallation(options = {}) {
|
|
103
|
+
if (options.disableLookup) {
|
|
104
|
+
return {
|
|
105
|
+
installed: false,
|
|
106
|
+
platform: process.platform,
|
|
107
|
+
exePath: null,
|
|
108
|
+
guardHome: null,
|
|
109
|
+
configDir: null,
|
|
110
|
+
snapshotsDir: null,
|
|
111
|
+
dataDir: null,
|
|
112
|
+
via: null,
|
|
113
|
+
releaseUrl: RELEASE_URL,
|
|
114
|
+
installerUrl: INSTALLER_URL,
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const candidates = [];
|
|
119
|
+
const pushCandidate = (dir, via) => {
|
|
120
|
+
if (!dir) return;
|
|
121
|
+
const resolved = path.resolve(dir);
|
|
122
|
+
candidates.push({ exe: path.join(resolved, 'DSHGuard.exe'), home: resolved, via });
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
if (options.guardHome) {
|
|
126
|
+
pushCandidate(options.guardHome, 'option');
|
|
127
|
+
}
|
|
128
|
+
if (process.env.DSHGUARD_HOME) {
|
|
129
|
+
pushCandidate(process.env.DSHGUARD_HOME, 'env:DSHGUARD_HOME');
|
|
130
|
+
}
|
|
70
131
|
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
if (existsSync(exeCandidate)) matchedExe = exeCandidate
|
|
78
|
-
if (existsSync(snapCandidate)) matchedSnapshots = snapCandidate
|
|
79
|
-
break
|
|
132
|
+
if (process.platform === 'win32' && !options.guardHome) {
|
|
133
|
+
const regDir = readRegistryInstallLocation();
|
|
134
|
+
if (regDir) pushCandidate(regDir, 'registry');
|
|
135
|
+
if (process.env.LOCALAPPDATA) {
|
|
136
|
+
pushCandidate(path.join(process.env.LOCALAPPDATA, 'Programs', 'DSHGuard'), 'localappdata');
|
|
137
|
+
pushCandidate(path.join(process.env.LOCALAPPDATA, 'DSHGuard'), 'localappdata-root');
|
|
80
138
|
}
|
|
139
|
+
pushCandidate('D:\\Applications\\DSHGuard', 'default-d-apps');
|
|
140
|
+
pushCandidate('C:\\Program Files\\DSHGuard', 'program-files');
|
|
81
141
|
}
|
|
82
142
|
|
|
83
|
-
|
|
84
|
-
|
|
143
|
+
for (const item of candidates) {
|
|
144
|
+
if (fs.existsSync(item.exe)) {
|
|
145
|
+
const guardHome = path.dirname(item.exe);
|
|
146
|
+
const localAppData = process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local');
|
|
147
|
+
const dataCandidates = [
|
|
148
|
+
path.join(guardHome, 'Snapshots'),
|
|
149
|
+
path.join(localAppData, 'DSHGuard', 'Snapshots'),
|
|
150
|
+
];
|
|
151
|
+
const snapshotsDir = dataCandidates.find((d) => fs.existsSync(d)) || dataCandidates[0];
|
|
152
|
+
const configDir = path.join(guardHome, 'Config');
|
|
153
|
+
return {
|
|
154
|
+
installed: true,
|
|
155
|
+
platform: process.platform,
|
|
156
|
+
exePath: item.exe,
|
|
157
|
+
guardHome,
|
|
158
|
+
configDir: fs.existsSync(configDir) ? configDir : null,
|
|
159
|
+
snapshotsDir,
|
|
160
|
+
dataDir: path.dirname(snapshotsDir),
|
|
161
|
+
via: item.via,
|
|
162
|
+
releaseUrl: RELEASE_URL,
|
|
163
|
+
installerUrl: INSTALLER_URL,
|
|
164
|
+
};
|
|
165
|
+
}
|
|
85
166
|
}
|
|
86
167
|
|
|
87
168
|
return {
|
|
88
|
-
installed:
|
|
89
|
-
|
|
90
|
-
exePath:
|
|
91
|
-
|
|
169
|
+
installed: false,
|
|
170
|
+
platform: process.platform,
|
|
171
|
+
exePath: null,
|
|
172
|
+
guardHome: null,
|
|
173
|
+
configDir: null,
|
|
174
|
+
snapshotsDir: null,
|
|
175
|
+
dataDir: null,
|
|
176
|
+
via: null,
|
|
92
177
|
releaseUrl: RELEASE_URL,
|
|
93
178
|
installerUrl: INSTALLER_URL,
|
|
94
|
-
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function unquoteYamlScalar(raw) {
|
|
183
|
+
const s = String(raw || '').trim();
|
|
184
|
+
if (!s) return '';
|
|
185
|
+
if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) {
|
|
186
|
+
const inner = s.slice(1, -1);
|
|
187
|
+
if (s.startsWith('"')) {
|
|
188
|
+
return inner.replace(/\\"/g, '"').replace(/\\\\/g, '\\').replace(/\\n/g, '\n');
|
|
189
|
+
}
|
|
190
|
+
return inner.replace(/''/g, "'");
|
|
95
191
|
}
|
|
192
|
+
return s;
|
|
96
193
|
}
|
|
97
194
|
|
|
98
|
-
function
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
195
|
+
function stripYamlComment(line) {
|
|
196
|
+
let inSingle = false;
|
|
197
|
+
let inDouble = false;
|
|
198
|
+
let escaped = false;
|
|
199
|
+
for (let i = 0; i < line.length; i += 1) {
|
|
200
|
+
const ch = line[i];
|
|
201
|
+
if (escaped) {
|
|
202
|
+
escaped = false;
|
|
203
|
+
continue;
|
|
204
|
+
}
|
|
205
|
+
if (inDouble && ch === '\\') {
|
|
206
|
+
escaped = true;
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
if (ch === "'" && !inDouble) {
|
|
210
|
+
inSingle = !inSingle;
|
|
211
|
+
continue;
|
|
212
|
+
}
|
|
213
|
+
if (ch === '"' && !inSingle) {
|
|
214
|
+
inDouble = !inDouble;
|
|
215
|
+
continue;
|
|
216
|
+
}
|
|
217
|
+
if (ch === '#' && !inSingle && !inDouble) {
|
|
218
|
+
if (i === 0 || /\s/.test(line[i - 1])) {
|
|
219
|
+
return line.slice(0, i).replace(/\s+$/, '');
|
|
220
|
+
}
|
|
221
|
+
}
|
|
104
222
|
}
|
|
223
|
+
return line.replace(/\s+$/, '');
|
|
105
224
|
}
|
|
106
225
|
|
|
107
|
-
function
|
|
108
|
-
|
|
109
|
-
|
|
226
|
+
function splitKeyValue(trimmed) {
|
|
227
|
+
let inSingle = false;
|
|
228
|
+
let inDouble = false;
|
|
229
|
+
let escaped = false;
|
|
230
|
+
for (let i = 0; i < trimmed.length; i += 1) {
|
|
231
|
+
const ch = trimmed[i];
|
|
232
|
+
if (escaped) {
|
|
233
|
+
escaped = false;
|
|
234
|
+
continue;
|
|
235
|
+
}
|
|
236
|
+
if (inDouble && ch === '\\') {
|
|
237
|
+
escaped = true;
|
|
238
|
+
continue;
|
|
239
|
+
}
|
|
240
|
+
if (ch === "'" && !inDouble) {
|
|
241
|
+
inSingle = !inSingle;
|
|
242
|
+
continue;
|
|
243
|
+
}
|
|
244
|
+
if (ch === '"' && !inSingle) {
|
|
245
|
+
inDouble = !inDouble;
|
|
246
|
+
continue;
|
|
247
|
+
}
|
|
248
|
+
if (ch === ':' && !inSingle && !inDouble) {
|
|
249
|
+
const next = trimmed[i + 1];
|
|
250
|
+
if (next === undefined || /\s/.test(next)) {
|
|
251
|
+
const key = unquoteYamlScalar(trimmed.slice(0, i).trim());
|
|
252
|
+
const val = trimmed.slice(i + 1).trim();
|
|
253
|
+
return { key, val };
|
|
254
|
+
}
|
|
255
|
+
}
|
|
110
256
|
}
|
|
111
|
-
|
|
112
|
-
|
|
257
|
+
return null;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
function parseSimpleScalar(rawVal) {
|
|
261
|
+
const s = String(rawVal || '').trim();
|
|
262
|
+
if (!s) return undefined;
|
|
263
|
+
if (s === 'true') return true;
|
|
264
|
+
if (s === 'false') return false;
|
|
265
|
+
if (s === 'null' || s === '~') return null;
|
|
266
|
+
if (/^!!js\b/.test(s)) return { __jsTag: s };
|
|
267
|
+
if (/^-?\d+(?:\.\d+)?$/.test(s)) return Number(s);
|
|
268
|
+
if ((s.startsWith('[') && s.endsWith(']')) || (s.startsWith('{') && s.endsWith('}'))) {
|
|
269
|
+
try {
|
|
270
|
+
return JSON.parse(s.replace(/'([^'\\]*(?:\\.[^'\\]*)*)'/g, '"$1"'));
|
|
271
|
+
} catch {
|
|
272
|
+
return s;
|
|
273
|
+
}
|
|
113
274
|
}
|
|
114
|
-
return
|
|
275
|
+
return unquoteYamlScalar(s);
|
|
115
276
|
}
|
|
116
277
|
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
278
|
+
/**
|
|
279
|
+
* Indentation-driven lightweight YAML parser tailored for Cordis cordis.patch.yml / cordis.yml.
|
|
280
|
+
* Preserves top-level patch structure (`- insert:` and `- id:`) without executing YAML tags.
|
|
281
|
+
*/
|
|
282
|
+
function parseYamlStructure(text) {
|
|
283
|
+
if (!text) return [];
|
|
284
|
+
const rawLines = text.replace(/\r\n/g, '\n').split('\n');
|
|
285
|
+
const tokens = [];
|
|
286
|
+
for (let idx = 0; idx < rawLines.length; idx += 1) {
|
|
287
|
+
const clean = stripYamlComment(rawLines[idx]);
|
|
288
|
+
if (!clean.trim()) continue;
|
|
289
|
+
const indent = clean.length - clean.trimStart().length;
|
|
290
|
+
tokens.push({ lineIdx: idx, indent, text: clean.trimStart(), raw: rawLines[idx] });
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
let cursor = 0;
|
|
294
|
+
|
|
295
|
+
function parseBlock(minIndent) {
|
|
296
|
+
if (cursor >= tokens.length) return null;
|
|
297
|
+
const first = tokens[cursor];
|
|
298
|
+
if (first.indent < minIndent) return null;
|
|
299
|
+
if (first.text === '-' || first.text.startsWith('- ')) {
|
|
300
|
+
return parseSequence(first.indent);
|
|
128
301
|
}
|
|
302
|
+
return parseMapping(first.indent);
|
|
129
303
|
}
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
const
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
304
|
+
|
|
305
|
+
function parseSequence(seqIndent) {
|
|
306
|
+
const arr = [];
|
|
307
|
+
while (cursor < tokens.length) {
|
|
308
|
+
const tok = tokens[cursor];
|
|
309
|
+
if (tok.indent < seqIndent) break;
|
|
310
|
+
if (tok.indent !== seqIndent || !(tok.text === '-' || tok.text.startsWith('- '))) break;
|
|
311
|
+
const startLine = tok.lineIdx;
|
|
312
|
+
const afterDash = tok.text === '-' ? '' : tok.text.slice(2).trimStart();
|
|
313
|
+
cursor += 1;
|
|
314
|
+
|
|
315
|
+
if (!afterDash) {
|
|
316
|
+
const val = cursor < tokens.length && tokens[cursor].indent > seqIndent
|
|
317
|
+
? parseBlock(seqIndent + 1)
|
|
318
|
+
: null;
|
|
319
|
+
if (val && typeof val === 'object' && !Array.isArray(val)) {
|
|
320
|
+
val.__lineRange = [startLine, cursor > 0 ? tokens[cursor - 1].lineIdx : startLine];
|
|
321
|
+
}
|
|
322
|
+
arr.push(val);
|
|
323
|
+
continue;
|
|
145
324
|
}
|
|
146
|
-
|
|
147
|
-
|
|
325
|
+
|
|
326
|
+
const kv = splitKeyValue(afterDash);
|
|
327
|
+
if (kv) {
|
|
328
|
+
const obj = {};
|
|
329
|
+
const itemIndent = seqIndent + 2;
|
|
330
|
+
if (kv.val === '|' || kv.val === '>') {
|
|
331
|
+
const lines = [];
|
|
332
|
+
while (cursor < tokens.length && tokens[cursor].indent >= itemIndent + 1) {
|
|
333
|
+
lines.push(tokens[cursor].text);
|
|
334
|
+
cursor += 1;
|
|
335
|
+
}
|
|
336
|
+
obj[kv.key] = lines.join('\n');
|
|
337
|
+
} else if (!kv.val) {
|
|
338
|
+
if (cursor < tokens.length && tokens[cursor].indent > seqIndent) {
|
|
339
|
+
// Handle `- insert:` followed by same-indent `- ...` or deeper indent mapping/list
|
|
340
|
+
obj[kv.key] = parseBlock(seqIndent + 1);
|
|
341
|
+
} else {
|
|
342
|
+
obj[kv.key] = null;
|
|
343
|
+
}
|
|
344
|
+
} else {
|
|
345
|
+
obj[kv.key] = parseSimpleScalar(kv.val);
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
while (cursor < tokens.length) {
|
|
349
|
+
const next = tokens[cursor];
|
|
350
|
+
if (next.indent < itemIndent) break;
|
|
351
|
+
if (next.indent === seqIndent && (next.text === '-' || next.text.startsWith('- '))) break;
|
|
352
|
+
if (next.indent > itemIndent && !splitKeyValue(next.text)) {
|
|
353
|
+
cursor += 1;
|
|
354
|
+
continue;
|
|
355
|
+
}
|
|
356
|
+
if (next.indent === itemIndent) {
|
|
357
|
+
const subKv = splitKeyValue(next.text);
|
|
358
|
+
if (!subKv) {
|
|
359
|
+
cursor += 1;
|
|
360
|
+
continue;
|
|
361
|
+
}
|
|
362
|
+
cursor += 1;
|
|
363
|
+
if (subKv.val === '|' || subKv.val === '>') {
|
|
364
|
+
const lines = [];
|
|
365
|
+
while (cursor < tokens.length && tokens[cursor].indent > itemIndent) {
|
|
366
|
+
lines.push(tokens[cursor].text);
|
|
367
|
+
cursor += 1;
|
|
368
|
+
}
|
|
369
|
+
obj[subKv.key] = lines.join('\n');
|
|
370
|
+
} else if (!subKv.val) {
|
|
371
|
+
obj[subKv.key] = cursor < tokens.length && tokens[cursor].indent > itemIndent
|
|
372
|
+
? parseBlock(itemIndent + 1)
|
|
373
|
+
: null;
|
|
374
|
+
} else {
|
|
375
|
+
obj[subKv.key] = parseSimpleScalar(subKv.val);
|
|
376
|
+
}
|
|
377
|
+
} else {
|
|
378
|
+
break;
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
obj.__lineRange = [startLine, cursor > 0 ? tokens[cursor - 1].lineIdx : startLine];
|
|
382
|
+
arr.push(obj);
|
|
383
|
+
} else {
|
|
384
|
+
arr.push(parseSimpleScalar(afterDash));
|
|
148
385
|
}
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
386
|
+
}
|
|
387
|
+
return arr;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
function parseMapping(mapIndent) {
|
|
391
|
+
const obj = {};
|
|
392
|
+
while (cursor < tokens.length) {
|
|
393
|
+
const tok = tokens[cursor];
|
|
394
|
+
if (tok.indent < mapIndent) break;
|
|
395
|
+
if (tok.indent !== mapIndent) break;
|
|
396
|
+
if (tok.text === '-' || tok.text.startsWith('- ')) break;
|
|
397
|
+
const kv = splitKeyValue(tok.text);
|
|
398
|
+
if (!kv) {
|
|
399
|
+
cursor += 1;
|
|
400
|
+
continue;
|
|
152
401
|
}
|
|
153
|
-
|
|
154
|
-
|
|
402
|
+
cursor += 1;
|
|
403
|
+
if (kv.val === '|' || kv.val === '>') {
|
|
404
|
+
const lines = [];
|
|
405
|
+
while (cursor < tokens.length && tokens[cursor].indent > mapIndent) {
|
|
406
|
+
lines.push(tokens[cursor].text);
|
|
407
|
+
cursor += 1;
|
|
408
|
+
}
|
|
409
|
+
obj[kv.key] = lines.join('\n');
|
|
410
|
+
} else if (!kv.val) {
|
|
411
|
+
if (cursor < tokens.length) {
|
|
412
|
+
const nxt = tokens[cursor];
|
|
413
|
+
if (nxt.indent > mapIndent || (nxt.indent === mapIndent && (nxt.text === '-' || nxt.text.startsWith('- ')))) {
|
|
414
|
+
obj[kv.key] = parseBlock(nxt.indent);
|
|
415
|
+
} else {
|
|
416
|
+
obj[kv.key] = null;
|
|
417
|
+
}
|
|
418
|
+
} else {
|
|
419
|
+
obj[kv.key] = null;
|
|
420
|
+
}
|
|
421
|
+
} else {
|
|
422
|
+
obj[kv.key] = parseSimpleScalar(kv.val);
|
|
155
423
|
}
|
|
156
424
|
}
|
|
425
|
+
return obj;
|
|
426
|
+
}
|
|
157
427
|
|
|
158
|
-
|
|
159
|
-
|
|
428
|
+
const parsed = parseBlock(0);
|
|
429
|
+
return parsed ?? [];
|
|
430
|
+
}
|
|
160
431
|
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
432
|
+
function collectPatchNodes(parsed) {
|
|
433
|
+
const list = Array.isArray(parsed)
|
|
434
|
+
? parsed
|
|
435
|
+
: Array.isArray(parsed?.plugins)
|
|
436
|
+
? parsed.plugins
|
|
437
|
+
: [];
|
|
438
|
+
const entries = [];
|
|
439
|
+
for (const item of list) {
|
|
440
|
+
if (!item || typeof item !== 'object') continue;
|
|
441
|
+
if (item.insert !== undefined && item.insert !== null) {
|
|
442
|
+
const inserts = Array.isArray(item.insert) ? item.insert : [item.insert];
|
|
443
|
+
for (const ins of inserts) {
|
|
444
|
+
if (ins && typeof ins === 'object') {
|
|
445
|
+
entries.push({
|
|
446
|
+
kind: 'insert',
|
|
447
|
+
id: typeof ins.id === 'string' ? ins.id : null,
|
|
448
|
+
name: typeof ins.name === 'string' ? ins.name : null,
|
|
449
|
+
disabled: ins.disabled === true,
|
|
450
|
+
disabledRaw: ins.disabled,
|
|
451
|
+
config: ins.config && typeof ins.config === 'object' ? ins.config : {},
|
|
452
|
+
lineRange: ins.__lineRange || item.__lineRange || null,
|
|
453
|
+
});
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
continue;
|
|
170
457
|
}
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
458
|
+
entries.push({
|
|
459
|
+
kind: 'override',
|
|
460
|
+
id: typeof item.id === 'string' ? item.id : null,
|
|
461
|
+
name: typeof item.name === 'string' ? item.name : null,
|
|
462
|
+
disabled: item.disabled === true,
|
|
463
|
+
disabledRaw: item.disabled,
|
|
464
|
+
hasConfig: item.config !== undefined,
|
|
465
|
+
config: item.config && typeof item.config === 'object' ? item.config : {},
|
|
466
|
+
keys: Object.keys(item).filter((k) => k !== '__lineRange'),
|
|
467
|
+
lineRange: item.__lineRange || null,
|
|
468
|
+
});
|
|
469
|
+
}
|
|
470
|
+
return entries;
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
export function quoteYamlId(id) {
|
|
474
|
+
const s = String(id || '');
|
|
475
|
+
if (!s) return '""';
|
|
476
|
+
const needsQuote =
|
|
477
|
+
/^(?:@|!|&|\*|\?|:|-|\[|\{|#|%|\||>|'|"|`)/.test(s) ||
|
|
478
|
+
/^(?:true|false|null|yes|no|on|off|~)$/i.test(s) ||
|
|
479
|
+
/^-?\d+(?:\.\d+)?$/.test(s) ||
|
|
480
|
+
/[:#\s]/.test(s) ||
|
|
481
|
+
/: /.test(s);
|
|
482
|
+
if (!needsQuote) return s;
|
|
483
|
+
return `"${s.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
export function findBrokenModuleLinks(profileDir) {
|
|
487
|
+
const nodeModulesDir = path.join(profileDir, 'node_modules');
|
|
488
|
+
const broken = [];
|
|
489
|
+
if (!fs.existsSync(nodeModulesDir)) return broken;
|
|
490
|
+
|
|
491
|
+
const inspectEntry = (pkgName, fullPath) => {
|
|
492
|
+
try {
|
|
493
|
+
const st = fs.lstatSync(fullPath);
|
|
494
|
+
if (!st.isSymbolicLink()) return;
|
|
495
|
+
let brokenTarget = null;
|
|
496
|
+
try {
|
|
497
|
+
brokenTarget = fs.readlinkSync(fullPath);
|
|
498
|
+
} catch {
|
|
499
|
+
brokenTarget = null;
|
|
500
|
+
}
|
|
501
|
+
if (!fs.existsSync(fullPath)) {
|
|
502
|
+
broken.push({ name: pkgName, linkPath: fullPath, brokenTarget });
|
|
503
|
+
}
|
|
504
|
+
} catch {
|
|
505
|
+
// Ignore unreadable entries.
|
|
506
|
+
}
|
|
507
|
+
};
|
|
508
|
+
|
|
509
|
+
let entries = [];
|
|
510
|
+
try {
|
|
511
|
+
entries = fs.readdirSync(nodeModulesDir, { withFileTypes: true });
|
|
512
|
+
} catch {
|
|
513
|
+
return broken;
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
for (const dirent of entries) {
|
|
517
|
+
const fullPath = path.join(nodeModulesDir, dirent.name);
|
|
518
|
+
if (dirent.name.startsWith('@') && !dirent.isSymbolicLink() && dirent.isDirectory()) {
|
|
519
|
+
try {
|
|
520
|
+
const scoped = fs.readdirSync(fullPath, { withFileTypes: true });
|
|
521
|
+
for (const sub of scoped) {
|
|
522
|
+
inspectEntry(`${dirent.name}/${sub.name}`, path.join(fullPath, sub.name));
|
|
523
|
+
}
|
|
524
|
+
} catch {
|
|
525
|
+
// Ignore unreadable scoped folder.
|
|
526
|
+
}
|
|
527
|
+
} else if (!dirent.name.startsWith('.')) {
|
|
528
|
+
inspectEntry(dirent.name, fullPath);
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
return broken;
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
function collectApiKeyEnvs(node, outSet, depth = 0) {
|
|
535
|
+
if (!node || typeof node !== 'object' || depth > 10) return;
|
|
536
|
+
if (Array.isArray(node)) {
|
|
537
|
+
for (const item of node) collectApiKeyEnvs(item, outSet, depth + 1);
|
|
538
|
+
return;
|
|
539
|
+
}
|
|
540
|
+
for (const [k, v] of Object.entries(node)) {
|
|
541
|
+
if (k === 'apiKeyEnv' && typeof v === 'string' && v.trim()) {
|
|
542
|
+
outSet.add(v.trim());
|
|
543
|
+
} else if (v && typeof v === 'object') {
|
|
544
|
+
collectApiKeyEnvs(v, outSet, depth + 1);
|
|
181
545
|
}
|
|
182
546
|
}
|
|
183
547
|
}
|
|
184
548
|
|
|
549
|
+
export function inspectProfile(dshHome, profileName) {
|
|
550
|
+
const profileDir = path.join(dshHome, 'profiles', profileName);
|
|
551
|
+
const exists = fs.existsSync(profileDir);
|
|
552
|
+
const pkgPath = path.join(profileDir, 'package.json');
|
|
553
|
+
const patchPath = path.join(profileDir, 'cordis.patch.yml');
|
|
554
|
+
const basePath = path.join(profileDir, 'cordis.yml');
|
|
555
|
+
const pkg = safeReadJson(pkgPath);
|
|
556
|
+
const patchText = safeReadText(patchPath);
|
|
557
|
+
const baseText = safeReadText(basePath);
|
|
558
|
+
const brokenLinks = exists ? findBrokenModuleLinks(profileDir) : [];
|
|
559
|
+
|
|
560
|
+
const deps = pkg && typeof pkg.dependencies === 'object' && pkg.dependencies ? Object.keys(pkg.dependencies) : [];
|
|
561
|
+
const depSet = new Set(deps);
|
|
562
|
+
const bundleNames = pkg?.dsh?.bundles && typeof pkg.dsh.bundles === 'object' ? Object.keys(pkg.dsh.bundles) : [];
|
|
563
|
+
const missingBundles = bundleNames.filter((b) => !depSet.has(b));
|
|
564
|
+
const thirdPartyDeps = deps.filter((name) => !name.startsWith('@deepseek-ai/'));
|
|
565
|
+
const parsedPatch = patchText ? parseYamlStructure(patchText) : null;
|
|
566
|
+
const patchEntries = parsedPatch ? collectPatchNodes(parsedPatch) : [];
|
|
567
|
+
const referencedEnvSet = new Set();
|
|
568
|
+
if (parsedPatch) collectApiKeyEnvs(parsedPatch, referencedEnvSet);
|
|
569
|
+
const mcpCount = patchEntries.filter((e) => e.kind === 'insert' && e.name === MCP_CLIENT_PKG).length;
|
|
570
|
+
const disabledOverrides = patchEntries.filter((e) => e.disabled === true);
|
|
571
|
+
|
|
572
|
+
return {
|
|
573
|
+
name: profileName,
|
|
574
|
+
exists,
|
|
575
|
+
profileDir,
|
|
576
|
+
packageJsonPresent: Boolean(pkg),
|
|
577
|
+
totalDependencies: deps.length,
|
|
578
|
+
thirdPartyCount: thirdPartyDeps.length,
|
|
579
|
+
thirdPartyNames: thirdPartyDeps,
|
|
580
|
+
missingBundles,
|
|
581
|
+
referencedEnvKeys: Array.from(referencedEnvSet),
|
|
582
|
+
mcpCount,
|
|
583
|
+
disabledEntryCount: disabledOverrides.length,
|
|
584
|
+
brokenLinks,
|
|
585
|
+
brokenLinkCount: brokenLinks.length,
|
|
586
|
+
patchPresent: patchText !== null,
|
|
587
|
+
patchHash: patchText !== null ? sha256Text(patchText).slice(0, 12) : null,
|
|
588
|
+
patchBytes: patchText !== null ? Buffer.byteLength(patchText, 'utf8') : 0,
|
|
589
|
+
basePresent: baseText !== null,
|
|
590
|
+
baseHash: baseText !== null ? sha256Text(baseText).slice(0, 12) : null,
|
|
591
|
+
};
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
function parseCredentialRefsDocument(rawText) {
|
|
595
|
+
const lines = rawText ? rawText.replace(/\r\n/g, '\n').split('\n') : [];
|
|
596
|
+
let inRefs = false;
|
|
597
|
+
let refsStart = -1;
|
|
598
|
+
let refsEnd = -1;
|
|
599
|
+
const entries = [];
|
|
600
|
+
let current = null;
|
|
601
|
+
|
|
602
|
+
const flushCurrent = () => {
|
|
603
|
+
if (!current) return;
|
|
604
|
+
entries.push(current);
|
|
605
|
+
current = null;
|
|
606
|
+
};
|
|
607
|
+
|
|
608
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
609
|
+
const line = lines[i];
|
|
610
|
+
const trimmed = line.trim();
|
|
611
|
+
|
|
612
|
+
if (/^\S/.test(line) && !trimmed.startsWith('#')) {
|
|
613
|
+
if (inRefs) {
|
|
614
|
+
flushCurrent();
|
|
615
|
+
refsEnd = i;
|
|
616
|
+
inRefs = false;
|
|
617
|
+
}
|
|
618
|
+
if (/^refs:\s*(?:#.*)?$/.test(line)) {
|
|
619
|
+
inRefs = true;
|
|
620
|
+
refsStart = i;
|
|
621
|
+
} else if (/^refs:\s*\{\}\s*(?:#.*)?$/.test(line)) {
|
|
622
|
+
refsStart = i;
|
|
623
|
+
refsEnd = i + 1;
|
|
624
|
+
}
|
|
625
|
+
continue;
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
if (!inRefs) continue;
|
|
629
|
+
if (!trimmed || trimmed.startsWith('#')) continue;
|
|
630
|
+
|
|
631
|
+
const indent = line.length - line.trimStart().length;
|
|
632
|
+
if (indent === 2 && !line.trimStart().startsWith('-')) {
|
|
633
|
+
const kv = splitKeyValue(line.trimStart());
|
|
634
|
+
if (kv && kv.key) {
|
|
635
|
+
flushCurrent();
|
|
636
|
+
const isProtectedAccount = /_ACCOUNT(?:_|$)/i.test(kv.key);
|
|
637
|
+
const val = kv.val;
|
|
638
|
+
const isBlock = val === '|' || val === '|-' || val === '|+' || val === '>' || val === '>-' || !val;
|
|
639
|
+
const present = isBlock ? true : val !== '""' && val !== "''" && val !== 'null' && val !== '~';
|
|
640
|
+
current = {
|
|
641
|
+
key: kv.key,
|
|
642
|
+
protected: isProtectedAccount,
|
|
643
|
+
present,
|
|
644
|
+
isMultiline: isBlock,
|
|
645
|
+
startLine: i,
|
|
646
|
+
endLine: i,
|
|
647
|
+
};
|
|
648
|
+
}
|
|
649
|
+
} else if (current && indent > 2) {
|
|
650
|
+
current.endLine = i;
|
|
651
|
+
current.isMultiline = true;
|
|
652
|
+
current.present = true;
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
if (inRefs) {
|
|
657
|
+
flushCurrent();
|
|
658
|
+
refsEnd = lines.length;
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
return { lines, refsStart, refsEnd, entries };
|
|
662
|
+
}
|
|
663
|
+
|
|
185
664
|
/**
|
|
186
|
-
*
|
|
665
|
+
* Inspect .credentials.yaml ONLY for key existence/readiness metadata.
|
|
666
|
+
* Never reads or returns any secret literal, preview, or prefix.
|
|
187
667
|
*/
|
|
188
|
-
export function
|
|
189
|
-
const
|
|
190
|
-
|
|
191
|
-
|
|
668
|
+
export function inspectCredentialKeysMasked(dshHome) {
|
|
669
|
+
const credPath = path.join(dshHome, '.credentials.yaml');
|
|
670
|
+
if (!fs.existsSync(credPath)) {
|
|
671
|
+
return {
|
|
672
|
+
present: false,
|
|
673
|
+
path: credPath,
|
|
674
|
+
count: 0,
|
|
675
|
+
protectedCount: 0,
|
|
676
|
+
keys: [],
|
|
677
|
+
};
|
|
678
|
+
}
|
|
192
679
|
|
|
193
|
-
|
|
680
|
+
const raw = safeReadText(credPath);
|
|
681
|
+
if (raw === null) {
|
|
194
682
|
return {
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
unregisteredDeps: [],
|
|
203
|
-
patch: scanCordisPatch(patchPath),
|
|
204
|
-
issues: [],
|
|
205
|
-
}
|
|
683
|
+
present: true,
|
|
684
|
+
unreadable: true,
|
|
685
|
+
path: credPath,
|
|
686
|
+
count: 0,
|
|
687
|
+
protectedCount: 0,
|
|
688
|
+
keys: [],
|
|
689
|
+
};
|
|
206
690
|
}
|
|
207
691
|
|
|
208
|
-
const
|
|
209
|
-
|
|
210
|
-
|
|
692
|
+
const doc = parseCredentialRefsDocument(raw);
|
|
693
|
+
const seen = new Set();
|
|
694
|
+
const keys = [];
|
|
695
|
+
|
|
696
|
+
for (const entry of doc.entries) {
|
|
697
|
+
if (!entry.key || seen.has(entry.key)) continue;
|
|
698
|
+
seen.add(entry.key);
|
|
699
|
+
keys.push({
|
|
700
|
+
key: entry.key,
|
|
701
|
+
protected: entry.protected,
|
|
702
|
+
present: entry.present,
|
|
703
|
+
source: 'refs',
|
|
704
|
+
envSet: Boolean(process.env[entry.key]),
|
|
705
|
+
});
|
|
706
|
+
}
|
|
211
707
|
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
708
|
+
// Fallback for flat legacy key: value files without refs: section
|
|
709
|
+
if (doc.refsStart === -1) {
|
|
710
|
+
for (const rawLine of doc.lines) {
|
|
711
|
+
const clean = stripYamlComment(rawLine);
|
|
712
|
+
if (!clean.trim() || /^\s/.test(clean) || clean.trimStart().startsWith('-')) continue;
|
|
713
|
+
const kv = splitKeyValue(clean.trim());
|
|
714
|
+
if (!kv || !kv.key || /^(?:version|records|refs)$/i.test(kv.key) || seen.has(kv.key)) continue;
|
|
715
|
+
seen.add(kv.key);
|
|
716
|
+
keys.push({
|
|
717
|
+
key: kv.key,
|
|
718
|
+
protected: /_ACCOUNT(?:_|$)/i.test(kv.key),
|
|
719
|
+
present: Boolean(kv.val && kv.val !== '""' && kv.val !== "''" && kv.val !== 'null'),
|
|
720
|
+
source: 'root',
|
|
721
|
+
envSet: Boolean(process.env[kv.key]),
|
|
722
|
+
});
|
|
723
|
+
}
|
|
724
|
+
}
|
|
217
725
|
|
|
218
|
-
const
|
|
219
|
-
? extractBundleIds(pkgRes.data.dsh.bundles ?? (pkgRes.data.dsh.profile && pkgRes.data.dsh.profile.bundles))
|
|
220
|
-
: []
|
|
221
|
-
const bundleSet = new Set(bundles)
|
|
726
|
+
const nonEmptyKeysCount = keys.filter((k) => k.present).length;
|
|
222
727
|
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
728
|
+
return {
|
|
729
|
+
present: true,
|
|
730
|
+
path: credPath,
|
|
731
|
+
count: keys.length,
|
|
732
|
+
nonEmptyKeysCount,
|
|
733
|
+
protectedCount: keys.filter((k) => k.protected).length,
|
|
734
|
+
missingReferencedKeys: [],
|
|
735
|
+
keys,
|
|
736
|
+
};
|
|
737
|
+
}
|
|
228
738
|
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
739
|
+
/**
|
|
740
|
+
* One-way secret write into ~/.dsh/.credentials.yaml `refs:` preserving `version`, `records`,
|
|
741
|
+
* comments, and existing `*_ACCOUNT_*` OAuth blocks. Never returns or logs the secret value.
|
|
742
|
+
*/
|
|
743
|
+
export function upsertCredentialKey(dshHome, keyName, secretValue) {
|
|
744
|
+
const key = String(keyName || '').trim();
|
|
745
|
+
if (!/^[A-Za-z_][A-Za-z0-9_.-]{1,95}$/.test(key)) {
|
|
746
|
+
return { ok: false, error: '环境变量名格式无效(仅支持字母、数字、下划线、点或连字符)' };
|
|
233
747
|
}
|
|
234
|
-
if (
|
|
235
|
-
|
|
748
|
+
if (/^(?:version|records|refs)$/i.test(key) || /_ACCOUNT(?:_|$)/i.test(key)) {
|
|
749
|
+
return { ok: false, error: `保护键 ${key} 不可通过插件覆盖写入` };
|
|
236
750
|
}
|
|
237
|
-
|
|
238
|
-
|
|
751
|
+
const secret = typeof secretValue === 'string' ? secretValue.trim() : '';
|
|
752
|
+
if (!secret || /[\r\n]/.test(secret) || secret.length > 4096) {
|
|
753
|
+
return { ok: false, error: '密钥值不能为空且必须为单行(<= 4096 字符)' };
|
|
239
754
|
}
|
|
240
|
-
|
|
241
|
-
|
|
755
|
+
|
|
756
|
+
const credPath = path.join(dshHome, '.credentials.yaml');
|
|
757
|
+
const escaped = secret.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
|
|
758
|
+
const formattedLine = ` ${key}: "${escaped}"`;
|
|
759
|
+
|
|
760
|
+
if (!fs.existsSync(credPath)) {
|
|
761
|
+
const initial = `version: 1\nrecords: []\nrefs:\n${formattedLine}\n`;
|
|
762
|
+
atomicWriteText(credPath, initial, true);
|
|
763
|
+
return { ok: true, key, path: credPath, created: true };
|
|
242
764
|
}
|
|
243
765
|
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
exists: true,
|
|
248
|
-
packageJsonOk: pkgRes.ok,
|
|
249
|
-
dependenciesCount: depNames.length,
|
|
250
|
-
bundlesCount: bundles.length,
|
|
251
|
-
missingInDeps,
|
|
252
|
-
unregisteredDeps,
|
|
253
|
-
patch,
|
|
254
|
-
issues,
|
|
766
|
+
const raw = safeReadText(credPath);
|
|
767
|
+
if (raw === null) {
|
|
768
|
+
return { ok: false, error: '无法读取 .credentials.yaml' };
|
|
255
769
|
}
|
|
770
|
+
|
|
771
|
+
const doc = parseCredentialRefsDocument(raw);
|
|
772
|
+
const lines = doc.lines.slice();
|
|
773
|
+
const existing = doc.entries.find((e) => e.key === key);
|
|
774
|
+
|
|
775
|
+
if (existing) {
|
|
776
|
+
lines.splice(existing.startLine, existing.endLine - existing.startLine + 1, formattedLine);
|
|
777
|
+
} else if (doc.refsStart !== -1) {
|
|
778
|
+
if (/^refs:\s*\{\}/.test(lines[doc.refsStart])) {
|
|
779
|
+
lines[doc.refsStart] = 'refs:';
|
|
780
|
+
lines.splice(doc.refsStart + 1, 0, formattedLine);
|
|
781
|
+
} else {
|
|
782
|
+
let insertAt = doc.refsStart + 1;
|
|
783
|
+
for (let i = doc.refsStart + 1; i < doc.refsEnd; i += 1) {
|
|
784
|
+
if (lines[i].trim()) insertAt = i + 1;
|
|
785
|
+
}
|
|
786
|
+
lines.splice(insertAt, 0, formattedLine);
|
|
787
|
+
}
|
|
788
|
+
} else {
|
|
789
|
+
while (lines.length > 0 && !lines[lines.length - 1].trim()) lines.pop();
|
|
790
|
+
lines.push('refs:', formattedLine);
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
const output = `${lines.join('\n').replace(/\n+$/, '')}\n`;
|
|
794
|
+
atomicWriteText(credPath, output, true);
|
|
795
|
+
return { ok: true, key, path: credPath, created: !existing };
|
|
256
796
|
}
|
|
257
797
|
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
const
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
const
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
798
|
+
export function inspectProviders(dshHome) {
|
|
799
|
+
const maskedCreds = inspectCredentialKeysMasked(dshHome);
|
|
800
|
+
const readyKeys = new Set(maskedCreds.keys.filter((k) => k.present).map((k) => k.key));
|
|
801
|
+
const merged = new Map();
|
|
802
|
+
|
|
803
|
+
for (const profileName of ['web', 'desktop']) {
|
|
804
|
+
const profileDir = path.join(dshHome, 'profiles', profileName);
|
|
805
|
+
for (const fileName of ['cordis.patch.yml', 'cordis.yml']) {
|
|
806
|
+
const text = safeReadText(path.join(profileDir, fileName));
|
|
807
|
+
if (!text) continue;
|
|
808
|
+
const nodes = collectPatchNodes(parseYamlStructure(text));
|
|
809
|
+
const piNode = nodes.find((n) => LLM_PLUGIN_IDS.has(n.id || '') || LLM_PLUGIN_IDS.has(n.name || ''));
|
|
810
|
+
const providers = piNode?.config?.providers;
|
|
811
|
+
if (!providers || typeof providers !== 'object') continue;
|
|
812
|
+
|
|
813
|
+
for (const [pid, cfg] of Object.entries(providers)) {
|
|
814
|
+
if (!cfg || typeof cfg !== 'object') continue;
|
|
815
|
+
const existing = merged.get(pid) || {
|
|
816
|
+
id: pid,
|
|
817
|
+
displayName: String(cfg.displayName || cfg.name || pid),
|
|
818
|
+
api: String(cfg.api || 'openai-completions'),
|
|
819
|
+
baseURL: String(cfg.baseURL || cfg.baseUrl || cfg.url || ''),
|
|
820
|
+
apiKeyEnv: String(cfg.apiKeyEnv || ''),
|
|
821
|
+
keyConfigured: false,
|
|
822
|
+
profiles: [],
|
|
823
|
+
models: [],
|
|
824
|
+
};
|
|
825
|
+
if (!existing.profiles.includes(profileName)) {
|
|
826
|
+
existing.profiles.push(profileName);
|
|
827
|
+
}
|
|
828
|
+
if (Array.isArray(cfg.models) && existing.models.length === 0) {
|
|
829
|
+
existing.models = cfg.models
|
|
830
|
+
.map((m) => {
|
|
831
|
+
if (typeof m === 'string') return { id: m, name: m };
|
|
832
|
+
if (m && typeof m === 'object') {
|
|
833
|
+
return { id: String(m.id || m.name || ''), name: String(m.name || m.id || '') };
|
|
834
|
+
}
|
|
835
|
+
return null;
|
|
836
|
+
})
|
|
837
|
+
.filter((m) => m && m.id);
|
|
283
838
|
}
|
|
839
|
+
existing.keyConfigured = existing.apiKeyEnv
|
|
840
|
+
? readyKeys.has(existing.apiKeyEnv) || Boolean(process.env[existing.apiKeyEnv])
|
|
841
|
+
: false;
|
|
842
|
+
merged.set(pid, existing);
|
|
284
843
|
}
|
|
285
|
-
|
|
286
|
-
// Unreadable file stays nonEmptyKeys empty; never leak raw error internals with secrets.
|
|
844
|
+
break;
|
|
287
845
|
}
|
|
288
846
|
}
|
|
289
847
|
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
key,
|
|
293
|
-
ready: nonEmptyKeys.has(key),
|
|
294
|
-
}))
|
|
295
|
-
const missingReferencedKeys = referencedKeys.filter((item) => !item.ready).map((item) => item.key)
|
|
848
|
+
return Array.from(merged.values());
|
|
849
|
+
}
|
|
296
850
|
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
851
|
+
function readPackageLoaderIds(profileDir, pkgName, guard) {
|
|
852
|
+
const pkgDir = path.join(profileDir, 'node_modules', ...pkgName.split('/'));
|
|
853
|
+
const pkgJson = safeReadJson(path.join(pkgDir, 'package.json'));
|
|
854
|
+
const patchRel = pkgJson?.dsh?.bundle?.patch;
|
|
855
|
+
const candidateFiles = [];
|
|
856
|
+
if (typeof patchRel === 'string' && patchRel.trim()) {
|
|
857
|
+
const resolved = path.resolve(pkgDir, patchRel.trim());
|
|
858
|
+
if (resolved.startsWith(pkgDir)) candidateFiles.push(resolved);
|
|
303
859
|
}
|
|
304
|
-
|
|
860
|
+
candidateFiles.push(path.join(pkgDir, 'cordis.patch.yml'));
|
|
305
861
|
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
? options.target
|
|
313
|
-
: 'all'
|
|
862
|
+
const ids = [];
|
|
863
|
+
const pushId = (val) => {
|
|
864
|
+
if (typeof val === 'string' && val.trim() && !ids.includes(val.trim())) {
|
|
865
|
+
ids.push(val.trim());
|
|
866
|
+
}
|
|
867
|
+
};
|
|
314
868
|
|
|
315
|
-
const
|
|
316
|
-
|
|
317
|
-
|
|
869
|
+
for (const file of candidateFiles) {
|
|
870
|
+
const text = safeReadText(file);
|
|
871
|
+
if (!text) continue;
|
|
872
|
+
const nodes = collectPatchNodes(parseYamlStructure(text));
|
|
873
|
+
for (const n of nodes) {
|
|
874
|
+
if (n.kind === 'insert' && n.id) pushId(n.id);
|
|
875
|
+
}
|
|
876
|
+
if (ids.length > 0) break;
|
|
318
877
|
}
|
|
319
|
-
|
|
320
|
-
|
|
878
|
+
|
|
879
|
+
if (guard?.configDir) {
|
|
880
|
+
const mapJson = safeReadJson(path.join(guard.configDir, 'loader-ids.json'));
|
|
881
|
+
const mapped = mapJson?.[pkgName];
|
|
882
|
+
if (Array.isArray(mapped)) {
|
|
883
|
+
for (const m of mapped) pushId(m);
|
|
884
|
+
} else if (typeof mapped === 'string') {
|
|
885
|
+
pushId(mapped);
|
|
886
|
+
}
|
|
321
887
|
}
|
|
322
888
|
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
const guard = locateGuardInstallation(options)
|
|
889
|
+
return { ids, description: typeof pkgJson?.description === 'string' ? pkgJson.description : '', version: pkgJson?.version || '' };
|
|
890
|
+
}
|
|
326
891
|
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
892
|
+
export function inspectExtensions(dshHome, target = 'web', guard = null) {
|
|
893
|
+
const profileName = target === 'desktop' ? 'desktop' : 'web';
|
|
894
|
+
const profileDir = path.join(dshHome, 'profiles', profileName);
|
|
895
|
+
const pkg = safeReadJson(path.join(profileDir, 'package.json'));
|
|
896
|
+
const patchPath = path.join(profileDir, 'cordis.patch.yml');
|
|
897
|
+
const patchText = safeReadText(patchPath) || '';
|
|
898
|
+
const patchNodes = collectPatchNodes(parseYamlStructure(patchText));
|
|
899
|
+
|
|
900
|
+
const disabledMap = new Map();
|
|
901
|
+
for (const n of patchNodes) {
|
|
902
|
+
if (n.id && n.kind === 'override') {
|
|
903
|
+
if (n.disabled === true) disabledMap.set(n.id, true);
|
|
904
|
+
else if (n.disabled === false || n.disabledRaw === false) disabledMap.set(n.id, false);
|
|
905
|
+
}
|
|
330
906
|
}
|
|
331
907
|
|
|
332
|
-
const
|
|
908
|
+
const deps = pkg?.dependencies && typeof pkg.dependencies === 'object' ? pkg.dependencies : {};
|
|
909
|
+
const plugins = [];
|
|
910
|
+
for (const [name, versionSpec] of Object.entries(deps)) {
|
|
911
|
+
const isCore = name.startsWith('@deepseek-ai/');
|
|
912
|
+
const isSelf = SELF_LOADER_IDS.has(name);
|
|
913
|
+
const meta = readPackageLoaderIds(profileDir, name, guard);
|
|
914
|
+
const loaderIds = [...meta.ids];
|
|
915
|
+
for (const n of patchNodes) {
|
|
916
|
+
if (n.name === name && n.id && !loaderIds.includes(n.id)) {
|
|
917
|
+
loaderIds.push(n.id);
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
if (loaderIds.length === 0) {
|
|
921
|
+
const short = name.includes('/') ? name.split('/').pop() : name;
|
|
922
|
+
loaderIds.push(short);
|
|
923
|
+
if (short !== name) loaderIds.push(name);
|
|
924
|
+
}
|
|
333
925
|
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
926
|
+
const disabled = loaderIds.some((id) => disabledMap.get(id) === true);
|
|
927
|
+
plugins.push({
|
|
928
|
+
name,
|
|
929
|
+
version: meta.version || String(versionSpec || ''),
|
|
930
|
+
description: meta.description,
|
|
931
|
+
isCore,
|
|
932
|
+
isSelf,
|
|
933
|
+
canToggle: !isCore && !isSelf,
|
|
934
|
+
loaderIds,
|
|
935
|
+
primaryId: loaderIds[0],
|
|
936
|
+
enabled: !disabled,
|
|
937
|
+
disabled,
|
|
938
|
+
});
|
|
344
939
|
}
|
|
345
|
-
}
|
|
346
940
|
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
941
|
+
plugins.sort((a, b) => {
|
|
942
|
+
if (a.isSelf !== b.isSelf) return a.isSelf ? -1 : 1;
|
|
943
|
+
if (a.isCore !== b.isCore) return a.isCore ? 1 : -1;
|
|
944
|
+
return a.name.localeCompare(b.name);
|
|
945
|
+
});
|
|
352
946
|
|
|
353
|
-
const
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
947
|
+
const mcpServers = [];
|
|
948
|
+
for (const n of patchNodes) {
|
|
949
|
+
if (n.kind === 'insert' && n.name === MCP_CLIENT_PKG && n.id) {
|
|
950
|
+
const overrideDisabled = disabledMap.get(n.id);
|
|
951
|
+
const isDisabled = overrideDisabled !== undefined ? overrideDisabled : n.disabled === true;
|
|
952
|
+
const cfg = n.config || {};
|
|
953
|
+
mcpServers.push({
|
|
954
|
+
id: n.id,
|
|
955
|
+
serverName: String(cfg.serverName || n.id.replace(/^mcp-/, '')),
|
|
956
|
+
transport: String(cfg.transport || (cfg.url ? 'sse' : 'stdio')),
|
|
957
|
+
command: cfg.command ? String(cfg.command) : null,
|
|
958
|
+
url: cfg.url ? String(cfg.url) : null,
|
|
959
|
+
enabled: !isDisabled,
|
|
960
|
+
disabled: isDisabled,
|
|
961
|
+
canToggle: true,
|
|
962
|
+
});
|
|
365
963
|
}
|
|
366
964
|
}
|
|
367
965
|
|
|
368
|
-
|
|
369
|
-
target
|
|
966
|
+
return {
|
|
967
|
+
target: profileName,
|
|
968
|
+
profileExists: fs.existsSync(profileDir),
|
|
969
|
+
patchPath,
|
|
970
|
+
plugins,
|
|
971
|
+
mcpServers,
|
|
972
|
+
};
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
export function repairBrokenModuleLinks(dshHome, target = 'web') {
|
|
976
|
+
const profileName = target === 'desktop' ? 'desktop' : 'web';
|
|
977
|
+
const profileDir = path.join(dshHome, 'profiles', profileName);
|
|
978
|
+
const broken = findBrokenModuleLinks(profileDir);
|
|
979
|
+
if (broken.length === 0) {
|
|
980
|
+
return { ok: true, target: profileName, repairedCount: 0, unresolvableCount: 0, results: [] };
|
|
370
981
|
}
|
|
371
982
|
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
983
|
+
const otherProfile = profileName === 'web' ? 'desktop' : 'web';
|
|
984
|
+
const results = [];
|
|
985
|
+
|
|
986
|
+
for (const item of broken) {
|
|
987
|
+
const parts = item.name.split('/');
|
|
988
|
+
const candidates = [
|
|
989
|
+
path.join(dshHome, '.dsh-module-fallback', 'node_modules', ...parts),
|
|
990
|
+
path.join(dshHome, 'profiles', otherProfile, 'node_modules', ...parts),
|
|
991
|
+
path.join(dshHome, 'node_modules', ...parts),
|
|
992
|
+
];
|
|
993
|
+
|
|
994
|
+
let resolvedSource = null;
|
|
995
|
+
for (const cand of candidates) {
|
|
996
|
+
try {
|
|
997
|
+
if (fs.existsSync(cand)) {
|
|
998
|
+
const real = fs.realpathSync(cand);
|
|
999
|
+
if (fs.existsSync(path.join(real, 'package.json'))) {
|
|
1000
|
+
resolvedSource = real;
|
|
1001
|
+
break;
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
} catch {
|
|
1005
|
+
// Ignore broken candidate.
|
|
1006
|
+
}
|
|
376
1007
|
}
|
|
377
|
-
|
|
378
|
-
|
|
1008
|
+
|
|
1009
|
+
if (!resolvedSource) {
|
|
1010
|
+
results.push({ name: item.name, status: 'unresolvable', linkPath: item.linkPath });
|
|
1011
|
+
continue;
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
try {
|
|
1015
|
+
try {
|
|
1016
|
+
fs.unlinkSync(item.linkPath);
|
|
1017
|
+
} catch {
|
|
1018
|
+
fs.rmSync(item.linkPath, { recursive: true, force: true });
|
|
1019
|
+
}
|
|
1020
|
+
fs.symlinkSync(
|
|
1021
|
+
resolvedSource,
|
|
1022
|
+
item.linkPath,
|
|
1023
|
+
process.platform === 'win32' ? 'junction' : 'dir',
|
|
1024
|
+
);
|
|
1025
|
+
results.push({ name: item.name, status: 'repaired', linkPath: item.linkPath, targetDir: resolvedSource });
|
|
1026
|
+
} catch (err) {
|
|
1027
|
+
results.push({
|
|
1028
|
+
name: item.name,
|
|
1029
|
+
status: 'error',
|
|
1030
|
+
linkPath: item.linkPath,
|
|
1031
|
+
error: err instanceof Error ? err.message : String(err),
|
|
1032
|
+
});
|
|
379
1033
|
}
|
|
380
|
-
} catch {
|
|
381
|
-
// Ignore stat errors on individual directories
|
|
382
1034
|
}
|
|
383
1035
|
|
|
384
1036
|
return {
|
|
385
|
-
|
|
386
|
-
target,
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
1037
|
+
ok: results.every((r) => r.status === 'repaired'),
|
|
1038
|
+
target: profileName,
|
|
1039
|
+
repairedCount: results.filter((r) => r.status === 'repaired').length,
|
|
1040
|
+
unresolvableCount: results.filter((r) => r.status !== 'repaired').length,
|
|
1041
|
+
results,
|
|
1042
|
+
};
|
|
1043
|
+
}
|
|
1044
|
+
|
|
1045
|
+
function getSnapshotsRoot(dshHome) {
|
|
1046
|
+
return path.join(dshHome, 'guard-snapshots');
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
function collectSnapshotCandidates(dshHome, target) {
|
|
1050
|
+
const profiles = target === 'all' ? ['web', 'desktop'] : [target === 'desktop' ? 'desktop' : 'web'];
|
|
1051
|
+
const list = [];
|
|
1052
|
+
for (const p of profiles) {
|
|
1053
|
+
const dir = path.join(dshHome, 'profiles', p);
|
|
1054
|
+
const prefix = profiles.length > 1 ? `profile-${p}-` : 'profile-';
|
|
1055
|
+
list.push({ relPath: `profiles/${p}/cordis.patch.yml`, snapFile: `${prefix}cordis.patch.yml`, absPath: path.join(dir, 'cordis.patch.yml') });
|
|
1056
|
+
list.push({ relPath: `profiles/${p}/cordis.yml`, snapFile: `${prefix}cordis.yml`, absPath: path.join(dir, 'cordis.yml') });
|
|
1057
|
+
list.push({ relPath: `profiles/${p}/package.json`, snapFile: `${prefix}package.json`, absPath: path.join(dir, 'package.json') });
|
|
390
1058
|
}
|
|
1059
|
+
list.push({ relPath: 'settings.yaml', snapFile: 'home-settings.yaml', absPath: path.join(dshHome, 'settings.yaml') });
|
|
1060
|
+
return list;
|
|
391
1061
|
}
|
|
392
1062
|
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
1063
|
+
export function createSnapshot(dshHome, target = 'web', kind = 'manual', reason = '') {
|
|
1064
|
+
const normTarget = target === 'desktop' || target === 'all' ? target : 'web';
|
|
1065
|
+
const now = new Date();
|
|
1066
|
+
const stamp = [
|
|
1067
|
+
now.getUTCFullYear(),
|
|
1068
|
+
String(now.getUTCMonth() + 1).padStart(2, '0'),
|
|
1069
|
+
String(now.getUTCDate()).padStart(2, '0'),
|
|
1070
|
+
'-',
|
|
1071
|
+
String(now.getUTCHours()).padStart(2, '0'),
|
|
1072
|
+
String(now.getUTCMinutes()).padStart(2, '0'),
|
|
1073
|
+
String(now.getUTCSeconds()).padStart(2, '0'),
|
|
1074
|
+
'-',
|
|
1075
|
+
String(now.getUTCMilliseconds()).padStart(3, '0'),
|
|
1076
|
+
].join('');
|
|
1077
|
+
const safeKind = String(kind || 'manual').replace(/[^a-z0-9_-]/gi, '').slice(0, 24) || 'manual';
|
|
1078
|
+
const id = `${stamp}-${safeKind}-${normTarget}`;
|
|
1079
|
+
const snapDir = path.join(getSnapshotsRoot(dshHome), id);
|
|
1080
|
+
fs.mkdirSync(snapDir, { recursive: true });
|
|
402
1081
|
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
1082
|
+
const candidates = collectSnapshotCandidates(dshHome, normTarget);
|
|
1083
|
+
const items = [];
|
|
1084
|
+
|
|
1085
|
+
for (const cand of candidates) {
|
|
1086
|
+
if (CRED_SKIP_RE.test(cand.relPath) || !SNAPSHOT_SAFE_EXT_RE.test(cand.relPath)) continue;
|
|
1087
|
+
if (!fs.existsSync(cand.absPath)) continue;
|
|
1088
|
+
const raw = fs.readFileSync(cand.absPath);
|
|
1089
|
+
const dest = path.join(snapDir, cand.snapFile);
|
|
1090
|
+
fs.writeFileSync(dest, raw);
|
|
1091
|
+
items.push({
|
|
1092
|
+
relPath: cand.relPath,
|
|
1093
|
+
snapFile: cand.snapFile,
|
|
1094
|
+
sha256: crypto.createHash('sha256').update(raw).digest('hex'),
|
|
1095
|
+
size: raw.length,
|
|
1096
|
+
});
|
|
1097
|
+
}
|
|
1098
|
+
|
|
1099
|
+
const manifest = {
|
|
1100
|
+
id,
|
|
1101
|
+
source: 'plugin',
|
|
1102
|
+
target: normTarget,
|
|
1103
|
+
kind: safeKind,
|
|
1104
|
+
reason: String(reason || (safeKind === 'manual' ? '手动配置快照' : safeKind)),
|
|
1105
|
+
createdAt: now.toISOString(),
|
|
1106
|
+
itemCount: items.length,
|
|
1107
|
+
items,
|
|
1108
|
+
};
|
|
1109
|
+
atomicWriteText(path.join(snapDir, 'manifest.json'), JSON.stringify(manifest, null, 2));
|
|
1110
|
+
return { ok: true, snapshot: manifest, dir: snapDir };
|
|
1111
|
+
}
|
|
1112
|
+
|
|
1113
|
+
export function togglePatchEntry(dshHome, target = 'web', id, disabled, guard = null) {
|
|
1114
|
+
const profileName = target === 'desktop' ? 'desktop' : 'web';
|
|
1115
|
+
const entryId = String(id || '').trim();
|
|
1116
|
+
if (!entryId) return { ok: false, error: '缺少条目 ID' };
|
|
1117
|
+
if (SELF_LOADER_IDS.has(entryId)) {
|
|
1118
|
+
return { ok: false, error: '不能通过伴生插件禁用当前正在运行的 @gluztm/dsh-guard 自身' };
|
|
1119
|
+
}
|
|
1120
|
+
|
|
1121
|
+
const ext = inspectExtensions(dshHome, profileName, guard);
|
|
1122
|
+
const matchedPlugin = ext.plugins.find((p) => p.loaderIds.includes(entryId) || p.name === entryId);
|
|
1123
|
+
if (matchedPlugin && matchedPlugin.isCore) {
|
|
1124
|
+
return { ok: false, error: `核心组件 ${matchedPlugin.name} 受保护,请保持启用` };
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
const patchPath = path.join(dshHome, 'profiles', profileName, 'cordis.patch.yml');
|
|
1128
|
+
const existingText = safeReadText(patchPath) ?? '';
|
|
1129
|
+
const targetId = matchedPlugin ? matchedPlugin.primaryId : entryId;
|
|
1130
|
+
const wantDisabled = Boolean(disabled);
|
|
1131
|
+
|
|
1132
|
+
const preSnap = createSnapshot(
|
|
1133
|
+
dshHome,
|
|
1134
|
+
profileName,
|
|
1135
|
+
'auto-toggle',
|
|
1136
|
+
`${wantDisabled ? '禁用' : '启用'} ${targetId} 前自动快照`,
|
|
1137
|
+
);
|
|
1138
|
+
|
|
1139
|
+
const rawLines = existingText ? existingText.replace(/\r\n/g, '\n').split('\n') : [];
|
|
1140
|
+
const parsedNodes = collectPatchNodes(parseYamlStructure(existingText));
|
|
1141
|
+
const idsToMatch = matchedPlugin ? new Set(matchedPlugin.loaderIds) : new Set([targetId]);
|
|
1142
|
+
|
|
1143
|
+
const overrideBlocks = parsedNodes.filter(
|
|
1144
|
+
(n) => n.kind === 'override' && n.id && idsToMatch.has(n.id) && Array.isArray(n.lineRange),
|
|
1145
|
+
);
|
|
1146
|
+
const insertBlocks = parsedNodes.filter(
|
|
1147
|
+
(n) => n.kind === 'insert' && n.id && idsToMatch.has(n.id) && Array.isArray(n.lineRange),
|
|
1148
|
+
);
|
|
1149
|
+
|
|
1150
|
+
const linesToRemove = new Set();
|
|
1151
|
+
let updatedOverrideInPlace = false;
|
|
1152
|
+
|
|
1153
|
+
if (!wantDisabled) {
|
|
1154
|
+
for (const blk of overrideBlocks) {
|
|
1155
|
+
const [s, e] = blk.lineRange;
|
|
1156
|
+
const nonControlKeys = blk.keys.filter((k) => k !== 'id' && k !== 'disabled');
|
|
1157
|
+
if (nonControlKeys.length === 0) {
|
|
1158
|
+
for (let i = s; i <= e; i += 1) linesToRemove.add(i);
|
|
1159
|
+
} else {
|
|
1160
|
+
for (let i = s; i <= e; i += 1) {
|
|
1161
|
+
if (/^\s+disabled:\s*/.test(rawLines[i])) linesToRemove.add(i);
|
|
1162
|
+
}
|
|
1163
|
+
}
|
|
412
1164
|
}
|
|
1165
|
+
for (const blk of insertBlocks) {
|
|
1166
|
+
const [s, e] = blk.lineRange;
|
|
1167
|
+
for (let i = s; i <= e; i += 1) {
|
|
1168
|
+
if (/^\s+disabled:\s*true\b/.test(rawLines[i])) linesToRemove.add(i);
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
} else {
|
|
1172
|
+
for (const blk of overrideBlocks) {
|
|
1173
|
+
const [s, e] = blk.lineRange;
|
|
1174
|
+
let hadDisabledLine = false;
|
|
1175
|
+
for (let i = s; i <= e; i += 1) {
|
|
1176
|
+
if (/^\s+disabled:\s*/.test(rawLines[i])) {
|
|
1177
|
+
rawLines[i] = rawLines[i].replace(/(^\s+disabled:\s*).*/, '$1true');
|
|
1178
|
+
hadDisabledLine = true;
|
|
1179
|
+
updatedOverrideInPlace = true;
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
if (!hadDisabledLine) {
|
|
1183
|
+
rawLines.splice(e + 1, 0, ' disabled: true');
|
|
1184
|
+
updatedOverrideInPlace = true;
|
|
1185
|
+
}
|
|
1186
|
+
}
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1189
|
+
let nextLines = rawLines.filter((_, idx) => !linesToRemove.has(idx));
|
|
1190
|
+
if (wantDisabled && !updatedOverrideInPlace) {
|
|
1191
|
+
while (nextLines.length > 0 && !nextLines[nextLines.length - 1].trim()) nextLines.pop();
|
|
1192
|
+
nextLines.push(`- id: ${quoteYamlId(targetId)}`, ' disabled: true');
|
|
413
1193
|
}
|
|
414
1194
|
|
|
415
|
-
|
|
1195
|
+
const finalBody = nextLines.length > 0 ? `${nextLines.join('\n').replace(/\n+$/, '')}\n` : '';
|
|
1196
|
+
atomicWriteText(patchPath, finalBody);
|
|
1197
|
+
|
|
1198
|
+
return {
|
|
1199
|
+
ok: true,
|
|
1200
|
+
target: profileName,
|
|
1201
|
+
id: targetId,
|
|
1202
|
+
enabled: !wantDisabled,
|
|
1203
|
+
disabled: wantDisabled,
|
|
1204
|
+
preSnapshotId: preSnap.snapshot.id,
|
|
1205
|
+
patchPath,
|
|
1206
|
+
restartHint: profileName === 'web'
|
|
1207
|
+
? '已写入 Web 配置文件,重载 DSH 服务后生效(已在变更前自动保存快照)'
|
|
1208
|
+
: '已写入桌面端配置文件,重启 DSH 桌面端后生效(已在变更前自动保存快照)',
|
|
1209
|
+
};
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
function readSnapshotRecordsFromDir(rootDir, sourceKind, dshHome) {
|
|
1213
|
+
if (!rootDir || !fs.existsSync(rootDir)) return [];
|
|
1214
|
+
let dirs = [];
|
|
416
1215
|
try {
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
1216
|
+
dirs = fs.readdirSync(rootDir, { withFileTypes: true }).filter((d) => d.isDirectory());
|
|
1217
|
+
} catch {
|
|
1218
|
+
return [];
|
|
1219
|
+
}
|
|
1220
|
+
|
|
1221
|
+
const records = [];
|
|
1222
|
+
for (const d of dirs) {
|
|
1223
|
+
const full = path.join(rootDir, d.name);
|
|
1224
|
+
const manifest = safeReadJson(path.join(full, 'manifest.json'));
|
|
1225
|
+
let createdAt = manifest?.createdAt || manifest?.CreatedAt || null;
|
|
1226
|
+
if (!createdAt) {
|
|
1227
|
+
try {
|
|
1228
|
+
createdAt = fs.statSync(full).mtime.toISOString();
|
|
1229
|
+
} catch {
|
|
1230
|
+
createdAt = null;
|
|
424
1231
|
}
|
|
425
1232
|
}
|
|
426
|
-
|
|
427
|
-
|
|
1233
|
+
|
|
1234
|
+
const rawItems = Array.isArray(manifest?.items)
|
|
1235
|
+
? manifest.items
|
|
1236
|
+
: Array.isArray(manifest?.Items)
|
|
1237
|
+
? manifest.Items
|
|
1238
|
+
: null;
|
|
1239
|
+
|
|
1240
|
+
let files = [];
|
|
1241
|
+
if (rawItems) {
|
|
1242
|
+
files = rawItems
|
|
1243
|
+
.map((it) => {
|
|
1244
|
+
const relPath = String(it.relPath || it.RelPath || '').replace(/\\/g, '/');
|
|
1245
|
+
const snapFile = String(it.snapFile || it.SnapFile || path.basename(relPath));
|
|
1246
|
+
if (!snapFile || CRED_SKIP_RE.test(snapFile) || CRED_SKIP_RE.test(relPath)) return null;
|
|
1247
|
+
const snapSha = it.sha256 || it.Sha256 || sha256File(path.join(full, snapFile));
|
|
1248
|
+
let status = 'unknown';
|
|
1249
|
+
if (relPath) {
|
|
1250
|
+
const livePath = path.join(dshHome, ...relPath.split('/'));
|
|
1251
|
+
if (!fs.existsSync(livePath)) {
|
|
1252
|
+
status = 'missing_now';
|
|
1253
|
+
} else {
|
|
1254
|
+
const liveSha = sha256File(livePath);
|
|
1255
|
+
status = liveSha && snapSha ? (liveSha === snapSha ? 'same' : 'modified') : 'unknown';
|
|
1256
|
+
}
|
|
1257
|
+
}
|
|
1258
|
+
return {
|
|
1259
|
+
name: snapFile,
|
|
1260
|
+
relPath: relPath || snapFile,
|
|
1261
|
+
size: Number(it.size || it.Size || 0),
|
|
1262
|
+
sha256: snapSha,
|
|
1263
|
+
status,
|
|
1264
|
+
restorableInPlugin: RESTORABLE_REL_RE.test(relPath) && SNAPSHOT_SAFE_EXT_RE.test(snapFile),
|
|
1265
|
+
};
|
|
1266
|
+
})
|
|
1267
|
+
.filter(Boolean);
|
|
1268
|
+
} else if (Array.isArray(manifest?.files)) {
|
|
1269
|
+
files = manifest.files
|
|
1270
|
+
.filter((f) => typeof f === 'string' && !CRED_SKIP_RE.test(f))
|
|
1271
|
+
.map((f) => ({
|
|
1272
|
+
name: f,
|
|
1273
|
+
relPath: f,
|
|
1274
|
+
size: 0,
|
|
1275
|
+
sha256: null,
|
|
1276
|
+
status: 'unknown',
|
|
1277
|
+
restorableInPlugin: false,
|
|
1278
|
+
}));
|
|
1279
|
+
} else {
|
|
1280
|
+
try {
|
|
1281
|
+
const listed = fs.readdirSync(full, { withFileTypes: true }).filter((f) => f.isFile() && f.name !== 'manifest.json');
|
|
1282
|
+
files = listed
|
|
1283
|
+
.filter((f) => !CRED_SKIP_RE.test(f.name))
|
|
1284
|
+
.map((f) => {
|
|
1285
|
+
const p = path.join(full, f.name);
|
|
1286
|
+
let size = 0;
|
|
1287
|
+
try {
|
|
1288
|
+
size = fs.statSync(p).size;
|
|
1289
|
+
} catch {
|
|
1290
|
+
size = 0;
|
|
1291
|
+
}
|
|
1292
|
+
return {
|
|
1293
|
+
name: f.name,
|
|
1294
|
+
relPath: f.name,
|
|
1295
|
+
size,
|
|
1296
|
+
sha256: sha256File(p),
|
|
1297
|
+
status: 'unknown',
|
|
1298
|
+
restorableInPlugin: false,
|
|
1299
|
+
};
|
|
1300
|
+
});
|
|
1301
|
+
} catch {
|
|
1302
|
+
files = [];
|
|
1303
|
+
}
|
|
1304
|
+
}
|
|
1305
|
+
|
|
1306
|
+
const changedCount = files.filter((f) => f.status === 'modified' || f.status === 'missing_now').length;
|
|
1307
|
+
records.push({
|
|
1308
|
+
id: String(manifest?.id || manifest?.Id || d.name),
|
|
1309
|
+
source: manifest?.source || sourceKind,
|
|
1310
|
+
dir: full,
|
|
1311
|
+
target: manifest?.target || manifest?.Target || (d.name.includes('desktop') ? 'desktop' : 'web'),
|
|
1312
|
+
kind: manifest?.kind || manifest?.Kind || 'snapshot',
|
|
1313
|
+
reason: manifest?.reason || manifest?.Reason || '',
|
|
1314
|
+
createdAt,
|
|
1315
|
+
itemCount: Number(manifest?.itemCount || manifest?.ItemCount || files.length),
|
|
1316
|
+
changedCount,
|
|
1317
|
+
restorableCount: files.filter((f) => f.restorableInPlugin).length,
|
|
1318
|
+
files,
|
|
1319
|
+
});
|
|
428
1320
|
}
|
|
1321
|
+
return records;
|
|
1322
|
+
}
|
|
1323
|
+
|
|
1324
|
+
export function inspectSnapshots(options = {}) {
|
|
1325
|
+
const dshHome = resolveDshHome(options.dshHome);
|
|
1326
|
+
const guard = options.guard || locateGuardInstallation(options);
|
|
1327
|
+
const limit = Number.isFinite(options.limit) ? Math.max(1, Math.min(50, options.limit)) : 10;
|
|
1328
|
+
const targetFilter = options.target === 'web' || options.target === 'desktop' ? options.target : 'all';
|
|
429
1329
|
|
|
430
|
-
|
|
1330
|
+
const isolateGuardOnly = Boolean(options.guardHome && !options.dshHome && !process.env.DSH_HOME);
|
|
1331
|
+
const pluginRoot = getSnapshotsRoot(dshHome);
|
|
1332
|
+
const pluginRecs = isolateGuardOnly ? [] : readSnapshotRecordsFromDir(pluginRoot, 'plugin', dshHome);
|
|
1333
|
+
const desktopRecs = guard.snapshotsDir && path.resolve(guard.snapshotsDir) !== path.resolve(pluginRoot)
|
|
1334
|
+
? readSnapshotRecordsFromDir(guard.snapshotsDir, 'desktop', dshHome)
|
|
1335
|
+
: [];
|
|
1336
|
+
|
|
1337
|
+
const merged = new Map();
|
|
1338
|
+
for (const r of [...pluginRecs, ...desktopRecs]) {
|
|
1339
|
+
if (!merged.has(r.id)) merged.set(r.id, r);
|
|
1340
|
+
}
|
|
1341
|
+
|
|
1342
|
+
let snapshots = Array.from(merged.values()).sort((a, b) => {
|
|
1343
|
+
const ta = a.createdAt ? Date.parse(a.createdAt) : 0;
|
|
1344
|
+
const tb = b.createdAt ? Date.parse(b.createdAt) : 0;
|
|
1345
|
+
return tb - ta || b.id.localeCompare(a.id);
|
|
1346
|
+
});
|
|
1347
|
+
|
|
1348
|
+
if (targetFilter !== 'all') {
|
|
1349
|
+
snapshots = snapshots.filter((s) => s.target === targetFilter || s.target === 'all');
|
|
1350
|
+
}
|
|
431
1351
|
|
|
432
1352
|
return {
|
|
433
|
-
|
|
434
|
-
guardInstalled: guard.installed,
|
|
435
|
-
total: items.length,
|
|
436
|
-
snapshots: items.slice(0, limit),
|
|
1353
|
+
available: snapshots.length > 0 || fs.existsSync(pluginRoot) || Boolean(guard.snapshotsDir && fs.existsSync(guard.snapshotsDir)),
|
|
1354
|
+
guardInstalled: Boolean(guard.installed),
|
|
437
1355
|
releaseUrl: RELEASE_URL,
|
|
438
|
-
|
|
439
|
-
|
|
1356
|
+
pluginSnapshotsDir: pluginRoot,
|
|
1357
|
+
snapshotsDir: guard.snapshotsDir || pluginRoot,
|
|
1358
|
+
total: snapshots.length,
|
|
1359
|
+
snapshots: snapshots.slice(0, limit),
|
|
1360
|
+
};
|
|
1361
|
+
}
|
|
1362
|
+
|
|
1363
|
+
export function restoreSnapshotConfig(dshHome, guard, snapshotId) {
|
|
1364
|
+
const id = String(snapshotId || '').trim();
|
|
1365
|
+
if (!id || /[\\/]|\.\./.test(id)) {
|
|
1366
|
+
return { ok: false, error: '无效的快照 ID' };
|
|
440
1367
|
}
|
|
1368
|
+
|
|
1369
|
+
const listed = inspectSnapshots({ dshHome, guard, limit: 50 });
|
|
1370
|
+
const snap = listed.snapshots.find((s) => s.id === id);
|
|
1371
|
+
if (!snap) {
|
|
1372
|
+
return { ok: false, error: `未找到快照 ${id}` };
|
|
1373
|
+
}
|
|
1374
|
+
|
|
1375
|
+
const restorable = snap.files.filter((f) => f.restorableInPlugin);
|
|
1376
|
+
if (restorable.length === 0) {
|
|
1377
|
+
return {
|
|
1378
|
+
ok: false,
|
|
1379
|
+
error: '该快照仅包含桌面端级产物(如二进制包、注册表或非 YAML 档案),请在插件边界说明中使用原生桌面端还原',
|
|
1380
|
+
};
|
|
1381
|
+
}
|
|
1382
|
+
|
|
1383
|
+
const preSnap = createSnapshot(
|
|
1384
|
+
dshHome,
|
|
1385
|
+
snap.target === 'desktop' || snap.target === 'all' ? snap.target : 'web',
|
|
1386
|
+
'pre-restore',
|
|
1387
|
+
`恢复快照 ${id} 前自动备份`,
|
|
1388
|
+
);
|
|
1389
|
+
|
|
1390
|
+
const restoredFiles = [];
|
|
1391
|
+
const skippedFiles = [];
|
|
1392
|
+
const resolvedHome = path.resolve(dshHome);
|
|
1393
|
+
|
|
1394
|
+
for (const f of snap.files) {
|
|
1395
|
+
if (!f.restorableInPlugin) {
|
|
1396
|
+
skippedFiles.push({ relPath: f.relPath, reason: '超出伴生插件白名单范围' });
|
|
1397
|
+
continue;
|
|
1398
|
+
}
|
|
1399
|
+
const snapFile = String(f.snapFile || f.name || '').trim();
|
|
1400
|
+
if (!snapFile || CRED_SKIP_RE.test(snapFile) || CRED_SKIP_RE.test(f.relPath) || /[\\/]|\.\./.test(snapFile)) {
|
|
1401
|
+
skippedFiles.push({ relPath: f.relPath, reason: '安全跳过' });
|
|
1402
|
+
continue;
|
|
1403
|
+
}
|
|
1404
|
+
|
|
1405
|
+
const srcFile = path.join(snap.dir, snapFile);
|
|
1406
|
+
const destFile = path.resolve(resolvedHome, ...f.relPath.split('/'));
|
|
1407
|
+
if (!destFile.startsWith(`${resolvedHome}${path.sep}`)) {
|
|
1408
|
+
skippedFiles.push({ relPath: f.relPath, reason: '路径越界保护' });
|
|
1409
|
+
continue;
|
|
1410
|
+
}
|
|
1411
|
+
if (!fs.existsSync(srcFile)) {
|
|
1412
|
+
skippedFiles.push({ relPath: f.relPath, reason: '快照文件缺失' });
|
|
1413
|
+
continue;
|
|
1414
|
+
}
|
|
1415
|
+
|
|
1416
|
+
const content = fs.readFileSync(srcFile, 'utf8');
|
|
1417
|
+
atomicWriteText(destFile, content);
|
|
1418
|
+
restoredFiles.push(f.relPath);
|
|
1419
|
+
}
|
|
1420
|
+
|
|
1421
|
+
return {
|
|
1422
|
+
ok: restoredFiles.length > 0,
|
|
1423
|
+
snapshotId: id,
|
|
1424
|
+
preRestoreId: preSnap.snapshot.id,
|
|
1425
|
+
restoredFiles,
|
|
1426
|
+
skippedFiles,
|
|
1427
|
+
};
|
|
1428
|
+
}
|
|
1429
|
+
|
|
1430
|
+
export function inspectHealth(options = {}) {
|
|
1431
|
+
const dshHome = resolveDshHome(options.dshHome);
|
|
1432
|
+
const guard = locateGuardInstallation(options);
|
|
1433
|
+
const web = inspectProfile(dshHome, 'web');
|
|
1434
|
+
const desktop = inspectProfile(dshHome, 'desktop');
|
|
1435
|
+
const credentials = inspectCredentialKeysMasked(dshHome);
|
|
1436
|
+
const providers = inspectProviders(dshHome);
|
|
1437
|
+
const extensionsWeb = inspectExtensions(dshHome, 'web', guard);
|
|
1438
|
+
const extensionsDesktop = inspectExtensions(dshHome, 'desktop', guard);
|
|
1439
|
+
const snapshots = inspectSnapshots({ dshHome, guard, limit: 8 });
|
|
1440
|
+
|
|
1441
|
+
const readyKeySet = new Set(credentials.keys.filter((k) => k.present || k.envSet).map((k) => k.key));
|
|
1442
|
+
const referencedEnvSet = new Set([...(web.referencedEnvKeys || []), ...(desktop.referencedEnvKeys || [])]);
|
|
1443
|
+
const missingReferencedKeys = Array.from(referencedEnvSet).filter((k) => !readyKeySet.has(k));
|
|
1444
|
+
credentials.missingReferencedKeys = missingReferencedKeys;
|
|
1445
|
+
|
|
1446
|
+
const issues = [];
|
|
1447
|
+
if (!fs.existsSync(dshHome)) {
|
|
1448
|
+
issues.push(`未找到 DSH 目录: ${dshHome}`);
|
|
1449
|
+
}
|
|
1450
|
+
if (web.missingBundles && web.missingBundles.length > 0) {
|
|
1451
|
+
issues.push(`web 存在未在 dependencies 注册的 bundle: ${web.missingBundles.join(', ')}`);
|
|
1452
|
+
}
|
|
1453
|
+
if (desktop.missingBundles && desktop.missingBundles.length > 0) {
|
|
1454
|
+
issues.push(`desktop 存在未在 dependencies 注册的 bundle: ${desktop.missingBundles.join(', ')}`);
|
|
1455
|
+
}
|
|
1456
|
+
if (web.exists && desktop.exists) {
|
|
1457
|
+
if (web.patchHash && desktop.patchHash && web.patchHash !== desktop.patchHash) {
|
|
1458
|
+
issues.push('web 和 desktop 的 cordis.patch.yml 存在配置漂移');
|
|
1459
|
+
}
|
|
1460
|
+
if (web.totalDependencies !== desktop.totalDependencies) {
|
|
1461
|
+
issues.push(`依赖数量差异: web=${web.totalDependencies}, desktop=${desktop.totalDependencies}`);
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
if (web.brokenLinkCount > 0) {
|
|
1465
|
+
issues.push(`web 存在 ${web.brokenLinkCount} 个断裂依赖软链接`);
|
|
1466
|
+
}
|
|
1467
|
+
if (desktop.brokenLinkCount > 0) {
|
|
1468
|
+
issues.push(`desktop 存在 ${desktop.brokenLinkCount} 个断裂依赖软链接`);
|
|
1469
|
+
}
|
|
1470
|
+
if (!credentials.present) {
|
|
1471
|
+
issues.push('.credentials.yaml 尚未初始化');
|
|
1472
|
+
}
|
|
1473
|
+
if (missingReferencedKeys.length > 0) {
|
|
1474
|
+
issues.push(`配置中引用的凭据键缺失: ${missingReferencedKeys.join(', ')}`);
|
|
1475
|
+
}
|
|
1476
|
+
|
|
1477
|
+
return {
|
|
1478
|
+
companionVersion: PACKAGE_VERSION,
|
|
1479
|
+
checkedAt: new Date().toISOString(),
|
|
1480
|
+
platform: process.platform,
|
|
1481
|
+
dshHome,
|
|
1482
|
+
dshHomeExists: fs.existsSync(dshHome),
|
|
1483
|
+
healthy: issues.length === 0,
|
|
1484
|
+
issuesCount: issues.length,
|
|
1485
|
+
issues,
|
|
1486
|
+
driftWarnings: issues,
|
|
1487
|
+
guard,
|
|
1488
|
+
profiles: { web, desktop },
|
|
1489
|
+
credentials,
|
|
1490
|
+
providers,
|
|
1491
|
+
extensions: {
|
|
1492
|
+
web: extensionsWeb,
|
|
1493
|
+
desktop: extensionsDesktop,
|
|
1494
|
+
},
|
|
1495
|
+
snapshots,
|
|
1496
|
+
};
|
|
441
1497
|
}
|
|
442
1498
|
|
|
443
|
-
/**
|
|
444
|
-
* Locate or optionally launch the local Windows DSHGuard desktop supervisor.
|
|
445
|
-
*/
|
|
446
1499
|
export function openGuard(options = {}) {
|
|
447
|
-
const guard = locateGuardInstallation(options)
|
|
1500
|
+
const guard = locateGuardInstallation(options);
|
|
1501
|
+
if (process.platform !== 'win32') {
|
|
1502
|
+
return {
|
|
1503
|
+
ok: false,
|
|
1504
|
+
installed: false,
|
|
1505
|
+
launched: false,
|
|
1506
|
+
reason: 'non-windows',
|
|
1507
|
+
message: `当前系统为 ${process.platform};原版 DSHGuard 桌面应用目前仅提供 Windows 安装包(伴生插件本身的插件/凭据/快照功能已在当前平台完整可用)。`,
|
|
1508
|
+
releaseUrl: RELEASE_URL,
|
|
1509
|
+
installerUrl: INSTALLER_URL,
|
|
1510
|
+
installUrl: INSTALLER_URL,
|
|
1511
|
+
};
|
|
1512
|
+
}
|
|
448
1513
|
if (!guard.installed || !guard.exePath) {
|
|
449
1514
|
return {
|
|
1515
|
+
ok: false,
|
|
450
1516
|
installed: false,
|
|
451
1517
|
launched: false,
|
|
452
|
-
|
|
453
|
-
|
|
1518
|
+
reason: 'not-installed',
|
|
1519
|
+
message: '未在本机检测到 DSHGuard.exe(伴生插件本身已内置插件开关、凭据写入与配置快照);如需跨进程托管或硬件加密隔离,可安装 Windows 桌面端。',
|
|
454
1520
|
releaseUrl: RELEASE_URL,
|
|
455
1521
|
installerUrl: INSTALLER_URL,
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
}
|
|
1522
|
+
installUrl: INSTALLER_URL,
|
|
1523
|
+
};
|
|
459
1524
|
}
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
}
|
|
473
|
-
}
|
|
474
|
-
try {
|
|
475
|
-
const child = spawn(guard.exePath, [], {
|
|
476
|
-
detached: true,
|
|
477
|
-
stdio: 'ignore',
|
|
478
|
-
windowsHide: false,
|
|
479
|
-
})
|
|
480
|
-
if (typeof child.on === 'function') {
|
|
481
|
-
child.on('error', () => {})
|
|
482
|
-
}
|
|
483
|
-
child.unref()
|
|
484
|
-
return {
|
|
485
|
-
installed: true,
|
|
486
|
-
launched: true,
|
|
487
|
-
exePath: guard.exePath,
|
|
488
|
-
guardHome: guard.guardHome,
|
|
489
|
-
releaseUrl: RELEASE_URL,
|
|
490
|
-
installerUrl: INSTALLER_URL,
|
|
491
|
-
repoUrl: REPO_URL,
|
|
492
|
-
message: `已在桌面拉起 DSHGuard 守护壳(${basename(guard.exePath)})。`,
|
|
493
|
-
}
|
|
494
|
-
} catch (err) {
|
|
495
|
-
return {
|
|
496
|
-
installed: true,
|
|
497
|
-
launched: false,
|
|
498
|
-
exePath: guard.exePath,
|
|
499
|
-
guardHome: guard.guardHome,
|
|
500
|
-
releaseUrl: RELEASE_URL,
|
|
501
|
-
installerUrl: INSTALLER_URL,
|
|
502
|
-
repoUrl: REPO_URL,
|
|
503
|
-
message: `拉起 DSHGuard 守护壳失败:${err && err.message ? err.message : String(err)}`,
|
|
504
|
-
}
|
|
505
|
-
}
|
|
1525
|
+
if (!options.launch || options.dryRun) {
|
|
1526
|
+
return {
|
|
1527
|
+
ok: true,
|
|
1528
|
+
installed: true,
|
|
1529
|
+
launched: Boolean(options.dryRun && options.launch),
|
|
1530
|
+
dryRun: Boolean(options.dryRun),
|
|
1531
|
+
exePath: guard.exePath,
|
|
1532
|
+
message: `已定位到桌面端:${guard.exePath}${options.launch ? '(未拉起进程)' : ''}`,
|
|
1533
|
+
releaseUrl: RELEASE_URL,
|
|
1534
|
+
installerUrl: INSTALLER_URL,
|
|
1535
|
+
installUrl: INSTALLER_URL,
|
|
1536
|
+
};
|
|
506
1537
|
}
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
1538
|
+
try {
|
|
1539
|
+
const child = spawn(guard.exePath, [], {
|
|
1540
|
+
detached: true,
|
|
1541
|
+
stdio: 'ignore',
|
|
1542
|
+
windowsHide: false,
|
|
1543
|
+
});
|
|
1544
|
+
child.unref();
|
|
1545
|
+
return {
|
|
1546
|
+
ok: true,
|
|
1547
|
+
installed: true,
|
|
1548
|
+
launched: true,
|
|
1549
|
+
exePath: guard.exePath,
|
|
1550
|
+
pid: child.pid || null,
|
|
1551
|
+
message: `已启动桌面端:${guard.exePath}`,
|
|
1552
|
+
releaseUrl: RELEASE_URL,
|
|
1553
|
+
installerUrl: INSTALLER_URL,
|
|
1554
|
+
installUrl: INSTALLER_URL,
|
|
1555
|
+
};
|
|
1556
|
+
} catch (err) {
|
|
1557
|
+
return {
|
|
1558
|
+
ok: false,
|
|
1559
|
+
installed: true,
|
|
1560
|
+
launched: false,
|
|
1561
|
+
reason: 'spawn-error',
|
|
1562
|
+
exePath: guard.exePath,
|
|
1563
|
+
message: `启动失败:${err instanceof Error ? err.message : String(err)}`,
|
|
1564
|
+
releaseUrl: RELEASE_URL,
|
|
1565
|
+
installerUrl: INSTALLER_URL,
|
|
1566
|
+
installUrl: INSTALLER_URL,
|
|
1567
|
+
};
|
|
517
1568
|
}
|
|
518
1569
|
}
|
|
519
1570
|
|
|
520
1571
|
export function formatHealthText(report) {
|
|
521
|
-
const
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
}
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
)
|
|
536
|
-
}
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
}
|
|
555
|
-
}
|
|
556
|
-
return lines.join('\n')
|
|
557
|
-
}
|
|
558
|
-
|
|
559
|
-
export function formatSnapshotsText(report) {
|
|
560
|
-
if (!report.snapshotsDir || report.total === 0) {
|
|
561
|
-
return report.guardInstalled
|
|
562
|
-
? '本机 DSHGuard 尚无快照存档(Snapshots 目录为空或不存在)。'
|
|
563
|
-
: `未定位到本机 DSHGuard 快照目录;安装 Windows 桌面控制台可自动存档并于崩溃时回滚(支持四协议模型配置与 CC Switch 导入):\n安装包直链:${report.installerUrl || INSTALLER_URL}\n发布页:${report.releaseUrl}`
|
|
564
|
-
}
|
|
565
|
-
const lines = [`已找到 ${report.total} 份守护壳快照(展示最近 ${report.snapshots.length} 份):`]
|
|
566
|
-
for (const snap of report.snapshots) {
|
|
567
|
-
const meta = [snap.target, `${snap.itemCount} 项`, snap.createdAt].filter(Boolean).join(' · ')
|
|
568
|
-
lines.push(`- ${snap.id}(${meta})${snap.reason ? ` — ${snap.reason}` : ''}`)
|
|
569
|
-
}
|
|
570
|
-
return lines.join('\n')
|
|
1572
|
+
const web = report.profiles.web;
|
|
1573
|
+
const desk = report.profiles.desktop;
|
|
1574
|
+
const cred = report.credentials;
|
|
1575
|
+
const provCount = Array.isArray(report.providers) ? report.providers.length : 0;
|
|
1576
|
+
const mcpCount = (report.extensions?.web?.mcpServers?.length || 0);
|
|
1577
|
+
const lines = [
|
|
1578
|
+
`[dsh-guard v${report.companionVersion}] DSH Home: ${report.dshHome} (${report.dshHomeExists ? '已找到' : '未找到'})`,
|
|
1579
|
+
`桌面端: ${report.guard.installed ? `已安装 (${report.guard.exePath})` : report.platform === 'win32' ? '未检测到本地 DSHGuard.exe(非必需,插件功能可独立运行)' : `${report.platform}(原生桌面端仅限 Windows)`}`,
|
|
1580
|
+
`Web 档案: ${web.exists ? `${web.totalDependencies} 依赖(第三方 ${web.thirdPartyCount}),MCP ${mcpCount},断链 ${web.brokenLinkCount},patch=${web.patchHash || '无'}` : '未找到'}`,
|
|
1581
|
+
`桌面档案: ${desk.exists ? `${desk.totalDependencies} 依赖(第三方 ${desk.thirdPartyCount}),断链 ${desk.brokenLinkCount},patch=${desk.patchHash || '无'}` : '未找到'}`,
|
|
1582
|
+
`凭据与模型: ${cred.present ? `${cred.count} 个密钥引用(含 ${cred.protectedCount} 保护账号)` : '未找到 .credentials.yaml'} · ${provCount} 个模型提供商`,
|
|
1583
|
+
`快照: 共 ${report.snapshots.total} 份`,
|
|
1584
|
+
];
|
|
1585
|
+
if (report.driftWarnings.length > 0) {
|
|
1586
|
+
lines.push(`提示: ${report.driftWarnings.join(';')}`);
|
|
1587
|
+
} else {
|
|
1588
|
+
lines.push('状态: web/desktop 结构一致且无断链。');
|
|
1589
|
+
}
|
|
1590
|
+
return lines.join('\n');
|
|
1591
|
+
}
|
|
1592
|
+
|
|
1593
|
+
export function formatSnapshotsText(snapReport) {
|
|
1594
|
+
const lines = [
|
|
1595
|
+
`[dsh-guard] 快照目录: ${snapReport.pluginSnapshotsDir}`,
|
|
1596
|
+
`累计快照: ${snapReport.total} 份(展示最近 ${snapReport.snapshots.length} 份)`,
|
|
1597
|
+
];
|
|
1598
|
+
if (snapReport.snapshots.length === 0) {
|
|
1599
|
+
lines.push('暂无快照。在插件 UI 快照页签或运行 /guard backup 即可生成本地配置快照。');
|
|
1600
|
+
return lines.join('\n');
|
|
1601
|
+
}
|
|
1602
|
+
for (const s of snapReport.snapshots) {
|
|
1603
|
+
const srcTag = s.source === 'desktop' ? '桌面端' : '插件';
|
|
1604
|
+
const diffTag = s.changedCount > 0 ? ` · 与磁盘有 ${s.changedCount} 处差异` : '';
|
|
1605
|
+
lines.push(`- ${s.id} [${srcTag}/${s.target}/${s.kind}]${s.reason ? ` (${s.reason})` : ''} · ${s.itemCount} 文件${diffTag}`);
|
|
1606
|
+
}
|
|
1607
|
+
return lines.join('\n');
|
|
571
1608
|
}
|