| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334 |
- /**
- * 单元测试
- * =======
- * 只测"不需要真引擎、真 Chromium"的部分:这是 CI 和本地都能跑的底线。
- * 浏览器/引擎相关的行为在 docs/testing.md 里有一套手工清单(真机验证)。
- *
- * node --test test/
- */
- import test from 'node:test'
- import assert from 'node:assert/strict'
- import os from 'node:os'
- import path from 'node:path'
- import fs from 'node:fs'
- import crypto from 'node:crypto'
- const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'cocorobo-web-test-'))
- process.env.CC_DATA_DIR = tmp
- process.env.CC_SECRET = 'test-secret-0123456789abcdef0123456789abcdef'
- process.env.CC_ENGINE_ENTRY = '' // 不预检,单元测试不启动引擎
- const { config } = await import('../server/config.js')
- const auth = await import('../server/lib/auth.js')
- const { buildPatch } = await import('../server/lib/patch.js')
- const { Files } = await import('../server/lib/files.js')
- const { encodeFrame, WSConnection } = await import('../server/lib/ws.js')
- const { PageBridge } = await import('../server/lib/bridge.js')
- const { ApiBridge } = await import('../server/lib/apibridge.js')
- // ------------------------------------------------------------------ patch
- test('patch:品牌、模型、插件、技能都在,而且不吃默认技能根', () => {
- const yaml = buildPatch({
- workspaceDir: '/data/users/42/workspace',
- authFile: '/data/users/42/auth.json',
- bridgeFile: '/data/users/42/runtime/shell-bridge.json',
- apiBase: 'https://cloud.cocorobo.cn',
- pluginEntry: '/app/assets/plugins/cocorobo',
- brandEntry: '/app/assets/plugins/cocorobo-brand',
- skillsDir: '/app/assets/skills',
- llm: {
- baseURL: 'https://aiapi.cocorobo.cn/v1',
- model: 'deepseek-v4.1-flash',
- models: [{ id: 'deepseek-v4.1-flash', name: 'flash' }, { id: 'image-gen-1' }],
- protocol: 'openai-completions',
- userId: '42',
- orgId: '7'
- },
- locale: 'zh-CN'
- })
- assert.match(yaml, /- id: ui-brand-official\n disabled: true/)
- // 引擎用 ESM import() 加载插件,目录会被拒(ERR_UNSUPPORTED_DIR_IMPORT),必须落到入口文件。
- // 期望值用 path.join 拼,Windows 上是反斜杠。
- const entryOf = (base) => JSON.stringify(path.join(base, 'index.js'))
- assert.ok(yaml.includes(entryOf('/app/assets/plugins/cocorobo-brand')))
- assert.ok(yaml.includes(entryOf('/app/assets/plugins/cocorobo')))
- assert.match(yaml, /apiKeyEnv: CC_LLM_KEY/)
- assert.ok(yaml.includes('X-Cocorobo-User-Id: "42"'))
- // 生图模型不该进聊天模型下拉
- assert.ok(!/models:\n(?:.*\n)*?\s+- id: "image-gen-1"/.test(yaml))
- assert.match(yaml, /- id: cocorobo/)
- assert.match(yaml, /bridgeFile: "\/data\/users\/42\/runtime\/shell-bridge.json"/)
- assert.match(yaml, /includeDefaultRoots: false/)
- assert.match(yaml, /- "\/app\/assets\/skills"/)
- assert.match(yaml, /includeHarnessIdentity: false/)
- assert.match(yaml, /personaPrefix: \|/)
- // 人设里必须有身份句,避免被问"你是谁"时自称底层产品
- assert.ok(yaml.includes('你是「CocoBuddy」'))
- })
- test('patch:插件入口按目录里真实文件解析(cocorobo 是 index.mjs,品牌是 index.js)', () => {
- const mjsDir = path.join(tmp, 'plugins', 'cocorobo')
- const jsDir = path.join(tmp, 'plugins', 'brand')
- fs.mkdirSync(mjsDir, { recursive: true })
- fs.mkdirSync(jsDir, { recursive: true })
- fs.writeFileSync(path.join(mjsDir, 'index.mjs'), 'export const name = "cocorobo"')
- fs.writeFileSync(path.join(jsDir, 'index.js'), 'export const name = "brand"')
- const yaml = buildPatch({
- workspaceDir: '/w', authFile: '/a.json', bridgeFile: '/b.json',
- apiBase: 'https://cloud.cocorobo.cn',
- pluginEntry: mjsDir, brandEntry: jsDir, skillsDir: '/s',
- llm: { baseURL: 'https://aiapi.cocorobo.cn/v1', model: 'm', models: [{ id: 'm' }] }
- })
- assert.ok(yaml.includes(JSON.stringify(path.join(mjsDir, 'index.mjs'))), '目录里是 index.mjs 时必须指向它')
- assert.ok(yaml.includes(JSON.stringify(path.join(jsDir, 'index.js'))))
- })
- test('patch:英文版追加语言指令,且不改动技能文案', () => { const base = {
- workspaceDir: '/w', authFile: '/a.json', bridgeFile: '/b.json',
- apiBase: 'https://cloud.cocorobo.com',
- pluginEntry: '/p', brandEntry: '/br', skillsDir: '/s',
- llm: { baseURL: 'https://aiapi.cocorobo.com/v1', model: 'm', models: [{ id: 'm' }] }
- }
- const en = buildPatch({ ...base, locale: 'en' })
- const cn = buildPatch({ ...base, locale: 'zh-CN' })
- assert.ok(en.includes('Always reply in English'))
- assert.ok(!cn.includes('Always reply in English'))
- })
- // ------------------------------------------------------------------ auth
- test('auth:cookie 能用、伪造的不能用、过期会被清掉', () => {
- const session = auth.create({ apiKey: 'k', userid: 'u1', region: 'zh-CN' })
- const cookie = auth.cookieOf(session.sid).split(';')[0]
- assert.equal(auth.fromRequest({ headers: { cookie } }).user.userid, 'u1')
- const forged = cookie.replace(/\.([^.]+)$/, '.deadbeef')
- assert.equal(auth.fromRequest({ headers: { cookie: forged } }), null)
- assert.equal(auth.fromRequest({ headers: { cookie: 'cc_sid=' } }), null)
- auth.drop(session.sid)
- assert.equal(auth.fromRequest({ headers: { cookie } }), null)
- })
- test('auth:sessionHours 生效(过期即视为未登录)', () => {
- const session = auth.create({ apiKey: 'k2', userid: 'u2' })
- session.expiresAt = Date.now() - 1
- const cookie = auth.cookieOf(session.sid).split(';')[0]
- assert.equal(auth.fromRequest({ headers: { cookie } }), null)
- })
- // ------------------------------------------------------------------ files
- test('files:路径必须钉在允许的根里', async () => {
- const root = path.join(tmp, 'ws')
- fs.mkdirSync(root, { recursive: true })
- fs.writeFileSync(path.join(root, 'a.txt'), 'hi')
- const files = new Files({ roots: [root] })
- assert.equal(files.resolve('a.txt'), path.join(root, 'a.txt'))
- assert.equal(files.resolve('../../etc/passwd'), null)
- assert.equal(files.resolve('/etc/passwd'), null)
- assert.equal(files.resolve(''), null)
- const list = await files.list('')
- assert.ok(list.some((x) => x.name === 'a.txt'))
- files.dispose()
- })
- test('files:短时地址只映射一个文件,过期就失效', () => {
- const root = path.join(tmp, 'ws2')
- fs.mkdirSync(root, { recursive: true })
- fs.writeFileSync(path.join(root, 'b.pptx'), 'x')
- const files = new Files({ roots: [root] })
- const url = files.blobUrl('b.pptx', 'https://example.com')
- const token = url.split('/').pop()
- assert.equal(files.takeBlob(token), path.join(root, 'b.pptx'))
- const again = files.blobUrl('b.pptx', 'https://example.com').split('/').pop()
- files.blobs.get(again).expires = Date.now() - 1
- assert.equal(files.takeBlob(again), null)
- // 越界路径不给地址
- assert.equal(files.blobUrl('../../secret', 'https://example.com'), '')
- files.dispose()
- })
- // ------------------------------------------------------------------ ws
- test('ws:服务端帧格式(长度 <126 / 16 位 / 64 位)', () => {
- const small = encodeFrame('hi')
- assert.equal(small[0], 0x81)
- assert.equal(small[1], 2)
- assert.equal(small.subarray(2).toString(), 'hi')
- const mid = encodeFrame(Buffer.alloc(300))
- assert.equal(mid[1], 126)
- assert.equal(mid.readUInt16BE(2), 300)
- const big = encodeFrame(Buffer.alloc(70000))
- assert.equal(big[1], 127)
- assert.equal(Number(big.readBigUInt64BE(2)), 70000)
- })
- test('ws:能解出客户端带掩码的文本帧,半帧到达也不丢', () => {
- const received = []
- const handlers = {}
- const socket = {
- on (event, fn) { handlers[event] = fn },
- write () { return true },
- end () {},
- destroy () {},
- setNoDelay () {},
- setTimeout () {}
- }
- const conn = new WSConnection(socket, {}, (raw, binary) => received.push({ raw, binary }))
- const payload = Buffer.from('{"t":"resize"}')
- const mask = crypto.randomBytes(4)
- const masked = Buffer.from(payload)
- for (let i = 0; i < masked.length; i += 1) masked[i] ^= mask[i & 3]
- const frame = Buffer.concat([Buffer.from([0x81, 0x80 | masked.length]), mask, masked])
- handlers.data(frame.subarray(0, 3))
- assert.equal(received.length, 0)
- handlers.data(frame.subarray(3))
- assert.deepEqual(received, [{ raw: '{"t":"resize"}', binary: false }])
- // 关闭帧:不回调业务,直接把连接标记为已关
- handlers.data(Buffer.from([0x88, 0x00]))
- assert.equal(conn.closed, true)
- })
- test('ws:握手缺 key 直接拒绝', () => {
- const socket = { write () { return true }, destroy () {}, on () {}, setNoDelay () {}, setTimeout () {} }
- assert.equal(WSConnection.accept(socket, { headers: {} }), null)
- })
- // ------------------------------------------------------------------ bridge
- test('bridge:没有 token 一律 401;有 token 但没页面是 no-guest', async () => {
- const tokenFile = path.join(tmp, 'runtime', 'shell-bridge.json')
- const browser = { pickGuest: () => null, evaluate: async () => ({ value: 1 }) }
- const bridge = new PageBridge({ browser, tokenFile, fileUrl: () => '', log: () => {} })
- const info = await bridge.start()
- const base = `http://127.0.0.1:${info.port}`
- const unauthorized = await fetch(`${base}/page/eval`, {
- method: 'POST', headers: { 'content-type': 'application/json' }, body: '{"code":"1"}'
- })
- assert.equal(unauthorized.status, 401)
- const res = await fetch(`${base}/page/eval`, {
- method: 'POST',
- headers: { 'content-type': 'application/json', authorization: `Bearer ${info.token}` },
- body: JSON.stringify({ code: '1' })
- })
- const json = await res.json()
- assert.equal(json.ok, false)
- assert.equal(json.error, 'no-guest')
- // 通道凭据文件必须和桌面端同构:{port, token}
- const saved = JSON.parse(fs.readFileSync(tokenFile, 'utf8'))
- assert.equal(saved.port, info.port)
- assert.equal(saved.token, info.token)
- await bridge.stop()
- assert.equal(fs.existsSync(tokenFile), false)
- })
- test('bridge:有页面时返回执行结果,脚本报错走 eval-failed', async () => {
- const tokenFile = path.join(tmp, 'runtime', 'bridge2.json')
- const tab = { targetId: 't1', url: 'https://cloud.cocorobo.cn/#!/cococlass/1', title: '', loading: false }
- let mode = 'ok'
- const browser = {
- pickGuest: () => tab,
- evaluate: async () => {
- if (mode === 'boom') throw new Error('ReferenceError: x is not defined')
- return { value: '{"a":1}', truncated: false }
- }
- }
- const bridge = new PageBridge({ browser, tokenFile, fileUrl: () => '', log: () => {} })
- const info = await bridge.start()
- const call = async (body) => {
- const res = await fetch(`http://127.0.0.1:${info.port}/page/eval`, {
- method: 'POST',
- headers: { 'content-type': 'application/json', authorization: `Bearer ${info.token}` },
- body: JSON.stringify(body)
- })
- return res.json()
- }
- const ok = await call({ code: 'window.__cocorobo.currentLesson()' })
- assert.equal(ok.ok, true)
- assert.equal(ok.value, '{"a":1}')
- assert.equal(ok.url, tab.url)
- mode = 'boom'
- const bad = await call({ code: 'x.y' })
- assert.equal(bad.ok, false)
- assert.match(bad.error, /^eval-failed/)
- await bridge.stop()
- })
- // ------------------------------------------------------------------ apibridge(API 模式)
- test('apibridge:不执行页面,但把"为什么不行 + 怎么走"写进 error', async () => {
- const tokenFile = path.join(tmp, 'runtime', 'api-bridge.json')
- const bridge = new ApiBridge({
- tokenFile,
- platformBase: 'https://cloud.cocorobo.cn',
- filesUrl: 'https://cc.example.com',
- log: () => {}
- })
- const info = await bridge.start()
- // 凭据文件必须与 PageBridge 同构({port, token}),插件才能无差别读取
- const saved = JSON.parse(fs.readFileSync(tokenFile, 'utf8'))
- assert.equal(saved.port, info.port)
- assert.equal(saved.token, info.token)
- const call = async (pathname, body) => {
- const res = await fetch(`http://127.0.0.1:${info.port}${pathname}`, {
- method: 'POST',
- headers: { 'content-type': 'application/json', authorization: `Bearer ${info.token}` },
- body: JSON.stringify(body || {})
- })
- return res.json()
- }
- const noAuth = await fetch(`http://127.0.0.1:${info.port}/page/eval`, { method: 'POST', body: '{}' })
- assert.equal(noAuth.status, 401)
- const ev = await call('/page/eval', { code: 'window.__cocorobo.currentLesson()' })
- assert.equal(ev.ok, false)
- assert.match(ev.error, /no-server-page/)
- // 两条替代路都必须在文案里:模型只认 error 字符串
- assert.match(ev.error, /cocorobo_api/)
- assert.match(ev.error, /cloud\.cocorobo\.cn/)
- const drop = await call('/page/dropFile', { path: '/w/lesson.pptx' })
- assert.equal(drop.ok, false)
- assert.equal(drop.manual.file, 'lesson.pptx')
- assert.equal(drop.manual.filesUrl, 'https://cc.example.com')
- // 这两条必须是成功:技能链路里的"刷新/看控制台"不该中断整条流程
- assert.equal((await call('/page/reload', {})).ok, true)
- const dev = await call('/page/devtools', {})
- assert.equal(dev.ok, true)
- assert.equal(dev.panel, 'none')
- await bridge.stop()
- })
- test('config:默认区与三种语言的映射不串', () => {
- assert.equal(config.regions['zh-CN'].platform, 'https://cloud.cocorobo.cn')
- assert.equal(config.regions['zh-HK'].platform, 'https://cloud.cocorobo.hk')
- assert.equal(config.regions.en.platform, 'https://cloud.cocorobo.com')
- assert.equal(config.cookieName, 'cc_sid')
- })
|