dsh-modpack-kit 0.1.3 → 0.1.5

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/install.mjs CHANGED
@@ -8,7 +8,7 @@
8
8
  import fs from 'node:fs'
9
9
  import path from 'node:path'
10
10
  import { readZip, readZipText, safeEntryName } from './zip.mjs'
11
- import { scanEntries, renderScanReport } from './scan.mjs'
11
+ import { scanEntries, renderScanReport, groupFindings } from './scan.mjs'
12
12
  import { MANIFEST_NAME, normalizeManifest, sha256 } from './manifest.mjs'
13
13
  import { checkCompatibility } from './compat.mjs'
14
14
  import { captureConfigs, collectFiles } from './pack.mjs'
@@ -19,6 +19,7 @@ import {
19
19
  appendLog,
20
20
  pathsFor,
21
21
  slugify,
22
+ dshHome,
22
23
  } from './store.mjs'
23
24
  import {
24
25
  ensureBundles,
@@ -114,7 +115,10 @@ export function inspectPackBuffer(buffer, options = {}) {
114
115
  notes.push('打包方已确认 ' + scan.counts.high + ' 个高风险项(市场收录插件),明细见扫描报告')
115
116
  }
116
117
 
117
- return { manifest, entries, integrity, scan, report, blockingReasons, notes }
118
+ // 界面要按来源(插件 / 配置 / 整合包本体)分栏展示,分组结果一并给出去
119
+ const scanGroups = groupFindings(scan.findings, manifest.plugins)
120
+
121
+ return { manifest, entries, integrity, scan, scanGroups, report, blockingReasons, notes }
118
122
  }
119
123
 
120
124
  /** 从链接读取整合包(只允许 https 与白名单域名)。 */
@@ -174,7 +178,10 @@ function packDirOf(config, manifest) {
174
178
  export async function installPack(input) {
175
179
  const { manifest, entries, config, options = {}, context = {} } = input
176
180
  const profileDir = context.profileDir || pathsFor(config).profile
177
- const profile = config.profile || 'desktop'
181
+ // profile 名必须跟着 profileDir 走:DSH 命令行只认 --profile <名字>,
182
+ // 若拿 config.profile(桌面环境里恒为 desktop)去装,装进的是真 profile 而不是 targetDir。
183
+ const targetName = path.basename(path.resolve(profileDir))
184
+ const profile = targetName && targetName !== 'profiles' ? targetName : config.profile || 'desktop'
178
185
  const installed = listInstalled(profileDir)
179
186
  const compat = checkCompatibility(manifest.plugins, {
180
187
  installed,
@@ -194,6 +201,7 @@ export async function installPack(input) {
194
201
  reason: '兼容性检测有 ' + compat.counts.error + ' 个阻断问题',
195
202
  compat,
196
203
  actions,
204
+ deferred: [],
197
205
  lines,
198
206
  needsRestart: false,
199
207
  }
@@ -204,74 +212,164 @@ export async function installPack(input) {
204
212
  const packRoot = packDirOf(config, manifest)
205
213
  // CLI 自己会把 bundle 登记进 profile;「装好先不启用」靠装完撤回列表实现,所以先记一份原始清单。
206
214
  const bundlesBefore = readBundles(readProfilePackage(profileDir))
215
+ // 打包方已确认过风险的包,安装时不再因为 high 拦人(明细照样进报告)
216
+ const acknowledged = Boolean(manifest.security && (manifest.security.acknowledged === true || manifest.security.trustedOnly === true))
217
+
218
+ // 进度:和打包共用同一个进度窗(kind=install)
219
+ const progress = typeof options.onProgress === 'function' ? options.onProgress : () => {}
220
+ progress({ pct: 8, note: '检查本机已装的插件' })
221
+ const only = Array.isArray(options.only) && options.only.length > 0 ? new Set(options.only.map(String)) : null
222
+ // 默认「先跳过已装的,装完再问要不要换」;replaceExisting 时反过来,直接覆盖
223
+ const deferExisting = options.replaceExisting === true ? false : options.deferExisting !== false
224
+ const deferred = []
225
+ const total = manifest.plugins.length
226
+ let restartFromManager = false
207
227
 
208
228
  for (const plugin of manifest.plugins) {
229
+ const index = manifest.plugins.indexOf(plugin)
230
+ progress({ pct: 12 + Math.round(((index + 1) / total) * 68), note: '安装 ' + plugin.name + (plugin.version ? ' ' + plugin.version : '') })
231
+ if (only && !only.has(plugin.name)) {
232
+ actions.push({ plugin: plugin.name, action: 'skipped', ok: true, message: '这次不动它(你只选了替换其中几个)' })
233
+ continue
234
+ }
209
235
  const existing = installed.find((p) => p.name === plugin.name)
236
+ if (existing && deferExisting) {
237
+ // 同名或同插件不同版本都算已装:先跳过,其余照装,最后让你决定换不换
238
+ deferred.push({ name: plugin.name, localVersion: existing.version || '', packVersion: plugin.version || '', sameVersion: String(existing.version || '') === String(plugin.version || '') })
239
+ actions.push({ plugin: plugin.name, action: 'deferred', ok: true, message: '本机已装 ' + (existing.version || '(版本未知)') + ',先跳过;装完再问你换不换' })
240
+ continue
241
+ }
210
242
  const keepLocal = options.keepLocal !== false && config.keepLocal !== false && manifest.options.keepLocalOnInstall !== false
211
- if (existing && keepLocal) {
243
+ if (existing && !deferExisting && keepLocal && options.replaceExisting !== true) {
212
244
  actions.push({ plugin: plugin.name, action: 'kept', ok: true, message: '本地已装 ' + existing.version + ',按“保留本地修改”跳过覆盖' })
213
245
  continue
214
246
  }
215
247
 
216
- let dir = null
217
- if (manifest.format === 'full' && pluginPayload(entries, plugin.dirName || plugin.name).length > 0) {
248
+ // 联网且插件市场可用时,优先按市场版本装(用户要求:装整合包时优先同步市场版本)
249
+ // 取不到 / 离线 / 关掉开关(options.preferMarket === false)时,按包内带来的那份装
250
+ let marketHit = null
251
+ if (options.preferMarket !== false && typeof context.resolveMarket === 'function') {
218
252
  try {
219
- dir = materializePayload(entries, manifest, plugin, config)
253
+ marketHit = await context.resolveMarket(plugin)
220
254
  } catch (error) {
221
- actions.push({ plugin: plugin.name, action: 'install', ok: false, message: String(error?.message || error) })
255
+ lines.push('查不到市场版本(' + plugin.name + '):' + String(error?.message || error) + ',按包内的来')
256
+ }
257
+ }
258
+
259
+ let dir = null
260
+ if (!marketHit) {
261
+ if (manifest.format === 'full' && pluginPayload(entries, plugin.dirName || plugin.name).length > 0) {
262
+ try {
263
+ dir = materializePayload(entries, manifest, plugin, config)
264
+ } catch (error) {
265
+ actions.push({ plugin: plugin.name, action: 'install', ok: false, message: String(error?.message || error) })
266
+ continue
267
+ }
268
+ } else if (typeof context.resolveSource === 'function') {
269
+ try {
270
+ dir = await context.resolveSource(plugin, packRoot)
271
+ } catch (error) {
272
+ actions.push({ plugin: plugin.name, action: 'install', ok: false, message: '取包失败:' + String(error?.message || error) })
273
+ continue
274
+ }
275
+ } else {
276
+ actions.push({ plugin: plugin.name, action: 'install', ok: false, message: '轻量包需要在联网环境下解析来源' })
222
277
  continue
223
278
  }
224
- } else if (typeof context.resolveSource === 'function') {
225
- try {
226
- dir = await context.resolveSource(plugin, packRoot)
227
- } catch (error) {
228
- actions.push({ plugin: plugin.name, action: 'install', ok: false, message: '取包失败:' + String(error?.message || error) })
279
+
280
+ if (manifest.format !== 'full') {
281
+ // 轻量包本体不夹带源码,真正的代码是刚下载回来的:装之前必须补扫一遍,否则「安装前检测」是空转
282
+ try {
283
+ const brought = collectFiles(dir, {
284
+ prefix: '',
285
+ maxFileBytes: config.maxFileBytes ?? 16 * 1024 * 1024,
286
+ maxTotalBytes: 64 * 1024 * 1024,
287
+ })
288
+ const deep = scanEntries(brought.files, { extraRules: Array.isArray(config.extraScanRules) ? config.extraScanRules : [] })
289
+ if (deep.counts.high > 0 && !options.force && !acknowledged) {
290
+ actions.push({ plugin: plugin.name, action: 'install', ok: false, message: '从市场取回的代码里有 ' + deep.counts.high + ' 个高风险项,已拦下' })
291
+ continue
292
+ }
293
+ lines.push('轻量包:已补扫从市场取回的 ' + deep.scannedFiles + ' 个文件(高 ' + deep.counts.high + ')')
294
+ } catch (error) {
295
+ actions.push({ plugin: plugin.name, action: 'install', ok: false, message: '补充扫描失败:' + String(error?.message || error) })
296
+ continue
297
+ }
298
+ }
299
+
300
+ if (options.dryRun) {
301
+ actions.push({ plugin: plugin.name, action: 'install', ok: true, message: '演练:将添加 ' + dir })
229
302
  continue
230
303
  }
231
- } else {
232
- actions.push({ plugin: plugin.name, action: 'install', ok: false, message: '轻量包需要在联网环境下解析来源' })
304
+ } else if (options.dryRun) {
305
+ actions.push({ plugin: plugin.name, action: 'install', ok: true, message: '演练:将按市场版本安装 ' + marketHit.spec })
233
306
  continue
234
307
  }
235
308
 
236
- if (manifest.format !== 'full') {
237
- // 轻量包本体不夹带源码,真正的代码是刚下载回来的:装之前必须补扫一遍,否则「安装前检测」是空转
309
+ const targetSpec = marketHit ? marketHit.spec : 'file:' + dir
310
+ // 优先交给 DSH 自带的插件管理器:pnpm、激活与「要不要重启」都由宿主判断,
311
+ // 我们不再拼命令行,也就绕开了引号、编码、硬链接这些坑。拿不到服务时退回命令行。
312
+ const installBundle = typeof context.installBundle === 'function' ? context.installBundle : null
313
+ let code = 0
314
+ let output = ''
315
+ let application = ''
316
+ let usedManager = false
317
+ if (installBundle) {
318
+ let change = null
238
319
  try {
239
- const brought = collectFiles(dir, {
240
- prefix: '',
241
- maxFileBytes: config.maxFileBytes ?? 16 * 1024 * 1024,
242
- maxTotalBytes: 64 * 1024 * 1024,
320
+ change = await installBundle(targetSpec, {
321
+ enabled: options.enableBundles !== false,
322
+ ...(marketHit && marketHit.version ? { expected: { name: plugin.name, version: marketHit.version } } : {}),
243
323
  })
244
- const deep = scanEntries(brought.files, { extraRules: Array.isArray(config.extraScanRules) ? config.extraScanRules : [] })
245
- if (deep.counts.high > 0 && !options.force && !acknowledged) {
246
- actions.push({ plugin: plugin.name, action: 'install', ok: false, message: '从市场取回的代码里有 ' + deep.counts.high + ' 个高风险项,已拦下' })
247
- continue
248
- }
249
- lines.push('轻量包:已补扫从市场取回的 ' + deep.scannedFiles + ' 个文件(高 ' + deep.counts.high + ')')
250
324
  } catch (error) {
251
- actions.push({ plugin: plugin.name, action: 'install', ok: false, message: '补充扫描失败:' + String(error?.message || error) })
252
- continue
325
+ // 管理器出错时不要让整次安装悬着:记一行,退回命令行再试一次。
326
+ lines.push('插件管理器没能装成(' + String((error && error.message) || error) + '),改用命令行重试')
327
+ change = null
328
+ }
329
+ if (change && change.application === 'failed') {
330
+ const reason = change.error && change.error.code ? '(' + change.error.code + ')' : ''
331
+ lines.push('插件管理器安装失败' + reason + ',改用命令行重试')
332
+ change = null
333
+ }
334
+ if (change) {
335
+ usedManager = true
336
+ application = change.application ? String(change.application) : ''
337
+ code = 0
338
+ if (application === 'restart-required') restartFromManager = true
339
+ const bits = []
340
+ if (change.stage) bits.push('stage=' + change.stage)
341
+ if (application) bits.push('application=' + application)
342
+ if (change.error && change.error.code) bits.push('error=' + change.error.code)
343
+ if (change.packageResult && change.packageResult.output) bits.push(String(change.packageResult.output))
344
+ output = bits.join(' ')
253
345
  }
254
346
  }
255
-
256
- if (options.dryRun) {
257
- actions.push({ plugin: plugin.name, action: 'install', ok: true, message: '演练:将添加 ' + dir })
258
- continue
347
+ if (!usedManager) {
348
+ const runCli = typeof context.runCli === 'function' ? context.runCli : runDshPlugin
349
+ const result = await runCli(profile, ['plugin', '--profile', profile, 'add', targetSpec], {
350
+ cwd: profileDir,
351
+ onLine: (line) => { lines.push(line); onLine(line) },
352
+ })
353
+ code = result && typeof result.code === 'number' ? result.code : 1
354
+ output = String((result && result.output) || '')
259
355
  }
260
-
261
- const runCli = typeof context.runCli === 'function' ? context.runCli : runDshPlugin
262
- const result = await runCli(profile, ['plugin', '--profile', profile, 'add', 'file:' + dir], {
263
- cwd: profileDir,
264
- onLine: (line) => { lines.push(line); onLine(line) },
265
- })
266
- appendLog('install ' + plugin.name + ' exit=' + result.code)
267
- if (result.code !== 0) {
268
- actions.push({ plugin: plugin.name, action: 'install', ok: false, message: 'dsh plugin add 失败(退出码 ' + result.code + '),详见日志' })
356
+ if (output) lines.push(output)
357
+ appendLog('install ' + plugin.name + ' exit=' + code + ' via=' + (usedManager ? 'manager' : 'cli') + (marketHit ? '/market' : '/pack') + (application ? ' ' + application : ''))
358
+ if (code !== 0) {
359
+ actions.push({ plugin: plugin.name, action: 'install', ok: false, message: 'dsh plugin add 失败(退出码 ' + code + '),详见日志' })
269
360
  continue
270
361
  }
271
362
  if (plugin.isBundle && plugin.hasPatch) touchedBundles.push(plugin.name)
272
- actions.push({ plugin: plugin.name, action: 'install', ok: true, message: '已装 ' + (plugin.version || '') })
363
+ actions.push({
364
+ plugin: plugin.name,
365
+ action: 'install',
366
+ ok: true,
367
+ source: marketHit ? 'market' : 'pack',
368
+ message: marketHit ? ('已按市场版本安装 ' + marketHit.spec) : ('已装 ' + (plugin.version || '')),
369
+ })
273
370
  }
274
371
 
372
+ progress({ pct: 84, note: '登记启用清单' })
275
373
  if (!options.dryRun) {
276
374
  const before = bundlesBefore
277
375
  const after = readBundles(readProfilePackage(profileDir))
@@ -289,6 +387,7 @@ export async function installPack(input) {
289
387
  }
290
388
  }
291
389
 
390
+ progress({ pct: 92, note: '回填包内配置' })
292
391
  // 配置回填:只改目标条目,其它字节不动
293
392
  if (options.applyConfig !== false && manifest.options.includeConfig) {
294
393
  const patch = readPatch(profileDir)
@@ -315,6 +414,11 @@ export async function installPack(input) {
315
414
  })
316
415
  text = result.text
317
416
  configItems.push({ plugin: plugin.name, action: result.action })
417
+ // 打包时被擦掉的凭据只剩占位符,明确要求重填,避免装完才发现认证失败
418
+ const redacted = Array.isArray(snapConfig.configRedacted) ? snapConfig.configRedacted : []
419
+ if (redacted.length > 0) {
420
+ lines.push('配置 ' + plugin.name + ' 有 ' + redacted.length + ' 处凭据已替换为 ${REDACTED},需自行重填:' + redacted.slice(0, 6).join(', ') + (redacted.length > 6 ? ' 等' : ''))
421
+ }
318
422
  actions.push({ plugin: plugin.name, action: 'config', ok: true, message: (result.action === 'replaced' ? '已对齐配置' : '已补上配置条目') })
319
423
  }
320
424
  if (text !== patch && !options.dryRun) {
@@ -323,6 +427,52 @@ export async function installPack(input) {
323
427
  }
324
428
  }
325
429
 
430
+ // 数据快照回填:插件自己写在 ~/.dsh/<目录>/ 下的文本数据(记忆、词库、笔记…)。
431
+ // 默认只补缺、不覆盖本机已有文件——避免装个包把人家攒的东西冲掉。
432
+ if (manifest.options.includeConfig !== false) {
433
+ const home = dshHome()
434
+ const written = []
435
+ const kept = []
436
+ for (const plugin of manifest.plugins) {
437
+ const dirs = Array.isArray(plugin.dataDirs) ? plugin.dataDirs : []
438
+ if (!plugin.dataIncluded || dirs.length === 0) continue
439
+ for (const base of dirs) {
440
+ const prefix = 'data/' + base + '/'
441
+ const baseDir = path.resolve(home, base)
442
+ for (const entry of entries) {
443
+ if (!entry.name.startsWith(prefix)) continue
444
+ const rel = entry.name.slice(prefix.length)
445
+ const target = path.resolve(baseDir, rel)
446
+ if (target !== baseDir && !target.startsWith(baseDir + path.sep)) continue
447
+ if (options.dryRun) {
448
+ lines.push('演练:将写回数据 ' + base + '/' + rel)
449
+ continue
450
+ }
451
+ if (fs.existsSync(target) && options.overwriteData !== true) {
452
+ kept.push(base + '/' + rel)
453
+ continue
454
+ }
455
+ fs.mkdirSync(path.dirname(target), { recursive: true })
456
+ fs.writeFileSync(target, entry.data)
457
+ written.push(base + '/' + rel)
458
+ }
459
+ }
460
+ }
461
+ for (const plugin of manifest.plugins) {
462
+ if (plugin.dataRedacted > 0) {
463
+ lines.push('数据快照 ' + plugin.name + ' 有 ' + plugin.dataRedacted + ' 处凭据已替换为 ${REDACTED},相关功能可能需要重填凭据')
464
+ }
465
+ }
466
+ if (written.length > 0) {
467
+ lines.push('数据快照已写回 ' + written.length + ' 个文件:' + written.slice(0, 6).join(', ') + (written.length > 6 ? ' 等' : ''))
468
+ actions.push({ plugin: '', action: 'data', ok: true, message: '数据快照写回 ' + written.length + ' 个文件' })
469
+ }
470
+ if (kept.length > 0) {
471
+ lines.push('有 ' + kept.length + ' 个数据文件本机已有,未覆盖(需要覆盖就重新装一次并选择覆盖数据)')
472
+ actions.push({ plugin: '', action: 'data', ok: true, message: '本机已存在、未覆盖 ' + kept.length + ' 个数据文件' })
473
+ }
474
+ }
475
+
326
476
  const ok = actions.every((a) => a.ok)
327
477
  const record = {
328
478
  at: new Date().toISOString(),
@@ -336,13 +486,15 @@ export async function installPack(input) {
336
486
  }
337
487
  if (!options.dryRun) writeJsonAtomic(path.join(packRoot, 'install-result.json'), record)
338
488
 
489
+ progress({ pct: 100, note: '安装完成' })
339
490
  return {
340
491
  ok,
341
492
  compat,
342
493
  actions,
494
+ deferred,
343
495
  configItems,
344
496
  lines,
345
- needsRestart: options.enableBundles === false ? false : actions.some((a) => a.action === 'install' && a.ok),
497
+ needsRestart: options.enableBundles === false ? false : (restartFromManager || actions.some((a) => a.action === 'install' && a.ok)),
346
498
  }
347
499
  }
348
500
 
package/lib/manifest.mjs CHANGED
@@ -47,7 +47,20 @@ function normalizePlugin(raw) {
47
47
  // 老包没有 mode 字段,用 localEdits 兜底
48
48
  mode: raw.mode === 'local' ? 'local' : raw.mode === 'base' ? 'base' : bool(raw.localEdits) ? 'local' : 'base',
49
49
  configIncluded: bool(raw.configIncluded),
50
+ // 打包时被替换成 ${REDACTED} 的配置路径(安装后需要重填)
51
+ configRedacted: Array.isArray(raw.configRedacted)
52
+ ? raw.configRedacted.map((item) => str(item, 200)).filter(Boolean).slice(0, 50)
53
+ : [],
50
54
  dataIncluded: bool(raw.dataIncluded),
55
+ // 数据快照里被替换成 ${REDACTED} 的凭据条数(安装后可能需要重填)
56
+ dataRedacted: num(raw.dataRedacted),
57
+ // 插件数据目录的真名(安装时原路放回 ~/.dsh/<名字>)
58
+ dataDirs: Array.isArray(raw.dataDirs)
59
+ ? raw.dataDirs
60
+ .map((item) => str(item, 120))
61
+ .filter((item) => /^[A-Za-z0-9._-]+$/u.test(item))
62
+ .slice(0, 20)
63
+ : [],
51
64
  peerDependencies: peerList,
52
65
  engines: raw.engines && typeof raw.engines === 'object' ? raw.engines : {},
53
66
  // pnpm 别名 / link 安装时目录名可能不等于包名,payload 前缀以它为准
@@ -62,7 +75,11 @@ function normalizePlugin(raw) {
62
75
 
63
76
  export function normalizeManifest(raw) {
64
77
  if (!raw || typeof raw !== 'object') throw new Error('清单不是对象')
65
- if (raw.schema !== SCHEMA) throw new Error('不支持的清单版本:' + String(raw.schema))
78
+ const schema = Number(raw.schema)
79
+ if (schema > SCHEMA) {
80
+ throw new Error('这个整合包是更新的格式(schema ' + schema + '),请先升级 dsh-modpack-kit 再装;现在这份只认到 schema ' + SCHEMA)
81
+ }
82
+ if (raw.schema !== SCHEMA) throw new Error('不支持的清单版本:' + String(raw.schema) + '(这份插件只认 schema ' + SCHEMA + ')')
66
83
  if (raw.kind !== KIND) throw new Error('不是 dsh 整合包:kind=' + String(raw.kind))
67
84
  const plugins = Array.isArray(raw.plugins) ? raw.plugins.slice(0, 200).map(normalizePlugin) : []
68
85
  if (plugins.length === 0) throw new Error('整合包里没有插件')
@@ -168,8 +185,10 @@ export function buildReadme(manifest, extra = {}) {
168
185
  lines.push(' 2. 运行包内安装器(需要 Node 20+):')
169
186
  lines.push(' Windows: install\\install.cmd 其它: sh install/install.sh')
170
187
  lines.push(' 可加参数:--profile <名字>(默认 desktop)--dry-run(只看要做什么)')
171
- lines.push(' --no-bundles(装了但先不启用)--dsh "<DSH 可执行文件或 cli.js>"')
188
+ lines.push(' --no-bundles(装了但先不启用)--replace(本机已装的也换成包内版本)')
189
+ lines.push(' --dsh "<DSH 可执行文件或 cli.js>"')
172
190
  lines.push(' 3. 安装器会逐插件执行官方 dsh plugin add、把 configs/ 里的配置合并进 cordis.patch.yml;')
191
+ lines.push(' 本机已经装了的插件它会先跳过、装完列出来;要换成包内版本,加 --replace 重跑一次。')
173
192
  lines.push(' 4. 重启 DSH。')
174
193
  lines.push(' 方式 C(手工,没有 Node 时):解压后对 plugins/ 下每个目录执行')
175
194
  lines.push(' dsh plugin --profile <你的profile> add "file:<绝对路径>/plugins/<插件名>"')
@@ -192,6 +211,9 @@ export function buildReadme(manifest, extra = {}) {
192
211
  lines.push(' · 不绕过任何官方渠道,不提供破解、破解依赖或规避授权的功能。')
193
212
  lines.push(' · 使用前请遵守所在地法律与 B 站/DeepSeek 等平台的服务条款。')
194
213
  lines.push('')
214
+ lines.push('')
215
+ lines.push('项目与更新:https://github.com/Vesna-Strivozha-cn/dsh-modpack-kit')
216
+ lines.push(' 这个整合包由 dsh-modpack-kit 生成;觉得省事可以到仓库点个 Star。')
195
217
  if (extra.footer) lines.push(extra.footer)
196
218
  return lines.join('\n')
197
219
  }
package/lib/pack.mjs CHANGED
@@ -79,7 +79,8 @@ export function collectFiles(root, options = {}) {
79
79
  /** 从 profile 读一个已装插件。 */
80
80
  export function readInstalledPlugin(installed, options = {}) {
81
81
  const { files, notes } = collectFiles(installed.dir, {
82
- prefix: 'plugins/' + installed.dirName + '/',
82
+ // 调用方若没带 dirName(例如直接按名字选插件),退回到包名,避免写出 plugins/undefined/
83
+ prefix: 'plugins/' + (installed.dirName || installed.name) + '/',
83
84
  maxFileBytes: options.maxFileBytes,
84
85
  maxTotalBytes: options.maxTotalBytes,
85
86
  })
@@ -90,6 +91,60 @@ export function readInstalledPlugin(installed, options = {}) {
90
91
  * 抓 profile 补丁层里的配置(每个插件一条)。
91
92
  * 解析失败就整体放弃自动抓取,只留一句 note——宁可少带,也不带错。
92
93
  */
94
+ /**
95
+ * 配置里的凭据擦除。
96
+ *
97
+ * 打包会把插件的 config 一起带走,而 config 最容易藏 token。做法是两道:
98
+ * 字段名归一化后命中名单(`api_key` / `apiKey` / `api-key` 都算),或者值本身
99
+ * 长得像密钥,就替换成字面量 ${REDACTED}。只按“归一化后完全相等”判字段名,
100
+ * 免得把 `apiKeyEnv` 这种写环境变量名的字段误伤。
101
+ */
102
+ const SECRET_KEY_SET = new Set([
103
+ 'apikey', 'apitoken', 'token', 'accesstoken', 'refreshtoken', 'secret',
104
+ 'clientsecret', 'password', 'passwd', 'credential', 'credentials',
105
+ 'authorization', 'cookie', 'privatekey', 'secretkey', 'sessionkey',
106
+ 'sessdata', 'bilijct', 'dedeuserid',
107
+ ])
108
+
109
+ const SECRET_VALUE_PATTERN = 'sk-[A-Za-z0-9_-]{12,}|gh[pousr]_[A-Za-z0-9]{20,}|xox[baprs]-[A-Za-z0-9-]{10,}|AKIA[0-9A-Z]{16}'
110
+ const SECRET_VALUE_TEST = new RegExp(SECRET_VALUE_PATTERN)
111
+ const SECRET_VALUE_GLOBAL = new RegExp(SECRET_VALUE_PATTERN, 'gu')
112
+
113
+ export const REDACTED = '${REDACTED}'
114
+
115
+ export function normalizeConfigKey(key) {
116
+ return String(key ?? '').toLowerCase().replace(/[-_\s]/gu, '')
117
+ }
118
+
119
+ /**
120
+ * @returns {{value: unknown, paths: string[]}} 擦除后的值与命中路径
121
+ */
122
+ export function redactConfig(value, path = '', paths = []) {
123
+ if (Array.isArray(value)) {
124
+ return { value: value.map((item, index) => redactConfig(item, path + '[' + index + ']', paths).value), paths }
125
+ }
126
+ if (value && typeof value === 'object') {
127
+ const next = {}
128
+ for (const [key, child] of Object.entries(value)) {
129
+ const childPath = path ? path + '.' + key : key
130
+ const empty = child === undefined || child === null || child === ''
131
+ if (SECRET_KEY_SET.has(normalizeConfigKey(key))) {
132
+ if (!empty && typeof child !== 'boolean') paths.push(childPath)
133
+ next[key] = REDACTED
134
+ continue
135
+ }
136
+ next[key] = redactConfig(child, childPath, paths).value
137
+ }
138
+ return { value: next, paths }
139
+ }
140
+ if (typeof value === 'string' && SECRET_VALUE_TEST.test(value)) {
141
+ const replaced = value.replace(SECRET_VALUE_GLOBAL, REDACTED)
142
+ if (replaced !== value) paths.push(path || '(值)')
143
+ return { value: replaced, paths }
144
+ }
145
+ return { value, paths }
146
+ }
147
+
93
148
  export function captureConfigs(patchText, plugins, parsePatch) {
94
149
  const captured = new Map()
95
150
  const notes = []
@@ -108,31 +163,69 @@ export function captureConfigs(patchText, plugins, parsePatch) {
108
163
  const id = typeof item.id === 'string' ? item.id : ''
109
164
  const hit = byName.get(name) || byName.get(id)
110
165
  if (!hit) continue
111
- captured.set(hit.name, { id: item.id, name: item.name, disabled: item.disabled === true ? true : undefined, config: item.config ?? null })
166
+ // 配置里最可能藏 token;打包前按字段名与明文特征先抹掉,包离手之后就不会再漏。
167
+ const redacted = redactConfig(item.config ?? null)
168
+ if (redacted.paths.length > 0) {
169
+ notes.push('配置 ' + hit.name + ' 里 ' + redacted.paths.length + ' 处疑似凭据已替换为 ${REDACTED}:' + redacted.paths.slice(0, 6).join(', ') + (redacted.paths.length > 6 ? ' 等' : ''))
170
+ }
171
+ captured.set(hit.name, {
172
+ id: item.id,
173
+ name: item.name,
174
+ disabled: item.disabled === true ? true : undefined,
175
+ config: redacted.value,
176
+ ...(redacted.paths.length > 0 ? { configRedacted: redacted.paths } : {}),
177
+ })
112
178
  }
113
179
  return { captured, notes }
114
180
  }
115
181
 
116
182
  function dataDirsFor(name) {
117
183
  const home = process.env.DSH_HOME || path.join(process.env.USERPROFILE || '', '.dsh')
184
+ // 插件的数据目录名不一定等于包名(例如 dsh-plugin-memory 存在 plugin-memory 下),
185
+ // 所以按目录真名打包,安装时才能原路放回。
118
186
  const candidates = [name, name.replace(/^dsh-/u, '')].filter(Boolean)
119
187
  const out = []
188
+ const seen = new Set()
120
189
  for (const candidate of candidates) {
121
190
  const dir = path.join(home, candidate)
122
191
  try {
123
- if (fs.statSync(dir).isDirectory()) out.push({ dir, prefix: 'data/' + name + '/' })
192
+ if (!fs.statSync(dir).isDirectory()) continue
193
+ const base = path.basename(dir)
194
+ if (seen.has(base)) continue
195
+ seen.add(base)
196
+ out.push({ dir, base, prefix: 'data/' + base + '/' })
124
197
  } catch {}
125
198
  }
126
199
  return out
127
200
  }
128
201
 
202
+ /**
203
+ * 数据快照里的文本擦除:只动「明显的凭据值」,不改结构。
204
+ * - sk-/ghp_/xoxb-/AKIA 这类明文 token 直接替换;
205
+ * - SESSDATA=… / password: … / api_key=… 这类键值对,只保留键名。
206
+ * 原文不落盘,替换后写进包里;命中条数记在 note 上。
207
+ */
208
+ const DATA_SECRET_PAIR = /(\b(?:sessdata|bili_jct|dedeuserid|access[_-]?token|refresh[_-]?token|api[_-]?key|apikey|secret|password|passwd|authorization|cookie)\b\s*[:=]\s*)(["']?)([^\s"',;}]{8,})\2/giu
209
+
210
+ function scrubText(text) {
211
+ let count = 0
212
+ let out = text.replace(SECRET_VALUE_GLOBAL, () => { count += 1; return REDACTED })
213
+ out = out.replace(DATA_SECRET_PAIR, (whole, head, quote) => {
214
+ count += 1
215
+ return head + quote + REDACTED + quote
216
+ })
217
+ return { text: out, count }
218
+ }
219
+
129
220
  /** 插件数据快照:只收小体积文本类,凭证类文件名直接跳过。 */
130
221
  export function captureData(name, options = {}) {
131
222
  const files = []
132
223
  const notes = []
224
+ const dirs = []
133
225
  let total = 0
226
+ let redacted = 0
134
227
  const limit = options.maxBytes ?? 8 * 1024 * 1024
135
- for (const { dir, prefix } of dataDirsFor(name)) {
228
+ for (const { dir, base, prefix } of dataDirsFor(name)) {
136
229
  const entries = []
137
230
  const walk = (d, rel) => {
138
231
  let dirents
@@ -155,11 +248,22 @@ export function captureData(name, options = {}) {
155
248
  }
156
249
  }
157
250
  walk(dir, '')
251
+ if (entries.length > 0) dirs.push(base)
158
252
  for (const entry of entries) {
159
- try { files.push({ name: entry.name, data: fs.readFileSync(entry.abs), mtime: new Date() }) } catch {}
253
+ try {
254
+ const raw = fs.readFileSync(entry.abs)
255
+ const { text, count } = scrubText(raw.toString('utf8'))
256
+ if (count > 0) {
257
+ redacted += count
258
+ notes.push('数据文件 ' + entry.name + ' 里 ' + count + ' 处疑似凭据已替换为 ${REDACTED}')
259
+ files.push({ name: entry.name, data: Buffer.from(text, 'utf8'), mtime: new Date() })
260
+ } else {
261
+ files.push({ name: entry.name, data: raw, mtime: new Date() })
262
+ }
263
+ } catch {}
160
264
  }
161
265
  }
162
- return { files, notes }
266
+ return { files, notes, dirs, redacted }
163
267
  }
164
268
 
165
269
  function licenseId(pkg) {
@@ -315,16 +419,19 @@ export async function buildPack(input) {
315
419
  if (plugin.mode === 'base') continue
316
420
  const snap = captured.get(plugin.name)
317
421
  if (snap && (snap.config !== null || snap.disabled !== undefined)) {
318
- const body = JSON.stringify({ id: snap.id, name: snap.name, disabled: snap.disabled, config: snap.config, capturedAt: new Date().toISOString() }, null, 2)
422
+ const body = JSON.stringify({ id: snap.id, name: snap.name, disabled: snap.disabled, config: snap.config, ...(snap.configRedacted ? { configRedacted: snap.configRedacted } : {}), capturedAt: new Date().toISOString() }, null, 2)
319
423
  capturedFiles.push({ name: 'configs/' + plugin.name + '.json', data: Buffer.from(body, 'utf8') })
320
424
  plugin.configIncluded = true
321
425
  plugin.config = snap.config
426
+ if (Array.isArray(snap.configRedacted) && snap.configRedacted.length > 0) plugin.configRedacted = snap.configRedacted
322
427
  if (snap.disabled) plugin.note = '打包时该插件被禁用'
323
428
  }
324
429
  const data = captureData(plugin.name, { maxBytes: 8 * 1024 * 1024 })
430
+ if (data.redacted > 0) plugin.dataRedacted = (plugin.dataRedacted || 0) + data.redacted
325
431
  if (data.files.length > 0) {
326
432
  capturedFiles.push(...data.files)
327
433
  plugin.dataIncluded = true
434
+ plugin.dataDirs = data.dirs
328
435
  notes.push(...data.notes)
329
436
  }
330
437
  }
package/lib/scan.mjs CHANGED
@@ -9,6 +9,7 @@
9
9
  *
10
10
  * 规则表是数据,扩展接口 `registerScanner` 可以往里加规则,不用改这个文件。
11
11
  */
12
+ import { createHash } from 'node:crypto'
12
13
 
13
14
  const TEXT_EXT = new Set([
14
15
  '.js', '.mjs', '.cjs', '.ts', '.tsx', '.jsx', '.json', '.yml', '.yaml', '.toml', '.ini', '.cfg',
@@ -244,6 +245,7 @@ export function scanEntries(entries, options = {}) {
244
245
  const findings = []
245
246
  let scannedBytes = 0
246
247
  const skipped = []
248
+ const cache = new Map()
247
249
  const rules = Array.isArray(options.extraRules) ? options.extraRules : []
248
250
  const extra = rules
249
251
  .filter((r) => r && typeof r.id === 'string' && r.re instanceof RegExp)
@@ -251,6 +253,25 @@ export function scanEntries(entries, options = {}) {
251
253
 
252
254
  for (const entry of entries) {
253
255
  scannedBytes += entry.data.length
256
+ // 同一份内容在一个包里出现多次很常见(LICENSE、复制的依赖、同版本资产)。
257
+ // 内容相同就直接复用上一次的结论,只有文件名规则要按当前名字重算。
258
+ const reusable = entry.data.length > 0
259
+ && entry.data.length <= MAX_SCAN_BYTES
260
+ && !looksBinary(entry.data)
261
+ && scanFileName(entry.name).length === 0
262
+ if (reusable) {
263
+ const key = createHash('sha1').update(entry.data).digest('hex')
264
+ const hit = cache.get(key)
265
+ if (hit) {
266
+ for (const finding of hit) findings.push({ ...finding, file: entry.name })
267
+ continue
268
+ }
269
+ const result = scanFile(entry.name, entry.data)
270
+ findings.push(...result.findings)
271
+ if (result.skipped) skipped.push({ file: entry.name, reason: result.skipped })
272
+ cache.set(key, result.findings.map((finding) => ({ ...finding })))
273
+ continue
274
+ }
254
275
  const result = scanFile(entry.name, entry.data)
255
276
  findings.push(...result.findings)
256
277
  if (result.skipped) skipped.push({ file: entry.name, reason: result.skipped })
package/lib/store.mjs CHANGED
@@ -56,6 +56,8 @@ export const DEFAULT_CONFIG = {
56
56
  maxDownloadBytes: 256 * 1024 * 1024,
57
57
  maxPackBytes: 512 * 1024 * 1024,
58
58
  maxFileBytes: 16 * 1024 * 1024,
59
+ // 进度窗里「收尾」的记录留多久(秒):正常的完成记录留久一点,失败/取消的留很短,别堆在眼前
60
+ jobKeepSeconds: 60,
59
61
  // 二次开发用:额外扫描规则(形状同 lib/scan.mjs 的 SECRET_RULES)
60
62
  extraScanRules: [],
61
63
  historyLimit: 50,
@@ -68,6 +70,8 @@ export const DEFAULT_CONFIG = {
68
70
  showInPluginsTab: false,
69
71
  // 安装后是否直接登记到 bundles(默认关:只装文件,重启也不加载)
70
72
  enableOnInstall: false,
73
+ // 装整合包时若联网且插件市场有同名条目,优先按市场版本装(关掉则严格按包内那份)
74
+ preferMarketOnInstall: true,
71
75
  // 白名单迁移标记:跑过一次就别再往里并默认域名,尊重用户自己的增删
72
76
  hostsVersion: HOSTS_VERSION,
73
77
  }
@@ -105,6 +109,9 @@ function clampConfig(raw) {
105
109
  // 分页大小与刷新周期:给了边界,避免有人把 10000 写进设置把页面拖死
106
110
  cfg.catalogPageSize = Math.min(100, Math.max(5, Number(cfg.catalogPageSize) || DEFAULT_CONFIG.catalogPageSize))
107
111
  cfg.catalogRefreshHours = Math.min(168, Math.max(1, Number(cfg.catalogRefreshHours) || DEFAULT_CONFIG.catalogRefreshHours))
112
+ // 0 是合法的:等于「收尾就立刻清掉」,测试也靠它把时间压到零
113
+ const keepRaw = raw && typeof raw.jobKeepSeconds === 'number' ? raw.jobKeepSeconds : DEFAULT_CONFIG.jobKeepSeconds
114
+ cfg.jobKeepSeconds = Math.min(3600, Math.max(0, Math.floor(Number(keepRaw) || 0)))
108
115
  // 进度窗位置不在这里管:它由界面自己拖动并存在浏览器本地,服务端不需要知道
109
116
  // 打包前安全检测是强制的:设置里怎么写都不认,打包一律扫。
110
117
  cfg.scanBeforePack = true