workspaceRoutes.test.ts 16 KB

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