app.test.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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. const attachmentsRoot = join(home, 'attachments')
  25. const imagesRoot = join(home, 'images')
  26. mkdirSync(mediaRoot)
  27. mkdirSync(attachmentsRoot)
  28. mkdirSync(imagesRoot)
  29. homes.push(home)
  30. return {
  31. host: '127.0.0.1',
  32. port: 8800,
  33. upstream: new URL(upstream),
  34. allowedHosts: new Set(),
  35. home,
  36. mediaRoot,
  37. attachmentsRoot,
  38. imagesRoot,
  39. mediaOwner: 'samien',
  40. allowInsecureLan: false,
  41. insecureLan: false,
  42. production: false,
  43. }
  44. }
  45. function jsonResponse(value: unknown, init: ResponseInit = {}): Response {
  46. return new Response(JSON.stringify(value), {
  47. ...init,
  48. headers: { 'content-type': 'application/json', ...init.headers },
  49. })
  50. }
  51. function fakeGateway(records: RecordedRequest[]): typeof fetch {
  52. return (async (input: string | URL | Request, init?: RequestInit) => {
  53. const url = new URL(input instanceof Request ? input.url : String(input))
  54. const headers = new Headers(init?.headers)
  55. const rawBody = typeof init?.body === 'string' ? init.body : undefined
  56. const recorded: RecordedRequest = {
  57. path: url.pathname,
  58. method: init?.method ?? 'GET',
  59. search: url.searchParams,
  60. headers,
  61. body: rawBody ? JSON.parse(rawBody) : undefined,
  62. }
  63. records.push(recorded)
  64. switch (url.pathname) {
  65. case '/api/status':
  66. return jsonResponse({ auth_required: true }, {
  67. headers: { 'set-cookie': 'hermes_session_at=access-cookie; Path=/; HttpOnly; SameSite=Lax' },
  68. })
  69. case '/api/auth/me':
  70. return jsonResponse({
  71. user_id: 'user-1', display_name: '测试用户', provider: 'basic',
  72. })
  73. case '/api/profiles':
  74. return jsonResponse({ profiles: [{ name: 'default', is_default: true }] })
  75. case '/api/plugins/yaoyao/profiles':
  76. return jsonResponse({ profiles: [{ name: 'default', botName: '竹儿', agentName: '旧插件名称', isDefault: true }] })
  77. case '/api/auth/providers':
  78. return jsonResponse({ providers: [{ name: 'basic', supports_password: true }] })
  79. case '/auth/password-login':
  80. return jsonResponse({ ok: true })
  81. case '/api/profiles/sessions':
  82. case '/api/sessions':
  83. return jsonResponse({ sessions: [] })
  84. case '/api/sessions/session-1/messages':
  85. return jsonResponse({ messages: [], pagination: { returned: 0 } })
  86. case '/api/plugins/yaoyao/v1/rooms/11111111-1111-4111-8111-111111111111/messages':
  87. return jsonResponse({ accepted: true })
  88. default:
  89. return jsonResponse({ ok: true })
  90. }
  91. }) as typeof fetch
  92. }
  93. function cookieHeader(response: request.Response): string {
  94. const values = response.headers['set-cookie'] as unknown as string[]
  95. return values.map((value) => value.split(';', 1)[0]).join('; ')
  96. }
  97. describe('8800 BFF', () => {
  98. it('keeps existing CSRF tokens valid across an 8800 restart', async () => {
  99. const config = makeConfig()
  100. const first = createApplication({ config, fetchImpl: fakeGateway([]) })
  101. const bootstrap = await request(first.app.callback())
  102. .get('/api/app/bootstrap').set('Host', '127.0.0.1:8800').expect(200)
  103. const cookies = cookieHeader(bootstrap)
  104. first.close()
  105. const restarted = createApplication({ config, fetchImpl: fakeGateway([]) })
  106. runtimes.push(restarted)
  107. expect(restarted.csrf.verify(cookies, bootstrap.body.csrfToken)).toBe(true)
  108. })
  109. it('serves authenticated historical media only from the configured root', async () => {
  110. const config = makeConfig()
  111. writeFileSync(join(config.mediaRoot, '报告.txt'), '历史文件内容')
  112. const runtime = createApplication({ config, fetchImpl: fakeGateway([]) })
  113. runtimes.push(runtime)
  114. const bootstrap = await request(runtime.app.callback())
  115. .get('/api/app/bootstrap').set('Host', '127.0.0.1:8800').expect(200)
  116. const cookies = cookieHeader(bootstrap)
  117. const response = await request(runtime.app.callback())
  118. .get('/Users/samien/Agents/报告.txt').set('Host', '127.0.0.1:8800').set('Cookie', cookies).expect(200)
  119. expect(response.text).toBe('历史文件内容')
  120. expect(response.headers['content-disposition']).toContain('inline')
  121. await request(runtime.app.callback())
  122. .get('/Users/samien/Agents/../state.db').set('Host', '127.0.0.1:8800').set('Cookie', cookies).expect(404)
  123. })
  124. it('serves persisted Hermes attachment references from the restricted attachment root', async () => {
  125. const config = makeConfig()
  126. writeFileSync(join(config.attachmentsRoot, '报告.docx'), 'document bytes')
  127. const runtime = createApplication({ config, fetchImpl: fakeGateway([]) })
  128. runtimes.push(runtime)
  129. const bootstrap = await request(runtime.app.callback())
  130. .get('/api/app/bootstrap').set('Host', '127.0.0.1:8800').expect(200)
  131. const response = await request(runtime.app.callback())
  132. .get('/Users/samien/.hermes/attachments/报告.docx')
  133. .set('Host', '127.0.0.1:8800').set('Cookie', cookieHeader(bootstrap)).expect(200)
  134. expect(response.headers['content-length']).toBe(String(Buffer.byteLength('document bytes')))
  135. expect(response.headers['content-disposition']).toContain('inline')
  136. await request(runtime.app.callback())
  137. .get('/attachments/报告.docx')
  138. .set('Host', '127.0.0.1:8800').set('Cookie', cookieHeader(bootstrap)).expect(200)
  139. await request(runtime.app.callback())
  140. .get('/attachments/../state.db')
  141. .set('Host', '127.0.0.1:8800').set('Cookie', cookieHeader(bootstrap)).expect(404)
  142. })
  143. it('serves persisted Hermes image references from the restricted images root', async () => {
  144. const config = makeConfig()
  145. writeFileSync(join(config.imagesRoot, '照片.png'), 'image bytes')
  146. const runtime = createApplication({ config, fetchImpl: fakeGateway([]) })
  147. runtimes.push(runtime)
  148. const bootstrap = await request(runtime.app.callback())
  149. .get('/api/app/bootstrap').set('Host', '127.0.0.1:8800').expect(200)
  150. const response = await request(runtime.app.callback())
  151. .get('/Users/samien/.hermes/images/照片.png')
  152. .set('Host', '127.0.0.1:8800').set('Cookie', cookieHeader(bootstrap)).expect(200)
  153. expect(response.body.toString()).toBe('image bytes')
  154. await request(runtime.app.callback())
  155. .get('/Users/samien/.hermes/images/../state.db')
  156. .set('Host', '127.0.0.1:8800').set('Cookie', cookieHeader(bootstrap)).expect(404)
  157. })
  158. it('bootstraps sequentially without exposing the upstream address', async () => {
  159. const records: RecordedRequest[] = []
  160. const runtime = createApplication({ config: makeConfig(), fetchImpl: fakeGateway(records) })
  161. runtimes.push(runtime)
  162. const response = await request(runtime.app.callback())
  163. .get('/api/app/bootstrap')
  164. .set('Host', '127.0.0.1:8800')
  165. .expect(200)
  166. expect(records.map((entry) => entry.path)).toEqual([
  167. '/api/status', '/api/auth/me', '/api/profiles', '/api/plugins/yaoyao/profiles',
  168. ])
  169. expect(response.body).toMatchObject({
  170. authRequired: true,
  171. authenticated: true,
  172. user: { user_id: 'user-1' },
  173. profiles: [{ name: 'default', agentName: '竹儿' }],
  174. groupUploadsEnabled: true,
  175. })
  176. expect(response.body.csrfToken).toEqual(expect.any(String))
  177. expect(response.body.status).toEqual({
  178. state: 'unknown',
  179. gatewayRunning: false,
  180. })
  181. expect(JSON.stringify(response.body)).not.toContain('9119')
  182. expect(response.headers['content-security-policy']).toContain("default-src 'self'")
  183. })
  184. it('refreshes profiles from Hermes Bot names and ignores legacy plugin names', async () => {
  185. const records: RecordedRequest[] = []
  186. const runtime = createApplication({ config: makeConfig(), fetchImpl: fakeGateway(records) })
  187. runtimes.push(runtime)
  188. const response = await request(runtime.app.callback())
  189. .get('/api/app/profiles')
  190. .set('Host', '127.0.0.1:8800')
  191. .expect(200)
  192. expect(records.map(entry => entry.path)).toEqual([
  193. '/api/profiles', '/api/plugins/yaoyao/profiles',
  194. ])
  195. expect(response.body.profiles).toEqual([
  196. { name: 'default', is_default: true, agentName: '竹儿' },
  197. ])
  198. expect(JSON.stringify(response.body)).not.toContain('旧插件名称')
  199. })
  200. it('omits opener isolation on plaintext LAN origins but keeps it on loopback', async () => {
  201. const runtime = createApplication({ config: makeConfig(), fetchImpl: fakeGateway([]) })
  202. runtimes.push(runtime)
  203. const lan = await request(runtime.app.callback())
  204. .get('/healthz')
  205. .set('Host', '192.168.153.155:8800')
  206. .expect(200)
  207. expect(lan.headers['cross-origin-opener-policy']).toBeUndefined()
  208. const loopback = await request(runtime.app.callback())
  209. .get('/healthz')
  210. .set('Host', '127.0.0.1:8800')
  211. .expect(200)
  212. expect(loopback.headers['cross-origin-opener-policy']).toBe('same-origin')
  213. })
  214. it('degrades unsupported Gateway unread endpoints without browser 404 responses', async () => {
  215. const records: RecordedRequest[] = []
  216. const baseGateway = fakeGateway(records)
  217. const fetchImpl = (async (input: string | URL | Request, init?: RequestInit) => {
  218. const url = new URL(input instanceof Request ? input.url : String(input))
  219. if (url.pathname.startsWith('/api/session-unread')) {
  220. records.push({
  221. path: url.pathname,
  222. method: init?.method ?? 'GET',
  223. search: url.searchParams,
  224. headers: new Headers(init?.headers),
  225. })
  226. const status = (init?.method ?? 'GET') === 'PATCH' ? 405 : 404
  227. return jsonResponse({ detail: status === 405 ? 'Method Not Allowed' : 'Not Found' }, { status })
  228. }
  229. return baseGateway(input, init)
  230. }) as typeof fetch
  231. const runtime = createApplication({ config: makeConfig(), fetchImpl })
  232. runtimes.push(runtime)
  233. const unread = await request(runtime.app.callback())
  234. .get('/api/app/sessions/unread?profile=yaoer')
  235. .set('Host', '127.0.0.1:8800')
  236. .expect(200)
  237. expect(unread.body).toEqual({ profile: 'yaoer', total_unread: 0, sessions: [], supported: false })
  238. const bootstrap = await request(runtime.app.callback())
  239. .get('/api/app/bootstrap')
  240. .set('Host', '127.0.0.1:8800')
  241. .expect(200)
  242. const marked = await request(runtime.app.callback())
  243. .patch('/api/app/sessions/unread/session-1?profile=yaoer')
  244. .set('Host', '127.0.0.1:8800')
  245. .set('Origin', 'http://127.0.0.1:8800')
  246. .set('Cookie', cookieHeader(bootstrap))
  247. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  248. .send({ readMessageCount: 12 })
  249. .expect(200)
  250. expect(marked.body).toEqual({ ok: true, supported: false })
  251. })
  252. it('requires exact Origin and CSRF on login, then sequences the Gateway login', async () => {
  253. const records: RecordedRequest[] = []
  254. const runtime = createApplication({ config: makeConfig(), fetchImpl: fakeGateway(records) })
  255. runtimes.push(runtime)
  256. const bootstrap = await request(runtime.app.callback())
  257. .get('/api/app/bootstrap')
  258. .set('Host', '127.0.0.1:8800')
  259. .expect(200)
  260. const cookies = cookieHeader(bootstrap)
  261. await request(runtime.app.callback())
  262. .post('/api/app/login')
  263. .set('Host', '127.0.0.1:8800')
  264. .set('Cookie', cookies)
  265. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  266. .send({ username: 'user', password: 'secret' })
  267. .expect(403)
  268. records.length = 0
  269. const response = await request(runtime.app.callback())
  270. .post('/api/app/login')
  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({ username: 'user', password: 'secret' })
  276. .expect(200)
  277. expect(records.map((entry) => entry.path)).toEqual([
  278. '/api/auth/providers',
  279. '/auth/password-login',
  280. '/api/status',
  281. '/api/auth/me',
  282. '/api/profiles',
  283. '/api/plugins/yaoyao/profiles',
  284. ])
  285. expect(records[1]?.body).toEqual({ provider: 'basic', username: 'user', password: 'secret', next: '' })
  286. expect(response.body.authenticated).toBe(true)
  287. expect(JSON.stringify(response.body)).not.toContain('secret')
  288. })
  289. it('forces visibility and compressed-history query invariants', async () => {
  290. const records: RecordedRequest[] = []
  291. const runtime = createApplication({ config: makeConfig(), fetchImpl: fakeGateway(records) })
  292. runtimes.push(runtime)
  293. await request(runtime.app.callback())
  294. .get('/api/app/sessions?exclude_sources=evil')
  295. .set('Host', '127.0.0.1:8800')
  296. .expect(200)
  297. expect(records.at(-1)?.path).toBe('/api/profiles/sessions')
  298. expect(records.at(-1)?.search.get('exclude_sources')).toBe('cron,ios_group')
  299. await request(runtime.app.callback())
  300. .get('/api/app/sessions/session-1/messages?offset=3&limit=50&order=oldest&include_compacted=false&profile=default')
  301. .set('Host', '127.0.0.1:8800')
  302. .expect(200)
  303. const history = records.at(-1)!
  304. expect(history.search.get('offset')).toBe('3')
  305. expect(history.search.get('limit')).toBe('50')
  306. expect(history.search.get('order')).toBe('latest')
  307. expect(history.search.get('include_compacted')).toBe('true')
  308. expect(history.search.get('profile')).toBe('default')
  309. })
  310. it('proxies topic pagination and forwards topic-scoped message queries', async () => {
  311. const records: RecordedRequest[] = []
  312. const runtime = createApplication({ config: makeConfig(), fetchImpl: fakeGateway(records) })
  313. runtimes.push(runtime)
  314. const roomID = '11111111-1111-4111-8111-111111111111'
  315. const topicID = '22222222-2222-4222-8222-222222222222'
  316. await request(runtime.app.callback())
  317. .get(`/api/app/groups/rooms/${roomID}/topics?limit=25&cursor=next-topic&archived=true&ignored=drop-me`)
  318. .set('Host', '127.0.0.1:8800')
  319. .expect(200)
  320. const topics = records.at(-1)!
  321. expect(topics.path).toBe(`/api/plugins/yaoyao/v1/rooms/${roomID}/topics`)
  322. expect(topics.search.get('limit')).toBe('25')
  323. expect(topics.search.get('cursor')).toBe('next-topic')
  324. expect(topics.search.get('archived')).toBe('true')
  325. expect(topics.search.has('ignored')).toBe(false)
  326. const bootstrap = await request(runtime.app.callback())
  327. .get('/api/app/bootstrap')
  328. .set('Host', '127.0.0.1:8800')
  329. .expect(200)
  330. await request(runtime.app.callback())
  331. .patch(`/api/app/groups/rooms/${roomID}/topics/${topicID}`)
  332. .set('Host', '127.0.0.1:8800')
  333. .set('Origin', 'http://127.0.0.1:8800')
  334. .set('Cookie', cookieHeader(bootstrap))
  335. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  336. .send({ requestId: '33333333-3333-4333-8333-333333333333', title: '新标题' })
  337. .expect(200)
  338. const renamed = records.at(-1)!
  339. expect(renamed.method).toBe('PATCH')
  340. expect(renamed.path).toBe(`/api/plugins/yaoyao/v1/rooms/${roomID}/topics/${topicID}`)
  341. expect(renamed.body).toEqual({ requestId: '33333333-3333-4333-8333-333333333333', title: '新标题' })
  342. await request(runtime.app.callback())
  343. .delete(`/api/app/groups/rooms/${roomID}/topics/${topicID}`)
  344. .set('Host', '127.0.0.1:8800')
  345. .set('Origin', 'http://127.0.0.1:8800')
  346. .set('Cookie', cookieHeader(bootstrap))
  347. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  348. .send({ requestId: '55555555-5555-4555-8555-555555555555' })
  349. .expect(200)
  350. expect(records.at(-1)?.method).toBe('DELETE')
  351. expect(records.at(-1)?.path).toBe(`/api/plugins/yaoyao/v1/rooms/${roomID}/topics/${topicID}`)
  352. await request(runtime.app.callback())
  353. .post(`/api/app/groups/rooms/${roomID}/topics/${topicID}/restore`)
  354. .set('Host', '127.0.0.1:8800')
  355. .set('Origin', 'http://127.0.0.1:8800')
  356. .set('Cookie', cookieHeader(bootstrap))
  357. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  358. .send({ requestId: '66666666-6666-4666-8666-666666666666' })
  359. .expect(200)
  360. expect(records.at(-1)?.method).toBe('POST')
  361. expect(records.at(-1)?.path).toBe(`/api/plugins/yaoyao/v1/rooms/${roomID}/topics/${topicID}/restore`)
  362. await request(runtime.app.callback())
  363. .patch(`/api/app/groups/rooms/${roomID}/topics/${topicID}/read`)
  364. .set('Host', '127.0.0.1:8800')
  365. .set('Origin', 'http://127.0.0.1:8800')
  366. .set('Cookie', cookieHeader(bootstrap))
  367. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  368. .send({ requestId: '44444444-4444-4444-8444-444444444444', throughSeq: 42 })
  369. .expect(200)
  370. const markedRead = records.at(-1)!
  371. expect(markedRead.method).toBe('PATCH')
  372. expect(markedRead.path).toBe(`/api/plugins/yaoyao/v1/rooms/${roomID}/topics/${topicID}/read`)
  373. expect(markedRead.body).toEqual({ requestId: '44444444-4444-4444-8444-444444444444', throughSeq: 42 })
  374. await request(runtime.app.callback())
  375. .get(`/api/app/groups/rooms/${roomID}/messages?topicId=${topicID}&beforeSeq=40&limit=20`)
  376. .set('Host', '127.0.0.1:8800')
  377. .expect(200)
  378. const messages = records.at(-1)!
  379. expect(messages.path).toBe(`/api/plugins/yaoyao/v1/rooms/${roomID}/messages`)
  380. expect(messages.search.get('topicId')).toBe(topicID)
  381. expect(messages.search.get('beforeSeq')).toBe('40')
  382. expect(messages.search.get('limit')).toBe('20')
  383. })
  384. it('keeps unknown API routes out of the SPA fallback', async () => {
  385. const runtime = createApplication({ config: makeConfig(), fetchImpl: fakeGateway([]) })
  386. runtimes.push(runtime)
  387. const response = await request(runtime.app.callback())
  388. .get('/api/anything')
  389. .set('Host', '127.0.0.1:8800')
  390. .expect(404)
  391. expect(response.body.code).toBe('not_found')
  392. })
  393. it('reuses a valid CSRF token across tabs instead of invalidating the first tab', async () => {
  394. const runtime = createApplication({ config: makeConfig(), fetchImpl: fakeGateway([]) })
  395. runtimes.push(runtime)
  396. const first = await request(runtime.app.callback())
  397. .get('/api/app/bootstrap')
  398. .set('Host', '127.0.0.1:8800')
  399. .expect(200)
  400. const second = await request(runtime.app.callback())
  401. .get('/api/app/bootstrap')
  402. .set('Host', '127.0.0.1:8800')
  403. .set('Cookie', cookieHeader(first))
  404. .expect(200)
  405. expect(second.body.csrfToken).toBe(first.body.csrfToken)
  406. })
  407. it('refuses anonymous group uploads before reading a multipart body', async () => {
  408. const fetchImpl = (async (input: string | URL | Request) => {
  409. const url = new URL(input instanceof Request ? input.url : String(input))
  410. if (url.pathname === '/api/status') return jsonResponse({ auth_required: true })
  411. if (url.pathname === '/api/auth/me') return jsonResponse({ detail: 'Unauthorized' }, { status: 401 })
  412. return jsonResponse({ profiles: [] })
  413. }) as typeof fetch
  414. const runtime = createApplication({ config: makeConfig(), fetchImpl })
  415. runtimes.push(runtime)
  416. const bootstrap = await request(runtime.app.callback())
  417. .get('/api/app/bootstrap')
  418. .set('Host', '127.0.0.1:8800')
  419. .expect(200)
  420. await request(runtime.app.callback())
  421. .post('/api/app/group-uploads')
  422. .set('Host', '127.0.0.1:8800')
  423. .set('Origin', 'http://127.0.0.1:8800')
  424. .set('Cookie', cookieHeader(bootstrap))
  425. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  426. .attach('files', Buffer.from('hello'), { filename: 'hello.txt', contentType: 'text/plain' })
  427. .expect(401)
  428. })
  429. it('forces active file content to download instead of executing on the 8800 origin', async () => {
  430. const fetchImpl = (async () => new Response('<script>window.pwned=true</script>', {
  431. status: 200,
  432. headers: { 'content-type': 'text/html; charset=utf-8' },
  433. })) as typeof fetch
  434. const runtime = createApplication({ config: makeConfig(), fetchImpl })
  435. runtimes.push(runtime)
  436. const response = await request(runtime.app.callback())
  437. .get('/api/app/files/1/preview')
  438. .set('Host', '127.0.0.1:8800')
  439. .expect(200)
  440. expect(response.headers['content-type']).toMatch(/^application\/octet-stream/)
  441. expect(response.headers['content-disposition']).toContain('attachment')
  442. })
  443. it('stores group files opaquely and injects the local path only upstream', async () => {
  444. const records: RecordedRequest[] = []
  445. const runtime = createApplication({ config: makeConfig(), fetchImpl: fakeGateway(records) })
  446. runtimes.push(runtime)
  447. const bootstrap = await request(runtime.app.callback())
  448. .get('/api/app/bootstrap')
  449. .set('Host', '127.0.0.1:8800')
  450. .expect(200)
  451. const cookies = cookieHeader(bootstrap)
  452. const upload = await request(runtime.app.callback())
  453. .post('/api/app/group-uploads')
  454. .set('Host', '127.0.0.1:8800')
  455. .set('Origin', 'http://127.0.0.1:8800')
  456. .set('Cookie', cookies)
  457. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  458. .attach('files', Buffer.from('hello'), { filename: 'hello.txt', contentType: 'text/plain' })
  459. .expect(201)
  460. expect(upload.body.files[0]).toMatchObject({ name: 'hello.txt', size: 5 })
  461. expect(upload.body.files[0].path).toBeUndefined()
  462. await request(runtime.app.callback())
  463. .post('/api/app/groups/rooms/11111111-1111-4111-8111-111111111111/messages')
  464. .set('Host', '127.0.0.1:8800')
  465. .set('Origin', 'http://127.0.0.1:8800')
  466. .set('Cookie', cookies)
  467. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  468. .send({
  469. requestId: '22222222-2222-4222-8222-222222222222',
  470. clientMessageId: '33333333-3333-4333-8333-333333333333',
  471. content: '请看文件',
  472. mentionAgentIds: [],
  473. uploadIds: [upload.body.files[0].id],
  474. })
  475. .expect(200)
  476. const sent = records.at(-1)?.body as { content: string; uploadIds?: unknown }
  477. expect(sent.uploadIds).toBeUndefined()
  478. expect(sent.content).toContain('请看文件')
  479. expect(sent.content).toContain(runtime.uploads.uploadRoot)
  480. })
  481. })