import { newOperationID } from './operationKey' export interface UISettings { id: string state: 'validated' | 'active' | 'retired' | 'failed' document_refresh_seconds: 15 | 30 | 60 resource_refresh_seconds: 30 | 60 stalled_after_seconds: 1800 | 3600 finalizing_after_seconds: 7200 | 14400 ingestion_concurrency: number test_weknora_base_url: string production_weknora_base_url: string production_tenant_id: string production_knowledge_base_id: string updated_by: string created_at: string activated_at: string | null retired_at: string | null error_code: string } export interface UISettingsCandidateInput { document_refresh_seconds: UISettings['document_refresh_seconds'] resource_refresh_seconds: UISettings['resource_refresh_seconds'] stalled_after_seconds: UISettings['stalled_after_seconds'] finalizing_after_seconds: UISettings['finalizing_after_seconds'] ingestion_concurrency: number test_weknora_base_url: string production_weknora_base_url: string production_tenant_id: string production_knowledge_base_id: string } // 保存服务配置时后端会用生产地址真查一次:找到了才写入,并把知识库名回显; // 端点明确回答"不存在"会拒绝保存(HTTP 400 + 这句 message),端点抖动只警告不拦。 export interface ServiceEndpointStatus { status: string message: string } export interface ServiceTargetVerification { status: string message: string blocked: boolean knowledge_base_name: string observed_tenant_id: string test_endpoint: ServiceEndpointStatus production_endpoint: ServiceEndpointStatus checked_at: string } export interface ServiceSettingsSave { settings: UISettings verification: ServiceTargetVerification | null } export class UISettingsError extends Error { readonly verification: ServiceTargetVerification | null constructor(message: string, verification: ServiceTargetVerification | null) { super(message) this.name = 'UISettingsError' this.verification = verification } } // Both environments are operator-provided endpoints typed in the console. // Accepting only a bare http(s) origin keeps credentials, query strings and // fragments out of stored configuration; the backend enforces the same rule. export function validServiceEndpoint(value: string): boolean { const trimmed = value.trim() if (trimmed === '') return true if (trimmed !== value || trimmed.length > 300) return false try { const parsed = new URL(trimmed) if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return false if (parsed.username || parsed.password || parsed.search || parsed.hash) return false return parsed.host.length > 0 } catch { return false } } // The production tenant of the target WeKnora is a decimal id; a sign, space or // letter is a typing mistake, never a valid tenant. export function validProductionTenantID(value: string): boolean { if (value.trim() === '') return true if (value !== value.trim() || value.length > 20) return false if (!/^[0-9]+$/.test(value)) return false return Number(value) > 0 } // The target knowledge base is an opaque id (letters, digits, '.', '_', '-', // ':'). A pasted URL must not pass as an id, so paths, queries and whitespace // are rejected here and on the server. export function validKnowledgeBaseID(value: string): boolean { if (value.trim() === '') return true if (value !== value.trim() || value.length > 128) return false return !/[\x00\r\n\t /?#\\]/.test(value) } export function settingsRefreshDelays(settings: Pick) { return { documentMs: settings.document_refresh_seconds * 1000, resourceMs: settings.resource_refresh_seconds * 1000 } } const states = new Set(['validated', 'active', 'retired', 'failed']) const documentRefresh = new Set([15, 30, 60]) const resourceRefresh = new Set([30, 60]) const stalledAfter = new Set([1800, 3600]) const finalizingAfter = new Set([7200, 14400]) const isRecord = (value: unknown): value is Record => Boolean(value) && typeof value === 'object' && !Array.isArray(value) export function parseUISettingsResponse(value: unknown): UISettings { if (!isRecord(value) || !isRecord(value.data)) throw new Error('invalid UI settings response') const item = value.data if (typeof item.id !== 'string' || !/^[A-Za-z0-9._:-]{2,36}$/.test(item.id) || typeof item.state !== 'string' || !states.has(item.state) || typeof item.document_refresh_seconds !== 'number' || !documentRefresh.has(item.document_refresh_seconds) || typeof item.resource_refresh_seconds !== 'number' || !resourceRefresh.has(item.resource_refresh_seconds) || typeof item.stalled_after_seconds !== 'number' || !stalledAfter.has(item.stalled_after_seconds) || typeof item.finalizing_after_seconds !== 'number' || !finalizingAfter.has(item.finalizing_after_seconds) || typeof item.ingestion_concurrency !== 'number' || !Number.isInteger(item.ingestion_concurrency) || item.ingestion_concurrency < 1 || item.ingestion_concurrency > 16 || typeof item.test_weknora_base_url !== 'string' || !validServiceEndpoint(item.test_weknora_base_url) || typeof item.production_weknora_base_url !== 'string' || !validServiceEndpoint(item.production_weknora_base_url) || typeof item.production_tenant_id !== 'string' || !validProductionTenantID(item.production_tenant_id) || typeof item.production_knowledge_base_id !== 'string' || !validKnowledgeBaseID(item.production_knowledge_base_id) || typeof item.updated_by !== 'string' || typeof item.created_at !== 'string' || (item.activated_at !== null && typeof item.activated_at !== 'string') || (item.retired_at !== null && typeof item.retired_at !== 'string') || typeof item.error_code !== 'string') { throw new Error('invalid UI settings response') } return { id: item.id, state: item.state as UISettings['state'], document_refresh_seconds: item.document_refresh_seconds as UISettings['document_refresh_seconds'], resource_refresh_seconds: item.resource_refresh_seconds as UISettings['resource_refresh_seconds'], stalled_after_seconds: item.stalled_after_seconds as UISettings['stalled_after_seconds'], finalizing_after_seconds: item.finalizing_after_seconds as UISettings['finalizing_after_seconds'], ingestion_concurrency: item.ingestion_concurrency, test_weknora_base_url: item.test_weknora_base_url, production_weknora_base_url: item.production_weknora_base_url, production_tenant_id: item.production_tenant_id, production_knowledge_base_id: item.production_knowledge_base_id, updated_by: item.updated_by, created_at: item.created_at, activated_at: item.activated_at as string | null, retired_at: item.retired_at as string | null, error_code: item.error_code, } } function parseEndpointStatus(value: unknown): ServiceEndpointStatus { if (!isRecord(value) || typeof value.status !== 'string' || typeof value.message !== 'string') return { status: '', message: '' } return { status: value.status, message: value.message } } // 核验块是诚实声明,解析失败按"没有核验"处理,绝不编造"已核验"。 export function parseServiceTargetVerification(value: unknown): ServiceTargetVerification | null { if (!isRecord(value) || typeof value.status !== 'string' || typeof value.message !== 'string' || typeof value.blocked !== 'boolean') return null return { status: value.status, message: value.message, blocked: value.blocked, knowledge_base_name: typeof value.knowledge_base_name === 'string' ? value.knowledge_base_name : '', observed_tenant_id: typeof value.observed_tenant_id === 'string' ? value.observed_tenant_id : '', test_endpoint: parseEndpointStatus(value.test_endpoint), production_endpoint: parseEndpointStatus(value.production_endpoint), checked_at: typeof value.checked_at === 'string' ? value.checked_at : '', } } async function readPayload(response: Response): Promise> { if (response.ok) { const payload: unknown = await response.json() return isRecord(payload) ? payload : {} } // 拒绝保存时服务器给的就是要展示的那句话,别再退化成状态码。 const failure: unknown = await response.json().catch(() => null) const record = isRecord(failure) ? failure : {} const message = typeof record.error === 'string' && record.error.trim() !== '' ? record.error : `UI settings request failed (${response.status})` throw new UISettingsError(message, parseServiceTargetVerification(record.verification)) } async function readSettings(response: Response): Promise { return parseUISettingsResponse(await readPayload(response)) } async function readSettingsSave(response: Response): Promise { const payload = await readPayload(response) return { settings: parseUISettingsResponse(payload), verification: parseServiceTargetVerification(payload.verification) } } export async function fetchActiveUISettings(signal?: AbortSignal): Promise { return readSettings(await fetch('/api/v1/ui-settings', { signal })) } export async function createUISettingsCandidate(input: UISettingsCandidateInput): Promise { return readSettingsSave(await fetch('/api/v1/ui-settings/candidates', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Governance-Action': 'ui-settings', 'Idempotency-Key': newOperationID() }, body: JSON.stringify(input), })) } export async function activateUISettings(revisionID: string): Promise { if (!/^[A-Za-z0-9._:-]{2,36}$/.test(revisionID)) throw new Error('invalid UI settings revision') return readSettingsSave(await fetch(`/api/v1/ui-settings/${encodeURIComponent(revisionID)}/activate`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Governance-Action': 'ui-settings', 'Idempotency-Key': newOperationID() }, body: '{}', })) }