dsh-opencode-status 0.1.5 → 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 +34 -0
- package/README.md +26 -1
- package/package.json +4 -3
- package/src/client.js +19 -11
- package/src/index.js +265 -34
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,39 @@
|
|
|
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
|
+
|
|
3
37
|
## 0.1.5
|
|
4
38
|
|
|
5
39
|
- 消除点击弹窗中的重复进度条展示:用量进度条与倒计时全部由 220ms 悬浮微卡呈现(免点即看),点击按钮直达「⚙ OpenCode GO 连接配置」管理卡片(配置 Base URL、设置 API Key、清除 Key 与强制同步)。
|
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.
|
|
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.
|
|
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', {
|
|
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) {
|
|
@@ -215,7 +217,7 @@ window.__ModuleLoader__.load({
|
|
|
215
217
|
margin: '2px auto',
|
|
216
218
|
},
|
|
217
219
|
title: st?.error?.message || `OpenCode GO ${value || ''}`,
|
|
218
|
-
onClick: () => store.set({ open: !state.open
|
|
220
|
+
onClick: () => store.set({ open: !state.open }),
|
|
219
221
|
},
|
|
220
222
|
st?.monthlyUsedPct !== null && st?.monthlyUsedPct !== undefined ? `${st.monthlyUsedPct}%` : 'GO',
|
|
221
223
|
)
|
|
@@ -240,7 +242,7 @@ window.__ModuleLoader__.load({
|
|
|
240
242
|
background: state.open ? 'var(--dsw-alias-interactive-bg-hover, rgba(59,130,246,.12))' : 'transparent',
|
|
241
243
|
},
|
|
242
244
|
onClick: () => {
|
|
243
|
-
store.set({ open: !state.open
|
|
245
|
+
store.set({ open: !state.open })
|
|
244
246
|
if (!state.open) {
|
|
245
247
|
refreshStatus(false)
|
|
246
248
|
refreshConfig()
|
|
@@ -372,7 +374,7 @@ window.__ModuleLoader__.load({
|
|
|
372
374
|
headers: { 'content-type': 'application/json' },
|
|
373
375
|
body: JSON.stringify({ baseUrl, ...(apiKey ? { apiKey } : {}) }),
|
|
374
376
|
})
|
|
375
|
-
store.set({ status: result.status, config: result.config
|
|
377
|
+
store.set({ status: result.status, config: result.config })
|
|
376
378
|
setApiKey('')
|
|
377
379
|
} catch (e) {
|
|
378
380
|
setError(e?.message ?? '保存失败')
|
|
@@ -391,7 +393,7 @@ window.__ModuleLoader__.load({
|
|
|
391
393
|
headers: { 'content-type': 'application/json' },
|
|
392
394
|
body: JSON.stringify({ baseUrl, clearApiKey: true }),
|
|
393
395
|
})
|
|
394
|
-
store.set({ status: result.status, config: result.config
|
|
396
|
+
store.set({ status: result.status, config: result.config })
|
|
395
397
|
} catch (e) {
|
|
396
398
|
setError(e?.message ?? '清除失败')
|
|
397
399
|
} finally {
|
|
@@ -399,6 +401,14 @@ window.__ModuleLoader__.load({
|
|
|
399
401
|
}
|
|
400
402
|
}
|
|
401
403
|
|
|
404
|
+
/** 放弃未保存的编辑并关闭面板:重新打开时表单会从已保存的配置重新渲染。 */
|
|
405
|
+
function cancel() {
|
|
406
|
+
setBaseUrl(cfg?.baseUrl ?? '')
|
|
407
|
+
setApiKey('')
|
|
408
|
+
setError(null)
|
|
409
|
+
store.set({ open: false })
|
|
410
|
+
}
|
|
411
|
+
|
|
402
412
|
return h('div', null, [
|
|
403
413
|
h('div', { key: 'u', style: { marginBottom: 10 } }, [
|
|
404
414
|
h('label', { style: { display: 'block', fontSize: 12, color: T.secondary, marginBottom: 4 } }, 'Base URL'),
|
|
@@ -427,9 +437,7 @@ window.__ModuleLoader__.load({
|
|
|
427
437
|
{ className: 'oc-btn oc-btn-primary', style: { ...btnBase, background: T.brand, borderColor: T.brand, color: '#fff' }, disabled: saving, onClick: save },
|
|
428
438
|
saving ? '保存中…' : '保存并连接',
|
|
429
439
|
),
|
|
430
|
-
|
|
431
|
-
? h('button', { className: 'oc-btn', style: btnBase, disabled: saving, onClick: () => store.set({ editing: false }) }, '取消')
|
|
432
|
-
: null,
|
|
440
|
+
h('button', { className: 'oc-btn', style: btnBase, disabled: saving, onClick: cancel }, '取消'),
|
|
433
441
|
keyState.configured && keyState.writable
|
|
434
442
|
? h('button', { className: 'oc-btn', style: { ...btnBase, color: T.err, marginLeft: 'auto' }, disabled: saving, onClick: clearKey }, '清除')
|
|
435
443
|
: null,
|
|
@@ -460,7 +468,7 @@ window.__ModuleLoader__.load({
|
|
|
460
468
|
const handleClickOutside = (e) => {
|
|
461
469
|
if (panelRef.current && !panelRef.current.contains(e.target)) {
|
|
462
470
|
const isBtn = e.target.closest && e.target.closest('.oc-footer-btn')
|
|
463
|
-
if (!isBtn) store.set({ open: false
|
|
471
|
+
if (!isBtn) store.set({ open: false })
|
|
464
472
|
}
|
|
465
473
|
}
|
|
466
474
|
window.addEventListener('mousedown', handleClickOutside)
|
|
@@ -540,7 +548,7 @@ window.__ModuleLoader__.load({
|
|
|
540
548
|
color: T.secondary,
|
|
541
549
|
background: 'transparent',
|
|
542
550
|
},
|
|
543
|
-
onClick: () => store.set({ open: false
|
|
551
|
+
onClick: () => store.set({ open: false }),
|
|
544
552
|
title: '关闭',
|
|
545
553
|
},
|
|
546
554
|
'✕',
|
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 = ['
|
|
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
|
-
|
|
31
|
+
// DSH 0.2.x 用插件导出的 Config 取代已移除的 settings 配置注册接口。
|
|
32
|
+
export const Config = z.object({
|
|
26
33
|
// 环境变量只作为未持久化配置时的默认值;非法值不覆盖官方端点。
|
|
27
|
-
baseUrl: z.string().default(
|
|
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
|
-
|
|
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
|
-
|
|
73
|
-
|
|
74
|
-
|
|
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
|
|
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:
|
|
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
|
|
101
|
-
const
|
|
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
|
-
|
|
117
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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) ||
|
|
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 =
|
|
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
|
}
|