hermesMediaRoutes.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. // @vitest-environment node
  2. import { mkdtempSync, rmSync } from 'node:fs'
  3. import { tmpdir } from 'node:os'
  4. import { join } from 'node:path'
  5. import request from 'supertest'
  6. import { afterEach, describe, expect, it } from 'vitest'
  7. import { createApplication, type ApplicationRuntime } from '../../src/server/app.js'
  8. import type { ServerConfig } from '../../src/server/config.js'
  9. import { createAuthenticatedApplication } from './authenticatedApplication.js'
  10. const HOST = '127.0.0.1:15300'
  11. const IMAGE_NAME = 'openai_codex_gpt-image-2-high_20260902_194820_1d225f08.png'
  12. const IMAGE = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jR5kAAAAASUVORK5CYII=', 'base64')
  13. const homes: string[] = []
  14. const runtimes: ApplicationRuntime[] = []
  15. afterEach(() => {
  16. for (const runtime of runtimes.splice(0)) runtime.close()
  17. for (const home of homes.splice(0)) rmSync(home, { recursive: true, force: true })
  18. })
  19. interface UpstreamCall {
  20. url: URL
  21. method: string
  22. headers: Headers
  23. }
  24. function config(): ServerConfig {
  25. const home = mkdtempSync(join(tmpdir(), 'yaoyao-hermes-media-'))
  26. homes.push(home)
  27. return {
  28. host: '127.0.0.1', port: 15300,
  29. upstream: new URL('http://10.10.1.200:9119'),
  30. upstreamUsername: 'fixture-service', upstreamPassword: 'fixture-password',
  31. allowedHosts: new Set(), home,
  32. mediaRoot: home, attachmentsRoot: home, imagesRoot: home,
  33. mediaOwner: 'web-host-owner',
  34. allowInsecureLan: false, insecureLan: false, production: false,
  35. }
  36. }
  37. function gateway(response: () => Response = () => new Response(IMAGE, {
  38. headers: { 'content-type': 'image/png', 'content-disposition': `attachment; filename="${IMAGE_NAME}"` },
  39. })) {
  40. const calls: UpstreamCall[] = []
  41. const fetchImpl = (async (input: string | URL | Request, init?: RequestInit) => {
  42. const url = new URL(input instanceof Request ? input.url : String(input))
  43. calls.push({ url, method: init?.method ?? 'GET', headers: new Headers(init?.headers) })
  44. if (url.pathname === '/api/status') return Response.json({ auth_required: true }, {
  45. headers: { 'set-cookie': 'hermes_service=fixture-service-cookie; Path=/; HttpOnly' },
  46. })
  47. if (url.pathname === '/api/auth/me') return Response.json({ user_id: 'fixture-service' })
  48. if (url.pathname === '/api/auth/providers') return Response.json({ providers: [{ name: 'basic', supports_password: true }] })
  49. if (url.pathname === '/auth/password-login') return Response.json({ ok: true }, {
  50. headers: { 'set-cookie': 'hermes_service=fixture-service-cookie; Path=/; HttpOnly' },
  51. })
  52. if (url.pathname === '/api/files/download') return response()
  53. return Response.json({ error: 'Unexpected upstream route' }, { status: 404 })
  54. }) as typeof fetch
  55. return { calls, fetchImpl, downloads: () => calls.filter(call => call.url.pathname === '/api/files/download') }
  56. }
  57. function runtimeFor(fixture: ReturnType<typeof gateway>, authenticated = true): ApplicationRuntime {
  58. const runtime = (authenticated ? createAuthenticatedApplication : createApplication)({
  59. config: config(), fetchImpl: fixture.fetchImpl,
  60. })
  61. runtimes.push(runtime)
  62. return runtime
  63. }
  64. function bodyBytes(response: request.Response): Buffer {
  65. return Buffer.isBuffer(response.body) ? response.body : Buffer.from(response.text ?? '')
  66. }
  67. describe('historical Hermes media routes', () => {
  68. it.each([
  69. '/Users/samien/.hermes/workspace/gpt-6-astra-report.md',
  70. '/Users/samien/.hermes/profiles/yaoer/workspace/详细 文档.md',
  71. ])('serves generated workspace documents for preview and download: %s', async path => {
  72. const document = '# GPT-6\n\n文档正文'
  73. const fixture = gateway(() => new Response(document, {
  74. headers: { 'content-type': 'text/markdown', 'content-disposition': 'attachment; filename="report.md"' },
  75. }))
  76. const runtime = runtimeFor(fixture)
  77. const response = await request(runtime.app.callback()).get(encodeURI(path)).set('Host', HOST).expect(200)
  78. expect(response.text).toBe(document)
  79. expect(response.headers['content-type']).toMatch(/^text\/markdown/)
  80. expect(response.headers['content-disposition']).toBeUndefined()
  81. expect(response.headers['cache-control']).toContain('private, no-store')
  82. expect([...fixture.downloads()[0]!.url.searchParams]).toEqual([['path', path]])
  83. })
  84. it.each([
  85. `/Users/samien/.hermes/cache/images/${IMAGE_NAME}`,
  86. `/Users/samien/.hermes/profiles/yaoer/cache/images/${IMAGE_NAME}`,
  87. ])('serves the original generated-image URL through the remote Hermes service: %s', async path => {
  88. const fixture = gateway()
  89. const runtime = runtimeFor(fixture)
  90. const response = await request(runtime.app.callback()).get(path)
  91. .set('Host', HOST).set('Cookie', 'browser_only=must-not-forward').expect(200)
  92. expect(bodyBytes(response)).toEqual(IMAGE)
  93. expect(response.headers['content-type']).toMatch(/^image\/png/)
  94. expect(response.headers['content-disposition'] ?? '').not.toMatch(/^attachment/i)
  95. expect(response.headers['cache-control']).toContain('private')
  96. expect(response.headers['cache-control']).toContain('no-store')
  97. expect(response.headers['set-cookie']).toBeUndefined()
  98. expect(fixture.downloads()).toHaveLength(1)
  99. const download = fixture.downloads()[0]!
  100. expect(download.url.origin).toBe('http://10.10.1.200:9119')
  101. expect([...download.url.searchParams]).toEqual([['path', path]])
  102. expect(download.method).toBe('GET')
  103. expect(download.headers.get('cookie')).toContain('hermes_service=fixture-service-cookie')
  104. expect(download.headers.get('cookie')).not.toContain('browser_only')
  105. })
  106. it('decodes nested Chinese filenames once and ignores browser query overrides', async () => {
  107. const fixture = gateway()
  108. const runtime = runtimeFor(fixture)
  109. const path = '/Users/远端用户/.hermes/profiles/yaoer/cache/images/三视图/角色 图.png'
  110. const encodedPath = path.split('/').map(encodeURIComponent).join('/')
  111. await request(runtime.app.callback())
  112. .get(`${encodedPath}?path=%2Fetc%2Fpasswd&profile=forged&token=browser-secret`)
  113. .set('Host', HOST).expect(200)
  114. expect([...fixture.downloads()[0]!.url.searchParams]).toEqual([['path', path]])
  115. })
  116. it.each(['images', 'screenshots', 'attachments'])('supports the profile %s media directory', async directory => {
  117. const fixture = gateway()
  118. const runtime = runtimeFor(fixture)
  119. const path = `/Users/remote/.hermes/profiles/yaoer/${directory}/nested/result.png`
  120. await request(runtime.app.callback()).get(path).set('Host', HOST).expect(200)
  121. expect(fixture.downloads()[0]!.url.searchParams.get('path')).toBe(path)
  122. })
  123. it('preserves range requests and partial image responses', async () => {
  124. const partial = IMAGE.subarray(2, 8)
  125. const fixture = gateway(() => new Response(partial, {
  126. status: 206,
  127. headers: {
  128. 'content-type': 'image/png', 'content-disposition': 'attachment; filename="result.png"',
  129. 'accept-ranges': 'bytes', 'content-range': `bytes 2-7/${IMAGE.length}`, 'content-length': '6',
  130. },
  131. }))
  132. const runtime = runtimeFor(fixture)
  133. const response = await request(runtime.app.callback())
  134. .get('/Users/samien/.hermes/profiles/yaoer/cache/images/result.png')
  135. .set('Host', HOST).set('Range', 'bytes=2-7').expect(206)
  136. expect(bodyBytes(response)).toEqual(partial)
  137. expect(fixture.downloads()[0]!.headers.get('range')).toBe('bytes=2-7')
  138. expect(response.headers['content-range']).toBe(`bytes 2-7/${IMAGE.length}`)
  139. expect(response.headers['accept-ranges']).toBe('bytes')
  140. expect(response.headers['content-disposition'] ?? '').not.toMatch(/^attachment/i)
  141. })
  142. it.each([
  143. '/Users/samien/.hermes/profiles/yaoer/cache/images/result.png',
  144. '/Users/samien/.hermes/workspace/report.md',
  145. ])('requires a local login before contacting Hermes: %s', async path => {
  146. const fixture = gateway()
  147. const runtime = runtimeFor(fixture, false)
  148. await request(runtime.app.callback())
  149. .get(path)
  150. .set('Host', HOST).expect(401)
  151. expect(fixture.calls).toHaveLength(0)
  152. })
  153. it.each([401, 403, 404])('preserves upstream %s without a broader file-read fallback', async status => {
  154. const fixture = gateway(() => Response.json({ detail: `upstream-${status}` }, { status }))
  155. const runtime = runtimeFor(fixture)
  156. const response = await request(runtime.app.callback())
  157. .get('/Users/samien/.hermes/profiles/yaoer/cache/images/result.png')
  158. .set('Host', HOST).expect(status)
  159. expect(response.body).toEqual({ detail: `upstream-${status}` })
  160. expect(fixture.downloads().length).toBeGreaterThan(0)
  161. expect(fixture.calls.some(call => call.url.pathname === '/api/fs/read-data-url' || call.url.pathname === '/api/media')).toBe(false)
  162. })
  163. it('keeps active content as an attachment even beneath a media directory', async () => {
  164. const fixture = gateway(() => new Response('<svg xmlns="http://www.w3.org/2000/svg"/>', {
  165. headers: { 'content-type': 'image/svg+xml', 'content-disposition': 'inline; filename="result.svg"' },
  166. }))
  167. const runtime = runtimeFor(fixture)
  168. const response = await request(runtime.app.callback())
  169. .get('/Users/samien/.hermes/profiles/yaoer/cache/images/result.svg')
  170. .set('Host', HOST).expect(200)
  171. expect(response.headers['content-type']).toMatch(/^application\/octet-stream/)
  172. expect(response.headers['content-disposition']).toMatch(/^attachment/i)
  173. expect(response.headers['cache-control']).toContain('no-store')
  174. })
  175. it.each([
  176. '/Users/samien/.hermes/workspace/nested%2F..%2Fconfig.yaml',
  177. '/Users/samien/.hermes/workspace/result%5C.md',
  178. '/Users/samien/.hermes/workspace/result%00.md',
  179. '/Users/samien/.hermes/profiles/yaoer/config/result.png',
  180. '/Users/samien/.hermes/profiles/yaoer/cache/images/nested%2F..%2Fresult.png',
  181. '/Users/samien/.hermes/profiles/yaoer/cache/images/result%5C.png',
  182. '/Users/samien/.hermes/profiles/yaoer/cache/images/result%00.png',
  183. '/Users/samien/.hermes/profiles/yaoer%2Fother/cache/images/result.png',
  184. '/Users/samien%2Fother/.hermes/cache/images/result.png',
  185. ])('rejects unsupported directories and invalid decoded path segments: %s', async path => {
  186. const fixture = gateway()
  187. const runtime = runtimeFor(fixture)
  188. const response = await request(runtime.app.callback()).get(path).set('Host', HOST)
  189. expect([400, 404]).toContain(response.status)
  190. expect(fixture.calls).toHaveLength(0)
  191. })
  192. })