proxy.js 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. /**
  2. * 反向代理
  3. * ========
  4. * 一个源站、一个 cookie:所有请求默认都转给"当前老师自己的引擎"。
  5. * 这样老师拿到的就是引擎原生的 Web 界面(会话、斜杠菜单、技能、设置全都在),
  6. * 我们只在 HTML 里注入两段脚本:
  7. *
  8. * cocorobo-shim 把桌面端 window.cocorobo 的那些方法接到 Web 服务上
  9. * webview-polyfill 把 <webview> 换成"服务端浏览器 + 画面回传"
  10. *
  11. * 不做路径前缀(/app/...)的原因:引擎前端资源都是绝对路径 /assets/...,
  12. * 挂到子路径下要改一堆 base,收益为零。
  13. */
  14. import http from 'node:http'
  15. import net from 'node:net'
  16. const HOP_HEADERS = new Set([
  17. 'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization',
  18. 'te', 'trailer', 'transfer-encoding', 'upgrade', 'host'
  19. ])
  20. export function createProxy (options = {}) {
  21. const injectHtml = options.injectHtml || ''
  22. const log = options.log || (() => {})
  23. function handleHttp (req, res, targetPort, injectOverride) {
  24. const inject = injectOverride || injectHtml
  25. const headers = {}
  26. for (const [key, value] of Object.entries(req.headers)) {
  27. if (HOP_HEADERS.has(key.toLowerCase())) continue
  28. headers[key] = value
  29. }
  30. headers.host = `127.0.0.1:${targetPort}`
  31. // 要改 HTML 就必须拿明文:引擎的静态服务会按 accept-encoding 压 gzip/br
  32. if (inject) delete headers['accept-encoding']
  33. const proxyReq = http.request({
  34. host: '127.0.0.1',
  35. port: targetPort,
  36. method: req.method,
  37. path: req.url,
  38. headers
  39. }, (proxyRes) => {
  40. const type = String(proxyRes.headers['content-type'] || '')
  41. const shouldInject = inject && /text\/html/i.test(type) && req.method === 'GET'
  42. if (!shouldInject) {
  43. res.writeHead(proxyRes.statusCode || 502, proxyRes.headers)
  44. proxyRes.pipe(res)
  45. return
  46. }
  47. const chunks = []
  48. let size = 0
  49. proxyRes.on('data', (chunk) => {
  50. size += chunk.length
  51. if (size > 8 * 1024 * 1024) {
  52. // 页面大到离谱就别改了,原样吐出去(多半是日志页/调试页)
  53. res.writeHead(proxyRes.statusCode || 200, proxyRes.headers)
  54. res.write(Buffer.concat(chunks))
  55. res.write(chunk)
  56. proxyRes.pipe(res)
  57. return
  58. }
  59. chunks.push(chunk)
  60. })
  61. proxyRes.on('end', () => {
  62. let html = Buffer.concat(chunks).toString('utf8')
  63. const tag = `<script>${inject.replace(/<\/script>/gi, '<\\/script>')}</script>`
  64. if (/<\/head>/i.test(html)) html = html.replace(/<\/head>/i, `${tag}</head>`)
  65. else html = html.replace(/<body[^>]*>/i, (m) => `${tag}${m}`)
  66. const out = Buffer.from(html, 'utf8')
  67. const next = { ...proxyRes.headers }
  68. delete next['content-encoding']
  69. delete next['transfer-encoding']
  70. next['content-length'] = String(out.length)
  71. next['content-type'] = 'text/html; charset=utf-8'
  72. res.writeHead(proxyRes.statusCode || 200, next)
  73. res.end(out)
  74. })
  75. })
  76. proxyReq.on('error', (err) => {
  77. log(`[proxy] 引擎请求失败 ${req.method} ${req.url}:${err.message}`)
  78. if (!res.headersSent) {
  79. res.writeHead(502, { 'content-type': 'text/html; charset=utf-8' })
  80. res.end(`<meta charset="utf-8"><p>引擎还没起来:${String(err.message).replace(/[<>&]/g, '')}</p>`)
  81. } else {
  82. res.destroy()
  83. }
  84. })
  85. // 流式回答可能是 SSE,别让默认 120 秒的超时把长回答掐掉
  86. proxyReq.setTimeout(0)
  87. req.pipe(proxyReq)
  88. }
  89. function handleUpgrade (req, socket, head, targetPort) {
  90. const upstream = net.connect(targetPort, '127.0.0.1', () => {
  91. const lines = [`${req.method} ${req.url} HTTP/1.1`]
  92. const headers = { ...req.headers, host: `127.0.0.1:${targetPort}` }
  93. delete headers.upgrade
  94. delete headers.connection
  95. for (const [key, value] of Object.entries(headers)) {
  96. if (Array.isArray(value)) for (const v of value) lines.push(`${key}: ${v}`)
  97. else if (value != null) lines.push(`${key}: ${value}`)
  98. }
  99. lines.push('Connection: Upgrade', 'Upgrade: websocket', '', '')
  100. upstream.write(lines.join('\r\n'))
  101. if (head && head.length) upstream.write(head)
  102. upstream.pipe(socket)
  103. socket.pipe(upstream)
  104. })
  105. const close = () => {
  106. upstream.destroy()
  107. socket.destroy()
  108. }
  109. upstream.on('error', close)
  110. socket.on('error', close)
  111. socket.setTimeout(0)
  112. }
  113. return { handleHttp, handleUpgrade }
  114. }