workspaceRoutes.test.ts 15 KB

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