dsh-opencode-status 0.1.5 → 0.3.0

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/src/index.js CHANGED
@@ -7,13 +7,18 @@
7
7
  * PUT /api/opencode-status/config 创建/更新配置
8
8
  * POST /api/opencode-status/sync 强制同步最新配额
9
9
  *
10
+ * 配置走 DSH 0.2.x 的 Config schema:baseUrl/keyRef 声明为 volatile 字段,宿主据此
11
+ * 生成配置表单,并以 { get() } live ref 的形式传入 apply。baseUrl 的持久化通过可选的
12
+ * settings 服务完成(update(profile 条目 id, patch)),密钥始终存放在 credentials。
13
+ *
10
14
  * 数据源:https://opencode.ai/zen/go/v1/usage
11
15
  */
12
16
  import z from '@deepseek-ai/schemastery'
13
17
 
14
18
  export const name = 'opencode-status'
15
- export const inject = ['settings', 'credentials', 'webServer']
19
+ export const inject = ['credentials', 'webServer']
16
20
 
21
+ // profile 条目 id(见 cordis.patch.yml),也是 settings 表单的命名空间。
17
22
  const NS = /** @type {any} */ ('opencode-status')
18
23
  const DEFAULT_KEY_REF = /** @type {any} */ ('OPENCODE_GO_API_KEY')
19
24
  const DEFAULT_BASE_URL = 'https://opencode.ai/zen/go'
@@ -21,11 +26,13 @@ const DEFAULT_CACHE_TTL_MS = 30_000
21
26
  const REQUEST_TIMEOUT_MS = 10_000
22
27
 
23
28
  const envBaseUrl = normalizeBase(process.env.OPENCODE_BASE_URL)
29
+ const defaultBaseUrl = isAbsoluteHttpUrl(envBaseUrl) ? envBaseUrl : DEFAULT_BASE_URL
24
30
 
25
- const schema = z.object({
31
+ // DSH 0.2.x 用插件导出的 Config 取代已移除的 settings 配置注册接口。
32
+ export const Config = z.object({
26
33
  // 环境变量只作为未持久化配置时的默认值;非法值不覆盖官方端点。
27
- baseUrl: z.string().default(isAbsoluteHttpUrl(envBaseUrl) ? envBaseUrl : DEFAULT_BASE_URL),
28
- keyRef: z.string().default(DEFAULT_KEY_REF),
34
+ baseUrl: z.string().default(defaultBaseUrl).volatile(),
35
+ keyRef: z.string().default(DEFAULT_KEY_REF).volatile(),
29
36
  })
30
37
 
31
38
  function normalizeBase(input) {
@@ -41,6 +48,91 @@ function isAbsoluteHttpUrl(input) {
41
48
  }
42
49
  }
43
50
 
51
+ /** PUT/POST 只接受 JSON 请求体,允许带 charset 参数。 */
52
+ function isJsonContentType(value) {
53
+ return typeof value === 'string' && /^application\/json\s*(?:;|$)/i.test(value.trim())
54
+ }
55
+
56
+ /** 读取请求头;Node 的 headers 是名字归一化后的普通对象。 */
57
+ function headerValue(headers, name) {
58
+ const value = headers?.[name]
59
+ return typeof value === 'string' ? value : Array.isArray(value) ? value[0] : undefined
60
+ }
61
+
62
+ /** 与 DSH client-connection 的 isLoopbackHostname 对齐:localhost、[::1] 与 127/8。 */
63
+ function isLoopbackHostname(hostname) {
64
+ if (hostname === 'localhost' || hostname === '[::1]') return true
65
+ const parts = hostname.split('.')
66
+ return parts.length === 4 && parts[0] === '127' && parts.every((part) => /^\d{1,3}$/.test(part) && Number(part) <= 255)
67
+ }
68
+
69
+ /** 按指定 scheme 解析裸 authority(host 或 host:port);非法值返回 undefined。 */
70
+ function parseAuthority(authority, scheme = 'http:') {
71
+ try {
72
+ return new URL(`${scheme}//${authority}`)
73
+ } catch {
74
+ return undefined
75
+ }
76
+ }
77
+
78
+ /** 绑定地址的 URL 主机名形式:IPv6 加方括号,去掉接口 zone。 */
79
+ function bindHostname(bindHost) {
80
+ if (typeof bindHost !== 'string' || bindHost === '') return undefined
81
+ const zoneAt = bindHost.indexOf('%')
82
+ const bare = zoneAt === -1 ? bindHost : bindHost.slice(0, zoneAt)
83
+ try {
84
+ return new URL(`http://${bare.includes(':') ? `[${bare}]` : bare}`).hostname.toLowerCase()
85
+ } catch {
86
+ return undefined
87
+ }
88
+ }
89
+
90
+ /** 对齐 DSH 的 isTrustedAuthority:无端口条目匹配任意端口,带端口条目精确匹配。 */
91
+ function isTrustedAuthority(hostUrl, trustedHosts, scheme) {
92
+ return trustedHosts.some((entry) => {
93
+ const entryUrl = parseAuthority(entry, scheme)
94
+ if (entryUrl === undefined) return false
95
+ const otherScheme = entryUrl.protocol === 'http:' ? 'https:' : 'http:'
96
+ const explicitPort = entryUrl.port !== '' ? entryUrl.port : new URL(`${otherScheme}//${entry}`).port
97
+ return explicitPort === ''
98
+ ? entryUrl.hostname === hostUrl.hostname
99
+ : entryUrl.host === hostUrl.host
100
+ })
101
+ }
102
+
103
+ /** Origin 的 http(s) scheme;非法或非 http(s) 值返回 undefined。 */
104
+ function originScheme(origin) {
105
+ try {
106
+ const url = new URL(origin)
107
+ return url.protocol === 'https:' ? 'https:' : url.protocol === 'http:' ? 'http:' : undefined
108
+ } catch {
109
+ return undefined
110
+ }
111
+ }
112
+
113
+ /** 对齐 DSH 的 isSameAuthorityOrigin:Host 按 Origin 的 scheme 归一化默认端口后比较。 */
114
+ function isSameAuthorityOrigin(origin, host) {
115
+ const scheme = originScheme(origin)
116
+ if (scheme === undefined) return false
117
+ const hostUrl = parseAuthority(host, scheme)
118
+ return hostUrl !== undefined && new URL(origin).host === hostUrl.host
119
+ }
120
+
121
+ /** 读取配置字段:volatile 字段是 { get() } live ref,普通配置对象则是具体值。 */
122
+ function readConfigField(config, key) {
123
+ const value = config?.[key]
124
+ return value && typeof value === 'object' && typeof value.get === 'function' ? value.get() : value
125
+ }
126
+
127
+ /** 读取宿主服务;未提供或未注入时 cordis 会抛错,这里统一降级为 undefined。 */
128
+ function readService(read) {
129
+ try {
130
+ return read()
131
+ } catch {
132
+ return undefined
133
+ }
134
+ }
135
+
44
136
  async function fetchUsageFromGateway(baseUrl, apiKey) {
45
137
  const ctrl = new AbortController()
46
138
  const timer = setTimeout(() => ctrl.abort(), REQUEST_TIMEOUT_MS)
@@ -59,26 +151,65 @@ async function fetchUsageFromGateway(baseUrl, apiKey) {
59
151
  }
60
152
  }
61
153
 
62
- export function apply(ctx) {
63
- const scope = ctx.settings.register(NS, schema)
64
-
65
- /** @type {{ at: number, data: any } | null} */
154
+ export function apply(ctx, config = {}) {
155
+ /** @type {{ at: number, baseUrl: string, keyRef: string, data: any } | null} */
66
156
  let usageCache = null
67
157
 
68
158
  function invalidateCache() {
69
159
  usageCache = null
70
160
  }
71
161
 
72
- async function getApiKey() {
73
- const cfg = scope.get()
74
- const keyRef = cfg.keyRef || DEFAULT_KEY_REF
162
+ function currentBaseUrl() {
163
+ return normalizeBase(readConfigField(config, 'baseUrl')) || defaultBaseUrl
164
+ }
165
+
166
+ function currentKeyRef() {
167
+ return readConfigField(config, 'keyRef') || DEFAULT_KEY_REF
168
+ }
169
+
170
+ /** settings 以 profile 条目 id 作为命名空间;优先取 loader 分配的条目 id。 */
171
+ function settingsNamespace() {
172
+ const entryId = readService(() => ctx.fiber?.entry?.options?.id)
173
+ return typeof entryId === 'string' && entryId ? entryId : NS
174
+ }
175
+
176
+ /**
177
+ * 可选的 settings 服务(DSH 0.2.x 用它持久化 volatile 配置)。
178
+ * 宿主未提供时返回 null,由调用方降级为明确错误响应。
179
+ */
180
+ function settingsService() {
181
+ const service = readService(() => (typeof ctx.get === 'function' ? ctx.get('settings') : undefined))
182
+ if (service && typeof service.update === 'function') return service
183
+ // 兼容把服务直接挂在 ctx 上的宿主;未注入时 cordis 的读取已由 readService 兜住。
184
+ const direct = readService(() => ctx.settings)
185
+ return direct && typeof direct.update === 'function' ? direct : null
186
+ }
187
+
188
+ async function persistBaseUrl(baseUrl) {
189
+ const settings = settingsService()
190
+ if (!settings) {
191
+ throw Object.assign(new Error('当前宿主未提供 settings 服务,无法持久化 Base URL'), {
192
+ statusCode: 409,
193
+ code: 'SETTINGS_UNAVAILABLE',
194
+ })
195
+ }
196
+ try {
197
+ await settings.update(settingsNamespace(), { baseUrl })
198
+ } catch (error) {
199
+ throw Object.assign(new Error(`Base URL 持久化失败: ${error?.message ?? error}`), {
200
+ statusCode: 409,
201
+ code: 'PERSIST_FAILED',
202
+ })
203
+ }
204
+ }
205
+
206
+ async function getApiKey(keyRef = currentKeyRef()) {
75
207
  const resolved = await ctx.credentials.resolve(keyRef).catch(() => undefined)
76
208
  return resolved?.value || null
77
209
  }
78
210
 
79
- async function publicConfig() {
80
- const cfg = scope.get()
81
- const keyRef = cfg.keyRef || DEFAULT_KEY_REF
211
+ async function publicConfig(overrideBaseUrl) {
212
+ const keyRef = currentKeyRef()
82
213
  const info = await ctx.credentials.describe(keyRef)
83
214
  let hint = null
84
215
  if (info.configured) {
@@ -86,7 +217,7 @@ export function apply(ctx) {
86
217
  hint = resolved?.value ? `••••${resolved.value.slice(-4)}` : '••••'
87
218
  }
88
219
  return {
89
- baseUrl: cfg.baseUrl || DEFAULT_BASE_URL,
220
+ baseUrl: overrideBaseUrl ?? currentBaseUrl(),
90
221
  apiKey: {
91
222
  configured: info.configured,
92
223
  source: info.source ?? null,
@@ -96,10 +227,10 @@ export function apply(ctx) {
96
227
  }
97
228
  }
98
229
 
99
- async function buildStatus(force = false) {
100
- const cfg = scope.get()
101
- const baseUrl = cfg.baseUrl || DEFAULT_BASE_URL
102
- const key = await getApiKey()
230
+ async function buildStatus(force = false, overrideBaseUrl) {
231
+ const baseUrl = overrideBaseUrl ?? currentBaseUrl()
232
+ const keyRef = currentKeyRef()
233
+ const key = await getApiKey(keyRef)
103
234
 
104
235
  if (!key) {
105
236
  return {
@@ -113,8 +244,16 @@ export function apply(ctx) {
113
244
  }
114
245
 
115
246
  const now = Date.now()
116
- if (!force && usageCache && now - usageCache.at < DEFAULT_CACHE_TTL_MS) {
117
- return usageCache.data
247
+ const cached = usageCache
248
+ // 命中条件同时比对缓存建立时的 baseUrl 与 keyRef:设置页热改配置后立即重新拉取。
249
+ if (
250
+ !force &&
251
+ cached &&
252
+ cached.baseUrl === baseUrl &&
253
+ cached.keyRef === keyRef &&
254
+ now - cached.at < DEFAULT_CACHE_TTL_MS
255
+ ) {
256
+ return cached.data
118
257
  }
119
258
 
120
259
  try {
@@ -160,7 +299,7 @@ export function apply(ctx) {
160
299
  windows,
161
300
  error: null,
162
301
  }
163
- usageCache = { at: now, data: result }
302
+ usageCache = { at: now, baseUrl, keyRef, data: result }
164
303
  return result
165
304
  } catch (error) {
166
305
  return {
@@ -192,20 +331,101 @@ export function apply(ctx) {
192
331
  }
193
332
  const text = Buffer.concat(chunks).toString('utf8')
194
333
  if (!text.trim()) return {}
195
- const data = JSON.parse(text)
334
+ let data
335
+ try {
336
+ data = JSON.parse(text)
337
+ } catch {
338
+ throw Object.assign(new Error('请求体必须是合法的 JSON'), { statusCode: 400, code: 'INVALID' })
339
+ }
196
340
  if (typeof data !== 'object' || data === null || Array.isArray(data)) {
197
- throw Object.assign(new Error('请求体必须是 JSON 对象'), { statusCode: 400 })
341
+ throw Object.assign(new Error('请求体必须是 JSON 对象'), { statusCode: 400, code: 'INVALID' })
198
342
  }
199
343
  return data
200
344
  }
201
345
 
202
- function guard(handler) {
346
+ /** connection 服务(DSH Web 的 Host/Origin fence 所有者)及其 trustedHosts。 */
347
+ function connectionService() {
348
+ return readService(() => (typeof ctx.get === 'function' ? ctx.get('connection') : undefined))
349
+ }
350
+
351
+ function connectionTrustedHosts() {
352
+ const trusted = readService(() => connectionService()?.trustedHosts)
353
+ return Array.isArray(trusted) ? trusted.filter((entry) => typeof entry === 'string') : []
354
+ }
355
+
356
+ /** 监听器 scheme(https 由 TLS 配置决定,从不取自请求头)。 */
357
+ function listenerScheme() {
358
+ const protocol = readService(() => ctx.webServer?.protocol)
359
+ return protocol === 'https:' || protocol === 'http:' ? protocol : 'http:'
360
+ }
361
+
362
+ /**
363
+ * 本地 Host/Origin fence,与 DSH client-connection 的 isTrustedApiRequest 等价:
364
+ * Host 必须是 loopback、监听器 bind 地址或 connection.trustedHosts 中的地址;
365
+ * 拒绝 sec-fetch-site: cross-site;带 Origin 时必须是同一 authority(默认端口按 Origin 的 scheme 归一化)。
366
+ */
367
+ function trustedByLocalFence(req) {
368
+ const headers = req.headers ?? {}
369
+ const host = headerValue(headers, 'host')
370
+ if (host === undefined || host === '') return false
371
+ const origin = headerValue(headers, 'origin')
372
+ const scheme = (origin !== undefined && originScheme(origin)) || listenerScheme()
373
+ const hostUrl = parseAuthority(host, scheme)
374
+ if (hostUrl === undefined) return false
375
+ const bind = bindHostname(readService(() => ctx.webServer?.host))
376
+ const hostTrusted = isLoopbackHostname(hostUrl.hostname)
377
+ || (bind !== undefined && hostUrl.hostname === bind)
378
+ || isTrustedAuthority(hostUrl, connectionTrustedHosts(), scheme)
379
+ if (!hostTrusted) return false
380
+ if (headerValue(headers, 'sec-fetch-site') === 'cross-site') return false
381
+ if (origin === undefined || origin === '') return true
382
+ return isSameAuthorityOrigin(origin, host)
383
+ }
384
+
385
+ /** 优先使用宿主的官方 fence,缺失 connection 服务时回退到等价的本地实现。 */
386
+ function isTrustedRequest(req) {
387
+ const connection = connectionService()
388
+ if (connection !== undefined && typeof connection.isTrusted === 'function') {
389
+ return readService(() => connection.isTrusted(req)) === true
390
+ }
391
+ return trustedByLocalFence(req)
392
+ }
393
+
394
+ /**
395
+ * 读请求防护:与写请求共用同一套 Host/来源白名单。
396
+ * 只读路径同样会被 DNS rebinding 利用(攻击者页面可读取 baseUrl、掩码与用配额),
397
+ * 因此 GET 不再放行任意来源。
398
+ */
399
+ function assertTrustedRead(req) {
400
+ if (!isTrustedRequest(req)) {
401
+ throw Object.assign(new Error('拒绝不可信的读请求来源'), { statusCode: 403, code: 'FORBIDDEN' })
402
+ }
403
+ }
404
+
405
+ /** 写请求防护:先做 Host/来源白名单(DNS rebinding 与跨站防护),再校验请求内容类型。 */
406
+ function assertTrustedWrite(req) {
407
+ if (!isTrustedRequest(req)) {
408
+ throw Object.assign(new Error('拒绝不可信的写请求来源'), { statusCode: 403, code: 'FORBIDDEN' })
409
+ }
410
+ if (!isJsonContentType((req.headers ?? {})['content-type'])) {
411
+ // 与宿主 client-connection 对齐:实体格式不受支持时返回 415,而不是 403。
412
+ throw Object.assign(new Error('写请求必须使用 application/json'), {
413
+ statusCode: 415,
414
+ code: 'UNSUPPORTED_MEDIA_TYPE',
415
+ })
416
+ }
417
+ }
418
+
419
+ function guard(handler, { writeMethods = [], fencedRead = false } = {}) {
203
420
  return async (req, res) => {
204
421
  try {
422
+ const method = String(req.method ?? '').toUpperCase()
423
+ if (writeMethods.includes(method)) assertTrustedWrite(req)
424
+ else if (fencedRead && method === 'GET') assertTrustedRead(req)
205
425
  await handler(req, res)
206
426
  } catch (error) {
207
427
  sendJson(res, error?.statusCode ?? 500, {
208
- error: { code: 'INTERNAL', message: String(error?.message ?? error) },
428
+ error: { code: error?.code ?? 'INTERNAL', message: String(error?.message ?? error) },
209
429
  })
210
430
  }
211
431
  }
@@ -220,7 +440,7 @@ export function apply(ctx) {
220
440
  if (req.method !== 'GET') return sendJson(res, 405, { error: { code: 'METHOD', message: 'GET only' } })
221
441
  const force = new URL(req.url ?? '/', 'http://localhost').searchParams.has('force')
222
442
  sendJson(res, 200, await buildStatus(force))
223
- }),
443
+ }, { fencedRead: true }),
224
444
  }),
225
445
  )
226
446
 
@@ -237,19 +457,30 @@ export function apply(ctx) {
237
457
  return sendJson(res, 405, { error: { code: 'METHOD', message: 'GET/PUT only' } })
238
458
  }
239
459
  const body = await readBody(req)
240
- const baseUrl = normalizeBase(body.baseUrl) || DEFAULT_BASE_URL
460
+ const baseUrl = normalizeBase(body.baseUrl) || defaultBaseUrl
241
461
  if (!isAbsoluteHttpUrl(baseUrl)) {
242
462
  return sendJson(res, 400, { error: { code: 'INVALID', message: 'Base URL 必须是有效的 http(s) 地址' } })
243
463
  }
244
464
 
245
465
  const newKey = typeof body.apiKey === 'string' ? body.apiKey.trim() : ''
246
466
  const clearKey = body.clearApiKey === true
247
- const keyRef = scope.get().keyRef || DEFAULT_KEY_REF
467
+ const keyRef = currentKeyRef()
248
468
 
249
469
  if (clearKey && newKey) {
250
470
  return sendJson(res, 400, { error: { code: 'INVALID', message: '不能同时设置新密钥并清除密钥' } })
251
471
  }
252
472
 
473
+ // baseUrl 变更先落盘:宿主不支持持久化时给出明确错误,避免只写入一半配置。
474
+ if (baseUrl !== currentBaseUrl()) {
475
+ try {
476
+ await persistBaseUrl(baseUrl)
477
+ } catch (error) {
478
+ return sendJson(res, error?.statusCode ?? 409, {
479
+ error: { code: error?.code ?? 'SETTINGS_UNAVAILABLE', message: String(error?.message ?? error) },
480
+ })
481
+ }
482
+ }
483
+
253
484
  try {
254
485
  if (clearKey) await ctx.credentials.unset(keyRef)
255
486
  else if (newKey) await ctx.credentials.set(keyRef, newKey)
@@ -257,15 +488,15 @@ export function apply(ctx) {
257
488
  return sendJson(res, 409, { error: { code: 'KEY_NOT_WRITABLE', message: `密钥写入失败: ${error?.message ?? error}` } })
258
489
  }
259
490
 
260
- await scope.update({ baseUrl })
261
491
  invalidateCache()
262
492
 
493
+ // 持久化成功后本次响应回显保存值;宿主刷新 live ref 后后续请求自动一致。
263
494
  sendJson(res, 200, {
264
495
  saved: true,
265
- config: await publicConfig(),
266
- status: await buildStatus(true),
496
+ config: await publicConfig(baseUrl),
497
+ status: await buildStatus(true, baseUrl),
267
498
  })
268
- }),
499
+ }, { writeMethods: ['PUT'], fencedRead: true }),
269
500
  }),
270
501
  )
271
502
 
@@ -277,7 +508,7 @@ export function apply(ctx) {
277
508
  handler: guard(async (req, res) => {
278
509
  if (req.method !== 'POST') return sendJson(res, 405, { error: { code: 'METHOD', message: 'POST only' } })
279
510
  sendJson(res, 200, await buildStatus(true))
280
- }),
511
+ }, { writeMethods: ['POST'] }),
281
512
  }),
282
513
  )
283
514
  }