dsh-opencode-status 0.1.3 → 0.2.3

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/CHANGELOG.md CHANGED
@@ -1,5 +1,51 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.3
4
+
5
+ - 修复配置面板「取消」按钮点击无反应:该按钮此前只翻转 `editing` 标记,而 0.1.5 的弹窗重构之后已没有任何渲染逻辑读取它。现在「取消」会丢弃未保存的编辑并关闭面板,重新打开时表单从已保存配置重新渲染。
6
+ - 移除 store 中已废弃的 `editing` 字段及其全部写入点。
7
+ - 测试增至 26 个用例,新增客户端「取消」处理函数的静态回归。
8
+
9
+ ## 0.2.2
10
+
11
+ - 修复 content-type 回归用例被 Host fence 掩盖的问题:原用例没带 `Host`,请求在来源检查阶段就被拒绝,因此删掉 content-type 校验后测试仍然全绿。现在用例明确带可信 `Host`、断言 `415 UNSUPPORTED_MEDIA_TYPE` 与错误消息,并校验凭据未被修改。
12
+ - `GET` 路由补上与写请求相同的 Host/来源 fence,闭合 DNS rebinding 的读取路径(此前攻击者可读取配额、`baseUrl` 与密钥尾四位掩码)。默认部署(loopback / bind 地址 / `connection.trustedHosts`)不受影响;宿主提供 `connection.isTrusted` 时,读与写都委托官方判定。
13
+ - 写请求 content-type 不合法时由 `403 FORBIDDEN` 改为 `415 UNSUPPORTED_MEDIA_TYPE`,与宿主 `client-connection` 的语义保持一致。
14
+ - 新增两条回归:GET 的 rebinding / 缺 Host / loopback 放行;`connection.isTrusted` 委托在读写两条路径上的放行与拒绝。
15
+ - 文档:README 安全说明区分「默认部署只监听 loopback」与「绑定其它地址时依赖 bind 地址白名单或 `trustedHosts`」,补充读路径 fence 与 415 语义;修复 CHANGELOG 中重复的 `## 0.2.0` 标题。
16
+ - 测试增至 25 个用例。
17
+
18
+ ## 0.2.1
19
+
20
+ - package.json 增加 `engines.dsh: ">=0.2.0 <0.3.0-0"` 兼容声明,版本升到 0.2.1。上界写成 `<0.3.0-0` 是为了让 0.3.0 的预发布版同样 UNMET;已用宿主 app-boot 的 `evaluatePluginCompatibility` 实测:`0.2.2-rc.1` → COMPATIBLE,`0.3.0-rc.1` / `0.3.0-rc.2` / `0.3.0` → UNMET(旧的 `>=0.2.0 <0.3.0` 会把 `0.3.0-rc.1`、`0.3.0-rc.2` 误判为 COMPATIBLE)。
21
+ - 请求体 JSON 解析失败时返回 `400` + 错误码 `INVALID`(此前会落到 guard 的 500);`64KB` 请求体上限仍返回 `413`,非对象 JSON 同样返回 `400 INVALID`。
22
+ - 状态缓存(30s TTL)命中条件增加 baseUrl 与 keyRef 比对:在设置页热改配置后,下一次 `GET /api/opencode-status` 立即重新拉取,不再等 TTL 过期;`PUT` 里的显式缓存失效保留。
23
+ - `PUT` / `POST` 写请求增加与宿主 `client-connection` 对齐的来源防护:`content-type` 必须为 `application/json`(允许 charset);`Host` 白名单要求 hostname 属于 loopback(`localhost`、`[::1]`、`127/8`)、等于 `ctx.webServer.host` 的 bind 地址,或命中 `ctx.get('connection')?.trustedHosts`(宿主提供官方 `isTrusted(req)` 时直接采用其结论);拒绝 `sec-fetch-site: cross-site`;带 `Origin` 时必须是同一 authority(`Host` 的默认端口按 `Origin` 的 scheme 归一化,对齐 `isSameAuthorityOrigin`)。否则返回 `403 FORBIDDEN` 且不触碰凭据与配置。`GET` 行为不变,不支持的写方法仍返回 `405`。
24
+ - 客户端强制刷新(`POST /api/opencode-status/sync`)补上 `content-type: application/json`,避免被新的写请求防护拦截。
25
+ - 测试增至 23 个用例,新增 malformed JSON→400、跨源 Origin→403、非 JSON content-type→403、热改配置缓存失效、`engines.dsh` 与客户端请求头断言,以及 DNS rebinding→403(零写入)与 loopback/localhost/bind/trustedHosts 浏览器形态→200 两条回归。
26
+ - 残余风险(后续项):写端点只做来源校验、不做浏览器会话鉴权,同机进程仍可直接访问 loopback 端点;后续可把写操作迁到带鉴权的 `/api` RPC(复用宿主 `connection.admit` 的 Peer 鉴权)。
27
+
28
+ ## 0.2.0
29
+
30
+ - 适配 DSH 0.2.x:宿主端改用官方 `Config`(schemastery)schema,`baseUrl` 与 `keyRef` 声明为 `volatile` 字段,删除已被移除的旧配置注册调用,修复插件在 0.2.2-rc.1 上无法激活的问题。
31
+ - `apply(ctx, config)` 同时兼容 plain 配置值与 volatile live ref(`{ get() }` 形态),字段缺失时回退到环境变量 / 官方端点与默认密钥引用。
32
+ - Base URL 修改通过宿主的 settings 服务持久化到 profile 条目 `opencode-status`;宿主未提供该服务或写入失败时返回 `SETTINGS_UNAVAILABLE` / `PERSIST_FAILED` 的 409 响应,不再抛到路由外。
33
+ - 保持对外行为不变:4 个 HTTP 端点(含 GET/PUT 配置与 POST 同步)的状态码与响应结构、30s 缓存、10s 超时、64KB 请求体上限、`no-store`、405 分支、密钥脱敏提示与错误码均未改变;API Key 仍只存放于 credentials。
34
+ - 依赖升级到 `@deepseek-ai/schemastery@^3.19.0`(volatile 字段支持)。
35
+ - 测试迁移到新的 Config 读取路径,并补充 volatile ref、settings 成功 / 缺失 / 失败三条路径与 Config 导出断言。
36
+
37
+ ## 0.1.5
38
+
39
+ - 消除点击弹窗中的重复进度条展示:用量进度条与倒计时全部由 220ms 悬浮微卡呈现(免点即看),点击按钮直达「⚙ OpenCode GO 连接配置」管理卡片(配置 Base URL、设置 API Key、清除 Key 与强制同步)。
40
+
41
+ ## 0.1.4
42
+
43
+ - 增加侧边栏鼠标悬停(Hover 220ms)3 维用量卡片预览:5h 滚动窗口、周窗口、月窗口实时用量条与重置倒计时鼠标悬停即看,免去频繁点击与关闭的交互负担。
44
+
45
+ ## 0.1.3
46
+
47
+ - 优化 README 安装命令为官方 npm 源优先。
48
+
3
49
  ## 0.1.2
4
50
 
5
51
  - 修复自定义 `keyRef` 配置下凭据读取、写入与清除目标不一致的问题
package/README.md CHANGED
@@ -15,6 +15,12 @@ OpenCode GO 套餐用量与配额状态监控面板插件(DeepSeek Harness)
15
15
 
16
16
  ## 安装与更新
17
17
 
18
+ ### 兼容性(DSH 0.2.x)
19
+
20
+ - 本版本(`0.2.x`)面向 **DeepSeek Harness 0.2.x**,已在 `0.2.2-rc.1` 上验证;`package.json` 通过 `engines.dsh: ">=0.2.0 <0.3.0-0"` 声明兼容范围(上界带 `-0` 显式排除 0.3.0 的预发布版;宿主用 semver `includePrerelease` 校验,已用其 `evaluatePluginCompatibility` 验证 `0.2.2-rc.1` 为 COMPATIBLE、`0.3.0-rc.1`/`0.3.0-rc.2`/`0.3.0` 为 UNMET)。
21
+ - DSH 0.2.x 移除了旧的插件配置注册接口,改为读取插件导出的 schemastery `Config`:`baseUrl`、`keyRef` 声明为 `volatile` 字段,由宿主生成配置表单并以 live ref 传入 `apply(ctx, config)`。因此 `0.1.x` 及更早版本在 DSH 0.2.x 上无法激活,请升级到 `0.2.0` 或更高版本。
22
+ - 升级方式:先把 DSH 升级到 0.2.x,再执行下面的安装命令(默认拉取 `@latest`),然后重启 `dsh web`。Base URL 会以插件配置写入当前 profile 的 `cordis.patch.yml`,API Key 仍保存在宿主凭据库,无需迁移。
23
+
18
24
  ### 1. 官方 npm 安装(推荐)
19
25
 
20
26
  ```sh
@@ -29,6 +35,7 @@ dsh plugin --profile web add github:j2st1n/dsh-opencode-status
29
35
 
30
36
  > **说明**:
31
37
  > - 无需指定版本号,默认拉取 `@latest` 最新版本;
38
+ > - 请使用 `0.2.0` 及以上版本,旧版无法在 DSH 0.2.x 上激活;
32
39
  > - 安装后重启 `dsh web` 即可立即生效。
33
40
 
34
41
  ### 3. 卸载
@@ -40,9 +47,27 @@ dsh plugin --profile web remove dsh-opencode-status
40
47
  ## 配置
41
48
 
42
49
  点侧栏「连接 OpenCode」或弹窗右上角「⚙」配置:
43
- - **Base URL**:默认 `https://opencode.ai/zen/go`
50
+ - **Base URL**:默认 `https://opencode.ai/zen/go`(也可用环境变量 `OPENCODE_BASE_URL` 提供未持久化时的默认值)
44
51
  - **API Key**:粘贴你的 OpenCode API Key(亦可直接在环境变量中配置 `OPENCODE_GO_API_KEY`)
45
52
 
53
+ 配置存储方式(DSH 0.2.x):
54
+ - **Base URL** 属于插件 `Config` 的 `volatile` 字段:修改时通过宿主的 settings 服务写回当前 profile 条目(`opencode-status`),重启后依然生效;宿主未提供 settings 服务时,修改 Base URL 会返回明确的错误响应,插件不会崩溃。
55
+ - **API Key** 只写入宿主凭据库(默认引用 `OPENCODE_GO_API_KEY`),HTTP 响应仅返回 `••••` 掩码提示,不回传明文。
56
+ - 状态缓存命中时会校验 baseUrl 与 keyRef,因此在 DSH 设置页改动配置后,下一次读取立即生效,无需等待 30s 缓存过期。
57
+
58
+ ## 安全说明
59
+
60
+ - 默认部署只监听本机 loopback,所有响应带 `Cache-Control: no-store`;绑定其它地址时(`--host` / 反代),写请求是否放行取决于 bind 地址白名单与 `connection.trustedHosts`。
61
+ - `GET` 与 `PUT` / `POST` 共用同一套 Host/来源防护,读路径同样会拒绝 DNS rebinding(攻击者页面无法读取配额、`baseUrl` 或密钥掩码):
62
+ - **Host 白名单**:Host 必须可解析,且 hostname 属于 loopback(`localhost`、`[::1]`、`127/8`)、等于监听器 bind 地址(`ctx.webServer.host`),或命中 `ctx.get('connection')?.trustedHosts`;宿主提供官方 `isTrusted(req)` 时直接采用其结论;
63
+ - 请求带 `sec-fetch-site: cross-site` 时直接拒绝;
64
+ - 带 `Origin` 头时必须是同一 authority(Host 的默认端口按 Origin 的 scheme 归一化,对齐 `isSameAuthorityOrigin`),否则返回 `403 FORBIDDEN`,且不会读取或写入凭据与配置。
65
+ - 写请求在上述防护之外还要求 `content-type: application/json`(允许 `charset` 参数),不满足时返回 `415 UNSUPPORTED_MEDIA_TYPE`(与宿主 `client-connection` 语义一致)。
66
+ - 不支持的方法仍返回 `405`(先于来源判定)。
67
+ - 请求体上限 64KB,超出返回 `413`;JSON 解析失败返回 `400`(错误码 `INVALID`)。
68
+ - API Key 只在宿主凭据库中保存,HTTP 响应仅回传尾 4 位掩码。
69
+ - **残余风险**:端点只做来源校验,不做浏览器会话鉴权,同机进程仍可直接访问 loopback 端点;后续可把操作迁到带鉴权的 `/api` RPC(复用宿主 `connection.admit` 的 Peer 鉴权)。
70
+
46
71
  ## License
47
72
 
48
73
  [Apache-2.0](./LICENSE)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-opencode-status",
3
- "version": "0.1.3",
3
+ "version": "0.2.3",
4
4
  "description": "OpenCode GO quota and plan status panel for DeepSeek Harness: sidebar health light, quota bars, countdown timers, and in-app key management",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -34,7 +34,7 @@
34
34
  }
35
35
  },
36
36
  "dependencies": {
37
- "@deepseek-ai/schemastery": "^3.18.1"
37
+ "@deepseek-ai/schemastery": "^3.19.0"
38
38
  },
39
39
  "repository": {
40
40
  "type": "git",
@@ -43,7 +43,8 @@
43
43
  "homepage": "https://github.com/j2st1n/dsh-opencode-status#readme",
44
44
  "bugs": "https://github.com/j2st1n/dsh-opencode-status/issues",
45
45
  "engines": {
46
- "node": ">=20"
46
+ "node": ">=20",
47
+ "dsh": ">=0.2.0 <0.3.0-0"
47
48
  },
48
49
  "scripts": {
49
50
  "test": "node --test"
package/src/client.js CHANGED
@@ -107,7 +107,6 @@ window.__ModuleLoader__.load({
107
107
  const store = {
108
108
  state: {
109
109
  open: false,
110
- editing: false,
111
110
  status: null,
112
111
  config: null,
113
112
  refreshing: false,
@@ -138,7 +137,10 @@ window.__ModuleLoader__.load({
138
137
  async function refreshStatus(force = false) {
139
138
  try {
140
139
  const status = force
141
- ? await api('/api/opencode-status/sync', { method: 'POST' })
140
+ ? await api('/api/opencode-status/sync', {
141
+ method: 'POST',
142
+ headers: { 'content-type': 'application/json' },
143
+ })
142
144
  : await api('/api/opencode-status')
143
145
  store.set({ status, error: null })
144
146
  } catch (err) {
@@ -153,9 +155,11 @@ window.__ModuleLoader__.load({
153
155
  } catch {}
154
156
  }
155
157
 
156
- // ---------- 常驻入口(上下结构单行按钮) ----------
158
+ // ---------- 常驻入口(上下结构单行按钮 + 悬停微卡) ----------
157
159
  function FooterEntry(props) {
158
160
  const state = useStore()
161
+ const [hovering, setHovering] = useState(false)
162
+ const hoverTimerRef = useRef(null)
159
163
 
160
164
  useEffect(() => {
161
165
  refreshStatus(false)
@@ -163,6 +167,15 @@ window.__ModuleLoader__.load({
163
167
  return () => clearInterval(timer)
164
168
  }, [])
165
169
 
170
+ const onMouseEnter = () => {
171
+ clearTimeout(hoverTimerRef.current)
172
+ hoverTimerRef.current = setTimeout(() => setHovering(true), 220)
173
+ }
174
+ const onMouseLeave = () => {
175
+ clearTimeout(hoverTimerRef.current)
176
+ setHovering(false)
177
+ }
178
+
166
179
  const st = state.status
167
180
  let color = T.warn
168
181
  let text = '连接 OpenCode'
@@ -204,16 +217,18 @@ window.__ModuleLoader__.load({
204
217
  margin: '2px auto',
205
218
  },
206
219
  title: st?.error?.message || `OpenCode GO ${value || ''}`,
207
- onClick: () => store.set({ open: !state.open, editing: false }),
220
+ onClick: () => store.set({ open: !state.open }),
208
221
  },
209
222
  st?.monthlyUsedPct !== null && st?.monthlyUsedPct !== undefined ? `${st.monthlyUsedPct}%` : 'GO',
210
223
  )
211
224
  }
212
225
 
213
- return h(
226
+ const node = h(
214
227
  'button',
215
228
  {
216
229
  className: 'oc-btn oc-footer-btn',
230
+ onMouseEnter,
231
+ onMouseLeave,
217
232
  style: {
218
233
  ...btnBase,
219
234
  display: props?.wide === false ? 'inline-flex' : 'flex',
@@ -223,22 +238,23 @@ window.__ModuleLoader__.load({
223
238
  margin: '2px 0',
224
239
  minWidth: 0,
225
240
  flexShrink: 0,
241
+ borderColor: state.open ? T.brand : T.border,
242
+ background: state.open ? 'var(--dsw-alias-interactive-bg-hover, rgba(59,130,246,.12))' : 'transparent',
226
243
  },
227
244
  onClick: () => {
228
- store.set({ open: !state.open, editing: false })
245
+ store.set({ open: !state.open })
229
246
  if (!state.open) {
230
247
  refreshStatus(false)
231
248
  refreshConfig()
232
249
  }
233
250
  },
234
- title: st?.error?.message || `OpenCode GO · ${value || '点击查看详情'}`,
235
251
  },
236
252
  h('span', { className: color === T.ok ? 'oc-dot-live' : undefined, style: dotStyle(color) }),
237
253
  h(
238
254
  'span',
239
255
  { style: { display: 'inline-flex', alignItems: 'center', lineHeight: '18px', whiteSpace: 'nowrap', minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis' } },
240
256
  [
241
- h('span', { key: 't', style: { color: T.label, flexShrink: 0 } }, text),
257
+ h('span', { key: 't', style: { color: T.label, fontWeight: 500, flexShrink: 0 } }, text),
242
258
  value
243
259
  ? [
244
260
  h('span', { key: 'sep', style: { color: T.secondary, margin: '0 5px', opacity: 0.7, flexShrink: 0 } }, '·'),
@@ -248,6 +264,53 @@ window.__ModuleLoader__.load({
248
264
  ].flat().filter(Boolean),
249
265
  ),
250
266
  )
267
+
268
+ if (!hovering || state.open || !st?.ok || !st?.windows?.length) return node
269
+
270
+ return h(
271
+ 'div',
272
+ {
273
+ style: { position: 'relative', width: '100%' },
274
+ onMouseEnter,
275
+ onMouseLeave,
276
+ },
277
+ node,
278
+ h(
279
+ 'div',
280
+ {
281
+ className: 'oc-panel-enter',
282
+ style: {
283
+ position: 'absolute',
284
+ left: 0,
285
+ right: 0,
286
+ bottom: 'calc(100% + 6px)',
287
+ background: T.bg,
288
+ border: `1px solid ${T.border2}`,
289
+ borderRadius: '10px',
290
+ boxShadow: '0 8px 24px rgba(0,0,0,.18)',
291
+ padding: '12px 14px 4px 14px',
292
+ fontSize: '11px',
293
+ color: T.label,
294
+ zIndex: 100,
295
+ fontFamily: 'system-ui, -apple-system, sans-serif',
296
+ },
297
+ },
298
+ h(
299
+ 'div',
300
+ {
301
+ style: {
302
+ display: 'flex',
303
+ alignItems: 'center',
304
+ justifyContent: 'space-between',
305
+ marginBottom: 10,
306
+ },
307
+ },
308
+ h('span', { style: { fontWeight: 600, fontSize: '12px' } }, '🚀 OpenCode GO 用量概览'),
309
+ st.plan ? h('span', { style: { fontSize: '10px', color: T.brand, fontWeight: 600 } }, st.plan) : null,
310
+ ),
311
+ st.windows.map((w, i) => h(QuotaRow, { key: i, window: w })),
312
+ ),
313
+ )
251
314
  }
252
315
 
253
316
  // ---------- 配额进度条 ----------
@@ -311,7 +374,7 @@ window.__ModuleLoader__.load({
311
374
  headers: { 'content-type': 'application/json' },
312
375
  body: JSON.stringify({ baseUrl, ...(apiKey ? { apiKey } : {}) }),
313
376
  })
314
- store.set({ status: result.status, config: result.config, editing: false })
377
+ store.set({ status: result.status, config: result.config })
315
378
  setApiKey('')
316
379
  } catch (e) {
317
380
  setError(e?.message ?? '保存失败')
@@ -330,7 +393,7 @@ window.__ModuleLoader__.load({
330
393
  headers: { 'content-type': 'application/json' },
331
394
  body: JSON.stringify({ baseUrl, clearApiKey: true }),
332
395
  })
333
- store.set({ status: result.status, config: result.config, editing: false })
396
+ store.set({ status: result.status, config: result.config })
334
397
  } catch (e) {
335
398
  setError(e?.message ?? '清除失败')
336
399
  } finally {
@@ -338,6 +401,14 @@ window.__ModuleLoader__.load({
338
401
  }
339
402
  }
340
403
 
404
+ /** 放弃未保存的编辑并关闭面板:重新打开时表单会从已保存的配置重新渲染。 */
405
+ function cancel() {
406
+ setBaseUrl(cfg?.baseUrl ?? '')
407
+ setApiKey('')
408
+ setError(null)
409
+ store.set({ open: false })
410
+ }
411
+
341
412
  return h('div', null, [
342
413
  h('div', { key: 'u', style: { marginBottom: 10 } }, [
343
414
  h('label', { style: { display: 'block', fontSize: 12, color: T.secondary, marginBottom: 4 } }, 'Base URL'),
@@ -366,9 +437,7 @@ window.__ModuleLoader__.load({
366
437
  { className: 'oc-btn oc-btn-primary', style: { ...btnBase, background: T.brand, borderColor: T.brand, color: '#fff' }, disabled: saving, onClick: save },
367
438
  saving ? '保存中…' : '保存并连接',
368
439
  ),
369
- state.status?.mode === 'ready'
370
- ? h('button', { className: 'oc-btn', style: btnBase, disabled: saving, onClick: () => store.set({ editing: false }) }, '取消')
371
- : null,
440
+ h('button', { className: 'oc-btn', style: btnBase, disabled: saving, onClick: cancel }, '取消'),
372
441
  keyState.configured && keyState.writable
373
442
  ? h('button', { className: 'oc-btn', style: { ...btnBase, color: T.err, marginLeft: 'auto' }, disabled: saving, onClick: clearKey }, '清除')
374
443
  : null,
@@ -376,7 +445,7 @@ window.__ModuleLoader__.load({
376
445
  ])
377
446
  }
378
447
 
379
- // ---------- 浮层面板 ----------
448
+ // ---------- 浮层配置面板(点击进入控制台管理,用量已在悬浮卡片展示) ----------
380
449
  function OverlayPanel() {
381
450
  const state = useStore()
382
451
  const panelRef = useRef(null)
@@ -399,7 +468,7 @@ window.__ModuleLoader__.load({
399
468
  const handleClickOutside = (e) => {
400
469
  if (panelRef.current && !panelRef.current.contains(e.target)) {
401
470
  const isBtn = e.target.closest && e.target.closest('.oc-footer-btn')
402
- if (!isBtn) store.set({ open: false, editing: false })
471
+ if (!isBtn) store.set({ open: false })
403
472
  }
404
473
  }
405
474
  window.addEventListener('mousedown', handleClickOutside)
@@ -409,7 +478,6 @@ window.__ModuleLoader__.load({
409
478
  if (phase === 'closed') return null
410
479
 
411
480
  const st = state.status
412
- const showConfig = state.editing || !st || st.mode === 'needs_config'
413
481
 
414
482
  return h(
415
483
  'div',
@@ -433,65 +501,35 @@ window.__ModuleLoader__.load({
433
501
  [
434
502
  // 头部
435
503
  h('div', { key: 'hd', style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12, borderBottom: `1px solid ${T.border}`, paddingBottom: 8 } }, [
436
- h('span', { style: { fontSize: 13, fontWeight: 600, color: T.label } }, showConfig ? '配置 OpenCode' : 'OpenCode GO 用量'),
504
+ h('span', { style: { fontSize: 13, fontWeight: 600, color: T.label } }, '⚙ OpenCode GO 连接配置'),
437
505
  h('div', { style: { display: 'flex', gap: 4, alignItems: 'center' } }, [
438
- !showConfig
439
- ? h(
440
- 'button',
441
- {
442
- className: 'oc-btn',
443
- style: {
444
- width: 26,
445
- height: 26,
446
- padding: 0,
447
- display: 'inline-flex',
448
- alignItems: 'center',
449
- justifyContent: 'center',
450
- fontSize: 14,
451
- border: 'none',
452
- borderRadius: 6,
453
- cursor: 'pointer',
454
- color: T.secondary,
455
- background: 'transparent',
456
- },
457
- onClick: async () => {
458
- store.set({ refreshing: true })
459
- await refreshStatus(true)
460
- store.set({ refreshing: false })
461
- },
462
- title: '刷新用量',
463
- },
464
- state.refreshing ? h('span', { className: 'oc-spin' }, '↻') : '↻',
465
- )
466
- : null,
467
- !showConfig
468
- ? h(
469
- 'button',
470
- {
471
- className: 'oc-btn',
472
- style: {
473
- width: 26,
474
- height: 26,
475
- padding: 0,
476
- display: 'inline-flex',
477
- alignItems: 'center',
478
- justifyContent: 'center',
479
- fontSize: 15,
480
- border: 'none',
481
- borderRadius: 6,
482
- cursor: 'pointer',
483
- color: T.secondary,
484
- background: 'transparent',
485
- },
486
- onClick: () => {
487
- store.set({ editing: true })
488
- refreshConfig()
489
- },
490
- title: '更新配置',
491
- },
492
- '⚙',
493
- )
494
- : null,
506
+ h(
507
+ 'button',
508
+ {
509
+ className: 'oc-btn',
510
+ style: {
511
+ width: 26,
512
+ height: 26,
513
+ padding: 0,
514
+ display: 'inline-flex',
515
+ alignItems: 'center',
516
+ justifyContent: 'center',
517
+ fontSize: 14,
518
+ border: 'none',
519
+ borderRadius: 6,
520
+ cursor: 'pointer',
521
+ color: T.secondary,
522
+ background: 'transparent',
523
+ },
524
+ onClick: async () => {
525
+ store.set({ refreshing: true })
526
+ await refreshStatus(true)
527
+ store.set({ refreshing: false })
528
+ },
529
+ title: '强制刷新同步',
530
+ },
531
+ state.refreshing ? h('span', { className: 'oc-spin' }, '↻') : '↻',
532
+ ),
495
533
  h(
496
534
  'button',
497
535
  {
@@ -510,21 +548,15 @@ window.__ModuleLoader__.load({
510
548
  color: T.secondary,
511
549
  background: 'transparent',
512
550
  },
513
- onClick: () => store.set({ open: false, editing: false }),
551
+ onClick: () => store.set({ open: false }),
514
552
  title: '关闭',
515
553
  },
516
554
  '✕',
517
555
  ),
518
556
  ]),
519
557
  ]),
520
- // 内容
521
- showConfig
522
- ? h(ConfigCard)
523
- : h('div', null, [
524
- st?.error ? h('div', { key: 'err', style: { fontSize: 11, color: T.err, marginBottom: 8 } }, st.error.message) : null,
525
- ...(st?.windows ?? []).map((w) => h(QuotaRow, { key: w.id, window: w })),
526
- h('div', { key: 'tip', style: { fontSize: 10, color: T.secondary, textAlign: 'right', marginTop: 6 } }, `更新于 ${new Date(st?.fetchedAt || Date.now()).toLocaleTimeString()}`),
527
- ]),
558
+ // 内容:直接展示配置与连接管理
559
+ h(ConfigCard),
528
560
  ],
529
561
  )
530
562
  }
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
  }