app.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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('keeps existing CSRF tokens valid across an 8800 restart', async () => {
  93. const config = makeConfig()
  94. const first = createApplication({ config, fetchImpl: fakeGateway([]) })
  95. const bootstrap = await request(first.app.callback())
  96. .get('/api/app/bootstrap').set('Host', '127.0.0.1:8800').expect(200)
  97. const cookies = cookieHeader(bootstrap)
  98. first.close()
  99. const restarted = createApplication({ config, fetchImpl: fakeGateway([]) })
  100. runtimes.push(restarted)
  101. expect(restarted.csrf.verify(cookies, bootstrap.body.csrfToken)).toBe(true)
  102. })
  103. it('serves authenticated historical media only from the configured root', async () => {
  104. const config = makeConfig()
  105. writeFileSync(join(config.mediaRoot, '报告.txt'), '历史文件内容')
  106. const runtime = createApplication({ config, fetchImpl: fakeGateway([]) })
  107. runtimes.push(runtime)
  108. const bootstrap = await request(runtime.app.callback())
  109. .get('/api/app/bootstrap').set('Host', '127.0.0.1:8800').expect(200)
  110. const cookies = cookieHeader(bootstrap)
  111. const response = await request(runtime.app.callback())
  112. .get('/Users/samien/Agents/报告.txt').set('Host', '127.0.0.1:8800').set('Cookie', cookies).expect(200)
  113. expect(response.text).toBe('历史文件内容')
  114. expect(response.headers['content-disposition']).toContain('inline')
  115. await request(runtime.app.callback())
  116. .get('/Users/samien/Agents/../state.db').set('Host', '127.0.0.1:8800').set('Cookie', cookies).expect(404)
  117. })
  118. it('bootstraps sequentially without exposing the upstream address', async () => {
  119. const records: RecordedRequest[] = []
  120. const runtime = createApplication({ config: makeConfig(), fetchImpl: fakeGateway(records) })
  121. runtimes.push(runtime)
  122. const response = await request(runtime.app.callback())
  123. .get('/api/app/bootstrap')
  124. .set('Host', '127.0.0.1:8800')
  125. .expect(200)
  126. expect(records.map((entry) => entry.path)).toEqual([
  127. '/api/status', '/api/auth/me', '/api/profiles', '/api/plugins/yaoyao/profiles',
  128. ])
  129. expect(response.body).toMatchObject({
  130. authRequired: true,
  131. authenticated: true,
  132. user: { user_id: 'user-1' },
  133. profiles: [{ name: 'default', agentName: '夭夭' }],
  134. groupUploadsEnabled: true,
  135. })
  136. expect(response.body.csrfToken).toEqual(expect.any(String))
  137. expect(response.body.status).toEqual({
  138. state: 'unknown',
  139. gatewayRunning: false,
  140. })
  141. expect(JSON.stringify(response.body)).not.toContain('9119')
  142. expect(response.headers['content-security-policy']).toContain("default-src 'self'")
  143. })
  144. it('omits opener isolation on plaintext LAN origins but keeps it on loopback', async () => {
  145. const runtime = createApplication({ config: makeConfig(), fetchImpl: fakeGateway([]) })
  146. runtimes.push(runtime)
  147. const lan = await request(runtime.app.callback())
  148. .get('/healthz')
  149. .set('Host', '192.168.153.155:8800')
  150. .expect(200)
  151. expect(lan.headers['cross-origin-opener-policy']).toBeUndefined()
  152. const loopback = await request(runtime.app.callback())
  153. .get('/healthz')
  154. .set('Host', '127.0.0.1:8800')
  155. .expect(200)
  156. expect(loopback.headers['cross-origin-opener-policy']).toBe('same-origin')
  157. })
  158. it('degrades unsupported Gateway unread endpoints without browser 404 responses', async () => {
  159. const records: RecordedRequest[] = []
  160. const baseGateway = fakeGateway(records)
  161. const fetchImpl = (async (input: string | URL | Request, init?: RequestInit) => {
  162. const url = new URL(input instanceof Request ? input.url : String(input))
  163. if (url.pathname.startsWith('/api/session-unread')) {
  164. records.push({
  165. path: url.pathname,
  166. method: init?.method ?? 'GET',
  167. search: url.searchParams,
  168. headers: new Headers(init?.headers),
  169. })
  170. const status = (init?.method ?? 'GET') === 'PATCH' ? 405 : 404
  171. return jsonResponse({ detail: status === 405 ? 'Method Not Allowed' : 'Not Found' }, { status })
  172. }
  173. return baseGateway(input, init)
  174. }) as typeof fetch
  175. const runtime = createApplication({ config: makeConfig(), fetchImpl })
  176. runtimes.push(runtime)
  177. const unread = await request(runtime.app.callback())
  178. .get('/api/app/sessions/unread?profile=yaoer')
  179. .set('Host', '127.0.0.1:8800')
  180. .expect(200)
  181. expect(unread.body).toEqual({ profile: 'yaoer', total_unread: 0, sessions: [], supported: false })
  182. const bootstrap = await request(runtime.app.callback())
  183. .get('/api/app/bootstrap')
  184. .set('Host', '127.0.0.1:8800')
  185. .expect(200)
  186. const marked = await request(runtime.app.callback())
  187. .patch('/api/app/sessions/unread/session-1?profile=yaoer')
  188. .set('Host', '127.0.0.1:8800')
  189. .set('Origin', 'http://127.0.0.1:8800')
  190. .set('Cookie', cookieHeader(bootstrap))
  191. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  192. .send({ readMessageCount: 12 })
  193. .expect(200)
  194. expect(marked.body).toEqual({ ok: true, supported: false })
  195. })
  196. it('requires exact Origin and CSRF on login, then sequences the Gateway login', async () => {
  197. const records: RecordedRequest[] = []
  198. const runtime = createApplication({ config: makeConfig(), fetchImpl: fakeGateway(records) })
  199. runtimes.push(runtime)
  200. const bootstrap = await request(runtime.app.callback())
  201. .get('/api/app/bootstrap')
  202. .set('Host', '127.0.0.1:8800')
  203. .expect(200)
  204. const cookies = cookieHeader(bootstrap)
  205. await request(runtime.app.callback())
  206. .post('/api/app/login')
  207. .set('Host', '127.0.0.1:8800')
  208. .set('Cookie', cookies)
  209. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  210. .send({ username: 'user', password: 'secret' })
  211. .expect(403)
  212. records.length = 0
  213. const response = await request(runtime.app.callback())
  214. .post('/api/app/login')
  215. .set('Host', '127.0.0.1:8800')
  216. .set('Origin', 'http://127.0.0.1:8800')
  217. .set('Cookie', cookies)
  218. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  219. .send({ username: 'user', password: 'secret' })
  220. .expect(200)
  221. expect(records.map((entry) => entry.path)).toEqual([
  222. '/api/auth/providers',
  223. '/auth/password-login',
  224. '/api/status',
  225. '/api/auth/me',
  226. '/api/profiles',
  227. '/api/plugins/yaoyao/profiles',
  228. ])
  229. expect(records[1]?.body).toEqual({ provider: 'basic', username: 'user', password: 'secret', next: '' })
  230. expect(response.body.authenticated).toBe(true)
  231. expect(JSON.stringify(response.body)).not.toContain('secret')
  232. })
  233. it('forces visibility and compressed-history query invariants', async () => {
  234. const records: RecordedRequest[] = []
  235. const runtime = createApplication({ config: makeConfig(), fetchImpl: fakeGateway(records) })
  236. runtimes.push(runtime)
  237. await request(runtime.app.callback())
  238. .get('/api/app/sessions?exclude_sources=evil')
  239. .set('Host', '127.0.0.1:8800')
  240. .expect(200)
  241. expect(records.at(-1)?.path).toBe('/api/profiles/sessions')
  242. expect(records.at(-1)?.search.get('exclude_sources')).toBe('cron,ios_group')
  243. await request(runtime.app.callback())
  244. .get('/api/app/sessions/session-1/messages?offset=3&limit=50&order=oldest&include_compacted=false&profile=default')
  245. .set('Host', '127.0.0.1:8800')
  246. .expect(200)
  247. const history = records.at(-1)!
  248. expect(history.search.get('offset')).toBe('3')
  249. expect(history.search.get('limit')).toBe('50')
  250. expect(history.search.get('order')).toBe('latest')
  251. expect(history.search.get('include_compacted')).toBe('true')
  252. expect(history.search.get('profile')).toBe('default')
  253. })
  254. it('keeps unknown API routes out of the SPA fallback', async () => {
  255. const runtime = createApplication({ config: makeConfig(), fetchImpl: fakeGateway([]) })
  256. runtimes.push(runtime)
  257. const response = await request(runtime.app.callback())
  258. .get('/api/anything')
  259. .set('Host', '127.0.0.1:8800')
  260. .expect(404)
  261. expect(response.body.code).toBe('not_found')
  262. })
  263. it('reuses a valid CSRF token across tabs instead of invalidating the first tab', async () => {
  264. const runtime = createApplication({ config: makeConfig(), fetchImpl: fakeGateway([]) })
  265. runtimes.push(runtime)
  266. const first = await request(runtime.app.callback())
  267. .get('/api/app/bootstrap')
  268. .set('Host', '127.0.0.1:8800')
  269. .expect(200)
  270. const second = await request(runtime.app.callback())
  271. .get('/api/app/bootstrap')
  272. .set('Host', '127.0.0.1:8800')
  273. .set('Cookie', cookieHeader(first))
  274. .expect(200)
  275. expect(second.body.csrfToken).toBe(first.body.csrfToken)
  276. })
  277. it('refuses anonymous group uploads before reading a multipart body', async () => {
  278. const fetchImpl = (async (input: string | URL | Request) => {
  279. const url = new URL(input instanceof Request ? input.url : String(input))
  280. if (url.pathname === '/api/status') return jsonResponse({ auth_required: true })
  281. if (url.pathname === '/api/auth/me') return jsonResponse({ detail: 'Unauthorized' }, { status: 401 })
  282. return jsonResponse({ profiles: [] })
  283. }) as typeof fetch
  284. const runtime = createApplication({ config: makeConfig(), fetchImpl })
  285. runtimes.push(runtime)
  286. const bootstrap = await request(runtime.app.callback())
  287. .get('/api/app/bootstrap')
  288. .set('Host', '127.0.0.1:8800')
  289. .expect(200)
  290. await request(runtime.app.callback())
  291. .post('/api/app/group-uploads')
  292. .set('Host', '127.0.0.1:8800')
  293. .set('Origin', 'http://127.0.0.1:8800')
  294. .set('Cookie', cookieHeader(bootstrap))
  295. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  296. .attach('files', Buffer.from('hello'), { filename: 'hello.txt', contentType: 'text/plain' })
  297. .expect(401)
  298. })
  299. it('forces active file content to download instead of executing on the 8800 origin', async () => {
  300. const fetchImpl = (async () => new Response('<script>window.pwned=true</script>', {
  301. status: 200,
  302. headers: { 'content-type': 'text/html; charset=utf-8' },
  303. })) as typeof fetch
  304. const runtime = createApplication({ config: makeConfig(), fetchImpl })
  305. runtimes.push(runtime)
  306. const response = await request(runtime.app.callback())
  307. .get('/api/app/files/1/preview')
  308. .set('Host', '127.0.0.1:8800')
  309. .expect(200)
  310. expect(response.headers['content-type']).toMatch(/^application\/octet-stream/)
  311. expect(response.headers['content-disposition']).toContain('attachment')
  312. })
  313. it('stores group files opaquely and injects the local path only upstream', async () => {
  314. const records: RecordedRequest[] = []
  315. const runtime = createApplication({ config: makeConfig(), fetchImpl: fakeGateway(records) })
  316. runtimes.push(runtime)
  317. const bootstrap = await request(runtime.app.callback())
  318. .get('/api/app/bootstrap')
  319. .set('Host', '127.0.0.1:8800')
  320. .expect(200)
  321. const cookies = cookieHeader(bootstrap)
  322. const upload = await request(runtime.app.callback())
  323. .post('/api/app/group-uploads')
  324. .set('Host', '127.0.0.1:8800')
  325. .set('Origin', 'http://127.0.0.1:8800')
  326. .set('Cookie', cookies)
  327. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  328. .attach('files', Buffer.from('hello'), { filename: 'hello.txt', contentType: 'text/plain' })
  329. .expect(201)
  330. expect(upload.body.files[0]).toMatchObject({ name: 'hello.txt', size: 5 })
  331. expect(upload.body.files[0].path).toBeUndefined()
  332. await request(runtime.app.callback())
  333. .post('/api/app/groups/rooms/11111111-1111-4111-8111-111111111111/messages')
  334. .set('Host', '127.0.0.1:8800')
  335. .set('Origin', 'http://127.0.0.1:8800')
  336. .set('Cookie', cookies)
  337. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  338. .send({
  339. requestId: '22222222-2222-4222-8222-222222222222',
  340. clientMessageId: '33333333-3333-4333-8333-333333333333',
  341. content: '请看文件',
  342. mentionAgentIds: [],
  343. uploadIds: [upload.body.files[0].id],
  344. })
  345. .expect(200)
  346. const sent = records.at(-1)?.body as { content: string; uploadIds?: unknown }
  347. expect(sent.uploadIds).toBeUndefined()
  348. expect(sent.content).toContain('请看文件')
  349. expect(sent.content).toContain(runtime.uploads.uploadRoot)
  350. })
  351. })