Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 25d574f3de | |||
| 1dfa4fa7fc | |||
| d76363c117 | |||
| 8c84c9c601 |
@@ -28,6 +28,8 @@ QA_AI_MASTER_KEY_FILE=
|
||||
# 留空时页面仍能读旧部署的文件凭据/默认绑定,但保存新密钥会被拒绝(不落明文)。
|
||||
WEKNORA_BINDING_MASTER_KEY_FILE=
|
||||
# 同网段 http(生产 18093 反代)放行:只接受 RFC1918/回环/链路本地,公网 http 仍拒绝。
|
||||
# 同时决定「知识库绑定」页是否允许录入新 Key(能力位来自服务端);开启后页面显示明文传输风险。
|
||||
# 控制台自身经 TLS 反代提供时,仍需 QA_AI_TRUST_TLS_PROXY=true 且反代传 X-Forwarded-Proto=https。
|
||||
WEKNORA_ALLOW_PRIVATE_HTTP=false
|
||||
# Empty uses system DNS; alidns enables certificate-verified public DNS-over-TLS for this client only.
|
||||
QA_AI_DNS_OVER_TLS=
|
||||
|
||||
@@ -1,5 +1,35 @@
|
||||
# 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(知识库绑定:生产侧待入库重排与按环境隔离)
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -70,6 +70,14 @@ docker inspect -f '{{.Name}} {{index .Config.Labels "release"}}' kg-test-storage
|
||||
http,公网 http 仍被拒绝;不再需要测试机上的 `ssh -L 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) /
|
||||
密钥无权限(403) / 成功(读到 N 个库)。保存后页面只显示「已配置 · 尾XXXX」;
|
||||
「清除密钥」是独立动作(二次确认),清除后该侧解析失败关闭,不会回落到服务器文件
|
||||
|
||||
@@ -34,7 +34,13 @@ func (config Config) handleKBBindings(w http.ResponseWriter, r *http.Request) {
|
||||
for _, view := range views {
|
||||
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) {
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,14 +16,7 @@ func secretTransportAllowed(r *http.Request, trustTLSProxy bool) bool {
|
||||
if r.TLS != nil {
|
||||
return true
|
||||
}
|
||||
host := 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() {
|
||||
if loopbackHost(r.Host) {
|
||||
return true
|
||||
}
|
||||
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
|
||||
// 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
|
||||
// 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 {
|
||||
if secretTransportAllowed(r, trustTLSProxy) {
|
||||
return true
|
||||
}
|
||||
if !allowPrivateHTTP || r.Header.Get("Sec-Fetch-Site") != "same-origin" {
|
||||
if !allowPrivateHTTP {
|
||||
return false
|
||||
}
|
||||
origin := strings.TrimSpace(r.Header.Get("Origin"))
|
||||
@@ -53,8 +48,70 @@ func secretTransportAllowedForPrivateConsole(r *http.Request, trustTLSProxy, all
|
||||
return false
|
||||
}
|
||||
host := parsed.Hostname()
|
||||
if ip := net.ParseIP(host); ip != nil {
|
||||
return ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast()
|
||||
}
|
||||
return strings.EqualFold(host, "localhost")
|
||||
return privateAddressHost(host)
|
||||
}
|
||||
|
||||
// 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())
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,12 @@ const binding = (environment: 'test' | 'production'): KBEnvironmentBinding => ({
|
||||
})
|
||||
|
||||
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 },
|
||||
}
|
||||
const catalog = {
|
||||
@@ -110,11 +116,11 @@ afterEach(async () => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
const render = async (role: 'admin' | 'viewer' = 'admin') => {
|
||||
const render = async (role: 'admin' | 'viewer' = 'admin', consoleLocation?: { protocol: string; hostname: string }) => {
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<AuthContext.Provider value={auth(role)}>
|
||||
<KnowledgeBaseBinding />
|
||||
<KnowledgeBaseBinding consoleLocation={consoleLocation} />
|
||||
</AuthContext.Provider>
|
||||
)
|
||||
})
|
||||
@@ -272,4 +278,66 @@ describe('KnowledgeBaseBinding', () => {
|
||||
const save = [...host.querySelectorAll('button')].find((button) => button.textContent?.includes('保存测试绑定'))
|
||||
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('已保存测试绑定')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
|
||||
import { useOptionalAuth } from './auth'
|
||||
import { secretEntryAllowed } from './secureEntry'
|
||||
import { plaintextRemoteConsole } from './secureEntry'
|
||||
import {
|
||||
KBBindingError,
|
||||
duplicateSelection,
|
||||
@@ -82,7 +82,18 @@ const fallbackLabel = (fallback: string): string =>
|
||||
const statusTone = (status: KBCatalog['status']): string =>
|
||||
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 isAdmin = auth?.identity?.role === 'admin'
|
||||
const [snapshot, setSnapshot] = useState<KBBindingSnapshot | null>(null)
|
||||
@@ -135,7 +146,13 @@ export function KnowledgeBaseBinding() {
|
||||
const busyNow = busy[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 keyAction = saved && draft ? keyActionFor(saved, draft.baseURL, draft.replaceKey) : 'replace'
|
||||
const keyReady = keyAction === 'keep' ? Boolean(saved?.key_configured) : draft?.apiKey.trim() !== ''
|
||||
@@ -518,9 +535,20 @@ export function KnowledgeBaseBinding() {
|
||||
)}
|
||||
</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>
|
||||
) : 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 ? (
|
||||
<p className="settings-warn">已更换服务地址:必须为新地址重新录入 API Key,旧密钥不会发往新地址。</p>
|
||||
) : null}
|
||||
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
+245
-60
@@ -1,5 +1,6 @@
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import {
|
||||
MembersRequestError,
|
||||
createManagedUser,
|
||||
fetchManagedUsers,
|
||||
resetManagedUserPassword,
|
||||
@@ -12,6 +13,41 @@ import { PasswordInput } from './PasswordInput'
|
||||
|
||||
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 {
|
||||
return cause instanceof Error && cause.message ? cause.message : fallback
|
||||
}
|
||||
@@ -26,12 +62,12 @@ export function MembersSection() {
|
||||
// 重置密码用受控对话框(遮罩输入),不再借浏览器 prompt 显示明文。
|
||||
const [resetTarget, setResetTarget] = useState<{ id: string; username: string } | null>(null)
|
||||
const [resetValue, setResetValue] = useState('')
|
||||
const [form, setForm] = useState({
|
||||
username: '',
|
||||
display_name: '',
|
||||
role: 'engineer' as ManagedUser['role'],
|
||||
password: '',
|
||||
})
|
||||
const [form, setForm] = useState<Draft>(emptyDraft)
|
||||
const [drawerOpen, setDrawerOpen] = useState(false)
|
||||
const [fieldErrors, setFieldErrors] = useState<DraftErrors>({})
|
||||
const [createError, setCreateError] = useState<string | null>(null)
|
||||
const triggerRef = useRef<HTMLButtonElement>(null)
|
||||
const usernameRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true)
|
||||
@@ -63,17 +99,80 @@ export function MembersSection() {
|
||||
}
|
||||
}
|
||||
|
||||
const create = () =>
|
||||
run(
|
||||
'create',
|
||||
async () => {
|
||||
await createManagedUser(form)
|
||||
setForm({ username: '', display_name: '', role: 'engineer', password: '' })
|
||||
},
|
||||
`成员 ${form.username} 已创建,初始密码只用于首次登录`
|
||||
)
|
||||
const resetDraft = useCallback(() => {
|
||||
setForm(emptyDraft())
|
||||
setFieldErrors({})
|
||||
setCreateError(null)
|
||||
}, [])
|
||||
|
||||
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 (
|
||||
<section className="settings-panel wide" id="settings-members">
|
||||
@@ -82,6 +181,18 @@ export function MembersSection() {
|
||||
<h2>成员与角色</h2>
|
||||
<p>登录后的一切操作自动记录在成员名下;角色决定谁能审核、封批和行使生产授权。</p>
|
||||
</div>
|
||||
<button
|
||||
ref={triggerRef}
|
||||
type="button"
|
||||
className="primary"
|
||||
aria-label="新增成员"
|
||||
onClick={() => {
|
||||
setCreateError(null)
|
||||
setDrawerOpen(true)
|
||||
}}
|
||||
>
|
||||
<span aria-hidden="true">+</span> 新增成员
|
||||
</button>
|
||||
</div>
|
||||
{loading ? <p>加载成员…</p> : null}
|
||||
{error ? (
|
||||
@@ -190,50 +301,124 @@ export function MembersSection() {
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div className="member-create-form" aria-label="新增成员">
|
||||
<label>
|
||||
用户名
|
||||
<input
|
||||
value={form.username}
|
||||
maxLength={64}
|
||||
placeholder="小写字母/数字,如 zhangsan"
|
||||
onChange={(event) => setForm((current) => ({ ...current, username: event.target.value.toLowerCase() }))}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
姓名
|
||||
<input
|
||||
value={form.display_name}
|
||||
maxLength={128}
|
||||
onChange={(event) => setForm((current) => ({ ...current, display_name: event.target.value }))}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
角色
|
||||
<select
|
||||
value={form.role}
|
||||
onChange={(event) =>
|
||||
setForm((current) => ({ ...current, role: event.target.value as ManagedUser['role'] }))
|
||||
}
|
||||
>
|
||||
<option value="viewer">观察者</option>
|
||||
<option value="engineer">知识工程师</option>
|
||||
<option value="admin">管理员</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
初始密码(≥8 位,首登强制修改)
|
||||
<PasswordInput
|
||||
value={form.password}
|
||||
autoComplete="new-password"
|
||||
onChange={(event) => setForm((current) => ({ ...current, password: event.target.value }))}
|
||||
/>
|
||||
</label>
|
||||
<button type="button" disabled={!formValid || busy === 'create'} onClick={() => void create()}>
|
||||
新增成员
|
||||
</button>
|
||||
</div>
|
||||
<small>停用不会删除任何业务记录,只禁止登录并立即撤销其在线会话。</small>
|
||||
{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
|
||||
ref={usernameRef}
|
||||
id="member-new-username"
|
||||
value={form.username}
|
||||
maxLength={64}
|
||||
autoComplete="username"
|
||||
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 className="member-drawer-field" htmlFor="member-new-display-name">
|
||||
<span>姓名</span>
|
||||
<input
|
||||
id="member-new-display-name"
|
||||
value={form.display_name}
|
||||
maxLength={128}
|
||||
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 className="member-drawer-field" htmlFor="member-new-role">
|
||||
<span>角色</span>
|
||||
<select
|
||||
id="member-new-role"
|
||||
value={form.role}
|
||||
onChange={(event) => patchForm({ role: event.target.value as ManagedUser['role'] })}
|
||||
>
|
||||
<option value="viewer">观察者</option>
|
||||
<option value="engineer">知识工程师</option>
|
||||
<option value="admin">管理员</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="member-drawer-field" htmlFor="member-new-password">
|
||||
<span>初始密码</span>
|
||||
<PasswordInput
|
||||
id="member-new-password"
|
||||
value={form.password}
|
||||
autoComplete="new-password"
|
||||
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>
|
||||
</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>
|
||||
</div>
|
||||
</form>
|
||||
</aside>
|
||||
</div>
|
||||
) : null}
|
||||
{resetTarget ? (
|
||||
<div className="member-reset-dialog" role="dialog" aria-modal="true" aria-label="重置临时密码">
|
||||
<h3>重置 {resetTarget.username} 的临时密码</h3>
|
||||
|
||||
@@ -39,11 +39,13 @@ describe('knowledgeBaseBindings', () => {
|
||||
data: {
|
||||
environments: [binding('test'), binding('production')],
|
||||
storage_ready: true,
|
||||
secret_entry_allowed: true,
|
||||
},
|
||||
})
|
||||
expect(parsed.test.base_url).toBe('https://test.example')
|
||||
expect(parsed.production.internal_kb_name).toBe('内部资料')
|
||||
expect(parsed.storage_ready).toBe(true)
|
||||
expect(parsed.secret_entry_allowed).toBe(true)
|
||||
const asRecord = parsed.test as unknown as Record<string, unknown>
|
||||
expect(asRecord.api_key).toBeUndefined()
|
||||
expect(asRecord.key_ciphertext).toBeUndefined()
|
||||
@@ -53,6 +55,24 @@ describe('knowledgeBaseBindings', () => {
|
||||
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', () => {
|
||||
expect(shortKnowledgeBaseID('0b217e8a-1234-5678')).toBe('0b217e8a…')
|
||||
expect(knowledgeBaseLabel('0b217e8a-1234-5678', '客户帮助中心')).toBe('客户帮助中心(0b217e8a…)')
|
||||
|
||||
@@ -34,6 +34,9 @@ export interface KBBindingSnapshot {
|
||||
test: KBEnvironmentBinding
|
||||
production: KBEnvironmentBinding
|
||||
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 {
|
||||
@@ -130,7 +133,13 @@ export function parseKBBindingSnapshot(value: unknown): KBBindingSnapshot {
|
||||
const test = byEnvironment.get('test')
|
||||
const production = byEnvironment.get('production')
|
||||
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 是唯一可辨的部分;两处都显示,不靠名称猜。
|
||||
|
||||
+11
-1
@@ -15,6 +15,16 @@ export const managedUserRoles = ['viewer', 'engineer', 'admin'] as const
|
||||
const record = (value: unknown): value is Record<string, unknown> =>
|
||||
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 {
|
||||
if (
|
||||
!record(raw) ||
|
||||
@@ -50,7 +60,7 @@ async function call(url: string, init: RequestInit, message: string): Promise<un
|
||||
})
|
||||
if (!response.ok) {
|
||||
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()
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -3,3 +3,10 @@
|
||||
export function secretEntryAllowed(location: { protocol: string; hostname: string }): boolean {
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -2282,28 +2282,3 @@ tbody tr:hover {
|
||||
.topbar-user-menu button: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);
|
||||
}
|
||||
|
||||
@@ -889,6 +889,143 @@ button.link {
|
||||
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 {
|
||||
margin-top: 16px;
|
||||
border: 1px solid var(--border);
|
||||
|
||||
Reference in New Issue
Block a user