unit.test.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. /**
  2. * 单元测试
  3. * =======
  4. * 只测"不需要真引擎、真 Chromium"的部分:这是 CI 和本地都能跑的底线。
  5. * 浏览器/引擎相关的行为在 docs/testing.md 里有一套手工清单(真机验证)。
  6. *
  7. * node --test test/
  8. */
  9. import test from 'node:test'
  10. import assert from 'node:assert/strict'
  11. import os from 'node:os'
  12. import path from 'node:path'
  13. import fs from 'node:fs'
  14. import crypto from 'node:crypto'
  15. const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'cocorobo-web-test-'))
  16. process.env.CC_DATA_DIR = tmp
  17. process.env.CC_SECRET = 'test-secret-0123456789abcdef0123456789abcdef'
  18. process.env.CC_ENGINE_ENTRY = '' // 不预检,单元测试不启动引擎
  19. const { config } = await import('../server/config.js')
  20. const auth = await import('../server/lib/auth.js')
  21. const { buildPatch } = await import('../server/lib/patch.js')
  22. const { Files } = await import('../server/lib/files.js')
  23. const { encodeFrame, WSConnection } = await import('../server/lib/ws.js')
  24. const { PageBridge } = await import('../server/lib/bridge.js')
  25. const { ApiBridge } = await import('../server/lib/apibridge.js')
  26. // ------------------------------------------------------------------ patch
  27. test('patch:品牌、模型、插件、技能都在,而且不吃默认技能根', () => {
  28. const yaml = buildPatch({
  29. workspaceDir: '/data/users/42/workspace',
  30. authFile: '/data/users/42/auth.json',
  31. bridgeFile: '/data/users/42/runtime/shell-bridge.json',
  32. apiBase: 'https://cloud.cocorobo.cn',
  33. pluginEntry: '/app/assets/plugins/cocorobo',
  34. brandEntry: '/app/assets/plugins/cocorobo-brand',
  35. skillsDir: '/app/assets/skills',
  36. llm: {
  37. baseURL: 'https://aiapi.cocorobo.cn/v1',
  38. model: 'deepseek-v4.1-flash',
  39. models: [{ id: 'deepseek-v4.1-flash', name: 'flash' }, { id: 'image-gen-1' }],
  40. protocol: 'openai-completions',
  41. userId: '42',
  42. orgId: '7'
  43. },
  44. locale: 'zh-CN'
  45. })
  46. assert.match(yaml, /- id: ui-brand-official\n disabled: true/)
  47. // 引擎用 ESM import() 加载插件,目录会被拒(ERR_UNSUPPORTED_DIR_IMPORT),必须落到入口文件。
  48. // 期望值用 path.join 拼,Windows 上是反斜杠。
  49. const entryOf = (base) => JSON.stringify(path.join(base, 'index.js'))
  50. assert.ok(yaml.includes(entryOf('/app/assets/plugins/cocorobo-brand')))
  51. assert.ok(yaml.includes(entryOf('/app/assets/plugins/cocorobo')))
  52. assert.match(yaml, /apiKeyEnv: CC_LLM_KEY/)
  53. assert.ok(yaml.includes('X-Cocorobo-User-Id: "42"'))
  54. // 生图模型不该进聊天模型下拉
  55. assert.ok(!/models:\n(?:.*\n)*?\s+- id: "image-gen-1"/.test(yaml))
  56. assert.match(yaml, /- id: cocorobo/)
  57. assert.match(yaml, /bridgeFile: "\/data\/users\/42\/runtime\/shell-bridge.json"/)
  58. assert.match(yaml, /includeDefaultRoots: false/)
  59. assert.match(yaml, /- "\/app\/assets\/skills"/)
  60. assert.match(yaml, /includeHarnessIdentity: false/)
  61. assert.match(yaml, /personaPrefix: \|/)
  62. // 人设里必须有身份句,避免被问"你是谁"时自称底层产品
  63. assert.ok(yaml.includes('你是「CocoBuddy」'))
  64. })
  65. test('patch:插件入口按目录里真实文件解析(cocorobo 是 index.mjs,品牌是 index.js)', () => {
  66. const mjsDir = path.join(tmp, 'plugins', 'cocorobo')
  67. const jsDir = path.join(tmp, 'plugins', 'brand')
  68. fs.mkdirSync(mjsDir, { recursive: true })
  69. fs.mkdirSync(jsDir, { recursive: true })
  70. fs.writeFileSync(path.join(mjsDir, 'index.mjs'), 'export const name = "cocorobo"')
  71. fs.writeFileSync(path.join(jsDir, 'index.js'), 'export const name = "brand"')
  72. const yaml = buildPatch({
  73. workspaceDir: '/w', authFile: '/a.json', bridgeFile: '/b.json',
  74. apiBase: 'https://cloud.cocorobo.cn',
  75. pluginEntry: mjsDir, brandEntry: jsDir, skillsDir: '/s',
  76. llm: { baseURL: 'https://aiapi.cocorobo.cn/v1', model: 'm', models: [{ id: 'm' }] }
  77. })
  78. assert.ok(yaml.includes(JSON.stringify(path.join(mjsDir, 'index.mjs'))), '目录里是 index.mjs 时必须指向它')
  79. assert.ok(yaml.includes(JSON.stringify(path.join(jsDir, 'index.js'))))
  80. })
  81. test('patch:英文版追加语言指令,且不改动技能文案', () => { const base = {
  82. workspaceDir: '/w', authFile: '/a.json', bridgeFile: '/b.json',
  83. apiBase: 'https://cloud.cocorobo.com',
  84. pluginEntry: '/p', brandEntry: '/br', skillsDir: '/s',
  85. llm: { baseURL: 'https://aiapi.cocorobo.com/v1', model: 'm', models: [{ id: 'm' }] }
  86. }
  87. const en = buildPatch({ ...base, locale: 'en' })
  88. const cn = buildPatch({ ...base, locale: 'zh-CN' })
  89. assert.ok(en.includes('Always reply in English'))
  90. assert.ok(!cn.includes('Always reply in English'))
  91. })
  92. // ------------------------------------------------------------------ auth
  93. test('auth:cookie 能用、伪造的不能用、过期会被清掉', () => {
  94. const session = auth.create({ apiKey: 'k', userid: 'u1', region: 'zh-CN' })
  95. const cookie = auth.cookieOf(session.sid).split(';')[0]
  96. assert.equal(auth.fromRequest({ headers: { cookie } }).user.userid, 'u1')
  97. const forged = cookie.replace(/\.([^.]+)$/, '.deadbeef')
  98. assert.equal(auth.fromRequest({ headers: { cookie: forged } }), null)
  99. assert.equal(auth.fromRequest({ headers: { cookie: 'cc_sid=' } }), null)
  100. auth.drop(session.sid)
  101. assert.equal(auth.fromRequest({ headers: { cookie } }), null)
  102. })
  103. test('auth:sessionHours 生效(过期即视为未登录)', () => {
  104. const session = auth.create({ apiKey: 'k2', userid: 'u2' })
  105. session.expiresAt = Date.now() - 1
  106. const cookie = auth.cookieOf(session.sid).split(';')[0]
  107. assert.equal(auth.fromRequest({ headers: { cookie } }), null)
  108. })
  109. // ------------------------------------------------------------------ files
  110. test('files:路径必须钉在允许的根里', async () => {
  111. const root = path.join(tmp, 'ws')
  112. fs.mkdirSync(root, { recursive: true })
  113. fs.writeFileSync(path.join(root, 'a.txt'), 'hi')
  114. const files = new Files({ roots: [root] })
  115. assert.equal(files.resolve('a.txt'), path.join(root, 'a.txt'))
  116. assert.equal(files.resolve('../../etc/passwd'), null)
  117. assert.equal(files.resolve('/etc/passwd'), null)
  118. assert.equal(files.resolve(''), null)
  119. const list = await files.list('')
  120. assert.ok(list.some((x) => x.name === 'a.txt'))
  121. files.dispose()
  122. })
  123. test('files:短时地址只映射一个文件,过期就失效', () => {
  124. const root = path.join(tmp, 'ws2')
  125. fs.mkdirSync(root, { recursive: true })
  126. fs.writeFileSync(path.join(root, 'b.pptx'), 'x')
  127. const files = new Files({ roots: [root] })
  128. const url = files.blobUrl('b.pptx', 'https://example.com')
  129. const token = url.split('/').pop()
  130. assert.equal(files.takeBlob(token), path.join(root, 'b.pptx'))
  131. const again = files.blobUrl('b.pptx', 'https://example.com').split('/').pop()
  132. files.blobs.get(again).expires = Date.now() - 1
  133. assert.equal(files.takeBlob(again), null)
  134. // 越界路径不给地址
  135. assert.equal(files.blobUrl('../../secret', 'https://example.com'), '')
  136. files.dispose()
  137. })
  138. // ------------------------------------------------------------------ ws
  139. test('ws:服务端帧格式(长度 <126 / 16 位 / 64 位)', () => {
  140. const small = encodeFrame('hi')
  141. assert.equal(small[0], 0x81)
  142. assert.equal(small[1], 2)
  143. assert.equal(small.subarray(2).toString(), 'hi')
  144. const mid = encodeFrame(Buffer.alloc(300))
  145. assert.equal(mid[1], 126)
  146. assert.equal(mid.readUInt16BE(2), 300)
  147. const big = encodeFrame(Buffer.alloc(70000))
  148. assert.equal(big[1], 127)
  149. assert.equal(Number(big.readBigUInt64BE(2)), 70000)
  150. })
  151. test('ws:能解出客户端带掩码的文本帧,半帧到达也不丢', () => {
  152. const received = []
  153. const handlers = {}
  154. const socket = {
  155. on (event, fn) { handlers[event] = fn },
  156. write () { return true },
  157. end () {},
  158. destroy () {},
  159. setNoDelay () {},
  160. setTimeout () {}
  161. }
  162. const conn = new WSConnection(socket, {}, (raw, binary) => received.push({ raw, binary }))
  163. const payload = Buffer.from('{"t":"resize"}')
  164. const mask = crypto.randomBytes(4)
  165. const masked = Buffer.from(payload)
  166. for (let i = 0; i < masked.length; i += 1) masked[i] ^= mask[i & 3]
  167. const frame = Buffer.concat([Buffer.from([0x81, 0x80 | masked.length]), mask, masked])
  168. handlers.data(frame.subarray(0, 3))
  169. assert.equal(received.length, 0)
  170. handlers.data(frame.subarray(3))
  171. assert.deepEqual(received, [{ raw: '{"t":"resize"}', binary: false }])
  172. // 关闭帧:不回调业务,直接把连接标记为已关
  173. handlers.data(Buffer.from([0x88, 0x00]))
  174. assert.equal(conn.closed, true)
  175. })
  176. test('ws:握手缺 key 直接拒绝', () => {
  177. const socket = { write () { return true }, destroy () {}, on () {}, setNoDelay () {}, setTimeout () {} }
  178. assert.equal(WSConnection.accept(socket, { headers: {} }), null)
  179. })
  180. // ------------------------------------------------------------------ bridge
  181. test('bridge:没有 token 一律 401;有 token 但没页面是 no-guest', async () => {
  182. const tokenFile = path.join(tmp, 'runtime', 'shell-bridge.json')
  183. const browser = { pickGuest: () => null, evaluate: async () => ({ value: 1 }) }
  184. const bridge = new PageBridge({ browser, tokenFile, fileUrl: () => '', log: () => {} })
  185. const info = await bridge.start()
  186. const base = `http://127.0.0.1:${info.port}`
  187. const unauthorized = await fetch(`${base}/page/eval`, {
  188. method: 'POST', headers: { 'content-type': 'application/json' }, body: '{"code":"1"}'
  189. })
  190. assert.equal(unauthorized.status, 401)
  191. const res = await fetch(`${base}/page/eval`, {
  192. method: 'POST',
  193. headers: { 'content-type': 'application/json', authorization: `Bearer ${info.token}` },
  194. body: JSON.stringify({ code: '1' })
  195. })
  196. const json = await res.json()
  197. assert.equal(json.ok, false)
  198. assert.equal(json.error, 'no-guest')
  199. // 通道凭据文件必须和桌面端同构:{port, token}
  200. const saved = JSON.parse(fs.readFileSync(tokenFile, 'utf8'))
  201. assert.equal(saved.port, info.port)
  202. assert.equal(saved.token, info.token)
  203. await bridge.stop()
  204. assert.equal(fs.existsSync(tokenFile), false)
  205. })
  206. test('bridge:有页面时返回执行结果,脚本报错走 eval-failed', async () => {
  207. const tokenFile = path.join(tmp, 'runtime', 'bridge2.json')
  208. const tab = { targetId: 't1', url: 'https://cloud.cocorobo.cn/#!/cococlass/1', title: '', loading: false }
  209. let mode = 'ok'
  210. const browser = {
  211. pickGuest: () => tab,
  212. evaluate: async () => {
  213. if (mode === 'boom') throw new Error('ReferenceError: x is not defined')
  214. return { value: '{"a":1}', truncated: false }
  215. }
  216. }
  217. const bridge = new PageBridge({ browser, tokenFile, fileUrl: () => '', log: () => {} })
  218. const info = await bridge.start()
  219. const call = async (body) => {
  220. const res = await fetch(`http://127.0.0.1:${info.port}/page/eval`, {
  221. method: 'POST',
  222. headers: { 'content-type': 'application/json', authorization: `Bearer ${info.token}` },
  223. body: JSON.stringify(body)
  224. })
  225. return res.json()
  226. }
  227. const ok = await call({ code: 'window.__cocorobo.currentLesson()' })
  228. assert.equal(ok.ok, true)
  229. assert.equal(ok.value, '{"a":1}')
  230. assert.equal(ok.url, tab.url)
  231. mode = 'boom'
  232. const bad = await call({ code: 'x.y' })
  233. assert.equal(bad.ok, false)
  234. assert.match(bad.error, /^eval-failed/)
  235. await bridge.stop()
  236. })
  237. // ------------------------------------------------------------------ apibridge(API 模式)
  238. test('apibridge:不执行页面,但把"为什么不行 + 怎么走"写进 error', async () => {
  239. const tokenFile = path.join(tmp, 'runtime', 'api-bridge.json')
  240. const bridge = new ApiBridge({
  241. tokenFile,
  242. platformBase: 'https://cloud.cocorobo.cn',
  243. filesUrl: 'https://cc.example.com',
  244. log: () => {}
  245. })
  246. const info = await bridge.start()
  247. // 凭据文件必须与 PageBridge 同构({port, token}),插件才能无差别读取
  248. const saved = JSON.parse(fs.readFileSync(tokenFile, 'utf8'))
  249. assert.equal(saved.port, info.port)
  250. assert.equal(saved.token, info.token)
  251. const call = async (pathname, body) => {
  252. const res = await fetch(`http://127.0.0.1:${info.port}${pathname}`, {
  253. method: 'POST',
  254. headers: { 'content-type': 'application/json', authorization: `Bearer ${info.token}` },
  255. body: JSON.stringify(body || {})
  256. })
  257. return res.json()
  258. }
  259. const noAuth = await fetch(`http://127.0.0.1:${info.port}/page/eval`, { method: 'POST', body: '{}' })
  260. assert.equal(noAuth.status, 401)
  261. const ev = await call('/page/eval', { code: 'window.__cocorobo.currentLesson()' })
  262. assert.equal(ev.ok, false)
  263. assert.match(ev.error, /no-server-page/)
  264. // 两条替代路都必须在文案里:模型只认 error 字符串
  265. assert.match(ev.error, /cocorobo_api/)
  266. assert.match(ev.error, /cloud\.cocorobo\.cn/)
  267. const drop = await call('/page/dropFile', { path: '/w/lesson.pptx' })
  268. assert.equal(drop.ok, false)
  269. assert.equal(drop.manual.file, 'lesson.pptx')
  270. assert.equal(drop.manual.filesUrl, 'https://cc.example.com')
  271. // 这两条必须是成功:技能链路里的"刷新/看控制台"不该中断整条流程
  272. assert.equal((await call('/page/reload', {})).ok, true)
  273. const dev = await call('/page/devtools', {})
  274. assert.equal(dev.ok, true)
  275. assert.equal(dev.panel, 'none')
  276. await bridge.stop()
  277. })
  278. test('config:默认区与三种语言的映射不串', () => {
  279. assert.equal(config.regions['zh-CN'].platform, 'https://cloud.cocorobo.cn')
  280. assert.equal(config.regions['zh-HK'].platform, 'https://cloud.cocorobo.hk')
  281. assert.equal(config.regions.en.platform, 'https://cloud.cocorobo.com')
  282. assert.equal(config.cookieName, 'cc_sid')
  283. })