gongxiangp2/lib/desktop-client/knowledge-proxy.ts

136 lines
5.8 KiB
TypeScript

import { desktopAssert, DesktopClientError } from './contract.mjs'
import { issueKnowledgeSession } from './knowledge-session'
const proxyPrefix = '/api/desktop/knowledge/proxy'
const knowledgePath = /^\/api\/xiaoyi\/v1\/(?:templates(?:\/[A-Za-z0-9][\w.-]*\/(?:current|releases\/[A-Za-z0-9][\w.-]*\/(?:manifest|bundle)))?|blobs\/[a-f0-9]{64})$/
const headerTimeoutMs = 15_000
const maxErrorBodyBytes = 8192
const requestHeaderNames = ['accept', 'if-none-match', 'if-modified-since', 'if-range', 'range', 'x-ekb-client-version']
const responseHeaderNames = ['content-type', 'content-length', 'content-range', 'accept-ranges', 'etag', 'last-modified']
export const knowledgeResponseHeaders = {
'Cache-Control': 'private, no-store, no-transform',
'X-Content-Type-Options': 'nosniff',
'Content-Security-Policy': "sandbox; default-src 'none'",
}
function upstreamOrigin() {
const configured = process.env.XIAOYI_KNOWLEDGE_UPSTREAM_ORIGIN?.trim()
if (configured && /^https?:\/\/[^/?#@\\\s]+\/?$/i.test(configured)) {
try {
return new URL(configured).origin
} catch {
// Invalid URL or port is a configuration error.
}
}
throw new DesktopClientError('企业知识库上游地址未正确配置,请联系管理员', 503, 'knowledge_upstream_misconfigured')
}
async function readNotFoundCode(upstream: Response): Promise<unknown> {
if (!upstream.headers.get('content-type')?.toLowerCase().includes('application/json')) {
await upstream.body?.cancel()
return
}
const reader = upstream.body?.getReader()
if (!reader) return
const body = new Uint8Array(maxErrorBodyBytes)
let bytesRead = 0
try {
for (;;) {
const { done, value } = await reader.read()
if (done) break
if (bytesRead + value.byteLength > body.byteLength) {
await reader.cancel()
return
}
body.set(value, bytesRead)
bytesRead += value.byteLength
}
return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(body.subarray(0, bytesRead)))?.code
} catch {
return undefined
} finally {
reader.releaseLock()
}
}
export async function proxyKnowledge(request: Request, ownerId: string, expiresAt: Date, isSuperAdmin: boolean) {
const { method } = request
desktopAssert(method === 'GET' || method === 'HEAD', '企业知识库代理只支持 GET 和 HEAD', 405, 'knowledge_method_not_allowed')
const requestTarget = request.url.match(/^https?:\/\/[^/?#]+([^?#]*)(\?[^#]*)?$/)
const pathname = requestTarget?.[1] ?? ''
const path = pathname.slice(proxyPrefix.length)
desktopAssert(pathname.startsWith(proxyPrefix) && !/[\u0000-\u0020\u007f]/.test(path) && !path.includes('..') && knowledgePath.test(path),
'企业知识库请求路径无效', 400, 'invalid_knowledge_path')
const origin = upstreamOrigin()
const { token } = issueKnowledgeSession(ownerId, expiresAt, isSuperAdmin)
const requestHeaders = new Headers({ Authorization: `Bearer ${token}`, 'Accept-Encoding': 'identity' })
for (const name of requestHeaderNames) {
const value = request.headers.get(name)
if (value !== null) requestHeaders.set(name, value)
}
const timeout = new AbortController()
const timer = setTimeout(() => timeout.abort(), headerTimeoutMs)
let upstream: Response
try {
upstream = await fetch(origin + path + (requestTarget?.[2] ?? ''), {
method,
headers: requestHeaders,
cache: 'no-store',
redirect: 'manual',
signal: AbortSignal.any([request.signal, timeout.signal]),
})
} catch (error) {
const cause = error instanceof Error ? error.cause as { code?: string } | undefined : undefined
if (timeout.signal.aborted || cause?.code === 'UND_ERR_CONNECT_TIMEOUT' || cause?.code === 'UND_ERR_HEADERS_TIMEOUT') {
throw new DesktopClientError('企业知识库上游请求超时,请稍后重试', 504, 'knowledge_upstream_timeout')
}
throw new DesktopClientError('企业知识库上游不可达,请稍后重试', 502, 'knowledge_upstream_unreachable')
} finally {
clearTimeout(timer)
}
const { status } = upstream
if (status >= 400 && status < 500) {
if (status === 404) {
const upstreamCode = await readNotFoundCode(upstream)
if (upstreamCode === 'not_found') {
throw new DesktopClientError('企业知识库资源不存在', 404, 'not_found')
}
if (upstreamCode === 'not_published') {
throw new DesktopClientError('企业知识库模板尚未发布', 404, 'not_published')
}
throw new DesktopClientError('企业知识库资源不存在', 404, 'knowledge_upstream_rejected')
}
await upstream.body?.cancel()
if (status === 416) {
const headers = new Headers(knowledgeResponseHeaders)
const contentRange = upstream.headers.get('content-range')
if (contentRange !== null) headers.set('Content-Range', contentRange)
return new Response(null, { status, headers })
}
throw new DesktopClientError('企业知识库拒绝了请求', status, 'knowledge_upstream_rejected')
}
if (status === 504) {
await upstream.body?.cancel()
throw new DesktopClientError('企业知识库上游请求超时,请稍后重试', 504, 'knowledge_upstream_timeout')
}
const encoding = upstream.headers.get('content-encoding')
if (![200, 206, 304].includes(status) || (encoding !== null && encoding.toLowerCase() !== 'identity')) {
await upstream.body?.cancel()
// Fetch decodes compressed bodies, so their length and byte ranges cannot be reused.
throw new DesktopClientError('企业知识库上游响应异常,请稍后重试', 502, 'knowledge_upstream_invalid_response')
}
const headers = new Headers(knowledgeResponseHeaders)
for (const name of responseHeaderNames) {
const value = upstream.headers.get(name)
if (value !== null) headers.set(name, value)
}
return new Response(method === 'HEAD' || status === 304 ? null : upstream.body, { status, headers })
}