workspaceRoutes.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. // @vitest-environment node
  2. import { mkdtempSync, rmSync, readFileSync } from 'node:fs'
  3. import { tmpdir } from 'node:os'
  4. import { join } from 'node:path'
  5. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
  6. import { randomUUID } from 'node:crypto'
  7. import request from 'supertest'
  8. import type Koa from 'koa'
  9. import { createApplication, type ApplicationRuntime } from '../../src/server/app'
  10. import { loadServerConfig } from '../../src/server/config'
  11. import { LocalAuthStore, type LocalUser } from '../../src/server/localAuth'
  12. import { WorkspaceAssets } from '../../src/server/workspaceAssets'
  13. let home: string, runtime: ApplicationRuntime, cookie: string, csrf: string, upstream: string[], bridgeReady: boolean
  14. const first: LocalUser = {
  15. id: 'first',
  16. username: 'first',
  17. role: 'admin',
  18. enabled: true,
  19. mustChangePassword: false,
  20. createdAt: 1,
  21. updatedAt: 1,
  22. }
  23. class TestAuth extends LocalAuthStore {
  24. override current(ctx: Koa.Context) {
  25. return this.require(ctx)
  26. }
  27. override require(ctx: Koa.Context) {
  28. return { ...first, id: ctx.get('x-test-user') || 'first' }
  29. }
  30. override requireAdmin(ctx: Koa.Context) {
  31. return this.require(ctx)
  32. }
  33. override canUseSource() { return true }
  34. override currentFromCookieHeader() {
  35. return first
  36. }
  37. override isUserActive() {
  38. return true
  39. }
  40. }
  41. function req(method: 'get' | 'post' | 'put' | 'patch' | 'delete', path: string, user = 'first') {
  42. return request(runtime.app.callback())
  43. [method](path)
  44. .set('Host', '127.0.0.1:15300')
  45. .set('Origin', 'http://127.0.0.1:15300')
  46. .set('Cookie', cookie)
  47. .set('X-CSRF-Token', csrf)
  48. .set('x-test-user', user)
  49. }
  50. beforeEach(async () => {
  51. home = mkdtempSync(join(tmpdir(), 'yaoyao-workspace-routes-'))
  52. upstream = []
  53. bridgeReady = false
  54. const config = loadServerConfig({
  55. HERMES_YAOYAO_HOME: home,
  56. HERMES_YAOYAO_UPSTREAM: 'http://127.0.0.1:19119',
  57. HERMES_YAOYAO_ALLOWED_HOSTS: '127.0.0.1,localhost',
  58. })
  59. runtime = createApplication({
  60. config,
  61. auth: new TestAuth(home, false),
  62. fetchImpl: (async (input) => {
  63. const path = new URL(String(input)).pathname
  64. upstream.push(path)
  65. const body =
  66. path === '/api/plugins/yaoyao-bot-bridge/capabilities' && bridgeReady
  67. ? {version:1,ready:true,in_process:true,native_tools:true}
  68. : path === '/api/pair/v1/capabilities'
  69. ? {protocolVersion:1,serviceType:'yaoyao-web',nodeId:'11111111-1111-4111-8111-111111111111',fingerprint:'f'.repeat(64)}
  70. : path === '/api/pair/v1/claim'
  71. ? {protocolVersion:1,serviceType:'yaoyao-web',nodeId:'11111111-1111-4111-8111-111111111111',fingerprint:'f'.repeat(64),deviceId:'22222222-2222-4222-8222-222222222222',token:'delegated-token',scopes:['agents.read','sessions.execute','history.read'],serverUrl:'http://child.test:15300/node/22222222-2222-4222-8222-222222222222'}
  72. : path === '/api/status'
  73. ? { auth_required: true }
  74. : path === '/api/auth/me'
  75. ? { user_id: 'upstream' }
  76. : path.endsWith('/api/profiles')
  77. ? { profiles: [{ name: 'default', display_name: '基础 Agent' }] }
  78. : { ok: true }
  79. return new Response(JSON.stringify(body), {
  80. status: path.includes('/plugins/') && !bridgeReady ? 404 : 200,
  81. headers: { 'Content-Type': 'application/json' },
  82. })
  83. }) as typeof fetch,
  84. })
  85. const b = await request(runtime.app.callback())
  86. .get('/api/app/bootstrap')
  87. .set('Host', '127.0.0.1:15300')
  88. .expect(200)
  89. cookie = (b.headers['set-cookie'] as unknown as string[]).map((v) => v.split(';')[0]).join('; ')
  90. csrf = b.body.csrfToken
  91. })
  92. afterEach(() => {
  93. runtime.close()
  94. rmSync(home, { recursive: true, force: true })
  95. })
  96. describe('application workspace HTTP contract', () => {
  97. it('resumes a stopped goal from a real user request without duplicating its run',async()=>{
  98. vi.spyOn(runtime.workspaceRuntime,'wake').mockImplementation(()=>{})
  99. vi.spyOn(runtime.workspaceRuntime.teamTools,'requireAvailable').mockResolvedValue()
  100. const lead=runtime.workspace.createAgent('first',{name:'任务负责人',profile:'default',canManageTeam:true})
  101. const member=runtime.workspace.createAgent('first',{name:'成员',profile:'default'})
  102. const source=runtime.workspace.list<any>('first','conversation').find(c=>c.kind==='direct'&&c.memberIds[0]===lead.id)!
  103. const original=runtime.workspaceRuntime.send('first',source.id,{requestId:randomUUID(),content:'完成任务'})
  104. const team=runtime.workspace.createGroup('first',{name:'任务组',memberIds:[lead.id,member.id],administratorId:lead.id})
  105. const task=runtime.workspace.tasks('first',team.id)[0]!
  106. runtime.workspaceRuntime.tasks.begin('first',task,lead,'完成任务',{conversationId:source.id,runId:original.id,agentId:lead.id})
  107. await req('post',`/api/app/conversations/${team.id}/tasks/${task.id}/stop`).send({}).expect(200)
  108. const input={requestId:randomUUID()}
  109. const resumed=await req('post',`/api/app/conversations/${team.id}/tasks/${task.id}/resume`).send(input).expect(200)
  110. expect(resumed.body.goal.status).toBe('running')
  111. const repeated=await req('post',`/api/app/conversations/${team.id}/tasks/${task.id}/resume`).send(input).expect(200)
  112. expect(repeated.body.run.id).toBe(resumed.body.run.id)
  113. await req('post',`/api/app/conversations/${team.id}/tasks/${task.id}/resume`,'second').send({requestId:randomUUID()}).expect(404)
  114. })
  115. it('grants team management only with a ready bridge and persists explicit revocation', async () => {
  116. const denied = await req('post','/api/app/agents').send({name:'老板',profile:'default',canManageTeam:true}).expect(409)
  117. expect(denied.body.code).toBe('team_tools_unavailable')
  118. expect((await req('get','/api/app/agents')).body.agents).toEqual([])
  119. bridgeReady = true
  120. const agent = (await req('post','/api/app/agents').send({name:'老板',profile:'default',canManageTeam:true}).expect(201)).body.agent
  121. expect(agent.canManageTeam).toBe(true)
  122. await req('patch',`/api/app/agents/${agent.id}`,'second').send({canManageTeam:false}).expect(404)
  123. bridgeReady = false
  124. const disabled = await req('patch',`/api/app/agents/${agent.id}`).send({canManageTeam:false}).expect(200)
  125. expect(disabled.body.agent.canManageTeam).toBe(false)
  126. expect((await req('get','/api/app/agents')).body.agents[0].canManageTeam).toBe(false)
  127. await req('patch',`/api/app/agents/${agent.id}`).send({canManageTeam:true}).expect(409)
  128. })
  129. it('accepts only child pairing, hides credentials, and scopes address edits to the owner', async () => {
  130. const code = new URL('yaoyao://pair')
  131. for (const [key,value] of Object.entries({v:'1',url:'http://child.test:15300',node:'11111111-1111-4111-8111-111111111111',id:'33333333-3333-4333-8333-333333333333',fingerprint:'f'.repeat(64),secret:'s'.repeat(64)})) code.searchParams.set(key,value)
  132. await req('post','/api/app/nodes').send({name:'legacy',url:'http://child.test:9119',username:'user',password:'password'}).expect(400)
  133. await req('post','/api/app/nodes').send({name:'child',qrPayload:code.href.replace('://pair','://login')}).expect(400)
  134. await req('post','/api/app/nodes').send({name:'child',qrPayload:code.href}).expect(201)
  135. const listing=await req('get','/api/app/nodes').expect(200), node=listing.body.nodes[0]
  136. expect(node.transport).toBe('paired-web'); expect(JSON.stringify(listing.body)).not.toContain('delegated-token'); expect(node.secret).toBeUndefined()
  137. expect((await req('get','/api/app/nodes','second').expect(200)).body.nodes).toEqual([])
  138. await req('patch',`/api/app/nodes/${node.id}`,'second').send({name:'other',url:'http://new-ip.test:15300'}).expect(404)
  139. await req('patch',`/api/app/nodes/${node.id}`).send({name:'new name',url:'http://new-ip.test:15300'}).expect(200)
  140. const updated=(await req('get','/api/app/nodes').expect(200)).body.nodes[0]
  141. expect(updated.id).toBe(node.id); expect(updated.url).toBe('http://new-ip.test:15300/')
  142. const sources=(await req('get','/api/app/agents/sources').expect(200)).body.sources
  143. expect(sources.some((s:any)=>s.nodeId===node.id && s.profile==='default')).toBe(true)
  144. })
  145. it('archives native-chat uploads through the standard file API with user ownership', async () => {
  146. const assets = new WorkspaceAssets(runtime.workspace, runtime.workspaceRuntime.nodes, home)
  147. await assets.archiveText(
  148. 'first',
  149. '{"path":"/tmp/native-upload.txt"}',
  150. 'local',
  151. 'default',
  152. 'native-session',
  153. 'native-message',
  154. 'user',
  155. )
  156. const page = await req('get', '/api/app/files').expect(200)
  157. expect(page.body.items[0]).toMatchObject({
  158. name: 'native-upload.txt',
  159. sender: 'user',
  160. profile: 'default',
  161. })
  162. expect(upstream).toContain('/api/files/download')
  163. expect((await req('get', '/api/app/files', 'second')).body.items).toEqual([])
  164. expect(upstream.some((p) => p.includes('/plugins/'))).toBe(false)
  165. })
  166. it('works without plugin discovery, installation, or any plugin HTTP request', async () => {
  167. const capabilities = (await req('get', '/api/app/capabilities').expect(200)).body.features
  168. expect(capabilities).toContain('editableGroups')
  169. expect(capabilities).not.toContain('immutableGroups')
  170. await req('get', '/api/app/files').expect(200)
  171. await req('get', '/api/app/voice/runtime').expect(200)
  172. await req('get', '/api/app/system/update/status').expect(200)
  173. await req('post', '/api/app/plugins/yaoyao/reconcile').send({}).expect(410)
  174. await req('get', '/api/plugins/yaoyao/v1/capabilities').expect(410)
  175. expect(upstream.some((p) => p.includes('/plugins/'))).toBe(false)
  176. })
  177. it('changes members over HTTP while protecting the administrator and ownership', async () => {
  178. const a = (
  179. await req('post', '/api/app/agents').send({ name: '编辑', profile: 'default' }).expect(201)
  180. ).body.agent
  181. const b = (
  182. await req('post', '/api/app/agents').send({ name: '审查', profile: 'default' }).expect(201)
  183. ).body.agent
  184. const c = (
  185. await req('post', '/api/app/conversations')
  186. .send({ name: '团队', memberIds: [a.id, b.id], administratorId: a.id })
  187. .expect(201)
  188. ).body.conversation
  189. const rows = await req('get', '/api/app/conversations').expect(200)
  190. expect(rows.body.conversations).toHaveLength(3)
  191. await req('patch', `/api/app/conversations/${c.id}`)
  192. .send({ memberIds: [b.id], administratorId: b.id })
  193. .expect(400)
  194. await req('patch', `/api/app/conversations/${c.id}`).send({ memberIds: [a.id] }).expect(200)
  195. expect((await req('get', `/api/app/conversations/${c.id}`)).body.conversation.memberIds).toEqual([a.id])
  196. await req('patch', `/api/app/conversations/${c.id}`).send({ memberIds: [a.id, b.id] }).expect(200)
  197. await req('get', `/api/app/conversations/${c.id}`, 'second').expect(404)
  198. await req('patch', `/api/app/agents/${a.id}`, 'second').send({ name: '入侵' }).expect(404)
  199. expect((await req('get', '/api/app/events', 'second')).body.events).toEqual([])
  200. expect(upstream.some((p) => p.includes('sessions'))).toBe(false)
  201. })
  202. it('creates, lists, renames, selects, and deletes group tasks without changing remote members', async () => {
  203. const a = (
  204. await req('post', '/api/app/agents').send({ name: '本机管理员', profile: 'default' }).expect(201)
  205. ).body.agent
  206. const b = (
  207. await req('post', '/api/app/agents').send({ name: '远程成员', nodeId: 'local', profile: 'default' }).expect(201)
  208. ).body.agent
  209. const conversation = (
  210. await req('post', '/api/app/conversations')
  211. .send({ name: '多任务团队', memberIds: [a.id, b.id], administratorId: a.id })
  212. .expect(201)
  213. ).body.conversation
  214. const initial = (await req('get', `/api/app/conversations/${conversation.id}/tasks`).expect(200)).body.tasks
  215. expect(initial).toHaveLength(1)
  216. expect(initial[0]).toMatchObject({
  217. conversationId: conversation.id,
  218. title: '新任务',
  219. titleSource: 'automatic',
  220. messageCount: 0,
  221. })
  222. const task = (
  223. await req('post', `/api/app/conversations/${conversation.id}/tasks`)
  224. .send({ title: '远程 Agent 调研' })
  225. .expect(201)
  226. ).body.task
  227. expect(task).toMatchObject({ title: '远程 Agent 调研', titleSource: 'user' })
  228. const renamed = (
  229. await req('patch', `/api/app/conversations/${conversation.id}/tasks/${task.id}`)
  230. .send({ title: '远程 Agent 复核' })
  231. .expect(200)
  232. ).body.task
  233. expect(renamed).toMatchObject({ title: '远程 Agent 复核', titleSource: 'user' })
  234. const detail = (await req('get', `/api/app/conversations/${conversation.id}?taskId=${task.id}`).expect(200)).body
  235. expect(detail.task.id).toBe(task.id)
  236. expect(detail.tasks.map((row: { id: string }) => row.id)).toContain(task.id)
  237. expect(detail.messages).toEqual([])
  238. expect(detail.conversation).toMatchObject({ memberIds: [a.id, b.id], administratorId: a.id })
  239. expect((await req('put', `/api/app/conversations/${conversation.id}/tasks/${task.id}/read`).send({ seq: 100 }).expect(200)).body.task)
  240. .toMatchObject({ readSeq: 0, lastSeq: 0, unreadCount: 0 })
  241. await req('get', `/api/app/conversations/${conversation.id}/tasks`, 'second').expect(404)
  242. await req('delete', `/api/app/conversations/${conversation.id}/tasks/${task.id}`).expect(200)
  243. const remaining = (await req('get', `/api/app/conversations/${conversation.id}/tasks`).expect(200)).body.tasks
  244. expect(remaining.map((row: { id: string }) => row.id)).not.toContain(task.id)
  245. expect((await req('get', `/api/app/conversations/${conversation.id}`)).body.conversation)
  246. .toMatchObject({ memberIds: [a.id, b.id], administratorId: a.id })
  247. await req('delete', `/api/app/conversations/${conversation.id}/tasks/${initial[0].id}`).expect(200)
  248. const replacement = (await req('get', `/api/app/conversations/${conversation.id}/tasks`).expect(200)).body.tasks
  249. expect(replacement).toHaveLength(1)
  250. expect(replacement[0].id).not.toBe(initial[0].id)
  251. })
  252. it('archives files on the Web server, preserves native library fields, and blocks cross-user downloads', async () => {
  253. const f = (
  254. await req('post', '/api/app/uploads')
  255. .attach('files', Buffer.from('hello'), { filename: 'hello.txt', contentType: 'text/plain' })
  256. .expect(201)
  257. ).body.files[0]
  258. expect(f.path).toBeUndefined()
  259. expect(runtime.uploads.cleanupUncommitted(0)).toBe(0)
  260. const list = await req('get', '/api/app/files').expect(200),
  261. item = list.body.items[0]
  262. expect(typeof item.id).toBe('number')
  263. expect(item.path).toBe(`/api/app/files/${f.id}/download`)
  264. expect(item).toMatchObject({ name: 'hello.txt', size: 5, exists: true, archiveStatus: 'ready' })
  265. expect((await req('get', item.path).expect(200)).text).toBe('hello')
  266. await req('get', item.path, 'second').expect(404)
  267. await req('get', `/api/app/files/${item.id}/download`, 'second').expect(404)
  268. expect((await req('get', '/api/app/files', 'second')).body.total).toBe(0)
  269. expect(upstream.some((p) => p.includes('/files'))).toBe(false)
  270. })
  271. it('does not serve uploaded HTML or SVG as executable same-origin previews', async () => {
  272. const f = (
  273. await req('post', '/api/app/uploads')
  274. .attach('files', Buffer.from('<svg onload="alert(1)"/>'), {
  275. filename: 'unsafe.svg',
  276. contentType: 'image/svg+xml',
  277. })
  278. .expect(201)
  279. ).body.files[0]
  280. const response = await req('get', `/api/app/files/${f.id}/preview`).expect(200)
  281. expect(response.headers['content-type']).toContain('application/octet-stream')
  282. expect(response.headers['content-disposition']).toContain('attachment')
  283. })
  284. it('persists encrypted voice credentials while giving each user their own selected voice', async () => {
  285. await req('put', '/api/app/admin/duplex-voice')
  286. .send({
  287. apiKey: 'private-test-key',
  288. voices: [
  289. { id: 'a', name: '甲' },
  290. { id: 'b', name: '乙' },
  291. ],
  292. currentVoiceId: 'a',
  293. })
  294. .expect(200)
  295. const publicResponse = await req('get', '/api/app/admin/duplex-voice').expect(200)
  296. expect(publicResponse.body.hasApiKey).toBe(true)
  297. expect(publicResponse.body.apiKey).toBeUndefined()
  298. await req('put', '/api/app/voice/current-voice', 'second')
  299. .send({ currentVoiceId: 'b' })
  300. .expect(200)
  301. expect((await req('get', '/api/app/voice/runtime')).body.currentVoiceId).toBe('a')
  302. expect((await req('get', '/api/app/voice/runtime', 'second')).body.currentVoiceId).toBe('b')
  303. expect(
  304. readFileSync(join(home, 'workspace.sqlite3')).includes(Buffer.from('private-test-key')),
  305. ).toBe(false)
  306. })
  307. it('stores monotonic profile-scoped context snapshots without a plugin', async () => {
  308. const path = '/api/app/session-context/session-one?profile=default'
  309. const b = { usedTokens: 200, limitTokens: 1000, percent: 20, observedAt: 20 }
  310. await req('put', path).send(b).expect(200)
  311. await req('put', path)
  312. .send({ ...b, usedTokens: 10, observedAt: 10 })
  313. .expect(200)
  314. expect((await req('get', path)).body.snapshot).toMatchObject({ ...b, sessionId: 'session-one' })
  315. expect((await req('get', path, 'second')).body.snapshot).toBeNull()
  316. expect(
  317. (await req('get', '/api/app/session-context/session-one?profile=other')).body.snapshot,
  318. ).toBeNull()
  319. })
  320. it('protects internal Hermes session IDs on native HTTP endpoints', async () => {
  321. runtime.workspace.put('first', 'binding', 'binding', {
  322. storedId: 'internal-session',
  323. runtimeId: 'internal-runtime',
  324. aliases: ['old-id'],
  325. })
  326. await req('get', '/api/app/sessions/internal-session/messages').expect(404)
  327. await req('get', '/api/sessions/old-id/messages', 'second').expect(404)
  328. expect(upstream.some((p) => p.includes('internal-session') || p.includes('old-id'))).toBe(false)
  329. })
  330. })