app.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
  2. import { tmpdir } from 'node:os'
  3. import { join } from 'node:path'
  4. import request from 'supertest'
  5. import { afterEach, describe, expect, it } from 'vitest'
  6. import { createApplication, type ApplicationRuntime } from '../../src/server/app.js'
  7. import type { ServerConfig } from '../../src/server/config.js'
  8. interface RecordedRequest {
  9. path: string
  10. method: string
  11. search: URLSearchParams
  12. headers: Headers
  13. body?: unknown
  14. }
  15. const runtimes: ApplicationRuntime[] = []
  16. const homes: string[] = []
  17. afterEach(() => {
  18. for (const runtime of runtimes.splice(0)) runtime.close()
  19. for (const home of homes.splice(0)) rmSync(home, { recursive: true, force: true })
  20. })
  21. function makeConfig(upstream = 'http://127.0.0.1:9119'): ServerConfig {
  22. const home = mkdtempSync(join(tmpdir(), 'hermes-yaoyao-server-'))
  23. const mediaRoot = join(home, 'media')
  24. mkdirSync(mediaRoot)
  25. homes.push(home)
  26. return {
  27. host: '127.0.0.1',
  28. port: 8800,
  29. upstream: new URL(upstream),
  30. allowedHosts: new Set(),
  31. home,
  32. mediaRoot,
  33. mediaOwner: 'samien',
  34. allowInsecureLan: false,
  35. insecureLan: false,
  36. production: false,
  37. }
  38. }
  39. function jsonResponse(value: unknown, init: ResponseInit = {}): Response {
  40. return new Response(JSON.stringify(value), {
  41. ...init,
  42. headers: { 'content-type': 'application/json', ...init.headers },
  43. })
  44. }
  45. function fakeGateway(records: RecordedRequest[]): typeof fetch {
  46. return (async (input: string | URL | Request, init?: RequestInit) => {
  47. const url = new URL(input instanceof Request ? input.url : String(input))
  48. const headers = new Headers(init?.headers)
  49. const rawBody = typeof init?.body === 'string' ? init.body : undefined
  50. const recorded: RecordedRequest = {
  51. path: url.pathname,
  52. method: init?.method ?? 'GET',
  53. search: url.searchParams,
  54. headers,
  55. body: rawBody ? JSON.parse(rawBody) : undefined,
  56. }
  57. records.push(recorded)
  58. switch (url.pathname) {
  59. case '/api/status':
  60. return jsonResponse({ auth_required: true }, {
  61. headers: { 'set-cookie': 'hermes_session_at=access-cookie; Path=/; HttpOnly; SameSite=Lax' },
  62. })
  63. case '/api/auth/me':
  64. return jsonResponse({
  65. user_id: 'user-1', display_name: '测试用户', provider: 'basic',
  66. })
  67. case '/api/profiles':
  68. return jsonResponse({ profiles: [{ name: 'default', is_default: true }] })
  69. case '/api/plugins/yaoyao/profiles':
  70. return jsonResponse({ profiles: [{ name: 'default', agentName: '夭夭', isDefault: true }] })
  71. case '/api/auth/providers':
  72. return jsonResponse({ providers: [{ name: 'basic', supports_password: true }] })
  73. case '/auth/password-login':
  74. return jsonResponse({ ok: true })
  75. case '/api/profiles/sessions':
  76. case '/api/sessions':
  77. return jsonResponse({ sessions: [] })
  78. case '/api/sessions/session-1/messages':
  79. return jsonResponse({ messages: [], pagination: { returned: 0 } })
  80. case '/api/plugins/yaoyao/v1/rooms/11111111-1111-4111-8111-111111111111/messages':
  81. return jsonResponse({ accepted: true })
  82. default:
  83. return jsonResponse({ ok: true })
  84. }
  85. }) as typeof fetch
  86. }
  87. function cookieHeader(response: request.Response): string {
  88. const values = response.headers['set-cookie'] as unknown as string[]
  89. return values.map((value) => value.split(';', 1)[0]).join('; ')
  90. }
  91. describe('8800 BFF', () => {
  92. it('serves authenticated historical media only from the configured root', async () => {
  93. const config = makeConfig()
  94. writeFileSync(join(config.mediaRoot, '报告.txt'), '历史文件内容')
  95. const runtime = createApplication({ config, fetchImpl: fakeGateway([]) })
  96. runtimes.push(runtime)
  97. const bootstrap = await request(runtime.app.callback())
  98. .get('/api/app/bootstrap').set('Host', '127.0.0.1:8800').expect(200)
  99. const cookies = cookieHeader(bootstrap)
  100. const response = await request(runtime.app.callback())
  101. .get('/Users/samien/Agents/报告.txt').set('Host', '127.0.0.1:8800').set('Cookie', cookies).expect(200)
  102. expect(response.text).toBe('历史文件内容')
  103. expect(response.headers['content-disposition']).toContain('inline')
  104. await request(runtime.app.callback())
  105. .get('/Users/samien/Agents/../state.db').set('Host', '127.0.0.1:8800').set('Cookie', cookies).expect(404)
  106. })
  107. it('bootstraps sequentially without exposing the upstream address', async () => {
  108. const records: RecordedRequest[] = []
  109. const runtime = createApplication({ config: makeConfig(), fetchImpl: fakeGateway(records) })
  110. runtimes.push(runtime)
  111. const response = await request(runtime.app.callback())
  112. .get('/api/app/bootstrap')
  113. .set('Host', '127.0.0.1:8800')
  114. .expect(200)
  115. expect(records.map((entry) => entry.path)).toEqual([
  116. '/api/status', '/api/auth/me', '/api/profiles', '/api/plugins/yaoyao/profiles',
  117. ])
  118. expect(response.body).toMatchObject({
  119. authRequired: true,
  120. authenticated: true,
  121. user: { user_id: 'user-1' },
  122. profiles: [{ name: 'default', agentName: '夭夭' }],
  123. groupUploadsEnabled: true,
  124. })
  125. expect(response.body.csrfToken).toEqual(expect.any(String))
  126. expect(response.body.status).toEqual({
  127. state: 'unknown',
  128. gatewayRunning: false,
  129. })
  130. expect(JSON.stringify(response.body)).not.toContain('9119')
  131. expect(response.headers['content-security-policy']).toContain("default-src 'self'")
  132. })
  133. it('requires exact Origin and CSRF on login, then sequences the Gateway login', async () => {
  134. const records: RecordedRequest[] = []
  135. const runtime = createApplication({ config: makeConfig(), fetchImpl: fakeGateway(records) })
  136. runtimes.push(runtime)
  137. const bootstrap = await request(runtime.app.callback())
  138. .get('/api/app/bootstrap')
  139. .set('Host', '127.0.0.1:8800')
  140. .expect(200)
  141. const cookies = cookieHeader(bootstrap)
  142. await request(runtime.app.callback())
  143. .post('/api/app/login')
  144. .set('Host', '127.0.0.1:8800')
  145. .set('Cookie', cookies)
  146. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  147. .send({ username: 'user', password: 'secret' })
  148. .expect(403)
  149. records.length = 0
  150. const response = await request(runtime.app.callback())
  151. .post('/api/app/login')
  152. .set('Host', '127.0.0.1:8800')
  153. .set('Origin', 'http://127.0.0.1:8800')
  154. .set('Cookie', cookies)
  155. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  156. .send({ username: 'user', password: 'secret' })
  157. .expect(200)
  158. expect(records.map((entry) => entry.path)).toEqual([
  159. '/api/auth/providers',
  160. '/auth/password-login',
  161. '/api/status',
  162. '/api/auth/me',
  163. '/api/profiles',
  164. '/api/plugins/yaoyao/profiles',
  165. ])
  166. expect(records[1]?.body).toEqual({ provider: 'basic', username: 'user', password: 'secret', next: '' })
  167. expect(response.body.authenticated).toBe(true)
  168. expect(JSON.stringify(response.body)).not.toContain('secret')
  169. })
  170. it('forces visibility and compressed-history query invariants', async () => {
  171. const records: RecordedRequest[] = []
  172. const runtime = createApplication({ config: makeConfig(), fetchImpl: fakeGateway(records) })
  173. runtimes.push(runtime)
  174. await request(runtime.app.callback())
  175. .get('/api/app/sessions?exclude_sources=evil')
  176. .set('Host', '127.0.0.1:8800')
  177. .expect(200)
  178. expect(records.at(-1)?.path).toBe('/api/profiles/sessions')
  179. expect(records.at(-1)?.search.get('exclude_sources')).toBe('cron,ios_group')
  180. await request(runtime.app.callback())
  181. .get('/api/app/sessions/session-1/messages?offset=3&limit=50&order=oldest&include_compacted=false&profile=default')
  182. .set('Host', '127.0.0.1:8800')
  183. .expect(200)
  184. const history = records.at(-1)!
  185. expect(history.search.get('offset')).toBe('3')
  186. expect(history.search.get('limit')).toBe('50')
  187. expect(history.search.get('order')).toBe('latest')
  188. expect(history.search.get('include_compacted')).toBe('true')
  189. expect(history.search.get('profile')).toBe('default')
  190. })
  191. it('keeps unknown API routes out of the SPA fallback', async () => {
  192. const runtime = createApplication({ config: makeConfig(), fetchImpl: fakeGateway([]) })
  193. runtimes.push(runtime)
  194. const response = await request(runtime.app.callback())
  195. .get('/api/anything')
  196. .set('Host', '127.0.0.1:8800')
  197. .expect(404)
  198. expect(response.body.code).toBe('not_found')
  199. })
  200. it('reuses a valid CSRF token across tabs instead of invalidating the first tab', async () => {
  201. const runtime = createApplication({ config: makeConfig(), fetchImpl: fakeGateway([]) })
  202. runtimes.push(runtime)
  203. const first = await request(runtime.app.callback())
  204. .get('/api/app/bootstrap')
  205. .set('Host', '127.0.0.1:8800')
  206. .expect(200)
  207. const second = await request(runtime.app.callback())
  208. .get('/api/app/bootstrap')
  209. .set('Host', '127.0.0.1:8800')
  210. .set('Cookie', cookieHeader(first))
  211. .expect(200)
  212. expect(second.body.csrfToken).toBe(first.body.csrfToken)
  213. })
  214. it('refuses anonymous group uploads before reading a multipart body', async () => {
  215. const fetchImpl = (async (input: string | URL | Request) => {
  216. const url = new URL(input instanceof Request ? input.url : String(input))
  217. if (url.pathname === '/api/status') return jsonResponse({ auth_required: true })
  218. if (url.pathname === '/api/auth/me') return jsonResponse({ detail: 'Unauthorized' }, { status: 401 })
  219. return jsonResponse({ profiles: [] })
  220. }) as typeof fetch
  221. const runtime = createApplication({ config: makeConfig(), fetchImpl })
  222. runtimes.push(runtime)
  223. const bootstrap = await request(runtime.app.callback())
  224. .get('/api/app/bootstrap')
  225. .set('Host', '127.0.0.1:8800')
  226. .expect(200)
  227. await request(runtime.app.callback())
  228. .post('/api/app/group-uploads')
  229. .set('Host', '127.0.0.1:8800')
  230. .set('Origin', 'http://127.0.0.1:8800')
  231. .set('Cookie', cookieHeader(bootstrap))
  232. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  233. .attach('files', Buffer.from('hello'), { filename: 'hello.txt', contentType: 'text/plain' })
  234. .expect(401)
  235. })
  236. it('forces active file content to download instead of executing on the 8800 origin', async () => {
  237. const fetchImpl = (async () => new Response('<script>window.pwned=true</script>', {
  238. status: 200,
  239. headers: { 'content-type': 'text/html; charset=utf-8' },
  240. })) as typeof fetch
  241. const runtime = createApplication({ config: makeConfig(), fetchImpl })
  242. runtimes.push(runtime)
  243. const response = await request(runtime.app.callback())
  244. .get('/api/app/files/1/preview')
  245. .set('Host', '127.0.0.1:8800')
  246. .expect(200)
  247. expect(response.headers['content-type']).toMatch(/^application\/octet-stream/)
  248. expect(response.headers['content-disposition']).toContain('attachment')
  249. })
  250. it('stores group files opaquely and injects the local path only upstream', async () => {
  251. const records: RecordedRequest[] = []
  252. const runtime = createApplication({ config: makeConfig(), fetchImpl: fakeGateway(records) })
  253. runtimes.push(runtime)
  254. const bootstrap = await request(runtime.app.callback())
  255. .get('/api/app/bootstrap')
  256. .set('Host', '127.0.0.1:8800')
  257. .expect(200)
  258. const cookies = cookieHeader(bootstrap)
  259. const upload = await request(runtime.app.callback())
  260. .post('/api/app/group-uploads')
  261. .set('Host', '127.0.0.1:8800')
  262. .set('Origin', 'http://127.0.0.1:8800')
  263. .set('Cookie', cookies)
  264. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  265. .attach('files', Buffer.from('hello'), { filename: 'hello.txt', contentType: 'text/plain' })
  266. .expect(201)
  267. expect(upload.body.files[0]).toMatchObject({ name: 'hello.txt', size: 5 })
  268. expect(upload.body.files[0].path).toBeUndefined()
  269. await request(runtime.app.callback())
  270. .post('/api/app/groups/rooms/11111111-1111-4111-8111-111111111111/messages')
  271. .set('Host', '127.0.0.1:8800')
  272. .set('Origin', 'http://127.0.0.1:8800')
  273. .set('Cookie', cookies)
  274. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  275. .send({
  276. requestId: '22222222-2222-4222-8222-222222222222',
  277. clientMessageId: '33333333-3333-4333-8333-333333333333',
  278. content: '请看文件',
  279. mentionAgentIds: [],
  280. uploadIds: [upload.body.files[0].id],
  281. })
  282. .expect(200)
  283. const sent = records.at(-1)?.body as { content: string; uploadIds?: unknown }
  284. expect(sent.uploadIds).toBeUndefined()
  285. expect(sent.content).toContain('请看文件')
  286. expect(sent.content).toContain(runtime.uploads.uploadRoot)
  287. })
  288. })