| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205 |
- /**
- * 页面执行通道(服务端实现)
- * ========================
- * 桌面端是 electron/page-bridge.js:外壳起一个只监听 127.0.0.1 的 HTTP 服务,
- * 把 {port, token} 写进 runtime/shell-bridge.json,引擎里的 cocorobo 插件读它,
- * POST /page/eval。**这套契约原样照搬**,插件一个字都不用改 —— 换掉的只是
- * "通道另一边是谁":从 Electron 的 webview 变成服务端的 Chromium。
- *
- * 四条路由与桌面端一一对应:
- * POST /page/eval {code, urlMatch, timeoutMs}
- * POST /page/devtools {} → 控制台日志流
- * POST /page/reload {urlMatch, hard} → F5 / Ctrl+Shift+R
- * POST /page/dropFile {path, name, urlMatch, clickText, pageFn, ...}
- *
- * 安全边界同样保留:只绑 127.0.0.1、Bearer 定长比对、只对平台域名页面生效、
- * 请求体与返回体都设上限。
- */
- import http from 'node:http'
- import crypto from 'node:crypto'
- import fs from 'node:fs'
- import path from 'node:path'
- const MAX_BODY = 512 * 1024
- const DEFAULT_TIMEOUT = 8000
- function safeEqual (a, b) {
- const x = Buffer.from(String(a))
- const y = Buffer.from(String(b))
- if (x.length !== y.length) return false
- try { return crypto.timingSafeEqual(x, y) } catch { return false }
- }
- function readBody (req) {
- return new Promise((resolve, reject) => {
- let size = 0
- const chunks = []
- req.on('data', (chunk) => {
- size += chunk.length
- if (size > MAX_BODY) { reject(new Error('body-too-large')); req.destroy(); return }
- chunks.push(chunk)
- })
- req.on('end', () => {
- if (!chunks.length) return resolve({})
- try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8'))) } catch (err) {
- reject(new Error(`body-invalid: ${err.message}`))
- }
- })
- req.on('error', reject)
- })
- }
- export class PageBridge {
- /**
- * @param {object} options
- * @param {import('./browser.js').RemoteBrowser} options.browser
- * @param {string} options.tokenFile 引擎插件读的那个 JSON({port, token})
- * @param {(filePath:string)=>string} options.fileUrl 给页面取文件的短时地址
- * @param {(msg:string)=>void} [options.log]
- */
- constructor (options) {
- this.browser = options.browser
- this.tokenFile = options.tokenFile
- this.fileUrl = options.fileUrl || (() => '')
- this.log = options.log || (() => {})
- this.token = crypto.randomBytes(24).toString('hex')
- this.server = null
- this.info = null
- this.devtools = new Map() // targetId → 最近日志快照
- }
- async start () {
- const server = http.createServer((req, res) => { this.#handle(req, res) })
- this.server = server
- await new Promise((resolve, reject) => {
- server.once('error', reject)
- server.listen(0, '127.0.0.1', resolve)
- })
- const port = server.address().port
- this.info = { port, token: this.token }
- await fs.promises.mkdir(path.dirname(this.tokenFile), { recursive: true })
- await fs.promises.writeFile(this.tokenFile, JSON.stringify(this.info), 'utf8')
- this.log(`[bridge] 页面通道 :${port}`)
- return this.info
- }
- async stop () {
- try { await fs.promises.unlink(this.tokenFile) } catch { /* 已经不在了 */ }
- if (!this.server) return
- await new Promise((resolve) => this.server.close(resolve))
- this.server = null
- }
- async #handle (req, res) {
- const reply = (status, body) => {
- const text = JSON.stringify(body)
- res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
- res.end(text)
- }
- try {
- if (req.method !== 'POST') return reply(405, { ok: false, error: 'method-not-allowed' })
- const auth = String(req.headers.authorization || '')
- if (!auth.startsWith('Bearer ') || !safeEqual(auth.slice(7), this.token)) {
- return reply(401, { ok: false, error: 'unauthorized' })
- }
- const url = new URL(req.url, 'http://127.0.0.1')
- const payload = await readBody(req)
- let result
- if (url.pathname === '/page/eval') result = await this.#eval(payload)
- else if (url.pathname === '/page/reload') result = await this.#reload(payload)
- else if (url.pathname === '/page/devtools') result = await this.#devtools(payload)
- else if (url.pathname === '/page/dropFile') result = await this.#dropFile(payload)
- else return reply(404, { ok: false, error: 'not-found' })
- if (url.pathname !== '/page/eval') {
- this.log(`[bridge] ${url.pathname} → ${result.ok ? 'ok' : result.error}${result.url ? ` ${result.url}` : ''}`)
- }
- reply(200, result)
- } catch (err) {
- const code = /body-too-large/.test(err.message) ? 'body-too-large'
- : /body-invalid/.test(err.message) ? 'body-invalid'
- : `bridge-failed: ${err.message}`
- reply(200, { ok: false, error: code })
- }
- }
- async #guest (urlMatch) {
- const tab = this.browser.pickGuest(urlMatch)
- if (!tab) return null
- return tab
- }
- async #eval (payload) {
- const code = String((payload && payload.code) || '').trim()
- if (!code) return { ok: false, error: 'empty-code' }
- const tab = await this.#guest(payload && payload.urlMatch)
- if (!tab) {
- return {
- ok: false, error: 'no-guest',
- hint: '还没有打开平台页面,先用 cocorobo_open_page 打开,再执行页面脚本'
- }
- }
- const timeout = Math.min(Math.max(Number(payload.timeoutMs) || DEFAULT_TIMEOUT, 1000), 20000)
- try {
- const { value, truncated } = await this.browser.evaluate(tab, code, { timeoutMs: timeout })
- return { ok: true, url: tab.url, value, truncated }
- } catch (err) {
- if (/超时/.test(err.message)) return { ok: false, error: 'timeout', url: tab.url, timeoutMs: timeout }
- return { ok: false, error: `eval-failed: ${err.message}`, url: tab.url }
- }
- }
- async #reload (payload) {
- const tab = await this.#guest(payload && payload.urlMatch)
- if (!tab) {
- return {
- ok: false, error: 'no-guest',
- hint: '还没有打开平台页面,先用 cocorobo_open_page 打开,再刷新'
- }
- }
- const hard = payload && payload.hard === true
- await this.browser.reload(tab, hard)
- return { ok: true, url: tab.url, hard }
- }
- async #devtools (payload) {
- const tab = await this.#guest(payload && payload.urlMatch)
- if (!tab) {
- return {
- ok: false, error: 'no-guest',
- hint: '还没有打开平台页面,先用 cocorobo_open_page 打开,再开调试工具'
- }
- }
- // headless 里没有可看的 F12 面板,这里把控制台输出接出来:
- // 前端右侧面板会以覆盖层显示,效果和看 devtools 的 Console 一样。
- return { ok: true, url: tab.url, mode: 'console-stream', lines: this.browser.logsOf(tab).slice(-50) }
- }
- async #dropFile (payload) {
- const filePath = String((payload && (payload.path || payload.filePath)) || '').trim()
- if (!filePath) return { ok: false, error: 'empty-path' }
- const tab = await this.#guest(payload && payload.urlMatch)
- if (!tab) {
- return {
- ok: false, error: 'no-guest',
- hint: '还没有打开平台页面,先用 cocorobo_open_page 打开,再投递文件'
- }
- }
- const result = await this.browser.dropFile(tab, {
- path: filePath,
- name: String(payload.name || ''),
- clickText: Array.isArray(payload.clickText) ? payload.clickText.map(String) : [],
- pageFn: String(payload.pageFn || ''),
- pageFnArgs: payload.pageFnArgs === 'array' ? 'array' : 'single',
- pageFnTimeoutMs: Number(payload.pageFnTimeoutMs) || 0,
- fileUrl: this.fileUrl(filePath)
- })
- if (!result.ok) return result
- return {
- ...result,
- message: result.via === 'fn'
- ? '文件已经交给页面函数,返回值见 value'
- : '文件已经投进页面,等页面解析完再回读核对'
- }
- }
- }
|