@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.
@@ -57,6 +57,7 @@ import {
57
57
  sampleResources,
58
58
  totalResources,
59
59
  } from '../kernel/index.mjs'
60
+ import { authErrorBody, checkRequestAuth } from '../lib/http-auth.mjs'
60
61
  import {
61
62
  CommandCache,
62
63
  EventLog,
@@ -825,6 +826,29 @@ export function apply(ctx, config) {
825
826
  flushed: Array.isArray(flushed?.flushed) ? flushed.flushed : [],
826
827
  }
827
828
  }],
829
+
830
+ // 方案 A:物理分支。分身会话只存在分身自己的 DSH 进程里,母体侧够不到,
831
+ // 所以在分身宿主内调用 sessions.fork,把子会话挂回同一分身。
832
+ [ADAPTER_OP.FORK_SESSION, async (payload) => {
833
+ const sessions = safeGet('sessions')
834
+ if (!sessions || typeof sessions.fork !== 'function') {
835
+ return { ok: false, code: 'sessions-service-unavailable', error: 'sessions.fork unavailable in this instance' }
836
+ }
837
+ const sourceSessionId = String(payload?.sessionId ?? '').trim()
838
+ if (!sourceSessionId) return { ok: false, code: 'bad-session-id' }
839
+ const boundary = payload?.boundary
840
+ const childSessionId = String(payload?.childSessionId ?? '').trim()
841
+ try {
842
+ const child = childSessionId
843
+ ? await sessions.fork(sourceSessionId, boundary, childSessionId)
844
+ : await sessions.fork(sourceSessionId, boundary)
845
+ const id = typeof child === 'string' ? child : (child?.id ?? child?.sessionId ?? childSessionId ?? null)
846
+ appendAudit('fork-session', { sourceSessionId, childSessionId: id, boundary: boundary ?? null })
847
+ return { ok: true, sourceSessionId, childSessionId: id }
848
+ } catch (error) {
849
+ return { ok: false, code: 'fork-failed', error: String(error?.message ?? error) }
850
+ }
851
+ }],
828
852
  ])
829
853
 
830
854
  /**
@@ -1153,14 +1177,33 @@ export function apply(ctx, config) {
1153
1177
  webServer.register({
1154
1178
  kind: 'exact',
1155
1179
  path: routePath,
1180
+ method,
1156
1181
  handler: async (req, res) => {
1157
1182
  const actual = String(req?.method ?? 'GET').toUpperCase()
1158
- if (actual !== method) {
1159
- return json(res, 405, { ok: false, code: 'method-not-allowed', error: 'method-not-allowed', path: routePath })
1183
+ // Same perimeter as /fang/api/*: loopback Host, Origin/Sec-Fetch-Site,
1184
+ // adapter Bearer token, JSON-only writes. Auth before method (401 not 405).
1185
+ const decision = checkRequestAuth(req, {
1186
+ token: adapterToken,
1187
+ // v2 compatibility (explicit allowLegacyNoToken) is the only case where
1188
+ // the token comparison is skipped; Host/Origin/CSRF still apply.
1189
+ publicRoute: adapterToken.length === 0 && legacyAllowed,
1190
+ })
1191
+ if (!decision.ok) {
1192
+ return json(res, decision.status, { ...authErrorBody(decision), path: routePath })
1193
+ }
1194
+ if (!['GET', 'HEAD', 'OPTIONS'].includes(actual)) {
1195
+ const contentType = String(req?.headers?.['content-type'] ?? '').toLowerCase()
1196
+ if (contentType && !contentType.includes('application/json')) {
1197
+ return json(res, 415, { ok: false, code: 'content-type-required', error: 'content-type-required', path: routePath })
1198
+ }
1160
1199
  }
1161
1200
  if (!authorized(req)) {
1162
1201
  return json(res, 401, { ok: false, code: 'unauthorized', error: 'unauthorized', path: routePath })
1163
1202
  }
1203
+ if (actual !== method) {
1204
+ try { res.setHeader?.('allow', method) } catch { /* fake res */ }
1205
+ return json(res, 405, { ok: false, code: 'method-not-allowed', error: 'method-not-allowed', path: routePath })
1206
+ }
1164
1207
  try {
1165
1208
  return await handler(req, res)
1166
1209
  } catch (e) {
@@ -57,6 +57,7 @@ import {
57
57
  z,
58
58
  } from '../kernel/index.mjs'
59
59
  import { computeBackoff, planRestart, reconcileOrphans, writeForkMeta, probeHttpAlive, SUPERVISION_DEFAULTS } from '../lib/fork-supervisor.mjs'
60
+ import { applyForkConfigLock, setProfileConfigReadonly } from '../lib/fork-config-lock.mjs'
60
61
 
61
62
  export const name = 'fang-forker'
62
63
  export const inject = []
@@ -745,11 +746,13 @@ export function apply(ctx, config) {
745
746
  ensureDir(profileDir)
746
747
 
747
748
  const warnings = []
748
- const nodeModulesSource = path.join(sourceTemplateDir, 'node_modules')
749
+ // 显式 profileTemplate(例如原身 merged/profile)优先:此时不再用 clean template。
750
+ const useCleanTemplate = typeof opts.cleanTemplate === 'boolean' ? opts.cleanTemplate : cleanTemplate
751
+ const nodeModulesSource = String(opts.nodeModulesSource ?? '').trim() || path.join(sourceTemplateDir, 'node_modules')
749
752
  let template = sourceTemplateDir
750
753
  let cloned = []
751
754
 
752
- if (cleanTemplate) {
755
+ if (useCleanTemplate) {
753
756
  // Forker-owned clean template: never written into the mother profile directory.
754
757
  const cleanDir = path.join(homeDir, 'templates', forkProfileTag)
755
758
  const ensured = ensureTemplate({
@@ -770,6 +773,11 @@ export function apply(ctx, config) {
770
773
  } else {
771
774
  cloned = cloneProfileConfig(sourceTemplateDir, profileDir)
772
775
  }
776
+ // 生产盘锁定:关闭插件安装 / 设置 UI(派生时写入 profile patch)。
777
+ const configLock = applyForkConfigLock(profileDir)
778
+ if (configLock.ok !== true) warnings.push('fork-config-lock-failed')
779
+ // 配置文件只读:防误写(DSH_FANG_FORK_PROFILE_RO=0 可关)。
780
+ const profileReadonly = setProfileConfigReadonly(profileDir, true)
773
781
 
774
782
  // node_modules junction in the fork profile (always to the mother's module tree).
775
783
  let nodeModules = null
@@ -810,7 +818,7 @@ export function apply(ctx, config) {
810
818
  records.set(forkId, rec)
811
819
  persist()
812
820
  audit(AUDIT.FORK_CREATED, { forkId, homeDir, profile, taskTitle: rec.taskTitle, cloned, warnings, template })
813
- return { ok: true, forkId, homeDir, profileDir, bufferDir, profile, template, cloned, node_modules: nodeModules, warnings }
821
+ return { ok: true, forkId, homeDir, profileDir, bufferDir, profile, template, cloned, node_modules: nodeModules, warnings, configLock, profileReadonly }
814
822
  }
815
823
 
816
824
  // ───────────────────────────── spawn ─────────────────────────────
@@ -883,6 +891,27 @@ export function apply(ctx, config) {
883
891
  log: collector,
884
892
  })
885
893
  records.set(forkId, rec)
894
+ // v3.0.9 生产盘:每次打开/重启都从来源模板重放配置(原身 merged 或 clean template),
895
+ // 分身自己的改动不保存;sessions/storages/buffer 与 node_modules junction 保持不动。
896
+ const templateDirForRec = String(rec.template ?? '').trim()
897
+ if (templateDirForRec && exists(templateDirForRec) && exists(rec.profileDir)) {
898
+ try {
899
+ // 重放前先解锁,否则复制会因只读失败。
900
+ setProfileConfigReadonly(rec.profileDir, false)
901
+ cloneProfileConfig(templateDirForRec, rec.profileDir)
902
+ const settingsSrc = path.join(templateDirForRec, 'settings')
903
+ if (exists(settingsSrc)) {
904
+ const settingsDst = path.join(rec.profileDir, 'settings')
905
+ if (exists(settingsDst)) removeTree(settingsDst)
906
+ copyTree(settingsSrc, settingsDst)
907
+ }
908
+ rec.configSync = { at: nowMs(), from: templateDirForRec }
909
+ } catch (e) {
910
+ rec.configSync = { at: nowMs(), ok: false, error: msgOf(e) }
911
+ }
912
+ }
913
+ try { rec.configLock = applyForkConfigLock(rec.profileDir) } catch { rec.configLock = { ok: false } }
914
+ try { rec.profileReadonly = setProfileConfigReadonly(rec.profileDir, true) } catch { rec.profileReadonly = { ok: false } }
886
915
  writeForkMetaOf(rec)
887
916
  // 广播新 token:首次派生 = 生成,重启 = 刷新;订阅者拿到的是「当前 token」,
888
917
  // 不是「进程就绪」信号(进程就绪以 fang/fork-started 为准)。