browser.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  1. /**
  2. * 服务端 Chromium
  3. * ===============
  4. * 桌面端的右侧页面是 Electron 的 <webview>,它的能力来自"同一台机器上的浏览器"。
  5. * Web 版没有这台机器,所以这里给每个老师起一个独立的 Chromium:
  6. *
  7. * · 页签(target)—— 对应桌面端按站点分的那几页;
  8. * · 页面脚本 —— Page.eval 走 Runtime.evaluate,语义和 executeJavaScript 一致;
  9. * · 投递文件 —— 上传控件走 DOM.setFileInputFiles,页面函数走"取字节 → new File";
  10. * · 硬刷新 —— 清 HTTP 缓存 + 该站 Service Worker,再 ignoreCache 重载;
  11. * · 画面回传 —— Page.startScreencast,前端拿 canvas 画;
  12. * · 输入转发 —— Input.dispatchMouseEvent / dispatchKeyEvent / insertText。
  13. *
  14. * 安全边界和桌面端保持一致:脚本只允许在 **平台域名** 的页面里执行;浏览器只监听
  15. * 127.0.0.1 的调试端口;每个老师一份 user-data-dir,登录态互不可见。
  16. */
  17. import { spawn } from 'node:child_process'
  18. import fs from 'node:fs'
  19. import path from 'node:path'
  20. import { CDP, CDPError } from './cdp.js'
  21. const PLATFORM_RE = /^https?:\/\/([a-z0-9-]+\.)*cocorobo\.(cn|hk|com)(\/|$)/i
  22. const MAX_RESULT = 200 * 1024
  23. const MAX_TABS = 8
  24. const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
  25. export function isPlatformUrl (url) {
  26. return PLATFORM_RE.test(String(url || ''))
  27. }
  28. function hostOf (url) {
  29. try { return new URL(url).host } catch { return '' }
  30. }
  31. /** 交给页面的 File 要带对 MIME:上传控件会按 type 过滤,application/octet-stream 常被拒 */
  32. function guessType (file) {
  33. const ext = path.extname(String(file || '')).toLowerCase()
  34. const map = {
  35. '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif',
  36. '.webp': 'image/webp', '.svg': 'image/svg+xml', '.pdf': 'application/pdf',
  37. '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  38. '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  39. '.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  40. '.json': 'application/json', '.txt': 'text/plain', '.html': 'text/html',
  41. '.zip': 'application/zip', '.mp4': 'video/mp4', '.mp3': 'audio/mpeg'
  42. }
  43. return map[ext] || 'application/octet-stream'
  44. }
  45. /** 页面里可能抛任何东西:统一压成可 JSON 化的字符串,别把工具调用打挂 */
  46. function describeValue (value) {
  47. if (value == null) return null
  48. try {
  49. const json = JSON.stringify(value)
  50. return json.length > MAX_RESULT ? json.slice(0, MAX_RESULT) : json
  51. } catch {
  52. return String(value)
  53. }
  54. }
  55. export class RemoteBrowser {
  56. constructor (options = {}) {
  57. this.exe = options.exe || ''
  58. this.userDataDir = options.userDataDir || ''
  59. this.downloadDir = options.downloadDir || ''
  60. this.headless = options.headless !== false
  61. this.width = options.width || 1440
  62. this.height = options.height || 900
  63. this.noSandbox = options.noSandbox !== false
  64. this.log = options.log || (() => {})
  65. this.extraArgs = options.extraArgs || []
  66. this.proc = null
  67. this.httpPort = 0
  68. this.browserCdp = null
  69. this.tabs = new Map() // targetId → tab
  70. this.hostKey = new Map() // host → targetId(桌面端"一个站点一页"的对应关系)
  71. this.logs = new Map() // targetId → 最近日志
  72. this.screencast = new Map() // targetId → {subs:Set, active:boolean, meta}
  73. this.stopped = false
  74. }
  75. // ---------------------------------------------------------------- 生命周期
  76. async start () {
  77. if (!this.exe) throw new Error('没有配置浏览器可执行文件(CC_CHROME)')
  78. if (!fs.existsSync(this.exe)) throw new Error(`浏览器不存在:${this.exe}`)
  79. fs.mkdirSync(this.userDataDir, { recursive: true })
  80. const args = [
  81. '--remote-debugging-port=0',
  82. `--user-data-dir=${this.userDataDir}`,
  83. `--window-size=${this.width},${this.height}`,
  84. '--no-first-run',
  85. '--no-default-browser-check',
  86. '--disable-background-networking',
  87. '--disable-component-update',
  88. '--disable-sync',
  89. '--disable-extensions',
  90. '--disable-features=Translate,MediaRouter,OptimizationHints',
  91. '--force-color-profile=srgb',
  92. '--hide-scrollbars',
  93. '--mute-audio',
  94. '--lang=zh-CN',
  95. ...this.extraArgs
  96. ]
  97. if (this.headless) args.push('--headless=new')
  98. // 容器里以 root 跑必须关沙箱;生产环境请用非 root 并去掉这条
  99. if (this.noSandbox) args.push('--no-sandbox', '--disable-dev-shm-usage')
  100. args.push('about:blank')
  101. this.proc = spawn(this.exe, args, { stdio: ['ignore', 'ignore', 'pipe'] })
  102. this.proc.on('exit', (code) => {
  103. this.log(`[browser] 退出 code=${code}`)
  104. if (!this.stopped) this.#failAllTabs('浏览器进程已退出')
  105. })
  106. const wsUrl = await this.#waitDevtools()
  107. this.httpPort = Number(new URL(wsUrl).port)
  108. this.browserCdp = await CDP.connect(wsUrl, { label: 'browser', timeoutMs: 20_000 })
  109. this.#watchTargets()
  110. this.log(`[browser] 就绪 :${this.httpPort}(${this.headless ? 'headless' : 'headed'})`)
  111. return this
  112. }
  113. #waitDevtools () {
  114. return new Promise((resolve, reject) => {
  115. let buf = ''
  116. const timer = setTimeout(() => {
  117. reject(new Error(`浏览器 20 秒内没有给出调试地址:${buf.slice(-400)}`))
  118. }, 20_000)
  119. timer.unref?.()
  120. const onData = (chunk) => {
  121. buf += chunk.toString('utf8')
  122. const m = /DevTools listening on (ws:\/\/[^\s]+)/.exec(buf)
  123. if (m) {
  124. clearTimeout(timer)
  125. this.proc.stderr.off('data', onData)
  126. resolve(m[1])
  127. }
  128. if (buf.length > 8000) buf = buf.slice(-4000)
  129. }
  130. this.proc.stderr.on('data', onData)
  131. this.proc.on('exit', (code) => {
  132. clearTimeout(timer)
  133. reject(new Error(`浏览器启动失败(code=${code}):${buf.slice(-400)}`))
  134. })
  135. })
  136. }
  137. #watchTargets () {
  138. const cdp = this.browserCdp
  139. cdp.send('Target.setDiscoverTargets', { discover: true }).catch((err) => {
  140. this.log(`[browser] 订阅 target 失败:${err.message}`)
  141. })
  142. cdp.on('Target.targetCreated', ({ targetInfo }) => this.#trackTarget(targetInfo))
  143. cdp.on('Target.targetInfoChanged', ({ targetInfo }) => this.#updateTarget(targetInfo))
  144. cdp.on('Target.targetDestroyed', ({ targetId }) => this.#dropTarget(targetId))
  145. }
  146. #trackTarget (info) {
  147. if (!info || info.type !== 'page') return
  148. if (String(info.url || '').startsWith('devtools://')) return
  149. const targetId = info.targetId
  150. if (this.tabs.has(targetId)) return this.#updateTarget(info)
  151. const tab = {
  152. targetId,
  153. url: String(info.url || ''),
  154. title: String(info.title || ''),
  155. loading: false,
  156. error: '',
  157. key: '',
  158. cdp: null,
  159. opening: null,
  160. lastUsed: Date.now()
  161. }
  162. tab.key = this.#keyFor(tab)
  163. this.tabs.set(targetId, tab)
  164. this.log(`[browser] 新页签 ${tab.key} ${tab.url}`)
  165. // 页签上限:关最久没用的那个,防止老师开一堆把内存吃满
  166. if (this.tabs.size > MAX_TABS) {
  167. const victim = [...this.tabs.values()]
  168. .filter((t) => t.targetId !== targetId)
  169. .sort((a, b) => a.lastUsed - b.lastUsed)[0]
  170. if (victim) this.closeTab(victim.targetId).catch(() => {})
  171. }
  172. }
  173. #keyFor (tab) {
  174. const host = hostOf(tab.url)
  175. if (!host) return 'blank'
  176. const taken = this.hostKey.get(host)
  177. if (!taken || taken === tab.targetId || !this.tabs.has(taken)) {
  178. this.hostKey.set(host, tab.targetId)
  179. return host
  180. }
  181. return `${host}#${tab.targetId.slice(0, 4)}`
  182. }
  183. #updateTarget (info) {
  184. if (!info || info.type !== 'page') return
  185. const tab = this.tabs.get(info.targetId)
  186. if (!tab) return this.#trackTarget(info)
  187. if (info.url && info.url !== tab.url) {
  188. tab.url = info.url
  189. tab.key = this.#keyFor(tab)
  190. }
  191. if (typeof info.title === 'string' && info.title !== tab.title) {
  192. tab.title = info.title
  193. this.#emit(tab, { type: 'state', field: 'title', value: tab.title })
  194. }
  195. }
  196. #dropTarget (targetId) {
  197. const tab = this.tabs.get(targetId)
  198. if (!tab) return
  199. this.tabs.delete(targetId)
  200. const host = hostOf(tab.url)
  201. if (host && this.hostKey.get(host) === targetId) this.hostKey.delete(host)
  202. try { tab.cdp?.close() } catch { /* 已经断了 */ }
  203. this.screencast.delete(targetId)
  204. this.logs.delete(targetId)
  205. }
  206. #failAllTabs (message) {
  207. for (const tab of this.tabs.values()) {
  208. tab.error = message
  209. this.#emit(tab, { type: 'state', field: 'error', value: message })
  210. }
  211. this.tabs.clear()
  212. this.hostKey.clear()
  213. }
  214. async closeTab (targetId) {
  215. try {
  216. await this.browserCdp?.send('Target.closeTarget', { targetId })
  217. } catch { /* 目标可能已经没了 */ }
  218. this.#dropTarget(targetId)
  219. }
  220. async stop () {
  221. this.stopped = true
  222. try { this.browserCdp?.close() } catch { /* 已经断了 */ }
  223. for (const tab of this.tabs.values()) {
  224. try { tab.cdp?.close() } catch { /* 已经断了 */ }
  225. }
  226. this.tabs.clear()
  227. this.hostKey.clear()
  228. if (this.proc && !this.proc.killed) {
  229. try { this.proc.kill('SIGTERM') } catch { /* 已经退了 */ }
  230. await sleep(300)
  231. if (this.proc.exitCode == null) {
  232. try { this.proc.kill('SIGKILL') } catch { /* 已经退了 */ }
  233. }
  234. }
  235. }
  236. // ---------------------------------------------------------------- 页签
  237. list () {
  238. return [...this.tabs.values()]
  239. .filter((t) => t.url && !t.url.startsWith('about:'))
  240. .sort((a, b) => b.lastUsed - a.lastUsed)
  241. .map((t) => ({ key: t.key, url: t.url, title: t.title, loading: t.loading, error: t.error }))
  242. }
  243. /** 桌面端 pickPlatformGuest 的等价物:只认平台域名,urlMatch 按地址挑。 */
  244. pickGuest (urlMatch) {
  245. const want = String(urlMatch || '').trim().toLowerCase()
  246. const candidates = [...this.tabs.values()]
  247. .filter((t) => isPlatformUrl(t.url))
  248. .sort((a, b) => b.lastUsed - a.lastUsed)
  249. if (!candidates.length) return null
  250. if (!want) return candidates[0]
  251. return candidates.find((t) => t.url.toLowerCase().includes(want)) || null
  252. }
  253. async openTab (url) {
  254. const target = String(url || '').trim()
  255. if (!/^https?:\/\//i.test(target)) throw new Error('只支持 http(s) 地址')
  256. const host = hostOf(target)
  257. const existingId = host ? this.hostKey.get(host) : ''
  258. const existing = existingId ? this.tabs.get(existingId) : null
  259. if (existing) {
  260. existing.lastUsed = Date.now()
  261. if (existing.url !== target) await this.navigate(existing, target)
  262. return existing
  263. }
  264. const { targetId } = await this.browserCdp.send('Target.createTarget', { url: 'about:blank' })
  265. // targetCreated 事件是异步的,等它把 tab 建出来再导航,避免拿不到对象
  266. const tab = await this.#waitTab(targetId)
  267. tab.lastUsed = Date.now()
  268. await this.navigate(tab, target)
  269. return tab
  270. }
  271. async #waitTab (targetId) {
  272. for (let i = 0; i < 100; i += 1) {
  273. const tab = this.tabs.get(targetId)
  274. if (tab) return tab
  275. await sleep(50)
  276. }
  277. throw new Error('页签创建后没有出现')
  278. }
  279. async navigate (tab, url) {
  280. const cdp = await this.#cdpOf(tab)
  281. tab.loading = true
  282. tab.error = ''
  283. this.#emit(tab, { type: 'state', field: 'loading', value: true })
  284. try {
  285. await cdp.send('Page.navigate', { url })
  286. } catch (err) {
  287. tab.loading = false
  288. tab.error = err.message
  289. this.#emit(tab, { type: 'state', field: 'error', value: err.message })
  290. throw err
  291. }
  292. return tab
  293. }
  294. async reload (tab, hard = false) {
  295. const cdp = await this.#cdpOf(tab)
  296. tab.error = ''
  297. this.#emit(tab, { type: 'state', field: 'error', value: '' })
  298. if (hard) {
  299. const origin = (() => { try { return new URL(tab.url).origin } catch { return '' } })()
  300. await cdp.send('Network.enable').catch(() => {})
  301. await cdp.send('Network.setCacheDisabled', { cacheDisabled: true }).catch(() => {})
  302. if (origin) {
  303. await cdp.send('Storage.clearDataForOrigin', {
  304. origin,
  305. storageTypes: 'service_workers,cache_storage'
  306. }).catch(() => {})
  307. }
  308. // 页面自己注册的 SW 也要一并清掉,否则下次导航又被接回去
  309. await cdp.send('Runtime.evaluate', {
  310. expression: `(async () => {
  311. try {
  312. const rs = await navigator.serviceWorker.getRegistrations()
  313. await Promise.all(rs.map((r) => r.unregister()))
  314. if (globalThis.caches) {
  315. const keys = await caches.keys()
  316. await Promise.all(keys.map((k) => caches.delete(k)))
  317. }
  318. return true
  319. } catch { return false }
  320. })()`,
  321. awaitPromise: true,
  322. returnByValue: true
  323. }).catch(() => {})
  324. }
  325. await cdp.send('Page.reload', { ignoreCache: !!hard })
  326. if (hard) setTimeout(() => { cdp.send('Network.setCacheDisabled', { cacheDisabled: false }).catch(() => {}) }, 1500)
  327. return { ok: true, url: tab.url }
  328. }
  329. // ---------------------------------------------------------------- 页面 CDP
  330. async #cdpOf (tab) {
  331. if (tab.cdp) return tab.cdp
  332. if (tab.opening) return tab.opening
  333. tab.opening = (async () => {
  334. const ws = await this.#pageWs(tab.targetId)
  335. const cdp = await CDP.connect(ws, { label: `page:${tab.key}`, timeoutMs: 20_000 })
  336. tab.cdp = cdp
  337. tab.opening = null
  338. await this.#wire(cdp, tab)
  339. return cdp
  340. })().catch((err) => {
  341. tab.opening = null
  342. throw err
  343. })
  344. return tab.opening
  345. }
  346. async #pageWs (targetId) {
  347. for (let i = 0; i < 60; i += 1) {
  348. try {
  349. const res = await fetch(`http://127.0.0.1:${this.httpPort}/json/list`)
  350. const list = await res.json()
  351. const hit = list.find((t) => t.id === targetId)
  352. if (hit && hit.webSocketDebuggerUrl) return hit.webSocketDebuggerUrl
  353. } catch { /* 浏览器还没起稳 */ }
  354. await sleep(100)
  355. }
  356. throw new Error('拿不到页签的调试地址')
  357. }
  358. async #wire (cdp, tab) {
  359. cdp.send('Page.enable').catch(() => {})
  360. cdp.send('Runtime.enable').catch(() => {})
  361. if (this.downloadDir) {
  362. cdp.send('Page.setDownloadBehavior', { behavior: 'allow', downloadPath: this.downloadDir }).catch(() => {})
  363. }
  364. cdp.on('Page.frameNavigated', ({ frame }) => {
  365. if (!frame || frame.parentId) return
  366. if (frame.url && frame.url !== tab.url) {
  367. tab.url = frame.url
  368. tab.key = this.#keyFor(tab)
  369. this.#emit(tab, { type: 'state', field: 'url', value: tab.url })
  370. }
  371. })
  372. cdp.on('Page.loadEventFired', async () => {
  373. tab.loading = false
  374. this.#emit(tab, { type: 'state', field: 'loading', value: false })
  375. const title = await this.#title(tab)
  376. if (title && title !== tab.title) {
  377. tab.title = title
  378. this.#emit(tab, { type: 'state', field: 'title', value: title })
  379. }
  380. })
  381. cdp.on('Page.loadingFailed', ({ errorText, isMainFrame }) => {
  382. if (isMainFrame === false) return
  383. tab.loading = false
  384. tab.error = String(errorText || '页面加载失败')
  385. this.#emit(tab, { type: 'state', field: 'error', value: tab.error })
  386. this.#emit(tab, { type: 'state', field: 'loading', value: false })
  387. })
  388. cdp.on('Inspector.targetCrashed', () => {
  389. tab.error = '页面崩溃了'
  390. this.#emit(tab, { type: 'state', field: 'error', value: tab.error })
  391. })
  392. // 页面弹 alert/confirm 会把整个页签卡住(CDP 不会自己点掉),统一按「确定」处理
  393. cdp.on('Page.javascriptDialogOpening', () => {
  394. cdp.send('Page.handleJavaScriptDialog', { accept: true }).catch(() => {})
  395. })
  396. cdp.on('Runtime.consoleAPICalled', ({ type, args }) => {
  397. this.#pushLog(tab, type, args)
  398. })
  399. }
  400. async #title (tab) {
  401. try {
  402. const cdp = tab.cdp
  403. if (!cdp) return ''
  404. const { result } = await cdp.send('Runtime.evaluate', {
  405. expression: 'document.title', returnByValue: true
  406. }, { timeoutMs: 3000 })
  407. return String((result && result.value) || '')
  408. } catch { return '' }
  409. }
  410. // ---------------------------------------------------------------- 执行脚本
  411. async evaluate (tab, code, options = {}) {
  412. const cdp = await this.#cdpOf(tab)
  413. tab.lastUsed = Date.now()
  414. const timeoutMs = Math.min(Math.max(Number(options.timeoutMs) || 8000, 1), 20_000)
  415. const run = (expression) => cdp.send('Runtime.evaluate', {
  416. expression,
  417. awaitPromise: true,
  418. returnByValue: true,
  419. userGesture: true,
  420. allowUnsafeEvalBlockedByCSP: true
  421. }, { timeoutMs })
  422. // 桌面端用的是 executeJavaScript(code):按脚本执行,取"最后一条表达式的值"。
  423. // 这里先原样执行;只有语法错(典型是模型写了顶层 return)才包一层 async IIFE,
  424. // 而不是靠字符串里有没有 "return" 来判断 —— 那会误伤 querySelector('[type=return]')。
  425. let evaluated
  426. try {
  427. evaluated = await run(code)
  428. } catch (err) {
  429. if (!/超时/.test(err.message)) throw err
  430. throw err
  431. }
  432. if (evaluated.exceptionDetails && /SyntaxError/i.test(String(evaluated.exceptionDetails.text || ''))) {
  433. evaluated = await run(`(async () => { ${code} })()`)
  434. }
  435. const { result, exceptionDetails } = evaluated
  436. if (exceptionDetails) {
  437. const text = (exceptionDetails.exception && (exceptionDetails.exception.description || exceptionDetails.exception.value)) ||
  438. exceptionDetails.text || '脚本报错'
  439. throw new Error(String(text).split('\n')[0])
  440. }
  441. const raw = describeValue(result && result.value)
  442. const truncated = raw != null && raw.length >= MAX_RESULT
  443. return { value: raw, truncated }
  444. }
  445. // ---------------------------------------------------------------- 投递文件
  446. /**
  447. * 和外壳 dropFileIntoBrowser 对齐:有 pageFn 就交给页面函数,否则找 input[type=file]。
  448. * 差别只有一处:桌面端手里直接有 File 对象,这里必须让页面自己去取一次字节 ——
  449. * 所以文件通过一条带 token 的短时 URL 暴露给页面(见 files.js),
  450. * 页面里 fetch 完再 new File(),仍然是一个**真 File**,页面业务逻辑一行不用改。
  451. */
  452. async dropFile (tab, input) {
  453. const filePath = String(input.path || '')
  454. const stat = await fs.promises.stat(filePath).catch(() => null)
  455. if (!stat || !stat.isFile()) return { ok: false, error: 'file-missing' }
  456. if (stat.size > 512 * 1024 * 1024) return { ok: false, error: 'too-large', size: stat.size }
  457. const name = String(input.name || '').trim() || path.basename(filePath)
  458. const cdp = await this.#cdpOf(tab)
  459. if (input.pageFn) {
  460. const fnPath = input.pageFn.split('.').filter(Boolean)
  461. const argsMode = input.pageFnArgs === 'array' ? 'array' : 'single'
  462. const literal = JSON.stringify(fnPath)
  463. const type = guessType(filePath)
  464. /**
  465. * 页面拿到真 File 的两种方式,按体积选:
  466. *
  467. * ≤ 8MB —— 直接把字节内联进脚本。页面是 https、服务端是 http 时 fetch 会被
  468. * 浏览器按混合内容拦掉(本机联调就是这样),内联没有任何网络依赖。
  469. * 更大 —— 走带 token 的短时地址。要求部署在 https 上(同协议、公网域名),
  470. * 否则浏览器同样会拦;这条限制写进 docs/troubleshooting.md。
  471. */
  472. const INLINE_LIMIT = 8 * 1024 * 1024
  473. let loader
  474. if (stat.size <= INLINE_LIMIT) {
  475. const b64 = (await fs.promises.readFile(filePath)).toString('base64')
  476. loader = `const bin = atob(${JSON.stringify(b64)});
  477. const bytes = new Uint8Array(bin.length);
  478. for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
  479. const blob = new Blob([bytes], { type: ${JSON.stringify(type)} });`
  480. } else {
  481. const fileUrl = String(input.fileUrl || '')
  482. if (!fileUrl) {
  483. return { ok: false, error: 'no-file-url', hint: '文件超过 8MB,需要 https 部署才能交给页面函数' }
  484. }
  485. loader = `const res = await fetch(${JSON.stringify(fileUrl)}, { cache: 'no-store', credentials: 'omit' });
  486. if (!res.ok) return { ok: false, error: 'file-fetch-failed', status: res.status };
  487. const blob = await res.blob();`
  488. }
  489. const expression = `(async () => {
  490. const path = ${literal};
  491. let fn = window;
  492. for (const k of path) {
  493. fn = fn && fn[k];
  494. if (fn == null) break;
  495. }
  496. if (typeof fn !== 'function') return { ok: false, error: 'no-fn', fn: path.join('.') };
  497. ${loader}
  498. const file = new File([blob], ${JSON.stringify(name)}, { type: ${JSON.stringify(type)}, lastModified: Date.now() });
  499. const meta = { name: file.name, size: file.size, type: file.type, lastModified: file.lastModified };
  500. try {
  501. const out = ${argsMode === 'array' ? 'await fn([file], meta)' : 'await fn(file, meta)'};
  502. return { ok: true, value: out === undefined ? null : out };
  503. } catch (err) {
  504. return { ok: false, error: 'fn-threw', hint: String((err && err.message) || err) };
  505. }
  506. })()`
  507. const timeoutMs = Math.min(Number(input.pageFnTimeoutMs) || 120_000, 300_000)
  508. let evaluated
  509. try {
  510. evaluated = await cdp.send('Runtime.evaluate', {
  511. expression, awaitPromise: true, returnByValue: true, userGesture: true
  512. }, { timeoutMs })
  513. } catch (err) {
  514. if (err instanceof CDPError && /超时/.test(err.message)) {
  515. return { ok: false, error: 'fn-timeout', hint: '页面函数没有按时返回;文件已经交到页面手里,不要重复投递' }
  516. }
  517. throw err
  518. }
  519. const { result, exceptionDetails } = evaluated
  520. if (!result) return { ok: false, error: 'fn-timeout', hint: '页面函数没有按时返回;文件已经交到页面手里,不要重复投递' }
  521. if (exceptionDetails) {
  522. return { ok: false, error: 'fn-threw', hint: String(exceptionDetails.text || '页面函数抛错') }
  523. }
  524. const out = result.value || {}
  525. if (out.ok !== true) return { ...out, ok: false }
  526. return { ok: true, via: 'fn', fn: input.pageFn, name, size: stat.size, value: describeValue(out.value), url: tab.url }
  527. }
  528. const nodeId = await this.#findFileInput(tab, input.clickText)
  529. if (!nodeId) return { ok: false, error: 'no-target', hint: '页面上没有找到 input[type=file]' }
  530. await cdp.send('DOM.setFileInputFiles', { files: [filePath], nodeId }, { timeoutMs: 60_000 })
  531. return { ok: true, via: 'change', name, size: stat.size, url: tab.url }
  532. }
  533. /** 找上传控件;页面要"先点一下才露出控件"时按 clickText 点一次再找。 */
  534. async #findFileInput (tab, clickText) {
  535. const cdp = await this.#cdpOf(tab)
  536. const find = async () => {
  537. for (const expression of [
  538. `document.querySelector('input[type=file]')`,
  539. // 弹窗/组件里常见:控件在 shadow DOM 或同源 iframe 里
  540. `(() => {
  541. const walk = (root) => {
  542. const hit = root.querySelector && root.querySelector('input[type=file]')
  543. if (hit) return hit
  544. for (const el of root.querySelectorAll ? root.querySelectorAll('*') : []) {
  545. if (el.shadowRoot) { const h = walk(el.shadowRoot); if (h) return h }
  546. }
  547. for (const f of document.querySelectorAll('iframe')) {
  548. try { const d = f.contentDocument; if (d) { const h = walk(d); if (h) return h } } catch { /* 跨域 */ }
  549. }
  550. return null
  551. }
  552. return walk(document)
  553. })()`
  554. ]) {
  555. const { result } = await cdp.send('Runtime.evaluate', {
  556. expression: `(() => { const el = ${expression}; return el ? true : false })()`,
  557. returnByValue: true
  558. }, { timeoutMs: 4000 }).catch(() => ({ result: { value: false } }))
  559. if (result && result.value) {
  560. const { root } = await cdp.send('DOM.getDocument', { depth: -1, pierce: true })
  561. const { nodeId } = await cdp.send('DOM.querySelector', { nodeId: root.nodeId, selector: 'input[type=file]' })
  562. if (nodeId) return nodeId
  563. }
  564. }
  565. return 0
  566. }
  567. let nodeId = await find()
  568. if (nodeId) return nodeId
  569. const texts = (Array.isArray(clickText) ? clickText : []).filter(Boolean)
  570. for (const text of texts) {
  571. await cdp.send('Runtime.evaluate', {
  572. expression: `(() => {
  573. const want = ${JSON.stringify(String(text))}
  574. const nodes = [...document.querySelectorAll('button,a,div,span,li')]
  575. const hit = nodes.find((el) => (el.textContent || '').trim() === want) ||
  576. nodes.find((el) => (el.textContent || '').includes(want))
  577. if (!hit) return false
  578. hit.click()
  579. return true
  580. })()`,
  581. returnByValue: true,
  582. userGesture: true
  583. }).catch(() => {})
  584. for (let i = 0; i < 10; i += 1) {
  585. await sleep(150)
  586. nodeId = await find()
  587. if (nodeId) return nodeId
  588. }
  589. }
  590. return 0
  591. }
  592. // ---------------------------------------------------------------- 画面 / 输入
  593. /** 订阅某个页签的画面与状态。返回退订函数。 */
  594. subscribe (tab, fn) {
  595. const state = this.#screencastOf(tab)
  596. state.subs.add(fn)
  597. // 先把当前状态补一份:新接上的前端不该干等"下一次状态变化"(页面早就加载完了)
  598. const snapshot = [
  599. { type: 'state', field: 'url', value: tab.url },
  600. { type: 'state', field: 'title', value: tab.title },
  601. { type: 'state', field: 'loading', value: tab.loading }
  602. ]
  603. if (tab.error) snapshot.push({ type: 'state', field: 'error', value: tab.error })
  604. for (const item of snapshot) {
  605. try { fn(item) } catch { /* 订阅方自己处理 */ }
  606. }
  607. this.#startScreencast(tab).catch((err) => {
  608. this.log(`[browser] 起画面回传失败:${err.message}`)
  609. fn({ type: 'state', field: 'error', value: `画面回传失败:${err.message}` })
  610. })
  611. return () => {
  612. state.subs.delete(fn)
  613. if (state.subs.size === 0) this.#stopScreencast(tab).catch(() => {})
  614. }
  615. }
  616. #emit (tab, payload) {
  617. const state = this.screencast.get(tab.targetId)
  618. if (!state) return
  619. for (const fn of state.subs) {
  620. try { fn(payload) } catch { /* 订阅方自己处理 */ }
  621. }
  622. }
  623. #screencastOf (tab) {
  624. let state = this.screencast.get(tab.targetId)
  625. if (!state) {
  626. state = { subs: new Set(), active: false, meta: null, width: this.width, height: this.height }
  627. this.screencast.set(tab.targetId, state)
  628. }
  629. return state
  630. }
  631. async #startScreencast (tab) {
  632. const state = this.#screencastOf(tab)
  633. if (state.active) return
  634. const cdp = await this.#cdpOf(tab)
  635. state.active = true
  636. // 视口按前端画布尺寸设,超出会被缩;这样页面拿到的是"平板/桌面浏览器"尺寸,
  637. // 不是 headless 默认的 800×600(否则平台页面会走移动断点)
  638. await cdp.send('Emulation.setDeviceMetricsOverride', {
  639. width: state.width, height: state.height, deviceScaleFactor: 1, mobile: false
  640. }).catch(() => {})
  641. cdp.on('Page.screencastFrame', ({ data, metadata, sessionId }) => {
  642. state.meta = metadata || null
  643. cdp.send('Page.screencastFrameAck', { sessionId }).catch(() => {})
  644. this.#emit(tab, {
  645. type: 'frame',
  646. jpeg: Buffer.from(String(data || ''), 'base64'),
  647. meta: metadata || {}
  648. })
  649. })
  650. await cdp.send('Page.startScreencast', {
  651. format: 'jpeg',
  652. quality: 72,
  653. maxWidth: state.width,
  654. maxHeight: state.height,
  655. everyNthFrame: 1
  656. })
  657. }
  658. async #stopScreencast (tab) {
  659. const state = this.#screencastOf(tab)
  660. state.active = false
  661. try { await tab.cdp?.send('Page.stopScreencast') } catch { /* 连接可能已断 */ }
  662. }
  663. /** 前端画布尺寸变了:重设视口并重开回传,避免画面被拉伸。 */
  664. async resize (tab, width, height) {
  665. const state = this.#screencastOf(tab)
  666. const w = Math.max(320, Math.min(Number(width) || 0, 2560))
  667. const h = Math.max(240, Math.min(Number(height) || 0, 1600))
  668. if (w === state.width && h === state.height) return
  669. state.width = w
  670. state.height = h
  671. const cdp = await this.#cdpOf(tab)
  672. await cdp.send('Emulation.setDeviceMetricsOverride', {
  673. width: w, height: h, deviceScaleFactor: 1, mobile: false
  674. }).catch(() => {})
  675. if (state.active) {
  676. await cdp.send('Page.stopScreencast').catch(() => {})
  677. await cdp.send('Page.startScreencast', {
  678. format: 'jpeg', quality: 72, maxWidth: w, maxHeight: h, everyNthFrame: 1
  679. }).catch(() => {})
  680. }
  681. }
  682. // ------------------------------------------------------------------ 输入
  683. async input (tab, msg) {
  684. const cdp = await this.#cdpOf(tab)
  685. tab.lastUsed = Date.now()
  686. // 前端已经把画布坐标换算成页面 CSS 像素(它知道帧尺寸与 deviceWidth),
  687. // 这里不再做二次换算,避免两边各缩一次。
  688. if (msg.t === 'mouse') {
  689. const x = Number(msg.x) || 0
  690. const y = Number(msg.y) || 0
  691. const button = msg.button === 'right' ? 'right' : msg.button === 'middle' ? 'middle' : 'left'
  692. const buttons = msg.buttons != null ? Number(msg.buttons) : (msg.action === 'down' ? 1 : 0)
  693. if (msg.action === 'wheel') {
  694. await cdp.send('Input.dispatchMouseEvent', {
  695. type: 'mouseWheel', x, y, deltaX: Number(msg.deltaX) || 0, deltaY: Number(msg.deltaY) || 0,
  696. modifiers: Number(msg.modifiers) || 0
  697. })
  698. return
  699. }
  700. const type = msg.action === 'down' ? 'mousePressed' : msg.action === 'up' ? 'mouseReleased' : 'mouseMoved'
  701. await cdp.send('Input.dispatchMouseEvent', {
  702. type, x, y, button: type === 'mouseMoved' ? 'none' : button,
  703. buttons, clickCount: msg.action === 'move' ? 0 : (msg.clickCount || 1),
  704. pointerType: msg.pointerType === 'touch' ? 'mouse' : 'mouse',
  705. modifiers: Number(msg.modifiers) || 0
  706. })
  707. return
  708. }
  709. if (msg.t === 'key') {
  710. const key = String(msg.key || '')
  711. const code = String(msg.code || '')
  712. const vk = Number(msg.keyCode) || keyCodeOf(key, code)
  713. const modifiers = Number(msg.modifiers) || 0
  714. const printable = key.length === 1 && !msg.ctrlOnly
  715. if (msg.action === 'down') {
  716. await cdp.send('Input.dispatchKeyEvent', {
  717. type: printable ? 'keyDown' : 'rawKeyDown',
  718. key, code, windowsVirtualKeyCode: vk, nativeVirtualKeyCode: vk,
  719. text: printable ? key : (key === 'Enter' ? '\r' : undefined),
  720. unmodifiedText: printable ? key : undefined,
  721. modifiers, autoRepeat: !!msg.repeat
  722. })
  723. if (!printable && key === 'Enter') {
  724. await cdp.send('Input.dispatchKeyEvent', {
  725. type: 'char', key: '\r', text: '\r', unmodifiedText: '\r', modifiers
  726. }).catch(() => {})
  727. }
  728. } else {
  729. await cdp.send('Input.dispatchKeyEvent', {
  730. type: 'keyUp', key, code, windowsVirtualKeyCode: vk, nativeVirtualKeyCode: vk, modifiers
  731. })
  732. }
  733. return
  734. }
  735. if (msg.t === 'text') {
  736. await cdp.send('Input.insertText', { text: String(msg.text || '') })
  737. return
  738. }
  739. if (msg.t === 'nav') {
  740. const url = String(msg.url || '')
  741. if (!/^https?:\/\//i.test(url)) throw new Error('只支持 http(s) 地址')
  742. await this.navigate(tab, url)
  743. return
  744. }
  745. if (msg.t === 'close') {
  746. await this.closeTab(tab.targetId)
  747. return
  748. }
  749. }
  750. // ------------------------------------------------------------------ 日志
  751. #pushLog (tab, level, args) {
  752. const text = (args || []).map((a) => {
  753. if (a == null) return ''
  754. if ('value' in a) return typeof a.value === 'string' ? a.value : JSON.stringify(a.value)
  755. if (a.description) return String(a.description)
  756. return String(a.type || '')
  757. }).join(' ').slice(0, 4000)
  758. const list = this.logs.get(tab.targetId) || []
  759. list.push({ level, text, at: Date.now() })
  760. if (list.length > 200) list.shift()
  761. this.logs.set(tab.targetId, list)
  762. this.#emit(tab, { type: 'log', level, text })
  763. }
  764. logsOf (tab) {
  765. return this.logs.get(tab.targetId) || []
  766. }
  767. }
  768. /** 键盘事件缺 keyCode 时按 key/code 兜底,否则平台页面的快捷键分支识别不到 */
  769. function keyCodeOf (key, code) {
  770. const special = {
  771. Enter: 13, Tab: 9, Backspace: 8, Escape: 27, Delete: 46, ' ': 32,
  772. ArrowLeft: 37, ArrowUp: 38, ArrowRight: 39, ArrowDown: 40,
  773. Home: 36, End: 35, PageUp: 33, PageDown: 34,
  774. Shift: 16, Control: 17, Alt: 18, Meta: 91, CapsLock: 20
  775. }
  776. if (special[key]) return special[key]
  777. if (/^F\d{1,2}$/.test(key)) return 111 + Number(key.slice(1))
  778. if (key.length === 1) {
  779. const up = key.toUpperCase()
  780. if (/[A-Z]/.test(up)) return up.charCodeAt(0)
  781. if (/[0-9]/.test(key)) return key.charCodeAt(0)
  782. return up.charCodeAt(0)
  783. }
  784. const m = /^Key([A-Z])$/.exec(code || '')
  785. if (m) return m[1].charCodeAt(0)
  786. const d = /^Digit([0-9])$/.exec(code || '')
  787. if (d) return d[1].charCodeAt(0)
  788. return 0
  789. }