feat(binding): 连接四态验证、密钥尾号与私网 http 放行
build / build (push) Successful in 1m45s

在既有 kbbinding(迁移 000081)上补齐任务要求,不另建表、不另起路由:
- 测试连接区分 401/403(密钥无效 / 无权限)与不可达、成功四态;
- 视图回显密钥尾 4 位(服务端不存、不回读明文);
- key_action=clear 作为独立动作,清除后解析失败关闭、不回落文件旧 Key;
- 内外库留空 = 取消绑定,回报回退来源(测试侧部署默认库 / 生产侧同 ID 语义);
- 生产绑定回报在飞执行的冻结/仍可改指向条数,已冻结目标不被改写;
- 新增 WEKNORA_ALLOW_PRIVATE_HTTP:客户端/探活/连接页共用 HTTPAllowed,
  只放行 RFC1918/回环/链路本地 http,生产 18093 同网段反代因此可用。
This commit is contained in:
狐友 GXXP & Miku
2026-11-22 15:46:13 +08:00
committed by 姚章浩
parent cb026e8dd1
commit 7d91343e5f
21 changed files with 528 additions and 73 deletions
+39 -4
View File
@@ -24,6 +24,11 @@ const binding = (environment: 'test' | 'production'): KBEnvironmentBinding => ({
storage_ready: true,
replanned: 0,
retired_duplicates: 0,
key_tail: '9f2c',
internal_fallback: '',
external_fallback: '',
frozen: 0,
retargetable: 0,
})
const snapshot = {
@@ -181,7 +186,7 @@ describe('KnowledgeBaseBinding', () => {
expect(body.api_key).toBeUndefined()
})
it('does not allow saving until both directions have an explicit base', async () => {
it('allows clearing one direction and says where the empty side falls back', async () => {
vi.stubGlobal(
'fetch',
vi.fn((url: string) => {
@@ -195,10 +200,40 @@ describe('KnowledgeBaseBinding', () => {
await choose('对内知识库', 'kb-new-in-0001')
await choose('对外知识库', '')
const save = [...host.querySelectorAll('button')].find((button) => button.textContent?.includes('保存测试绑定'))
expect(save?.hasAttribute('disabled')).toBe(true)
expect(host.textContent).toContain('未选择不会回落到旧实例的默认库')
await choose('对外知识库', 'kb-new-out-0001')
// 留空 = 取消绑定:允许保存,但必须说清回退到哪里。
expect(save?.hasAttribute('disabled')).toBe(false)
expect(host.textContent).toContain('留空 = 取消该方向绑定')
await choose('对外知识库', 'kb-new-in-0001')
// 两边同一个库仍然不允许保存。
expect(save?.hasAttribute('disabled')).toBe(true)
})
it('clears the key through the dedicated action, not by saving a blank draft', async () => {
const put = vi
.fn()
.mockResolvedValue(
json({ data: { ...binding('test'), key_configured: false, key_tail: '', verification: 'not_configured' } })
)
vi.stubGlobal(
'fetch',
vi.fn((url: string, init?: RequestInit) => {
if (String(url) === '/api/v1/kb-bindings') return Promise.resolve(json(snapshot))
if (String(url).includes('/catalog')) return Promise.resolve(json(catalog))
if (init?.method === 'PUT') return put(url, init)
return Promise.resolve(json({ data: binding('test') }))
})
)
vi.stubGlobal('confirm', () => true)
await render()
const clear = [...host.querySelectorAll('button')].find((button) => button.textContent?.includes('清除密钥'))
expect(clear).toBeTruthy()
await act(async () => {
clear!.dispatchEvent(new MouseEvent('click', { bubbles: true }))
})
expect(put).toHaveBeenCalled()
const body = JSON.parse(String((put.mock.calls[0][1] as { body: string }).body))
expect(body.key_action).toBe('clear')
expect(body.api_key).toBeUndefined()
})
it('gives viewers a read-only summary with no editing inputs', async () => {
+71 -8
View File
@@ -70,6 +70,15 @@ const sameDraft = (draft: Draft, saved: KBEnvironmentBinding): boolean =>
draft.internalID === saved.internal_kb_id &&
draft.externalID === saved.external_kb_id
// 留空不是「什么都没发生」:它意味着回退到部署默认库(测试侧)或同 ID 语义
// (生产侧),页面必须把这一点说出来。
const fallbackLabel = (fallback: string): string =>
!fallback
? '部署默认(未设置)'
: fallback === 'same-id'
? '同 ID 语义'
: `部署默认库 ${shortKnowledgeBaseID(fallback)}`
const statusTone = (status: KBCatalog['status']): string =>
status === 'ok' ? 'ok' : status === 'empty' ? 'empty' : 'error'
@@ -148,8 +157,6 @@ export function KnowledgeBaseBinding() {
storageReady &&
endpointValid &&
keyReady &&
draft.internalID !== '' &&
draft.externalID !== '' &&
!duplicate &&
catalogReady
)
@@ -266,13 +273,20 @@ export function KnowledgeBaseBinding() {
view.replanned || view.retired_duplicates
? `;同时把 ${view.replanned} 项未上传的待入库重新指向新库${view.retired_duplicates ? `,${view.retired_duplicates} 项因新库已有同篇而退休` : ''}`
: ''
const fallbacks: string[] = []
if (!view.internal_kb_id) fallbacks.push(`对内回退到${fallbackLabel(view.internal_fallback)}`)
if (!view.external_kb_id) fallbacks.push(`对外回退到${fallbackLabel(view.external_fallback)}`)
const frozen =
view.frozen + view.retargetable > 0
? `;已冻结目标 ${view.frozen} 条(不会被改写),仍可改指向 ${view.retargetable} 条`
: ''
setNotices((current) => ({
...current,
[targetEnv]: {
tone: 'ok',
text: `已保存${environments.find((item) => item.key === targetEnv)?.short}绑定:对内 ${
view.internal_kb_name || shortKnowledgeBaseID(view.internal_kb_id) || '未绑定'
} · 对外 ${view.external_kb_name || shortKnowledgeBaseID(view.external_kb_id) || '未绑定'}${replan}`,
} · 对外 ${view.external_kb_name || shortKnowledgeBaseID(view.external_kb_id) || '未绑定'}${fallbacks.length ? `;${fallbacks.join(';')}` : ''}${replan}${frozen}`,
},
}))
} catch (cause) {
@@ -299,6 +313,44 @@ export function KnowledgeBaseBinding() {
}
}
// 清除密钥是独立动作:不换地址、不动绑定,只是这一侧不再有可用凭据。
const runClearKey = async () => {
if (!saved || !isAdmin || busyNow !== '') return
if (!window.confirm('清除后该侧不再有可用密钥:列库与发布会失败,也不会回落到服务器文件里的旧 Key。确定清除?'))
return
const targetEnv = env
const seq = ++saveSeq.current
setBusy((current) => ({ ...current, [targetEnv]: 'saving' }))
setNotices((current) => ({ ...current, [targetEnv]: null }))
try {
const view = await saveKBBinding(targetEnv, {
base_revision: saved.revision,
base_url: saved.base_url,
key_action: 'clear',
internal_kb_id: saved.internal_kb_id,
external_kb_id: saved.external_kb_id,
})
if (seq !== saveSeq.current) return
setSnapshot((current) => (current ? { ...current, [targetEnv]: view } : current))
setDrafts((current) => (current ? { ...current, [targetEnv]: draftFrom(view) } : current))
setNotices((current) => ({
...current,
[targetEnv]: {
tone: 'ok',
text: `已清除${environments.find((item) => item.key === targetEnv)?.short}连接的 API Key;地址与内外库绑定保留。`,
},
}))
} catch (cause) {
if (seq !== saveSeq.current) return
setNotices((current) => ({
...current,
[targetEnv]: { tone: 'error', text: cause instanceof Error ? cause.message : '清除密钥失败' },
}))
} finally {
setBusy((current) => ({ ...current, [targetEnv]: '' }))
}
}
const currentOptions = useMemo<{ internal: KBCatalogOption[]; external: KBCatalogOption[] }>(() => {
const base = draft?.catalog?.options ?? []
const withSelection = (id: string, name: string): KBCatalogOption[] => {
@@ -327,7 +379,9 @@ export function KnowledgeBaseBinding() {
{binding.key_configured
? binding.key_source === 'file'
? 'API Key 来自服务器文件'
: 'API Key 已配置(不回显)'
: binding.key_tail
? `API Key 已配置 · 尾${binding.key_tail}`
: 'API Key 已配置(不回读)'
: 'API Key 未配置'}
{binding.source === 'legacy' ? ' · 旧部署配置' : ` · 版本 ${binding.revision}`}
</small>
@@ -479,6 +533,11 @@ export function KnowledgeBaseBinding() {
{busyNow === 'catalog' ? '正在验证并读取…' : '验证并读取知识库'}
</button>
<small>服务器会用这份地址与密钥真实列库,只读,不写入。</small>
{saved?.key_configured ? (
<button type="button" className="danger" onClick={() => void runClearKey()} disabled={busyNow !== ''}>
清除密钥
</button>
) : null}
</div>
{draft.catalog ? (
<div className={`kb-catalog-status ${statusTone(draft.catalog.status)}`} role="status">
@@ -522,7 +581,9 @@ export function KnowledgeBaseBinding() {
}}
disabled={busyNow !== '' || !draft.catalog || draft.catalog.status !== 'ok'}
>
<option value="">请选择知识库</option>
<option value="">
未绑定({env === 'production' ? '生产侧回退到同 ID 语义' : '测试侧回退到部署默认库'})
</option>
{currentOptions.internal.map((option) => (
<option key={option.id} value={option.id}>
{option.name}({shortKnowledgeBaseID(option.id)})
@@ -540,7 +601,9 @@ export function KnowledgeBaseBinding() {
}}
disabled={busyNow !== '' || !draft.catalog || draft.catalog.status !== 'ok'}
>
<option value="">请选择知识库</option>
<option value="">
未绑定({env === 'production' ? '生产侧回退到同 ID 语义' : '测试侧回退到部署默认库'})
</option>
{currentOptions.external.map((option) => (
<option key={option.id} value={option.id}>
{option.name}({shortKnowledgeBaseID(option.id)})
@@ -550,8 +613,8 @@ export function KnowledgeBaseBinding() {
</label>
</div>
<small>
名称相同很常见,括号里的短 ID
才是区分依据;对内与对外都必须选择且不能是同一个库。未选择不会回落到旧实例的默认库。
名称相同很常见,括号里的短 ID 才是区分依据;对内与对外不能是同一个库。 留空 = 取消该方向绑定:
{env === 'production' ? '生产侧回退到「同 ID 语义」' : '测试侧回退到部署默认库'}。
</small>
{duplicate ? <p className="error-message">对内和对外不能绑定同一个知识库。</p> : null}
</section>
+5
View File
@@ -26,6 +26,11 @@ const binding = (environment: 'test' | 'production'): KBEnvironmentBinding => ({
storage_ready: true,
replanned: 0,
retired_duplicates: 0,
key_tail: '9f2c',
internal_fallback: '',
external_fallback: '',
frozen: 0,
retargetable: 0,
})
describe('knowledgeBaseBindings', () => {
+17 -4
View File
@@ -8,6 +8,8 @@ export interface KBEnvironmentBinding {
base_url: string
key_configured: boolean
key_source: string
/** 只用于展示的密钥尾 4 位;服务端不存、不回读明文。 */
key_tail: string
internal_kb_id: string
internal_kb_name: string
external_kb_id: string
@@ -20,6 +22,12 @@ export interface KBEnvironmentBinding {
storage_ready: boolean
replanned: number
retired_duplicates: number
/** 该方向留空时回退到哪:测试侧是部署默认库 ID,生产侧是 same-id。 */
internal_fallback: string
external_fallback: string
/** 生产侧:执行已开始的发布目标已冻结,保存绑定不会改写。 */
frozen: number
retargetable: number
}
export interface KBBindingSnapshot {
@@ -34,7 +42,7 @@ export interface KBCatalogOption {
knowledge_count: number
}
export type KBCatalogStatus = 'ok' | 'empty' | 'unauthorized' | 'unreachable' | 'unsupported'
export type KBCatalogStatus = 'ok' | 'empty' | 'key_invalid' | 'key_forbidden' | 'unreachable' | 'unsupported'
export interface KBCatalog {
status: KBCatalogStatus
@@ -48,7 +56,7 @@ export interface KBCatalog {
export interface KBCatalogInput {
base_revision: number
base_url: string
key_action: 'keep' | 'replace'
key_action: 'keep' | 'replace' | 'clear'
api_key?: string
page: number
page_size: number
@@ -57,7 +65,7 @@ export interface KBCatalogInput {
export interface KBBindingSaveInput {
base_revision: number
base_url: string
key_action: 'keep' | 'replace'
key_action: 'keep' | 'replace' | 'clear'
api_key?: string
internal_kb_id: string
external_kb_id: string
@@ -90,6 +98,7 @@ function parseBinding(value: unknown): KBEnvironmentBinding {
base_url: text(value.base_url),
key_configured: bool(value.key_configured),
key_source: text(value.key_source),
key_tail: text(value.key_tail),
internal_kb_id: text(value.internal_kb_id),
internal_kb_name: text(value.internal_kb_name),
external_kb_id: text(value.external_kb_id),
@@ -102,6 +111,10 @@ function parseBinding(value: unknown): KBEnvironmentBinding {
storage_ready: bool(value.storage_ready),
replanned: count(value.replanned),
retired_duplicates: count(value.retired_duplicates),
internal_fallback: text(value.internal_fallback),
external_fallback: text(value.external_fallback),
frozen: count(value.frozen),
retargetable: count(value.retargetable),
}
}
@@ -181,7 +194,7 @@ export async function fetchKBCatalog(
if (!record(payload.data)) throw new Error('知识库列表响应无效')
const item = payload.data
const status = text(item.status)
if (!['ok', 'empty', 'unauthorized', 'unreachable', 'unsupported'].includes(status)) {
if (!['ok', 'empty', 'key_invalid', 'key_forbidden', 'unreachable', 'unsupported'].includes(status)) {
throw new Error('知识库列表响应无效')
}
const options = Array.isArray(item.options)