app.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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 as createUnauthenticatedApplication, type ApplicationRuntime } from '../../src/server/app.js'
  7. import type { ServerConfig } from '../../src/server/config.js'
  8. import { createAuthenticatedApplication as createApplication, createUserAuthenticatedApplication } from './authenticatedApplication.js'
  9. import { saveFileAccess } from '../../src/server/fileAccess.js'
  10. interface RecordedRequest {
  11. path: string
  12. method: string
  13. search: URLSearchParams
  14. headers: Headers
  15. body?: unknown
  16. }
  17. const runtimes: ApplicationRuntime[] = []
  18. const homes: string[] = []
  19. afterEach(() => {
  20. for (const runtime of runtimes.splice(0)) runtime.close()
  21. for (const home of homes.splice(0)) rmSync(home, { recursive: true, force: true })
  22. })
  23. function makeConfig(upstream = 'http://127.0.0.1:9119'): ServerConfig {
  24. const home = mkdtempSync(join(tmpdir(), 'hermes-yaoyao-server-'))
  25. saveFileAccess(home, { mode: 'all', folders: [] })
  26. const mediaRoot = join(home, 'media')
  27. const attachmentsRoot = join(home, 'attachments')
  28. const imagesRoot = join(home, 'images')
  29. mkdirSync(mediaRoot)
  30. mkdirSync(attachmentsRoot)
  31. mkdirSync(imagesRoot)
  32. homes.push(home)
  33. return {
  34. host: '127.0.0.1',
  35. port: 15300,
  36. upstream: new URL(upstream),
  37. allowedHosts: new Set(),
  38. home,
  39. mediaRoot,
  40. attachmentsRoot,
  41. imagesRoot,
  42. mediaOwner: 'samien',
  43. allowInsecureLan: false,
  44. insecureLan: false,
  45. production: false,
  46. }
  47. }
  48. function jsonResponse(value: unknown, init: ResponseInit = {}): Response {
  49. return new Response(JSON.stringify(value), {
  50. ...init,
  51. headers: { 'content-type': 'application/json', ...init.headers },
  52. })
  53. }
  54. function fakeGateway(records: RecordedRequest[]): typeof fetch {
  55. return (async (input: string | URL | Request, init?: RequestInit) => {
  56. const url = new URL(input instanceof Request ? input.url : String(input))
  57. const headers = new Headers(init?.headers)
  58. const rawBody = typeof init?.body === 'string' ? init.body : undefined
  59. const recorded: RecordedRequest = {
  60. path: url.pathname,
  61. method: init?.method ?? 'GET',
  62. search: url.searchParams,
  63. headers,
  64. body: rawBody ? JSON.parse(rawBody) : undefined,
  65. }
  66. records.push(recorded)
  67. switch (url.pathname) {
  68. case '/api/status':
  69. return jsonResponse({ auth_required: true }, {
  70. headers: { 'set-cookie': 'hermes_session_at=access-cookie; Path=/; HttpOnly; SameSite=Lax' },
  71. })
  72. case '/api/auth/me':
  73. return jsonResponse({
  74. user_id: 'user-1', display_name: '测试用户', provider: 'basic',
  75. })
  76. case '/api/profiles':
  77. return jsonResponse({ profiles: [{ name: 'default', is_default: true, display_name: '竹儿' }] })
  78. case '/api/plugins/yaoyao/profiles':
  79. return jsonResponse({ profiles: [{ name: 'default', botName: '竹儿', agentName: '旧插件名称', isDefault: true }] })
  80. case '/api/auth/providers':
  81. return jsonResponse({ providers: [{ name: 'basic', supports_password: true }] })
  82. case '/auth/password-login':
  83. return jsonResponse({ ok: true })
  84. case '/api/profiles/sessions':
  85. case '/api/sessions':
  86. return jsonResponse({ sessions: [] })
  87. case '/api/sessions/session-1/messages':
  88. return jsonResponse({ messages: [], pagination: { returned: 0 } })
  89. case '/api/plugins/yaoyao/v1/rooms/11111111-1111-4111-8111-111111111111/messages':
  90. return jsonResponse({ accepted: true })
  91. default:
  92. return jsonResponse({ ok: true })
  93. }
  94. }) as typeof fetch
  95. }
  96. function cookieHeader(response: request.Response): string {
  97. const values = response.headers['set-cookie'] as unknown as string[]
  98. return values.map((value) => value.split(';', 1)[0]).join('; ')
  99. }
  100. describe('15300 BFF', () => {
  101. it.each([
  102. { create: createUnauthenticatedApplication, authenticated: false },
  103. { create: createApplication, authenticated: true },
  104. { create: createUserAuthenticatedApplication, authenticated: true },
  105. ])('inspects local login state without binding a Hermes session (authenticated=$authenticated)', async ({ create, authenticated }) => {
  106. const records: RecordedRequest[] = []
  107. const runtime = create({ config: makeConfig(), fetchImpl: fakeGateway(records) })
  108. runtimes.push(runtime)
  109. const result = await request(runtime.app.callback()).get('/api/app/bootstrap?inspectOnly=1')
  110. .set('Host', '127.0.0.1:15300').expect(200)
  111. expect(result.body).toMatchObject({ authenticated, serverKind: 'yaoyao-web', profiles: [] })
  112. expect(result.body.registrationAvailable).toEqual(expect.any(Boolean))
  113. expect(runtime.csrf.verify(cookieHeader(result), result.body.csrfToken)).toBe(true)
  114. expect(result.headers['cache-control']).toContain('no-store')
  115. expect(records).toEqual([])
  116. })
  117. it.each([
  118. { create: createUnauthenticatedApplication, userId: null },
  119. { create: createApplication, userId: 'test-admin' },
  120. { create: createUserAuthenticatedApplication, userId: 'test-user' },
  121. ])('renews CSRF for $userId without requesting upstream profiles or status', async ({ create, userId }) => {
  122. const records: RecordedRequest[] = []
  123. const runtime = create({ config: makeConfig(), fetchImpl: fakeGateway(records) })
  124. runtimes.push(runtime)
  125. const result = await request(runtime.app.callback()).get('/api/app/bootstrap?csrfOnly=1')
  126. .set('Host', '127.0.0.1:15300').expect(200)
  127. expect(result.body).toEqual({ csrfToken: expect.any(String), userId })
  128. expect(runtime.csrf.verify(cookieHeader(result), result.body.csrfToken)).toBe(true)
  129. expect(result.headers['set-cookie'][0]).toContain('Max-Age=28800')
  130. expect(result.headers['cache-control']).toContain('no-store')
  131. expect(records).toEqual([])
  132. const again = await request(runtime.app.callback()).get('/api/app/bootstrap?csrfOnly=1')
  133. .set('Host', '127.0.0.1:15300').set('Cookie', cookieHeader(result)).expect(200)
  134. expect(again.body.csrfToken).toBe(result.body.csrfToken)
  135. expect(records).toEqual([])
  136. })
  137. it('keeps existing CSRF tokens valid across an 15300 restart', async () => {
  138. const config = makeConfig()
  139. const first = createApplication({ config, fetchImpl: fakeGateway([]) })
  140. const bootstrap = await request(first.app.callback())
  141. .get('/api/app/bootstrap').set('Host', '127.0.0.1:15300').expect(200)
  142. const cookies = cookieHeader(bootstrap)
  143. first.close()
  144. const restarted = createApplication({ config, fetchImpl: fakeGateway([]) })
  145. runtimes.push(restarted)
  146. expect(restarted.csrf.verify(cookies, bootstrap.body.csrfToken)).toBe(true)
  147. })
  148. it('serves authenticated historical media only from the configured root', async () => {
  149. const config = makeConfig()
  150. writeFileSync(join(config.mediaRoot, '报告.txt'), '历史文件内容')
  151. const runtime = createApplication({ config, fetchImpl: fakeGateway([]) })
  152. runtimes.push(runtime)
  153. const bootstrap = await request(runtime.app.callback())
  154. .get('/api/app/bootstrap').set('Host', '127.0.0.1:15300').expect(200)
  155. const cookies = cookieHeader(bootstrap)
  156. const response = await request(runtime.app.callback())
  157. .get('/Users/samien/Agents/报告.txt').set('Host', '127.0.0.1:15300').set('Cookie', cookies).expect(200)
  158. expect(response.text).toBe('历史文件内容')
  159. expect(response.headers['content-disposition']).toContain('inline')
  160. await request(runtime.app.callback())
  161. .get('/Users/samien/Agents/../state.db').set('Host', '127.0.0.1:15300').set('Cookie', cookies).expect(404)
  162. })
  163. it('serves persisted Hermes attachment references from the restricted attachment root', async () => {
  164. const config = makeConfig()
  165. writeFileSync(join(config.attachmentsRoot, '报告.docx'), 'document bytes')
  166. const runtime = createApplication({ config, fetchImpl: fakeGateway([]) })
  167. runtimes.push(runtime)
  168. const bootstrap = await request(runtime.app.callback())
  169. .get('/api/app/bootstrap').set('Host', '127.0.0.1:15300').expect(200)
  170. const response = await request(runtime.app.callback())
  171. .get('/Users/samien/.hermes/attachments/报告.docx')
  172. .set('Host', '127.0.0.1:15300').set('Cookie', cookieHeader(bootstrap)).expect(200)
  173. expect(response.headers['content-length']).toBe(String(Buffer.byteLength('document bytes')))
  174. expect(response.headers['content-disposition']).toContain('inline')
  175. await request(runtime.app.callback())
  176. .get('/attachments/报告.docx')
  177. .set('Host', '127.0.0.1:15300').set('Cookie', cookieHeader(bootstrap)).expect(200)
  178. await request(runtime.app.callback())
  179. .get('/attachments/../state.db')
  180. .set('Host', '127.0.0.1:15300').set('Cookie', cookieHeader(bootstrap)).expect(404)
  181. })
  182. it('serves persisted Hermes image references from the restricted images root', async () => {
  183. const config = makeConfig()
  184. writeFileSync(join(config.imagesRoot, '照片.png'), 'image bytes')
  185. const runtime = createApplication({ config, fetchImpl: fakeGateway([]) })
  186. runtimes.push(runtime)
  187. const bootstrap = await request(runtime.app.callback())
  188. .get('/api/app/bootstrap').set('Host', '127.0.0.1:15300').expect(200)
  189. const response = await request(runtime.app.callback())
  190. .get('/Users/samien/.hermes/images/照片.png')
  191. .set('Host', '127.0.0.1:15300').set('Cookie', cookieHeader(bootstrap)).expect(200)
  192. expect(response.body.toString()).toBe('image bytes')
  193. await request(runtime.app.callback())
  194. .get('/Users/samien/.hermes/images/../state.db')
  195. .set('Host', '127.0.0.1:15300').set('Cookie', cookieHeader(bootstrap)).expect(404)
  196. })
  197. it('bootstraps sequentially without exposing the upstream address', async () => {
  198. const records: RecordedRequest[] = []
  199. const runtime = createApplication({ config: makeConfig(), fetchImpl: fakeGateway(records) })
  200. runtimes.push(runtime)
  201. const response = await request(runtime.app.callback())
  202. .get('/api/app/bootstrap')
  203. .set('Host', '127.0.0.1:15300')
  204. .expect(200)
  205. expect(records.map((entry) => entry.path)).toEqual([
  206. '/api/status', '/api/auth/me', '/api/status',
  207. '/api/profiles',
  208. ])
  209. expect(response.body).toMatchObject({
  210. authRequired: true,
  211. authenticated: true,
  212. user: { username: 'test-admin', role: 'admin' },
  213. profiles: [{ name: 'default', agentName: '竹儿' }],
  214. groupUploadsEnabled: true,
  215. upstreamReady: true,
  216. })
  217. expect(response.body.csrfToken).toEqual(expect.any(String))
  218. expect(response.body.status).toEqual({
  219. state: 'unknown',
  220. gatewayRunning: false,
  221. })
  222. expect(JSON.stringify(response.body)).not.toContain('9119')
  223. expect(response.headers['content-security-policy']).toContain("default-src 'self'")
  224. })
  225. it('refreshes profiles from Hermes Bot names and ignores legacy plugin names', async () => {
  226. const records: RecordedRequest[] = []
  227. const runtime = createApplication({ config: makeConfig(), fetchImpl: fakeGateway(records) })
  228. runtimes.push(runtime)
  229. const response = await request(runtime.app.callback())
  230. .get('/api/app/profiles')
  231. .set('Host', '127.0.0.1:15300')
  232. .expect(200)
  233. expect(records.map(entry => entry.path)).toEqual([
  234. '/api/status', '/api/auth/me', '/api/profiles',
  235. ])
  236. expect(response.body.profiles).toEqual([
  237. { name: 'default', is_default: true, agentName: '竹儿', display_name: '竹儿', description: '竹儿' },
  238. ])
  239. expect(JSON.stringify(response.body)).not.toContain('旧插件名称')
  240. })
  241. it('omits opener isolation on plaintext LAN origins but keeps it on loopback', async () => {
  242. const runtime = createApplication({ config: makeConfig(), fetchImpl: fakeGateway([]) })
  243. runtimes.push(runtime)
  244. const lan = await request(runtime.app.callback())
  245. .get('/healthz')
  246. .set('Host', '192.168.153.155:15300')
  247. .expect(200)
  248. expect(lan.headers['cross-origin-opener-policy']).toBeUndefined()
  249. const loopback = await request(runtime.app.callback())
  250. .get('/healthz')
  251. .set('Host', '127.0.0.1:15300')
  252. .expect(200)
  253. expect(loopback.headers['cross-origin-opener-policy']).toBe('same-origin')
  254. })
  255. it('requires exact Origin and CSRF on local login without forwarding credentials upstream', async () => {
  256. const records: RecordedRequest[] = []
  257. const runtime = createUnauthenticatedApplication({ config: makeConfig(), fetchImpl: fakeGateway(records) })
  258. runtimes.push(runtime)
  259. const bootstrap = await request(runtime.app.callback())
  260. .get('/api/app/bootstrap')
  261. .set('Host', '127.0.0.1:15300')
  262. .expect(200)
  263. const cookies = cookieHeader(bootstrap)
  264. await request(runtime.app.callback())
  265. .post('/api/app/setup')
  266. .set('Host', '127.0.0.1:15300')
  267. .set('Cookie', cookies)
  268. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  269. .send({ username: 'owner', password: 'fixture-password' })
  270. .expect(403)
  271. records.length = 0
  272. const response = await request(runtime.app.callback())
  273. .post('/api/app/setup')
  274. .set('Host', '127.0.0.1:15300')
  275. .set('Origin', 'http://127.0.0.1:15300')
  276. .set('Cookie', cookies)
  277. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  278. .send({ username: 'owner', password: 'fixture-password' })
  279. .expect(200)
  280. expect(records.every(record => record.method === 'GET')).toBe(true)
  281. expect(records.some(record => record.path === '/auth/password-login')).toBe(false)
  282. expect(JSON.stringify(records)).not.toContain('fixture-password')
  283. expect(response.body.authenticated).toBe(true)
  284. expect(response.body.user).toMatchObject({ username: 'owner', role: 'admin', mustChangePassword: false })
  285. expect(response.body.profiles).toHaveLength(1)
  286. expect(JSON.stringify(response.body)).not.toContain('passwordHash')
  287. })
  288. it('keeps unknown API routes out of the SPA fallback', async () => {
  289. const runtime = createApplication({ config: makeConfig(), fetchImpl: fakeGateway([]) })
  290. runtimes.push(runtime)
  291. const response = await request(runtime.app.callback())
  292. .get('/api/anything')
  293. .set('Host', '127.0.0.1:15300')
  294. .expect(404)
  295. expect(response.body.code).toBe('not_found')
  296. })
  297. it('reuses a valid CSRF token across tabs instead of invalidating the first tab', async () => {
  298. const runtime = createApplication({ config: makeConfig(), fetchImpl: fakeGateway([]) })
  299. runtimes.push(runtime)
  300. const first = await request(runtime.app.callback())
  301. .get('/api/app/bootstrap')
  302. .set('Host', '127.0.0.1:15300')
  303. .expect(200)
  304. const second = await request(runtime.app.callback())
  305. .get('/api/app/bootstrap')
  306. .set('Host', '127.0.0.1:15300')
  307. .set('Cookie', cookieHeader(first))
  308. .expect(200)
  309. expect(second.body.csrfToken).toBe(first.body.csrfToken)
  310. })
  311. it('refuses anonymous group uploads before reading a multipart body', async () => {
  312. const fetchImpl = (async (input: string | URL | Request) => {
  313. const url = new URL(input instanceof Request ? input.url : String(input))
  314. if (url.pathname === '/api/status') return jsonResponse({ auth_required: true })
  315. if (url.pathname === '/api/auth/me') return jsonResponse({ detail: 'Unauthorized' }, { status: 401 })
  316. return jsonResponse({ profiles: [] })
  317. }) as typeof fetch
  318. const runtime = createUnauthenticatedApplication({ config: makeConfig(), fetchImpl })
  319. runtimes.push(runtime)
  320. const bootstrap = await request(runtime.app.callback())
  321. .get('/api/app/bootstrap')
  322. .set('Host', '127.0.0.1:15300')
  323. .expect(200)
  324. await request(runtime.app.callback())
  325. .post('/api/app/group-uploads')
  326. .set('Host', '127.0.0.1:15300')
  327. .set('Origin', 'http://127.0.0.1:15300')
  328. .set('Cookie', cookieHeader(bootstrap))
  329. .set('X-CSRF-Token', bootstrap.body.csrfToken)
  330. .attach('files', Buffer.from('hello'), { filename: 'hello.txt', contentType: 'text/plain' })
  331. .expect(401)
  332. })
  333. it('forces active file content to download instead of executing on the 15300 origin', async () => {
  334. const fetchImpl = (async (input: string | URL | Request) => {
  335. const path = new URL(input instanceof Request ? input.url : String(input)).pathname
  336. if (path === '/api/status') return jsonResponse({ auth_required: true })
  337. if (path === '/api/auth/me') return jsonResponse({ user_id: 'service' })
  338. return new Response('<script>window.pwned=true</script>', {
  339. status: 200,
  340. headers: { 'content-type': 'text/html; charset=utf-8' },
  341. })
  342. }) as typeof fetch
  343. const runtime = createApplication({ config: makeConfig(), fetchImpl })
  344. runtimes.push(runtime)
  345. const file = join(runtime.config.home, 'unsafe.html')
  346. writeFileSync(file, '<script>window.pwned=true</script>')
  347. runtime.workspace.put('test-admin','file','1',{id:'1',name:'unsafe.html',path:file,mimeType:'text/html',size:37,sender:'agent',createdAt:Date.now()})
  348. const response = await request(runtime.app.callback())
  349. .get('/api/app/files/1/preview')
  350. .set('Host', '127.0.0.1:15300')
  351. .expect(200)
  352. expect(response.headers['content-type']).toMatch(/^application\/octet-stream/)
  353. expect(response.headers['content-disposition']).toContain('attachment')
  354. })
  355. })
  356. it.each([true,false])('enforces administrator access for transfer settings and session sync (admin=%s)',async admin=>{
  357. const runtime=(admin?createApplication:createUserAuthenticatedApplication)({config:makeConfig(),fetchImpl:fakeGateway([])});runtimes.push(runtime)
  358. const callback=runtime.app.callback(),bootstrap=await request(callback).get('/api/app/bootstrap?csrfOnly=1').set('Host','127.0.0.1:15300').expect(200)
  359. const mutation=(path:string,method:'post'|'put',body:unknown)=>request(callback)[method](path).set('Host','127.0.0.1:15300').set('Origin','http://127.0.0.1:15300').set('Cookie',cookieHeader(bootstrap)).set('X-CSRF-Token',bootstrap.body.csrfToken).send(body as any)
  360. await request(callback).get('/api/app/admin/openviking/session-sync').set('Host','127.0.0.1:15300').expect(admin?200:403)
  361. await mutation('/api/app/admin/openviking/session-sync/retry','post',{}).expect(admin?200:403)
  362. await mutation('/api/app/settings/host-tools','put',{fileTransferMaxMiB:100}).expect(admin?200:403)
  363. if(admin){
  364. await mutation('/api/app/settings/host-tools','put',{cloud:false}).expect(200)
  365. const saved=await request(callback).get('/api/app/settings/host-tools').set('Host','127.0.0.1:15300').expect(200)
  366. expect(saved.body.fileTransferMaxMiB).toBe(100)
  367. await mutation('/api/app/settings/host-tools','put',{fileTransferMaxMiB:101}).expect(400)
  368. }
  369. })