import { desktopAssert, DesktopClientError } from './contract.mjs' import { issueKnowledgeSession } from './knowledge-session' import { request as requestHttp, type RequestOptions } from 'node:http' import { request as requestHttps } from 'node:https' import { isIPv4 } from 'node:net' import { Readable } from 'node:stream' 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 primaryTimeoutMs = 4_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 intranetHost(host: string) { if (!isIPv4(host)) { return host === '[::1]' || !host.includes('.') && !host.includes(':') || host.endsWith('.internal') || host.endsWith('.local') } const [first, second] = host.split('.').map(Number) return first === 127 || first === 10 || first === 192 && second === 168 || first === 172 && second >= 16 && second <= 31 } function upstreamOrigin(configured: string | undefined, httpsOnly = false) { configured = configured?.trim() if (configured && /^https?:\/\/[^/?#@\\\s]+\/?$/i.test(configured)) { try { const url = new URL(configured) if (url.protocol === 'https:' || !httpsOnly && intranetHost(url.hostname)) return url.origin } catch { // Invalid URL or port is a configuration error. } } throw new DesktopClientError('企业知识库上游地址未正确配置,请联系管理员', 503, 'knowledge_upstream_misconfigured') } // Company network traffic stays direct even when Node enables environment proxies. function fetchUpstream(url: URL, method: string, headers: Headers, signal: AbortSignal): Promise { if (!intranetHost(url.hostname)) { return fetch(url.href, { method, headers, cache: 'no-store', redirect: 'manual', signal }) } return new Promise((resolve, reject) => { const send = url.protocol === 'https:' ? requestHttps : requestHttp const options: RequestOptions = { method, headers: Object.fromEntries(headers), signal, agent: false } const request = send(url, options, response => { const status = response.statusCode! const bodyless = method === 'HEAD' || [204, 205, 304].includes(status) if (bodyless) response.resume() const body = bodyless ? null : Readable.toWeb(response, { strategy: { highWaterMark: response.readableHighWaterMark, size: chunk => chunk.byteLength }, }) as ReadableStream resolve(new Response(body, { status, headers: response.headers as HeadersInit })) }) request.on('error', reject) request.end() }) } async function readUpstream(urls: URL[], method: string, headers: Headers, signal: AbortSignal) { for (let index = 0; index < urls.length; index++) { const hasBackup = index < urls.length - 1 const timeout = new AbortController() const timer = setTimeout(() => timeout.abort(), hasBackup ? primaryTimeoutMs : headerTimeoutMs) try { const response = await fetchUpstream(urls[index], method, headers, AbortSignal.any([signal, timeout.signal])) if (response.status === 404) { const notFoundCode = await readNotFoundCode(response) signal.throwIfAborted() timeout.signal.throwIfAborted() if (hasBackup && notFoundCode === 'channel_unavailable') continue return { response, notFoundCode } } if (!hasBackup || response.status < 500 || response.status >= 600) return { response } await response.body?.cancel() } catch (error) { signal.throwIfAborted() if (hasBackup) continue 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) } } throw new Error('企业知识库缺少可用地址') } async function readNotFoundCode(upstream: Response): Promise { 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 primary = upstreamOrigin(process.env.XIAOYI_KNOWLEDGE_UPSTREAM_ORIGIN) const backup = process.env.XIAOYI_KNOWLEDGE_FALLBACK_ORIGIN?.trim() const origins = new Set([primary, ...(backup ? [upstreamOrigin(backup, true)] : [])]) 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 urls = Array.from(origins, origin => new URL(path + (requestTarget?.[2] ?? ''), origin)) const { response: upstream, notFoundCode } = await readUpstream(urls, method, requestHeaders, request.signal) const { status } = upstream if (status >= 400 && status < 500) { if (status === 404) { if (notFoundCode === 'channel_unavailable') { throw new DesktopClientError('企业知识库连接入口未启用,请联系管理员核对网络配置', 503, 'knowledge_upstream_misconfigured') } if (notFoundCode === 'not_found') { throw new DesktopClientError('企业知识库资源不存在', 404, 'not_found') } if (notFoundCode === '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 }) } if (status === 401) { throw new DesktopClientError('企业知识库未通过自动授权,请联系管理员核对授权配置和服务器时间', 401, 'knowledge_upstream_session_rejected') } if (status === 403) { throw new DesktopClientError('当前账号无权读取此知识库资源,请联系管理员', 403, 'knowledge_upstream_rejected') } 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 }) }