/** * 反向代理 * ======== * 一个源站、一个 cookie:所有请求默认都转给"当前老师自己的引擎"。 * 这样老师拿到的就是引擎原生的 Web 界面(会话、斜杠菜单、技能、设置全都在), * 我们只在 HTML 里注入两段脚本: * * cocorobo-shim 把桌面端 window.cocorobo 的那些方法接到 Web 服务上 * webview-polyfill 把 换成"服务端浏览器 + 画面回传" * * 不做路径前缀(/app/...)的原因:引擎前端资源都是绝对路径 /assets/..., * 挂到子路径下要改一堆 base,收益为零。 */ import http from 'node:http' import net from 'node:net' const HOP_HEADERS = new Set([ 'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'te', 'trailer', 'transfer-encoding', 'upgrade', 'host' ]) export function createProxy (options = {}) { const injectHtml = options.injectHtml || '' const log = options.log || (() => {}) function handleHttp (req, res, targetPort, injectOverride) { const inject = injectOverride || injectHtml const headers = {} for (const [key, value] of Object.entries(req.headers)) { if (HOP_HEADERS.has(key.toLowerCase())) continue headers[key] = value } headers.host = `127.0.0.1:${targetPort}` // 要改 HTML 就必须拿明文:引擎的静态服务会按 accept-encoding 压 gzip/br if (inject) delete headers['accept-encoding'] const proxyReq = http.request({ host: '127.0.0.1', port: targetPort, method: req.method, path: req.url, headers }, (proxyRes) => { const type = String(proxyRes.headers['content-type'] || '') const shouldInject = inject && /text\/html/i.test(type) && req.method === 'GET' if (!shouldInject) { res.writeHead(proxyRes.statusCode || 502, proxyRes.headers) proxyRes.pipe(res) return } const chunks = [] let size = 0 proxyRes.on('data', (chunk) => { size += chunk.length if (size > 8 * 1024 * 1024) { // 页面大到离谱就别改了,原样吐出去(多半是日志页/调试页) res.writeHead(proxyRes.statusCode || 200, proxyRes.headers) res.write(Buffer.concat(chunks)) res.write(chunk) proxyRes.pipe(res) return } chunks.push(chunk) }) proxyRes.on('end', () => { let html = Buffer.concat(chunks).toString('utf8') const tag = `` if (/<\/head>/i.test(html)) html = html.replace(/<\/head>/i, `${tag}`) else html = html.replace(/]*>/i, (m) => `${tag}${m}`) const out = Buffer.from(html, 'utf8') const next = { ...proxyRes.headers } delete next['content-encoding'] delete next['transfer-encoding'] next['content-length'] = String(out.length) next['content-type'] = 'text/html; charset=utf-8' res.writeHead(proxyRes.statusCode || 200, next) res.end(out) }) }) proxyReq.on('error', (err) => { log(`[proxy] 引擎请求失败 ${req.method} ${req.url}:${err.message}`) if (!res.headersSent) { res.writeHead(502, { 'content-type': 'text/html; charset=utf-8' }) res.end(`

引擎还没起来:${String(err.message).replace(/[<>&]/g, '')}

`) } else { res.destroy() } }) // 流式回答可能是 SSE,别让默认 120 秒的超时把长回答掐掉 proxyReq.setTimeout(0) req.pipe(proxyReq) } function handleUpgrade (req, socket, head, targetPort) { const upstream = net.connect(targetPort, '127.0.0.1', () => { const lines = [`${req.method} ${req.url} HTTP/1.1`] const headers = { ...req.headers, host: `127.0.0.1:${targetPort}` } delete headers.upgrade delete headers.connection for (const [key, value] of Object.entries(headers)) { if (Array.isArray(value)) for (const v of value) lines.push(`${key}: ${v}`) else if (value != null) lines.push(`${key}: ${value}`) } lines.push('Connection: Upgrade', 'Upgrade: websocket', '', '') upstream.write(lines.join('\r\n')) if (head && head.length) upstream.write(head) upstream.pipe(socket) socket.pipe(upstream) }) const close = () => { upstream.destroy() socket.destroy() } upstream.on('error', close) socket.on('error', close) socket.setTimeout(0) } return { handleHttp, handleUpgrade } }