@twinsearth/dsh-fang 3.0.8 → 3.0.10

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.
@@ -2,7 +2,8 @@
2
2
  // Copyright (c) 2026 dsh-Fang contributors — see LICENSE-CORE.
3
3
  // fang-session-bridge — mother-side façade over a running PC host's loopback bridge.
4
4
  // Transport only: it never copies session files and never writes to the PC host.
5
- import { z, roleGate, SERVICE, FANG_VERSION } from '../kernel/index.mjs'
5
+ import { z, roleGate, resolveFangLayout, SERVICE, FANG_VERSION } from '../kernel/index.mjs'
6
+ import { createHttpGuard } from '../lib/http-auth.mjs'
6
7
  import { createBridgeClient, readBridgeDescriptor } from '../lib/bridge-client.mjs'
7
8
 
8
9
  export const name = 'fang-session-bridge'
@@ -16,6 +17,10 @@ export const Config = z.object({
16
17
  timeoutMs: z.number().min(1000).max(120000).default(15000)
17
18
  .description('每次桥接请求的超时(毫秒)'),
18
19
  routes: z.object({ enabled: z.boolean().default(true) }).default({}),
20
+ authToken: z.string().default('')
21
+ .description('安装级鉴权 token;留空 = env DSH_FANG_AUTH_TOKEN 或 <dataDir>/fang-auth.json(0600,自动生成)'),
22
+ authEnabled: z.boolean().default(true)
23
+ .description('是否要求 /fang/api/bridge/* 携带安装级鉴权 token(默认开启;仅测试/本地调试可关)'),
19
24
  })
20
25
 
21
26
  export function apply(ctx, config) {
@@ -25,6 +30,11 @@ export function apply(ctx, config) {
25
30
  const cfg = { ...Config({}), ...(config ?? {}) }
26
31
  const client = createBridgeClient({ dshHome: cfg.dshHome, timeoutMs: cfg.timeoutMs })
27
32
  const prefix = String(cfg.prefix ?? '/fang').replace(/\/+$/, '') || '/fang'
33
+ const authGuard = createHttpGuard({
34
+ dataDir: resolveFangLayout().dataDir,
35
+ token: cfg.authToken,
36
+ enabled: cfg.authEnabled !== false,
37
+ })
28
38
 
29
39
  const audit = (kind, data) => {
30
40
  try {
@@ -89,19 +99,57 @@ export function apply(ctx, config) {
89
99
  webServer.register({
90
100
  kind: 'exact',
91
101
  path: routePath,
102
+ method,
92
103
  handler: async (req, res) => {
93
104
  try {
94
- if (String(req?.method ?? 'GET').toUpperCase() !== method) return json(res, 405, { ok: false, error: 'method-not-allowed' })
105
+ const decision = authGuard.check(req)
106
+ if (!decision.ok) return json(res, decision.status, { ok: false, error: decision.code, code: decision.code })
107
+ if (String(req?.method ?? 'GET').toUpperCase() !== method) {
108
+ try { res.setHeader?.('allow', method) } catch { /* fake res */ }
109
+ return json(res, 405, { ok: false, error: 'method-not-allowed', code: 'method-not-allowed' })
110
+ }
95
111
  return await handler(req, res)
96
112
  } catch (e) {
97
- return json(res, 500, { ok: false, error: String(e?.message ?? e) })
113
+ return json(res, 500, { ok: false, error: String(e?.message ?? e), code: 'handler-threw' })
114
+ }
115
+ },
116
+ })
117
+ }
118
+
119
+ // DSH exact routes are keyed by path only: GET+POST share one registration.
120
+ const routeMethods = (routePath, handlers) => {
121
+ webServer.register({
122
+ kind: 'exact',
123
+ path: routePath,
124
+ method: Object.keys(handlers).join(','),
125
+ handler: async (req, res) => {
126
+ try {
127
+ const decision = authGuard.check(req)
128
+ if (!decision.ok) return json(res, decision.status, { ok: false, error: decision.code, code: decision.code })
129
+ const allow = Object.keys(handlers)
130
+ const fn = handlers[String(req?.method ?? 'GET').toUpperCase()]
131
+ if (typeof fn !== 'function') {
132
+ try { res.setHeader?.('allow', allow.join(', ')) } catch { /* fake res */ }
133
+ return json(res, 405, { ok: false, error: 'method-not-allowed', code: 'method-not-allowed' })
134
+ }
135
+ return await fn(req, res)
136
+ } catch (e) {
137
+ return json(res, 500, { ok: false, error: String(e?.message ?? e), code: 'handler-threw' })
98
138
  }
99
139
  },
100
140
  })
101
141
  }
102
142
 
103
143
  route('GET', `${prefix}/api/bridge/status`, (req, res) => json(res, 200, service.descriptor()))
104
- route('GET', `${prefix}/api/bridge/sessions`, async (req, res) => json(res, 200, await service.listSessions()))
144
+ routeMethods(`${prefix}/api/bridge/sessions`, {
145
+ GET: async (req, res) => json(res, 200, await service.listSessions()),
146
+ POST: async (req, res) => {
147
+ const body = await readBody(req)
148
+ if (body.__parseError) return json(res, 400, { ok: false, error: 'bad-json' })
149
+ const out = await service.create({ cwd: body.cwd, title: body.title })
150
+ json(res, out.ok ? 201 : 400, out)
151
+ },
152
+ })
105
153
  route('GET', `${prefix}/api/bridge/sessions/events`, async (req, res) => {
106
154
  const q = queryOf(req)
107
155
  const out = await service.events(q.get('sessionId') ?? '', { limit: q.get('limit') })
@@ -113,11 +161,6 @@ export function apply(ctx, config) {
113
161
  const out = await service.send(body.sessionId, body.text)
114
162
  json(res, out.ok ? 200 : 400, out)
115
163
  })
116
- route('POST', `${prefix}/api/bridge/sessions`, async (req, res) => {
117
- const body = await readBody(req)
118
- if (body.__parseError) return json(res, 400, { ok: false, error: 'bad-json' })
119
- const out = await service.create({ cwd: body.cwd, title: body.title })
120
- json(res, out.ok ? 201 : 400, out)
121
- })
164
+
122
165
  })
123
166
  }
@@ -29,9 +29,11 @@ import {
29
29
  z,
30
30
  roleGate,
31
31
  resolveDshHome,
32
+ resolveFangLayout,
32
33
  SERVICE,
33
34
  FANG_VERSION,
34
35
  } from '../kernel/index.mjs'
36
+ import { createHttpGuard } from '../lib/http-auth.mjs'
35
37
  import {
36
38
  SESSION_ID_RE,
37
39
  SESSION_LOG_FILE,
@@ -86,6 +88,10 @@ export const Config = z.object({
86
88
  .description('digest 预览的最大字符数(超过 digest 32KiB 上限会 halt 而不是截断)'),
87
89
  allowArchived: z.boolean().default(true)
88
90
  .description('是否允许在请求 includeArchived 时列出已归档会话'),
91
+ authToken: z.string().default('')
92
+ .description('安装级鉴权 token;留空 = env DSH_FANG_AUTH_TOKEN 或 <dataDir>/fang-auth.json(0600,自动生成)'),
93
+ authEnabled: z.boolean().default(true)
94
+ .description('是否要求 /fang/api/sessions* 携带安装级鉴权 token(默认开启;仅测试/本地调试可关)'),
89
95
  })
90
96
 
91
97
  function clampInt(value, min, max, fallback) {
@@ -125,6 +131,13 @@ export function apply(ctx, config) {
125
131
  const cfg = { ...DEFAULTS, ...configDefaults, ...(config ?? {}) }
126
132
 
127
133
  const dshHome = resolveDshHome()
134
+ // v3.0.8/B1: these three routes read real session content; they must use the
135
+ // same install-level Host/Origin/token gate as /fang/api/status.
136
+ const authGuard = createHttpGuard({
137
+ dataDir: resolveFangLayout({ dataRoot: cfg.dataRoot }).dataDir,
138
+ token: cfg.authToken,
139
+ enabled: cfg.authEnabled !== false,
140
+ })
128
141
  const sessionsRoot = cfg.sessionsRoot ? path.resolve(String(cfg.sessionsRoot)) : path.join(dshHome, 'sessions')
129
142
  const storagesRoot = cfg.storagesRoot ? path.resolve(String(cfg.storagesRoot)) : path.join(dshHome, 'storages')
130
143
  const workspaceIndexFile = path.join(storagesRoot, WORKSPACE_INDEX_FILE)
@@ -671,9 +684,16 @@ export function apply(ctx, config) {
671
684
  webServer.register({
672
685
  kind: 'exact',
673
686
  path: routePath,
687
+ method,
674
688
  handler: async (req, res) => {
689
+ // Auth before method: a token-less POST must be 401, not 405 (fail-closed).
690
+ const decision = authGuard.check(req)
691
+ if (!decision.ok) {
692
+ return json(res, decision.status, { ok: false, error: decision.code, code: decision.code })
693
+ }
675
694
  const actual = String(req?.method ?? 'GET').toUpperCase()
676
695
  if (actual !== method) {
696
+ try { res.setHeader?.('allow', method) } catch { /* fake res */ }
677
697
  return json(res, 405, { ok: false, code: 'method-not-allowed', error: 'method-not-allowed', path: routePath })
678
698
  }
679
699
  try {
@@ -6,7 +6,8 @@
6
6
  // cross-machine + realtime -> deny (bridge is loopback-only, sync not realtime)
7
7
  // same machine + host + bridge -> bridge
8
8
  // otherwise -> sync
9
- import { z, roleGate, SERVICE, FANG_VERSION } from '../kernel/index.mjs'
9
+ import { z, roleGate, resolveFangLayout, SERVICE, FANG_VERSION } from '../kernel/index.mjs'
10
+ import { createHttpGuard } from '../lib/http-auth.mjs'
10
11
  import { readBridgeDescriptor } from '../lib/bridge-client.mjs'
11
12
 
12
13
  export const name = 'fang-session-router'
@@ -23,6 +24,10 @@ export const Config = z.object({
23
24
  .description('PC 宿主 DSH_HOME(查找 desktop-bridge.json);留空 = 本机 $DSH_HOME'),
24
25
  prefix: z.string().default('/fang'),
25
26
  routes: z.object({ enabled: z.boolean().default(true) }).default({}),
27
+ authToken: z.string().default('')
28
+ .description('安装级鉴权 token;留空 = env DSH_FANG_AUTH_TOKEN 或 <dataDir>/fang-auth.json(0600,自动生成)'),
29
+ authEnabled: z.boolean().default(true)
30
+ .description('是否要求 /fang/api/route 携带安装级鉴权 token(默认开启;仅测试/本地调试可关)'),
26
31
  })
27
32
 
28
33
  /** Pure decision function; `deny` means the request cannot be satisfied honestly. */
@@ -43,6 +48,11 @@ export function apply(ctx, config) {
43
48
  if (!gate.active) return
44
49
  const cfg = { ...Config({}), ...(config ?? {}) }
45
50
  const prefix = String(cfg.prefix ?? '/fang').replace(/\/+$/, '') || '/fang'
51
+ const authGuard = createHttpGuard({
52
+ dataDir: resolveFangLayout().dataDir,
53
+ token: cfg.authToken,
54
+ enabled: cfg.authEnabled !== false,
55
+ })
46
56
 
47
57
  const probe = (context = {}) => {
48
58
  const desc = readBridgeDescriptor({ dshHome: cfg.dshHome })
@@ -86,10 +96,19 @@ export function apply(ctx, config) {
86
96
  webServer.register({
87
97
  kind: 'exact',
88
98
  path: `${prefix}/api/route`,
99
+ method: 'GET',
89
100
  handler: async (req, res) => {
101
+ const decision = authGuard.check(req)
102
+ if (!decision.ok) {
103
+ res.statusCode = decision.status
104
+ res.setHeader?.('content-type', 'application/json; charset=utf-8')
105
+ res.end(JSON.stringify({ ok: false, error: decision.code, code: decision.code }))
106
+ return
107
+ }
90
108
  if (String(req?.method ?? 'GET').toUpperCase() !== 'GET') {
91
109
  res.statusCode = 405
92
- res.end(JSON.stringify({ ok: false, error: 'method-not-allowed' }))
110
+ res.setHeader?.('allow', 'GET')
111
+ res.end(JSON.stringify({ ok: false, error: 'method-not-allowed', code: 'method-not-allowed' }))
93
112
  return
94
113
  }
95
114
  const q = new URL(String(req?.url ?? '/'), 'http://fang.local').searchParams
@@ -8,6 +8,7 @@ import {
8
8
  } from '../kernel/index.mjs'
9
9
  import { exportSessions, importSessions } from '../lib/session-bundle.mjs'
10
10
  import { encodeWorkspaceKey } from '../lib/session-format.mjs'
11
+ import { createHttpGuard } from '../lib/http-auth.mjs'
11
12
 
12
13
  export const name = 'fang-session-sync'
13
14
  export const inject = []
@@ -23,6 +24,10 @@ export const Config = z.object({
23
24
  maxBundleBytes: z.number().min(0).max(4 * 1024 * 1024 * 1024).default(512 * 1024 * 1024)
24
25
  .description('单个 bundle 的大小上限(字节);超过则拒绝导出'),
25
26
  routes: z.object({ enabled: z.boolean().default(true) }).default({}),
27
+ authToken: z.string().default('')
28
+ .description('安装级鉴权 token;留空 = env DSH_FANG_AUTH_TOKEN 或 <dataDir>/fang-auth.json(0600,自动生成)'),
29
+ authEnabled: z.boolean().default(true)
30
+ .description('是否要求 /fang/api/sync/* 携带安装级鉴权 token(默认开启;仅测试/本地调试可关)'),
26
31
  })
27
32
 
28
33
  export function apply(ctx, config) {
@@ -34,6 +39,11 @@ export function apply(ctx, config) {
34
39
  const storagesRoot = cfg.storagesRoot ? path.resolve(cfg.storagesRoot) : path.join(resolveDshHome(), 'storages')
35
40
  const bundleRoot = cfg.bundleRoot ? path.resolve(cfg.bundleRoot) : path.join(layout.dataDir, 'sync-bundles')
36
41
  const prefix = String(cfg.prefix ?? '/fang').replace(/\/+$/, '') || '/fang'
42
+ const authGuard = createHttpGuard({
43
+ dataDir: layout.dataDir,
44
+ token: cfg.authToken,
45
+ enabled: cfg.authEnabled !== false,
46
+ })
37
47
 
38
48
  const workspacesOf = (homeDir) => {
39
49
  const file = path.join(homeDir, 'storages', 'workspace.json')
@@ -128,11 +138,17 @@ export function apply(ctx, config) {
128
138
  webServer.register({
129
139
  kind: 'exact',
130
140
  path: routePath,
141
+ method,
131
142
  handler: async (req, res) => {
132
143
  try {
133
- if (String(req?.method ?? 'GET').toUpperCase() !== method) return json(res, 405, { ok: false, error: 'method-not-allowed' })
144
+ const decision = authGuard.check(req)
145
+ if (!decision.ok) return json(res, decision.status, { ok: false, error: decision.code, code: decision.code })
146
+ if (String(req?.method ?? 'GET').toUpperCase() !== method) {
147
+ try { res.setHeader?.('allow', method) } catch { /* fake res */ }
148
+ return json(res, 405, { ok: false, error: 'method-not-allowed', code: 'method-not-allowed' })
149
+ }
134
150
  return await handler(req, res)
135
- } catch (e) { return json(res, 500, { ok: false, error: String(e?.message ?? e) }) }
151
+ } catch (e) { return json(res, 500, { ok: false, error: String(e?.message ?? e), code: 'handler-threw' }) }
136
152
  },
137
153
  })
138
154
  }