@twinsearth/dsh-fang 3.0.8 → 3.0.9

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.
@@ -86,6 +86,11 @@ function asObject(value) {
86
86
  return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : {}
87
87
  }
88
88
 
89
+ /** v3.0.9:冻结(archived)的元主只能删除,其它操作一律拒绝。 */
90
+ function assertNotFrozen(meta) {
91
+ if (meta && meta.archived === true) throw new Error(`essence ${meta.id} is archived/frozen(已冻结,只能删除)`)
92
+ }
93
+
89
94
  /**
90
95
  * 原身(顶层)配额检查。
91
96
  * @param {string} tier VIP 等级
@@ -562,6 +567,105 @@ export class EssenceManager {
562
567
  })
563
568
  }
564
569
 
570
+ /**
571
+ * 从母体 profile 生成元主(v3.0.9):把母体的**可写层**克隆成新元主的覆盖层。
572
+ *
573
+ * 克隆范围(只读母体):
574
+ * * `cordis.patch.yml` → overlay patch entries(插件安装/启用/配置)
575
+ * * `package.json` → overlay 的 name/private/type/dsh/dependencies(可关)
576
+ * * `settings/*.yaml` → overlay settings(可关)
577
+ * 绝不复制:credentials、sessions、storages、logs、node_modules(B8 边界)。
578
+ *
579
+ * @param {string} profileDir 母体 profile 目录(必须含 package.json)
580
+ * @param {{name?:string, tier?:string, parentId?:string|null, includeDependencies?:boolean,
581
+ * includeSettings?:boolean, defaultPatchEntries?:Array<Record<string,unknown>>, skipQuota?:boolean}} [options]
582
+ * @returns {{meta:any, captured:Record<string,unknown>, conflicts:Conflict[], status:string}}
583
+ */
584
+ captureFromProfile(profileDir, options = {}) {
585
+ const dir = path.resolve(String(profileDir ?? '').trim())
586
+ if (dir.length === 0) throw new Error('capture: mother profile dir required')
587
+ const packageFile = path.join(dir, 'package.json')
588
+ if (!exists(packageFile)) throw new Error(`capture: mother profile has no package.json: ${dir}`)
589
+ // 元主自己的物化目录不能当母体(否则是自我叠加)。
590
+ const relative = path.relative(path.resolve(this.essencesRoot), dir)
591
+ if (relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative))) {
592
+ throw new Error('capture: refusing to clone from an essence directory')
593
+ }
594
+ const profilePkg = asObject(readJson(packageFile, {}))
595
+ const patchText = exists(path.join(dir, 'cordis.patch.yml'))
596
+ ? fs.readFileSync(path.join(dir, 'cordis.patch.yml'), 'utf8')
597
+ : ''
598
+ const parsed = parsePatchEntries(patchText)
599
+ if (parsed.errors.length > 0) {
600
+ throw new Error(`capture: mother patch parse failed: ${parsed.errors.join('; ')}`)
601
+ }
602
+ const fallbackName = typeof profilePkg.name === 'string' && profilePkg.name.length > 0
603
+ ? `${profilePkg.name} 元主` : `${path.basename(dir)} 元主`
604
+ const name = String(options?.name ?? '').trim() || fallbackName
605
+
606
+ const created = this.create({
607
+ name,
608
+ tier: options?.tier,
609
+ parentId: options?.parentId ?? null,
610
+ skipQuota: options?.skipQuota === true,
611
+ })
612
+ const root = this.essenceRoot(created.id)
613
+ const overlay = this.loadOverlay(root)
614
+ const seedEntries = Array.isArray(options?.defaultPatchEntries)
615
+ ? options.defaultPatchEntries.map(entry => ({ ...entry })) : []
616
+ overlay.patchEntries = [...seedEntries, ...parsed.entries, ...overlay.patchEntries]
617
+ if (options?.includeDependencies !== false) {
618
+ overlay.packageJson = { ...this.selectProfilePackage(profilePkg), ...overlay.packageJson }
619
+ }
620
+ if (options?.includeSettings !== false) {
621
+ Object.assign(overlay.settings, this.readProfileSettings(dir))
622
+ }
623
+ this.saveOverlay(root, overlay)
624
+ const merge = this.recompute(created.id)
625
+ const bundles = asObject(profilePkg.dsh).profile?.bundles
626
+ const captured = {
627
+ profileDir: dir,
628
+ profileName: typeof profilePkg.name === 'string' ? profilePkg.name : null,
629
+ patchEntries: parsed.entries.length,
630
+ dependencies: Object.keys(asObject(overlay.packageJson.dependencies)).length,
631
+ bundles: Array.isArray(bundles) ? bundles.length : 0,
632
+ settings: Object.keys(overlay.settings).length,
633
+ credentialsCopied: false,
634
+ }
635
+ return { meta: this.getMeta(created.id), captured, conflicts: merge.conflicts, status: merge.status }
636
+ }
637
+
638
+ /** 提取可安全复制进元主 overlay 的 profile package.json 字段(不含 scripts/devDeps)。 */
639
+ selectProfilePackage(profilePkg) {
640
+ /** @type {Record<string, unknown>} */
641
+ const picked = {}
642
+ for (const key of ['name', 'private', 'type']) {
643
+ if (profilePkg?.[key] !== undefined) picked[key] = profilePkg[key]
644
+ }
645
+ const dsh = asObject(profilePkg?.dsh)
646
+ if (Object.keys(dsh).length > 0) picked.dsh = dsh
647
+ const deps = asObject(profilePkg?.dependencies)
648
+ if (Object.keys(deps).length > 0) picked.dependencies = deps
649
+ return picked
650
+ }
651
+
652
+ /** 读取母体 profile 的 settings/*.yaml(仅为覆盖层,不碰其他目录)。 */
653
+ readProfileSettings(profileDir) {
654
+ /** @type {Record<string, unknown>} */
655
+ const settings = {}
656
+ const settingsDir = path.join(String(profileDir), 'settings')
657
+ if (!exists(settingsDir)) return settings
658
+ for (const file of fs.readdirSync(settingsDir)) {
659
+ if (!file.endsWith('.yaml') && !file.endsWith('.yml')) continue
660
+ const text = fs.readFileSync(path.join(settingsDir, file), 'utf8')
661
+ const name = file.replace(/\.ya?ml$/, '')
662
+ try { settings[name] = JSON.parse(text) } catch {
663
+ settings[name] = parseYamlSubset(text).value
664
+ }
665
+ }
666
+ return settings
667
+ }
668
+
565
669
  /**
566
670
  * 修改覆盖层并重算(mutator 直接改 overlay 对象;save 由 manager 完成)。
567
671
  * @param {string} essenceId
@@ -572,6 +676,7 @@ export class EssenceManager {
572
676
  const root = this.essenceRoot(essenceId)
573
677
  const meta = this.readMeta(root)
574
678
  if (meta.locked === true) throw new Error(`essence ${essenceId} is locked(官方推荐原身不支持修改设置)`)
679
+ assertNotFrozen(meta)
575
680
  const overlay = this.loadOverlay(root)
576
681
  await mutator(overlay)
577
682
  this.saveOverlay(root, overlay)
@@ -587,6 +692,8 @@ export class EssenceManager {
587
692
  remove(essenceId) {
588
693
  const meta = this.getMeta(essenceId)
589
694
  if (meta.locked === true) throw new Error(`essence ${essenceId} is locked(官方推荐原身不可删除)`)
695
+ // v3.0.9 规则:先归档(冻结)才允许删除,删除本身不可撤销。
696
+ if (meta.archived !== true) throw new Error(`essence ${essenceId} is not archived; archive it before deleting`)
590
697
  if (meta.parentId === null) {
591
698
  const children = this.listChildren(essenceId)
592
699
  if (children.length > 0) throw new Error(`essence ${essenceId} has ${children.length} sub-essences; remove them first`)
@@ -600,6 +707,7 @@ export class EssenceManager {
600
707
  const root = this.essenceRoot(essenceId)
601
708
  const meta = this.readMeta(root)
602
709
  if (meta.locked === true) throw new Error(`essence ${essenceId} is locked(官方推荐原身等级不可修改)`)
710
+ assertNotFrozen(meta)
603
711
  const next = { ...meta, tier: normalizeTier(tier), updatedAt: this.now() }
604
712
  this.writeMeta(root, next)
605
713
  return this.getMeta(essenceId)
@@ -613,6 +721,7 @@ export class EssenceManager {
613
721
  const root = this.essenceRoot(essenceId)
614
722
  const meta = this.readMeta(root)
615
723
  if (meta.locked === true) throw new Error(`essence ${essenceId} is locked(官方推荐原身不可重命名)`)
724
+ assertNotFrozen(meta)
616
725
  const next = { ...meta, name: trimmed, updatedAt: this.now() }
617
726
  this.writeMeta(root, next)
618
727
  return this.getMeta(essenceId)
@@ -659,6 +768,7 @@ export class EssenceManager {
659
768
  */
660
769
  copy(essenceId, options = {}) {
661
770
  const source = this.getMeta(essenceId)
771
+ assertNotFrozen(source)
662
772
  const sourceRoot = this.essenceRoot(essenceId)
663
773
  const name = String(options?.name ?? `${source.name} 副本`).trim()
664
774
  const created = this.create({
@@ -667,11 +777,35 @@ export class EssenceManager {
667
777
  parentId: source.parentId ?? null,
668
778
  })
669
779
  const nextRoot = this.essenceRoot(created.id)
670
- const overlay = this.loadOverlay(sourceRoot)
671
- overlay.credentialsPath = ''
672
- this.saveOverlay(nextRoot, overlay)
780
+ // v3.0.9 深复制:整份沙箱目录(overlay + merged + 自定义数据)到新文件夹。
781
+ // 边界:不复制 credentials(B8)、不复制 runtime(运行态进程目录)、不复制 Backup、不覆盖新 meta。
782
+ const skip = new Set(['meta.json', 'credentials', 'runtime', 'Backup'])
783
+ let copiedFiles = 0
784
+ for (const entry of fs.readdirSync(sourceRoot, { withFileTypes: true })) {
785
+ if (skip.has(entry.name)) continue
786
+ const from = path.join(sourceRoot, entry.name)
787
+ const to = path.join(nextRoot, entry.name)
788
+ if (exists(to)) removeTree(to)
789
+ copyTree(from, to)
790
+ // overlay/credentials 属于登录态,必须剔除(B8)。
791
+ const copiedCredentials = path.join(to, 'credentials')
792
+ if (entry.name === 'overlay' && exists(copiedCredentials)) removeTree(copiedCredentials)
793
+ if (entry.isDirectory()) {
794
+ const walk = (dir) => {
795
+ for (const child of fs.readdirSync(dir, { withFileTypes: true })) {
796
+ const file = path.join(dir, child.name)
797
+ if (child.isDirectory()) walk(file)
798
+ else if (child.isFile()) copiedFiles += 1
799
+ }
800
+ }
801
+ walk(to)
802
+ } else if (entry.isFile()) copiedFiles += 1
803
+ }
804
+ // 凭据目录在新沙箱里保持为空(不继承任何登录态)。
805
+ ensureDir(path.join(nextRoot, 'overlay', 'credentials'))
673
806
  this.recompute(created.id)
674
- return this.getMeta(created.id)
807
+ const meta = this.getMeta(created.id)
808
+ return { ...meta, copy: { sourceId: source.id, copiedFiles } }
675
809
  }
676
810
 
677
811
  /** 元主当前插件条目数(用于面板卡片)。 */
@@ -687,24 +821,137 @@ export class EssenceManager {
687
821
  const maxBytes = Math.max(1024, Math.floor(Number(options.maxBytes) || 32 * 1024 * 1024))
688
822
  const root = this.essenceRoot(essenceId)
689
823
  const meta = this.getMeta(essenceId)
690
- const overlayRoot = path.join(root, 'overlay')
824
+ const full = options.full === true
825
+ const base = full ? root : path.join(root, 'overlay')
691
826
  const files = []
692
827
  let total = 0
828
+ // full=true:整包导出(跨机迁移);跳过凭据、运行时 home 与备份目录。
829
+ const skip = new Set(full ? ['credentials', 'runtime', 'Backup'] : ['credentials'])
693
830
  const walk = (dir, relative) => {
694
831
  for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
695
- if (entry.name === 'credentials') continue
696
- const full = path.join(dir, entry.name)
832
+ if (skip.has(entry.name)) continue
833
+ // full=true:运行态只导出它的会话沙箱(runtime/home/sessions),不含进程/依赖目录。
834
+ if (full && entry.name === 'runtime') {
835
+ const sessionsDir = path.join(dir, 'runtime', 'home', 'sessions')
836
+ if (exists(sessionsDir)) walk(sessionsDir, 'runtime/home/sessions')
837
+ continue
838
+ }
839
+ const target = path.join(dir, entry.name)
697
840
  const rel = relative ? `${relative}/${entry.name}` : entry.name
698
- if (entry.isDirectory()) { walk(full, rel); continue }
841
+ if (entry.isDirectory()) { walk(target, rel); continue }
699
842
  if (!entry.isFile()) continue
700
- const bytes = fs.readFileSync(full)
843
+ const bytes = fs.readFileSync(target)
701
844
  total += bytes.length
702
845
  if (total > maxBytes) throw new Error('essence bundle too large')
703
- files.push({ path: `overlay/${rel}`, base64: bytes.toString('base64') })
846
+ files.push({ path: full ? rel : `overlay/${rel}`, base64: bytes.toString('base64') })
847
+ }
848
+ }
849
+ if (exists(base)) walk(base, '')
850
+ if (full) {
851
+ // 迁移引导 + 清单,保证新 PC 拿到包就知道怎么导入。
852
+ const guide = [
853
+ '# dsh-Fang 元主导入引导',
854
+ '',
855
+ '1. 目标机器安装并启用 dsh-Fang(@twinsearth/dsh-fang)。',
856
+ '2. 打开瓮城面板 → 元主区 → 「导入」→ 选择本 JSON 文件(或 POST /fang/api/essence/import)。',
857
+ '3. 导入会生成新的 essences/<新id> 并自动重算;凭据不随包迁移,需要重新登录。',
858
+ '4. 打开前建议先执行「同步」,把该元主重放到目标机器当前的母体镜像。',
859
+ '',
860
+ `来源元主:${String(meta?.name ?? '')} (${essenceId})`,
861
+ `导出时间:${new Date(this.now()).toISOString()}`,
862
+ '包格式:dsh-fang-essence-bundle v1',
863
+ ].join('\n')
864
+ const manifest = JSON.stringify({
865
+ format: 'dsh-fang-essence-bundle',
866
+ version: 1,
867
+ createdAt: this.now(),
868
+ sourceId: essenceId,
869
+ name: meta?.name ?? null,
870
+ tier: meta?.tier ?? null,
871
+ files: files.length,
872
+ }, null, 2)
873
+ const appendText = (name, text) => {
874
+ const bytes = Buffer.from(text, 'utf8')
875
+ total += bytes.length
876
+ if (total > maxBytes) throw new Error('essence bundle too large')
877
+ files.push({ path: name, base64: bytes.toString('base64') })
878
+ }
879
+ appendText('IMPORT-GUIDE.md', guide)
880
+ appendText('manifest.json', manifest)
881
+ }
882
+ return { ok: true, essenceId, meta, files, bytes: total, full, createdAt: this.now() }
883
+ }
884
+
885
+ /** v3.0.9 备份:essences/<id>/Backup(固定一份,旧备份覆盖)。 */
886
+ backup(essenceId) {
887
+ const root = this.essenceRoot(essenceId)
888
+ assertNotFrozen(this.getMeta(essenceId))
889
+ const target = path.join(root, 'Backup')
890
+ if (exists(target)) removeTree(target)
891
+ // 原子写可能留下 .meta.json.*.tmp:默认过滤点文件,避免备份时 EPERM/半成品。
892
+ // runtime 是运行态进程目录(可能含 node_modules junction),不进入备份。
893
+ copyTree(root, target, {
894
+ filter: (name) => name !== 'meta.json' && name !== 'runtime' && !name.startsWith('.'),
895
+ })
896
+ const metaFile = path.join(root, 'meta.json')
897
+ if (exists(metaFile)) {
898
+ fs.writeFileSync(path.join(target, 'meta.json'), fs.readFileSync(metaFile))
899
+ }
900
+ const nested = path.join(target, 'Backup')
901
+ if (exists(nested)) removeTree(nested)
902
+ let bytes = 0
903
+ const walk = (dir) => {
904
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
905
+ const file = path.join(dir, entry.name)
906
+ if (entry.isDirectory()) walk(file)
907
+ else if (entry.isFile()) bytes += fs.statSync(file).size
704
908
  }
705
909
  }
706
- if (exists(overlayRoot)) walk(overlayRoot, '')
707
- return { ok: true, essenceId, meta, files, bytes: total, createdAt: this.now() }
910
+ walk(target)
911
+ return { ok: true, essenceId, backupDir: target, bytes, at: this.now() }
912
+ }
913
+
914
+ /** v3.0.9 还原:用 Backup 覆盖当前 overlay/merged/meta(Backup 保留一份)。 */
915
+ restoreBackup(essenceId) {
916
+ assertNotFrozen(this.getMeta(essenceId))
917
+ const root = this.essenceRoot(essenceId)
918
+ const backupDir = path.join(root, 'Backup')
919
+ if (!exists(backupDir)) throw new Error('backup-missing')
920
+ for (const entry of fs.readdirSync(backupDir, { withFileTypes: true })) {
921
+ if (entry.name === 'Backup' || entry.name === 'runtime' || entry.name === 'meta.json') continue
922
+ const from = path.join(backupDir, entry.name)
923
+ const to = path.join(root, entry.name)
924
+ if (exists(to)) removeTree(to)
925
+ copyTree(from, to)
926
+ }
927
+ this.recompute(essenceId)
928
+ return { ok: true, essenceId, restored: true, at: this.now() }
929
+ }
930
+
931
+ /** v3.0.9 导入:{meta, files:[{path,base64}]} → 新元主目录,可直接继续开发。 */
932
+ importBundle(doc, options = {}) {
933
+ const sourceMeta = asObject(doc?.meta)
934
+ const files = Array.isArray(doc?.files) ? doc.files : []
935
+ if (files.length === 0) throw new Error('bundle has no files')
936
+ const name = String(options?.name ?? sourceMeta.name ?? '导入的元主').trim() || '导入的元主'
937
+ const meta = this.create({
938
+ name,
939
+ tier: options?.tier ?? sourceMeta.tier,
940
+ parentId: options?.parentId ?? null,
941
+ skipQuota: options?.skipQuota === true,
942
+ })
943
+ const root = this.essenceRoot(meta.id)
944
+ for (const file of files) {
945
+ const rel = String(file?.path ?? '')
946
+ if (!rel || rel.includes('..') || path.isAbsolute(rel)) continue
947
+ // 包里的 meta.json / Backup 不能覆盖导入后新建的元数据。
948
+ if (rel === 'meta.json' || rel.startsWith('Backup/') || rel === 'Backup') continue
949
+ const target = path.join(root, rel)
950
+ ensureDir(path.dirname(target))
951
+ fs.writeFileSync(target, Buffer.from(String(file.base64 ?? ''), 'base64'))
952
+ }
953
+ this.recompute(meta.id)
954
+ return { ok: true, essence: this.getMeta(meta.id), files: files.length, sourceId: sourceMeta.id ?? null }
708
955
  }
709
956
 
710
957
  // ── 合并与物化 ──────────────────────────────────────────────────────────
@@ -0,0 +1,54 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // v3.0.9 分身 = 生产盘:派生 profile 里关闭插件安装 / 设置入口。
3
+ // 只锁定在当前 DSH 组合里确认存在的条目 id;DSH_FANG_FORK_CONFIG_LOCK=0 可整体关闭。
4
+ import fs from 'node:fs'
5
+ import path from 'node:path'
6
+
7
+ export const FORK_LOCKED_ENTRY_IDS = Object.freeze([
8
+ // 只禁用不影响 DSH 客户端服务图的条目。
9
+ // 禁用 config-editor / ui-settings 会移除 configForms 服务,导致 locale 及之后
10
+ // 50 个客户端插件永久 pending(实测:web boot 50 entries did not activate)。
11
+ 'tool-plugin-manager',
12
+ ])
13
+
14
+ // cordis.yml 不加只读:DSH 启动时会打开它做规范化写入,只读会导致 EPERM 启动失败。
15
+ export const PROFILE_CONFIG_FILES = Object.freeze(['package.json', 'cordis.patch.yml'])
16
+
17
+ /** 把分身 profile 的配置文件设为只读(防止误写;不防有意绕过)。 */
18
+ export function setProfileConfigReadonly(profileDir, readonly = true) {
19
+ if (String(process.env.DSH_FANG_FORK_PROFILE_RO ?? '1') === '0') return { ok: true, skipped: true, changed: [] }
20
+ const changed = []
21
+ for (const name of PROFILE_CONFIG_FILES) {
22
+ const file = path.join(String(profileDir), name)
23
+ try {
24
+ fs.chmodSync(file, readonly ? 0o444 : 0o644)
25
+ changed.push(name)
26
+ } catch { /* 文件不存在/平台不支持则跳过 */ }
27
+ }
28
+ return { ok: true, changed }
29
+ }
30
+
31
+ export function applyForkConfigLock(profileDir, options = {}) {
32
+ if (String(process.env.DSH_FANG_FORK_CONFIG_LOCK ?? '1') === '0') return { ok: true, skipped: true }
33
+ const file = path.join(String(profileDir), 'cordis.patch.yml')
34
+ let text = ''
35
+ try { text = fs.readFileSync(file, 'utf8') } catch { text = '' }
36
+ // 模板里的 `[]`(空 YAML 数组)必须去掉,否则追加 `- id:` 会变成非法 YAML。
37
+ const kept = text
38
+ .replace(/^\uFEFF/, '')
39
+ .split(/\r?\n/)
40
+ .filter((line) => !/^\s*\[\s*\]\s*(#.*)?$/.test(line))
41
+ text = kept.join('\n')
42
+ const lines = []
43
+ for (const id of (options.ids ?? FORK_LOCKED_ENTRY_IDS)) {
44
+ const present = new RegExp(`(^|\\n)\\s*-\\s*id:\\s*${id}\\s*$`, 'm').test(text)
45
+ if (present) continue
46
+ lines.push(`- id: ${id}`, ' disabled: true')
47
+ }
48
+ if (lines.length === 0) return { ok: true, entries: 0 }
49
+ const prefix = text.trim().length === 0 ? '' : (text.endsWith('\n') ? text : text + '\n')
50
+ const comment = text.includes('# fang: fork is production-only')
51
+ ? '' : '# fang: fork is production-only (plugin install / settings disabled)\n'
52
+ fs.writeFileSync(file, `${prefix}${comment}${lines.join('\n')}\n`, 'utf8')
53
+ return { ok: true, entries: lines.length / 2 }
54
+ }
@@ -13,18 +13,16 @@ export function safeJoin(root, ...parts) {
13
13
 
14
14
  export function assertInside(root, target, { followSymlink = true } = {}) {
15
15
  const base = path.resolve(root)
16
- let resolved = path.resolve(target)
16
+ const lexical = path.resolve(target)
17
+ let resolved = lexical
18
+ let boundary = base
17
19
  if (followSymlink) {
18
- try { resolved = fs.realpathSync.native(resolved) } catch {
19
- try { resolved = path.join(fs.realpathSync.native(path.dirname(resolved)), path.basename(resolved)) } catch { /* keep lexical */ }
20
- }
21
- try {
22
- const realBase = fs.realpathSync.native(base)
23
- if (resolved !== realBase && !resolved.startsWith(realBase + path.sep)) throw new Error('path-escape')
24
- } catch (error) {
25
- if (error?.message === 'path-escape') throw error
20
+ try { boundary = fs.realpathSync.native(base) } catch { /* keep lexical */ }
21
+ try { resolved = fs.realpathSync.native(lexical) } catch {
22
+ try { resolved = path.join(fs.realpathSync.native(path.dirname(lexical)), path.basename(lexical)) } catch { /* keep lexical */ }
26
23
  }
27
24
  }
28
- if (resolved !== base && !resolved.startsWith(base + path.sep)) throw new Error('path-escape')
29
- return resolved
25
+ const rel = path.relative(boundary, resolved)
26
+ if (rel === '..' || rel.startsWith('..' + path.sep) || path.isAbsolute(rel)) throw new Error('path-escape')
27
+ return lexical
30
28
  }
@@ -28,16 +28,26 @@ export function loadAuthToken(dataDir, envToken = process.env.DSH_FANG_AUTH_TOKE
28
28
  return token
29
29
  }
30
30
 
31
- /** Host 是否 loopback(支持 localhost / 127.0.0.1 / [::1] / ::1,可带端口)。 */
31
+ /**
32
+ * Host 是否 loopback(支持 localhost / 127.0.0.1 / [::1] / ::1,可带端口)。
33
+ *
34
+ * 严格解析:`[::1]evil.example`、`127.0.0.1:3080@evil.example` 这类带尾随垃圾的
35
+ * Host 必须判假——否则 DNS rebinding 防护会被一个字符串前缀绕过。
36
+ */
32
37
  export function isLoopbackHost(host) {
33
38
  const raw = String(host ?? '').trim().toLowerCase()
34
39
  if (raw.length === 0) return false
35
- const name = raw.startsWith('[')
36
- ? raw.slice(0, raw.indexOf(']') + 1)
37
- : raw.includes(':') && raw.split(':').length === 2 && /^\d+$/.test(raw.split(':')[1])
38
- ? raw.split(':')[0]
39
- : raw
40
- return name === 'localhost' || name === '127.0.0.1' || name === '[::1]' || name === '::1'
40
+ if (raw === '::1') return true
41
+ if (raw.startsWith('[')) {
42
+ const match = /^\[([0-9a-f:.]+)\](?::(\d{1,5}))?$/.exec(raw)
43
+ if (!match) return false
44
+ if (match[2] !== undefined && Number(match[2]) > 65535) return false
45
+ return match[1] === '::1'
46
+ }
47
+ const match = /^([a-z0-9.-]+)(?::(\d{1,5}))?$/.exec(raw)
48
+ if (!match) return false
49
+ if (match[2] !== undefined && Number(match[2]) > 65535) return false
50
+ return match[1] === 'localhost' || match[1] === '127.0.0.1'
41
51
  }
42
52
 
43
53
  /** Origin 是否允许(同源 loopback / dsh-app 壳 / 无 Origin)。 */
@@ -103,3 +113,50 @@ export function checkRequestAuth(req, options) {
103
113
  }
104
114
  return { ok: true }
105
115
  }
116
+
117
+ /** Stable error envelope for every auth/host/origin rejection (additive `code`). */
118
+ export function authErrorBody(decision) {
119
+ const code = String(decision?.code ?? 'unauthorized')
120
+ return { ok: false, error: code, code }
121
+ }
122
+
123
+ /**
124
+ * Install-level guard shared by every plugin that owns `/fang/api/*` routes.
125
+ *
126
+ * Resolves the token exactly once at startup, with the same precedence as the
127
+ * orchestrator: explicit config > env > `<dataDir>/fang-auth.json` (0600).
128
+ * `enabled: false` is the explicit test/debug escape hatch and still enforces
129
+ * Host/Origin/CSRF — it only skips the token comparison.
130
+ *
131
+ * @param {{dataDir?:string, token?:string, envToken?:string, enabled?:boolean}} [options]
132
+ * @returns {{token:string, enabled:boolean, check:(req:any, routeOptions?:{public?:boolean})=>
133
+ * ({ok:true}|{ok:false,status:number,code:string})}}
134
+ */
135
+ export function createHttpGuard(options = {}) {
136
+ const enabled = options.enabled !== false
137
+ const dataDir = String(options.dataDir ?? '').trim()
138
+ const explicit = String(options.token ?? '').trim()
139
+ const envToken = options.envToken === undefined ? process.env.DSH_FANG_AUTH_TOKEN : options.envToken
140
+ let token = ''
141
+ if (enabled) {
142
+ if (dataDir) {
143
+ token = loadAuthToken(dataDir, explicit || envToken)
144
+ } else {
145
+ const candidate = explicit || String(envToken ?? '').trim()
146
+ if (candidate.length < MIN_TOKEN_LENGTH) {
147
+ throw new Error('http-auth: dataDir or a >=32-char auth token is required when auth is enabled')
148
+ }
149
+ token = candidate
150
+ }
151
+ }
152
+ return {
153
+ token,
154
+ enabled: token.length > 0,
155
+ check(req, routeOptions = {}) {
156
+ return checkRequestAuth(req, {
157
+ token,
158
+ publicRoute: token.length === 0 || routeOptions.public === true,
159
+ })
160
+ },
161
+ }
162
+ }
@@ -57,6 +57,17 @@ export const PREFERENCES_SCHEMA = Object.freeze({
57
57
  description: '开启后任何原身冲突都会阻止派生,而不是自动跳过',
58
58
  defaultValue: false,
59
59
  }),
60
+ syncIntervalHours: Object.freeze({
61
+ kind: 'enum', label: '母体自动同步间隔',
62
+ description: '每隔多久从本机母体 profile 克隆到镜像(off = 关闭;同步前自动备份)',
63
+ defaultValue: 'off',
64
+ options: Object.freeze([
65
+ { value: 'off', label: '关闭' },
66
+ { value: '6', label: '6 小时' },
67
+ { value: '12', label: '12 小时' },
68
+ { value: '24', label: '24 小时' },
69
+ ]),
70
+ }),
60
71
  })
61
72
 
62
73
  export const PREFERENCES_KEYS = Object.freeze(Object.keys(PREFERENCES_SCHEMA))
@@ -3,7 +3,7 @@
3
3
  // 服务端返回后,UI 只做投影,不再自行推断禁用原因;data-btn-id 与 id 一一对应。
4
4
 
5
5
  export const TASK_ACTION_IDS = Object.freeze(['open', 'rename', 'archive', 'copy', 'download', 'delete'])
6
- export const ESSENCE_ACTION_IDS = Object.freeze(['derive', 'configure', 'rename', 'archive', 'copy', 'download', 'delete'])
6
+ export const ESSENCE_ACTION_IDS = Object.freeze(['derive', 'configure', 'rename', 'archive', 'restore', 'copy', 'download', 'delete'])
7
7
 
8
8
  const item = (id, enabled, code, reason, confirm = 'none') => ({
9
9
  id,
@@ -29,22 +29,25 @@ export function buildTaskActions({ running = false, archived = false } = {}) {
29
29
  return { actions, blocks }
30
30
  }
31
31
 
32
- /** 元主动作矩阵:官方 locked 只允许派生/复制/下载;归档后禁止派生/配置。 */
32
+ /** 元主动作矩阵:冻结(archived)后只能删除;官方 locked 只允许派生/复制/下载。 */
33
33
  export function buildEssenceActions({ locked = false, archived = false } = {}) {
34
- const mutable = locked !== true && archived !== true
34
+ const frozen = archived === true
35
+ const mutable = locked !== true && frozen !== true
35
36
  const actions = {
36
- derive: item('derive', archived !== true, 'archived', '已归档的元主不可派生'),
37
- configure: item('configure', mutable, locked ? 'locked' : 'archived', locked ? '官方推荐元主不支持修改设置' : '已归档的元主不可配置'),
38
- rename: item('rename', locked !== true, 'locked', '官方推荐元主不可重命名'),
39
- archive: item('archive', locked !== true && archived !== true, locked ? 'locked' : 'archived', locked ? '官方推荐元主不可归档' : '已归档', 'once'),
40
- copy: item('copy', true, 'ok', ''),
41
- download: item('download', true, 'ok', ''),
42
- delete: item('delete', locked !== true, 'locked', '官方推荐元主不可删除', 'strong'),
37
+ derive: item('derive', frozen !== true, 'archived', '已归档(冻结)的元主不可派生'),
38
+ configure: item('configure', mutable, locked ? 'locked' : 'archived', locked ? '官方推荐元主不支持修改设置' : '已冻结的元主不可配置'),
39
+ rename: item('rename', mutable, locked ? 'locked' : 'archived', locked ? '官方推荐元主不可重命名' : '已冻结的元主不可重命名'),
40
+ archive: item('archive', mutable, locked ? 'locked' : 'archived', locked ? '官方推荐元主不可归档' : '已归档(冻结)', 'once'),
41
+ // 冻结态唯一可做的两件事:还原(解冻)或删除。
42
+ restore: item('restore', frozen === true && locked !== true, locked ? 'locked' : 'not-archived', locked ? '官方推荐元主不可操作' : '未冻结,无需还原(备份回滚请用「还原备份」)'),
43
+ copy: item('copy', frozen !== true, 'archived', '已冻结的元主不可复制'),
44
+ download: item('download', frozen !== true, 'archived', '已冻结的元主不可下载'),
45
+ delete: item('delete', frozen === true && locked !== true, locked ? 'locked' : 'archived-required', locked ? '官方推荐元主不可删除' : '需先归档(冻结)才能删除', 'strong'),
43
46
  }
44
47
  const blocks = locked === true
45
48
  ? [{ code: 'locked', reason: '官方推荐元主不支持修改设置' }]
46
- : archived === true
47
- ? [{ code: 'archived', reason: '元主已归档' }]
49
+ : frozen
50
+ ? [{ code: 'archived', reason: '元主已归档(冻结):只能删除' }]
48
51
  : []
49
52
  return { actions, blocks }
50
53
  }
@@ -1,12 +1,12 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // v3.0.9 read-only upgrade status. Pure function: no IO, no upgrade/backup side effects.
3
- export function buildUpgradeStatus({ version = '', mirror = null, essences = [] } = {}) {
4
- const current = mirror?.current ?? null
5
- const latest = mirror?.latest ?? null
3
+ export function buildUpgradeStatus({ version = '', mirror = null, essences = [], compat = null, tasks = null } = {}) {
4
+ const current = mirror?.current ?? mirror?.currentVersion ?? null
5
+ const latest = mirror?.latest ?? mirror?.officialLatest ?? null
6
6
  const mother = {
7
7
  current,
8
8
  latest,
9
- updateAvailable: Boolean(current && latest && current !== latest),
9
+ updateAvailable: Boolean(current && latest && current !== latest) || mirror?.updateAvailable === true,
10
10
  lastBackupAt: Number(mirror?.lastBackupAt) || 0,
11
11
  backupIntervalHours: [6, 12, 24].includes(Number(mirror?.backupIntervalHours)) ? Number(mirror.backupIntervalHours) : 24,
12
12
  }
@@ -16,5 +16,28 @@ export function buildUpgradeStatus({ version = '', mirror = null, essences = []
16
16
  status: String(e?.status ?? 'unknown'),
17
17
  stale: Boolean(e?.stale),
18
18
  })) : []
19
- return { ok: true, version: String(version || ''), mother, essences: list, operation: null }
19
+ const staleCount = list.filter((e) => e.stale).length
20
+ const conflicted = list.filter((e) => e.status === 'conflicted').length
21
+ const failedTasks = Number(tasks?.failed) || 0
22
+
23
+ // 系统状态灯:绿=全绿;黄=有更新/待同步;红=有失败。
24
+ const level = { green: 0, yellow: 1, red: 2 }
25
+ let tone = 'green'
26
+ const reasons = []
27
+ const bump = (next, code, text) => {
28
+ if (level[next] > level[tone]) tone = next
29
+ reasons.push({ code, text })
30
+ }
31
+ if (mother.updateAvailable) bump('yellow', 'mother-update', '母体有新版本可更新')
32
+ if (staleCount > 0) bump('yellow', 'essence-stale', `${staleCount} 个元主待同步到新母体`)
33
+ if (compat && compat.ok === false) bump('red', 'compat-failed', '兼容门禁未通过,子插件可能被关闭')
34
+ if (conflicted > 0) bump('red', 'essence-conflicted', `${conflicted} 个元主存在致命冲突`)
35
+ if (failedTasks > 0) bump('red', 'fork-failed', `${failedTasks} 个分身处于失败状态`)
36
+
37
+ return {
38
+ ok: true, version: String(version || ''), mother,
39
+ essences: list, operation: null,
40
+ staleCount, conflicted, failedTasks,
41
+ light: { tone, reasons },
42
+ }
20
43
  }