| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813 |
- /**
- * CocoBuddy Web 版 · 入口
- * =====================
- * 一条原则:**一个源站,一个 cookie,其余全部转给这位老师自己的引擎。**
- *
- * / 引擎原生 Web 界面(会话、技能、斜杠菜单都是现成的)
- * /_cc/login 登录页(平台账号 / apiKey)
- * /_cc/api/* Web 层自己的接口(会话、积分、文件、浏览器)
- * /_cc/rt 右侧页面的画面回传 + 输入(WebSocket)
- * /_cc/blob/:token 页面取文件的短时地址(投递上传用)
- *
- * 不按 /app/<用户>/ 划分子路径:引擎前端全是绝对路径资源,挂子路径只会引入
- * 一堆 base 配置;用 cookie 认人更省事,也和"老师只会有一个账号"这件事一致。
- */
- import http from 'node:http'
- import fs from 'node:fs'
- import fsp from 'node:fs/promises'
- import path from 'node:path'
- import crypto from 'node:crypto'
- import { fileURLToPath } from 'node:url'
- import { config, preflight, REGIONS, normalizeLocale } from './config.js'
- import * as auth from './lib/auth.js'
- import * as platform from './lib/platform.js'
- import { SessionManager } from './lib/session.js'
- import { createProxy } from './lib/proxy.js'
- import { WSConnection, rejectUpgrade } from './lib/ws.js'
- const here = path.dirname(fileURLToPath(import.meta.url))
- // ------------------------------------------------------------------ 日志
- function log (message, level = 'info') {
- const order = { debug: 10, info: 20, warn: 30, error: 40 }
- if (order[level] < order[config.logLevel]) return
- const stamp = new Date().toISOString().replace('T', ' ').slice(0, 19)
- process.stdout.write(`[${stamp}] ${level.toUpperCase()} ${message}\n`)
- }
- // ------------------------------------------------------------------ 注入脚本
- const injectDir = path.join(here, 'inject')
- const shimSource = fs.readFileSync(path.join(injectDir, 'cocorobo-shim.js'), 'utf8')
- const polyfillSource = fs.readFileSync(path.join(injectDir, 'webview-polyfill.js'), 'utf8')
- const loginHtml = fs.readFileSync(path.join(injectDir, 'login.html'), 'utf8')
- const callbackHtml = fs.readFileSync(path.join(injectDir, 'callback.html'), 'utf8')
- /** 每页注入:先给语言/区域这类同步就要读的值,再挂 shim 与 <webview> 实现 */
- function injectFor (session) {
- const region = REGIONS[session.user.region] || REGIONS[config.defaultRegion]
- const boot = {
- locale: session.user.locale || 'zh-CN',
- region: session.user.region || config.defaultRegion,
- uid: session.uid,
- cococlassUrl: `${region.platform}/`,
- llmBaseURL: config.llm.baseURL,
- // 前端据此决定 <webview> 是"接服务端画面"还是"交给老师自己的浏览器"
- pageMode: config.pageMode
- }
- return [
- `<script>window.__CC__=${JSON.stringify(boot)}</script>`,
- `<script>${shimSource.replace(/<\/script>/gi, '<\\/script>')}</script>`,
- `<script>${polyfillSource.replace(/<\/script>/gi, '<\\/script>')}</script>`
- ].join('\n')
- }
- // ------------------------------------------------------------------ 工具
- const MAX_JSON = 2 * 1024 * 1024
- function readJson (req) {
- return new Promise((resolve, reject) => {
- let size = 0
- const chunks = []
- req.on('data', (chunk) => {
- size += chunk.length
- if (size > MAX_JSON) { reject(Object.assign(new Error('请求体过大'), { status: 413 })); 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(Object.assign(new Error('请求体不是合法 JSON'), { status: 400 }))
- }
- })
- req.on('error', reject)
- })
- }
- function sendJson (res, status, body, headers = {}) {
- const text = JSON.stringify(body)
- res.writeHead(status, {
- 'content-type': 'application/json; charset=utf-8',
- 'cache-control': 'no-store',
- ...headers
- })
- res.end(text)
- }
- function sendHtml (res, status, html, headers = {}) {
- res.writeHead(status, {
- 'content-type': 'text/html; charset=utf-8',
- 'cache-control': 'no-store',
- ...headers
- })
- res.end(html)
- }
- function wantsHtml (req) {
- return /text\/html/.test(String(req.headers.accept || ''))
- }
- function clientIp (req) {
- if (config.trustProxy) {
- const fwd = String(req.headers['x-forwarded-for'] || '').split(',')[0].trim()
- if (fwd) return fwd
- }
- return String(req.socket.remoteAddress || '')
- }
- // 登录失败限速:同一 IP 每分钟 8 次,防撞库(进程内计数,够用)
- const loginAttempts = new Map()
- function tooManyAttempts (ip) {
- const now = Date.now()
- const entry = loginAttempts.get(ip) || { count: 0, reset: now + 60_000 }
- if (entry.reset < now) { entry.count = 0; entry.reset = now + 60_000 }
- entry.count += 1
- loginAttempts.set(ip, entry)
- return entry.count > 8
- }
- // ------------------------------------------------------------------ 单点登录
- /** 老师浏览器看到的基地址:优先 CC_PUBLIC_BASE,反代下退到 X-Forwarded-* 与 Host。 */
- function publicBaseOf (req) {
- if (config.publicBase) return config.publicBase
- const proto = String(req.headers['x-forwarded-proto'] || '').split(',')[0].trim() || 'http'
- const host = String(req.headers['x-forwarded-host'] || req.headers.host || `127.0.0.1:${config.port}`)
- .split(',')[0].trim()
- return `${proto}://${host}`
- }
- /** 平台登录页地址 + 回调参数。参数名与桌面端完全一致(含 form/from 的兼容写法)。 */
- function ssoLoginUrl (req, state) {
- const url = new URL(config.ssoUrl)
- url.searchParams.set('form', 'desktop')
- url.searchParams.set('from', 'desktop')
- url.searchParams.set('state', state)
- url.searchParams.set(config.ssoRedirectParam, `${publicBaseOf(req)}/_cc/callback`)
- return url.toString()
- }
- /**
- * 接住平台登录后的回调。
- * 平台带回来的是 apiKey + 身份(userid/username/schoolname/organizeid),
- * 与桌面端 `cocorobo://auth/callback` 拿到的是同一组参数,语义也一致:
- * key 由平台签发,等同于一次成功登录,不再二次校验。
- */
- async function handleSsoCallback (req, res, url) {
- const cookies = auth.parseCookies(req.headers.cookie)
- const savedState = cookies.cc_sso_state || ''
- const gotState = url.searchParams.get('state') || ''
- const clearState = 'cc_sso_state=; Path=/_cc; HttpOnly; SameSite=Lax; Max-Age=0'
- // state 只为挡住"第三方构造好的登录链接",平台没回传时不强求
- if (savedState && gotState && savedState !== gotState) {
- log('[sso] state 不匹配,拒绝', 'warn')
- res.writeHead(302, {
- location: '/_cc/login?err=' + encodeURIComponent('登录状态校验失败,请重新登录') + '&local=1',
- 'set-cookie': clearState,
- 'cache-control': 'no-store'
- })
- return res.end()
- }
- const key = String(
- url.searchParams.get('apiKey') ||
- url.searchParams.get('api_key') ||
- url.searchParams.get('key') ||
- url.searchParams.get('token') ||
- ''
- ).trim()
- // 没带 key:返回落地页,由浏览器读 location.hash
- if (!key) {
- res.writeHead(200, {
- 'content-type': 'text/html; charset=utf-8',
- 'cache-control': 'no-store',
- 'set-cookie': clearState
- })
- return res.end(callbackHtml)
- }
- const raw = String(url.searchParams.get('region') || '')
- const regionKey = REGIONS[raw] ? raw : config.defaultRegion
- const userid = String(url.searchParams.get('userid') || url.searchParams.get('userId') || '').trim()
- try {
- let user
- if (userid) {
- // 平台已经把身份带回来了:和桌面端走同一条"信任回调"的路
- user = {
- apiKey: key,
- userid,
- username: String(url.searchParams.get('username') || url.searchParams.get('name') || ''),
- organizeId: String(url.searchParams.get('organizeid') || url.searchParams.get('organizeId') || url.searchParams.get('orgId') || ''),
- organizeName: String(url.searchParams.get('schoolname') || url.searchParams.get('organizeName') || url.searchParams.get('orgName') || '')
- }
- } else {
- // 只带 key 的旧回调:用平台接口反查身份
- if (tooManyAttempts(clientIp(req))) {
- res.writeHead(302, { location: '/_cc/login?err=' + encodeURIComponent('尝试太频繁,请一分钟后再试') + '&local=1', 'cache-control': 'no-store' })
- return res.end()
- }
- user = await platform.verifyKey({ region: REGIONS[regionKey], apiKey: key })
- }
- user.region = regionKey
- user.locale = normalizeLocale(raw || regionKey)
- const created = auth.create(user)
- log(`[sso] ${user.userid || user.username || 'user'} 登录成功`)
- res.writeHead(302, {
- location: '/',
- 'set-cookie': [auth.cookieOf(created.sid), clearState],
- 'cache-control': 'no-store'
- })
- return res.end()
- } catch (err) {
- log(`[sso] ${err.message}`, 'warn')
- res.writeHead(302, {
- location: '/_cc/login?err=' + encodeURIComponent(err.message || '登录失败') + '&local=1',
- 'set-cookie': clearState,
- 'cache-control': 'no-store'
- })
- return res.end()
- }
- }
- // ------------------------------------------------------------------ 引导页
- function bootPage (sess) {
- const state = sess.engine ? '引擎就绪' : '正在启动引擎…'
- return `<!doctype html><html><head><meta charset="utf-8">
- <meta name="viewport" content="width=device-width,initial-scale=1">
- <title>CocoBuddy</title>
- <style>
- html,body{height:100%;margin:0;background:#f7f8fa;color:#1d2129;
- font:15px/1.6 -apple-system,"Segoe UI",system-ui,"PingFang SC","Microsoft YaHei",sans-serif}
- .wrap{height:100%;display:flex;align-items:center;justify-content:center}
- .box{text-align:center;max-width:420px;padding:0 24px}
- .spin{width:34px;height:34px;margin:0 auto 18px;border-radius:50%;
- border:3px solid #e5e8ef;border-top-color:#2f6bff;animation:r .9s linear infinite}
- @keyframes r{to{transform:rotate(360deg)}}
- h1{font-size:17px;font-weight:600;margin:0 0 6px}
- p{margin:0;color:#6b7280;font-size:13px}
- .err{color:#c0392b;white-space:pre-wrap;text-align:left;background:#fff;border:1px solid #f0d0cb;
- border-radius:10px;padding:12px;margin-top:16px;font-size:12px;max-height:260px;overflow:auto}
- </style></head><body><div class="wrap"><div class="box">
- <div class="spin" id="spin"></div>
- <h1 id="title">正在为你准备环境</h1>
- <p id="hint">${state} · 首次启动大约需要 20–60 秒</p>
- <div class="err" id="err" hidden></div>
- </div></div>
- <script>
- var tries = 0
- var timer = setInterval(async function () {
- tries += 1
- try {
- var res = await fetch('/_cc/api/ready', { cache: 'no-store' })
- var info = await res.json()
- if (info.ready) { clearInterval(timer); location.replace('/'); return }
- if (info.error) {
- clearInterval(timer)
- document.getElementById('spin').style.display = 'none'
- document.getElementById('title').textContent = '启动失败'
- document.getElementById('hint').textContent = '把下面的信息发给管理员'
- var box = document.getElementById('err')
- box.hidden = false
- box.textContent = info.error
- return
- }
- if (info.stage) document.getElementById('hint').textContent = info.stage
- } catch (err) { /* 服务还在起 */ }
- if (tries > 120) { clearInterval(timer); document.getElementById('hint').textContent = '等太久了,刷新一下页面' }
- }, 1200)
- </script></body></html>`
- }
- // ------------------------------------------------------------------ 主体
- const manager = new SessionManager((msg, level) => log(msg, level))
- const proxy = createProxy({ log })
- /** 会话 → 确保环境;返回 null 表示还在启动(调用方去吐引导页) */
- async function ensureSession (session, res, req, forApi = false) {
- if (session.engine && session.engine.port && session.engine.child) return session
- session.ensure().catch((err) => {
- log(`[session ${session.uid}] 启动失败:${err.message}`, 'error')
- session.problem = err.message
- })
- if (forApi) {
- sendJson(res, 503, { ok: false, error: 'starting', stage: '环境正在启动' })
- } else if (wantsHtml(req)) {
- sendHtml(res, 200, bootPage(session))
- } else {
- res.writeHead(503, { 'retry-after': '3', 'content-type': 'text/plain; charset=utf-8' })
- res.end('starting')
- }
- return null
- }
- async function handleInternal (req, res, url, session) {
- const p = url.pathname
- if (p === '/_cc/login' && req.method === 'GET') {
- // 配了平台单点登录:直接去平台自己的登录界面(和桌面端同一套账号与回调)。
- // 带 err / local 时留在本页,否则回调失败会来回跳成死循环;
- // ?sso=1 供本地表单上的「用平台账号登录」按钮使用。
- const keepLocal = url.searchParams.has('err') || url.searchParams.has('local')
- const wantSso = url.searchParams.has('sso')
- if (config.ssoUrl && (wantSso || (config.ssoAuto && !keepLocal))) {
- try {
- const state = crypto.randomBytes(16).toString('base64url')
- res.writeHead(302, {
- location: ssoLoginUrl(req, state),
- 'set-cookie': `cc_sso_state=${state}; Path=/_cc; HttpOnly; SameSite=Lax; Max-Age=600`,
- 'cache-control': 'no-store'
- })
- return res.end()
- } catch (err) {
- log(`[sso] CC_SSO_URL 不合法:${err.message}`, 'warn')
- }
- }
- const boot = config.ssoUrl
- ? { sso: { url: config.ssoUrl, param: config.ssoRedirectParam } }
- : {}
- const html = loginHtml.replaceAll('__CC_SSO_JSON__', () => JSON.stringify(boot).replace(/</g, '\\u003c'))
- return sendHtml(res, 200, html)
- }
- if (p === '/_cc/callback' && req.method === 'GET') {
- return handleSsoCallback(req, res, url)
- }
- if (p === '/_cc/api/login' && req.method === 'POST') {
- const ip = clientIp(req)
- if (tooManyAttempts(ip)) return sendJson(res, 429, { ok: false, error: '尝试太频繁,请一分钟后再试' })
- const body = await readJson(req)
- const regionKey = String(body.region || config.defaultRegion)
- const region = REGIONS[regionKey] || REGIONS[config.defaultRegion]
- const locale = normalizeLocale(body.locale || regionKey)
- try {
- let user
- if (body.apiKey) {
- user = await platform.verifyKey({ region, apiKey: String(body.apiKey).trim() })
- } else {
- user = await platform.login({
- region,
- mode: body.mode,
- account: String(body.account || '').trim(),
- password: String(body.password || ''),
- code: String(body.code || ''),
- deviceId: String(body.deviceId || ''),
- clientVersion: 'web'
- })
- }
- user.region = regionKey
- user.locale = locale
- const created = auth.create(user)
- loginAttempts.delete(ip)
- return sendJson(res, 200, {
- ok: true,
- user: { userid: user.userid, username: user.username, organizeName: user.organizeName }
- }, { 'set-cookie': auth.cookieOf(created.sid) })
- } catch (err) {
- log(`[login] ${err.message}`, 'warn')
- return sendJson(res, 401, { ok: false, error: err.message || '登录失败' })
- }
- }
- if (p === '/_cc/api/logout' && req.method === 'POST') {
- if (session) {
- await manager.peek(session.user)?.stop('退出登录').catch(() => {})
- auth.drop(session.sid)
- }
- return sendJson(res, 200, { ok: true }, { 'set-cookie': auth.clearCookie() })
- }
- if (!session) {
- if (p.startsWith('/_cc/api/')) return sendJson(res, 401, { ok: false, error: 'not-logged-in' })
- res.writeHead(302, { location: '/_cc/login' })
- return res.end()
- }
- // 这里往下都要操作"运行环境"(引擎/浏览器/工作区),所以统一换成 live 会话对象。
- // session 是登录凭据(sid + user),live 是这台服务器上属于这个老师的那套进程。
- const live = manager.peek(session.user) || manager.getOrCreate(session.user)
- if (p === '/_cc/api/session') {
- const region = REGIONS[session.user.region] || REGIONS[config.defaultRegion]
- return sendJson(res, 200, {
- user: {
- id: session.user.userid || '',
- userid: session.user.userid || '',
- name: session.user.username || '',
- organizeId: session.user.organizeId || '',
- organizeName: session.user.organizeName || ''
- },
- locale: session.user.locale || 'zh-CN',
- region: session.user.region || config.defaultRegion,
- llmBaseURL: config.llm.baseURL,
- platformBase: region.platform,
- uid: session.uid,
- // 前端据此决定右侧栏是"服务端画面"还是"外链页签":
- // api 模式没有页面可推流,只能把地址交给老师自己的浏览器。
- pageMode: config.pageMode
- })
- }
- if (p === '/_cc/api/ready') {
- const live = manager.peek(session.user)
- return sendJson(res, 200, {
- ready: !!(live && live.engine && live.engine.port),
- // 只按引擎判断阶段:api 模式下 browser 永远是 null,
- // 用它当条件会让界面永久停在"正在启动运行时"。
- stage: live ? (live.engine ? '引擎就绪' : '正在启动引擎…') : '正在启动运行时…',
- pageMode: config.pageMode,
- error: (live && live.problem) || session.problem || ''
- })
- }
- if (p === '/_cc/api/points') {
- try {
- const region = REGIONS[session.user.region] || REGIONS[config.defaultRegion]
- const json = await platform.pointsUsage({
- region, apiKey: session.user.apiKey, userId: session.user.userid
- })
- const num = (v) => (Number.isFinite(Number(v)) ? Number(v) : 0)
- const balance = num(json.balance)
- return sendJson(res, 200, {
- ok: true,
- balance,
- state: String(json.state || (balance <= 0 ? 'empty' : 'ok')),
- lowAt: num(json.low_at),
- available: json.available === undefined ? Math.max(balance, 0) : num(json.available),
- debt: num(json.debt),
- topupUrl: String(json.topup_url || ''),
- canTopup: json.can_topup === true,
- canChat: json.can_chat !== false,
- today: num(json.today_consumed),
- total: num(json.total_consumed),
- granted: num(json.total_granted),
- last: json.last_usage || null,
- at: Date.now()
- })
- } catch (err) {
- return sendJson(res, 200, { ok: false, error: err.message })
- }
- }
- if (p === '/_cc/api/points/url') {
- const region = REGIONS[session.user.region] || REGIONS[config.defaultRegion]
- return sendJson(res, 200, {
- url: platform.pointsPageUrl({
- region, userId: session.user.userid, locale: session.user.locale
- })
- })
- }
- // ---------------------------------------------------------- 右侧浏览器
- // API 模式统一在这里回话:前端拿到 mode:'external' 就把地址交给老师自己的浏览器
- // (同域,登录态本来就在老师本机),右侧栏显示成外链页签,不再等服务端画面。
- if (config.pageMode !== 'browser' && p.startsWith('/_cc/api/browser/')) {
- const body = req.method === 'POST' ? await readJson(req).catch(() => ({})) : {}
- if (p === '/_cc/api/browser/tabs') {
- return sendJson(res, 200, { ok: true, mode: 'external', tabs: [], guest: '' })
- }
- if (p === '/_cc/api/browser/open' || p === '/_cc/api/browser/attach') {
- const target = String(body.url || '')
- if (!target) return sendJson(res, 200, { ok: false, mode: 'external', error: 'empty-url' })
- return sendJson(res, 200, { ok: true, mode: 'external', url: target })
- }
- if (p === '/_cc/api/browser/drop') {
- // 投递需要真页面,这里不能假装成功,否则技能会以为文件已经进页面了
- return sendJson(res, 200, { ok: false, mode: 'external', error: 'page-mode-api' })
- }
- return sendJson(res, 200, { ok: true, mode: 'external' })
- }
- if (p === '/_cc/api/browser/open' && req.method === 'POST') {
- if (!(await ensureSession(live, res, req, true))) return
- const body = await readJson(req)
- try {
- const tab = await live.browser.openTab(String(body.url || ''))
- return sendJson(res, 200, { ok: true, tabId: tab.targetId, key: tab.key, url: tab.url })
- } catch (err) {
- return sendJson(res, 200, { ok: false, error: err.message })
- }
- }
- if (p === '/_cc/api/browser/attach' && req.method === 'POST') {
- if (!(await ensureSession(live, res, req, true))) return
- const body = await readJson(req)
- try {
- const tab = await attachTab(session, String(body.url || ''))
- return sendJson(res, 200, { ok: true, tabId: tab.targetId, key: tab.key, url: tab.url })
- } catch (err) {
- return sendJson(res, 200, { ok: false, error: err.message })
- }
- }
- if (p === '/_cc/api/browser/reload' && req.method === 'POST') {
- if (!(await ensureSession(live, res, req, true))) return
- const body = await readJson(req)
- const tab = tabOf(session, body.tabId)
- if (!tab) return sendJson(res, 404, { ok: false, error: 'no-tab' })
- await live.browser.reload(tab, body.hard === true).catch(() => {})
- return sendJson(res, 200, { ok: true })
- }
- if (p === '/_cc/api/browser/close' && req.method === 'POST') {
- const body = await readJson(req)
- const tab = tabOf(session, body.tabId)
- if (!tab) return sendJson(res, 404, { ok: false, error: 'no-tab' })
- await live.browser.closeTab(tab.targetId).catch(() => {})
- return sendJson(res, 200, { ok: true })
- }
- if (p === '/_cc/api/browser/tabs' && req.method === 'GET') {
- const browser = live.browser
- if (!browser) return sendJson(res, 200, { ok: true, tabs: [] })
- const guest = browser.pickGuest(url.searchParams.get('urlMatch') || '')
- return sendJson(res, 200, { ok: true, tabs: browser.list(), guest: guest ? guest.targetId : '' })
- }
- if (p === '/_cc/api/browser/drop' && req.method === 'POST') {
- if (!(await ensureSession(live, res, req, true))) return
- const body = await readJson(req)
- const tab = body.urlMatch || !body.tabId
- ? live.browser.pickGuest(String(body.urlMatch || ''))
- : tabOf(session, body.tabId)
- if (!tab) return sendJson(res, 200, { ok: false, error: 'no-guest' })
- const abs = live.files.resolve(String(body.path || ''))
- if (!abs) return sendJson(res, 200, { ok: false, error: 'path-not-allowed' })
- const result = await live.browser.dropFile(tab, {
- path: abs,
- name: String(body.name || ''),
- clickText: Array.isArray(body.clickText) ? body.clickText : [],
- pageFn: String(body.pageFn || ''),
- pageFnArgs: body.pageFnArgs === 'array' ? 'array' : 'single',
- pageFnTimeoutMs: Number(body.pageFnTimeoutMs) || 0,
- fileUrl: live.files.blobUrl(abs, live.origin || config.publicBase)
- })
- return sendJson(res, 200, result)
- }
- // ---------------------------------------------------------- 文件
- if (p === '/_cc/api/files' && req.method === 'GET') {
- const list = await live.files?.list(url.searchParams.get('path') || '')
- return sendJson(res, 200, { ok: !!list, root: live.dir.workspace, entries: list || [] })
- }
- if (p === '/_cc/api/files/upload' && req.method === 'POST') {
- if (!live.files) return sendJson(res, 503, { ok: false, error: 'starting' })
- try {
- const saved = await live.files.saveUpload(url.searchParams.get('name') || 'upload.bin', req)
- return sendJson(res, 200, { ok: true, path: saved.path, name: saved.name, size: saved.size })
- } catch (err) {
- return sendJson(res, err.code === 'too_large' ? 413 : 500, { ok: false, error: err.message })
- }
- }
- if (p === '/_cc/api/files/download' && req.method === 'GET') {
- const abs = live.files?.resolve(url.searchParams.get('path') || '')
- const info = abs ? await fsp.stat(abs).catch(() => null) : null
- if (!abs || !info || !info.isFile()) {
- res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
- return res.end('not found')
- }
- res.writeHead(200, {
- 'content-type': 'application/octet-stream',
- 'content-length': String(info.size),
- 'content-disposition': `attachment; filename*=UTF-8''${encodeURIComponent(path.basename(abs))}`
- })
- fs.createReadStream(abs).pipe(res)
- return
- }
- if (p.startsWith('/_cc/blob/') && req.method === 'GET') {
- const file = live.files?.takeBlob(p.slice('/_cc/blob/'.length))
- const info = file ? await fsp.stat(file).catch(() => null) : null
- if (!file || !info) {
- res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
- return res.end('expired')
- }
- // 页面(平台域名)跨源取这个文件:必须放开 CORS,且不能带 cookie
- res.writeHead(200, {
- 'content-type': guessType(file),
- 'content-length': String(info.size),
- 'access-control-allow-origin': '*',
- 'cache-control': 'no-store'
- })
- fs.createReadStream(file).pipe(res)
- return
- }
- sendJson(res, 404, { ok: false, error: 'not-found' })
- }
- function tabOf (live, tabId) {
- if (!live.browser || !tabId) return null
- return live.browser.tabs.get(String(tabId)) || null
- }
- async function attachTab (live, url) {
- const browser = live.browser
- const host = (() => { try { return new URL(url).host } catch { return '' } })()
- for (const tab of browser.tabs.values()) {
- try {
- if (new URL(tab.url).host === host) {
- tab.lastUsed = Date.now()
- return tab
- }
- } catch { /* about:blank 之类,跳过 */ }
- }
- return browser.openTab(url)
- }
- function guessType (file) {
- const ext = path.extname(file).toLowerCase()
- const map = {
- '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif',
- '.webp': 'image/webp', '.svg': 'image/svg+xml', '.pdf': 'application/pdf',
- '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
- '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
- '.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
- '.json': 'application/json', '.txt': 'text/plain; charset=utf-8', '.html': 'text/html; charset=utf-8'
- }
- return map[ext] || 'application/octet-stream'
- }
- // ------------------------------------------------------------------ HTTP
- const server = http.createServer(async (req, res) => {
- const url = new URL(req.url, `http://${req.headers.host || '127.0.0.1'}`)
- try {
- if (url.pathname.startsWith('/_cc/')) {
- const session = auth.fromRequest(req)
- if (session) {
- session.touch?.()
- const live = manager.peek(session.user)
- if (live) live.touch()
- }
- return await handleInternal(req, res, url, session)
- }
- // 其余全部是引擎的界面
- const session = auth.fromRequest(req)
- if (!session) {
- if (wantsHtml(req)) {
- res.writeHead(302, { location: '/_cc/login' })
- return res.end()
- }
- res.writeHead(401, { 'content-type': 'text/plain; charset=utf-8' })
- return res.end('unauthorized')
- }
- let live = manager.peek(session.user)
- if (!live) {
- // 只建对象、不在这里等启动:首屏立刻吐引导页,环境在后台起
- live = manager.getOrCreate(session.user)
- }
- live.touch()
- live.origin = config.publicBase || `${req.headers['x-forwarded-proto'] || 'http'}://${req.headers.host}`
- if (!(await ensureSession(live, res, req))) return
- // 引擎要求先做一次 token 配对(桌面端是直接加载 sidecar 打印的带 ?token= 的地址)。
- // 这里替老师完成:没配过就 302 到 /?token=…,引擎回 Set-Cookie 后整站就通了。
- if (!live.paired && live.engine.token && wantsHtml(req) && req.method === 'GET') {
- live.paired = true
- res.writeHead(302, { location: `/?token=${encodeURIComponent(live.engine.token)}` })
- return res.end()
- }
- proxy.handleHttp(req, res, live.engine.port, injectFor(live))
- } catch (err) {
- log(`[http] ${req.method} ${req.url} → ${err.message}`, 'error')
- if (!res.headersSent) {
- res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' })
- res.end('internal error')
- } else {
- res.destroy()
- }
- }
- })
- // ------------------------------------------------------------------ WebSocket
- server.on('upgrade', (req, socket, head) => {
- const url = new URL(req.url, `http://${req.headers.host || '127.0.0.1'}`)
- if (url.pathname === '/_cc/rt') {
- // API 模式没有可推流的页面。前端拿到 session.pageMode 就不会来连,
- // 这里还要挡一层:老缓存的前端可能仍在重连。
- if (config.pageMode !== 'browser') return rejectUpgrade(socket, 404, 'api-mode')
- const session = auth.fromRequest(req)
- if (!session) return rejectUpgrade(socket, 401, 'unauthorized')
- const live = manager.peek(session.user)
- if (!live || !live.browser) return rejectUpgrade(socket, 503, 'starting')
- const tab = tabOf(live, url.searchParams.get('tab'))
- if (!tab) return rejectUpgrade(socket, 404, 'no-tab')
- const conn = WSConnection.accept(socket, req)
- if (!conn) return socket.destroy()
- live.touch()
- conn.onMessage = (raw, binary) => {
- if (binary) return
- let msg = null
- try { msg = JSON.parse(raw) } catch { return }
- if (msg.t === 'resize') {
- live.browser.resize(tab, msg.w, msg.h).catch(() => {})
- return
- }
- live.browser.input(tab, msg).catch((err) => {
- conn.sendJSON({ t: 'log', level: 'error', text: err.message })
- })
- }
- const off = live.browser.subscribe(tab, (payload) => {
- if (payload.type === 'frame') {
- conn.sendBinary(payload.jpeg)
- return
- }
- if (payload.type === 'log') {
- conn.sendJSON({ t: 'log', level: payload.level, text: payload.text })
- return
- }
- conn.sendJSON({ t: 'state', field: payload.field, value: payload.value })
- })
- conn.onClose = () => { try { off() } catch { /* 已经退了 */ } }
- return
- }
- // 引擎自己的 WS(会话流式回答走这里)
- const session = auth.fromRequest(req)
- if (!session) return rejectUpgrade(socket, 401, 'unauthorized')
- const live = manager.peek(session.user)
- if (!live || !live.engine) return rejectUpgrade(socket, 503, 'starting')
- live.touch()
- proxy.handleUpgrade(req, socket, head, live.engine.port)
- })
- // ------------------------------------------------------------------ 启动
- const problems = preflight()
- if (problems.length) {
- for (const problem of problems) log(problem, 'error')
- log('预检没通过:补齐上面的路径再启动(见 README 的「部署」一节)', 'error')
- process.exit(1)
- }
- /**
- * 本机联调用的登录态注入。
- * 只在设置了 CC_DEV_USER 时生效,格式:
- * CC_DEV_USER='{"userid":"dev","apiKey":"dev","username":"本地联调"}'
- * 生产环境不设这个变量就没有这段逻辑 —— 它不写日志以外的任何东西。
- */
- if (process.env.CC_DEV_USER) {
- try {
- const dev = JSON.parse(process.env.CC_DEV_USER)
- const created = auth.create({
- apiKey: String(dev.apiKey || 'dev'),
- userid: String(dev.userid || 'dev'),
- username: String(dev.username || 'dev'),
- organizeId: String(dev.organizeId || ''),
- organizeName: String(dev.organizeName || ''),
- region: String(dev.region || config.defaultRegion),
- locale: normalizeLocale(dev.locale || 'zh-CN')
- })
- log('[dev] 已注入联调登录态,浏览器请求带上这个 Cookie 即可:', 'warn')
- log(`[dev] ${auth.cookieOf(created.sid).split(';')[0]}`, 'warn')
- } catch (err) {
- log(`[dev] CC_DEV_USER 解析失败:${err.message}`, 'error')
- }
- }
- server.listen(config.port, config.host, () => {
- log(`CocoBuddy Web 监听 ${config.host}:${config.port}`)
- log(`引擎:${config.engineEntry}`)
- log(`页面通道:${config.pageMode === 'browser'
- ? `服务端 Chromium(${config.chrome},${config.headless ? 'headless' : 'headed'})`
- : 'API 模式(不启动浏览器,业务接口直连平台;页面类操作交给老师自己的浏览器)'}`)
- log(`数据目录:${config.dataDir}`)
- })
- let shuttingDown = false
- async function shutdown (signal) {
- if (shuttingDown) return
- shuttingDown = true
- log(`收到 ${signal},正在收尾…`, 'warn')
- server.close(() => {})
- await manager.stopAll().catch(() => {})
- process.exit(0)
- }
- process.on('SIGTERM', () => shutdown('SIGTERM'))
- process.on('SIGINT', () => shutdown('SIGINT'))
- process.on('unhandledRejection', (err) => log(`未处理的 Promise 拒绝:${err && err.message}`, 'error'))
- process.on('uncaughtException', (err) => log(`未捕获异常:${err && err.message}`, 'error'))
|