Compare commits

...

6 Commits

Author SHA1 Message Date
狐友 GXXP & Miku 25d574f3de fix(web): keep trigger focus when closing member drawer via backdrop
build / build (push) Successful in 2m7s
Prevent the backdrop mousedown default from moving focus to body, so closing the drawer always restores focus to the 新增成员 trigger as the drawer contract requires.
2026-11-24 12:28:41 +08:00
狐友 GXXP & Miku 1dfa4fa7fc feat(web): added member creation drawer with inline validation
- Replaced the inline member form with a header button and right-side drawer.
- Added inline validation, 409/400 field mapping, dirty-close confirm, and focus handling.
- Added MembersRequestError with HTTP status and a mounted regression test.
2026-11-24 12:06:54 +08:00
zheromiku d76363c117 Merge pull request 'feat(settings): 存储与备份只读摘要页对齐验收' (#30) from hifox-agent/len/CYWL-16 into main
build / build (push) Successful in 2m8s
2026-11-24 11:56:21 +08:00
狐友 GXXP & LEN b2248a9b64 feat(settings): 存储与备份只读摘要页对齐验收
build / build (push) Successful in 2m12s
- 单一「存储与备份」页:目录、最近成功/失败、归档占用、磁盘剩余四张卡片 + 备份目录条
- 四条容量告警按磁盘可用/配额已用阈值给出 正常/注意/需处理,缺数显示 未知 而非正常
- 批次表默认 20 条 + 加载更多,展示失败原因与单条复制;60 秒自动刷新
- 未接入/未上报/过期/不完整/不可用分状态措辞,不用 0 冒充
- 移除计划编辑、下发、立即备份与库内诊断块(写端点保留)
- compose 接线 LIBRARY_CAPACITY_BUDGET_BYTES 与 BACKUP_HOST_* 只读元数据
2026-11-24 11:53:49 +08:00
狐友 GXXP & Miku 8c84c9c601 fix(kb-bindings): allow key entry on private HTTP consoles
build / build (push) Successful in 2m26s
- Accept the private-console transport with an exact Origin/Host match; the http console is not a secure context, so Chrome sends no Sec-Fetch-Site and that requirement made every real write 400.
- Reject bracketed non-IPv6 host spellings, including ported forms, instead of normalising them to loopback.
- Show the plaintext-warning copy or the disabled state from a tri-state capability field; old APIs keep the legacy message.
- Document WEKNORA_ALLOW_PRIVATE_HTTP in .env.example and the operations runbook.
2026-11-24 11:22:06 +08:00
zheromiku 660320d646 Merge pull request 'fix(cd): 核验主站首页的 SSO 同源改写' (#29) from fix/cd-serving-proof into main
build / build (push) Successful in 1m46s
2026-11-23 22:00:48 +08:00
32 changed files with 2643 additions and 3182 deletions
+2
View File
@@ -28,6 +28,8 @@ QA_AI_MASTER_KEY_FILE=
# 留空时页面仍能读旧部署的文件凭据/默认绑定,但保存新密钥会被拒绝(不落明文)。 # 留空时页面仍能读旧部署的文件凭据/默认绑定,但保存新密钥会被拒绝(不落明文)。
WEKNORA_BINDING_MASTER_KEY_FILE= WEKNORA_BINDING_MASTER_KEY_FILE=
# 同网段 http(生产 18093 反代)放行:只接受 RFC1918/回环/链路本地,公网 http 仍拒绝。 # 同网段 http(生产 18093 反代)放行:只接受 RFC1918/回环/链路本地,公网 http 仍拒绝。
# 同时决定「知识库绑定」页是否允许录入新 Key(能力位来自服务端);开启后页面显示明文传输风险。
# 控制台自身经 TLS 反代提供时,仍需 QA_AI_TRUST_TLS_PROXY=true 且反代传 X-Forwarded-Proto=https。
WEKNORA_ALLOW_PRIVATE_HTTP=false WEKNORA_ALLOW_PRIVATE_HTTP=false
# Empty uses system DNS; alidns enables certificate-verified public DNS-over-TLS for this client only. # Empty uses system DNS; alidns enables certificate-verified public DNS-over-TLS for this client only.
QA_AI_DNS_OVER_TLS= QA_AI_DNS_OVER_TLS=
+30
View File
@@ -1,5 +1,35 @@
# Changelog # Changelog
## 开发快照 0.1.415(成员管理:新增成员改为右侧抽屉)
### Fixed
- **新增入口移到标题栏**:成员表格下方常驻表单改为「成员与角色」标题右侧的
`新增成员` 按钮,点击从右侧滑出抽屉;桌面宽 480px,窄屏铺满,表单字段与
重置密码弹层共用同一套控件与校验提示。
- **关闭前确认未保存输入**:Esc、取消、关闭按钮与遮罩点击在草稿非空时先确认;
清空草稿后直接关闭并把焦点还给触发按钮;创建请求进行中忽略一切关闭请求。
- **创建失败留在抽屉**:409 固定到用户名行,400 收敛为表单级提示,二者都保留
已填内容;成功后关闭抽屉、刷新列表,页级错误/成功条只承载加载与行内操作。
### Changed
- **请求错误带 HTTP 状态**:`web/src/members.ts` 的失败改为 `MembersRequestError`
(含 `status`),组件按 409/400 分流,不再依赖错误文案匹配。
## 开发快照 0.1.414(知识库绑定:私网 http 可录入 Key)
### Fixed
- **私网 http 控制台无法录入 API Key**:页面过去只看浏览器 URL 决定能否录入,而服务端写侧
已按 `WEKNORA_ALLOW_PRIVATE_HTTP` 放行私网 http,导致「开关开着、输入框仍禁用」。GET
`/api/v1/kb-bindings` 现在返回 `secret_entry_allowed`,由服务端按本次连接的 TLS、回环、
开关与受信反代判定;API 未返回该字段时前端按不可录入处理(失败关闭)。写侧判定不变。
- **明文录入没有风险提示**:能力位开启且页面经非回环 http 打开时,Key 输入下方常驻提示密钥
将明文传输;HTTPS 反代未配置 `QA_AI_TRUST_TLS_PROXY` 时改为提示该配置,不再笼统要求 HTTPS。
- **`Host: [::1]`(无端口)被误判为非回环**:地址规范化统一去掉 IPv6 方括号与可选端口,
回环写入不再被拒;受信反代能力位对 GET 只依赖 `X-Forwarded-Proto`(浏览器无法伪造该头)。
## 开发快照 0.1.413(知识库绑定:生产侧待入库重排与按环境隔离) ## 开发快照 0.1.413(知识库绑定:生产侧待入库重排与按环境隔离)
### Fixed ### Fixed
+8
View File
@@ -52,6 +52,14 @@ services:
# 「整库版本」页:只读已封存的整库候选产物。归档根由 `libraryctl capture` # 「整库版本」页:只读已封存的整库候选产物。归档根由 `libraryctl capture`
# 在主机上写入(私有 0700),这里只挂只读;留空 = 未接线(页面降级展示原因)。 # 在主机上写入(私有 0700),这里只挂只读;留空 = 未接线(页面降级展示原因)。
LIBRARY_ARCHIVE_ROOT: "${LIBRARY_ARCHIVE_ROOT:-/var/lib/knowledge-governance/library}" LIBRARY_ARCHIVE_ROOT: "${LIBRARY_ARCHIVE_ROOT:-/var/lib/knowledge-governance/library}"
# 「存储与备份」摘要页的归档配额(字节)。留空 = 未设置,页面显示"配额未设置";
# 显式写 0 会被 appconfig 拒绝(必须为正整数),所以只能用空串表示未设置。
LIBRARY_CAPACITY_BUDGET_BYTES: "${LIBRARY_CAPACITY_BUDGET_BYTES:-}"
# 宿主每 5 分钟上报的整库备份元数据快照(collector 写入,平台只读)。
# 留空 = 未接线,页面按验收显示"主机未上报";路径必须是宿主机侧绝对路径。
BACKUP_HOST_METADATA_PATH: "${BACKUP_HOST_METADATA_PATH:-}"
BACKUP_HOST_METADATA_MAX_AGE: "${BACKUP_HOST_METADATA_MAX_AGE:-15m}"
BACKUP_HOST_READONLY_HOST_PATH: "${BACKUP_HOST_READONLY_HOST_PATH:-}"
# 主机侧封存 agent 的 unix socket:api 只用它判断"能不能从页面发起", # 主机侧封存 agent 的 unix socket:api 只用它判断"能不能从页面发起",
# worker 用它投递作业。容器里没有 Docker socket,也没有来源凭据。 # worker 用它投递作业。容器里没有 Docker socket,也没有来源凭据。
LIBRARY_AGENT_SOCKET: "${LIBRARY_AGENT_SOCKET:-/run/library-agent/agent.sock}" LIBRARY_AGENT_SOCKET: "${LIBRARY_AGENT_SOCKET:-/run/library-agent/agent.sock}"
+8
View File
@@ -70,6 +70,14 @@ docker inspect -f '{{.Name}} {{index .Config.Labels "release"}}' kg-test-storage
http,公网 http 仍被拒绝;不再需要测试机上的 `ssh -L 18092`,停掉隧道后生产连接仍 http,公网 http 仍被拒绝;不再需要测试机上的 `ssh -L 18092`,停掉隧道后生产连接仍
应可用。没有反代时继续填 `http://127.0.0.1:18092` 走隧道(回环地址不需要该开关)。 应可用。没有反代时继续填 `http://127.0.0.1:18092` 走隧道(回环地址不需要该开关)。
**页面为什么能看到开关。** 「知识库绑定」页不再用浏览器 URL 自行判断能否录入 Key;GET
`/api/v1/kb-bindings` 返回 `secret_entry_allowed`,由服务端按本次连接的 TLS、回环、
`WEKNORA_ALLOW_PRIVATE_HTTP` 与受信反代判定。开启开关后,经私网 http 打开的控制台可以
录入/更换 Key,并显示「密钥会以明文经过这段内网」;关闭时保持 HTTPS/回环要求。控制台
自身经 TLS 反代提供时,必须同时设置 `QA_AI_TRUST_TLS_PROXY=true` 且反代传
`X-Forwarded-Proto: https`,否则页面提示「服务器未信任本控制台的 TLS 反代」并禁用录入。
先升级 API 再升级 Web:旧 API 不返回该字段时前端按不可录入处理(失败关闭),不会误放行。
**四态与尾号。** 「验证并读取知识库」会真实列库并区分:地址不可达 / 密钥无效(401) / **四态与尾号。** 「验证并读取知识库」会真实列库并区分:地址不可达 / 密钥无效(401) /
密钥无权限(403) / 成功(读到 N 个库)。保存后页面只显示「已配置 · 尾XXXX」; 密钥无权限(403) / 成功(读到 N 个库)。保存后页面只显示「已配置 · 尾XXXX」;
「清除密钥」是独立动作(二次确认),清除后该侧解析失败关闭,不会回落到服务器文件 「清除密钥」是独立动作(二次确认),清除后该侧解析失败关闭,不会回落到服务器文件
+7 -1
View File
@@ -34,7 +34,13 @@ func (config Config) handleKBBindings(w http.ResponseWriter, r *http.Request) {
for _, view := range views { for _, view := range views {
storageReady = storageReady || view.StorageReady storageReady = storageReady || view.StorageReady
} }
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"environments": views, "storage_ready": storageReady}}) writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{
"environments": views,
"storage_ready": storageReady,
// The page cannot test the server's transport rule from the browser URL
// alone (a TLS proxy and an untrusted proxy look identical there).
"secret_entry_allowed": consoleSecretEntryAllowed(r, config.QAAITrustTLSProxy, config.WeKnoraAllowPrivateHTTP),
}})
} }
func (config Config) handleKBBindingCatalog(w http.ResponseWriter, r *http.Request) { func (config Config) handleKBBindingCatalog(w http.ResponseWriter, r *http.Request) {
+93
View File
@@ -128,3 +128,96 @@ func TestKBBindingWritesAreAdminOnly(t *testing.T) {
} }
} }
} }
func TestKBBindingsReadReportsSecretEntryCapability(t *testing.T) {
store := &fakeKBBindings{views: []kbbinding.View{{Environment: kbbinding.EnvTest, Revision: 1, StorageReady: true}}}
for _, tc := range []struct {
name string
host string
allow bool
want bool
}{
{name: "private console with toggle", host: "172.29.151.11:28188", allow: true, want: true},
{name: "private console without toggle", host: "172.29.151.11:28188", want: false},
{name: "loopback console", host: "127.0.0.1:8080", want: true},
} {
t.Run(tc.name, func(t *testing.T) {
config := kbBindingHandler(t, store)
config.WeKnoraAllowPrivateHTTP = tc.allow
request := httptest.NewRequest(http.MethodGet, "/api/v1/kb-bindings", nil)
request.Host = tc.host
response := httptest.NewRecorder()
config.handleKBBindings(response, request)
if response.Code != http.StatusOK {
t.Fatalf("GET status = %d body=%s", response.Code, response.Body.String())
}
var payload struct {
Data struct {
SecretEntryAllowed bool `json:"secret_entry_allowed"`
} `json:"data"`
}
if err := json.Unmarshal(response.Body.Bytes(), &payload); err != nil {
t.Fatal(err)
}
if payload.Data.SecretEntryAllowed != tc.want {
t.Fatalf("secret_entry_allowed = %v, want %v", payload.Data.SecretEntryAllowed, tc.want)
}
})
}
}
func TestKBBindingPrivatePlainHTTPWritesRequireToggle(t *testing.T) {
const (
privateHost = "172.29.151.11:28188"
origin = "http://172.29.151.11:28188"
)
store := &fakeKBBindings{
views: []kbbinding.View{{Environment: kbbinding.EnvTest, Revision: 1, StorageReady: true}},
catalog: kbbinding.Catalog{Status: "ok", Message: "已读取 1 个知识库", Page: 1, PageSize: 20, Total: 1},
}
body := `{"base_revision":1,"base_url":"http://172.29.151.11:9001","key_action":"replace","api_key":"typed-key","internal_kb_id":"kb-in","external_kb_id":"kb-out"}`
save := func(config *Config) *httptest.ResponseRecorder {
request := httptest.NewRequest(http.MethodPut, "http://"+privateHost+"/api/v1/kb-bindings/test", bytes.NewBufferString(body))
request.Host = privateHost
request.SetPathValue("environment", "test")
request.Header.Set("X-Governance-Action", "kb-bindings")
request.Header.Set("Sec-Fetch-Site", "same-origin")
request.Header.Set("Origin", origin)
response := httptest.NewRecorder()
config.handleKBBindingSave(response, request)
return response
}
catalog := func(config *Config) *httptest.ResponseRecorder {
request := httptest.NewRequest(http.MethodPost, "http://"+privateHost+"/api/v1/kb-bindings/test/catalog",
bytes.NewBufferString(`{"base_revision":1,"base_url":"http://172.29.151.11:9001","key_action":"replace","api_key":"typed-key","page":1,"page_size":20}`))
request.Host = privateHost
request.SetPathValue("environment", "test")
request.Header.Set("X-Governance-Action", "kb-bindings")
request.Header.Set("Sec-Fetch-Site", "same-origin")
request.Header.Set("Origin", origin)
response := httptest.NewRecorder()
config.handleKBBindingCatalog(response, request)
return response
}
enabled := kbBindingHandler(t, store)
enabled.WeKnoraAllowPrivateHTTP = true
if response := save(enabled); response.Code != http.StatusOK {
t.Fatalf("save with toggle status=%d body=%s", response.Code, response.Body.String())
}
if store.lastSave.APIKey != "typed-key" {
t.Fatalf("save did not forward the typed key: %q", store.lastSave.APIKey)
}
if response := catalog(enabled); response.Code != http.StatusOK {
t.Fatalf("catalog with toggle status=%d body=%s", response.Code, response.Body.String())
}
disabled := kbBindingHandler(t, store)
if response := save(disabled); response.Code != http.StatusBadRequest {
t.Fatalf("save without toggle status=%d body=%s", response.Code, response.Body.String())
}
if response := catalog(disabled); response.Code != http.StatusBadRequest {
t.Fatalf("catalog without toggle status=%d body=%s", response.Code, response.Body.String())
}
}
+70 -13
View File
@@ -16,14 +16,7 @@ func secretTransportAllowed(r *http.Request, trustTLSProxy bool) bool {
if r.TLS != nil { if r.TLS != nil {
return true return true
} }
host := r.Host if loopbackHost(r.Host) {
if parsedHost, _, err := net.SplitHostPort(host); err == nil {
host = parsedHost
}
if strings.EqualFold(host, "localhost") {
return true
}
if ip := net.ParseIP(host); ip != nil && ip.IsLoopback() {
return true return true
} }
if trustTLSProxy && r.Header.Get("X-Forwarded-Proto") == "https" && r.Header.Get("Sec-Fetch-Site") == "same-origin" { if trustTLSProxy && r.Header.Get("X-Forwarded-Proto") == "https" && r.Header.Get("Sec-Fetch-Site") == "same-origin" {
@@ -36,12 +29,14 @@ func secretTransportAllowed(r *http.Request, trustTLSProxy bool) bool {
// secretTransportAllowedForPrivateConsole additionally accepts a same-origin // secretTransportAllowedForPrivateConsole additionally accepts a same-origin
// fetch from the operator console itself when it is served over plain http on a // fetch from the operator console itself when it is served over plain http on a
// private address. That is the only non-TLS shape this deployment needs, and it // private address. That is the only non-TLS shape this deployment needs, and it
// still requires an exact Origin/Host match. // still requires an exact Origin/Host match. It deliberately does not require
// Sec-Fetch-Site: Chrome only sends Sec-Fetch-* from secure contexts, so an
// http console on a private address never carries that header.
func secretTransportAllowedForPrivateConsole(r *http.Request, trustTLSProxy, allowPrivateHTTP bool) bool { func secretTransportAllowedForPrivateConsole(r *http.Request, trustTLSProxy, allowPrivateHTTP bool) bool {
if secretTransportAllowed(r, trustTLSProxy) { if secretTransportAllowed(r, trustTLSProxy) {
return true return true
} }
if !allowPrivateHTTP || r.Header.Get("Sec-Fetch-Site") != "same-origin" { if !allowPrivateHTTP {
return false return false
} }
origin := strings.TrimSpace(r.Header.Get("Origin")) origin := strings.TrimSpace(r.Header.Get("Origin"))
@@ -53,8 +48,70 @@ func secretTransportAllowedForPrivateConsole(r *http.Request, trustTLSProxy, all
return false return false
} }
host := parsed.Hostname() host := parsed.Hostname()
if ip := net.ParseIP(host); ip != nil { return privateAddressHost(host)
return ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast()
} }
return strings.EqualFold(host, "localhost")
// consoleSecretEntryAllowed mirrors the transports the write gates accept, but
// it cannot simply call secretTransportAllowed: that gate guards a write and
// therefore insists on a same-origin Origin header, which a GET navigation
// never sends. Trusting X-Forwarded-Proto alone on a read is safe because
// browsers cannot set it and the deployment already declares the proxy
// trusted; a forged header still cannot make the write gate accept anything.
func consoleSecretEntryAllowed(r *http.Request, trustTLSProxy, allowPrivateHTTP bool) bool {
if r.TLS != nil || loopbackHost(r.Host) {
return true
}
if trustTLSProxy && r.Header.Get("X-Forwarded-Proto") == "https" {
return true
}
return allowPrivateHTTP && privateAddressHost(r.Host)
}
// requestHostname strips the optional port and IPv6 brackets. Brackets come
// off only around a real IPv6 literal: "[127.0.0.1]", "[localhost]" and their
// ported forms are not address spellings the server or a browser ever emits,
// so they stay untouched and keep failing the address checks.
func requestHostname(host string) string {
host = strings.TrimSpace(host)
if strings.HasPrefix(host, "[") {
end := strings.Index(host, "]")
if end <= 0 {
return host
}
ip := net.ParseIP(host[1:end])
if ip == nil || ip.To4() != nil {
return host
}
if rest := host[end+1:]; rest != "" && (rest[0] != ':' || rest == ":" || strings.Trim(rest[1:], "0123456789") != "") {
return host
}
return ip.String()
}
if parsedHost, _, err := net.SplitHostPort(host); err == nil {
return parsedHost
}
return host
}
// loopbackHost is the address-only part of the secret transport rule: a
// request from this machine never crosses a network.
func loopbackHost(host string) bool {
host = requestHostname(host)
if strings.EqualFold(host, "localhost") {
return true
}
ip := net.ParseIP(host)
return ip != nil && ip.IsLoopback()
}
// privateAddressHost accepts loopback and private addresses. Names other than
// localhost are rejected because the deployment toggle is about addresses,
// not about trusting whatever DNS resolves to.
func privateAddressHost(host string) bool {
host = requestHostname(host)
if strings.EqualFold(host, "localhost") {
return true
}
ip := net.ParseIP(host)
return ip != nil && (ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast())
} }
+112
View File
@@ -0,0 +1,112 @@
package httpapi
import (
"crypto/tls"
"net/http"
"net/http/httptest"
"testing"
)
func TestConsoleSecretEntryAllowedMatrix(t *testing.T) {
cases := []struct {
name string
host string
tls bool
xfp string
trust bool
allow bool
want bool
}{
{name: "direct TLS", host: "console.example", tls: true, want: true},
{name: "loopback name", host: "localhost:8080", want: true},
{name: "loopback v4", host: "127.0.0.1:8080", want: true},
{name: "loopback v6 with port", host: "[::1]:8080", want: true},
{name: "loopback v6 without port", host: "[::1]", want: true},
// Bracketed non-IPv6 hosts are not address spellings; they must not
// borrow loopback trust from the bracket stripper.
{name: "bracketed v4 is not loopback", host: "[127.0.0.1]", want: false},
{name: "bracketed localhost is not loopback", host: "[localhost]", want: false},
{name: "bracketed v4 with toggle is not private", host: "[127.0.0.1]", allow: true, want: false},
{name: "private address with toggle", host: "172.29.151.11:28188", allow: true, want: true},
{name: "private address without toggle", host: "172.29.151.11:28188", want: false},
{name: "link-local with toggle", host: "169.254.10.7:8080", allow: true, want: true},
{name: "public address with toggle", host: "203.0.113.10:8080", allow: true, want: false},
{name: "public name with toggle", host: "console.example", allow: true, want: false},
{name: "trusted proxy https", host: "console.example", xfp: "https", trust: true, want: true},
{name: "untrusted proxy https", host: "console.example", xfp: "https", want: false},
{name: "trusted proxy reports http", host: "console.example", xfp: "http", trust: true, want: false},
// A forged header must not beat the address rule when the proxy is not trusted.
{name: "untrusted proxy on private host", host: "172.29.151.11:28188", xfp: "https", want: false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
request := httptest.NewRequest(http.MethodGet, "http://placeholder/api/v1/kb-bindings", nil)
request.Host = tc.host
if tc.tls {
request.TLS = &tls.ConnectionState{}
}
if tc.xfp != "" {
request.Header.Set("X-Forwarded-Proto", tc.xfp)
}
if got := consoleSecretEntryAllowed(request, tc.trust, tc.allow); got != tc.want {
t.Fatalf("consoleSecretEntryAllowed = %v, want %v", got, tc.want)
}
})
}
}
func TestSecretTransportAllowedAcceptsBareIPv6Loopback(t *testing.T) {
request := httptest.NewRequest(http.MethodPost, "http://placeholder/api/v1/kb-bindings/test", nil)
request.Host = "[::1]"
if !secretTransportAllowed(request, false) {
t.Fatal("bare [::1] Host was rejected as a loopback transport")
}
request.Host = "console.example"
if secretTransportAllowed(request, false) {
t.Fatal("public name without TLS was accepted")
}
}
// Plain-http consoles are not secure contexts, so Chrome never sends
// Sec-Fetch-* with their fetches. A matching Origin is the whole contract.
func TestSecretTransportPrivateConsoleNeedsOriginNotSecFetch(t *testing.T) {
request := httptest.NewRequest(http.MethodPost, "http://placeholder/api/v1/kb-bindings/test/catalog", nil)
request.Host = "192.168.50.134:18093"
request.Header.Set("Origin", "http://192.168.50.134:18093")
if !secretTransportAllowedForPrivateConsole(request, false, true) {
t.Fatal("same-origin private console without Sec-Fetch-Site was rejected")
}
request.Header.Set("Origin", "http://evil.example")
if secretTransportAllowedForPrivateConsole(request, false, true) {
t.Fatal("cross-origin request was accepted as a private console")
}
request.Header.Set("Origin", "http://192.168.50.134:18093")
if secretTransportAllowedForPrivateConsole(request, false, false) {
t.Fatal("private console was accepted with the deployment toggle off")
}
}
func TestSecretTransportRejectsBracketedNonIPv6Hosts(t *testing.T) {
for _, host := range []string{"[127.0.0.1]", "[127.0.0.1]:28188", "[localhost]", "[localhost]:28188"} {
request := httptest.NewRequest(http.MethodPost, "http://placeholder/api/v1/kb-bindings/test", nil)
request.Host = host
if secretTransportAllowed(request, false) {
t.Fatalf("Host %q was accepted as a loopback transport", host)
}
request.Header.Set("Sec-Fetch-Site", "same-origin")
request.Header.Set("Origin", "http://"+host)
if secretTransportAllowedForPrivateConsole(request, false, true) {
t.Fatalf("Host %q was accepted as a private console", host)
}
}
}
func TestSecretTransportRejectsMalformedIPv6Suffixes(t *testing.T) {
for _, host := range []string{"[::1]junk", "[::1]:", "[::1]:abc"} {
request := httptest.NewRequest(http.MethodPost, "http://placeholder/api/v1/kb-bindings/test", nil)
request.Host = host
if secretTransportAllowed(request, false) {
t.Fatalf("Host %q was accepted as a loopback transport", host)
}
}
}
-717
View File
@@ -1,717 +0,0 @@
import { renderToStaticMarkup } from 'react-dom/server'
import { describe, expect, it, vi } from 'vitest'
import {
BackupScheduleView,
backupDaysValid,
backupMonthsValid,
backupTimeValid,
copyBackupPath,
formatBackupBytes,
inventoryAlerts,
inventorySnapshotState,
inventoryUsage,
runMoment,
storageAlerts,
storageAlertSummary,
storageUsage,
} from './BackupScheduleSection'
import type { StorageDiskObservation } from './BackupScheduleSection'
import type { BackupInventory } from './backupInventory'
import type { BackupSchedule } from './backupSchedule'
const base: BackupSchedule = {
enabled: true,
schedule_time: '03:30',
retention_days: 7,
retention_months: 3,
updated_by: 'yaozhanghao',
updated_at: '2026-10-09T12:00:00Z',
last_applied_at: '2026-10-09T12:00:00Z',
last_applied_summary: '每天 03:30 · 保留 7 天 · 每月归档 3 份',
host_configured: true,
host_target: 'weknora-test',
host_endpoint: '100.85.111.121:22',
host_reachable: true,
host_error: '',
host_schedule_enabled: true,
host_schedule_time: '03:30',
host_keep_days: 7,
host_keep_months: 3,
host_cron_lines: [
'30 03 * * * root /bin/bash /opt/weknora-test/logical-backup.sh >> /srv/kb-backups/logs/logical-backup.log 2>&1',
],
host_cron_service: 'active',
host_script_present: true,
last_run_stamp: '20261009T052909Z',
last_run_created_at: '2026-10-09T05:29:09Z',
last_run_duration_seconds: 33,
last_run_total_bytes: 778_502_144,
last_run_databases: ['weknora_test', 'dobotai_prod'],
last_run_failed_databases: [],
last_run_error: '',
in_sync: true,
applied: true,
apply_error: '',
running: false,
running_started_at: '',
run_last_error: '',
}
const GiB = 1024 * 1024 * 1024
const diskFixture = (overrides: Partial<StorageDiskObservation> = {}): StorageDiskObservation => ({
total_bytes: 240 * GiB,
free_bytes: 48 * GiB,
backup_bytes: 62 * GiB,
other_volume_backup_bytes: 0,
quota_bytes: 100 * GiB,
reserve_bytes: 10 * GiB,
estimate_bytes: 12 * GiB,
sampled_at: '2026-11-19T02:00:00Z',
...overrides,
})
const inventoryFixture = (overrides: Partial<BackupInventory> = {}): BackupInventory => {
const baseInventory: BackupInventory = {
wired: true,
metadata: {
configured: true,
present: true,
valid: true,
fresh: true,
complete: true,
path: '/var/lib/knowledge-governance/backup-host/metadata.json',
collected_at: '2026-11-19T03:30:00Z',
age_seconds: 10,
max_age_seconds: 900,
schema_version: 1,
generation: '20261119T033000Z-abc123',
host: 'weknora-test',
collector_version: 'backup-metadata/1',
error: '',
},
root: '/srv/kb-backups/rds-logical',
host_root: '/srv/kb-backups/rds-logical',
source: 'weknora-test:/srv/kb-backups/rds-logical',
observed_at: '2026-11-19T03:30:10Z',
error: '',
measurement: 'host_collector',
mount: {
container_root: '',
mount_verified: true,
lives_on_container_root: false,
read_only: true,
evidence: '宿主采集器:/dev/sdb1 挂在 /srv/kb-backups(ext4),API 不遍历备份目录',
mount_point: '/srv/kb-backups',
device: '/dev/sdb1',
fs_type: 'ext4',
},
capacity: {
measured: true,
total_bytes: 240 * GiB,
free_bytes: 48 * GiB,
available_bytes: 45 * GiB,
used_bytes: 192 * GiB,
},
batches: [
{
stamp: '20261118T193001Z',
path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261118T193001Z',
host_path: '/srv/kb-backups/rds-logical/20261118T193001Z',
manifest_state: 'ok',
manifest_path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261118T193001Z/MANIFEST.json',
kind: 'rds-logical-backup',
created_at: '20261118T193001Z',
started_at: '20261118T192908Z',
duration_seconds: 53,
manifest_total_bytes: 1_393_646_469,
apparent_bytes: 1_393_646_469,
actual_bytes: 1_500_000_000,
file_count: 214,
sizes_complete: true,
databases: [
{
name: 'weknora_v090prod',
dir_name: 'weknora_v090prod.dir',
path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261118T193001Z/weknora_v090prod.dir',
host_path: '/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir',
present: true,
failed: false,
in_manifest: true,
apparent_bytes: 700_000,
actual_bytes: 720_896,
file_count: 12,
},
{
name: 'weknora_test',
dir_name: 'weknora_test.dir',
path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261118T193001Z/weknora_test.dir',
host_path: '/srv/kb-backups/rds-logical/20261118T193001Z/weknora_test.dir',
present: true,
failed: true,
in_manifest: true,
apparent_bytes: 10,
actual_bytes: 4096,
file_count: 1,
},
],
},
{
stamp: '20261117T193001Z',
path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261117T193001Z',
host_path: '/srv/kb-backups/rds-logical/20261117T193001Z',
manifest_state: 'invalid',
manifest_path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261117T193001Z/MANIFEST.json',
manifest_error: '清单无法解析:unexpected end of JSON input',
kind: '',
created_at: '',
started_at: '',
duration_seconds: 0,
manifest_total_bytes: 0,
apparent_bytes: 2048,
actual_bytes: 4096,
file_count: 1,
sizes_complete: true,
databases: [
{
name: 'weknora_archive',
dir_name: 'weknora_archive.dir',
path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261117T193001Z/weknora_archive.dir',
host_path: '/srv/kb-backups/rds-logical/20261117T193001Z/weknora_archive.dir',
present: false,
failed: false,
in_manifest: false,
apparent_bytes: 0,
actual_bytes: 0,
file_count: 0,
},
],
},
],
totals: {
batch_count: 2,
database_count: 3,
apparent_bytes: 1_393_648_517,
actual_bytes: 1_500_004_096,
latest_stamp: '20261118T193001Z',
latest_actual_bytes: 1_500_000_000,
complete: true,
},
incomplete_count: 1,
skipped: [{ name: 'junk', reason: '不是批次目录' }],
truncated: false,
}
return { ...baseInventory, ...overrides }
}
const view = (
overrides: Partial<BackupSchedule> = {},
extra: Record<string, unknown> = {},
disk: StorageDiskObservation | null = null
) => {
const schedule = { ...base, ...overrides }
return renderToStaticMarkup(
<BackupScheduleView
schedule={schedule}
isAdmin={(extra.isAdmin as boolean) ?? true}
loading={false}
probing={false}
busy={(extra.busy as 'save' | 'apply' | 'run' | null) ?? null}
error={(extra.error as string | null) ?? null}
message={(extra.message as string) ?? ''}
enabledDraft={(extra.enabledDraft as boolean) ?? schedule.enabled}
timeDraft={(extra.timeDraft as string) ?? schedule.schedule_time}
daysDraft={(extra.daysDraft as string) ?? String(schedule.retention_days)}
monthsDraft={(extra.monthsDraft as string) ?? String(schedule.retention_months)}
onEnabledChange={vi.fn()}
onTimeChange={vi.fn()}
onDaysChange={vi.fn()}
onMonthsChange={vi.fn()}
onSave={vi.fn()}
onApply={vi.fn()}
onRunNow={vi.fn()}
onReload={vi.fn()}
disk={disk}
inventory={(extra.inventory as BackupInventory) ?? null}
inventoryLoading={(extra.inventoryLoading as boolean) ?? false}
inventoryError={(extra.inventoryError as string | null) ?? null}
onReloadInventory={vi.fn()}
/>
)
}
describe('BackupScheduleView', () => {
it('按真实契约给出范围与读写方向,并把立即备份限定为整批', () => {
const html = view()
for (const text of [
'存储与备份',
'数据库整库逻辑备份',
'范围与读写方向',
'备份执行主机 weknora-test 本机直连 RDS',
'最近批次含 2 个数据库',
'元数据快照未读取',
'元数据快照未读取:目录不可验证,不按设置推定',
'整批 · 2 个数据库(weknora_test、dobotai_prod)',
'100.85.111.121:22',
'立即备份一次(整批 2 个数据库)',
'不开放单库动作',
'仅备份该库(不可用)',
])
expect(html).toContain(text)
// 不存在把整批接口包装成单库操作的按钮文案。
expect(html).not.toContain('>立即备份</button>')
expect(html).not.toContain('生产 090')
expect(html).not.toContain('weknora_v090prod')
})
it('策略区分主机生效状态与编辑草稿,保留期与时间仍是真实可保存字段', () => {
const html = view({}, { timeDraft: '05:10', daysDraft: '14' })
expect(html).toContain('主机生效:每天 03:30 · 保留 7 天 · 每月 3 份 · 与设置已一致')
expect(html).toContain('最后下发(历史)')
expect(html).toContain('只记录当时下发结果,不能代表当前主机计划或执行状态')
expect(html).toContain('编辑草稿:每天 05:10 · 保留 14 天')
expect(html).toContain('有未保存修改,主机仍按生效计划执行')
expect(html).toContain('type="time"')
expect(html).toContain('value="05:10"')
expect(html).toContain('储存天数')
expect(html).toContain('每月归档保留')
expect(html).toContain('保存并下发到主机')
expect(html).toContain('重新下发当前设置')
})
it('目录/配额/预留没有后端字段:控件禁用并写明原因,不会假装可保存', () => {
const html = view()
expect(html).toContain('备份主机上的目录')
expect(html).toContain('元数据快照未读取')
expect(html).toContain('检查目录(不可用)')
expect(html).toContain('备份总配额(GiB)')
expect(html).toContain('磁盘预留(GiB)')
expect(html).toContain('不会被保存')
expect(html).toContain('保存只提交后端契约里的四项')
expect(html).toContain('disabled')
})
it('宿主快照:展示全部批次、MANIFEST 状态、子库完整路径与实际占盘', () => {
const html = view({}, { inventory: inventoryFixture() })
for (const text of [
'备份记录',
'2 批 · 元数据快照',
'最近批次 20261118T193001Z',
'清单完整',
'清单损坏',
'批次戳 20261118T193001Z',
'实际占盘',
'weknora_v090prod',
'weknora_test',
'已写入',
'失败',
'目录缺失',
'/srv/kb-backups/rds-logical/20261118T193001Z',
'/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir',
'/srv/kb-backups/rds-logical/20261117T193001Z/weknora_archive.dir',
'复制子库目录',
'清单无法解析',
'有 1 个',
'junk(不是批次目录)',
'恢复验证:未接线',
])
expect(html).toContain(text)
expect(html).not.toContain('子库路径待接口返回')
expect(html).not.toContain('复制目录(不可用)')
})
it('没有快照:不展示任何历史批次或伪造路径', () => {
const html = view()
expect(html).toContain('尚未读取宿主元数据快照')
expect(html).not.toContain('批次戳')
expect(html).not.toContain('/srv/kb-backups/rds-logical')
})
it('快照未接线:说明与 SSH 计划读回独立,未读到不等于没有备份', () => {
const base = inventoryFixture()
const html = view(
{},
{
inventory: inventoryFixture({
wired: false,
metadata: {
...base.metadata,
configured: false,
present: false,
valid: false,
fresh: false,
complete: false,
error: '元数据快照未接线(BACKUP_HOST_METADATA_PATH 未设置)',
},
error: '元数据快照未接线(BACKUP_HOST_METADATA_PATH 未设置)',
batches: [],
capacity: { measured: false, total_bytes: 0, free_bytes: 0, available_bytes: 0, used_bytes: 0 },
}),
}
)
expect(html).toContain('元数据快照未接线')
expect(html).toContain('未读到批次不等于没有备份')
expect(html).not.toContain('/srv/kb-backups/rds-logical/20261118T193001Z')
})
it('快照可读但没有批次时说明不能据此判断成功/失败', () => {
const html = view(
{
last_run_stamp: '',
last_run_created_at: '',
last_run_databases: [],
last_run_total_bytes: 0,
host_reachable: false,
},
{
inventory: inventoryFixture({
batches: [],
totals: {
batch_count: 0,
database_count: 0,
apparent_bytes: 0,
actual_bytes: 0,
latest_stamp: '',
latest_actual_bytes: 0,
complete: true,
},
}),
}
)
expect(html).toContain('宿主快照可读,但没有批次目录')
expect(html).toContain('不能证明备份成功或失败')
})
it('非管理员只读:没有保存/下发/立即备份按钮,只给当前设置', () => {
const html = view({}, { isAdmin: false })
expect(html).toContain('定时备份设置仅管理员可修改')
expect(html).toContain('立即备份仅管理员可触发')
expect(html).not.toContain('保存并下发到主机')
expect(html).not.toContain('立即备份一次(整批')
})
it('无主机凭据:不能宣称远端计划停止,历史下发只作历史记录', () => {
const html = view({
host_configured: false,
host_reachable: false,
host_error: '目标主机凭据未挂载(BACKUP_HOST_SSH_CONFIG / BACKUP_HOST_TARGET)',
in_sync: false,
})
expect(html).toContain('平台未挂载主机凭据(远端状态未知)')
expect(html).toContain('无法确认当前主机计划')
expect(html).toContain('远端 cron 可能仍在执行')
expect(html).toContain('历史下发不能代替实时状态')
expect(html).toContain('最后下发(历史)')
expect(html).toContain('只记录当时下发结果,不能代表当前主机计划或执行状态')
expect(html).toContain('无法比对(未读取主机计划)')
expect(html).toContain('未探测(平台未挂载主机凭据)')
expect(html).toContain('目标主机凭据未挂载')
// 没读到主机就断言"不会执行"是同类误报。
expect(html).not.toContain('不会执行')
expect(html).not.toContain('未接通备份执行主机')
expect(html).toContain('disabled')
})
it('主机已接线但尚未探测:区分"连不上"与"还没读",不按设置推定', () => {
const html = view({ host_reachable: false, host_error: '', host_checked_at: '', in_sync: false })
expect(html).toContain('weknora-test · 尚未探测')
expect(html).not.toContain('weknora-test · 连接失败')
expect(html).toContain('尚未探测当前主机计划:不能按设置或历史下发推定')
expect(html).toContain('尚未比对')
expect(html).toContain('尚未探测主机,无法确认下一次执行')
})
it('连不上主机:报连接失败与拨号地址,脚本状态写未知而不是"缺失"', () => {
const html = view({
host_reachable: false,
host_endpoint: '120.76.217.51:22',
host_error:
'目标主机 weknora-test 不可达(ssh: connect to host 120.76.217.51 port 22: Operation timed out);未执行任何主机侧脚本,脚本与计划状态未知(拨号地址 120.76.217.51:22)',
in_sync: false,
host_script_present: false,
})
expect(html).toContain('weknora-test · 连接失败')
expect(html).toContain('120.76.217.51:22')
expect(html).toContain('未知(未连上主机,未执行主机侧脚本)')
expect(html).not.toContain('<dt>备份脚本</dt><dd>缺失</dd>')
expect(html).toContain('主机连不上:以下&quot;主机生效&quot;状态未知')
expect(html).toContain('无法比对(主机不可达)')
})
it('已连上且脚本真的不在:这时才显示"缺失"', () => {
const html = view({ host_reachable: true, host_script_present: false, in_sync: false })
expect(html).toContain('weknora-test · 已连接')
expect(html).toContain('缺失')
expect(html).not.toContain('未知(未连上主机')
})
it('待下发(主机上的计划与设置不一致)时提示', () => {
const html = view({ host_schedule_time: '05:00', in_sync: false })
expect(html).toContain('待下发')
expect(html).toContain('每天 05:00')
})
it('在途备份:只报在途与开始时间,不造百分比', () => {
const html = view({ running: true, running_started_at: '2026-10-09T12:30:00Z' })
expect(html).toContain('备份进行中…')
expect(html).toContain('正在备份')
expect(html).toContain('没有真实百分比接口')
})
it('非法输入就地拦截,且保存按钮在未改动时不可点', () => {
const html = view({}, { timeDraft: '25:99', daysDraft: '0' })
expect(html).toContain('定时时间需为 HH:MM(00:00~23:59),储存天数 1~365,每月归档 0~24。')
expect(html).toContain('disabled')
expect(backupTimeValid('03:30')).toBe(true)
expect(backupTimeValid('24:00')).toBe(false)
expect(backupDaysValid(0)).toBe(false)
expect(backupDaysValid(365)).toBe(true)
expect(backupMonthsValid(0)).toBe(true)
expect(backupMonthsValid(25)).toBe(false)
})
it('展示失败的库与最近一次读取错误', () => {
const html = view({ last_run_failed_databases: ['rdsadmin'], last_run_error: '清单无法解析' })
expect(html).toContain('rdsadmin')
expect(html).toContain('清单无法解析')
})
it('最近一次备份不重复显示同一个时间戳', () => {
expect(runMoment({ last_run_stamp: '20261009T060736Z', last_run_created_at: '20261009T060736Z' })).toBe('')
expect(runMoment({ last_run_stamp: '20261009T060736Z', last_run_created_at: '' })).toBe('')
expect(runMoment({ last_run_stamp: '20261009T060736Z', last_run_created_at: '2026-10-09T06:07:36Z' })).not.toBe('')
})
it('体积格式化:未知与零分开', () => {
expect(formatBackupBytes(0)).toBe('0 B')
expect(formatBackupBytes(null)).toBe('—')
expect(formatBackupBytes(undefined)).toBe('—')
expect(formatBackupBytes(1024 * 1024)).toBe('1.0 MiB')
expect(formatBackupBytes(4096)).toBe('4.0 KiB')
expect(formatBackupBytes(720896)).toBe('0.7 MiB')
expect(formatBackupBytes(2 * 1024 * 1024 * 1024)).toBe('2.00 GiB')
})
})
describe('整盘占用与告警', () => {
it('没有快照时:不显示示例容量,四条告警只报未知原因', () => {
const html = view()
expect(html).toContain('占盘未知 · 不使用部分字节')
expect(html).toContain('宿主单项元数据采集器')
expect(html).toContain('无法判定')
expect(html).toContain('整盘总量 / 空闲 / 备份实际占盘:未接线')
// 原型里的示例容量不能被当成产品事实带进来。
expect(html).not.toContain('总容量 240 GiB')
expect(html).not.toContain('总容量 500 GiB')
expect(html).not.toContain('可再写')
})
it('四段色带按真实读数计算:系统其他、备份已用、配额内空闲、配额外空闲', () => {
const usage = storageUsage(diskFixture())
expect(usage.system_other).toBe(130 * GiB) // 240 - 48 - 62
expect(usage.backup).toBe(62 * GiB)
expect(usage.quota_free).toBe(38 * GiB)
expect(usage.beyond_quota_free).toBe(10 * GiB) // 48 - 38
expect(usage.allowance).toBe(38 * GiB)
const html = view({}, {}, diskFixture())
expect(html).toContain('系统其他占用 130 GiB')
expect(html).toContain('备份已用 62 GiB')
expect(html).toContain('配额内空闲 38 GiB')
expect(html).toContain('配额外空闲 10 GiB')
expect(html).toContain('四项均正常')
})
it('磁盘不足:只剩磁盘告警,差值与预计新增都来自读数', () => {
const alerts = storageAlerts(diskFixture({ free_bytes: 20 * GiB, quota_bytes: 80 * GiB }))
expect(alerts.find((item) => item.code === 'disk_low')?.active).toBe(true)
expect(alerts.find((item) => item.code === 'quota_low')?.active).toBe(false)
expect(alerts.find((item) => item.code === 'both_low')?.active).toBe(false)
expect(storageAlertSummary(alerts)).toBe('磁盘不足')
const html = view({}, {}, diskFixture({ free_bytes: 20 * GiB, quota_bytes: 80 * GiB }))
expect(html).toContain('差 2 GiB')
})
it('配额不足:磁盘够、配额差 7 GiB', () => {
const alerts = storageAlerts(diskFixture({ backup_bytes: 95 * GiB }))
expect(alerts.find((item) => item.code === 'quota_low')?.active).toBe(true)
expect(alerts.find((item) => item.code === 'disk_low')?.active).toBe(false)
expect(alerts.find((item) => item.code === 'quota_low')?.detail).toContain('差 7 GiB')
expect(storageAlertSummary(alerts)).toBe('配额不足')
})
it('两者同时不足:第三条告警成立', () => {
const alerts = storageAlerts(diskFixture({ free_bytes: 20 * GiB, backup_bytes: 95 * GiB }))
expect(alerts.find((item) => item.code === 'both_low')?.active).toBe(true)
expect(storageAlertSummary(alerts)).toContain('磁盘与配额同时不足')
})
it('配额超出物理空闲:配额余量大于盘上空闲时单独告警', () => {
const alerts = storageAlerts(diskFixture({ quota_bytes: 200 * GiB }))
expect(alerts.find((item) => item.code === 'quota_over_physical')?.active).toBe(true)
expect(alerts.find((item) => item.code === 'quota_over_physical')?.detail).toContain('超出部分画不进磁盘')
})
it('缺下次新增体积时,磁盘/配额判定保持未知而不是默认正常', () => {
const alerts = storageAlerts(diskFixture({ estimate_bytes: null }))
expect(alerts.filter((item) => !item.known).map((item) => item.code)).toEqual(['disk_low', 'quota_low', 'both_low'])
})
it('真实快照:整盘色带取采集器容量与 st_blocks 实际占盘', () => {
const inventory = inventoryFixture()
const usage = inventoryUsage(inventory)
expect(usage).not.toBeNull()
expect(usage!.total).toBe(240 * GiB)
expect(usage!.free).toBe(45 * GiB)
expect(usage!.backup).toBe(1_500_004_096)
expect(usage!.system_other).toBe(192 * GiB - 1_500_004_096)
const alerts = inventoryAlerts(inventory)
expect(alerts.find((item) => item.code === 'disk_low')?.known).toBe(true)
expect(alerts.find((item) => item.code === 'disk_low')?.active).toBe(false)
expect(alerts.find((item) => item.code === 'quota_low')?.known).toBe(false)
expect(storageAlertSummary(alerts)).toBe('磁盘项正常 · 配额字段未接线')
const html = view({}, { inventory })
for (const text of [
'宿主采集器实测',
'系统其他占用',
'备份实际占盘',
'可用',
'配额内/外 —(无配额字段)',
'文件系统已用',
'采集时间',
'读回时间',
'(API 读回)',
'备份文件系统必须由备份主机可写',
'空间预测仅以上次整批实际占盘 1.40 GiB',
'宿主采集器:/dev/sdb1 挂在 /srv/kb-backups',
'磁盘项正常 · 配额字段未接线',
'0.7 MiB',
'重新盘点(仅重读快照)',
])
expect(html).toContain(text)
expect(html).not.toContain('挂载可写')
expect(html).not.toContain('不是只读')
expect(html).not.toContain('缺主机磁盘读数')
expect(html).not.toContain('0.0 MiB')
})
it('过期快照:目录与历史标已过期,不显示未接线,也不沿用旧批次/旧容量', () => {
const base = inventoryFixture()
const stale = inventoryFixture({
metadata: {
...base.metadata,
valid: false,
fresh: false,
complete: false,
age_seconds: 1200,
error: '元数据已陈旧:采集于 2026-11-19T03:30:00Z,超过 15m0s',
},
capacity: { measured: false, total_bytes: 0, free_bytes: 0, available_bytes: 0, used_bytes: 0 },
totals: { ...base.totals, apparent_bytes: null, actual_bytes: null, latest_actual_bytes: null, complete: false },
// 即使 API 意外保留旧批次,页面也不得用过期快照的路径/容量。
batches: base.batches,
})
expect(inventorySnapshotState(stale)).toBe('stale')
expect(inventoryUsage(stale)).toBeNull()
const alerts = inventoryAlerts(stale)
expect(alerts.find((item) => item.code === 'disk_low')?.known).toBe(false)
expect(alerts.find((item) => item.code === 'disk_low')?.detail).toContain('陈旧')
const html = view({}, { inventory: stale })
for (const text of [
'元数据快照已过期',
'采集时间',
'年龄 1200 秒 / 上限 900 秒',
'已过期',
'读回时间',
'(API 读回)',
'不展示旧批次',
'元数据快照已过期:目录不可验证,不沿用旧路径',
'等待宿主重新采集',
'旧批次、旧目录与旧容量都不再展示',
])
expect(html).toContain(text)
expect(html).not.toContain('元数据快照未接线')
expect(html).not.toContain('/20261118T193001Z')
expect(html).not.toContain('实际占盘 1.40 GiB')
expect(html).not.toContain('文件系统已用')
})
it('未配置快照:明确未接线,不能冒充过期或展示目录/历史', () => {
const base = inventoryFixture()
const unconfigured = inventoryFixture({
wired: false,
metadata: {
...base.metadata,
configured: false,
present: false,
valid: false,
fresh: false,
complete: false,
error: '元数据快照未接线(BACKUP_HOST_METADATA_PATH 未设置)',
},
source: '',
root: '',
host_root: '',
capacity: { measured: false, total_bytes: 0, free_bytes: 0, available_bytes: 0, used_bytes: 0 },
totals: { ...base.totals, apparent_bytes: null, actual_bytes: null, latest_actual_bytes: null, complete: false },
batches: [],
})
expect(inventorySnapshotState(unconfigured)).toBe('unconfigured')
const html = view({}, { inventory: unconfigured })
expect(html).toContain('元数据快照未接线')
expect(html).toContain('目录不可证明')
expect(html).not.toContain('元数据快照已过期')
expect(html).not.toContain('不展示旧目录路径')
})
it('快照请求失败:与未配置/过期分开,不展示目录或旧批次', () => {
const html = view({}, { inventoryError: 'HTTP 503' })
expect(html).toContain('元数据快照读取失败')
expect(html).toContain('快照请求失败:HTTP 503')
expect(html).toContain('目录不可验证')
expect(html).not.toContain('元数据快照未接线')
expect(html).not.toContain('元数据快照已过期')
})
it('不完整快照:容量图与占盘不使用部分字节', () => {
const base = inventoryFixture()
const inventory = inventoryFixture({
metadata: {
...base.metadata,
complete: false,
error: '采集不完整:遍历失败:PermissionError: Permission denied',
},
capacity: { measured: false, total_bytes: 0, free_bytes: 0, available_bytes: 0, used_bytes: 0 },
totals: { ...base.totals, apparent_bytes: null, actual_bytes: null, latest_actual_bytes: null, complete: false },
batches: base.batches.map((batch) => ({
...batch,
apparent_bytes: null,
actual_bytes: null,
file_count: null,
sizes_complete: false,
sizes_error: '宿主采集器该项不完整,占盘未知',
databases: batch.databases.map((database) => ({
...database,
apparent_bytes: null,
actual_bytes: null,
file_count: null,
})),
})),
})
expect(inventoryUsage(inventory)).toBeNull()
const alerts = inventoryAlerts(inventory)
expect(alerts.find((item) => item.code === 'disk_low')?.known).toBe(false)
expect(alerts.find((item) => item.code === 'disk_low')?.detail).toContain('不完整')
expect(storageAlertSummary(alerts)).toBe('无法判定(缺读数与配额字段)')
const html = view({}, { inventory })
expect(html).toContain('占盘未知 · 不使用部分字节')
expect(html).toContain('采集快照不完整:所有批次占盘与容量未知')
expect(html).toContain('占盘未知(采集不完整)')
expect(html).not.toContain('备份实际占盘 1.40 GiB')
expect(html).not.toContain('缺主机磁盘读数')
})
it('复制路径:空值与不可用按钮不谎报成功', async () => {
expect(await copyBackupPath('')).toBe(false)
})
})
File diff suppressed because it is too large Load Diff
+70 -2
View File
@@ -32,6 +32,12 @@ const binding = (environment: 'test' | 'production'): KBEnvironmentBinding => ({
}) })
const snapshot = { const snapshot = {
data: { environments: [binding('test'), binding('production')], storage_ready: true, secret_entry_allowed: true },
}
const snapshotWith = (secretEntryAllowed: boolean) => ({
data: { ...snapshot.data, secret_entry_allowed: secretEntryAllowed },
})
const snapshotWithoutCapability = {
data: { environments: [binding('test'), binding('production')], storage_ready: true }, data: { environments: [binding('test'), binding('production')], storage_ready: true },
} }
const catalog = { const catalog = {
@@ -110,11 +116,11 @@ afterEach(async () => {
vi.unstubAllGlobals() vi.unstubAllGlobals()
}) })
const render = async (role: 'admin' | 'viewer' = 'admin') => { const render = async (role: 'admin' | 'viewer' = 'admin', consoleLocation?: { protocol: string; hostname: string }) => {
await act(async () => { await act(async () => {
root.render( root.render(
<AuthContext.Provider value={auth(role)}> <AuthContext.Provider value={auth(role)}>
<KnowledgeBaseBinding /> <KnowledgeBaseBinding consoleLocation={consoleLocation} />
</AuthContext.Provider> </AuthContext.Provider>
) )
}) })
@@ -272,4 +278,66 @@ describe('KnowledgeBaseBinding', () => {
const save = [...host.querySelectorAll('button')].find((button) => button.textContent?.includes('保存测试绑定')) const save = [...host.querySelectorAll('button')].find((button) => button.textContent?.includes('保存测试绑定'))
expect(save?.hasAttribute('disabled')).toBe(true) expect(save?.hasAttribute('disabled')).toBe(true)
}) })
it('disables key entry when the server reports no accepted transport', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshotWith(false))))
await render()
await click('更换密钥')
const input = host.querySelector<HTMLInputElement>('input[name="kb_key_test"]')
expect(input?.disabled).toBe(true)
expect(host.textContent).toContain('请用有效 HTTPS 或本机 localhost')
})
it('points an HTTPS console at the untrusted proxy setting instead of asking for HTTPS', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshotWith(false))))
await render('admin', { protocol: 'https:', hostname: 'kb.example' })
expect(host.textContent).toContain('QA_AI_TRUST_TLS_PROXY=true')
expect(host.textContent).not.toContain('请用有效 HTTPS 或本机 localhost')
})
it('does not blame a proxy when an older API omits the capability', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshotWithoutCapability)))
await render('admin', { protocol: 'https:', hostname: 'kb.example' })
expect(host.textContent).toContain('请用有效 HTTPS 或本机 localhost')
expect(host.textContent).not.toContain('QA_AI_TRUST_TLS_PROXY')
})
it('allows key entry on a private plain-HTTP console and warns about plaintext', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshotWith(true))))
await render('admin', { protocol: 'http:', hostname: '172.29.151.11' })
await click('更换密钥')
const input = host.querySelector<HTMLInputElement>('input[name="kb_key_test"]')
expect(input?.disabled).toBe(false)
expect(host.textContent).toContain('密钥会以明文经过这段内网')
expect(host.textContent).toContain('WEKNORA_ALLOW_PRIVATE_HTTP=true')
})
it('does not warn on an HTTPS console the server already trusts', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshotWith(true))))
await render('admin', { protocol: 'https:', hostname: 'kb.example' })
expect(host.textContent).not.toContain('密钥会以明文经过这段内网')
})
it('keeps existing-key operations available while key entry is closed', async () => {
const fetchMock = vi.fn((url: string, init?: RequestInit) => {
if (String(url) === '/api/v1/kb-bindings') return Promise.resolve(json(snapshotWith(false)))
if (String(url).includes('/catalog')) return Promise.resolve(json(catalog))
if (init?.method === 'PUT') return Promise.resolve(json({ data: binding('test') }))
return Promise.resolve(json({ data: binding('test') }))
})
vi.stubGlobal('fetch', fetchMock)
await render()
await click('验证并读取知识库')
await choose('对内知识库', 'kb-new-in-0001')
const save = [...host.querySelectorAll('button')].find((button) => button.textContent?.includes('保存测试绑定'))
// 没有新密钥也能改选库:keep 不经过密钥传输闸门。
expect(save?.hasAttribute('disabled')).toBe(false)
await click('保存测试绑定')
const put = fetchMock.mock.calls.find((call) => call[1]?.method === 'PUT')
expect(put).toBeTruthy()
const body = JSON.parse(String(put![1]?.body))
expect(body.key_action).toBe('keep')
expect(body.api_key).toBeUndefined()
expect(host.textContent).toContain('已保存测试绑定')
})
}) })
+32 -4
View File
@@ -1,7 +1,7 @@
import { useEffect, useMemo, useRef, useState } from 'react' import { useEffect, useMemo, useRef, useState } from 'react'
import { useOptionalAuth } from './auth' import { useOptionalAuth } from './auth'
import { secretEntryAllowed } from './secureEntry' import { plaintextRemoteConsole } from './secureEntry'
import { import {
KBBindingError, KBBindingError,
duplicateSelection, duplicateSelection,
@@ -82,7 +82,18 @@ const fallbackLabel = (fallback: string): string =>
const statusTone = (status: KBCatalog['status']): string => const statusTone = (status: KBCatalog['status']): string =>
status === 'ok' ? 'ok' : status === 'empty' ? 'empty' : 'error' status === 'ok' ? 'ok' : status === 'empty' ? 'empty' : 'error'
export function KnowledgeBaseBinding() { interface ConsoleLocation {
protocol: string
hostname: string
}
// consoleLocation is injected by tests that need both console shapes; the app
// always uses the real window.
export function KnowledgeBaseBinding({
consoleLocation,
}: {
consoleLocation?: ConsoleLocation
} = {}) {
const auth = useOptionalAuth() const auth = useOptionalAuth()
const isAdmin = auth?.identity?.role === 'admin' const isAdmin = auth?.identity?.role === 'admin'
const [snapshot, setSnapshot] = useState<KBBindingSnapshot | null>(null) const [snapshot, setSnapshot] = useState<KBBindingSnapshot | null>(null)
@@ -135,7 +146,13 @@ export function KnowledgeBaseBinding() {
const busyNow = busy[env] const busyNow = busy[env]
const notice = notices[env] const notice = notices[env]
const secure = typeof window !== 'undefined' && secretEntryAllowed(window.location) const console = consoleLocation ?? (typeof window !== 'undefined' ? window.location : { protocol: '', hostname: '' })
// The server decides whether it will accept a key on this connection; the
// browser URL cannot tell a trusted TLS proxy from an untrusted one.
const secretEntryAllowed = snapshot?.secret_entry_allowed
const secure = secretEntryAllowed === true
const plaintext = secure && plaintextRemoteConsole(console)
const untrustedProxy = secretEntryAllowed === false && console.protocol === 'https:'
const storageReady = Boolean(snapshot?.storage_ready) const storageReady = Boolean(snapshot?.storage_ready)
const keyAction = saved && draft ? keyActionFor(saved, draft.baseURL, draft.replaceKey) : 'replace' const keyAction = saved && draft ? keyActionFor(saved, draft.baseURL, draft.replaceKey) : 'replace'
const keyReady = keyAction === 'keep' ? Boolean(saved?.key_configured) : draft?.apiKey.trim() !== '' const keyReady = keyAction === 'keep' ? Boolean(saved?.key_configured) : draft?.apiKey.trim() !== ''
@@ -518,9 +535,20 @@ export function KnowledgeBaseBinding() {
)} )}
</div> </div>
</div> </div>
{!secure ? ( {untrustedProxy ? (
<p className="settings-warn">
服务器未信任本控制台的 TLS 反代:HTTPS 在反代终止时需 QA_AI_TRUST_TLS_PROXY=true,并传递
X-Forwarded-Proto。
</p>
) : !secure ? (
<p className="settings-warn">当前不是安全密钥录入连接:请用有效 HTTPS 或本机 localhost 录入新密钥。</p> <p className="settings-warn">当前不是安全密钥录入连接:请用有效 HTTPS 或本机 localhost 录入新密钥。</p>
) : null} ) : null}
{plaintext ? (
<p className="settings-warn">
当前通过明文 HTTP 录入:密钥会以明文经过这段内网。该部署已放开私网
HTTP(WEKNORA_ALLOW_PRIVATE_HTTP=true)。
</p>
) : null}
{saved.base_url && draft.baseURL.trim() !== saved.base_url && saved.key_configured ? ( {saved.base_url && draft.baseURL.trim() !== saved.base_url && saved.key_configured ? (
<p className="settings-warn">已更换服务地址:必须为新地址重新录入 API Key,旧密钥不会发往新地址。</p> <p className="settings-warn">已更换服务地址:必须为新地址重新录入 API Key,旧密钥不会发往新地址。</p>
) : null} ) : null}
-175
View File
@@ -1,175 +0,0 @@
import { useEffect, useState } from 'react'
import { fetchLibraryStorage, formatBytes, type LibraryStorage } from './librarySnapshots'
import './libraryStorage.css'
// 系统设置 → 存储管理:只读展示整库归档的真实口径。
// 保留策略、依赖保护、清理预览都只是"如果清理会怎样",没有任何删除动作;
// 自动清理恒为关闭,策略未设置时不生成候选。
export function LibraryStorageSection() {
const [data, setData] = useState<LibraryStorage | null>(null)
const [error, setError] = useState<string | null>(null)
const [loading, setLoading] = useState(true)
useEffect(() => {
const controller = new AbortController()
fetchLibraryStorage(controller.signal)
.then((value) => {
setData(value)
setError(null)
})
.catch((loadError) => {
if ((loadError as Error).name === 'AbortError') return
setError(loadError instanceof Error ? loadError.message : '读取存储用量失败')
})
.finally(() => setLoading(false))
return () => controller.abort()
}, [])
const plan = data?.plan
const policyConfigured = Boolean(plan?.policy_configured)
return (
<section className="library-storage" aria-label="存储管理">
<header>
<h3>归档占用(版本快照,不是数据库备份)</h3>
<p>
只读口径:被版本引用的去重内容、blob 文件表观/实际分配字节、未被引用对象、清单文件。
这些归档文件与上面的整库数据库备份分开计量,不能相加。
</p>
</header>
{loading ? <p className="library-storage-hint">读取中…</p> : null}
{error ? (
<div className="library-storage-blocked">
<strong>读取失败</strong>
<p>{error}</p>
</div>
) : null}
{data && !data.available ? <p className="library-storage-hint">{data.reason || '归档未接线'}</p> : null}
{data?.available ? (
<>
<dl className="library-storage-grid">
<div>
<dt>版本数</dt>
<dd>{data.versions.length}</dd>
</div>
<div>
<dt>被版本引用的去重内容</dt>
<dd>{formatBytes(data.content_bytes)}</dd>
</div>
<div>
<dt>blob 文件(表观)</dt>
<dd>{formatBytes(data.blob_file_bytes)}</dd>
</div>
<div>
<dt>blob 实际分配</dt>
<dd>{formatBytes(data.blob_allocated_bytes)}</dd>
</div>
<div>
<dt>未被任何版本引用</dt>
<dd>
{data.unreferenced_blobs} 个 / {formatBytes(data.unreferenced_bytes)}
</dd>
</div>
<div>
<dt>清单文件</dt>
<dd>{formatBytes(data.manifest_file_bytes)}</dd>
</div>
</dl>
<div className="library-storage-panel">
<h4>容量门禁</h4>
{data.capacity.configured ? (
<p>
预算 {formatBytes(data.capacity.budget_bytes)} · 当前 {formatBytes(data.capacity.current_bytes)} ·
目标版本约 {formatBytes(data.capacity.required_bytes)} →{' '}
{data.capacity.ok ? '可写入' : `阻断:${data.capacity.reason}`}
</p>
) : (
<p className="library-storage-warn">
容量预算未设置(LIBRARY_CAPACITY_BUDGET_BYTES):无法证明装得下,生产写入按阻断处理。
</p>
)}
</div>
<details className="settings-details" open={!policyConfigured}>
<summary>保留策略与清理预览(未设置时按“全部保留”处理)</summary>
<div className="library-storage-panel">
<h4>保留与依赖保护</h4>
<p>
{policyConfigured
? `策略:${[
plan && plan.policy.keep_versions > 0 ? `保留最近 ${plan.policy.keep_versions} 个版本` : '',
plan && plan.policy.keep_days > 0 ? `保留 ${plan.policy.keep_days} 天` : '',
]
.filter(Boolean)
.join(' + ')}`
: '策略:未设置(不生成清理候选)'}
</p>
<p>
受保护版本 {plan?.protected.length ?? 0} 个:生产生效、每库最近封存、每次生产预备份、运行中作业引用,
不论多久都不会进入候选。
</p>
{data.versions.filter((item) => item.protected).length > 0 ? (
<ul className="library-storage-versions">
{data.versions
.filter((item) => item.protected)
.map((item) => (
<li key={item.id}>
<code>{item.id.slice(0, 12)}</code> {item.kind} · {(item.protected_by ?? []).join('、')}
</li>
))}
</ul>
) : null}
</div>
<div className="library-storage-panel">
<h4>清理预览</h4>
{policyConfigured ? (
plan && plan.candidates.length > 0 ? (
<>
<p>
按策略可考虑清理 {plan.candidates.length} 个版本,独占字节上限{' '}
{formatBytes(plan.reclaim_preview_bytes)}(共享归档文件不会因此释放,这不是可回收空间)。
</p>
<ul className="library-storage-versions">
{plan.candidates.map((item) => (
<li key={item.id}>
<code>{item.id.slice(0, 12)}</code> {item.kind} · {item.reason.join(';')} ·{' '}
{formatBytes(item.exclusive_bytes)}
</li>
))}
</ul>
</>
) : (
<p>按当前策略没有可清理的候选版本。</p>
)
) : (
<p className="library-storage-warn">
保留数量与天数都未设置,按「全部保留」处理:不生成候选,也不提供默认值。
</p>
)}
{plan?.blocked.length ? (
<ul className="library-storage-blocked-list">
{plan.blocked.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
) : null}
</div>
<ul className="library-storage-limits">
<li>自动清理:{data.automatic_cleanup ? '开启' : '保持关闭'}(页面不提供删除动作)</li>
<li>实际删除需要单独授权,本页只给预览</li>
<li>以上数字都不是「可回收空间」,不能用来估算清理收益</li>
{data.notes.map((note) => (
// 服务端注记里的 blob 指归档文件:页面统一术语,不把实现细节甩给操作者。
<li key={note}>{note.replace(/blob/gi, '归档文件')}</li>
))}
</ul>
</details>
</>
) : null}
</section>
)
}
+224
View File
@@ -0,0 +1,224 @@
// @vitest-environment jsdom
import { act } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { Mock } from 'vitest'
import { MembersSection } from './MembersSection'
type FetchStub = (path: string, init?: RequestInit) => Promise<Response>
let root: Root, host: HTMLDivElement
let fetcher: Mock<FetchStub>
let postStatus: 'ok' | 400 | 409 | 'pending'
let releasePost: (() => void) | null
const PASSWORD = 'test-only-pass'
const roster = [
{
id: 'u1',
username: 'wangwu',
display_name: '王五',
role: 'engineer',
state: 'active',
must_change_password: false,
last_login_at: null,
},
]
const json = (data: unknown, status = 200) => new Response(JSON.stringify({ data }), { status })
const dialog = () => host.querySelector<HTMLElement>('[role=dialog]')
const trigger = () => host.querySelector<HTMLButtonElement>('button[aria-label="新增成员"]')
const submit = () =>
[...(dialog()?.querySelectorAll('button') ?? [])].find((b) => b.textContent?.trim() === '新增成员') as
HTMLButtonElement | undefined
const button = (label: string) =>
[...(dialog()?.querySelectorAll('button') ?? [])].find((b) => b.textContent?.trim() === label) as
HTMLButtonElement | undefined
const input = (label: string) => {
const wrapper = [...(dialog()?.querySelectorAll('label') ?? [])].find((l) =>
l.textContent?.trimStart().startsWith(label)
)
return wrapper?.querySelector('input') as HTMLInputElement | undefined
}
const alerts = () => [...host.querySelectorAll('[role=alert]')]
const type = async (label: string, value: string) => {
const field = input(label)
expect(field, label).toBeTruthy()
await act(async () => {
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(field, value)
field!.dispatchEvent(new Event('input', { bubbles: true }))
})
}
const open = async () => {
await act(async () => trigger()!.click())
}
const pressEscape = async () => {
await act(async () => {
document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }))
})
}
const fillValid = async () => {
await type('用户名', 'li.si')
await type('姓名', ' 李四 ')
await type('初始密码', PASSWORD)
}
beforeEach(() => {
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
postStatus = 'ok'
releasePost = null
host = document.createElement('div')
document.body.append(host)
root = createRoot(host)
fetcher = vi.fn(async (path: string, init?: RequestInit) => {
const method = init?.method ?? 'GET'
const created = () => {
const body = JSON.parse(String(init?.body)) as Record<string, unknown>
return json({ id: 'u2', state: 'active', must_change_password: true, last_login_at: null, ...body }, 201)
}
if (path === '/api/v1/users' && method === 'GET') return json(roster)
if (path === '/api/v1/users' && method === 'POST') {
if (postStatus === 409) return new Response(JSON.stringify({ error: 'username already exists' }), { status: 409 })
if (postStatus === 400) return new Response(JSON.stringify({ error: 'invalid user' }), { status: 400 })
if (postStatus === 'pending') {
const promise = new Promise<Response>((resolve) => {
releasePost = () => resolve(created())
})
return promise
}
return created()
}
throw new Error(`unexpected ${method} ${path}`)
})
vi.stubGlobal('fetch', fetcher)
})
afterEach(async () => {
await act(async () => root.unmount())
host.remove()
vi.unstubAllGlobals()
vi.restoreAllMocks()
})
describe('成员新增抽屉', () => {
it('starts with a header button and no inline form or dialog', async () => {
await act(async () => root.render(<MembersSection />))
expect(trigger()).toBeTruthy()
expect(dialog()).toBeNull()
expect(host.querySelector('.member-create-form')).toBeNull()
})
it('opens an accessible drawer and focuses the username field', async () => {
await act(async () => root.render(<MembersSection />))
await open()
expect(dialog()).toBeTruthy()
expect(dialog()!.getAttribute('aria-modal')).toBe('true')
expect(dialog()!.textContent).toContain('新增成员')
expect(document.activeElement).toBe(input('用户名'))
})
it('reports every empty field on submit without sending a request', async () => {
await act(async () => root.render(<MembersSection />))
await open()
await act(async () => submit()!.click())
expect(dialog()).toBeTruthy()
expect(alerts().map((node) => node.textContent)).toEqual(
expect.arrayContaining(['请输入用户名', '请输入姓名', '请输入初始密码'])
)
expect(fetcher.mock.calls.filter(([, init]) => init?.method === 'POST')).toHaveLength(0)
})
it('creates a trimmed member, closes, reloads, and restores focus', async () => {
await act(async () => root.render(<MembersSection />))
await open()
await fillValid()
await act(async () => submit()!.click())
const post = fetcher.mock.calls.find(([, init]) => init?.method === 'POST')
expect(JSON.parse(String(post?.[1]?.body))).toEqual({
username: 'li.si',
display_name: '李四',
role: 'engineer',
password: PASSWORD,
})
expect(dialog()).toBeNull()
expect(host.textContent).toContain('成员 li.si 已创建,初始密码只用于首次登录')
expect(
fetcher.mock.calls.filter(([path, init]) => path === '/api/v1/users' && init?.method === 'GET')
).toHaveLength(2)
expect(document.activeElement).toBe(trigger())
})
it('keeps the draft and pins a 409 to the username field', async () => {
await act(async () => root.render(<MembersSection />))
postStatus = 409
await open()
await fillValid()
await act(async () => submit()!.click())
expect(dialog()).toBeTruthy()
expect(dialog()!.textContent).toContain('该用户名已存在')
expect(input('初始密码')!.value).toBe(PASSWORD)
expect(alerts().filter((node) => !dialog()!.contains(node))).toHaveLength(0)
})
it('shows a form-level chinese error for 400 and stays open', async () => {
await act(async () => root.render(<MembersSection />))
postStatus = 400
await open()
await fillValid()
await act(async () => submit()!.click())
expect(dialog()).toBeTruthy()
expect(dialog()!.textContent).toContain('用户信息不符合规则,请检查用户名与密码')
expect(input('初始密码')!.value).toBe(PASSWORD)
})
it('asks before discarding a dirty draft and honours the answer', async () => {
const confirm = vi.spyOn(window, 'confirm').mockReturnValue(false)
await act(async () => root.render(<MembersSection />))
await open()
await type('用户名', 'li.si')
await pressEscape()
expect(confirm).toHaveBeenCalledWith('放弃未保存的新增成员?')
expect(dialog()).toBeTruthy()
confirm.mockReturnValue(true)
await pressEscape()
expect(dialog()).toBeNull()
await open()
expect(input('用户名')!.value).toBe('')
})
it('closes a clean draft without confirmation', async () => {
const confirm = vi.spyOn(window, 'confirm')
await act(async () => root.render(<MembersSection />))
await open()
await pressEscape()
expect(confirm).not.toHaveBeenCalled()
expect(dialog()).toBeNull()
})
it('ignores close requests while the create request is in flight', async () => {
const confirm = vi.spyOn(window, 'confirm')
await act(async () => root.render(<MembersSection />))
postStatus = 'pending'
await open()
await fillValid()
await act(async () => submit()!.click())
expect(dialog()!.textContent).toContain('创建中…')
await pressEscape()
await act(async () => button('取消')!.click())
expect(dialog()).toBeTruthy()
expect(confirm).not.toHaveBeenCalled()
await act(async () => {
releasePost!()
await Promise.resolve()
})
expect(dialog()).toBeNull()
})
})
+221 -36
View File
@@ -1,5 +1,6 @@
import { useCallback, useEffect, useState } from 'react' import { useCallback, useEffect, useRef, useState } from 'react'
import { import {
MembersRequestError,
createManagedUser, createManagedUser,
fetchManagedUsers, fetchManagedUsers,
resetManagedUserPassword, resetManagedUserPassword,
@@ -12,6 +13,41 @@ import { PasswordInput } from './PasswordInput'
export const memberRoleLabels = roleLabels export const memberRoleLabels = roleLabels
type Draft = {
username: string
display_name: string
role: ManagedUser['role']
password: string
}
type DraftErrors = Partial<Record<'username' | 'display_name' | 'password', string>>
const emptyDraft = (): Draft => ({ username: '', display_name: '', role: 'engineer', password: '' })
function validateDraft(form: Draft): DraftErrors {
const errors: DraftErrors = {}
const username = form.username.trim()
if (!username) {
errors.username = '请输入用户名'
} else if (!/^[a-z0-9][a-z0-9._-]{1,63}$/.test(username)) {
errors.username = '用户名需 2–64 位,以小写字母或数字开头,可含 . _ -'
}
const displayName = form.display_name.trim()
if (!displayName) {
errors.display_name = '请输入姓名'
} else if (displayName.length > 128) {
errors.display_name = '姓名最多 128 字'
}
if (!form.password) {
errors.password = '请输入初始密码'
} else if (form.password.length < 8) {
errors.password = '初始密码至少 8 位'
} else if (form.password.length > 128) {
errors.password = '初始密码最多 128 位'
}
return errors
}
function friendly(cause: unknown, fallback: string): string { function friendly(cause: unknown, fallback: string): string {
return cause instanceof Error && cause.message ? cause.message : fallback return cause instanceof Error && cause.message ? cause.message : fallback
} }
@@ -26,12 +62,12 @@ export function MembersSection() {
// 重置密码用受控对话框(遮罩输入),不再借浏览器 prompt 显示明文。 // 重置密码用受控对话框(遮罩输入),不再借浏览器 prompt 显示明文。
const [resetTarget, setResetTarget] = useState<{ id: string; username: string } | null>(null) const [resetTarget, setResetTarget] = useState<{ id: string; username: string } | null>(null)
const [resetValue, setResetValue] = useState('') const [resetValue, setResetValue] = useState('')
const [form, setForm] = useState({ const [form, setForm] = useState<Draft>(emptyDraft)
username: '', const [drawerOpen, setDrawerOpen] = useState(false)
display_name: '', const [fieldErrors, setFieldErrors] = useState<DraftErrors>({})
role: 'engineer' as ManagedUser['role'], const [createError, setCreateError] = useState<string | null>(null)
password: '', const triggerRef = useRef<HTMLButtonElement>(null)
}) const usernameRef = useRef<HTMLInputElement>(null)
const load = useCallback(async () => { const load = useCallback(async () => {
setLoading(true) setLoading(true)
@@ -63,17 +99,80 @@ export function MembersSection() {
} }
} }
const create = () => const resetDraft = useCallback(() => {
run( setForm(emptyDraft())
'create', setFieldErrors({})
async () => { setCreateError(null)
await createManagedUser(form) }, [])
setForm({ username: '', display_name: '', role: 'engineer', password: '' })
},
`成员 ${form.username} 已创建,初始密码只用于首次登录`
)
const formValid = /^[a-z0-9][a-z0-9._-]{1,63}$/.test(form.username.trim()) && form.password.length >= 8 const closeDrawer = useCallback(() => {
setDrawerOpen(false)
resetDraft()
triggerRef.current?.focus()
}, [resetDraft])
const dirty = form.username !== '' || form.display_name !== '' || form.role !== 'engineer' || form.password !== ''
const requestClose = useCallback(() => {
if (busy === 'create') return
if (dirty && !window.confirm('放弃未保存的新增成员?')) return
closeDrawer()
}, [busy, dirty, closeDrawer])
useEffect(() => {
if (drawerOpen) usernameRef.current?.focus()
}, [drawerOpen])
useEffect(() => {
if (!drawerOpen) return
const onKeyDown = (event: KeyboardEvent) => {
if (event.key !== 'Escape') return
event.preventDefault()
requestClose()
}
document.addEventListener('keydown', onKeyDown)
return () => document.removeEventListener('keydown', onKeyDown)
}, [drawerOpen, requestClose])
const patchForm = (patch: Partial<Draft>) => {
setForm((current) => ({ ...current, ...patch }))
setFieldErrors((current) => {
const next = { ...current }
for (const key of Object.keys(patch) as (keyof DraftErrors)[]) delete next[key]
return next
})
}
const submitCreate = async () => {
if (busy === 'create') return
const errors = validateDraft(form)
setFieldErrors(errors)
if (Object.keys(errors).length > 0) return
const username = form.username.trim()
setBusy('create')
setCreateError(null)
try {
await createManagedUser({
username,
display_name: form.display_name.trim(),
role: form.role,
password: form.password,
})
setMessage(`成员 ${username} 已创建,初始密码只用于首次登录`)
closeDrawer()
await load()
} catch (cause) {
if (cause instanceof MembersRequestError && cause.status === 409) {
setFieldErrors({ username: '该用户名已存在' })
} else if (cause instanceof MembersRequestError && cause.status === 400) {
setCreateError('用户信息不符合规则,请检查用户名与密码')
} else {
setCreateError(friendly(cause, '新增成员失败'))
}
} finally {
setBusy(null)
}
}
return ( return (
<section className="settings-panel wide" id="settings-members"> <section className="settings-panel wide" id="settings-members">
@@ -82,6 +181,18 @@ export function MembersSection() {
<h2>成员与角色</h2> <h2>成员与角色</h2>
<p>登录后的一切操作自动记录在成员名下;角色决定谁能审核、封批和行使生产授权。</p> <p>登录后的一切操作自动记录在成员名下;角色决定谁能审核、封批和行使生产授权。</p>
</div> </div>
<button
ref={triggerRef}
type="button"
className="primary"
aria-label="新增成员"
onClick={() => {
setCreateError(null)
setDrawerOpen(true)
}}
>
<span aria-hidden="true">+</span> 新增成员
</button>
</div> </div>
{loading ? <p>加载成员…</p> : null} {loading ? <p>加载成员…</p> : null}
{error ? ( {error ? (
@@ -190,50 +301,124 @@ export function MembersSection() {
</tbody> </tbody>
</table> </table>
</div> </div>
<div className="member-create-form" aria-label="新增成员"> <small>停用不会删除任何业务记录,只禁止登录并立即撤销其在线会话。</small>
<label> {drawerOpen ? (
用户名 <div
className="member-drawer-backdrop"
onMouseDown={(event) => {
if (event.target !== event.currentTarget) return
// 阻止默认聚焦把焦点从触发按钮夺走:关闭后焦点必须回到「新增成员」。
event.preventDefault()
requestClose()
}}
>
<aside className="member-drawer" role="dialog" aria-modal="true" aria-labelledby="member-drawer-title">
<div className="member-drawer-header">
<h3 id="member-drawer-title">新增成员</h3>
<button
type="button"
className="member-drawer-close"
aria-label="关闭新增成员"
disabled={busy === 'create'}
onClick={requestClose}
>
<span aria-hidden="true">×</span>
</button>
</div>
<form
className="member-drawer-form"
onSubmit={(event) => {
event.preventDefault()
void submitCreate()
}}
>
<div className="member-drawer-body">
{createError ? (
<p className="member-drawer-error member-drawer-form-error" role="alert">
{createError}
</p>
) : null}
<label className="member-drawer-field" htmlFor="member-new-username">
<span>用户名</span>
<input <input
ref={usernameRef}
id="member-new-username"
value={form.username} value={form.username}
maxLength={64} maxLength={64}
placeholder="小写字母/数字,如 zhangsan" autoComplete="username"
onChange={(event) => setForm((current) => ({ ...current, username: event.target.value.toLowerCase() }))} aria-invalid={Boolean(fieldErrors.username)}
aria-describedby="member-new-username-note"
onChange={(event) => patchForm({ username: event.target.value.toLowerCase() })}
/> />
<small
id="member-new-username-note"
className={fieldErrors.username ? 'member-drawer-error' : 'member-drawer-hint'}
role={fieldErrors.username ? 'alert' : undefined}
>
{fieldErrors.username ?? '小写字母/数字,可含 . _ -'}
</small>
</label> </label>
<label> <label className="member-drawer-field" htmlFor="member-new-display-name">
姓名 <span>姓名</span>
<input <input
id="member-new-display-name"
value={form.display_name} value={form.display_name}
maxLength={128} maxLength={128}
onChange={(event) => setForm((current) => ({ ...current, display_name: event.target.value }))} autoComplete="name"
aria-invalid={Boolean(fieldErrors.display_name)}
aria-describedby={fieldErrors.display_name ? 'member-new-display-name-note' : undefined}
onChange={(event) => patchForm({ display_name: event.target.value })}
/> />
{fieldErrors.display_name ? (
<small id="member-new-display-name-note" className="member-drawer-error" role="alert">
{fieldErrors.display_name}
</small>
) : null}
</label> </label>
<label> <label className="member-drawer-field" htmlFor="member-new-role">
角色 <span>角色</span>
<select <select
id="member-new-role"
value={form.role} value={form.role}
onChange={(event) => onChange={(event) => patchForm({ role: event.target.value as ManagedUser['role'] })}
setForm((current) => ({ ...current, role: event.target.value as ManagedUser['role'] }))
}
> >
<option value="viewer">观察者</option> <option value="viewer">观察者</option>
<option value="engineer">知识工程师</option> <option value="engineer">知识工程师</option>
<option value="admin">管理员</option> <option value="admin">管理员</option>
</select> </select>
</label> </label>
<label> <label className="member-drawer-field" htmlFor="member-new-password">
初始密码(≥8 位,首登强制修改) <span>初始密码</span>
<PasswordInput <PasswordInput
id="member-new-password"
value={form.password} value={form.password}
autoComplete="new-password" autoComplete="new-password"
onChange={(event) => setForm((current) => ({ ...current, password: event.target.value }))} maxLength={128}
aria-invalid={Boolean(fieldErrors.password)}
aria-describedby="member-new-password-note"
onChange={(event) => patchForm({ password: event.target.value })}
/> />
<small
id="member-new-password-note"
className={fieldErrors.password ? 'member-drawer-error' : 'member-drawer-hint'}
role={fieldErrors.password ? 'alert' : undefined}
>
{fieldErrors.password ?? '至少 8 位,首次登录强制修改'}
</small>
</label> </label>
<button type="button" disabled={!formValid || busy === 'create'} onClick={() => void create()}> </div>
新增成员 <div className="member-drawer-actions">
<button type="button" className="secondary-action" disabled={busy === 'create'} onClick={requestClose}>
取消
</button>
<button type="submit" className="primary" disabled={busy === 'create'}>
{busy === 'create' ? '创建中…' : '新增成员'}
</button> </button>
</div> </div>
<small>停用不会删除任何业务记录,只禁止登录并立即撤销其在线会话。</small> </form>
</aside>
</div>
) : null}
{resetTarget ? ( {resetTarget ? (
<div className="member-reset-dialog" role="dialog" aria-modal="true" aria-label="重置临时密码"> <div className="member-reset-dialog" role="dialog" aria-modal="true" aria-label="重置临时密码">
<h3>重置 {resetTarget.username} 的临时密码</h3> <h3>重置 {resetTarget.username} 的临时密码</h3>
+280
View File
@@ -0,0 +1,280 @@
// @vitest-environment jsdom
import { act } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { StorageBackupSummary } from './StorageBackupSummary'
import type { BackupInventory, BackupInventoryBatch } from './backupInventory'
import type { LibraryStorage } from './librarySnapshots'
const GIB = 1024 ** 3
const TB = 1024 * GIB
const batch = (index: number, overrides: Partial<BackupInventoryBatch> = {}): BackupInventoryBatch => {
const stamp = `202611${String(24 - Math.floor(index / 24)).padStart(2, '0')}T${String(index % 24).padStart(2, '0')}0000Z`
const created = `2026-11-${String(24 - Math.floor(index / 24)).padStart(2, '0')}T${String(index % 24).padStart(2, '0')}:00:00Z`
return {
stamp,
path: `/srv/kb-backups/rds-logical/${stamp}`,
host_path: `/srv/kb-backups/rds-logical/${stamp}`,
manifest_state: 'ok',
manifest_path: `/srv/kb-backups/rds-logical/${stamp}/MANIFEST.json`,
kind: 'rds',
created_at: created,
started_at: created,
duration_seconds: 240,
manifest_total_bytes: 10 * GIB,
apparent_bytes: 10 * GIB,
actual_bytes: 9 * GIB,
file_count: 120,
sizes_complete: true,
databases: [
{
name: 'weknora',
dir_name: 'weknora.dir',
path: `/srv/kb-backups/rds-logical/${stamp}/weknora.dir`,
host_path: `/srv/kb-backups/rds-logical/${stamp}/weknora.dir`,
present: true,
failed: false,
in_manifest: true,
apparent_bytes: 10 * GIB,
actual_bytes: 9 * GIB,
file_count: 120,
},
],
...overrides,
}
}
const inventory = (overrides: Partial<BackupInventory> = {}): BackupInventory => ({
wired: true,
metadata: {
configured: true,
present: true,
valid: true,
fresh: true,
complete: true,
path: '/var/lib/kb-backups/metadata.json',
collected_at: '2026-11-24T10:17:00Z',
age_seconds: 60,
max_age_seconds: 900,
schema_version: 1,
generation: 'g-1',
host: 'backup-host',
collector_version: '1',
error: '',
},
root: '/srv/kb-backups/rds-logical',
host_root: '/srv/kb-backups/rds-logical',
source: 'host',
observed_at: '2026-11-24T10:18:00Z',
measurement: 'host-reported',
mount: {
container_root: '',
mount_verified: true,
lives_on_container_root: false,
read_only: true,
evidence: '',
mount_point: '/srv/kb-backups',
device: '/dev/sdb1',
fs_type: 'ext4',
},
capacity: {
measured: true,
total_bytes: 2 * TB,
free_bytes: 1.2 * TB,
available_bytes: 1.2 * TB,
used_bytes: 0.8 * TB,
},
batches: [batch(0), batch(1, { manifest_state: 'invalid' })],
totals: {
batch_count: 2,
database_count: 2,
apparent_bytes: 20 * GIB,
actual_bytes: 18 * GIB,
latest_stamp: '20261124T000000Z',
latest_actual_bytes: 9 * GIB,
complete: true,
},
incomplete_count: 0,
skipped: [],
truncated: false,
...overrides,
})
const archive: LibraryStorage = {
available: true,
archive_root: '/var/lib/knowledge-governance/library',
versions: [],
content_bytes: 41_231_686_042,
blob_file_bytes: 0,
blob_allocated_bytes: 0,
unreferenced_blobs: 0,
unreferenced_bytes: 0,
manifest_file_bytes: 0,
policy: { keep_versions: 0, keep_days: 0 },
capacity: {
budget_bytes: 100 * GIB,
current_bytes: 41_231_686_042,
required_bytes: 0,
projected_bytes: 41_231_686_042,
configured: true,
ok: true,
},
automatic_cleanup: false,
notes: [],
}
let root: Root
let container: HTMLDivElement
let fetcher: ReturnType<typeof vi.fn<(path: string, init?: RequestInit) => Promise<Response>>>
const paths = (): string[] => fetcher.mock.calls.map((call) => String(call[0]))
const flush = async () => {
await act(async () => {
await Promise.resolve()
await Promise.resolve()
})
}
beforeEach(() => {
container = document.createElement('div')
document.body.append(container)
root = createRoot(container)
fetcher = vi.fn(async (path: string) => {
if (path.endsWith('/inventory')) {
return new Response(JSON.stringify({ data: inventory() }), { status: 200 })
}
return new Response(JSON.stringify(archive), { status: 200 })
})
vi.stubGlobal('fetch', fetcher)
})
afterEach(() => {
act(() => root.unmount())
container.remove()
vi.unstubAllGlobals()
vi.useRealTimers()
})
describe('StorageBackupSummary', () => {
it('renders directory, recent outcomes, archive usage, disk and the alert table', async () => {
act(() => root.render(<StorageBackupSummary />))
await flush()
const text = container.textContent || ''
expect(text).toContain('备份目录')
expect(text).toContain('/srv/kb-backups/rds-logical')
expect(text).toContain('最近成功')
expect(text).toContain('最近失败')
expect(text).toContain('归档占用')
expect(text).toContain('38.4 GB')
expect(text).toContain('配额 100 GB')
expect(text).toContain('磁盘剩余')
expect(text).toContain('1.2 TB')
expect(text).toContain('上次上报')
expect(text).toContain('清单损坏')
expect(container.querySelectorAll('tbody tr')).toHaveLength(2)
expect(container.querySelectorAll('.storage-alerts li')).toHaveLength(4)
expect(text).not.toContain('无法判定')
expect(text).not.toContain('未接线')
expect(text).not.toContain('示例')
})
it('asks for both read-only endpoints and refreshes once per 60 seconds while visible', async () => {
vi.useFakeTimers()
act(() => root.render(<StorageBackupSummary />))
await flush()
expect(paths().filter((path) => path.endsWith('/inventory'))).toHaveLength(1)
expect(paths().filter((path) => path.endsWith('/library/storage'))).toHaveLength(1)
await act(async () => {
await vi.advanceTimersByTimeAsync(60_000)
})
await flush()
expect(paths().filter((path) => path.endsWith('/inventory'))).toHaveLength(2)
Object.defineProperty(document, 'visibilityState', { value: 'hidden', configurable: true })
await act(async () => {
await vi.advanceTimersByTimeAsync(60_000)
})
await flush()
expect(paths().filter((path) => path.endsWith('/inventory'))).toHaveLength(2)
Object.defineProperty(document, 'visibilityState', { value: 'visible', configurable: true })
})
it('shows 主机未上报 with the last report time and no zero placeholders when the host is unwired', async () => {
fetcher.mockImplementation(async (path: string) => {
if (path.endsWith('/inventory')) {
const wired = inventory()
return new Response(
JSON.stringify({
data: {
...wired,
wired: false,
root: '',
host_root: '',
batches: [],
capacity: { measured: false, total_bytes: 0, free_bytes: 0, available_bytes: 0, used_bytes: 0 },
metadata: { ...wired.metadata, present: false, valid: false, fresh: false, collected_at: '' },
},
}),
{ status: 200 }
)
}
return new Response(
JSON.stringify({ ...archive, available: false, capacity: { ...archive.capacity, configured: false } }),
{
status: 200,
}
)
})
act(() => root.render(<StorageBackupSummary />))
await flush()
const text = container.textContent || ''
expect(text).toContain('主机未上报')
expect(text).toContain('上次上报 —')
expect(text).toContain('未接入宿主上报')
expect(text).not.toContain('0 B')
expect(text).not.toContain('0 GB')
expect(container.querySelectorAll('tbody tr')).toHaveLength(0)
expect(text).toContain('主机未上报(上次上报 —)')
})
it('copies a path once the browser grants clipboard access', async () => {
const writeText = vi.fn().mockResolvedValue(undefined)
Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true })
act(() => root.render(<StorageBackupSummary />))
await flush()
const button = container.querySelector<HTMLButtonElement>('button[aria-label="复制备份目录"]')
expect(button).not.toBeNull()
await act(async () => {
button!.click()
await Promise.resolve()
})
expect(writeText).toHaveBeenCalledWith('/srv/kb-backups/rds-logical')
expect(button!.textContent).toBe('已复制')
})
it('pages long batch lists 20 at a time', async () => {
fetcher.mockImplementation(async (path: string) => {
if (path.endsWith('/inventory')) {
const batches = Array.from({ length: 25 }, (_, index) => batch(index))
return new Response(
JSON.stringify({ data: { ...inventory(), batches, totals: { ...inventory().totals, batch_count: 25 } } }),
{ status: 200 }
)
}
return new Response(JSON.stringify(archive), { status: 200 })
})
act(() => root.render(<StorageBackupSummary />))
await flush()
expect(container.querySelectorAll('tbody tr')).toHaveLength(20)
const more = container.querySelector<HTMLButtonElement>('.storage-more')
expect(more?.textContent).toContain('剩余 5 个')
await act(async () => {
more!.click()
})
expect(container.querySelectorAll('tbody tr')).toHaveLength(25)
expect(container.querySelector('.storage-more')).toBeNull()
})
})
+271
View File
@@ -0,0 +1,271 @@
// 「系统设置 → 存储与备份」只读摘要页:目录、最近成功/失败、归档占用、磁盘剩余、
// 四条容量告警和批次列表。数据只来自宿主每 5 分钟上报的快照与归档库接口,
// 本页没有任何写操作;读不到的量显示"主机未上报"或"—",不用 0 占位。
import { useCallback, useEffect, useRef, useState } from 'react'
import { fetchBackupInventory } from './backupInventory'
import type { BackupInventory } from './backupInventory'
import { fetchLibraryStorage } from './librarySnapshots'
import type { LibraryStorage } from './librarySnapshots'
import {
UNKNOWN,
batchOutcome,
batchWhen,
formatSize,
formatWhen,
hostState,
hostValueLabel,
pendingAlertCount,
storageAlerts,
summaryCards,
} from './storageSummary'
import type { HostState } from './storageSummary'
import './storageBackup.css'
export const REFRESH_INTERVAL_MS = 60_000
const BATCH_PAGE = 20
export async function copyText(value: string): Promise<boolean> {
if (!value) return false
try {
await navigator.clipboard.writeText(value)
return true
} catch {
// 内网 http 页面没有 clipboard 权限时退回选中,不谎报"已复制"。
const area = document.createElement('textarea')
area.value = value
area.setAttribute('readonly', '')
area.style.position = 'fixed'
area.style.opacity = '0'
document.body.append(area)
area.focus()
area.select()
const copied = document.execCommand('copy')
area.remove()
return copied
}
}
const hostStateLabel = (state: HostState): string => {
switch (state) {
case 'unwired':
return '未接入宿主上报'
case 'missing':
return '尚无上报表'
case 'stale':
return '上次上报已过期'
case 'invalid':
return '上次上报不可用'
case 'incomplete':
return '本次上报不完整'
default:
return ''
}
}
export function StorageBackupSummary() {
const [inventory, setInventory] = useState<BackupInventory | null>(null)
const [archive, setArchive] = useState<LibraryStorage | null>(null)
const [archiveFailed, setArchiveFailed] = useState(false)
const [errors, setErrors] = useState<string[]>([])
const [loading, setLoading] = useState(true)
const [visible, setVisible] = useState(BATCH_PAGE)
const [copied, setCopied] = useState('')
const inFlight = useRef(false)
const copiedTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)
const load = useCallback(async () => {
if (inFlight.current) return
inFlight.current = true
const [inventoryResult, archiveResult] = await Promise.allSettled([fetchBackupInventory(), fetchLibraryStorage()])
const nextErrors: string[] = []
if (inventoryResult.status === 'fulfilled') {
setInventory(inventoryResult.value)
} else {
nextErrors.push(inventoryResult.reason instanceof Error ? inventoryResult.reason.message : '读取备份元数据失败')
}
if (archiveResult.status === 'fulfilled') {
setArchive(archiveResult.value)
setArchiveFailed(archiveResult.value === null)
if (archiveResult.value === null) nextErrors.push('读取归档占用失败')
} else {
setArchiveFailed(true)
nextErrors.push(archiveResult.reason instanceof Error ? archiveResult.reason.message : '读取归档占用失败')
}
setErrors(nextErrors)
setLoading(false)
inFlight.current = false
}, [])
useEffect(() => {
void load()
const timer = setInterval(() => {
if (document.visibilityState === 'hidden') return
void load()
}, REFRESH_INTERVAL_MS)
return () => {
clearInterval(timer)
clearTimeout(copiedTimer.current)
}
}, [load])
const state = hostState(inventory)
const alerts = storageAlerts(inventory, archive, archiveFailed)
const cards = summaryCards(inventory, archive, archiveFailed)
const batches = inventory?.batches ?? []
const shown = batches.slice(0, visible)
const handleCopy = (key: string, value: string) => {
void copyText(value).then((ok) => {
if (!ok) return
setCopied(key)
clearTimeout(copiedTimer.current)
copiedTimer.current = setTimeout(() => setCopied(''), 2000)
})
}
const lastReport = formatWhen(inventory?.metadata.collected_at)
const stateNote = hostStateLabel(state)
return (
<section className="settings-panel storage-summary" aria-label="存储与备份">
<header className="storage-summary-head">
<div>
<h2>存储与备份</h2>
{stateNote ? <p className="storage-summary-state">{stateNote}</p> : null}
</div>
<div className="storage-summary-meta">
<span>上次上报 {lastReport || UNKNOWN}</span>
<button type="button" className="storage-refresh" onClick={() => void load()} disabled={loading}>
刷新
</button>
</div>
</header>
{errors.length > 0 ? (
<p className="storage-summary-error" role="alert">
{errors.join(';')}
</p>
) : null}
{loading ? (
<p className="storage-summary-loading">正在读取存储与备份…</p>
) : (
<>
<div className="storage-cards">
{cards.map((card) => (
<div className={card.key === 'root' ? 'storage-card storage-card-root' : 'storage-card'} key={card.key}>
<span className="storage-card-label">{card.label}</span>
<span className={card.unknown ? 'storage-card-value is-unknown' : 'storage-card-value'}>
{card.value}
</span>
<span className="storage-card-note">
{card.note}
{card.copy ? (
<button
type="button"
className="storage-copy"
onClick={() => handleCopy(card.key, card.copy!)}
aria-label={`复制${card.label}`}
>
{copied === card.key ? '已复制' : '复制'}
</button>
) : null}
</span>
</div>
))}
</div>
<section className="storage-alerts" aria-label="容量告警">
<header>
<h3>容量告警</h3>
<span
className={pendingAlertCount(alerts) > 0 ? 'storage-alert-count is-pending' : 'storage-alert-count'}
>
{pendingAlertCount(alerts)} 项需处理
</span>
</header>
<ul>
{alerts.map((alert) => (
<li key={alert.key} data-tone={alert.tone}>
<span className="storage-alert-label">{alert.label}</span>
<span className="storage-alert-value">{alert.value}</span>
<span className="storage-alert-conclusion" data-tone={alert.tone}>
{alert.conclusion}
</span>
</li>
))}
</ul>
</section>
<section className="storage-batches" aria-label="备份批次">
<header>
<h3>备份批次</h3>
<span>{batches.length > 0 ? `共 ${batches.length} 个` : ''}</span>
</header>
{batches.length === 0 ? (
<p className="storage-batches-empty">
{state === 'ready' || state === 'incomplete'
? '暂无批次'
: `${hostValueLabel(state)}(上次上报 ${lastReport || UNKNOWN})`}
</p>
) : (
<table>
<thead>
<tr>
<th>时间</th>
<th>结果</th>
<th>大小</th>
<th>批次</th>
<th>路径</th>
<th aria-label="复制" />
</tr>
</thead>
<tbody>
{shown.map((batch) => {
const outcome = batchOutcome(batch)
return (
<tr key={batch.stamp}>
<td className="storage-batch-time">{batchWhen(batch)}</td>
<td>
<span
className={outcome.failed ? 'storage-batch-result is-failed' : 'storage-batch-result is-ok'}
>
{outcome.failed ? '失败' : '成功'}
</span>
{outcome.reasons.length > 0 ? (
<p className="storage-batch-reason">{outcome.reasons.join(';')}</p>
) : null}
</td>
<td className="storage-batch-size">{formatSize(batch.actual_bytes)}</td>
<td className="storage-batch-stamp">{batch.stamp}</td>
<td className="storage-batch-path" title={batch.path}>
<span>{batch.path}</span>
</td>
<td>
<button
type="button"
className="storage-copy"
onClick={() => handleCopy(batch.stamp, batch.path)}
aria-label={`复制路径 ${batch.stamp}`}
>
{copied === batch.stamp ? '已复制' : '复制'}
</button>
</td>
</tr>
)
})}
</tbody>
</table>
)}
{visible < batches.length ? (
<button type="button" className="storage-more" onClick={() => setVisible((value) => value + BATCH_PAGE)}>
加载更多(剩余 {batches.length - visible} 个)
</button>
) : null}
</section>
</>
)}
</section>
)
}
+2 -2
View File
@@ -256,9 +256,9 @@ describe('SystemSettingsView', () => {
initialSection="storage" initialSection="storage"
/> />
) )
// 存储与备份分区已换成真实功能(整库逻辑备份的定时计划),静态占位文案不再存在。 // 存储与备份分区是只读摘要页:SSR 先给加载态,静态占位文案不再存在。
expect(storageHtml).toContain('存储与备份') expect(storageHtml).toContain('存储与备份')
expect(storageHtml).toContain('正在读取备份计划…') expect(storageHtml).toContain('正在读取存储与备份…')
expect(storageHtml).not.toContain('仅保存凭据引用,不可回读') expect(storageHtml).not.toContain('仅保存凭据引用,不可回读')
const refreshHtml = renderToStaticMarkup( const refreshHtml = renderToStaticMarkup(
<SystemSettingsView <SystemSettingsView
+2 -8
View File
@@ -1,7 +1,6 @@
import { useCallback, useEffect, useState } from 'react' import { useCallback, useEffect, useState } from 'react'
import { BackupScheduleSection } from './BackupScheduleSection' import { StorageBackupSummary } from './StorageBackupSummary'
import { LibraryStorageSection } from './LibraryStorageSection'
import { QAModelSettings } from './QAModelSettings' import { QAModelSettings } from './QAModelSettings'
import { MembersSection } from './MembersSection' import { MembersSection } from './MembersSection'
import { DingtalkAccountStatus, SourceManagementDetails, SourceSettingsCard } from './SourceManagement' import { DingtalkAccountStatus, SourceManagementDetails, SourceSettingsCard } from './SourceManagement'
@@ -242,12 +241,7 @@ export function SystemSettingsView({
</details> </details>
</> </>
) : null} ) : null}
{section === 'storage' ? ( {section === 'storage' ? <StorageBackupSummary /> : null}
<>
<BackupScheduleSection />
<LibraryStorageSection />
</>
) : null}
{section === 'members' && identity?.role === 'admin' ? <MembersSection /> : null} {section === 'members' && identity?.role === 'admin' ? <MembersSection /> : null}
{section === 'refresh' && settings ? ( {section === 'refresh' && settings ? (
<section className="settings-panel wide" id="settings-refresh"> <section className="settings-panel wide" id="settings-refresh">
-87
View File
@@ -1,87 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { fetchBackupSchedule, fetchBackupScheduleHost, runBackupNow, saveBackupSchedule } from './backupSchedule'
const payload = {
enabled: true,
schedule_time: '03:30',
retention_days: 7,
retention_months: 3,
updated_by: 'yaozhanghao',
updated_at: '2026-10-09T12:00:00Z',
last_applied_at: '',
last_applied_summary: '',
host_configured: true,
host_target: 'weknora-test',
host_reachable: true,
host_error: '',
host_schedule_enabled: true,
host_schedule_time: '03:30',
host_keep_days: 7,
host_keep_months: 3,
host_cron_lines: ['30 03 * * * root …'],
host_cron_service: 'active',
host_script_present: true,
last_run_stamp: '20261009T052909Z',
last_run_created_at: '2026-10-09T05:29:09Z',
last_run_duration_seconds: 33,
last_run_total_bytes: 778502144,
last_run_databases: ['weknora_test'],
last_run_failed_databases: [],
last_run_error: '',
in_sync: true,
applied: true,
apply_error: '',
running: false,
running_started_at: '',
run_last_error: '',
}
const jsonResponse = (body: unknown, status = 200) =>
new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } })
afterEach(() => {
vi.unstubAllGlobals()
})
describe('backupSchedule 客户端', () => {
it('解析计划三要素与主机回执', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async () => jsonResponse({ data: payload }))
)
const schedule = await fetchBackupSchedule()
expect(schedule.schedule_time).toBe('03:30')
expect(schedule.retention_days).toBe(7)
expect(schedule.host_cron_lines).toHaveLength(1)
expect(schedule.last_run_failed_databases).toEqual([])
})
it('缺计划字段就报错,绝不把默认值伪装成真实设置', async () => {
const broken = { ...payload } as Record<string, unknown>
delete broken.retention_days
vi.stubGlobal(
'fetch',
vi.fn(async () => jsonResponse({ data: broken }))
)
await expect(fetchBackupScheduleHost()).rejects.toThrow('存储与备份响应缺少计划字段')
})
it('保存失败时把后端的中文原因透出来', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async () => jsonResponse({ error: '储存天数需在 1~365 之间,收到 0' }, 400))
)
await expect(
saveBackupSchedule({ enabled: true, schedule_time: '03:30', retention_days: 0, retention_months: 3 })
).rejects.toThrow('储存天数需在 1~365 之间,收到 0')
})
it('立即备份返回 202 时识别为已启动', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async () => jsonResponse({ data: { started: true, running: true } }, 202))
)
await expect(runBackupNow()).resolves.toEqual({ started: true, running: true })
})
})
-187
View File
@@ -1,187 +0,0 @@
import { newOperationID } from './operationKey'
// 「系统设置 → 存储与备份」:整库逻辑备份的定时计划(时间 + 储存天数)与主机回执。
export interface BackupSchedule {
enabled: boolean
schedule_time: string
retention_days: number
retention_months: number
updated_by: string
updated_at: string
last_applied_at: string
last_applied_summary: string
host_configured: boolean
host_target: string
// host_endpoint 是这条别名真实拨号的 host:port(来自挂载的 ssh 配置)。
host_endpoint: string
host_reachable: boolean
host_error: string
host_schedule_enabled: boolean
host_schedule_time: string
// 主机若没有返回真实 next-run,保持空串;页面不得用历史下发时间推算。
host_next_run?: string
host_checked_at?: string
host_keep_days: number
host_keep_months: number
host_cron_lines: string[]
host_cron_service: string
host_script_present: boolean
last_run_stamp: string
last_run_created_at: string
last_run_duration_seconds: number
last_run_total_bytes: number
last_run_databases: string[]
last_run_failed_databases: string[]
last_run_error: string
in_sync: boolean
applied: boolean
apply_error: string
running: boolean
running_started_at: string
run_last_error: string
}
export interface BackupRunStart {
started: boolean
running: boolean
}
const record = (value: unknown): value is Record<string, unknown> =>
Boolean(value) && typeof value === 'object' && !Array.isArray(value)
const asString = (value: unknown): string => (typeof value === 'string' ? value : '')
const asNumber = (value: unknown): number => (typeof value === 'number' && Number.isFinite(value) ? value : 0)
const asStringList = (value: unknown): string[] =>
Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : []
// 严格解析:计划三要素(时间/天数/月数)必须是正确类型,缺一个就整块报错,
// 而不是让界面显示成"默认 03:30 / 7 天"这种假状态。
function scheduleProjection(item: Record<string, unknown>): BackupSchedule {
if (
typeof item.schedule_time !== 'string' ||
typeof item.retention_days !== 'number' ||
typeof item.retention_months !== 'number'
) {
throw new Error('存储与备份响应缺少计划字段(schedule_time / retention_days / retention_months)')
}
return {
enabled: item.enabled === true,
schedule_time: item.schedule_time,
retention_days: item.retention_days,
retention_months: item.retention_months,
updated_by: asString(item.updated_by),
updated_at: asString(item.updated_at),
last_applied_at: asString(item.last_applied_at),
last_applied_summary: asString(item.last_applied_summary),
host_configured: item.host_configured === true,
host_target: asString(item.host_target),
host_endpoint: asString(item.host_endpoint),
host_reachable: item.host_reachable === true,
host_error: asString(item.host_error),
host_schedule_enabled: item.host_schedule_enabled === true,
host_schedule_time: asString(item.host_schedule_time),
host_next_run: asString(item.host_next_run),
host_checked_at: asString(item.host_checked_at),
host_keep_days: asNumber(item.host_keep_days),
host_keep_months: asNumber(item.host_keep_months),
host_cron_lines: asStringList(item.host_cron_lines),
host_cron_service: asString(item.host_cron_service),
host_script_present: item.host_script_present === true,
last_run_stamp: asString(item.last_run_stamp),
last_run_created_at: asString(item.last_run_created_at),
last_run_duration_seconds: asNumber(item.last_run_duration_seconds),
last_run_total_bytes: asNumber(item.last_run_total_bytes),
last_run_databases: asStringList(item.last_run_databases),
last_run_failed_databases: asStringList(item.last_run_failed_databases),
last_run_error: asString(item.last_run_error),
in_sync: item.in_sync === true,
applied: item.applied === true,
apply_error: asString(item.apply_error),
running: item.running === true,
running_started_at: asString(item.running_started_at),
run_last_error: asString(item.run_last_error),
}
}
async function readSchedule(path: string, failure: string, signal?: AbortSignal): Promise<BackupSchedule> {
const response = await fetch(path, { signal, headers: { Accept: 'application/json' } })
if (!response.ok) throw new Error(`${failure}(HTTP ${response.status})`)
const value = (await response.json()) as unknown
if (!record(value) || !record(value.data)) throw new Error('存储与备份响应无效')
return scheduleProjection(value.data)
}
export function fetchBackupSchedule(signal?: AbortSignal): Promise<BackupSchedule> {
return readSchedule('/api/v1/backup-schedule', '读取备份计划失败', signal)
}
// host 端点会 SSH 探测目标主机(计划 + 最近一次结果),单独调用以免拖慢首屏。
export function fetchBackupScheduleHost(signal?: AbortSignal): Promise<BackupSchedule> {
return readSchedule('/api/v1/backup-schedule/host', '读取目标主机上的备份状态失败', signal)
}
async function writeSchedule(
path: string,
method: string,
body: unknown,
failure: string,
signal?: AbortSignal
): Promise<BackupSchedule> {
const response = await fetch(path, {
method,
signal,
headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'Idempotency-Key': newOperationID() },
body: body === undefined ? undefined : JSON.stringify(body),
})
if (!response.ok) {
let reason = `${failure}(HTTP ${response.status})`
try {
const payload = (await response.json()) as unknown
if (record(payload) && typeof payload.error === 'string') reason = payload.error
} catch {
/* keep the status text */
}
throw new Error(reason)
}
const value = (await response.json()) as unknown
if (!record(value) || !record(value.data)) throw new Error('存储与备份响应无效')
return scheduleProjection(value.data)
}
export interface BackupScheduleInput {
enabled: boolean
schedule_time: string
retention_days: number
retention_months: number
// 默认 true:保存后立刻下发到目标主机(页面按钮"保存并下发")。
apply?: boolean
}
export function saveBackupSchedule(input: BackupScheduleInput, signal?: AbortSignal): Promise<BackupSchedule> {
return writeSchedule('/api/v1/backup-schedule', 'PUT', input, '保存备份计划失败', signal)
}
export function applyBackupSchedule(signal?: AbortSignal): Promise<BackupSchedule> {
return writeSchedule('/api/v1/backup-schedule/apply', 'POST', undefined, '下发备份计划失败', signal)
}
export async function runBackupNow(signal?: AbortSignal): Promise<BackupRunStart> {
const response = await fetch('/api/v1/backup-schedule/run', {
method: 'POST',
signal,
headers: { Accept: 'application/json', 'Idempotency-Key': newOperationID() },
})
if (!response.ok) {
let reason = `触发备份失败(HTTP ${response.status})`
try {
const payload = (await response.json()) as unknown
if (record(payload) && typeof payload.error === 'string') reason = payload.error
} catch {
/* keep the status text */
}
throw new Error(reason)
}
const value = (await response.json()) as unknown
if (!record(value) || !record(value.data)) throw new Error('触发备份响应无效')
return { started: value.data.started === true, running: value.data.running === true }
}
+20
View File
@@ -39,11 +39,13 @@ describe('knowledgeBaseBindings', () => {
data: { data: {
environments: [binding('test'), binding('production')], environments: [binding('test'), binding('production')],
storage_ready: true, storage_ready: true,
secret_entry_allowed: true,
}, },
}) })
expect(parsed.test.base_url).toBe('https://test.example') expect(parsed.test.base_url).toBe('https://test.example')
expect(parsed.production.internal_kb_name).toBe('内部资料') expect(parsed.production.internal_kb_name).toBe('内部资料')
expect(parsed.storage_ready).toBe(true) expect(parsed.storage_ready).toBe(true)
expect(parsed.secret_entry_allowed).toBe(true)
const asRecord = parsed.test as unknown as Record<string, unknown> const asRecord = parsed.test as unknown as Record<string, unknown>
expect(asRecord.api_key).toBeUndefined() expect(asRecord.api_key).toBeUndefined()
expect(asRecord.key_ciphertext).toBeUndefined() expect(asRecord.key_ciphertext).toBeUndefined()
@@ -53,6 +55,24 @@ describe('knowledgeBaseBindings', () => {
expect(() => parseKBBindingSnapshot({ data: { environments: [binding('test')], storage_ready: true } })).toThrow() expect(() => parseKBBindingSnapshot({ data: { environments: [binding('test')], storage_ready: true } })).toThrow()
}) })
it('leaves the capability absent when an older API does not report it', () => {
const parsed = parseKBBindingSnapshot({
data: { environments: [binding('test'), binding('production')], storage_ready: true },
})
expect(parsed.secret_entry_allowed).toBeUndefined()
})
it('keeps an explicit refusal distinguishable from a missing field', () => {
const parsed = parseKBBindingSnapshot({
data: {
environments: [binding('test'), binding('production')],
storage_ready: true,
secret_entry_allowed: false,
},
})
expect(parsed.secret_entry_allowed).toBe(false)
})
it('shows a short id next to the name so same-name bases are distinguishable', () => { it('shows a short id next to the name so same-name bases are distinguishable', () => {
expect(shortKnowledgeBaseID('0b217e8a-1234-5678')).toBe('0b217e8a…') expect(shortKnowledgeBaseID('0b217e8a-1234-5678')).toBe('0b217e8a…')
expect(knowledgeBaseLabel('0b217e8a-1234-5678', '客户帮助中心')).toBe('客户帮助中心(0b217e8a…)') expect(knowledgeBaseLabel('0b217e8a-1234-5678', '客户帮助中心')).toBe('客户帮助中心(0b217e8a…)')
+10 -1
View File
@@ -34,6 +34,9 @@ export interface KBBindingSnapshot {
test: KBEnvironmentBinding test: KBEnvironmentBinding
production: KBEnvironmentBinding production: KBEnvironmentBinding
storage_ready: boolean storage_ready: boolean
// Absent stays absent: an older API must not be reported as an untrusted
// proxy, and it must still fail closed for key entry.
secret_entry_allowed?: boolean
} }
export interface KBCatalogOption { export interface KBCatalogOption {
@@ -130,7 +133,13 @@ export function parseKBBindingSnapshot(value: unknown): KBBindingSnapshot {
const test = byEnvironment.get('test') const test = byEnvironment.get('test')
const production = byEnvironment.get('production') const production = byEnvironment.get('production')
if (!test || !production) throw new Error('知识库绑定响应缺少环境') if (!test || !production) throw new Error('知识库绑定响应缺少环境')
return { test, production, storage_ready: bool(value.data.storage_ready) } return {
test,
production,
storage_ready: bool(value.data.storage_ready),
secret_entry_allowed:
typeof value.data.secret_entry_allowed === 'boolean' ? value.data.secret_entry_allowed : undefined,
}
} }
// 名称相同是常见情况,短 ID 是唯一可辨的部分;两处都显示,不靠名称猜。 // 名称相同是常见情况,短 ID 是唯一可辨的部分;两处都显示,不靠名称猜。
-99
View File
@@ -1,99 +0,0 @@
.library-storage {
border: 1px solid var(--border-base, #e2e8f0);
border-radius: 10px;
padding: 16px 18px;
margin-bottom: 18px;
background: #fff;
}
.library-storage header h3 {
margin: 0 0 4px;
font-size: 16px;
}
.library-storage header p {
margin: 0 0 12px;
font-size: 12px;
color: var(--ink-mute, #64748b);
line-height: 1.6;
}
.library-storage-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
gap: 10px;
margin: 0 0 12px;
}
.library-storage-grid div {
border: 1px solid #e6edf2;
border-radius: 8px;
padding: 9px 11px;
}
.library-storage-grid dt {
font-size: 11px;
color: var(--ink-mute, #64748b);
}
.library-storage-grid dd {
margin: 3px 0 0;
font-size: 16px;
font-variant-numeric: tabular-nums;
}
.library-storage-limits {
margin: 0;
padding-left: 18px;
font-size: 12px;
color: #986b24;
line-height: 1.8;
}
.library-storage-hint {
margin: 0;
font-size: 12px;
color: var(--ink-mute, #64748b);
}
.library-storage-blocked {
border: 1px solid #f3c2b8;
background: #fff6f3;
border-radius: 8px;
padding: 10px 12px;
margin-bottom: 10px;
}
.library-storage-blocked strong {
display: block;
font-size: 12px;
color: #a03a1e;
}
.library-storage-blocked p {
margin: 2px 0 0;
font-size: 12px;
color: #7c2d12;
}
.library-storage-panel {
border: 1px solid #e6edf2;
border-radius: 8px;
padding: 10px 12px;
margin-bottom: 10px;
}
.library-storage-panel h4 {
margin: 0 0 6px;
font-size: 13px;
}
.library-storage-panel p {
margin: 0 0 6px;
font-size: 12px;
line-height: 1.7;
color: #3f5566;
}
.library-storage-warn {
color: #986b24 !important;
}
.library-storage-versions {
margin: 4px 0 0;
padding-left: 18px;
font-size: 12px;
line-height: 1.8;
color: #3f5566;
}
.library-storage-blocked-list {
margin: 4px 0 0;
padding-left: 18px;
font-size: 12px;
color: #a03a1e;
}
+11 -1
View File
@@ -15,6 +15,16 @@ export const managedUserRoles = ['viewer', 'engineer', 'admin'] as const
const record = (value: unknown): value is Record<string, unknown> => const record = (value: unknown): value is Record<string, unknown> =>
Boolean(value) && typeof value === 'object' && !Array.isArray(value) Boolean(value) && typeof value === 'object' && !Array.isArray(value)
export class MembersRequestError extends Error {
readonly status: number
constructor(message: string, status: number) {
super(message)
this.name = 'MembersRequestError'
this.status = status
}
}
function parseUser(raw: unknown): ManagedUser { function parseUser(raw: unknown): ManagedUser {
if ( if (
!record(raw) || !record(raw) ||
@@ -50,7 +60,7 @@ async function call(url: string, init: RequestInit, message: string): Promise<un
}) })
if (!response.ok) { if (!response.ok) {
const payload = (await response.json().catch(() => null)) as { error?: string } | null const payload = (await response.json().catch(() => null)) as { error?: string } | null
throw new Error(payload?.error || `${message}(HTTP ${response.status})`) throw new MembersRequestError(payload?.error || `${message}(HTTP ${response.status})`, response.status)
} }
return response.json() return response.json()
} }
+25
View File
@@ -0,0 +1,25 @@
import { describe, expect, it } from 'vitest'
import { plaintextRemoteConsole, secretEntryAllowed } from './secureEntry'
describe('secureEntry', () => {
it('accepts HTTPS and loopback whatever the deployment toggle says', () => {
for (const location of [
{ protocol: 'https:', hostname: 'kb.example' },
{ protocol: 'http:', hostname: 'localhost' },
{ protocol: 'http:', hostname: '127.0.0.1' },
{ protocol: 'http:', hostname: '[::1]' },
{ protocol: 'http:', hostname: '::1' },
]) {
expect(secretEntryAllowed(location), JSON.stringify(location)).toBe(true)
expect(plaintextRemoteConsole(location)).toBe(false)
}
})
it('treats plain HTTP from any other host as a plaintext network path', () => {
for (const hostname of ['172.29.151.11', '10.0.0.5', 'kb.internal.example', '203.0.113.10']) {
const location = { protocol: 'http:', hostname }
expect(secretEntryAllowed(location), hostname).toBe(false)
expect(plaintextRemoteConsole(location), hostname).toBe(true)
}
})
})
+7
View File
@@ -3,3 +3,10 @@
export function secretEntryAllowed(location: { protocol: string; hostname: string }): boolean { export function secretEntryAllowed(location: { protocol: string; hostname: string }): boolean {
return location.protocol === 'https:' || ['localhost', '127.0.0.1', '[::1]', '::1'].includes(location.hostname) return location.protocol === 'https:' || ['localhost', '127.0.0.1', '[::1]', '::1'].includes(location.hostname)
} }
// True when a key typed here would cross a network in the clear, even though
// the server presently allows it. Drives the warning only, never the gate:
// the gate is the server-reported capability.
export function plaintextRemoteConsole(location: { protocol: string; hostname: string }): boolean {
return !secretEntryAllowed(location)
}
+330 -382
View File
@@ -1,424 +1,372 @@
/* 「系统设置 → 存储与备份」:数据库整库逻辑备份。 /* 存储与备份:只读摘要页。全部颜色走 tokens,状态色沿用全局 fail/warn/done。 */
原型里的单条整盘图与告警在这里保留位置;真实读数未接线时用虚底而不是假容量。 */ .storage-summary {
.storage-settings-panel {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 14px; gap: 18px;
} }
.storage-settings-panel .settings-section-heading p {
.storage-summary-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
flex-wrap: wrap;
}
.storage-summary-head h2 {
margin: 0; margin: 0;
max-width: 78ch; font-size: 16px;
color: var(--ink-mute, #64748b); color: var(--ink-strong);
font-size: 11px;
line-height: 1.7;
} }
/* 主机读回用两栏事实表;窄列时自动落成一栏,避免 dd 把 dt 挤成竖排。 */
.settings-panel .storage-settings-grid { .storage-summary-state {
grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); margin: 4px 0 0;
font-size: 12px;
color: var(--c-warn);
} }
.settings-panel .storage-settings-grid > dl {
grid-template-columns: minmax(104px, max-content) minmax(0, 1fr); .storage-summary-meta {
display: flex;
align-items: center;
gap: 12px;
font-size: 12px;
color: var(--ink-mute);
} }
.storage-settings-panel code {
.storage-refresh,
.storage-more {
border: 1px solid var(--border-strong);
background: var(--bg-panel);
border-radius: 6px;
padding: 5px 12px;
font-size: 12px;
color: var(--ink-base);
cursor: pointer;
}
.storage-refresh:hover,
.storage-more:hover {
background: var(--bg-hover);
}
.storage-refresh:disabled {
color: var(--ink-faint);
cursor: default;
}
.storage-summary-error {
margin: 0;
padding: 8px 12px;
border-radius: 6px;
border: 1px solid var(--c-fail-border);
background: var(--c-fail-bg);
color: var(--c-fail);
font-size: 12px;
}
.storage-summary-loading {
margin: 0;
font-size: 13px;
color: var(--ink-mute);
}
.storage-cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(190px, 1fr));
gap: 12px;
}
.storage-card {
border: 1px solid var(--border-base);
border-radius: 10px;
background: var(--bg-panel);
padding: 14px 16px;
display: flex;
flex-direction: column;
gap: 6px;
min-width: 0;
}
.storage-card-label {
font-size: 12px;
color: var(--ink-mute);
}
.storage-card-value {
font-size: 24px;
font-weight: 600;
line-height: 1.15;
color: var(--ink-strong);
overflow-wrap: anywhere; overflow-wrap: anywhere;
} }
.storage-block {
border-top: 1px solid var(--border-base, #e2e8f0); .storage-card-value.is-unknown {
padding-top: 12px; font-size: 15px;
font-weight: 500;
color: var(--ink-mute);
} }
.storage-block-heading {
/* 备份目录是配置事实而不是指标:独占一行、字号收小,避免长路径撑爆卡片。 */
.storage-card-root {
grid-column: 1 / -1;
}
.storage-card-root .storage-card-value {
font-size: 16px;
line-height: 1.35;
overflow-wrap: anywhere;
}
.storage-card-note {
display: flex;
align-items: center;
gap: 8px;
font-size: 12px;
color: var(--ink-mute);
min-height: 18px;
}
.storage-copy {
border: 1px solid var(--border-base);
background: var(--bg-soft);
border-radius: 5px;
padding: 1px 7px;
font-size: 11px;
color: var(--ink-mute);
cursor: pointer;
flex: none;
}
.storage-copy:hover {
background: var(--bg-hover);
color: var(--ink-base);
}
.storage-alerts,
.storage-batches {
border: 1px solid var(--border-base);
border-radius: 10px;
background: var(--bg-panel);
overflow: hidden;
}
.storage-alerts > header,
.storage-batches > header {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
gap: 8px 14px; gap: 12px;
flex-wrap: wrap; padding: 12px 16px;
margin-bottom: 6px; border-bottom: 1px solid var(--border-soft);
} }
.storage-block-heading h3 {
.storage-alerts h3,
.storage-batches h3 {
margin: 0; margin: 0;
font-size: 13px; font-size: 13px;
color: var(--ink-base); color: var(--ink-strong);
} }
.storage-block-heading button {
font: inherit; .storage-batches > header span,
font-size: 10px; .storage-alert-count {
padding: 3px 9px; font-size: 12px;
border-radius: 5px; color: var(--ink-mute);
border: 1px solid var(--border-base, #cbd5e1);
background: var(--bg-panel, #fff);
color: inherit;
cursor: pointer;
} }
.storage-block-heading button:disabled {
opacity: 0.55; .storage-alert-count.is-pending {
cursor: default; color: var(--c-fail);
font-weight: 600;
} }
.storage-chip {
border-radius: 999px; .storage-alerts ul {
padding: 2px 9px; list-style: none;
font-size: 10px;
border: 1px solid var(--border-base, #e2e8f0);
color: var(--ink-mute, #64748b);
}
.storage-chip.ok {
color: #17695a;
border-color: #a9d5c8;
background: #effaf5;
}
.storage-chip.warn {
color: #985d10;
border-color: #f0d3a4;
background: #fff8ec;
}
.storage-chip.off {
color: var(--ink-mute, #64748b);
background: var(--bg-soft, #f6f8fa);
}
.settings-panel .storage-facts {
display: grid;
grid-template-columns: minmax(96px, max-content) minmax(0, 1fr);
gap: 5px 14px;
margin: 6px 0;
font-size: 11px;
color: var(--ink-mute, #64748b);
}
.settings-panel .storage-facts dd {
margin: 0; margin: 0;
padding: 0;
}
.storage-alerts li {
display: grid;
grid-template-columns: 180px minmax(0, 1fr) 84px;
gap: 12px;
align-items: center;
padding: 10px 16px;
border-bottom: 1px solid var(--border-soft);
font-size: 13px;
}
.storage-alerts li:last-child {
border-bottom: none;
}
.storage-alert-label {
color: var(--ink-base); color: var(--ink-base);
}
.storage-alert-value {
color: var(--ink-mute);
overflow-wrap: anywhere; overflow-wrap: anywhere;
} }
.storage-inline-note {
display: block; .storage-alert-conclusion {
color: var(--ink-mute, #64748b); justify-self: end;
font-size: 10px;
}
.storage-block-actions {
display: flex;
align-items: center;
gap: 8px 12px;
flex-wrap: wrap;
margin: 7px 0;
}
.storage-block-actions .hint {
max-width: 72ch;
}
.storage-block-actions button {
font: inherit;
font-size: 11px;
padding: 5px 11px;
border-radius: 6px;
border: 1px solid var(--border-base, #cbd5e1);
background: var(--bg-panel, #fff);
color: inherit;
cursor: pointer;
}
.storage-block-actions button:disabled {
opacity: 0.55;
cursor: default;
}
.storage-block-actions button.primary {
background: #185f78;
border-color: #185f78;
color: #fff;
}
.storage-progress {
margin: 6px 0;
}
.storage-running {
margin: 0 0 5px;
font-size: 11px;
color: var(--ink-base);
}
.storage-progress-bar {
width: 100%;
height: 10px;
}
.storage-disk-track {
display: flex;
height: 22px;
margin: 8px 0;
border-radius: 5px;
overflow: hidden;
background: #e4e9ef;
outline: 1px solid #aab9c1;
}
.storage-disk-other {
background: #77889a;
}
.storage-disk-zone {
display: flex;
background: #c0dfed;
box-shadow: inset 0 0 0 1px #6191a8;
}
.storage-disk-used {
background: #19698c;
}
.storage-disk-blank {
background: #e4e9ef;
}
.storage-disk-track-unknown {
display: flex;
align-items: center;
justify-content: center;
background: repeating-linear-gradient(45deg, #eef2f5 0 6px, #e1e7eb 6px 12px);
border: 1px dashed #aab9c1;
outline: none;
color: #576674;
font-size: 10px;
}
.storage-disk-low .storage-disk-other {
background: #9d625d;
}
.storage-disk-low .storage-disk-used {
background: #be6c10;
}
.storage-disk-low .storage-disk-zone {
background: #ffe0a8;
}
.storage-disk-legend {
display: flex;
gap: 6px 16px;
flex-wrap: wrap;
font-size: 10px;
color: #3f5566;
}
.storage-dot {
display: inline-block;
width: 10px;
height: 10px;
margin-right: 4px;
border-radius: 2px;
vertical-align: -1px;
}
.storage-dot.other {
background: #77889a;
}
.storage-dot.used {
background: #19698c;
}
.storage-dot.zone {
background: #c0dfed;
}
.storage-dot.blank {
background: #e4e9ef;
outline: 1px solid #c4ced6;
}
.storage-metric {
margin: 6px 0 2px;
font-size: 11px;
font-weight: 600;
}
.storage-manifest {
font-size: 10px;
padding: 1px 7px;
border-radius: 999px; border-radius: 999px;
border: 1px solid var(--border-base, #e2e8f0); padding: 2px 10px;
font-size: 12px;
border: 1px solid var(--border-base);
color: var(--ink-mute);
background: var(--bg-soft);
} }
.storage-manifest.ok {
color: #17695a; .storage-alert-conclusion[data-tone='ok'] {
border-color: #a9d5c8; color: var(--c-done);
background: #effaf5; border-color: var(--c-done-border);
background: var(--c-done-bg);
} }
.storage-manifest.missing,
.storage-manifest.invalid { .storage-alert-conclusion[data-tone='warn'] {
color: #a03a1e; color: var(--c-warn);
border-color: #f3c2b8; border-color: var(--c-warn-border);
background: #fff6f3; background: var(--c-warn-bg);
} }
.storage-path-row {
display: grid; .storage-alert-conclusion[data-tone='bad'] {
grid-template-columns: max-content minmax(0, 1fr) max-content; color: var(--c-fail);
gap: 4px 8px; border-color: var(--c-fail-border);
align-items: center; background: var(--c-fail-bg);
margin: 5px 0;
} }
.storage-path-row small {
color: var(--ink-mute, #64748b); .storage-batches table {
width: 100%;
border-collapse: collapse;
font-size: 12px;
table-layout: fixed;
} }
.storage-path-row code {
font-size: 10px; .storage-batches th {
padding: 3px 6px; text-align: left;
border-radius: 4px; font-weight: 500;
background: var(--bg-soft, #f6f8fa); color: var(--ink-mute);
padding: 8px 16px;
border-bottom: 1px solid var(--border-soft);
}
.storage-batches td {
padding: 10px 16px;
border-bottom: 1px solid var(--border-soft);
vertical-align: top;
color: var(--ink-base);
}
.storage-batches th:nth-child(1),
.storage-batches td:nth-child(1) {
width: 96px;
}
.storage-batches th:nth-child(2),
.storage-batches td:nth-child(2) {
width: 200px;
}
.storage-batches th:nth-child(3),
.storage-batches td:nth-child(3) {
width: 88px;
}
.storage-batches th:nth-child(4),
.storage-batches td:nth-child(4) {
width: 170px;
}
.storage-batches th:nth-child(6),
.storage-batches td:nth-child(6) {
width: 64px;
}
.storage-batch-time,
.storage-batch-stamp {
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.storage-batch-size {
white-space: nowrap;
}
.storage-batch-result {
display: inline-block;
border-radius: 999px;
padding: 1px 9px;
border: 1px solid var(--border-base);
font-size: 11px;
}
.storage-batch-result.is-ok {
color: var(--c-done);
border-color: var(--c-done-border);
background: var(--c-done-bg);
}
.storage-batch-result.is-failed {
color: var(--c-fail);
border-color: var(--c-fail-border);
background: var(--c-fail-bg);
}
.storage-batch-reason {
margin: 4px 0 0;
font-size: 11px;
color: var(--c-fail);
white-space: normal;
overflow-wrap: anywhere; overflow-wrap: anywhere;
} }
.storage-path-row button,
.storage-sublibraries button { /* 长路径中间截断:保留结尾(批次目录名),从开头省略。 */
font: inherit; .storage-batch-path {
font-size: 10px; min-width: 0;
padding: 3px 8px;
border-radius: 5px;
border: 1px solid var(--border-base, #cbd5e1);
background: var(--bg-panel, #fff);
color: inherit;
cursor: pointer;
} }
.storage-path-row button:disabled,
.storage-sublibraries button:disabled { .storage-batch-path > span {
opacity: 0.55; display: block;
cursor: default; direction: rtl;
unicode-bidi: plaintext;
text-align: left;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
color: var(--ink-mute);
} }
.storage-sublibrary-path {
margin: 2px 0 0; .storage-batches-empty {
grid-template-columns: minmax(0, 1fr) max-content; margin: 0;
padding: 24px 16px;
font-size: 13px;
color: var(--ink-mute);
text-align: center;
} }
.storage-alert-summary {
margin: 8px 0 0; .storage-more {
font-size: 11px; display: block;
font-weight: 600; margin: 12px auto;
color: #3f5566;
}
.storage-alerts {
list-style: none;
margin: 8px 0 0;
padding: 0;
display: grid;
gap: 5px;
} }
@media (max-width: 720px) {
.storage-alerts li { .storage-alerts li {
display: grid; grid-template-columns: minmax(0, 1fr) 84px;
grid-template-columns: max-content max-content minmax(0, 1fr);
gap: 4px 10px;
align-items: baseline;
font-size: 10px;
padding: 4px 8px;
border-radius: 6px;
background: var(--bg-soft, #f6f8fa);
} }
.storage-alerts li strong {
font-size: 11px; .storage-alerts .storage-alert-value {
}
.storage-alerts li small {
color: var(--ink-mute, #64748b);
overflow-wrap: anywhere;
}
.storage-alerts .alert-on {
background: #fff1ec;
color: #a03a1e;
}
.storage-alerts .alert-ok {
background: #f0faf6;
color: #17695a;
}
.storage-alerts .alert-unknown {
background: #f8f5ee;
color: #715c2c;
}
.storage-plan {
margin: 4px 0;
font-size: 11px;
color: #3f5566;
}
.storage-policy-editor {
display: flex;
flex-direction: column;
gap: 8px;
margin-top: 6px;
}
.storage-policy-editor > label {
display: grid;
gap: 3px;
font-size: 10px;
color: var(--ink-mute, #64748b);
}
.storage-policy-editor input[type='text'],
.storage-policy-editor input[type='time'],
.storage-policy-editor input[type='number'] {
width: 100%;
max-width: 320px;
font: inherit;
font-size: 11px;
padding: 5px 8px;
border-radius: 5px;
border: 1px solid var(--border-base, #cbd5e1);
background: var(--bg-panel, #fff);
color: inherit;
}
.storage-policy-editor input:disabled {
background: var(--bg-soft, #f1f4f6);
color: var(--ink-mute, #64748b);
}
.storage-checkbox {
display: flex !important;
align-items: center;
gap: 6px;
font-size: 11px !important;
color: var(--ink-base) !important;
}
.storage-policy-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
gap: 8px 12px;
}
.storage-policy-grid label {
display: grid;
gap: 3px;
font-size: 10px;
color: var(--ink-mute, #64748b);
}
.storage-policy-grid input {
width: 100%;
}
.storage-batch {
border: 1px solid var(--border-base, #e2e8f0);
border-radius: 8px;
padding: 8px 10px;
font-size: 11px;
}
.storage-batch summary {
display: flex;
gap: 6px 14px;
flex-wrap: wrap;
align-items: baseline;
cursor: pointer;
}
.storage-batch summary strong.ok {
color: #17695a;
}
.storage-batch summary strong.off {
color: #a03a1e;
}
.storage-batch p {
margin: 6px 0;
color: #3f5566;
}
.storage-sublibraries {
list-style: none;
margin: 6px 0;
padding: 0;
display: grid;
gap: 4px;
}
.storage-sublibraries li {
display: grid;
grid-template-columns: minmax(120px, max-content) max-content minmax(0, 1fr);
gap: 4px 10px;
align-items: baseline;
padding: 3px 6px;
border-radius: 5px;
background: var(--bg-soft, #f6f8fa);
}
.storage-sublibrary-path {
grid-column: 1 / -1; grid-column: 1 / -1;
grid-row: 2;
} }
.storage-sublibraries .ok {
color: #17695a; .storage-batches table {
table-layout: auto;
} }
.storage-sublibraries .off {
color: #a03a1e; .storage-batches th:nth-child(4),
} .storage-batches td:nth-child(4),
.storage-sublibraries small { .storage-batches th:nth-child(5),
color: var(--ink-mute, #64748b); .storage-batches td:nth-child(5) {
} display: none;
.storage-verify {
margin: 6px 0 0;
color: #715c2c;
font-size: 10px;
}
@media (max-width: 700px) {
.storage-facts,
.storage-sublibraries li,
.storage-alerts li {
grid-template-columns: minmax(0, 1fr);
} }
} }
+308
View File
@@ -0,0 +1,308 @@
import { describe, expect, it } from 'vitest'
import type { BackupInventory, BackupInventoryBatch } from './backupInventory'
import type { LibraryStorage } from './librarySnapshots'
import {
DISK_CRITICAL_AVAILABLE_PERCENT,
batchOutcome,
formatSize,
formatWhen,
hostState,
orderedBatches,
pendingAlertCount,
recentOutcome,
storageAlerts,
summaryCards,
} from './storageSummary'
const GIB = 1024 ** 3
const TB = 1024 * GIB
export const batch = (overrides: Partial<BackupInventoryBatch> = {}): BackupInventoryBatch => ({
stamp: '20261124T020000Z',
path: '/srv/kb-backups/rds-logical/20261124T020000Z',
host_path: '/srv/kb-backups/rds-logical/20261124T020000Z',
manifest_state: 'ok',
manifest_path: '/srv/kb-backups/rds-logical/20261124T020000Z/MANIFEST.json',
kind: 'rds',
created_at: '2026-11-24T02:00:00Z',
started_at: '2026-11-24T02:00:00Z',
duration_seconds: 240,
manifest_total_bytes: 10 * GIB,
apparent_bytes: 10 * GIB,
actual_bytes: 9 * GIB,
file_count: 120,
sizes_complete: true,
databases: [
{
name: 'weknora',
dir_name: 'weknora.dir',
path: '/srv/kb-backups/rds-logical/20261124T020000Z/weknora.dir',
host_path: '/srv/kb-backups/rds-logical/20261124T020000Z/weknora.dir',
present: true,
failed: false,
in_manifest: true,
apparent_bytes: 10 * GIB,
actual_bytes: 9 * GIB,
file_count: 120,
},
],
...overrides,
})
export const inventory = (overrides: Partial<BackupInventory> = {}): BackupInventory => ({
wired: true,
metadata: {
configured: true,
present: true,
valid: true,
fresh: true,
complete: true,
path: '/var/lib/kb-backups/metadata.json',
collected_at: '2026-11-24T10:17:00Z',
age_seconds: 60,
max_age_seconds: 900,
schema_version: 1,
generation: 'g-1',
host: 'backup-host',
collector_version: '1',
error: '',
},
root: '/srv/kb-backups/rds-logical',
host_root: '/srv/kb-backups/rds-logical',
source: 'host',
observed_at: '2026-11-24T10:18:00Z',
measurement: 'host-reported',
mount: {
container_root: '',
mount_verified: true,
lives_on_container_root: false,
read_only: true,
evidence: '',
mount_point: '/srv/kb-backups',
device: '/dev/sdb1',
fs_type: 'ext4',
},
capacity: {
measured: true,
total_bytes: 2 * TB,
free_bytes: 1.2 * TB,
available_bytes: 1.2 * TB,
used_bytes: 0.8 * TB,
},
batches: [batch()],
totals: {
batch_count: 1,
database_count: 1,
apparent_bytes: 10 * GIB,
actual_bytes: 9 * GIB,
latest_stamp: '20261124T020000Z',
latest_actual_bytes: 9 * GIB,
complete: true,
},
incomplete_count: 0,
skipped: [],
truncated: false,
...overrides,
})
export const archive = (overrides: Partial<LibraryStorage> = {}): LibraryStorage => ({
available: true,
archive_root: '/var/lib/knowledge-governance/library',
versions: [],
content_bytes: 41_231_686_042,
blob_file_bytes: 0,
blob_allocated_bytes: 0,
unreferenced_blobs: 0,
unreferenced_bytes: 0,
manifest_file_bytes: 0,
policy: { keep_versions: 0, keep_days: 0 },
capacity: {
budget_bytes: 100 * GIB,
current_bytes: 41_231_686_042,
required_bytes: 0,
projected_bytes: 41_231_686_042,
configured: true,
ok: true,
},
automatic_cleanup: false,
notes: [],
...overrides,
})
const unreported = (): BackupInventory =>
inventory({
wired: false,
metadata: {
configured: false,
present: false,
valid: false,
fresh: false,
complete: false,
path: '',
collected_at: '',
age_seconds: 0,
max_age_seconds: 900,
schema_version: 0,
generation: '',
host: '',
collector_version: '',
error: '元数据快照未接线(BACKUP_HOST_METADATA_PATH 未设置)',
},
root: '',
host_root: '',
capacity: { measured: false, total_bytes: 0, free_bytes: 0, available_bytes: 0, used_bytes: 0 },
batches: [],
totals: {
batch_count: 0,
database_count: 0,
apparent_bytes: null,
actual_bytes: null,
latest_stamp: '',
latest_actual_bytes: null,
complete: false,
},
})
describe('formatSize', () => {
it('keeps one decimal below 100 units and never calls an unknown value zero', () => {
expect(formatSize(41_231_686_042)).toBe('38.4 GB')
expect(formatSize(100 * GIB)).toBe('100 GB')
expect(formatSize(1.2 * TB)).toBe('1.2 TB')
expect(formatSize(2 * TB)).toBe('2 TB')
expect(formatSize(0)).toBe('0 B')
expect(formatSize(null)).toBe('—')
expect(formatSize(undefined)).toBe('—')
})
})
describe('hostState', () => {
it('separates unreported, stale, incomplete and ready snapshots', () => {
expect(hostState(null)).toBe('loading')
expect(hostState(unreported())).toBe('unwired')
expect(hostState(inventory({ metadata: { ...inventory().metadata, present: false } }))).toBe('missing')
expect(hostState(inventory({ metadata: { ...inventory().metadata, fresh: false } }))).toBe('stale')
expect(hostState(inventory({ metadata: { ...inventory().metadata, complete: false } }))).toBe('incomplete')
expect(hostState(inventory())).toBe('ready')
})
})
describe('batchOutcome', () => {
it('reports manifest damage and failed databases as failure reasons', () => {
expect(batchOutcome(batch())).toEqual({ failed: false, reasons: [] })
expect(batchOutcome(batch({ manifest_state: 'missing' })).reasons).toEqual(['清单缺失'])
expect(
batchOutcome(
batch({
manifest_state: 'invalid',
manifest_error: 'MANIFEST.json 无法解析',
databases: [{ ...batch().databases[0], failed: true }],
})
)
).toEqual({ failed: true, reasons: ['清单损坏', 'MANIFEST.json 无法解析', '子库失败:weknora'] })
})
})
describe('recentOutcome', () => {
it('uses the newest batch per outcome and counts only the 7 day window', () => {
const now = Date.parse('2026-11-24T12:00:00Z')
const outcome = recentOutcome(
[
batch({ stamp: '20261124T020000Z', created_at: '2026-11-24T02:00:00Z' }),
batch({ stamp: '20261123T020000Z', created_at: '2026-11-23T02:00:00Z', manifest_state: 'invalid' }),
batch({ stamp: '20261101T020000Z', created_at: '2026-11-01T02:00:00Z', manifest_state: 'missing' }),
],
now
)
expect(outcome.latestSuccessAt).toBe(formatWhen('2026-11-24T02:00:00Z'))
expect(outcome.latestFailureAt).toBe(formatWhen('2026-11-23T02:00:00Z'))
expect(outcome.successCount).toBe(1)
expect(outcome.failureCount).toBe(1)
})
it('orders batches by time even when the host sends them unsorted', () => {
const ordered = orderedBatches([
batch({ stamp: '20261122T020000Z', created_at: '2026-11-22T02:00:00Z' }),
batch({ stamp: '20261124T020000Z', created_at: '2026-11-24T02:00:00Z' }),
])
expect(ordered.map((item) => item.stamp)).toEqual(['20261124T020000Z', '20261122T020000Z'])
})
})
describe('summaryCards', () => {
it('shows real values when the host reported and the archive is available', () => {
const cards = summaryCards(inventory(), archive(), false)
const byKey = Object.fromEntries(cards.map((card) => [card.key, card.value]))
expect(byKey.root).toBe('/srv/kb-backups/rds-logical')
expect(byKey.success).toBe(formatWhen('2026-11-24T02:00:00Z'))
expect(byKey.failure).toBe('无')
expect(byKey.archive).toBe('38.4 GB')
expect(byKey.disk).toBe('1.2 TB')
expect(cards.find((card) => card.key === 'archive')?.note).toBe('配额 100 GB')
})
it('shows 主机未上报 with the last report time instead of 0 when the host never reported', () => {
const cards = summaryCards(unreported(), archive({ available: false }), false)
for (const key of ['root', 'success', 'failure', 'disk']) {
const card = cards.find((item) => item.key === key)!
expect(card.value).toBe('主机未上报')
expect(card.note).toBe('上次上报 —')
}
expect(cards.find((card) => card.key === 'archive')?.value).toBe('—')
expect(cards.some((card) => card.value === '0 B')).toBe(false)
})
it('keeps paths readable but leaves sizes empty for an incomplete report', () => {
const cards = summaryCards(inventory({ metadata: { ...inventory().metadata, complete: false } }), archive(), false)
expect(cards.find((card) => card.key === 'root')?.value).toBe('/srv/kb-backups/rds-logical')
expect(cards.find((card) => card.key === 'disk')?.value).toBe('—')
expect(cards.find((card) => card.key === 'disk')?.note).toBe('本次上报不完整')
})
})
describe('storageAlerts', () => {
it('judges disk and quota independently and counts pending rows', () => {
const healthy = storageAlerts(inventory(), archive(), false)
expect(healthy.map((row) => row.conclusion)).toEqual(['正常', '正常', '正常', '正常'])
expect(pendingAlertCount(healthy)).toBe(0)
const nearQuota = storageAlerts(
inventory(),
archive({
capacity: { ...archive().capacity, current_bytes: 95 * GIB, budget_bytes: 100 * GIB },
}),
false
)
expect(nearQuota.find((row) => row.key === 'quota_low')?.tone).toBe('warn')
expect(nearQuota.find((row) => row.key === 'both_low')?.conclusion).toBe('正常')
expect(pendingAlertCount(nearQuota)).toBe(1)
})
it('flags both-insufficient and quota larger than physical free space', () => {
const tight = storageAlerts(
inventory({
capacity: {
measured: true,
total_bytes: 2 * TB,
free_bytes: 0.01 * TB,
available_bytes: 0.01 * TB,
used_bytes: 1.99 * TB,
},
}),
archive({ capacity: { ...archive().capacity, current_bytes: 100 * GIB, budget_bytes: 100 * GIB } }),
false
)
expect(tight.find((row) => row.key === 'disk_low')?.tone).toBe('bad')
expect(tight.find((row) => row.key === 'both_low')?.conclusion).toBe('需处理')
expect(tight.find((row) => row.key === 'quota_over_physical')?.conclusion).toBe('需处理')
expect(pendingAlertCount(tight)).toBe(4)
expect(DISK_CRITICAL_AVAILABLE_PERCENT).toBe(5)
})
it('never claims a conclusion without numbers', () => {
const alerts = storageAlerts(unreported(), null, true)
expect(alerts.every((row) => row.conclusion === '未知')).toBe(true)
expect(alerts.find((row) => row.key === 'disk_low')?.value).toBe('主机未上报')
expect(alerts.some((row) => row.value.includes('无法判定'))).toBe(false)
})
})
+348
View File
@@ -0,0 +1,348 @@
// 「存储与备份」只读摘要的纯逻辑:数据源只有两个只读接口——
// /api/v1/backup-schedule/inventory (宿主每 5 分钟上报的元数据快照)
// /api/v1/library/storage (归档库自身的占用与配额)
// 页面不提供任何写操作。读不到的量一律留空("主机未上报" / "—"),不用 0 冒充。
import type { BackupInventory, BackupInventoryBatch } from './backupInventory'
import type { LibraryStorage } from './librarySnapshots'
// 阈值(与 docs/STORAGE_BACKUP_READONLY_API.md 的「页面口径」一致):
// 磁盘:可用空间 < 5% 红,< 10% 黄
// 配额:已用 >= 100% 红,>= 90% 黄
export const DISK_CRITICAL_AVAILABLE_PERCENT = 5
export const DISK_WARN_AVAILABLE_PERCENT = 10
export const QUOTA_CRITICAL_USED_PERCENT = 100
export const QUOTA_WARN_USED_PERCENT = 90
export const RECENT_WINDOW_DAYS = 7
export type Tone = 'ok' | 'warn' | 'bad' | 'none'
export type HostState = 'loading' | 'unwired' | 'missing' | 'stale' | 'invalid' | 'incomplete' | 'ready'
// 陈旧在先:stale 的快照会被后端判为 invalid,但"上次上报时间"仍然可读。
export const hostState = (inventory: BackupInventory | null): HostState => {
if (!inventory) return 'loading'
if (!inventory.wired) return 'unwired'
if (!inventory.metadata.present) return 'missing'
if (!inventory.metadata.fresh) return 'stale'
if (!inventory.metadata.valid) return 'invalid'
if (!inventory.metadata.complete) return 'incomplete'
return 'ready'
}
export const UNREPORTED = '主机未上报'
// 没有可用的上报表时的说法要和真实原因一致:未接入/从未上报、过期、不可用是三件事。
export const hostValueLabel = (state: HostState): string => {
switch (state) {
case 'unwired':
case 'missing':
return UNREPORTED
case 'stale':
return '上报已过期'
case 'invalid':
return '上报不可用'
default:
return UNKNOWN
}
}
export const UNKNOWN = '—'
// 结论未知与数值缺失是两件事:数值缺用“—”,无法判断结论用“未知”。
export const UNKNOWN_STATE = '未知'
const UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'] as const
export function formatSize(bytes: number | null | undefined): string {
if (bytes === null || bytes === undefined || !Number.isFinite(bytes) || bytes < 0) return UNKNOWN
if (bytes === 0) return '0 B'
let value = bytes
let index = 0
while (value >= 1024 && index < UNITS.length - 1) {
value /= 1024
index += 1
}
const digits = index === 0 || value >= 100 ? 0 : 1
const text = value.toFixed(digits).replace(/\.0$/, '')
return `${text} ${UNITS[index]}`
}
// 本地时间 MM/DD HH:mm;无法解析时返回空串,由调用方显示 "—"。
export function formatWhen(value: string | null | undefined): string {
if (!value) return ''
const date = new Date(value)
if (Number.isNaN(date.getTime())) return ''
return `${String(date.getMonth() + 1).padStart(2, '0')}/${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}
const STAMP = /^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z?$/
const stampTime = (stamp: string): number => {
const match = STAMP.exec(stamp)
if (!match) return 0
return Date.UTC(+match[1], +match[2] - 1, +match[3], +match[4], +match[5], +match[6])
}
export function batchWhen(batch: BackupInventoryBatch): string {
const iso = formatWhen(batch.created_at) || formatWhen(batch.started_at)
if (iso) return iso
const parsed = stampTime(batch.stamp)
return parsed ? formatWhen(new Date(parsed).toISOString()) || UNKNOWN : UNKNOWN
}
const batchTime = (batch: BackupInventoryBatch): number => {
const created = Date.parse(batch.created_at)
if (!Number.isNaN(created)) return created
const started = Date.parse(batch.started_at)
if (!Number.isNaN(started)) return started
return stampTime(batch.stamp)
}
export function orderedBatches(batches: BackupInventoryBatch[]): BackupInventoryBatch[] {
return [...batches].sort((left, right) => batchTime(right) - batchTime(left))
}
export interface BatchOutcome {
failed: boolean
reasons: string[]
}
// 失败判定:任一子库失败、清单缺失或损坏都算失败。宿主上报里没有自由文本原因,
// 页面只写能证明的事实(清单状态、失败子库名),不编造原因。
export function batchOutcome(batch: BackupInventoryBatch): BatchOutcome {
const reasons: string[] = []
if (batch.manifest_state === 'missing') reasons.push('清单缺失')
if (batch.manifest_state === 'invalid') reasons.push('清单损坏')
const manifestError = batch.manifest_error?.trim()
if (manifestError) reasons.push(manifestError)
const failedDatabases = batch.databases.filter((database) => database.failed).map((database) => database.name)
if (failedDatabases.length > 0) reasons.push(`子库失败:${failedDatabases.join('、')}`)
return { failed: reasons.length > 0, reasons }
}
export interface RecentOutcome {
latestSuccessAt: string
latestFailureAt: string
successCount: number
failureCount: number
}
export function recentOutcome(batches: BackupInventoryBatch[], now: number = Date.now()): RecentOutcome {
const windowStart = now - RECENT_WINDOW_DAYS * 24 * 60 * 60 * 1000
let latestSuccessAt = ''
let latestFailureAt = ''
let successCount = 0
let failureCount = 0
for (const batch of orderedBatches(batches)) {
const failed = batchOutcome(batch).failed
const when = batchWhen(batch)
const at = batchTime(batch)
if (failed) {
if (!latestFailureAt) latestFailureAt = when
} else if (!latestSuccessAt) {
latestSuccessAt = when
}
if (at >= windowStart) {
if (failed) failureCount += 1
else successCount += 1
}
}
return { latestSuccessAt, latestFailureAt, successCount, failureCount }
}
export interface SummaryCard {
key: string
label: string
value: string
note: string
copy?: string
unknown: boolean
}
const lastReportNote = (inventory: BackupInventory): string =>
`上次上报 ${formatWhen(inventory.metadata.collected_at) || UNKNOWN}`
export function summaryCards(
inventory: BackupInventory | null,
archive: LibraryStorage | null,
archiveFailed: boolean
): SummaryCard[] {
const state = hostState(inventory)
const facts = state === 'ready' || state === 'incomplete'
const sizes = state === 'ready'
const pending = Boolean(inventory) && state !== 'loading'
const recent = inventory && facts ? recentOutcome(inventory.batches) : null
const hostValue = pending && !facts ? hostValueLabel(state) : UNKNOWN
const hostNote = pending ? lastReportNote(inventory!) : UNKNOWN
const partialNote = facts && !sizes ? '本次上报不完整' : hostNote
const root = inventory ? inventory.host_root || inventory.root : ''
const rootKnown = facts && Boolean(root)
const capacity = inventory?.capacity
const diskKnown = sizes && Boolean(capacity?.measured) && (capacity?.total_bytes ?? 0) > 0
const availablePercent = diskKnown ? Math.round((capacity!.available_bytes / capacity!.total_bytes) * 100) : 0
const archiveKnown = Boolean(archive?.available) && !archiveFailed
return [
{
key: 'root',
label: '备份目录',
value: rootKnown ? root : hostValue,
note: rootKnown ? inventory!.metadata.host || UNKNOWN : partialNote,
copy: rootKnown ? root : undefined,
unknown: !rootKnown,
},
{
key: 'success',
label: '最近成功',
value: recent ? recent.latestSuccessAt || '无' : hostValue,
note: recent ? `近 ${RECENT_WINDOW_DAYS} 天 ${recent.successCount} 次` : partialNote,
unknown: !recent,
},
{
key: 'failure',
label: '最近失败',
value: recent ? recent.latestFailureAt || '无' : hostValue,
note: recent ? `近 ${RECENT_WINDOW_DAYS} 天 ${recent.failureCount} 次` : partialNote,
unknown: !recent,
},
{
key: 'archive',
label: '归档占用',
value: archiveKnown ? formatSize(archive!.capacity.current_bytes) : UNKNOWN,
note: archiveFailed
? '归档读取失败'
: !archive || !archive.available
? '归档不可用'
: archive.capacity.configured
? `配额 ${formatSize(archive.capacity.budget_bytes)}`
: '配额未设置',
unknown: !archiveKnown,
},
{
key: 'disk',
label: '磁盘剩余',
value: diskKnown ? formatSize(capacity!.available_bytes) : sizes ? UNKNOWN : hostValue,
note: diskKnown
? `共 ${formatSize(capacity!.total_bytes)} · 可用 ${availablePercent}%`
: sizes
? '容量未上报'
: partialNote,
unknown: !diskKnown,
},
]
}
export interface SummaryAlert {
key: string
label: string
value: string
tone: Tone
conclusion: string
}
export interface StorageFacts {
diskAvailableBytes: number | null
diskTotalBytes: number | null
archiveUsedBytes: number | null
archiveBudgetBytes: number | null
}
export function storageFacts(
inventory: BackupInventory | null,
archive: LibraryStorage | null,
archiveFailed: boolean
): StorageFacts {
const capacity = inventory?.capacity
const diskKnown = hostState(inventory) === 'ready' && Boolean(capacity?.measured) && (capacity?.total_bytes ?? 0) > 0
const archiveCapacity = archive?.available && !archiveFailed ? archive.capacity : null
return {
diskAvailableBytes: diskKnown ? capacity!.available_bytes : null,
diskTotalBytes: diskKnown ? capacity!.total_bytes : null,
archiveUsedBytes: archiveCapacity ? archiveCapacity.current_bytes : null,
archiveBudgetBytes: archiveCapacity?.configured ? archiveCapacity.budget_bytes : null,
}
}
const tonePercent = (value: number, warn: number, critical: number): Tone =>
value >= critical ? 'bad' : value >= warn ? 'warn' : 'ok'
const conclusionText = (tone: Tone): string =>
tone === 'ok' ? '正常' : tone === 'warn' ? '注意' : tone === 'bad' ? '需处理' : UNKNOWN_STATE
export function storageAlerts(
inventory: BackupInventory | null,
archive: LibraryStorage | null,
archiveFailed: boolean
): SummaryAlert[] {
const state = hostState(inventory)
const facts = storageFacts(inventory, archive, archiveFailed)
const diskKnown = facts.diskAvailableBytes !== null && (facts.diskTotalBytes ?? 0) > 0
const availablePercent = diskKnown ? Math.round((facts.diskAvailableBytes! / facts.diskTotalBytes!) * 100) : 0
const diskTone: Tone = diskKnown
? availablePercent < DISK_CRITICAL_AVAILABLE_PERCENT
? 'bad'
: availablePercent < DISK_WARN_AVAILABLE_PERCENT
? 'warn'
: 'ok'
: 'none'
const quotaKnown = facts.archiveUsedBytes !== null && (facts.archiveBudgetBytes ?? 0) > 0
const usedPercent = quotaKnown ? Math.round((facts.archiveUsedBytes! / facts.archiveBudgetBytes!) * 100) : 0
const quotaTone: Tone = quotaKnown
? tonePercent(usedPercent, QUOTA_WARN_USED_PERCENT, QUOTA_CRITICAL_USED_PERCENT)
: 'none'
const bothTone: Tone =
diskTone === 'none' || quotaTone === 'none' ? 'none' : diskTone !== 'ok' && quotaTone !== 'ok' ? 'bad' : 'ok'
const overPhysical: Tone =
diskKnown && facts.archiveBudgetBytes !== null
? facts.archiveBudgetBytes > facts.diskAvailableBytes!
? 'bad'
: 'ok'
: 'none'
const hostValue = hostValueLabel(state)
return [
{
key: 'disk_low',
label: '磁盘不足',
value: diskKnown ? `${formatSize(facts.diskAvailableBytes)}(可用 ${availablePercent}%)` : hostValue,
tone: diskTone,
conclusion: diskKnown ? conclusionText(diskTone) : UNKNOWN_STATE,
},
{
key: 'quota_low',
label: '配额不足',
value: quotaKnown
? `${formatSize(facts.archiveUsedBytes)} / ${formatSize(facts.archiveBudgetBytes)}(${usedPercent}%)`
: archiveFailed
? UNKNOWN
: archive?.available
? '配额未设置'
: UNKNOWN,
tone: quotaTone,
conclusion: quotaKnown ? conclusionText(quotaTone) : UNKNOWN_STATE,
},
{
key: 'both_low',
label: '磁盘与配额同时不足',
value: diskKnown && quotaKnown ? `磁盘可用 ${availablePercent}% · 配额已用 ${usedPercent}%` : hostValue,
tone: bothTone,
conclusion: diskKnown && quotaKnown ? conclusionText(bothTone) : UNKNOWN_STATE,
},
{
key: 'quota_over_physical',
label: '配额超出物理空闲',
value:
diskKnown && facts.archiveBudgetBytes !== null
? `配额 ${formatSize(facts.archiveBudgetBytes)} · 可用 ${formatSize(facts.diskAvailableBytes)}`
: UNKNOWN,
tone: overPhysical,
conclusion: diskKnown && facts.archiveBudgetBytes !== null ? conclusionText(overPhysical) : UNKNOWN_STATE,
},
]
}
export const pendingAlertCount = (alerts: SummaryAlert[]): number =>
alerts.filter((alert) => alert.tone === 'warn' || alert.tone === 'bad').length
-25
View File
@@ -2282,28 +2282,3 @@ tbody tr:hover {
.topbar-user-menu button:hover { .topbar-user-menu button:hover {
background: var(--bg-hover); background: var(--bg-hover);
} }
.member-create-form {
display: flex;
flex-wrap: wrap;
gap: 12px;
align-items: flex-end;
margin-top: 14px;
padding-top: 14px;
border-top: 1px solid var(--border-soft);
}
.member-create-form label {
display: grid;
gap: 5px;
font-size: 12.5px;
color: var(--ink-base);
font-weight: 600;
}
.member-create-form input,
.member-create-form select {
padding: 8px 10px;
border: 1px solid var(--border-strong);
border-radius: 6px;
font: inherit;
background: var(--bg-panel);
}
+137
View File
@@ -889,6 +889,143 @@ button.link {
font-size: 12px; font-size: 12px;
} }
/* 新增成员抽屉:右侧滑入,表单与表格同屏隔离,Esc 仅在无未保存输入时关闭。 */
.member-drawer-backdrop {
position: fixed;
z-index: 60;
inset: 0;
display: flex;
justify-content: flex-end;
background: rgb(15 23 32 / 40%);
}
.member-drawer {
display: flex;
flex-direction: column;
width: min(480px, 100vw);
height: 100%;
border-left: 1px solid var(--border-base);
background: var(--bg-panel);
box-shadow: var(--shadow-float);
animation: member-drawer-in 160ms ease-out;
}
@keyframes member-drawer-in {
from {
transform: translateX(100%);
}
to {
transform: none;
}
}
@media (prefers-reduced-motion: reduce) {
.member-drawer {
animation: none;
}
}
.member-drawer-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 16px 20px;
border-bottom: 1px solid var(--border-soft);
}
.member-drawer-header h3 {
margin: 0;
font-size: 16px;
}
.member-drawer-close {
display: grid;
place-items: center;
width: 32px;
height: 32px;
padding: 0;
border: 1px solid transparent;
border-radius: 8px;
background: transparent;
color: var(--ink-mute);
font-size: 20px;
line-height: 1;
box-shadow: none;
}
.member-drawer-close:hover:not(:disabled) {
background: var(--bg-hover);
color: var(--ink-base);
}
.member-drawer-form {
display: flex;
flex: 1;
min-height: 0;
flex-direction: column;
}
.member-drawer-body {
display: grid;
flex: 1;
gap: 14px;
align-content: start;
overflow: auto;
padding: 18px 20px;
}
.member-drawer-field {
display: grid;
gap: 6px;
color: var(--ink-base);
font-size: 13px;
font-weight: 600;
}
.member-drawer-field input,
.member-drawer-field select {
width: 100%;
padding: 8px 10px;
border: 1px solid var(--border-strong);
border-radius: 8px;
background: var(--bg-panel);
color: var(--ink-base);
font: inherit;
font-weight: 400;
}
.member-drawer-field input:focus,
.member-drawer-field select:focus {
outline: 2px solid var(--c-run);
outline-offset: 1px;
border-color: transparent;
}
.member-drawer-field [aria-invalid='true'] {
border-color: var(--c-fail);
}
.member-drawer-field .password-field input {
padding-right: 56px;
}
.member-drawer-hint {
color: var(--ink-mute);
font-size: 11px;
font-weight: 400;
}
.member-drawer-error {
margin: 0;
color: var(--c-fail);
font-size: 11px;
font-weight: 400;
}
.member-drawer-form-error {
padding: 8px 10px;
border: 1px solid var(--c-fail-border);
border-radius: 8px;
background: var(--c-fail-bg);
}
.member-drawer-actions {
display: flex;
justify-content: flex-end;
gap: 8px;
padding: 14px 20px;
border-top: 1px solid var(--border-soft);
background: var(--bg-panel);
}
@media (max-width: 650px) {
.member-drawer {
width: 100%;
}
}
.member-reset-dialog { .member-reset-dialog {
margin-top: 16px; margin-top: 16px;
border: 1px solid var(--border); border: 1px solid var(--border);