workspaceRoutes.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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[]
  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 currentFromCookieHeader() {
  33. return first
  34. }
  35. override isUserActive() {
  36. return true
  37. }
  38. }
  39. function req(method: 'get' | 'post' | 'put' | 'patch' | 'delete', path: string, user = 'first') {
  40. return request(runtime.app.callback())
  41. [method](path)
  42. .set('Host', '127.0.0.1:15300')
  43. .set('Origin', 'http://127.0.0.1:15300')
  44. .set('Cookie', cookie)
  45. .set('X-CSRF-Token', csrf)
  46. .set('x-test-user', user)
  47. }
  48. beforeEach(async () => {
  49. home = mkdtempSync(join(tmpdir(), 'yaoyao-workspace-routes-'))
  50. upstream = []
  51. const config = loadServerConfig({
  52. HERMES_YAOYAO_HOME: home,
  53. HERMES_YAOYAO_UPSTREAM: 'http://127.0.0.1:19119',
  54. HERMES_YAOYAO_ALLOWED_HOSTS: '127.0.0.1,localhost',
  55. })
  56. runtime = createApplication({
  57. config,
  58. auth: new TestAuth(home, false),
  59. fetchImpl: (async (input) => {
  60. const path = new URL(String(input)).pathname
  61. upstream.push(path)
  62. const body =
  63. path === '/api/status'
  64. ? { auth_required: true }
  65. : path === '/api/auth/me'
  66. ? { user_id: 'upstream' }
  67. : path === '/api/profiles'
  68. ? { profiles: [{ name: 'default', display_name: '基础 Agent' }] }
  69. : { ok: true }
  70. return new Response(JSON.stringify(body), {
  71. status: path.includes('/plugins/') ? 404 : 200,
  72. headers: { 'Content-Type': 'application/json' },
  73. })
  74. }) as typeof fetch,
  75. })
  76. const b = await request(runtime.app.callback())
  77. .get('/api/app/bootstrap')
  78. .set('Host', '127.0.0.1:15300')
  79. .expect(200)
  80. cookie = (b.headers['set-cookie'] as unknown as string[]).map((v) => v.split(';')[0]).join('; ')
  81. csrf = b.body.csrfToken
  82. })
  83. afterEach(() => {
  84. runtime.close()
  85. rmSync(home, { recursive: true, force: true })
  86. })
  87. describe('application workspace HTTP contract', () => {
  88. it('archives native-chat uploads through the standard file API with user ownership', async () => {
  89. const assets = new WorkspaceAssets(runtime.workspace, runtime.workspaceRuntime.nodes, home)
  90. await assets.archiveText(
  91. 'first',
  92. '{"path":"/tmp/native-upload.txt"}',
  93. 'local',
  94. 'default',
  95. 'native-session',
  96. 'native-message',
  97. 'user',
  98. )
  99. const page = await req('get', '/api/app/files').expect(200)
  100. expect(page.body.items[0]).toMatchObject({
  101. name: 'native-upload.txt',
  102. sender: 'user',
  103. profile: 'default',
  104. })
  105. expect(upstream).toContain('/api/files/download')
  106. expect((await req('get', '/api/app/files', 'second')).body.items).toEqual([])
  107. expect(upstream.some((p) => p.includes('/plugins/'))).toBe(false)
  108. })
  109. it('works without plugin discovery, installation, or any plugin HTTP request', async () => {
  110. const capabilities = (await req('get', '/api/app/capabilities').expect(200)).body.features
  111. expect(capabilities).toContain('editableGroups')
  112. expect(capabilities).not.toContain('immutableGroups')
  113. await req('get', '/api/app/files').expect(200)
  114. await req('get', '/api/app/voice/runtime').expect(200)
  115. await req('get', '/api/app/system/update/status').expect(200)
  116. await req('post', '/api/app/plugins/yaoyao/reconcile').send({}).expect(410)
  117. await req('get', '/api/plugins/yaoyao/v1/capabilities').expect(410)
  118. expect(upstream.some((p) => p.includes('/plugins/'))).toBe(false)
  119. })
  120. it('changes members over HTTP while protecting the administrator and ownership', async () => {
  121. const a = (
  122. await req('post', '/api/app/agents').send({ name: '编辑', profile: 'default' }).expect(201)
  123. ).body.agent
  124. const b = (
  125. await req('post', '/api/app/agents').send({ name: '审查', profile: 'default' }).expect(201)
  126. ).body.agent
  127. const c = (
  128. await req('post', '/api/app/conversations')
  129. .send({ name: '团队', memberIds: [a.id, b.id], administratorId: a.id })
  130. .expect(201)
  131. ).body.conversation
  132. const rows = await req('get', '/api/app/conversations').expect(200)
  133. expect(rows.body.conversations).toHaveLength(3)
  134. await req('patch', `/api/app/conversations/${c.id}`)
  135. .send({ memberIds: [b.id], administratorId: b.id })
  136. .expect(400)
  137. await req('patch', `/api/app/conversations/${c.id}`).send({ memberIds: [a.id] }).expect(200)
  138. expect((await req('get', `/api/app/conversations/${c.id}`)).body.conversation.memberIds).toEqual([a.id])
  139. await req('patch', `/api/app/conversations/${c.id}`).send({ memberIds: [a.id, b.id] }).expect(200)
  140. await req('get', `/api/app/conversations/${c.id}`, 'second').expect(404)
  141. await req('patch', `/api/app/agents/${a.id}`, 'second').send({ name: '入侵' }).expect(404)
  142. expect((await req('get', '/api/app/events', 'second')).body.events).toEqual([])
  143. expect(upstream.some((p) => p.includes('sessions'))).toBe(false)
  144. })
  145. it('creates, lists, renames, selects, and deletes group tasks without changing remote members', async () => {
  146. const a = (
  147. await req('post', '/api/app/agents').send({ name: '本机管理员', profile: 'default' }).expect(201)
  148. ).body.agent
  149. const b = (
  150. await req('post', '/api/app/agents').send({ name: '远程成员', nodeId: 'local', profile: 'default' }).expect(201)
  151. ).body.agent
  152. const conversation = (
  153. await req('post', '/api/app/conversations')
  154. .send({ name: '多任务团队', memberIds: [a.id, b.id], administratorId: a.id })
  155. .expect(201)
  156. ).body.conversation
  157. const initial = (await req('get', `/api/app/conversations/${conversation.id}/tasks`).expect(200)).body.tasks
  158. expect(initial).toHaveLength(1)
  159. expect(initial[0]).toMatchObject({
  160. conversationId: conversation.id,
  161. title: '新任务',
  162. titleSource: 'automatic',
  163. messageCount: 0,
  164. })
  165. const task = (
  166. await req('post', `/api/app/conversations/${conversation.id}/tasks`)
  167. .send({ title: '远程 Agent 调研' })
  168. .expect(201)
  169. ).body.task
  170. expect(task).toMatchObject({ title: '远程 Agent 调研', titleSource: 'user' })
  171. const renamed = (
  172. await req('patch', `/api/app/conversations/${conversation.id}/tasks/${task.id}`)
  173. .send({ title: '远程 Agent 复核' })
  174. .expect(200)
  175. ).body.task
  176. expect(renamed).toMatchObject({ title: '远程 Agent 复核', titleSource: 'user' })
  177. const detail = (await req('get', `/api/app/conversations/${conversation.id}?taskId=${task.id}`).expect(200)).body
  178. expect(detail.task.id).toBe(task.id)
  179. expect(detail.tasks.map((row: { id: string }) => row.id)).toContain(task.id)
  180. expect(detail.messages).toEqual([])
  181. expect(detail.conversation).toMatchObject({ memberIds: [a.id, b.id], administratorId: a.id })
  182. expect((await req('put', `/api/app/conversations/${conversation.id}/tasks/${task.id}/read`).send({ seq: 100 }).expect(200)).body.task)
  183. .toMatchObject({ readSeq: 0, lastSeq: 0, unreadCount: 0 })
  184. await req('get', `/api/app/conversations/${conversation.id}/tasks`, 'second').expect(404)
  185. await req('delete', `/api/app/conversations/${conversation.id}/tasks/${task.id}`).expect(200)
  186. const remaining = (await req('get', `/api/app/conversations/${conversation.id}/tasks`).expect(200)).body.tasks
  187. expect(remaining.map((row: { id: string }) => row.id)).not.toContain(task.id)
  188. expect((await req('get', `/api/app/conversations/${conversation.id}`)).body.conversation)
  189. .toMatchObject({ memberIds: [a.id, b.id], administratorId: a.id })
  190. await req('delete', `/api/app/conversations/${conversation.id}/tasks/${initial[0].id}`).expect(200)
  191. const replacement = (await req('get', `/api/app/conversations/${conversation.id}/tasks`).expect(200)).body.tasks
  192. expect(replacement).toHaveLength(1)
  193. expect(replacement[0].id).not.toBe(initial[0].id)
  194. })
  195. it('archives files on the Web server, preserves native library fields, and blocks cross-user downloads', async () => {
  196. const f = (
  197. await req('post', '/api/app/uploads')
  198. .attach('files', Buffer.from('hello'), { filename: 'hello.txt', contentType: 'text/plain' })
  199. .expect(201)
  200. ).body.files[0]
  201. expect(f.path).toBeUndefined()
  202. expect(runtime.uploads.cleanupUncommitted(0)).toBe(0)
  203. const list = await req('get', '/api/app/files').expect(200),
  204. item = list.body.items[0]
  205. expect(typeof item.id).toBe('number')
  206. expect(item.path).toBe(`/api/app/files/${f.id}/download`)
  207. expect(item).toMatchObject({ name: 'hello.txt', size: 5, exists: true, archiveStatus: 'ready' })
  208. expect((await req('get', item.path).expect(200)).text).toBe('hello')
  209. await req('get', item.path, 'second').expect(404)
  210. await req('get', `/api/app/files/${item.id}/download`, 'second').expect(404)
  211. expect((await req('get', '/api/app/files', 'second')).body.total).toBe(0)
  212. expect(upstream.some((p) => p.includes('/files'))).toBe(false)
  213. })
  214. it('does not serve uploaded HTML or SVG as executable same-origin previews', async () => {
  215. const f = (
  216. await req('post', '/api/app/uploads')
  217. .attach('files', Buffer.from('<svg onload="alert(1)"/>'), {
  218. filename: 'unsafe.svg',
  219. contentType: 'image/svg+xml',
  220. })
  221. .expect(201)
  222. ).body.files[0]
  223. const response = await req('get', `/api/app/files/${f.id}/preview`).expect(200)
  224. expect(response.headers['content-type']).toContain('application/octet-stream')
  225. expect(response.headers['content-disposition']).toContain('attachment')
  226. })
  227. it('persists encrypted voice credentials while giving each user their own selected voice', async () => {
  228. await req('put', '/api/app/admin/duplex-voice')
  229. .send({
  230. apiKey: 'private-test-key',
  231. voices: [
  232. { id: 'a', name: '甲' },
  233. { id: 'b', name: '乙' },
  234. ],
  235. currentVoiceId: 'a',
  236. })
  237. .expect(200)
  238. const publicResponse = await req('get', '/api/app/admin/duplex-voice').expect(200)
  239. expect(publicResponse.body.hasApiKey).toBe(true)
  240. expect(publicResponse.body.apiKey).toBeUndefined()
  241. await req('put', '/api/app/voice/current-voice', 'second')
  242. .send({ currentVoiceId: 'b' })
  243. .expect(200)
  244. expect((await req('get', '/api/app/voice/runtime')).body.currentVoiceId).toBe('a')
  245. expect((await req('get', '/api/app/voice/runtime', 'second')).body.currentVoiceId).toBe('b')
  246. expect(
  247. readFileSync(join(home, 'workspace.sqlite3')).includes(Buffer.from('private-test-key')),
  248. ).toBe(false)
  249. })
  250. it('stores monotonic profile-scoped context snapshots without a plugin', async () => {
  251. const path = '/api/app/session-context/session-one?profile=default'
  252. const b = { usedTokens: 200, limitTokens: 1000, percent: 20, observedAt: 20 }
  253. await req('put', path).send(b).expect(200)
  254. await req('put', path)
  255. .send({ ...b, usedTokens: 10, observedAt: 10 })
  256. .expect(200)
  257. expect((await req('get', path)).body.snapshot).toMatchObject({ ...b, sessionId: 'session-one' })
  258. expect((await req('get', path, 'second')).body.snapshot).toBeNull()
  259. expect(
  260. (await req('get', '/api/app/session-context/session-one?profile=other')).body.snapshot,
  261. ).toBeNull()
  262. })
  263. it('protects internal Hermes session IDs on native HTTP endpoints', async () => {
  264. runtime.workspace.put('first', 'binding', 'binding', {
  265. storedId: 'internal-session',
  266. runtimeId: 'internal-runtime',
  267. aliases: ['old-id'],
  268. })
  269. await req('get', '/api/app/sessions/internal-session/messages').expect(404)
  270. await req('get', '/api/sessions/old-id/messages', 'second').expect(404)
  271. expect(upstream.some((p) => p.includes('internal-session') || p.includes('old-id'))).toBe(false)
  272. })
  273. })