app.test.ts 15 KB

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