index.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  1. /**
  2. * CocoBuddy Web 版 · 入口
  3. * =====================
  4. * 一条原则:**一个源站,一个 cookie,其余全部转给这位老师自己的引擎。**
  5. *
  6. * / 引擎原生 Web 界面(会话、技能、斜杠菜单都是现成的)
  7. * /_cc/login 登录页(平台账号 / apiKey)
  8. * /_cc/api/* Web 层自己的接口(会话、积分、文件、浏览器)
  9. * /_cc/rt 右侧页面的画面回传 + 输入(WebSocket)
  10. * /_cc/blob/:token 页面取文件的短时地址(投递上传用)
  11. *
  12. * 不按 /app/<用户>/ 划分子路径:引擎前端全是绝对路径资源,挂子路径只会引入
  13. * 一堆 base 配置;用 cookie 认人更省事,也和"老师只会有一个账号"这件事一致。
  14. */
  15. import http from 'node:http'
  16. import fs from 'node:fs'
  17. import fsp from 'node:fs/promises'
  18. import path from 'node:path'
  19. import crypto from 'node:crypto'
  20. import { fileURLToPath } from 'node:url'
  21. import { config, preflight, REGIONS, normalizeLocale } from './config.js'
  22. import * as auth from './lib/auth.js'
  23. import * as platform from './lib/platform.js'
  24. import { SessionManager } from './lib/session.js'
  25. import { createProxy } from './lib/proxy.js'
  26. import { WSConnection, rejectUpgrade } from './lib/ws.js'
  27. const here = path.dirname(fileURLToPath(import.meta.url))
  28. // ------------------------------------------------------------------ 日志
  29. function log (message, level = 'info') {
  30. const order = { debug: 10, info: 20, warn: 30, error: 40 }
  31. if (order[level] < order[config.logLevel]) return
  32. const stamp = new Date().toISOString().replace('T', ' ').slice(0, 19)
  33. process.stdout.write(`[${stamp}] ${level.toUpperCase()} ${message}\n`)
  34. }
  35. // ------------------------------------------------------------------ 注入脚本
  36. const injectDir = path.join(here, 'inject')
  37. const shimSource = fs.readFileSync(path.join(injectDir, 'cocorobo-shim.js'), 'utf8')
  38. const polyfillSource = fs.readFileSync(path.join(injectDir, 'webview-polyfill.js'), 'utf8')
  39. const loginHtml = fs.readFileSync(path.join(injectDir, 'login.html'), 'utf8')
  40. const callbackHtml = fs.readFileSync(path.join(injectDir, 'callback.html'), 'utf8')
  41. /** 每页注入:先给语言/区域这类同步就要读的值,再挂 shim 与 <webview> 实现 */
  42. function injectFor (session) {
  43. const region = REGIONS[session.user.region] || REGIONS[config.defaultRegion]
  44. const boot = {
  45. locale: session.user.locale || 'zh-CN',
  46. region: session.user.region || config.defaultRegion,
  47. uid: session.uid,
  48. cococlassUrl: `${region.platform}/`,
  49. llmBaseURL: config.llm.baseURL,
  50. // 前端据此决定 <webview> 是"接服务端画面"还是"交给老师自己的浏览器"
  51. pageMode: config.pageMode
  52. }
  53. return [
  54. `<script>window.__CC__=${JSON.stringify(boot)}</script>`,
  55. `<script>${shimSource.replace(/<\/script>/gi, '<\\/script>')}</script>`,
  56. `<script>${polyfillSource.replace(/<\/script>/gi, '<\\/script>')}</script>`
  57. ].join('\n')
  58. }
  59. // ------------------------------------------------------------------ 工具
  60. const MAX_JSON = 2 * 1024 * 1024
  61. function readJson (req) {
  62. return new Promise((resolve, reject) => {
  63. let size = 0
  64. const chunks = []
  65. req.on('data', (chunk) => {
  66. size += chunk.length
  67. if (size > MAX_JSON) { reject(Object.assign(new Error('请求体过大'), { status: 413 })); req.destroy(); return }
  68. chunks.push(chunk)
  69. })
  70. req.on('end', () => {
  71. if (!chunks.length) return resolve({})
  72. try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8'))) } catch (err) {
  73. reject(Object.assign(new Error('请求体不是合法 JSON'), { status: 400 }))
  74. }
  75. })
  76. req.on('error', reject)
  77. })
  78. }
  79. function sendJson (res, status, body, headers = {}) {
  80. const text = JSON.stringify(body)
  81. res.writeHead(status, {
  82. 'content-type': 'application/json; charset=utf-8',
  83. 'cache-control': 'no-store',
  84. ...headers
  85. })
  86. res.end(text)
  87. }
  88. function sendHtml (res, status, html, headers = {}) {
  89. res.writeHead(status, {
  90. 'content-type': 'text/html; charset=utf-8',
  91. 'cache-control': 'no-store',
  92. ...headers
  93. })
  94. res.end(html)
  95. }
  96. function wantsHtml (req) {
  97. return /text\/html/.test(String(req.headers.accept || ''))
  98. }
  99. function clientIp (req) {
  100. if (config.trustProxy) {
  101. const fwd = String(req.headers['x-forwarded-for'] || '').split(',')[0].trim()
  102. if (fwd) return fwd
  103. }
  104. return String(req.socket.remoteAddress || '')
  105. }
  106. // 登录失败限速:同一 IP 每分钟 8 次,防撞库(进程内计数,够用)
  107. const loginAttempts = new Map()
  108. function tooManyAttempts (ip) {
  109. const now = Date.now()
  110. const entry = loginAttempts.get(ip) || { count: 0, reset: now + 60_000 }
  111. if (entry.reset < now) { entry.count = 0; entry.reset = now + 60_000 }
  112. entry.count += 1
  113. loginAttempts.set(ip, entry)
  114. return entry.count > 8
  115. }
  116. // ------------------------------------------------------------------ 单点登录
  117. /** 老师浏览器看到的基地址:优先 CC_PUBLIC_BASE,反代下退到 X-Forwarded-* 与 Host。 */
  118. function publicBaseOf (req) {
  119. if (config.publicBase) return config.publicBase
  120. const proto = String(req.headers['x-forwarded-proto'] || '').split(',')[0].trim() || 'http'
  121. const host = String(req.headers['x-forwarded-host'] || req.headers.host || `127.0.0.1:${config.port}`)
  122. .split(',')[0].trim()
  123. return `${proto}://${host}`
  124. }
  125. /** 平台登录页地址 + 回调参数。参数名与桌面端完全一致(含 form/from 的兼容写法)。 */
  126. function ssoLoginUrl (req, state) {
  127. const url = new URL(config.ssoUrl)
  128. url.searchParams.set('form', 'desktop')
  129. url.searchParams.set('from', 'desktop')
  130. url.searchParams.set('state', state)
  131. url.searchParams.set(config.ssoRedirectParam, `${publicBaseOf(req)}/_cc/callback`)
  132. return url.toString()
  133. }
  134. /**
  135. * 接住平台登录后的回调。
  136. * 平台带回来的是 apiKey + 身份(userid/username/schoolname/organizeid),
  137. * 与桌面端 `cocorobo://auth/callback` 拿到的是同一组参数,语义也一致:
  138. * key 由平台签发,等同于一次成功登录,不再二次校验。
  139. */
  140. async function handleSsoCallback (req, res, url) {
  141. const cookies = auth.parseCookies(req.headers.cookie)
  142. const savedState = cookies.cc_sso_state || ''
  143. const gotState = url.searchParams.get('state') || ''
  144. const clearState = 'cc_sso_state=; Path=/_cc; HttpOnly; SameSite=Lax; Max-Age=0'
  145. // state 只为挡住"第三方构造好的登录链接",平台没回传时不强求
  146. if (savedState && gotState && savedState !== gotState) {
  147. log('[sso] state 不匹配,拒绝', 'warn')
  148. res.writeHead(302, {
  149. location: '/_cc/login?err=' + encodeURIComponent('登录状态校验失败,请重新登录') + '&local=1',
  150. 'set-cookie': clearState,
  151. 'cache-control': 'no-store'
  152. })
  153. return res.end()
  154. }
  155. const key = String(
  156. url.searchParams.get('apiKey') ||
  157. url.searchParams.get('api_key') ||
  158. url.searchParams.get('key') ||
  159. url.searchParams.get('token') ||
  160. ''
  161. ).trim()
  162. // 没带 key:返回落地页,由浏览器读 location.hash
  163. if (!key) {
  164. res.writeHead(200, {
  165. 'content-type': 'text/html; charset=utf-8',
  166. 'cache-control': 'no-store',
  167. 'set-cookie': clearState
  168. })
  169. return res.end(callbackHtml)
  170. }
  171. const raw = String(url.searchParams.get('region') || '')
  172. const regionKey = REGIONS[raw] ? raw : config.defaultRegion
  173. const userid = String(url.searchParams.get('userid') || url.searchParams.get('userId') || '').trim()
  174. try {
  175. let user
  176. if (userid) {
  177. // 平台已经把身份带回来了:和桌面端走同一条"信任回调"的路
  178. user = {
  179. apiKey: key,
  180. userid,
  181. username: String(url.searchParams.get('username') || url.searchParams.get('name') || ''),
  182. organizeId: String(url.searchParams.get('organizeid') || url.searchParams.get('organizeId') || url.searchParams.get('orgId') || ''),
  183. organizeName: String(url.searchParams.get('schoolname') || url.searchParams.get('organizeName') || url.searchParams.get('orgName') || '')
  184. }
  185. } else {
  186. // 只带 key 的旧回调:用平台接口反查身份
  187. if (tooManyAttempts(clientIp(req))) {
  188. res.writeHead(302, { location: '/_cc/login?err=' + encodeURIComponent('尝试太频繁,请一分钟后再试') + '&local=1', 'cache-control': 'no-store' })
  189. return res.end()
  190. }
  191. user = await platform.verifyKey({ region: REGIONS[regionKey], apiKey: key })
  192. }
  193. user.region = regionKey
  194. user.locale = normalizeLocale(raw || regionKey)
  195. const created = auth.create(user)
  196. log(`[sso] ${user.userid || user.username || 'user'} 登录成功`)
  197. res.writeHead(302, {
  198. location: '/',
  199. 'set-cookie': [auth.cookieOf(created.sid), clearState],
  200. 'cache-control': 'no-store'
  201. })
  202. return res.end()
  203. } catch (err) {
  204. log(`[sso] ${err.message}`, 'warn')
  205. res.writeHead(302, {
  206. location: '/_cc/login?err=' + encodeURIComponent(err.message || '登录失败') + '&local=1',
  207. 'set-cookie': clearState,
  208. 'cache-control': 'no-store'
  209. })
  210. return res.end()
  211. }
  212. }
  213. // ------------------------------------------------------------------ 引导页
  214. function bootPage (sess) {
  215. const state = sess.engine ? '引擎就绪' : '正在启动引擎…'
  216. return `<!doctype html><html><head><meta charset="utf-8">
  217. <meta name="viewport" content="width=device-width,initial-scale=1">
  218. <title>CocoBuddy</title>
  219. <style>
  220. html,body{height:100%;margin:0;background:#f7f8fa;color:#1d2129;
  221. font:15px/1.6 -apple-system,"Segoe UI",system-ui,"PingFang SC","Microsoft YaHei",sans-serif}
  222. .wrap{height:100%;display:flex;align-items:center;justify-content:center}
  223. .box{text-align:center;max-width:420px;padding:0 24px}
  224. .spin{width:34px;height:34px;margin:0 auto 18px;border-radius:50%;
  225. border:3px solid #e5e8ef;border-top-color:#2f6bff;animation:r .9s linear infinite}
  226. @keyframes r{to{transform:rotate(360deg)}}
  227. h1{font-size:17px;font-weight:600;margin:0 0 6px}
  228. p{margin:0;color:#6b7280;font-size:13px}
  229. .err{color:#c0392b;white-space:pre-wrap;text-align:left;background:#fff;border:1px solid #f0d0cb;
  230. border-radius:10px;padding:12px;margin-top:16px;font-size:12px;max-height:260px;overflow:auto}
  231. </style></head><body><div class="wrap"><div class="box">
  232. <div class="spin" id="spin"></div>
  233. <h1 id="title">正在为你准备环境</h1>
  234. <p id="hint">${state} · 首次启动大约需要 20–60 秒</p>
  235. <div class="err" id="err" hidden></div>
  236. </div></div>
  237. <script>
  238. var tries = 0
  239. var timer = setInterval(async function () {
  240. tries += 1
  241. try {
  242. var res = await fetch('/_cc/api/ready', { cache: 'no-store' })
  243. var info = await res.json()
  244. if (info.ready) { clearInterval(timer); location.replace('/'); return }
  245. if (info.error) {
  246. clearInterval(timer)
  247. document.getElementById('spin').style.display = 'none'
  248. document.getElementById('title').textContent = '启动失败'
  249. document.getElementById('hint').textContent = '把下面的信息发给管理员'
  250. var box = document.getElementById('err')
  251. box.hidden = false
  252. box.textContent = info.error
  253. return
  254. }
  255. if (info.stage) document.getElementById('hint').textContent = info.stage
  256. } catch (err) { /* 服务还在起 */ }
  257. if (tries > 120) { clearInterval(timer); document.getElementById('hint').textContent = '等太久了,刷新一下页面' }
  258. }, 1200)
  259. </script></body></html>`
  260. }
  261. // ------------------------------------------------------------------ 主体
  262. const manager = new SessionManager((msg, level) => log(msg, level))
  263. const proxy = createProxy({ log })
  264. /** 会话 → 确保环境;返回 null 表示还在启动(调用方去吐引导页) */
  265. async function ensureSession (session, res, req, forApi = false) {
  266. if (session.engine && session.engine.port && session.engine.child) return session
  267. session.ensure().catch((err) => {
  268. log(`[session ${session.uid}] 启动失败:${err.message}`, 'error')
  269. session.problem = err.message
  270. })
  271. if (forApi) {
  272. sendJson(res, 503, { ok: false, error: 'starting', stage: '环境正在启动' })
  273. } else if (wantsHtml(req)) {
  274. sendHtml(res, 200, bootPage(session))
  275. } else {
  276. res.writeHead(503, { 'retry-after': '3', 'content-type': 'text/plain; charset=utf-8' })
  277. res.end('starting')
  278. }
  279. return null
  280. }
  281. async function handleInternal (req, res, url, session) {
  282. const p = url.pathname
  283. if (p === '/_cc/login' && req.method === 'GET') {
  284. // 配了平台单点登录:直接去平台自己的登录界面(和桌面端同一套账号与回调)。
  285. // 带 err / local 时留在本页,否则回调失败会来回跳成死循环;
  286. // ?sso=1 供本地表单上的「用平台账号登录」按钮使用。
  287. const keepLocal = url.searchParams.has('err') || url.searchParams.has('local')
  288. const wantSso = url.searchParams.has('sso')
  289. if (config.ssoUrl && (wantSso || (config.ssoAuto && !keepLocal))) {
  290. try {
  291. const state = crypto.randomBytes(16).toString('base64url')
  292. res.writeHead(302, {
  293. location: ssoLoginUrl(req, state),
  294. 'set-cookie': `cc_sso_state=${state}; Path=/_cc; HttpOnly; SameSite=Lax; Max-Age=600`,
  295. 'cache-control': 'no-store'
  296. })
  297. return res.end()
  298. } catch (err) {
  299. log(`[sso] CC_SSO_URL 不合法:${err.message}`, 'warn')
  300. }
  301. }
  302. const boot = config.ssoUrl
  303. ? { sso: { url: config.ssoUrl, param: config.ssoRedirectParam } }
  304. : {}
  305. const html = loginHtml.replaceAll('__CC_SSO_JSON__', () => JSON.stringify(boot).replace(/</g, '\\u003c'))
  306. return sendHtml(res, 200, html)
  307. }
  308. if (p === '/_cc/callback' && req.method === 'GET') {
  309. return handleSsoCallback(req, res, url)
  310. }
  311. if (p === '/_cc/api/login' && req.method === 'POST') {
  312. const ip = clientIp(req)
  313. if (tooManyAttempts(ip)) return sendJson(res, 429, { ok: false, error: '尝试太频繁,请一分钟后再试' })
  314. const body = await readJson(req)
  315. const regionKey = String(body.region || config.defaultRegion)
  316. const region = REGIONS[regionKey] || REGIONS[config.defaultRegion]
  317. const locale = normalizeLocale(body.locale || regionKey)
  318. try {
  319. let user
  320. if (body.apiKey) {
  321. user = await platform.verifyKey({ region, apiKey: String(body.apiKey).trim() })
  322. } else {
  323. user = await platform.login({
  324. region,
  325. mode: body.mode,
  326. account: String(body.account || '').trim(),
  327. password: String(body.password || ''),
  328. code: String(body.code || ''),
  329. deviceId: String(body.deviceId || ''),
  330. clientVersion: 'web'
  331. })
  332. }
  333. user.region = regionKey
  334. user.locale = locale
  335. const created = auth.create(user)
  336. loginAttempts.delete(ip)
  337. return sendJson(res, 200, {
  338. ok: true,
  339. user: { userid: user.userid, username: user.username, organizeName: user.organizeName }
  340. }, { 'set-cookie': auth.cookieOf(created.sid) })
  341. } catch (err) {
  342. log(`[login] ${err.message}`, 'warn')
  343. return sendJson(res, 401, { ok: false, error: err.message || '登录失败' })
  344. }
  345. }
  346. if (p === '/_cc/api/logout' && req.method === 'POST') {
  347. if (session) {
  348. await manager.peek(session.user)?.stop('退出登录').catch(() => {})
  349. auth.drop(session.sid)
  350. }
  351. return sendJson(res, 200, { ok: true }, { 'set-cookie': auth.clearCookie() })
  352. }
  353. if (!session) {
  354. if (p.startsWith('/_cc/api/')) return sendJson(res, 401, { ok: false, error: 'not-logged-in' })
  355. res.writeHead(302, { location: '/_cc/login' })
  356. return res.end()
  357. }
  358. // 这里往下都要操作"运行环境"(引擎/浏览器/工作区),所以统一换成 live 会话对象。
  359. // session 是登录凭据(sid + user),live 是这台服务器上属于这个老师的那套进程。
  360. const live = manager.peek(session.user) || manager.getOrCreate(session.user)
  361. if (p === '/_cc/api/session') {
  362. const region = REGIONS[session.user.region] || REGIONS[config.defaultRegion]
  363. return sendJson(res, 200, {
  364. user: {
  365. id: session.user.userid || '',
  366. userid: session.user.userid || '',
  367. name: session.user.username || '',
  368. organizeId: session.user.organizeId || '',
  369. organizeName: session.user.organizeName || ''
  370. },
  371. locale: session.user.locale || 'zh-CN',
  372. region: session.user.region || config.defaultRegion,
  373. llmBaseURL: config.llm.baseURL,
  374. platformBase: region.platform,
  375. uid: session.uid,
  376. // 前端据此决定右侧栏是"服务端画面"还是"外链页签":
  377. // api 模式没有页面可推流,只能把地址交给老师自己的浏览器。
  378. pageMode: config.pageMode
  379. })
  380. }
  381. if (p === '/_cc/api/ready') {
  382. const live = manager.peek(session.user)
  383. return sendJson(res, 200, {
  384. ready: !!(live && live.engine && live.engine.port),
  385. // 只按引擎判断阶段:api 模式下 browser 永远是 null,
  386. // 用它当条件会让界面永久停在"正在启动运行时"。
  387. stage: live ? (live.engine ? '引擎就绪' : '正在启动引擎…') : '正在启动运行时…',
  388. pageMode: config.pageMode,
  389. error: (live && live.problem) || session.problem || ''
  390. })
  391. }
  392. if (p === '/_cc/api/points') {
  393. try {
  394. const region = REGIONS[session.user.region] || REGIONS[config.defaultRegion]
  395. const json = await platform.pointsUsage({
  396. region, apiKey: session.user.apiKey, userId: session.user.userid
  397. })
  398. const num = (v) => (Number.isFinite(Number(v)) ? Number(v) : 0)
  399. const balance = num(json.balance)
  400. return sendJson(res, 200, {
  401. ok: true,
  402. balance,
  403. state: String(json.state || (balance <= 0 ? 'empty' : 'ok')),
  404. lowAt: num(json.low_at),
  405. available: json.available === undefined ? Math.max(balance, 0) : num(json.available),
  406. debt: num(json.debt),
  407. topupUrl: String(json.topup_url || ''),
  408. canTopup: json.can_topup === true,
  409. canChat: json.can_chat !== false,
  410. today: num(json.today_consumed),
  411. total: num(json.total_consumed),
  412. granted: num(json.total_granted),
  413. last: json.last_usage || null,
  414. at: Date.now()
  415. })
  416. } catch (err) {
  417. return sendJson(res, 200, { ok: false, error: err.message })
  418. }
  419. }
  420. if (p === '/_cc/api/points/url') {
  421. const region = REGIONS[session.user.region] || REGIONS[config.defaultRegion]
  422. return sendJson(res, 200, {
  423. url: platform.pointsPageUrl({
  424. region, userId: session.user.userid, locale: session.user.locale
  425. })
  426. })
  427. }
  428. // ---------------------------------------------------------- 右侧浏览器
  429. // API 模式统一在这里回话:前端拿到 mode:'external' 就把地址交给老师自己的浏览器
  430. // (同域,登录态本来就在老师本机),右侧栏显示成外链页签,不再等服务端画面。
  431. if (config.pageMode !== 'browser' && p.startsWith('/_cc/api/browser/')) {
  432. const body = req.method === 'POST' ? await readJson(req).catch(() => ({})) : {}
  433. if (p === '/_cc/api/browser/tabs') {
  434. return sendJson(res, 200, { ok: true, mode: 'external', tabs: [], guest: '' })
  435. }
  436. if (p === '/_cc/api/browser/open' || p === '/_cc/api/browser/attach') {
  437. const target = String(body.url || '')
  438. if (!target) return sendJson(res, 200, { ok: false, mode: 'external', error: 'empty-url' })
  439. return sendJson(res, 200, { ok: true, mode: 'external', url: target })
  440. }
  441. if (p === '/_cc/api/browser/drop') {
  442. // 投递需要真页面,这里不能假装成功,否则技能会以为文件已经进页面了
  443. return sendJson(res, 200, { ok: false, mode: 'external', error: 'page-mode-api' })
  444. }
  445. return sendJson(res, 200, { ok: true, mode: 'external' })
  446. }
  447. if (p === '/_cc/api/browser/open' && req.method === 'POST') {
  448. if (!(await ensureSession(live, res, req, true))) return
  449. const body = await readJson(req)
  450. try {
  451. const tab = await live.browser.openTab(String(body.url || ''))
  452. return sendJson(res, 200, { ok: true, tabId: tab.targetId, key: tab.key, url: tab.url })
  453. } catch (err) {
  454. return sendJson(res, 200, { ok: false, error: err.message })
  455. }
  456. }
  457. if (p === '/_cc/api/browser/attach' && req.method === 'POST') {
  458. if (!(await ensureSession(live, res, req, true))) return
  459. const body = await readJson(req)
  460. try {
  461. const tab = await attachTab(session, String(body.url || ''))
  462. return sendJson(res, 200, { ok: true, tabId: tab.targetId, key: tab.key, url: tab.url })
  463. } catch (err) {
  464. return sendJson(res, 200, { ok: false, error: err.message })
  465. }
  466. }
  467. if (p === '/_cc/api/browser/reload' && req.method === 'POST') {
  468. if (!(await ensureSession(live, res, req, true))) return
  469. const body = await readJson(req)
  470. const tab = tabOf(session, body.tabId)
  471. if (!tab) return sendJson(res, 404, { ok: false, error: 'no-tab' })
  472. await live.browser.reload(tab, body.hard === true).catch(() => {})
  473. return sendJson(res, 200, { ok: true })
  474. }
  475. if (p === '/_cc/api/browser/close' && req.method === 'POST') {
  476. const body = await readJson(req)
  477. const tab = tabOf(session, body.tabId)
  478. if (!tab) return sendJson(res, 404, { ok: false, error: 'no-tab' })
  479. await live.browser.closeTab(tab.targetId).catch(() => {})
  480. return sendJson(res, 200, { ok: true })
  481. }
  482. if (p === '/_cc/api/browser/tabs' && req.method === 'GET') {
  483. const browser = live.browser
  484. if (!browser) return sendJson(res, 200, { ok: true, tabs: [] })
  485. const guest = browser.pickGuest(url.searchParams.get('urlMatch') || '')
  486. return sendJson(res, 200, { ok: true, tabs: browser.list(), guest: guest ? guest.targetId : '' })
  487. }
  488. if (p === '/_cc/api/browser/drop' && req.method === 'POST') {
  489. if (!(await ensureSession(live, res, req, true))) return
  490. const body = await readJson(req)
  491. const tab = body.urlMatch || !body.tabId
  492. ? live.browser.pickGuest(String(body.urlMatch || ''))
  493. : tabOf(session, body.tabId)
  494. if (!tab) return sendJson(res, 200, { ok: false, error: 'no-guest' })
  495. const abs = live.files.resolve(String(body.path || ''))
  496. if (!abs) return sendJson(res, 200, { ok: false, error: 'path-not-allowed' })
  497. const result = await live.browser.dropFile(tab, {
  498. path: abs,
  499. name: String(body.name || ''),
  500. clickText: Array.isArray(body.clickText) ? body.clickText : [],
  501. pageFn: String(body.pageFn || ''),
  502. pageFnArgs: body.pageFnArgs === 'array' ? 'array' : 'single',
  503. pageFnTimeoutMs: Number(body.pageFnTimeoutMs) || 0,
  504. fileUrl: live.files.blobUrl(abs, live.origin || config.publicBase)
  505. })
  506. return sendJson(res, 200, result)
  507. }
  508. // ---------------------------------------------------------- 文件
  509. if (p === '/_cc/api/files' && req.method === 'GET') {
  510. const list = await live.files?.list(url.searchParams.get('path') || '')
  511. return sendJson(res, 200, { ok: !!list, root: live.dir.workspace, entries: list || [] })
  512. }
  513. if (p === '/_cc/api/files/upload' && req.method === 'POST') {
  514. if (!live.files) return sendJson(res, 503, { ok: false, error: 'starting' })
  515. try {
  516. const saved = await live.files.saveUpload(url.searchParams.get('name') || 'upload.bin', req)
  517. return sendJson(res, 200, { ok: true, path: saved.path, name: saved.name, size: saved.size })
  518. } catch (err) {
  519. return sendJson(res, err.code === 'too_large' ? 413 : 500, { ok: false, error: err.message })
  520. }
  521. }
  522. if (p === '/_cc/api/files/download' && req.method === 'GET') {
  523. const abs = live.files?.resolve(url.searchParams.get('path') || '')
  524. const info = abs ? await fsp.stat(abs).catch(() => null) : null
  525. if (!abs || !info || !info.isFile()) {
  526. res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
  527. return res.end('not found')
  528. }
  529. res.writeHead(200, {
  530. 'content-type': 'application/octet-stream',
  531. 'content-length': String(info.size),
  532. 'content-disposition': `attachment; filename*=UTF-8''${encodeURIComponent(path.basename(abs))}`
  533. })
  534. fs.createReadStream(abs).pipe(res)
  535. return
  536. }
  537. if (p.startsWith('/_cc/blob/') && req.method === 'GET') {
  538. const file = live.files?.takeBlob(p.slice('/_cc/blob/'.length))
  539. const info = file ? await fsp.stat(file).catch(() => null) : null
  540. if (!file || !info) {
  541. res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
  542. return res.end('expired')
  543. }
  544. // 页面(平台域名)跨源取这个文件:必须放开 CORS,且不能带 cookie
  545. res.writeHead(200, {
  546. 'content-type': guessType(file),
  547. 'content-length': String(info.size),
  548. 'access-control-allow-origin': '*',
  549. 'cache-control': 'no-store'
  550. })
  551. fs.createReadStream(file).pipe(res)
  552. return
  553. }
  554. sendJson(res, 404, { ok: false, error: 'not-found' })
  555. }
  556. function tabOf (live, tabId) {
  557. if (!live.browser || !tabId) return null
  558. return live.browser.tabs.get(String(tabId)) || null
  559. }
  560. async function attachTab (live, url) {
  561. const browser = live.browser
  562. const host = (() => { try { return new URL(url).host } catch { return '' } })()
  563. for (const tab of browser.tabs.values()) {
  564. try {
  565. if (new URL(tab.url).host === host) {
  566. tab.lastUsed = Date.now()
  567. return tab
  568. }
  569. } catch { /* about:blank 之类,跳过 */ }
  570. }
  571. return browser.openTab(url)
  572. }
  573. function guessType (file) {
  574. const ext = path.extname(file).toLowerCase()
  575. const map = {
  576. '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif',
  577. '.webp': 'image/webp', '.svg': 'image/svg+xml', '.pdf': 'application/pdf',
  578. '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  579. '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  580. '.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  581. '.json': 'application/json', '.txt': 'text/plain; charset=utf-8', '.html': 'text/html; charset=utf-8'
  582. }
  583. return map[ext] || 'application/octet-stream'
  584. }
  585. // ------------------------------------------------------------------ HTTP
  586. const server = http.createServer(async (req, res) => {
  587. const url = new URL(req.url, `http://${req.headers.host || '127.0.0.1'}`)
  588. try {
  589. if (url.pathname.startsWith('/_cc/')) {
  590. const session = auth.fromRequest(req)
  591. if (session) {
  592. session.touch?.()
  593. const live = manager.peek(session.user)
  594. if (live) live.touch()
  595. }
  596. return await handleInternal(req, res, url, session)
  597. }
  598. // 其余全部是引擎的界面
  599. const session = auth.fromRequest(req)
  600. if (!session) {
  601. if (wantsHtml(req)) {
  602. res.writeHead(302, { location: '/_cc/login' })
  603. return res.end()
  604. }
  605. res.writeHead(401, { 'content-type': 'text/plain; charset=utf-8' })
  606. return res.end('unauthorized')
  607. }
  608. let live = manager.peek(session.user)
  609. if (!live) {
  610. // 只建对象、不在这里等启动:首屏立刻吐引导页,环境在后台起
  611. live = manager.getOrCreate(session.user)
  612. }
  613. live.touch()
  614. live.origin = config.publicBase || `${req.headers['x-forwarded-proto'] || 'http'}://${req.headers.host}`
  615. if (!(await ensureSession(live, res, req))) return
  616. // 引擎要求先做一次 token 配对(桌面端是直接加载 sidecar 打印的带 ?token= 的地址)。
  617. // 这里替老师完成:没配过就 302 到 /?token=…,引擎回 Set-Cookie 后整站就通了。
  618. if (!live.paired && live.engine.token && wantsHtml(req) && req.method === 'GET') {
  619. live.paired = true
  620. res.writeHead(302, { location: `/?token=${encodeURIComponent(live.engine.token)}` })
  621. return res.end()
  622. }
  623. proxy.handleHttp(req, res, live.engine.port, injectFor(live))
  624. } catch (err) {
  625. log(`[http] ${req.method} ${req.url} → ${err.message}`, 'error')
  626. if (!res.headersSent) {
  627. res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' })
  628. res.end('internal error')
  629. } else {
  630. res.destroy()
  631. }
  632. }
  633. })
  634. // ------------------------------------------------------------------ WebSocket
  635. server.on('upgrade', (req, socket, head) => {
  636. const url = new URL(req.url, `http://${req.headers.host || '127.0.0.1'}`)
  637. if (url.pathname === '/_cc/rt') {
  638. // API 模式没有可推流的页面。前端拿到 session.pageMode 就不会来连,
  639. // 这里还要挡一层:老缓存的前端可能仍在重连。
  640. if (config.pageMode !== 'browser') return rejectUpgrade(socket, 404, 'api-mode')
  641. const session = auth.fromRequest(req)
  642. if (!session) return rejectUpgrade(socket, 401, 'unauthorized')
  643. const live = manager.peek(session.user)
  644. if (!live || !live.browser) return rejectUpgrade(socket, 503, 'starting')
  645. const tab = tabOf(live, url.searchParams.get('tab'))
  646. if (!tab) return rejectUpgrade(socket, 404, 'no-tab')
  647. const conn = WSConnection.accept(socket, req)
  648. if (!conn) return socket.destroy()
  649. live.touch()
  650. conn.onMessage = (raw, binary) => {
  651. if (binary) return
  652. let msg = null
  653. try { msg = JSON.parse(raw) } catch { return }
  654. if (msg.t === 'resize') {
  655. live.browser.resize(tab, msg.w, msg.h).catch(() => {})
  656. return
  657. }
  658. live.browser.input(tab, msg).catch((err) => {
  659. conn.sendJSON({ t: 'log', level: 'error', text: err.message })
  660. })
  661. }
  662. const off = live.browser.subscribe(tab, (payload) => {
  663. if (payload.type === 'frame') {
  664. conn.sendBinary(payload.jpeg)
  665. return
  666. }
  667. if (payload.type === 'log') {
  668. conn.sendJSON({ t: 'log', level: payload.level, text: payload.text })
  669. return
  670. }
  671. conn.sendJSON({ t: 'state', field: payload.field, value: payload.value })
  672. })
  673. conn.onClose = () => { try { off() } catch { /* 已经退了 */ } }
  674. return
  675. }
  676. // 引擎自己的 WS(会话流式回答走这里)
  677. const session = auth.fromRequest(req)
  678. if (!session) return rejectUpgrade(socket, 401, 'unauthorized')
  679. const live = manager.peek(session.user)
  680. if (!live || !live.engine) return rejectUpgrade(socket, 503, 'starting')
  681. live.touch()
  682. proxy.handleUpgrade(req, socket, head, live.engine.port)
  683. })
  684. // ------------------------------------------------------------------ 启动
  685. const problems = preflight()
  686. if (problems.length) {
  687. for (const problem of problems) log(problem, 'error')
  688. log('预检没通过:补齐上面的路径再启动(见 README 的「部署」一节)', 'error')
  689. process.exit(1)
  690. }
  691. /**
  692. * 本机联调用的登录态注入。
  693. * 只在设置了 CC_DEV_USER 时生效,格式:
  694. * CC_DEV_USER='{"userid":"dev","apiKey":"dev","username":"本地联调"}'
  695. * 生产环境不设这个变量就没有这段逻辑 —— 它不写日志以外的任何东西。
  696. */
  697. if (process.env.CC_DEV_USER) {
  698. try {
  699. const dev = JSON.parse(process.env.CC_DEV_USER)
  700. const created = auth.create({
  701. apiKey: String(dev.apiKey || 'dev'),
  702. userid: String(dev.userid || 'dev'),
  703. username: String(dev.username || 'dev'),
  704. organizeId: String(dev.organizeId || ''),
  705. organizeName: String(dev.organizeName || ''),
  706. region: String(dev.region || config.defaultRegion),
  707. locale: normalizeLocale(dev.locale || 'zh-CN')
  708. })
  709. log('[dev] 已注入联调登录态,浏览器请求带上这个 Cookie 即可:', 'warn')
  710. log(`[dev] ${auth.cookieOf(created.sid).split(';')[0]}`, 'warn')
  711. } catch (err) {
  712. log(`[dev] CC_DEV_USER 解析失败:${err.message}`, 'error')
  713. }
  714. }
  715. server.listen(config.port, config.host, () => {
  716. log(`CocoBuddy Web 监听 ${config.host}:${config.port}`)
  717. log(`引擎:${config.engineEntry}`)
  718. log(`页面通道:${config.pageMode === 'browser'
  719. ? `服务端 Chromium(${config.chrome},${config.headless ? 'headless' : 'headed'})`
  720. : 'API 模式(不启动浏览器,业务接口直连平台;页面类操作交给老师自己的浏览器)'}`)
  721. log(`数据目录:${config.dataDir}`)
  722. })
  723. let shuttingDown = false
  724. async function shutdown (signal) {
  725. if (shuttingDown) return
  726. shuttingDown = true
  727. log(`收到 ${signal},正在收尾…`, 'warn')
  728. server.close(() => {})
  729. await manager.stopAll().catch(() => {})
  730. process.exit(0)
  731. }
  732. process.on('SIGTERM', () => shutdown('SIGTERM'))
  733. process.on('SIGINT', () => shutdown('SIGINT'))
  734. process.on('unhandledRejection', (err) => log(`未处理的 Promise 拒绝:${err && err.message}`, 'error'))
  735. process.on('uncaughtException', (err) => log(`未捕获异常:${err && err.message}`, 'error'))