hermesMediaRoutes.test.ts 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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/cache/images/${IMAGE_NAME}`,
  70. `/Users/samien/.hermes/profiles/yaoer/cache/images/${IMAGE_NAME}`,
  71. ])('serves the original generated-image URL through the remote Hermes service: %s', async path => {
  72. const fixture = gateway()
  73. const runtime = runtimeFor(fixture)
  74. const response = await request(runtime.app.callback()).get(path)
  75. .set('Host', HOST).set('Cookie', 'browser_only=must-not-forward').expect(200)
  76. expect(bodyBytes(response)).toEqual(IMAGE)
  77. expect(response.headers['content-type']).toMatch(/^image\/png/)
  78. expect(response.headers['content-disposition'] ?? '').not.toMatch(/^attachment/i)
  79. expect(response.headers['cache-control']).toContain('private')
  80. expect(response.headers['cache-control']).toContain('no-store')
  81. expect(response.headers['set-cookie']).toBeUndefined()
  82. expect(fixture.downloads()).toHaveLength(1)
  83. const download = fixture.downloads()[0]!
  84. expect(download.url.origin).toBe('http://10.10.1.200:9119')
  85. expect([...download.url.searchParams]).toEqual([['path', path]])
  86. expect(download.method).toBe('GET')
  87. expect(download.headers.get('cookie')).toContain('hermes_service=fixture-service-cookie')
  88. expect(download.headers.get('cookie')).not.toContain('browser_only')
  89. })
  90. it('decodes nested Chinese filenames once and ignores browser query overrides', async () => {
  91. const fixture = gateway()
  92. const runtime = runtimeFor(fixture)
  93. const path = '/Users/远端用户/.hermes/profiles/yaoer/cache/images/三视图/角色 图.png'
  94. const encodedPath = path.split('/').map(encodeURIComponent).join('/')
  95. await request(runtime.app.callback())
  96. .get(`${encodedPath}?path=%2Fetc%2Fpasswd&profile=forged&token=browser-secret`)
  97. .set('Host', HOST).expect(200)
  98. expect([...fixture.downloads()[0]!.url.searchParams]).toEqual([['path', path]])
  99. })
  100. it.each(['images', 'screenshots', 'attachments'])('supports the profile %s media directory', async directory => {
  101. const fixture = gateway()
  102. const runtime = runtimeFor(fixture)
  103. const path = `/Users/remote/.hermes/profiles/yaoer/${directory}/nested/result.png`
  104. await request(runtime.app.callback()).get(path).set('Host', HOST).expect(200)
  105. expect(fixture.downloads()[0]!.url.searchParams.get('path')).toBe(path)
  106. })
  107. it('preserves range requests and partial image responses', async () => {
  108. const partial = IMAGE.subarray(2, 8)
  109. const fixture = gateway(() => new Response(partial, {
  110. status: 206,
  111. headers: {
  112. 'content-type': 'image/png', 'content-disposition': 'attachment; filename="result.png"',
  113. 'accept-ranges': 'bytes', 'content-range': `bytes 2-7/${IMAGE.length}`, 'content-length': '6',
  114. },
  115. }))
  116. const runtime = runtimeFor(fixture)
  117. const response = await request(runtime.app.callback())
  118. .get('/Users/samien/.hermes/profiles/yaoer/cache/images/result.png')
  119. .set('Host', HOST).set('Range', 'bytes=2-7').expect(206)
  120. expect(bodyBytes(response)).toEqual(partial)
  121. expect(fixture.downloads()[0]!.headers.get('range')).toBe('bytes=2-7')
  122. expect(response.headers['content-range']).toBe(`bytes 2-7/${IMAGE.length}`)
  123. expect(response.headers['accept-ranges']).toBe('bytes')
  124. expect(response.headers['content-disposition'] ?? '').not.toMatch(/^attachment/i)
  125. })
  126. it('requires a local login before contacting Hermes', async () => {
  127. const fixture = gateway()
  128. const runtime = runtimeFor(fixture, false)
  129. await request(runtime.app.callback())
  130. .get('/Users/samien/.hermes/profiles/yaoer/cache/images/result.png')
  131. .set('Host', HOST).expect(401)
  132. expect(fixture.calls).toHaveLength(0)
  133. })
  134. it.each([401, 403, 404])('preserves upstream %s without a broader file-read fallback', async status => {
  135. const fixture = gateway(() => Response.json({ detail: `upstream-${status}` }, { status }))
  136. const runtime = runtimeFor(fixture)
  137. const response = await request(runtime.app.callback())
  138. .get('/Users/samien/.hermes/profiles/yaoer/cache/images/result.png')
  139. .set('Host', HOST).expect(status)
  140. expect(response.body).toEqual({ detail: `upstream-${status}` })
  141. expect(fixture.downloads().length).toBeGreaterThan(0)
  142. expect(fixture.calls.some(call => call.url.pathname === '/api/fs/read-data-url' || call.url.pathname === '/api/media')).toBe(false)
  143. })
  144. it('keeps active content as an attachment even beneath a media directory', async () => {
  145. const fixture = gateway(() => new Response('<svg xmlns="http://www.w3.org/2000/svg"/>', {
  146. headers: { 'content-type': 'image/svg+xml', 'content-disposition': 'inline; filename="result.svg"' },
  147. }))
  148. const runtime = runtimeFor(fixture)
  149. const response = await request(runtime.app.callback())
  150. .get('/Users/samien/.hermes/profiles/yaoer/cache/images/result.svg')
  151. .set('Host', HOST).expect(200)
  152. expect(response.headers['content-type']).toMatch(/^application\/octet-stream/)
  153. expect(response.headers['content-disposition']).toMatch(/^attachment/i)
  154. expect(response.headers['cache-control']).toContain('no-store')
  155. })
  156. it.each([
  157. '/Users/samien/.hermes/profiles/yaoer/config/result.png',
  158. '/Users/samien/.hermes/profiles/yaoer/cache/images/nested%2F..%2Fresult.png',
  159. '/Users/samien/.hermes/profiles/yaoer/cache/images/result%5C.png',
  160. '/Users/samien/.hermes/profiles/yaoer/cache/images/result%00.png',
  161. '/Users/samien/.hermes/profiles/yaoer%2Fother/cache/images/result.png',
  162. '/Users/samien%2Fother/.hermes/cache/images/result.png',
  163. ])('rejects unsupported directories and invalid decoded path segments: %s', async path => {
  164. const fixture = gateway()
  165. const runtime = runtimeFor(fixture)
  166. const response = await request(runtime.app.callback()).get(path).set('Host', HOST)
  167. expect([400, 404]).toContain(response.status)
  168. expect(fixture.calls).toHaveLength(0)
  169. })
  170. })