browser.mjs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. /**
  2. * 浏览器控制(Chrome / Edge DevTools 协议)
  3. * ------------------------------------------------
  4. * 引擎本身没有给模型"操作网页"的工具,右侧栏只是展示页面。这里自己连 CDP:
  5. * 启动一个独立的浏览器实例(独立 profile,不碰老师的日常浏览器)
  6. * → 用 HTTP 接口开页签 → 用 WebSocket 发命令(点击/输入/取文字/截图)。
  7. *
  8. * 为什么自己写 WebSocket:插件不在 dsh-runtime 的模块解析链上,裸 import 'ws' 会失败。
  9. * CDP 的帧结构简单(文本帧 + 长度前缀),自己实现比打进一份依赖更可控。
  10. *
  11. * 安全边界:只允许 http/https;file:// 与 chrome:// 一律拒绝,
  12. * 否则等于给对话开了一个任意读本地文件的口子。
  13. */
  14. import net from 'node:net'
  15. import crypto from 'node:crypto'
  16. import fs from 'node:fs'
  17. import path from 'node:path'
  18. import { spawn } from 'node:child_process'
  19. import { findBrowserExe } from './office.mjs'
  20. const MAX_TEXT = 20_000
  21. const CMD_TIMEOUT = 30_000
  22. // --------------------------------------------------------------- 最小 WebSocket
  23. class MiniWS {
  24. constructor (url) {
  25. const m = /^ws:\/\/([^/:]+)(?::(\d+))?(\/.*)?$/.exec(url)
  26. if (!m) throw new Error(`无法识别的 WebSocket 地址:${url}`)
  27. this.host = m[1]
  28. this.port = Number(m[2] || 80)
  29. this.path = m[3] || '/'
  30. this.buf = Buffer.alloc(0)
  31. this.frag = null
  32. this.closed = false
  33. this.handlers = { message: [], close: [] }
  34. }
  35. on (event, fn) { this.handlers[event].push(fn) }
  36. open () {
  37. return new Promise((resolve, reject) => {
  38. const key = crypto.randomBytes(16).toString('base64')
  39. this.socket = net.connect(this.port, this.host, () => {
  40. this.socket.write(
  41. `GET ${this.path} HTTP/1.1\r\nHost: ${this.host}:${this.port}\r\n` +
  42. 'Upgrade: websocket\r\nConnection: Upgrade\r\n' +
  43. `Sec-WebSocket-Key: ${key}\r\nSec-WebSocket-Version: 13\r\n\r\n`
  44. )
  45. })
  46. this.socket.setNoDelay(true)
  47. let handshook = false
  48. this.socket.on('data', (chunk) => {
  49. if (!handshook) {
  50. if (!chunk.includes('\r\n\r\n')) { this.buf = Buffer.concat([this.buf, chunk]); return }
  51. const text = chunk.toString('latin1')
  52. const idx = text.indexOf('\r\n\r\n')
  53. if (!/^HTTP\/1\.1 101/i.test(text)) {
  54. this.closed = true
  55. this.socket.destroy()
  56. return reject(new Error(`WebSocket 握手失败:${text.split('\r\n')[0]}`))
  57. }
  58. handshook = true
  59. this.buf = chunk.subarray(idx + 4)
  60. resolve()
  61. this._drain()
  62. return
  63. }
  64. this.buf = Buffer.concat([this.buf, chunk])
  65. this._drain()
  66. })
  67. this.socket.on('error', (err) => { if (!handshook) reject(err); this._emit('close') })
  68. this.socket.on('close', () => { this.closed = true; this._emit('close') })
  69. this.socket.setTimeout(0)
  70. })
  71. }
  72. _emit (event, arg) { for (const fn of this.handlers[event]) fn(arg) }
  73. _drain () {
  74. for (;;) {
  75. if (this.buf.length < 2) return
  76. const b0 = this.buf[0]
  77. const b1 = this.buf[1]
  78. const fin = (b0 & 0x80) !== 0
  79. const opcode = b0 & 0x0f
  80. const masked = (b1 & 0x80) !== 0
  81. let len = b1 & 0x7f
  82. let off = 2
  83. if (len === 126) {
  84. if (this.buf.length < 4) return
  85. len = this.buf.readUInt16BE(2); off = 4
  86. } else if (len === 127) {
  87. if (this.buf.length < 10) return
  88. len = Number(this.buf.readBigUInt64BE(2)); off = 10
  89. }
  90. let mask = null
  91. if (masked) {
  92. if (this.buf.length < off + 4) return
  93. mask = this.buf.subarray(off, off + 4); off += 4
  94. }
  95. if (this.buf.length < off + len) return
  96. let payload = this.buf.subarray(off, off + len)
  97. if (mask) {
  98. const copy = Buffer.allocUnsafe(len)
  99. for (let i = 0; i < len; i++) copy[i] = payload[i] ^ mask[i % 4]
  100. payload = copy
  101. }
  102. this.buf = this.buf.subarray(off + len)
  103. if (opcode === 0x1 || opcode === 0x0) {
  104. this.frag = this.frag ? Buffer.concat([this.frag, payload]) : payload
  105. if (fin) { const msg = this.frag.toString('utf8'); this.frag = null; this._emit('message', msg) }
  106. } else if (opcode === 0x8) {
  107. this.closed = true
  108. this.socket.end()
  109. this._emit('close')
  110. return
  111. } else if (opcode === 0x9) {
  112. this._frame(0x0a, payload)
  113. }
  114. }
  115. }
  116. _frame (opcode, payload) {
  117. const data = Buffer.isBuffer(payload) ? payload : Buffer.from(String(payload), 'utf8')
  118. const mask = crypto.randomBytes(4)
  119. let header
  120. if (data.length < 126) {
  121. header = Buffer.alloc(6)
  122. header[1] = 0x80 | data.length
  123. } else if (data.length < 65536) {
  124. header = Buffer.alloc(8)
  125. header[1] = 0x80 | 126
  126. header.writeUInt16BE(data.length, 2)
  127. } else {
  128. header = Buffer.alloc(14)
  129. header[1] = 0x80 | 127
  130. header.writeBigUInt64BE(BigInt(data.length), 2)
  131. }
  132. header[0] = 0x80 | opcode
  133. mask.copy(header, header.length - 4)
  134. const masked = Buffer.allocUnsafe(data.length)
  135. for (let i = 0; i < data.length; i++) masked[i] = data[i] ^ mask[i % 4]
  136. try { this.socket.write(Buffer.concat([header, masked])) } catch { /* 连接已断 */ }
  137. }
  138. send (text) { this._frame(0x1, text) }
  139. close () {
  140. if (this.closed) return
  141. this.closed = true
  142. try { this._frame(0x8, Buffer.alloc(0)) } catch { /* ignore */ }
  143. try { this.socket.end() } catch { /* ignore */ }
  144. }
  145. }
  146. // --------------------------------------------------------------- CDP 会话
  147. class CDP {
  148. constructor (wsUrl) {
  149. this.ws = new MiniWS(wsUrl)
  150. this.seq = 0
  151. this.pending = new Map()
  152. }
  153. async connect () {
  154. await this.ws.open()
  155. this.ws.on('message', (text) => {
  156. let msg
  157. try { msg = JSON.parse(text) } catch { return }
  158. if (msg.id && this.pending.has(msg.id)) {
  159. const { resolve, reject, timer } = this.pending.get(msg.id)
  160. clearTimeout(timer)
  161. this.pending.delete(msg.id)
  162. if (msg.error) reject(new Error(msg.error.message || '浏览器返回错误'))
  163. else resolve(msg.result)
  164. }
  165. })
  166. this.ws.on('close', () => {
  167. for (const { reject, timer } of this.pending.values()) { clearTimeout(timer); reject(new Error('浏览器连接已断开')) }
  168. this.pending.clear()
  169. })
  170. return this
  171. }
  172. send (method, params = {}) {
  173. const id = ++this.seq
  174. return new Promise((resolve, reject) => {
  175. const timer = setTimeout(() => { this.pending.delete(id); reject(new Error(`浏览器命令超时:${method}`)) }, CMD_TIMEOUT)
  176. this.pending.set(id, { resolve, reject, timer })
  177. this.ws.send(JSON.stringify({ id, method, params }))
  178. })
  179. }
  180. async evaluate (expression) {
  181. const res = await this.send('Runtime.evaluate', {
  182. expression, returnByValue: true, awaitPromise: true, userGesture: true
  183. })
  184. if (res.exceptionDetails) {
  185. throw new Error(res.exceptionDetails.exception?.description || res.exceptionDetails.text || '页面脚本执行失败')
  186. }
  187. return res.result?.value
  188. }
  189. close () { this.ws.close() }
  190. }
  191. // --------------------------------------------------------------- HTTP 小工具
  192. async function httpJson (url, method = 'GET') {
  193. const res = await fetch(url, { method })
  194. const text = await res.text()
  195. try { return JSON.parse(text) } catch { return { raw: text, status: res.status } }
  196. }
  197. async function waitFor (fn, { timeout = 20_000, interval = 250, what = '等待超时' } = {}) {
  198. const end = Date.now() + timeout
  199. let lastErr
  200. while (Date.now() < end) {
  201. try {
  202. const v = await fn()
  203. if (v) return v
  204. } catch (err) { lastErr = err }
  205. await new Promise((r) => setTimeout(r, interval))
  206. }
  207. throw new Error(lastErr ? `${what}:${lastErr.message}` : what)
  208. }
  209. // --------------------------------------------------------------- 浏览器实例
  210. export function createBrowserController ({ userDataDir, browserExe, headless = true } = {}) {
  211. const profileDir = userDataDir || path.join(process.env.TEMP || '.', 'cocobuddy-browser')
  212. let proc = null
  213. let port = 0
  214. const alive = async (p) => {
  215. try {
  216. const v = await httpJson(`http://127.0.0.1:${p}/json/version`, 'GET')
  217. return !!(v && v.webSocketDebuggerUrl)
  218. } catch { return false }
  219. }
  220. async function ensureRunning () {
  221. if (port && await alive(port)) return port
  222. const exe = findBrowserExe(browserExe)
  223. if (!exe) throw new Error('这台电脑上没有找到 Chrome 或 Edge,无法打开网页')
  224. fs.mkdirSync(profileDir, { recursive: true })
  225. // 端口随机挑,避免和老师自己开着的调试端口撞车
  226. const candidates = [0, 0, 0].map(() => 9300 + Math.floor(Math.random() * 400))
  227. for (const candidate of candidates) {
  228. if (await alive(candidate)) { port = candidate; return port }
  229. const args = [
  230. `--remote-debugging-port=${candidate}`,
  231. `--user-data-dir=${profileDir}`,
  232. '--no-first-run', '--no-default-browser-check', '--disable-extensions',
  233. '--disable-background-networking', '--disable-sync', '--disable-features=Translate'
  234. ]
  235. if (headless) args.push('--headless=new', '--disable-gpu')
  236. args.push('about:blank')
  237. proc = spawn(exe, args, { detached: true, stdio: 'ignore', windowsHide: true })
  238. proc.unref()
  239. proc.on('error', () => {})
  240. try {
  241. await waitFor(() => alive(candidate), { timeout: 20_000, interval: 400, what: '浏览器启动超时' })
  242. port = candidate
  243. return port
  244. } catch {
  245. try { proc.kill() } catch { /* ignore */ }
  246. }
  247. }
  248. throw new Error('浏览器没能启动(可能被安全软件拦了),请重试一次')
  249. }
  250. async function listTabs () {
  251. const p = await ensureRunning()
  252. const list = await httpJson(`http://127.0.0.1:${p}/json/list`)
  253. return (Array.isArray(list) ? list : []).filter((t) => t.type === 'page')
  254. }
  255. async function newTab (url) {
  256. const p = await ensureRunning()
  257. const target = `http://127.0.0.1:${p}/json/new?${encodeURIComponent(url || 'about:blank')}`
  258. // Chrome 111+ 要求 PUT,老版本只认 GET,两种都试
  259. let tab
  260. try { tab = await httpJson(target, 'PUT') } catch { tab = await httpJson(target, 'GET') }
  261. if (!tab || !tab.id) throw new Error('没能新建浏览器页签')
  262. return tab
  263. }
  264. async function withTab (tabId, fn) {
  265. const tabs = await listTabs()
  266. if (!tabs.length) throw new Error('浏览器里还没有打开的页面')
  267. const tab = tabId ? tabs.find((t) => t.id === tabId) : tabs[tabs.length - 1]
  268. if (!tab) throw new Error(`找不到页签 ${tabId}(可能已关闭)`)
  269. const cdp = await new CDP(tab.webSocketDebuggerUrl).connect()
  270. try { return await fn(cdp, tab) } finally { cdp.close() }
  271. }
  272. function assertUrl (url) {
  273. const u = String(url || '').trim()
  274. if (!u) throw new Error('缺少网址')
  275. if (!/^https?:\/\//i.test(u)) throw new Error(`只支持 http/https 网址,收到的是 ${u}`)
  276. return u
  277. }
  278. async function waitLoaded (cdp, timeout = 20_000) {
  279. await waitFor(async () => {
  280. const state = await cdp.evaluate('document.readyState')
  281. return state === 'complete' || state === 'interactive'
  282. }, { timeout, interval: 300, what: '页面加载超时' })
  283. // 单页应用首屏数据还要一会儿,给一点缓冲,不能等太久让模型以为失败
  284. await new Promise((r) => setTimeout(r, 600))
  285. }
  286. async function open (url, { reuse = true } = {}) {
  287. const target = assertUrl(url)
  288. const tabs = await listTabs().catch(() => [])
  289. // 只有一个空白页时复用它,避免越开越多
  290. const blank = reuse ? tabs.find((t) => t.url === 'about:blank') : null
  291. const tab = blank || await newTab(target)
  292. return withTab(tab.id, async (cdp) => {
  293. if (blank) await cdp.send('Page.navigate', { url: target })
  294. await waitLoaded(cdp)
  295. return { tabId: tab.id, url: await cdp.evaluate('location.href'), title: await cdp.evaluate('document.title') }
  296. })
  297. }
  298. async function goto (url, tabId) {
  299. const target = assertUrl(url)
  300. return withTab(tabId, async (cdp) => {
  301. await cdp.send('Page.navigate', { url: target })
  302. await waitLoaded(cdp)
  303. return { url: await cdp.evaluate('location.href'), title: await cdp.evaluate('document.title') }
  304. })
  305. }
  306. async function pageText (tabId, { selector = 'body', limit = MAX_TEXT } = {}) {
  307. return withTab(tabId, async (cdp) => {
  308. const text = await cdp.evaluate(`(() => {
  309. const el = document.querySelector(${JSON.stringify(selector)});
  310. return el ? (el.innerText || el.textContent || '') : '';
  311. })()`)
  312. const clean = String(text || '').replace(/\n{3,}/g, '\n\n').trim()
  313. return {
  314. url: await cdp.evaluate('location.href'),
  315. title: await cdp.evaluate('document.title'),
  316. chars: clean.length,
  317. text: clean.slice(0, limit),
  318. truncated: clean.length > limit
  319. }
  320. })
  321. }
  322. async function click (tabId, { selector, text, index = 0 }) {
  323. return withTab(tabId, async (cdp) => {
  324. const result = await cdp.evaluate(`(() => {
  325. const idx = ${Number(index) || 0};
  326. let els = [];
  327. if (${JSON.stringify(selector || '')}) {
  328. els = [...document.querySelectorAll(${JSON.stringify(selector || '')})];
  329. } else {
  330. const needle = ${JSON.stringify(String(text || ''))};
  331. if (!needle) return { ok: false, error: 'no-target' };
  332. const all = [...document.querySelectorAll('a,button,[role=button],input[type=submit],li,span,div')];
  333. els = all.filter((el) => (el.innerText || el.value || '').trim().includes(needle) ||
  334. (el.getAttribute('aria-label') || '').includes(needle));
  335. // 命中多层时取最内层,避免点到外层容器
  336. els = els.filter((el) => !els.some((o) => o !== el && el.contains(o)));
  337. }
  338. const el = els[idx];
  339. if (!el) return { ok: false, error: 'not-found', found: els.length };
  340. el.scrollIntoView({ block: 'center' });
  341. el.click();
  342. return { ok: true, tag: el.tagName, label: (el.innerText || el.value || '').trim().slice(0, 60), found: els.length };
  343. })()`)
  344. if (!result || !result.ok) {
  345. throw new Error(result?.error === 'not-found'
  346. ? `页面上没找到「${text || selector}」,可以把页面文字取出来先确认按钮叫什么`
  347. : '点击失败,没有定位到元素')
  348. }
  349. await new Promise((r) => setTimeout(r, 800))
  350. return { ...result, url: await cdp.evaluate('location.href') }
  351. })
  352. }
  353. async function type (tabId, { selector, text, submit = false }) {
  354. return withTab(tabId, async (cdp) => {
  355. const value = String(text ?? '')
  356. const mode = await cdp.evaluate(`(() => {
  357. const el = document.querySelector(${JSON.stringify(selector)});
  358. if (!el) return 'missing';
  359. el.focus();
  360. const proto = el instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
  361. const setter = Object.getOwnPropertyDescriptor(proto, 'value').set;
  362. setter.call(el, ${JSON.stringify(value)});
  363. el.dispatchEvent(new Event('input', { bubbles: true }));
  364. el.dispatchEvent(new Event('change', { bubbles: true }));
  365. if (!${submit ? 'true' : 'false'}) return 'ok';
  366. // 搜索框大多在 form 里:直接提交表单最可靠,回车事件经常被前端拦住
  367. const form = el.form;
  368. if (form && typeof form.requestSubmit === 'function') { form.requestSubmit(); return 'form'; }
  369. if (form && typeof form.submit === 'function') { form.submit(); return 'form'; }
  370. return 'key';
  371. })()`)
  372. if (mode === 'missing') throw new Error(`页面上没有 ${selector},先取一次页面文字确认输入框怎么定位`)
  373. if (submit && mode === 'key') {
  374. for (const type of ['keyDown', 'keyUp']) {
  375. await cdp.send('Input.dispatchKeyEvent', { type, key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13 })
  376. }
  377. }
  378. if (submit) {
  379. // 提交后是跳转,等加载完成;超时不算失败(单页应用可能就地渲染)
  380. await waitLoaded(cdp).catch(() => {})
  381. }
  382. return { ok: true, selector, submitted: !!submit, url: await cdp.evaluate('location.href') }
  383. })
  384. }
  385. async function screenshot (tabId, file) {
  386. return withTab(tabId, async (cdp) => {
  387. const { data } = await cdp.send('Page.captureScreenshot', { format: 'png' })
  388. const target = path.resolve(file)
  389. fs.mkdirSync(path.dirname(target), { recursive: true })
  390. fs.writeFileSync(target, Buffer.from(data, 'base64'))
  391. return { file: target, bytes: fs.statSync(target).size }
  392. })
  393. }
  394. async function evaluate (tabId, expression) {
  395. return withTab(tabId, (cdp) => cdp.evaluate(String(expression || '')))
  396. }
  397. async function closeTab (tabId) {
  398. const p = await ensureRunning()
  399. await httpJson(`http://127.0.0.1:${p}/json/close/${encodeURIComponent(tabId)}`)
  400. return { closed: tabId }
  401. }
  402. async function quit () {
  403. const p = await ensureRunning().catch(() => 0)
  404. if (!p) return { quit: true }
  405. try { await httpJson(`http://127.0.0.1:${p}/json/close/` + (await listTabs())[0]?.id) } catch { /* ignore */ }
  406. try { proc?.kill() } catch { /* ignore */ }
  407. proc = null
  408. port = 0
  409. return { quit: true }
  410. }
  411. return { open, goto, pageText, click, type, screenshot, evaluate, closeTab, quit, listTabs }
  412. }