@gluztm/dsh-guard 2.4.0 → 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/lib/inspector.mjs CHANGED
@@ -1,552 +1,1608 @@
1
- import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
2
- import { execFileSync, spawn } from 'node:child_process'
3
- import { homedir } from 'node:os'
4
- import { basename, join, resolve } from 'node:path'
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 RELEASE_URL = 'https://github.com/gluztm/DSHGuard/releases/latest'
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`;
7
11
 
8
- const REG_POINTER_KEY = 'HKCU\\Software\\DSHGuard'
9
- const REG_UNINSTALL_KEY = 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{9E1F7C34-5B2A-4D18-9C77-6A0E5D3B21F4}_is1'
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;
10
19
 
11
- export function resolveDshHome(overrideHome) {
12
- if (overrideHome && String(overrideHome).trim()) {
13
- return resolve(String(overrideHome).trim())
20
+ function safeReadText(filePath) {
21
+ try {
22
+ return fs.readFileSync(filePath, 'utf8');
23
+ } catch {
24
+ return null;
14
25
  }
15
- if (process.env.DSH_HOME && process.env.DSH_HOME.trim()) {
16
- return resolve(process.env.DSH_HOME.trim())
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;
17
35
  }
18
- return join(homedir(), '.dsh')
19
36
  }
20
37
 
21
- function queryRegInstallLocation(keyPath, valueName) {
22
- if (process.platform !== 'win32') return null
38
+ function sha256Text(text) {
39
+ return crypto.createHash('sha256').update(text, 'utf8').digest('hex');
40
+ }
41
+
42
+ function sha256File(filePath) {
23
43
  try {
24
- const out = execFileSync('reg.exe', ['query', keyPath, '/v', valueName], {
25
- encoding: 'utf8',
26
- timeout: 2000,
27
- windowsHide: true,
28
- stdio: ['ignore', 'pipe', 'ignore'],
29
- })
30
- for (const rawLine of out.split(/\r?\n/)) {
31
- const m = rawLine.trim().match(new RegExp(`^${valueName}\\s+REG_\\w+\\s+(.+)$`, 'i'))
32
- if (m && m[1]) return m[1].trim()
33
- }
44
+ const buf = fs.readFileSync(filePath);
45
+ return crypto.createHash('sha256').update(buf).digest('hex');
34
46
  } catch {
35
- return null
47
+ return null;
36
48
  }
37
- return null
38
49
  }
39
50
 
40
- /**
41
- * Locate local DSHGuard out-of-band installation (strictly read-only).
42
- */
43
- export function locateGuardInstallation(options = {}) {
44
- const candidates = []
45
- if (options.guardHome && String(options.guardHome).trim()) {
46
- candidates.push(resolve(String(options.guardHome).trim()))
47
- } else {
48
- if (process.env.DSHGUARD_HOME && process.env.DSHGUARD_HOME.trim()) {
49
- candidates.push(resolve(process.env.DSHGUARD_HOME.trim()))
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.
50
63
  }
51
- const ptrDir = queryRegInstallLocation(REG_POINTER_KEY, 'InstallLocation')
52
- || queryRegInstallLocation(REG_POINTER_KEY, 'InstallDir')
53
- if (ptrDir) candidates.push(resolve(ptrDir))
64
+ }
65
+ }
54
66
 
55
- const uninstDir = queryRegInstallLocation(REG_UNINSTALL_KEY, 'InstallLocation')
56
- if (uninstDir) candidates.push(resolve(uninstDir))
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
+ }
57
76
 
58
- const localAppData = process.env.LOCALAPPDATA
59
- if (localAppData) {
60
- candidates.push(join(localAppData, 'Programs', 'DSHGuard'))
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.
61
97
  }
62
98
  }
99
+ return null;
100
+ }
101
+
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
+ }
63
117
 
64
- let matchedHome = null
65
- let matchedExe = null
66
- let matchedSnapshots = null
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
+ }
67
131
 
68
- for (const dir of candidates) {
69
- if (!dir || !existsSync(dir)) continue
70
- const exeCandidate = join(dir, 'DSHGuard.exe')
71
- const snapCandidate = options.snapshotsDir ? resolve(String(options.snapshotsDir)) : join(dir, 'Snapshots')
72
- if (existsSync(exeCandidate) || existsSync(snapCandidate)) {
73
- matchedHome = dir
74
- if (existsSync(exeCandidate)) matchedExe = exeCandidate
75
- if (existsSync(snapCandidate)) matchedSnapshots = snapCandidate
76
- 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');
77
138
  }
139
+ pushCandidate('D:\\Applications\\DSHGuard', 'default-d-apps');
140
+ pushCandidate('C:\\Program Files\\DSHGuard', 'program-files');
78
141
  }
79
142
 
80
- if (!matchedSnapshots && options.snapshotsDir && existsSync(resolve(String(options.snapshotsDir)))) {
81
- matchedSnapshots = resolve(String(options.snapshotsDir))
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
+ }
82
166
  }
83
167
 
84
168
  return {
85
- installed: Boolean(matchedExe),
86
- guardHome: matchedHome,
87
- exePath: matchedExe,
88
- snapshotsDir: matchedSnapshots,
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,
89
177
  releaseUrl: RELEASE_URL,
178
+ installerUrl: INSTALLER_URL,
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, "'");
90
191
  }
192
+ return s;
91
193
  }
92
194
 
93
- function readJsonSafe(filePath) {
94
- try {
95
- const raw = readFileSync(filePath, 'utf8')
96
- return { ok: true, data: JSON.parse(raw), error: null }
97
- } catch (err) {
98
- return { ok: false, data: null, error: err && err.message ? err.message : String(err) }
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
+ }
99
222
  }
223
+ return line.replace(/\s+$/, '');
100
224
  }
101
225
 
102
- function extractBundleIds(bundlesField) {
103
- if (Array.isArray(bundlesField)) {
104
- return bundlesField.map((item) => String(item || '').trim()).filter(Boolean)
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
+ }
105
256
  }
106
- if (bundlesField && typeof bundlesField === 'object') {
107
- return Object.keys(bundlesField).map((k) => k.trim()).filter(Boolean)
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
+ }
108
274
  }
109
- return []
275
+ return unquoteYamlScalar(s);
110
276
  }
111
277
 
112
- function scanCordisPatch(patchPath) {
113
- if (!existsSync(patchPath)) {
114
- return {
115
- exists: false,
116
- readable: false,
117
- syntaxOk: true,
118
- hasTabIndent: false,
119
- disabledCount: 0,
120
- apiKeyEnvKeys: [],
121
- mcpEntriesCount: 0,
122
- error: null,
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);
123
301
  }
302
+ return parseMapping(first.indent);
124
303
  }
125
- try {
126
- const raw = readFileSync(patchPath, 'utf8')
127
- const lines = raw.split(/\r?\n/)
128
- let hasTabIndent = false
129
- let disabledCount = 0
130
- let mcpEntriesCount = 0
131
- const envSet = new Set()
132
- let hasStructuredToken = false
133
-
134
- for (const line of lines) {
135
- if (/^\t+/.test(line)) hasTabIndent = true
136
- const trimmed = line.trim()
137
- if (!trimmed || trimmed.startsWith('#')) continue
138
- if (trimmed.startsWith('- ') || /^[A-Za-z0-9_.-]+\s*:/.test(trimmed)) {
139
- hasStructuredToken = true
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;
140
324
  }
141
- if (/^enabled\s*:\s*false\b/i.test(trimmed)) {
142
- disabledCount += 1
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));
143
385
  }
144
- const envMatch = trimmed.match(/^apiKeyEnv\s*:\s*['"]?([A-Za-z0-9_]+)['"]?/i)
145
- if (envMatch && envMatch[1]) {
146
- envSet.add(envMatch[1])
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;
147
401
  }
148
- if (/\bmcpServers\b|id\s*:\s*['"]?mcp\b/i.test(trimmed)) {
149
- mcpEntriesCount += 1
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);
150
423
  }
151
424
  }
425
+ return obj;
426
+ }
152
427
 
153
- const nonEmpty = lines.some((l) => l.trim() && !l.trim().startsWith('#'))
154
- const syntaxOk = !hasTabIndent && (!nonEmpty || hasStructuredToken)
428
+ const parsed = parseBlock(0);
429
+ return parsed ?? [];
430
+ }
155
431
 
156
- return {
157
- exists: true,
158
- readable: true,
159
- syntaxOk,
160
- hasTabIndent,
161
- disabledCount,
162
- apiKeyEnvKeys: Array.from(envSet).sort(),
163
- mcpEntriesCount,
164
- error: syntaxOk ? null : (hasTabIndent ? 'Tab indentation detected in YAML' : 'Unrecognized YAML structure'),
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;
165
457
  }
166
- } catch (err) {
167
- return {
168
- exists: true,
169
- readable: false,
170
- syntaxOk: false,
171
- hasTabIndent: false,
172
- disabledCount: 0,
173
- apiKeyEnvKeys: [],
174
- mcpEntriesCount: 0,
175
- error: err && err.message ? err.message : String(err),
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);
545
+ }
546
+ }
547
+ }
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;
176
653
  }
177
654
  }
655
+
656
+ if (inRefs) {
657
+ flushCurrent();
658
+ refsEnd = lines.length;
659
+ }
660
+
661
+ return { lines, refsStart, refsEnd, entries };
178
662
  }
179
663
 
180
664
  /**
181
- * Read-only health inspection of a single DSH profile ('web' or 'desktop').
665
+ * Inspect .credentials.yaml ONLY for key existence/readiness metadata.
666
+ * Never reads or returns any secret literal, preview, or prefix.
182
667
  */
183
- export function inspectProfile(profileDir, targetName) {
184
- const exists = existsSync(profileDir)
185
- const pkgPath = join(profileDir, 'package.json')
186
- const patchPath = join(profileDir, 'cordis.patch.yml')
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
+ }
187
679
 
188
- if (!exists) {
680
+ const raw = safeReadText(credPath);
681
+ if (raw === null) {
189
682
  return {
190
- target: targetName,
191
- profileDir,
192
- exists: false,
193
- packageJsonOk: false,
194
- dependenciesCount: 0,
195
- bundlesCount: 0,
196
- missingInDeps: [],
197
- unregisteredDeps: [],
198
- patch: scanCordisPatch(patchPath),
199
- issues: [],
200
- }
683
+ present: true,
684
+ unreadable: true,
685
+ path: credPath,
686
+ count: 0,
687
+ protectedCount: 0,
688
+ keys: [],
689
+ };
201
690
  }
202
691
 
203
- const pkgRes = existsSync(pkgPath)
204
- ? readJsonSafe(pkgPath)
205
- : { ok: false, data: null, error: 'package.json not found' }
692
+ const doc = parseCredentialRefsDocument(raw);
693
+ const seen = new Set();
694
+ const keys = [];
206
695
 
207
- const depsObj = pkgRes.ok && pkgRes.data && typeof pkgRes.data.dependencies === 'object' && pkgRes.data.dependencies
208
- ? pkgRes.data.dependencies
209
- : {}
210
- const depNames = Object.keys(depsObj)
211
- const depSet = new Set(depNames)
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
+ }
707
+
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
+ }
212
725
 
213
- const bundles = pkgRes.ok && pkgRes.data && pkgRes.data.dsh
214
- ? extractBundleIds(pkgRes.data.dsh.bundles ?? (pkgRes.data.dsh.profile && pkgRes.data.dsh.profile.bundles))
215
- : []
216
- const bundleSet = new Set(bundles)
726
+ const nonEmptyKeysCount = keys.filter((k) => k.present).length;
217
727
 
218
- const missingInDeps = bundles.filter((b) => !depSet.has(b))
219
- const unregisteredDeps = depNames.filter((d) => {
220
- if (bundleSet.has(d)) return false
221
- return d.startsWith('dsh-') || d.includes('/dsh-')
222
- })
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
+ }
223
738
 
224
- const patch = scanCordisPatch(patchPath)
225
- const issues = []
226
- if (!pkgRes.ok) {
227
- issues.push(`${targetName} package.json error: ${pkgRes.error}`)
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: '环境变量名格式无效(仅支持字母、数字、下划线、点或连字符)' };
228
747
  }
229
- if (missingInDeps.length > 0) {
230
- issues.push(`${targetName} manifest drift: ${missingInDeps.length} bundle(s) missing in dependencies (${missingInDeps.join(', ')})`)
748
+ if (/^(?:version|records|refs)$/i.test(key) || /_ACCOUNT(?:_|$)/i.test(key)) {
749
+ return { ok: false, error: `保护键 ${key} 不可通过插件覆盖写入` };
231
750
  }
232
- if (unregisteredDeps.length > 0) {
233
- issues.push(`${targetName} manifest drift: ${unregisteredDeps.length} plugin dep(s) not listed in bundles (${unregisteredDeps.join(', ')})`)
751
+ const secret = typeof secretValue === 'string' ? secretValue.trim() : '';
752
+ if (!secret || /[\r\n]/.test(secret) || secret.length > 4096) {
753
+ return { ok: false, error: '密钥值不能为空且必须为单行(<= 4096 字符)' };
234
754
  }
235
- if (patch.exists && !patch.syntaxOk) {
236
- issues.push(`${targetName} cordis.patch.yml warning: ${patch.error}`)
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 };
237
764
  }
238
765
 
239
- return {
240
- target: targetName,
241
- profileDir,
242
- exists: true,
243
- packageJsonOk: pkgRes.ok,
244
- dependenciesCount: depNames.length,
245
- bundlesCount: bundles.length,
246
- missingInDeps,
247
- unregisteredDeps,
248
- patch,
249
- issues,
766
+ const raw = safeReadText(credPath);
767
+ if (raw === null) {
768
+ return { ok: false, error: '无法读取 .credentials.yaml' };
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);
250
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 };
251
796
  }
252
797
 
253
- /**
254
- * Strictly masked credential readiness check: NEVER reads, slices, or returns secret values.
255
- */
256
- export function inspectCredentialKeysMasked(dshHome, referencedEnvKeys = []) {
257
- const credPath = join(dshHome, '.credentials.yaml')
258
- const nonEmptyKeys = new Set()
259
- let totalKeysCount = 0
260
- let fileExists = false
261
-
262
- if (existsSync(credPath)) {
263
- fileExists = true
264
- try {
265
- const raw = readFileSync(credPath, 'utf8')
266
- for (const rawLine of raw.split(/\r?\n/)) {
267
- const line = rawLine.trimEnd()
268
- if (!line || line.trim().startsWith('#') || /^\s/.test(line)) continue
269
- const m = line.match(/^([A-Za-z0-9_.-]+)\s*:\s*(.*)$/)
270
- if (!m) continue
271
- totalKeysCount += 1
272
- const keyName = m[1].trim()
273
- const rawVal = m[2].trim()
274
- const stripped = rawVal.replace(/^(['"])(.*)\1$/, '$2').trim()
275
- const isEmpty = !stripped || stripped === '~' || stripped.toLowerCase() === 'null'
276
- if (!isEmpty) {
277
- nonEmptyKeys.add(keyName)
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);
278
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);
838
+ }
839
+ existing.keyConfigured = existing.apiKeyEnv
840
+ ? readyKeys.has(existing.apiKeyEnv) || Boolean(process.env[existing.apiKeyEnv])
841
+ : false;
842
+ merged.set(pid, existing);
279
843
  }
280
- } catch {
281
- // Unreadable file stays nonEmptyKeys empty; never leak raw error internals with secrets.
844
+ break;
282
845
  }
283
846
  }
284
847
 
285
- const uniqueRefs = Array.from(new Set(referencedEnvKeys.filter(Boolean))).sort()
286
- const referencedKeys = uniqueRefs.map((key) => ({
287
- key,
288
- ready: nonEmptyKeys.has(key),
289
- }))
290
- const missingReferencedKeys = referencedKeys.filter((item) => !item.ready).map((item) => item.key)
848
+ return Array.from(merged.values());
849
+ }
291
850
 
292
- return {
293
- fileExists,
294
- totalKeysCount,
295
- nonEmptyKeysCount: nonEmptyKeys.size,
296
- referencedKeys,
297
- missingReferencedKeys,
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);
298
859
  }
299
- }
860
+ candidateFiles.push(path.join(pkgDir, 'cordis.patch.yml'));
300
861
 
301
- /**
302
- * Full read-only health report across Web & Desktop profiles, masked credentials, and DSHGuard.
303
- */
304
- export function inspectHealth(options = {}) {
305
- const dshHome = resolveDshHome(options.dshHome)
306
- const target = options.target && ['all', 'web', 'desktop'].includes(options.target)
307
- ? options.target
308
- : '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
+ };
309
868
 
310
- const profiles = []
311
- if (target === 'all' || target === 'web') {
312
- profiles.push(inspectProfile(join(dshHome, 'profiles', 'web'), 'web'))
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;
313
877
  }
314
- if (target === 'all' || target === 'desktop') {
315
- profiles.push(inspectProfile(join(dshHome, 'profiles', 'desktop'), 'desktop'))
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
+ }
316
887
  }
317
888
 
318
- const referencedEnvKeys = profiles.flatMap((p) => (p.patch ? p.patch.apiKeyEnvKeys : []))
319
- const credentials = inspectCredentialKeysMasked(dshHome, referencedEnvKeys)
320
- const guard = locateGuardInstallation(options)
889
+ return { ids, description: typeof pkgJson?.description === 'string' ? pkgJson.description : '', version: pkgJson?.version || '' };
890
+ }
891
+
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));
321
899
 
322
- const issues = profiles.flatMap((p) => p.issues)
323
- if (credentials.missingReferencedKeys.length > 0) {
324
- issues.push(`Missing credential key(s) in .credentials.yaml: ${credentials.missingReferencedKeys.join(', ')}`)
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
+ }
325
906
  }
326
907
 
327
- const healthy = issues.length === 0
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
+ }
328
925
 
329
- return {
330
- platform: process.platform,
331
- dshHome,
332
- target,
333
- healthy,
334
- issuesCount: issues.length,
335
- issues,
336
- profiles,
337
- credentials,
338
- guard,
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
+ });
339
939
  }
340
- }
341
940
 
342
- function classifySnapshotEntry(dirPath, name) {
343
- let target = 'web'
344
- let reason = ''
345
- let itemCount = 0
346
- let createdAt = ''
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
+ });
347
946
 
348
- const manifestPath = join(dirPath, 'manifest.json')
349
- if (existsSync(manifestPath)) {
350
- const res = readJsonSafe(manifestPath)
351
- if (res.ok && res.data) {
352
- if (typeof res.data.target === 'string' && res.data.target.toLowerCase().includes('desktop')) {
353
- target = 'desktop'
354
- } else if (typeof res.data.scope === 'string' && res.data.scope.toLowerCase().includes('desktop')) {
355
- target = 'desktop'
356
- }
357
- if (typeof res.data.reason === 'string') reason = res.data.reason
358
- if (typeof res.data.createdAt === 'string') createdAt = res.data.createdAt
359
- if (Array.isArray(res.data.files)) itemCount = res.data.files.length
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
+ });
360
963
  }
361
964
  }
362
965
 
363
- if (target === 'web' && /desktop/i.test(name)) {
364
- target = 'desktop'
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: [] };
365
981
  }
366
982
 
367
- try {
368
- const entries = readdirSync(dirPath)
369
- if (itemCount === 0) {
370
- itemCount = entries.filter((e) => e !== 'manifest.json').length
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
+ }
371
1007
  }
372
- if (!createdAt) {
373
- createdAt = new Date(statSync(dirPath).mtimeMs).toISOString()
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
+ });
374
1033
  }
375
- } catch {
376
- // Ignore stat errors on individual directories
377
1034
  }
378
1035
 
379
1036
  return {
380
- id: name,
381
- target,
382
- reason,
383
- itemCount,
384
- createdAt,
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') });
385
1058
  }
1059
+ list.push({ relPath: 'settings.yaml', snapFile: 'home-settings.yaml', absPath: path.join(dshHome, 'settings.yaml') });
1060
+ return list;
386
1061
  }
387
1062
 
388
- /**
389
- * List saved DSHGuard snapshots (strictly read-only).
390
- */
391
- export function inspectSnapshots(options = {}) {
392
- const guard = locateGuardInstallation(options)
393
- const limit = Math.max(1, Math.min(50, Number(options.limit) || 20))
394
- const targetFilter = options.target && ['all', 'web', 'desktop'].includes(options.target)
395
- ? options.target
396
- : 'all'
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 });
397
1081
 
398
- if (!guard.snapshotsDir || !existsSync(guard.snapshotsDir)) {
399
- return {
400
- snapshotsDir: guard.snapshotsDir,
401
- guardInstalled: guard.installed,
402
- total: 0,
403
- snapshots: [],
404
- releaseUrl: RELEASE_URL,
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
+ }
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
+ }
405
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');
406
1193
  }
407
1194
 
408
- let items = []
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 = [];
409
1215
  try {
410
- const entries = readdirSync(guard.snapshotsDir, { withFileTypes: true })
411
- for (const ent of entries) {
412
- if (!ent.isDirectory()) continue
413
- const full = join(guard.snapshotsDir, ent.name)
414
- const parsed = classifySnapshotEntry(full, ent.name)
415
- if (targetFilter === 'all' || parsed.target === targetFilter) {
416
- items.push(parsed)
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;
417
1231
  }
418
1232
  }
419
- } catch {
420
- items = []
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
+ });
421
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';
422
1329
 
423
- items.sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)))
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
+ }
424
1351
 
425
1352
  return {
426
- snapshotsDir: guard.snapshotsDir,
427
- guardInstalled: guard.installed,
428
- total: items.length,
429
- 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),
430
1355
  releaseUrl: RELEASE_URL,
431
- }
1356
+ pluginSnapshotsDir: pluginRoot,
1357
+ snapshotsDir: guard.snapshotsDir || pluginRoot,
1358
+ total: snapshots.length,
1359
+ snapshots: snapshots.slice(0, limit),
1360
+ };
432
1361
  }
433
1362
 
434
- /**
435
- * Locate or optionally launch the local Windows DSHGuard desktop supervisor.
436
- */
437
- export function openGuard(options = {}) {
438
- const guard = locateGuardInstallation(options)
439
- if (!guard.installed || !guard.exePath) {
1363
+ export function restoreSnapshotConfig(dshHome, guard, snapshotId) {
1364
+ const id = String(snapshotId || '').trim();
1365
+ if (!id || /[\\/]|\.\./.test(id)) {
1366
+ return { ok: false, error: '无效的快照 ID' };
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) {
440
1377
  return {
441
- installed: false,
442
- launched: false,
443
- exePath: null,
444
- guardHome: guard.guardHome,
445
- releaseUrl: RELEASE_URL,
446
- message: '未检测到本地安装的 DSHGuard 守护壳,可前往 GitHub Releases 下载官方 Windows 安装包。',
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;
447
1414
  }
1415
+
1416
+ const content = fs.readFileSync(srcFile, 'utf8');
1417
+ atomicWriteText(destFile, content);
1418
+ restoredFiles.push(f.relPath);
448
1419
  }
449
1420
 
450
- if (options.launch === true) {
451
- if (process.platform !== 'win32') {
452
- return {
453
- installed: true,
454
- launched: false,
455
- exePath: guard.exePath,
456
- guardHome: guard.guardHome,
457
- releaseUrl: RELEASE_URL,
458
- message: '当前非 Windows 环境,无法直接拉起桌面端 DSHGuard.exe。',
459
- }
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 存在配置漂移');
460
1459
  }
461
- try {
462
- const child = spawn(guard.exePath, [], {
463
- detached: true,
464
- stdio: 'ignore',
465
- windowsHide: false,
466
- })
467
- if (typeof child.on === 'function') {
468
- child.on('error', () => {})
469
- }
470
- child.unref()
471
- return {
472
- installed: true,
473
- launched: true,
474
- exePath: guard.exePath,
475
- guardHome: guard.guardHome,
476
- releaseUrl: RELEASE_URL,
477
- message: `已在桌面拉起 DSHGuard 守护壳(${basename(guard.exePath)})。`,
478
- }
479
- } catch (err) {
480
- return {
481
- installed: true,
482
- launched: false,
483
- exePath: guard.exePath,
484
- guardHome: guard.guardHome,
485
- releaseUrl: RELEASE_URL,
486
- message: `拉起 DSHGuard 守护壳失败:${err && err.message ? err.message : String(err)}`,
487
- }
1460
+ if (web.totalDependencies !== desktop.totalDependencies) {
1461
+ issues.push(`依赖数量差异: web=${web.totalDependencies}, desktop=${desktop.totalDependencies}`);
488
1462
  }
489
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
+ }
490
1476
 
491
1477
  return {
492
- installed: true,
493
- launched: false,
494
- exePath: guard.exePath,
495
- guardHome: guard.guardHome,
496
- releaseUrl: RELEASE_URL,
497
- message: `已定位本机 DSHGuard 守护壳:${guard.exePath}`,
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
+ };
1497
+ }
1498
+
1499
+ export function openGuard(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
+ }
1513
+ if (!guard.installed || !guard.exePath) {
1514
+ return {
1515
+ ok: false,
1516
+ installed: false,
1517
+ launched: false,
1518
+ reason: 'not-installed',
1519
+ message: '未在本机检测到 DSHGuard.exe(伴生插件本身已内置插件开关、凭据写入与配置快照);如需跨进程托管或硬件加密隔离,可安装 Windows 桌面端。',
1520
+ releaseUrl: RELEASE_URL,
1521
+ installerUrl: INSTALLER_URL,
1522
+ installUrl: INSTALLER_URL,
1523
+ };
1524
+ }
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
+ };
1537
+ }
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
+ };
498
1568
  }
499
1569
  }
500
1570
 
501
1571
  export function formatHealthText(report) {
502
- const lines = []
503
- lines.push(`DSH 守护壳伴生体检(状态:${report.healthy ? '正常' : `发现 ${report.issuesCount} 项异常`})`)
504
- for (const p of report.profiles) {
505
- if (!p.exists) {
506
- lines.push(`- [${p.target}] 未检测到配置目录`)
507
- continue
508
- }
509
- const patchNote = p.patch.exists
510
- ? (p.patch.syntaxOk ? `patch 正常(禁用 ${p.patch.disabledCount} 项)` : `patch 异常(${p.patch.error})`)
511
- : '无 cordis.patch.yml'
512
- lines.push(
513
- `- [${p.target}] bundles=${p.bundlesCount} / deps=${p.dependenciesCount} | ${patchNote}`
514
- + (p.missingInDeps.length ? ` | 缺依赖: ${p.missingInDeps.join(', ')}` : '')
515
- + (p.unregisteredDeps.length ? ` | 未登记: ${p.unregisteredDeps.join(', ')}` : '')
516
- )
517
- }
518
- const cred = report.credentials
519
- const refTotal = cred.referencedKeys.length
520
- const refReady = cred.referencedKeys.filter((r) => r.ready).length
521
- lines.push(
522
- `- [凭据脱敏对账] .credentials.yaml ${cred.fileExists ? `已存在(非空键 ${cred.nonEmptyKeysCount}/${cred.totalKeysCount})` : '未创建'}`
523
- + (refTotal > 0 ? ` | patch 引用键就绪 ${refReady}/${refTotal}` : '')
524
- + (cred.missingReferencedKeys.length ? ` | 缺失: ${cred.missingReferencedKeys.join(', ')}` : '')
525
- )
526
- lines.push(
527
- report.guard.installed
528
- ? `- [本机 DSHGuard] 已安装(${report.guard.exePath})`
529
- : `- [本机 DSHGuard] 未安装,官方下载:${report.guard.releaseUrl}`
530
- )
531
- if (report.issues.length > 0) {
532
- lines.push('诊断建议:')
533
- for (const issue of report.issues) {
534
- lines.push(` ! ${issue}`)
535
- }
536
- }
537
- return lines.join('\n')
538
- }
539
-
540
- export function formatSnapshotsText(report) {
541
- if (!report.snapshotsDir || report.total === 0) {
542
- return report.guardInstalled
543
- ? '本机 DSHGuard 尚无快照存档(Snapshots 目录为空或不存在)。'
544
- : `未定位到本机 DSHGuard 快照目录;可在 Windows 安装 DSHGuard 后自动存档:${report.releaseUrl}`
545
- }
546
- const lines = [`已找到 ${report.total} 份守护壳快照(展示最近 ${report.snapshots.length} 份):`]
547
- for (const snap of report.snapshots) {
548
- const meta = [snap.target, `${snap.itemCount} 项`, snap.createdAt].filter(Boolean).join(' · ')
549
- lines.push(`- ${snap.id}(${meta})${snap.reason ? ` — ${snap.reason}` : ''}`)
550
- }
551
- 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');
552
1608
  }