bridge.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. /**
  2. * 页面执行通道(服务端实现)
  3. * ========================
  4. * 桌面端是 electron/page-bridge.js:外壳起一个只监听 127.0.0.1 的 HTTP 服务,
  5. * 把 {port, token} 写进 runtime/shell-bridge.json,引擎里的 cocorobo 插件读它,
  6. * POST /page/eval。**这套契约原样照搬**,插件一个字都不用改 —— 换掉的只是
  7. * "通道另一边是谁":从 Electron 的 webview 变成服务端的 Chromium。
  8. *
  9. * 四条路由与桌面端一一对应:
  10. * POST /page/eval {code, urlMatch, timeoutMs}
  11. * POST /page/devtools {} → 控制台日志流
  12. * POST /page/reload {urlMatch, hard} → F5 / Ctrl+Shift+R
  13. * POST /page/dropFile {path, name, urlMatch, clickText, pageFn, ...}
  14. *
  15. * 安全边界同样保留:只绑 127.0.0.1、Bearer 定长比对、只对平台域名页面生效、
  16. * 请求体与返回体都设上限。
  17. */
  18. import http from 'node:http'
  19. import crypto from 'node:crypto'
  20. import fs from 'node:fs'
  21. import path from 'node:path'
  22. const MAX_BODY = 512 * 1024
  23. const DEFAULT_TIMEOUT = 8000
  24. function safeEqual (a, b) {
  25. const x = Buffer.from(String(a))
  26. const y = Buffer.from(String(b))
  27. if (x.length !== y.length) return false
  28. try { return crypto.timingSafeEqual(x, y) } catch { return false }
  29. }
  30. function readBody (req) {
  31. return new Promise((resolve, reject) => {
  32. let size = 0
  33. const chunks = []
  34. req.on('data', (chunk) => {
  35. size += chunk.length
  36. if (size > MAX_BODY) { reject(new Error('body-too-large')); req.destroy(); return }
  37. chunks.push(chunk)
  38. })
  39. req.on('end', () => {
  40. if (!chunks.length) return resolve({})
  41. try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8'))) } catch (err) {
  42. reject(new Error(`body-invalid: ${err.message}`))
  43. }
  44. })
  45. req.on('error', reject)
  46. })
  47. }
  48. export class PageBridge {
  49. /**
  50. * @param {object} options
  51. * @param {import('./browser.js').RemoteBrowser} options.browser
  52. * @param {string} options.tokenFile 引擎插件读的那个 JSON({port, token})
  53. * @param {(filePath:string)=>string} options.fileUrl 给页面取文件的短时地址
  54. * @param {(msg:string)=>void} [options.log]
  55. */
  56. constructor (options) {
  57. this.browser = options.browser
  58. this.tokenFile = options.tokenFile
  59. this.fileUrl = options.fileUrl || (() => '')
  60. this.log = options.log || (() => {})
  61. this.token = crypto.randomBytes(24).toString('hex')
  62. this.server = null
  63. this.info = null
  64. this.devtools = new Map() // targetId → 最近日志快照
  65. }
  66. async start () {
  67. const server = http.createServer((req, res) => { this.#handle(req, res) })
  68. this.server = server
  69. await new Promise((resolve, reject) => {
  70. server.once('error', reject)
  71. server.listen(0, '127.0.0.1', resolve)
  72. })
  73. const port = server.address().port
  74. this.info = { port, token: this.token }
  75. await fs.promises.mkdir(path.dirname(this.tokenFile), { recursive: true })
  76. await fs.promises.writeFile(this.tokenFile, JSON.stringify(this.info), 'utf8')
  77. this.log(`[bridge] 页面通道 :${port}`)
  78. return this.info
  79. }
  80. async stop () {
  81. try { await fs.promises.unlink(this.tokenFile) } catch { /* 已经不在了 */ }
  82. if (!this.server) return
  83. await new Promise((resolve) => this.server.close(resolve))
  84. this.server = null
  85. }
  86. async #handle (req, res) {
  87. const reply = (status, body) => {
  88. const text = JSON.stringify(body)
  89. res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
  90. res.end(text)
  91. }
  92. try {
  93. if (req.method !== 'POST') return reply(405, { ok: false, error: 'method-not-allowed' })
  94. const auth = String(req.headers.authorization || '')
  95. if (!auth.startsWith('Bearer ') || !safeEqual(auth.slice(7), this.token)) {
  96. return reply(401, { ok: false, error: 'unauthorized' })
  97. }
  98. const url = new URL(req.url, 'http://127.0.0.1')
  99. const payload = await readBody(req)
  100. let result
  101. if (url.pathname === '/page/eval') result = await this.#eval(payload)
  102. else if (url.pathname === '/page/reload') result = await this.#reload(payload)
  103. else if (url.pathname === '/page/devtools') result = await this.#devtools(payload)
  104. else if (url.pathname === '/page/dropFile') result = await this.#dropFile(payload)
  105. else return reply(404, { ok: false, error: 'not-found' })
  106. if (url.pathname !== '/page/eval') {
  107. this.log(`[bridge] ${url.pathname} → ${result.ok ? 'ok' : result.error}${result.url ? ` ${result.url}` : ''}`)
  108. }
  109. reply(200, result)
  110. } catch (err) {
  111. const code = /body-too-large/.test(err.message) ? 'body-too-large'
  112. : /body-invalid/.test(err.message) ? 'body-invalid'
  113. : `bridge-failed: ${err.message}`
  114. reply(200, { ok: false, error: code })
  115. }
  116. }
  117. async #guest (urlMatch) {
  118. const tab = this.browser.pickGuest(urlMatch)
  119. if (!tab) return null
  120. return tab
  121. }
  122. async #eval (payload) {
  123. const code = String((payload && payload.code) || '').trim()
  124. if (!code) return { ok: false, error: 'empty-code' }
  125. const tab = await this.#guest(payload && payload.urlMatch)
  126. if (!tab) {
  127. return {
  128. ok: false, error: 'no-guest',
  129. hint: '还没有打开平台页面,先用 cocorobo_open_page 打开,再执行页面脚本'
  130. }
  131. }
  132. const timeout = Math.min(Math.max(Number(payload.timeoutMs) || DEFAULT_TIMEOUT, 1000), 20000)
  133. try {
  134. const { value, truncated } = await this.browser.evaluate(tab, code, { timeoutMs: timeout })
  135. return { ok: true, url: tab.url, value, truncated }
  136. } catch (err) {
  137. if (/超时/.test(err.message)) return { ok: false, error: 'timeout', url: tab.url, timeoutMs: timeout }
  138. return { ok: false, error: `eval-failed: ${err.message}`, url: tab.url }
  139. }
  140. }
  141. async #reload (payload) {
  142. const tab = await this.#guest(payload && payload.urlMatch)
  143. if (!tab) {
  144. return {
  145. ok: false, error: 'no-guest',
  146. hint: '还没有打开平台页面,先用 cocorobo_open_page 打开,再刷新'
  147. }
  148. }
  149. const hard = payload && payload.hard === true
  150. await this.browser.reload(tab, hard)
  151. return { ok: true, url: tab.url, hard }
  152. }
  153. async #devtools (payload) {
  154. const tab = await this.#guest(payload && payload.urlMatch)
  155. if (!tab) {
  156. return {
  157. ok: false, error: 'no-guest',
  158. hint: '还没有打开平台页面,先用 cocorobo_open_page 打开,再开调试工具'
  159. }
  160. }
  161. // headless 里没有可看的 F12 面板,这里把控制台输出接出来:
  162. // 前端右侧面板会以覆盖层显示,效果和看 devtools 的 Console 一样。
  163. return { ok: true, url: tab.url, mode: 'console-stream', lines: this.browser.logsOf(tab).slice(-50) }
  164. }
  165. async #dropFile (payload) {
  166. const filePath = String((payload && (payload.path || payload.filePath)) || '').trim()
  167. if (!filePath) return { ok: false, error: 'empty-path' }
  168. const tab = await this.#guest(payload && payload.urlMatch)
  169. if (!tab) {
  170. return {
  171. ok: false, error: 'no-guest',
  172. hint: '还没有打开平台页面,先用 cocorobo_open_page 打开,再投递文件'
  173. }
  174. }
  175. const result = await this.browser.dropFile(tab, {
  176. path: filePath,
  177. name: String(payload.name || ''),
  178. clickText: Array.isArray(payload.clickText) ? payload.clickText.map(String) : [],
  179. pageFn: String(payload.pageFn || ''),
  180. pageFnArgs: payload.pageFnArgs === 'array' ? 'array' : 'single',
  181. pageFnTimeoutMs: Number(payload.pageFnTimeoutMs) || 0,
  182. fileUrl: this.fileUrl(filePath)
  183. })
  184. if (!result.ok) return result
  185. return {
  186. ...result,
  187. message: result.via === 'fn'
  188. ? '文件已经交给页面函数,返回值见 value'
  189. : '文件已经投进页面,等页面解析完再回读核对'
  190. }
  191. }
  192. }