app.test.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  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('installs a fresh Yaoyao plugin through authenticated Hermes and restarts supervised 9119', async () => {
  110. const records: RecordedRequest[] = []
  111. const baseGateway = fakeGateway(records)
  112. const fetchImpl = (async (input: string | URL | Request, init?: RequestInit) => {
  113. const url = new URL(input instanceof Request ? input.url : String(input))
  114. if (url.pathname === '/api/dashboard/plugins') return jsonResponse([])
  115. if (url.pathname === '/api/dashboard/agent-plugins/install') {
  116. const rawBody = typeof init?.body === 'string' ? init.body : '{}'
  117. records.push({
  118. path: url.pathname,
  119. method: init?.method ?? 'GET',
  120. search: url.searchParams,
  121. headers: new Headers(init?.headers),
  122. body: JSON.parse(rawBody),
  123. })
  124. return jsonResponse({ ok: true, plugin_name: 'yaoyao', enabled: true })
  125. }
  126. return baseGateway(input, init)
  127. }) as typeof fetch
  128. let restarts = 0
  129. const runtime = createApplication({
  130. config: makeConfig(),
  131. fetchImpl,
  132. restartDashboard: async () => { restarts += 1 },
  133. })
  134. runtimes.push(runtime)
  135. const bootstrap = await request(runtime.app.callback())
  136. .get('/api/app/bootstrap').set('Host', '127.0.0.1:8800').expect(200)
  137. const response = await request(runtime.app.callback())
  138. .post('/api/app/plugins/yaoyao/install')
  139. .set('Host', '127.0.0.1:8800')
  140. .set('Origin', 'http://127.0.0.1:8800')
  141. .set('Cookie', cookieHeader(bootstrap))
  142. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  143. .send({ force: false })
  144. .expect(200)
  145. const install = records.find((entry) => entry.path === '/api/dashboard/agent-plugins/install')
  146. expect(install?.body).toEqual({
  147. identifier: 'https://git.samien.cn/samien/hermes-yaoyao.git#hermes-plugins/yaoyao',
  148. force: false,
  149. enable: true,
  150. })
  151. expect(restarts).toBe(1)
  152. expect(response.body).toMatchObject({
  153. ok: true,
  154. plugin_name: 'yaoyao',
  155. restarted: true,
  156. restartRequired: false,
  157. })
  158. })
  159. it('refuses to replace an existing Yaoyao before durable storage is ready', async () => {
  160. const records: RecordedRequest[] = []
  161. const baseGateway = fakeGateway(records)
  162. const fetchImpl = (async (input: string | URL | Request, init?: RequestInit) => {
  163. const url = new URL(input instanceof Request ? input.url : String(input))
  164. if (url.pathname === '/api/dashboard/plugins') {
  165. return jsonResponse([{ name: 'yaoyao', version: '1.7.1' }])
  166. }
  167. if (url.pathname === '/api/plugins/yaoyao/maintenance/storage') {
  168. return jsonResponse({ detail: 'Not Found' }, { status: 404 })
  169. }
  170. return baseGateway(input, init)
  171. }) as typeof fetch
  172. const runtime = createApplication({ config: makeConfig(), fetchImpl })
  173. runtimes.push(runtime)
  174. const bootstrap = await request(runtime.app.callback())
  175. .get('/api/app/bootstrap').set('Host', '127.0.0.1:8800').expect(200)
  176. const response = await request(runtime.app.callback())
  177. .post('/api/app/plugins/yaoyao/install')
  178. .set('Host', '127.0.0.1:8800')
  179. .set('Origin', 'http://127.0.0.1:8800')
  180. .set('Cookie', cookieHeader(bootstrap))
  181. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  182. .send({ force: true })
  183. .expect(409)
  184. expect(response.body.code).toBe('yaoyao_storage_migration_required')
  185. expect(records.some((entry) => entry.path === '/api/dashboard/agent-plugins/install')).toBe(false)
  186. })
  187. it('upgrades an existing Yaoyao only after storage readiness and explicit force', async () => {
  188. const records: RecordedRequest[] = []
  189. const baseGateway = fakeGateway(records)
  190. const fetchImpl = (async (input: string | URL | Request, init?: RequestInit) => {
  191. const url = new URL(input instanceof Request ? input.url : String(input))
  192. if (url.pathname === '/api/dashboard/plugins') {
  193. return jsonResponse([{ name: 'yaoyao', version: '1.7.1' }])
  194. }
  195. if (url.pathname === '/api/plugins/yaoyao/maintenance/storage') {
  196. return jsonResponse({ ready: true, profiles: [{ profile: 'default', ready: true }] })
  197. }
  198. if (url.pathname === '/api/dashboard/agent-plugins/install') {
  199. const rawBody = typeof init?.body === 'string' ? init.body : '{}'
  200. records.push({
  201. path: url.pathname,
  202. method: init?.method ?? 'GET',
  203. search: url.searchParams,
  204. headers: new Headers(init?.headers),
  205. body: JSON.parse(rawBody),
  206. })
  207. return jsonResponse({ ok: true, plugin_name: 'yaoyao', enabled: true })
  208. }
  209. return baseGateway(input, init)
  210. }) as typeof fetch
  211. const runtime = createApplication({ config: makeConfig(), fetchImpl })
  212. runtimes.push(runtime)
  213. const bootstrap = await request(runtime.app.callback())
  214. .get('/api/app/bootstrap').set('Host', '127.0.0.1:8800').expect(200)
  215. const common = request(runtime.app.callback())
  216. .post('/api/app/plugins/yaoyao/install')
  217. .set('Host', '127.0.0.1:8800')
  218. .set('Origin', 'http://127.0.0.1:8800')
  219. .set('Cookie', cookieHeader(bootstrap))
  220. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  221. await common.send({ force: false }).expect(409)
  222. await request(runtime.app.callback())
  223. .post('/api/app/plugins/yaoyao/install')
  224. .set('Host', '127.0.0.1:8800')
  225. .set('Origin', 'http://127.0.0.1:8800')
  226. .set('Cookie', cookieHeader(bootstrap))
  227. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  228. .send({ force: true })
  229. .expect(200)
  230. const install = records.find((entry) => entry.path === '/api/dashboard/agent-plugins/install')
  231. expect(install?.body).toMatchObject({ force: true, enable: true })
  232. })
  233. it('serves authenticated historical media only from the configured root', async () => {
  234. const config = makeConfig()
  235. writeFileSync(join(config.mediaRoot, '报告.txt'), '历史文件内容')
  236. const runtime = createApplication({ config, fetchImpl: fakeGateway([]) })
  237. runtimes.push(runtime)
  238. const bootstrap = await request(runtime.app.callback())
  239. .get('/api/app/bootstrap').set('Host', '127.0.0.1:8800').expect(200)
  240. const cookies = cookieHeader(bootstrap)
  241. const response = await request(runtime.app.callback())
  242. .get('/Users/samien/Agents/报告.txt').set('Host', '127.0.0.1:8800').set('Cookie', cookies).expect(200)
  243. expect(response.text).toBe('历史文件内容')
  244. expect(response.headers['content-disposition']).toContain('inline')
  245. await request(runtime.app.callback())
  246. .get('/Users/samien/Agents/../state.db').set('Host', '127.0.0.1:8800').set('Cookie', cookies).expect(404)
  247. })
  248. it('serves persisted Hermes attachment references from the restricted attachment root', async () => {
  249. const config = makeConfig()
  250. writeFileSync(join(config.attachmentsRoot, '报告.docx'), 'document bytes')
  251. const runtime = createApplication({ config, fetchImpl: fakeGateway([]) })
  252. runtimes.push(runtime)
  253. const bootstrap = await request(runtime.app.callback())
  254. .get('/api/app/bootstrap').set('Host', '127.0.0.1:8800').expect(200)
  255. const response = await request(runtime.app.callback())
  256. .get('/Users/samien/.hermes/attachments/报告.docx')
  257. .set('Host', '127.0.0.1:8800').set('Cookie', cookieHeader(bootstrap)).expect(200)
  258. expect(response.headers['content-length']).toBe(String(Buffer.byteLength('document bytes')))
  259. expect(response.headers['content-disposition']).toContain('inline')
  260. await request(runtime.app.callback())
  261. .get('/attachments/报告.docx')
  262. .set('Host', '127.0.0.1:8800').set('Cookie', cookieHeader(bootstrap)).expect(200)
  263. await request(runtime.app.callback())
  264. .get('/attachments/../state.db')
  265. .set('Host', '127.0.0.1:8800').set('Cookie', cookieHeader(bootstrap)).expect(404)
  266. })
  267. it('serves persisted Hermes image references from the restricted images root', async () => {
  268. const config = makeConfig()
  269. writeFileSync(join(config.imagesRoot, '照片.png'), 'image bytes')
  270. const runtime = createApplication({ config, fetchImpl: fakeGateway([]) })
  271. runtimes.push(runtime)
  272. const bootstrap = await request(runtime.app.callback())
  273. .get('/api/app/bootstrap').set('Host', '127.0.0.1:8800').expect(200)
  274. const response = await request(runtime.app.callback())
  275. .get('/Users/samien/.hermes/images/照片.png')
  276. .set('Host', '127.0.0.1:8800').set('Cookie', cookieHeader(bootstrap)).expect(200)
  277. expect(response.body.toString()).toBe('image bytes')
  278. await request(runtime.app.callback())
  279. .get('/Users/samien/.hermes/images/../state.db')
  280. .set('Host', '127.0.0.1:8800').set('Cookie', cookieHeader(bootstrap)).expect(404)
  281. })
  282. it('bootstraps sequentially without exposing the upstream address', async () => {
  283. const records: RecordedRequest[] = []
  284. const runtime = createApplication({ config: makeConfig(), fetchImpl: fakeGateway(records) })
  285. runtimes.push(runtime)
  286. const response = await request(runtime.app.callback())
  287. .get('/api/app/bootstrap')
  288. .set('Host', '127.0.0.1:8800')
  289. .expect(200)
  290. expect(records.map((entry) => entry.path)).toEqual([
  291. '/api/status', '/api/auth/me', '/api/profiles', '/api/plugins/yaoyao/profiles',
  292. ])
  293. expect(response.body).toMatchObject({
  294. authRequired: true,
  295. authenticated: true,
  296. user: { user_id: 'user-1' },
  297. profiles: [{ name: 'default', agentName: '竹儿' }],
  298. groupUploadsEnabled: true,
  299. })
  300. expect(response.body.csrfToken).toEqual(expect.any(String))
  301. expect(response.body.status).toEqual({
  302. state: 'unknown',
  303. gatewayRunning: false,
  304. })
  305. expect(JSON.stringify(response.body)).not.toContain('9119')
  306. expect(response.headers['content-security-policy']).toContain("default-src 'self'")
  307. })
  308. it('refreshes profiles from Hermes Bot names and ignores legacy plugin names', async () => {
  309. const records: RecordedRequest[] = []
  310. const runtime = createApplication({ config: makeConfig(), fetchImpl: fakeGateway(records) })
  311. runtimes.push(runtime)
  312. const response = await request(runtime.app.callback())
  313. .get('/api/app/profiles')
  314. .set('Host', '127.0.0.1:8800')
  315. .expect(200)
  316. expect(records.map(entry => entry.path)).toEqual([
  317. '/api/profiles', '/api/plugins/yaoyao/profiles',
  318. ])
  319. expect(response.body.profiles).toEqual([
  320. { name: 'default', is_default: true, agentName: '竹儿' },
  321. ])
  322. expect(JSON.stringify(response.body)).not.toContain('旧插件名称')
  323. })
  324. it('omits opener isolation on plaintext LAN origins but keeps it on loopback', async () => {
  325. const runtime = createApplication({ config: makeConfig(), fetchImpl: fakeGateway([]) })
  326. runtimes.push(runtime)
  327. const lan = await request(runtime.app.callback())
  328. .get('/healthz')
  329. .set('Host', '192.168.153.155:8800')
  330. .expect(200)
  331. expect(lan.headers['cross-origin-opener-policy']).toBeUndefined()
  332. const loopback = await request(runtime.app.callback())
  333. .get('/healthz')
  334. .set('Host', '127.0.0.1:8800')
  335. .expect(200)
  336. expect(loopback.headers['cross-origin-opener-policy']).toBe('same-origin')
  337. })
  338. it('degrades unsupported Gateway unread endpoints without browser 404 responses', async () => {
  339. const records: RecordedRequest[] = []
  340. const baseGateway = fakeGateway(records)
  341. const fetchImpl = (async (input: string | URL | Request, init?: RequestInit) => {
  342. const url = new URL(input instanceof Request ? input.url : String(input))
  343. if (url.pathname.startsWith('/api/session-unread')) {
  344. records.push({
  345. path: url.pathname,
  346. method: init?.method ?? 'GET',
  347. search: url.searchParams,
  348. headers: new Headers(init?.headers),
  349. })
  350. const status = (init?.method ?? 'GET') === 'PATCH' ? 405 : 404
  351. return jsonResponse({ detail: status === 405 ? 'Method Not Allowed' : 'Not Found' }, { status })
  352. }
  353. return baseGateway(input, init)
  354. }) as typeof fetch
  355. const runtime = createApplication({ config: makeConfig(), fetchImpl })
  356. runtimes.push(runtime)
  357. const unread = await request(runtime.app.callback())
  358. .get('/api/app/sessions/unread?profile=yaoer')
  359. .set('Host', '127.0.0.1:8800')
  360. .expect(200)
  361. expect(unread.body).toEqual({ profile: 'yaoer', total_unread: 0, sessions: [], supported: false })
  362. const bootstrap = await request(runtime.app.callback())
  363. .get('/api/app/bootstrap')
  364. .set('Host', '127.0.0.1:8800')
  365. .expect(200)
  366. const marked = await request(runtime.app.callback())
  367. .patch('/api/app/sessions/unread/session-1?profile=yaoer')
  368. .set('Host', '127.0.0.1:8800')
  369. .set('Origin', 'http://127.0.0.1:8800')
  370. .set('Cookie', cookieHeader(bootstrap))
  371. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  372. .send({ readMessageCount: 12 })
  373. .expect(200)
  374. expect(marked.body).toEqual({ ok: true, supported: false })
  375. })
  376. it('requires exact Origin and CSRF on login, then sequences the Gateway login', async () => {
  377. const records: RecordedRequest[] = []
  378. const runtime = createApplication({ config: makeConfig(), fetchImpl: fakeGateway(records) })
  379. runtimes.push(runtime)
  380. const bootstrap = await request(runtime.app.callback())
  381. .get('/api/app/bootstrap')
  382. .set('Host', '127.0.0.1:8800')
  383. .expect(200)
  384. const cookies = cookieHeader(bootstrap)
  385. await request(runtime.app.callback())
  386. .post('/api/app/login')
  387. .set('Host', '127.0.0.1:8800')
  388. .set('Cookie', cookies)
  389. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  390. .send({ username: 'user', password: 'secret' })
  391. .expect(403)
  392. records.length = 0
  393. const response = await request(runtime.app.callback())
  394. .post('/api/app/login')
  395. .set('Host', '127.0.0.1:8800')
  396. .set('Origin', 'http://127.0.0.1:8800')
  397. .set('Cookie', cookies)
  398. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  399. .send({ username: 'user', password: 'secret' })
  400. .expect(200)
  401. expect(records.map((entry) => entry.path)).toEqual([
  402. '/api/auth/providers',
  403. '/auth/password-login',
  404. '/api/status',
  405. '/api/auth/me',
  406. '/api/profiles',
  407. '/api/plugins/yaoyao/profiles',
  408. ])
  409. expect(records[1]?.body).toEqual({ provider: 'basic', username: 'user', password: 'secret', next: '' })
  410. expect(response.body.authenticated).toBe(true)
  411. expect(JSON.stringify(response.body)).not.toContain('secret')
  412. })
  413. it('forces visibility and compressed-history query invariants', async () => {
  414. const records: RecordedRequest[] = []
  415. const runtime = createApplication({ config: makeConfig(), fetchImpl: fakeGateway(records) })
  416. runtimes.push(runtime)
  417. await request(runtime.app.callback())
  418. .get('/api/app/sessions?exclude_sources=evil')
  419. .set('Host', '127.0.0.1:8800')
  420. .expect(200)
  421. expect(records.at(-1)?.path).toBe('/api/profiles/sessions')
  422. expect(records.at(-1)?.search.get('exclude_sources')).toBe('cron,ios_group')
  423. await request(runtime.app.callback())
  424. .get('/api/app/sessions/session-1/messages?offset=3&limit=50&order=oldest&include_compacted=false&profile=default')
  425. .set('Host', '127.0.0.1:8800')
  426. .expect(200)
  427. const history = records.at(-1)!
  428. expect(history.search.get('offset')).toBe('3')
  429. expect(history.search.get('limit')).toBe('50')
  430. expect(history.search.get('order')).toBe('latest')
  431. expect(history.search.get('include_compacted')).toBe('true')
  432. expect(history.search.get('profile')).toBe('default')
  433. })
  434. it('proxies topic pagination and forwards topic-scoped message queries', async () => {
  435. const records: RecordedRequest[] = []
  436. const runtime = createApplication({ config: makeConfig(), fetchImpl: fakeGateway(records) })
  437. runtimes.push(runtime)
  438. const roomID = '11111111-1111-4111-8111-111111111111'
  439. const topicID = '22222222-2222-4222-8222-222222222222'
  440. await request(runtime.app.callback())
  441. .get('/api/app/groups/topics?limit=40&cursor=next-global-topic&archived=true&ignored=drop-me')
  442. .set('Host', '127.0.0.1:8800')
  443. .expect(200)
  444. const globalTopics = records.at(-1)!
  445. expect(globalTopics.path).toBe('/api/plugins/yaoyao/v1/topics')
  446. expect(globalTopics.search.get('limit')).toBe('40')
  447. expect(globalTopics.search.get('cursor')).toBe('next-global-topic')
  448. expect(globalTopics.search.has('archived')).toBe(false)
  449. expect(globalTopics.search.has('ignored')).toBe(false)
  450. await request(runtime.app.callback())
  451. .get(`/api/app/groups/rooms/${roomID}/topics?limit=25&cursor=next-topic&archived=true&ignored=drop-me`)
  452. .set('Host', '127.0.0.1:8800')
  453. .expect(200)
  454. const topics = records.at(-1)!
  455. expect(topics.path).toBe(`/api/plugins/yaoyao/v1/rooms/${roomID}/topics`)
  456. expect(topics.search.get('limit')).toBe('25')
  457. expect(topics.search.get('cursor')).toBe('next-topic')
  458. expect(topics.search.get('archived')).toBe('true')
  459. expect(topics.search.has('ignored')).toBe(false)
  460. const bootstrap = await request(runtime.app.callback())
  461. .get('/api/app/bootstrap')
  462. .set('Host', '127.0.0.1:8800')
  463. .expect(200)
  464. await request(runtime.app.callback())
  465. .patch(`/api/app/groups/rooms/${roomID}/topics/${topicID}`)
  466. .set('Host', '127.0.0.1:8800')
  467. .set('Origin', 'http://127.0.0.1:8800')
  468. .set('Cookie', cookieHeader(bootstrap))
  469. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  470. .send({ requestId: '33333333-3333-4333-8333-333333333333', title: '新标题' })
  471. .expect(200)
  472. const renamed = records.at(-1)!
  473. expect(renamed.method).toBe('PATCH')
  474. expect(renamed.path).toBe(`/api/plugins/yaoyao/v1/rooms/${roomID}/topics/${topicID}`)
  475. expect(renamed.body).toEqual({ requestId: '33333333-3333-4333-8333-333333333333', title: '新标题' })
  476. await request(runtime.app.callback())
  477. .delete(`/api/app/groups/rooms/${roomID}/topics/${topicID}`)
  478. .set('Host', '127.0.0.1:8800')
  479. .set('Origin', 'http://127.0.0.1:8800')
  480. .set('Cookie', cookieHeader(bootstrap))
  481. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  482. .send({ requestId: '55555555-5555-4555-8555-555555555555' })
  483. .expect(200)
  484. expect(records.at(-1)?.method).toBe('DELETE')
  485. expect(records.at(-1)?.path).toBe(`/api/plugins/yaoyao/v1/rooms/${roomID}/topics/${topicID}`)
  486. await request(runtime.app.callback())
  487. .post(`/api/app/groups/rooms/${roomID}/topics/${topicID}/restore`)
  488. .set('Host', '127.0.0.1:8800')
  489. .set('Origin', 'http://127.0.0.1:8800')
  490. .set('Cookie', cookieHeader(bootstrap))
  491. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  492. .send({ requestId: '66666666-6666-4666-8666-666666666666' })
  493. .expect(200)
  494. expect(records.at(-1)?.method).toBe('POST')
  495. expect(records.at(-1)?.path).toBe(`/api/plugins/yaoyao/v1/rooms/${roomID}/topics/${topicID}/restore`)
  496. await request(runtime.app.callback())
  497. .patch(`/api/app/groups/rooms/${roomID}/topics/${topicID}/read`)
  498. .set('Host', '127.0.0.1:8800')
  499. .set('Origin', 'http://127.0.0.1:8800')
  500. .set('Cookie', cookieHeader(bootstrap))
  501. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  502. .send({ requestId: '44444444-4444-4444-8444-444444444444', throughSeq: 42 })
  503. .expect(200)
  504. const markedRead = records.at(-1)!
  505. expect(markedRead.method).toBe('PATCH')
  506. expect(markedRead.path).toBe(`/api/plugins/yaoyao/v1/rooms/${roomID}/topics/${topicID}/read`)
  507. expect(markedRead.body).toEqual({ requestId: '44444444-4444-4444-8444-444444444444', throughSeq: 42 })
  508. await request(runtime.app.callback())
  509. .get(`/api/app/groups/rooms/${roomID}/messages?topicId=${topicID}&beforeSeq=40&limit=20`)
  510. .set('Host', '127.0.0.1:8800')
  511. .expect(200)
  512. const messages = records.at(-1)!
  513. expect(messages.path).toBe(`/api/plugins/yaoyao/v1/rooms/${roomID}/messages`)
  514. expect(messages.search.get('topicId')).toBe(topicID)
  515. expect(messages.search.get('beforeSeq')).toBe('40')
  516. expect(messages.search.get('limit')).toBe('20')
  517. })
  518. it('keeps unknown API routes out of the SPA fallback', async () => {
  519. const runtime = createApplication({ config: makeConfig(), fetchImpl: fakeGateway([]) })
  520. runtimes.push(runtime)
  521. const response = await request(runtime.app.callback())
  522. .get('/api/anything')
  523. .set('Host', '127.0.0.1:8800')
  524. .expect(404)
  525. expect(response.body.code).toBe('not_found')
  526. })
  527. it('reuses a valid CSRF token across tabs instead of invalidating the first tab', async () => {
  528. const runtime = createApplication({ config: makeConfig(), fetchImpl: fakeGateway([]) })
  529. runtimes.push(runtime)
  530. const first = await request(runtime.app.callback())
  531. .get('/api/app/bootstrap')
  532. .set('Host', '127.0.0.1:8800')
  533. .expect(200)
  534. const second = await request(runtime.app.callback())
  535. .get('/api/app/bootstrap')
  536. .set('Host', '127.0.0.1:8800')
  537. .set('Cookie', cookieHeader(first))
  538. .expect(200)
  539. expect(second.body.csrfToken).toBe(first.body.csrfToken)
  540. })
  541. it('refuses anonymous group uploads before reading a multipart body', async () => {
  542. const fetchImpl = (async (input: string | URL | Request) => {
  543. const url = new URL(input instanceof Request ? input.url : String(input))
  544. if (url.pathname === '/api/status') return jsonResponse({ auth_required: true })
  545. if (url.pathname === '/api/auth/me') return jsonResponse({ detail: 'Unauthorized' }, { status: 401 })
  546. return jsonResponse({ profiles: [] })
  547. }) as typeof fetch
  548. const runtime = createApplication({ config: makeConfig(), fetchImpl })
  549. runtimes.push(runtime)
  550. const bootstrap = await request(runtime.app.callback())
  551. .get('/api/app/bootstrap')
  552. .set('Host', '127.0.0.1:8800')
  553. .expect(200)
  554. await request(runtime.app.callback())
  555. .post('/api/app/group-uploads')
  556. .set('Host', '127.0.0.1:8800')
  557. .set('Origin', 'http://127.0.0.1:8800')
  558. .set('Cookie', cookieHeader(bootstrap))
  559. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  560. .attach('files', Buffer.from('hello'), { filename: 'hello.txt', contentType: 'text/plain' })
  561. .expect(401)
  562. })
  563. it('forces active file content to download instead of executing on the 8800 origin', async () => {
  564. const fetchImpl = (async () => new Response('<script>window.pwned=true</script>', {
  565. status: 200,
  566. headers: { 'content-type': 'text/html; charset=utf-8' },
  567. })) as typeof fetch
  568. const runtime = createApplication({ config: makeConfig(), fetchImpl })
  569. runtimes.push(runtime)
  570. const response = await request(runtime.app.callback())
  571. .get('/api/app/files/1/preview')
  572. .set('Host', '127.0.0.1:8800')
  573. .expect(200)
  574. expect(response.headers['content-type']).toMatch(/^application\/octet-stream/)
  575. expect(response.headers['content-disposition']).toContain('attachment')
  576. })
  577. it('stores group files opaquely and injects the local path only upstream', async () => {
  578. const records: RecordedRequest[] = []
  579. const runtime = createApplication({ config: makeConfig(), fetchImpl: fakeGateway(records) })
  580. runtimes.push(runtime)
  581. const bootstrap = await request(runtime.app.callback())
  582. .get('/api/app/bootstrap')
  583. .set('Host', '127.0.0.1:8800')
  584. .expect(200)
  585. const cookies = cookieHeader(bootstrap)
  586. const upload = await request(runtime.app.callback())
  587. .post('/api/app/group-uploads')
  588. .set('Host', '127.0.0.1:8800')
  589. .set('Origin', 'http://127.0.0.1:8800')
  590. .set('Cookie', cookies)
  591. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  592. .attach('files', Buffer.from('hello'), { filename: 'hello.txt', contentType: 'text/plain' })
  593. .expect(201)
  594. expect(upload.body.files[0]).toMatchObject({ name: 'hello.txt', size: 5 })
  595. expect(upload.body.files[0].path).toBeUndefined()
  596. await request(runtime.app.callback())
  597. .post('/api/app/groups/rooms/11111111-1111-4111-8111-111111111111/messages')
  598. .set('Host', '127.0.0.1:8800')
  599. .set('Origin', 'http://127.0.0.1:8800')
  600. .set('Cookie', cookies)
  601. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  602. .send({
  603. requestId: '22222222-2222-4222-8222-222222222222',
  604. clientMessageId: '33333333-3333-4333-8333-333333333333',
  605. content: '请看文件',
  606. mentionAgentIds: [],
  607. uploadIds: [upload.body.files[0].id],
  608. })
  609. .expect(200)
  610. const sent = records.at(-1)?.body as { content: string; uploadIds?: unknown }
  611. expect(sent.uploadIds).toBeUndefined()
  612. expect(sent.content).toContain('请看文件')
  613. expect(sent.content).toContain(runtime.uploads.uploadRoot)
  614. })
  615. })