upstream.test.ts 5.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import { describe, expect, it, vi } from 'vitest'
  2. import { CookieJar, UpstreamClient } from '../../src/server/upstream.js'
  3. import type { UpstreamRequestOptions } from '../../src/server/upstream.js'
  4. describe('upstream request boundary', () => {
  5. it('rejects a path that URL normalization would escape', async () => {
  6. const fetchImpl = vi.fn<typeof fetch>()
  7. const client = new UpstreamClient(new URL('http://127.0.0.1:9119'), fetchImpl)
  8. await expect(client.request('/api/sessions/..', new CookieJar())).rejects.toThrow(/normalization/i)
  9. expect(fetchImpl).not.toHaveBeenCalled()
  10. })
  11. it('derives proxy scheme from public 15300 TLS and forwards only the trusted peer IP', async () => {
  12. let headers = new Headers()
  13. const fetchImpl = vi.fn<typeof fetch>(async (_input, init) => {
  14. headers = new Headers(init?.headers)
  15. return new Response('{}', {
  16. status: 200,
  17. headers: { 'content-type': 'application/json', 'set-cookie': 'session=test; Path=/; HttpOnly; SameSite=Lax' },
  18. })
  19. })
  20. const jar = new CookieJar()
  21. const client = new UpstreamClient(new URL('http://127.0.0.1:9119'), fetchImpl, true)
  22. await client.request('/api/status', jar, { clientAddress: '::ffff:192.168.1.22' })
  23. expect(headers.get('x-forwarded-proto')).toBe('https')
  24. expect(headers.get('x-forwarded-for')).toBe('192.168.1.22')
  25. expect(jar.browserCookies[0]).toContain('Secure')
  26. expect(jar.browserCookies[0]).not.toMatch(/Domain=/i)
  27. })
  28. })
  29. it.each([
  30. {path:'/api/config', options:{search:new URLSearchParams({profile:'yaoer',token:'private-query'})}, stage:'Profile「yaoer」读取配置', seconds:30},
  31. {path:'/api/plugins/yaoyao-bot-bridge/capabilities', options:{search:new URLSearchParams({profile:'default'})}, stage:'Profile「default」检查工具桥', seconds:30},
  32. {path:'/api/plugins/yaoyao-bot-bridge/bind', options:{method:'POST',body:{profile:'yaoer',token:'private-bridge-token'}}, stage:'Profile「yaoer」绑定工具桥', seconds:60},
  33. {path:'/api/config', options:{search:new URLSearchParams({profile:'invalid\nprivate-value'})}, stage:'读取配置', seconds:30},
  34. ] satisfies Array<{path:string;options:UpstreamRequestOptions;stage:string;seconds:number}>)('identifies a timed-out $path without exposing request secrets',async({path,options,stage,seconds})=>{
  35. vi.useFakeTimers()
  36. const fetchImpl=vi.fn<typeof fetch>((_url,init)=>new Promise((_resolve,reject)=>{
  37. init?.signal?.addEventListener('abort',()=>reject(new Error('aborted')),{once:true})
  38. }))
  39. const client=new UpstreamClient(new URL('http://127.0.0.1:9119'),fetchImpl)
  40. try{
  41. const failed=expect(client.request(path,new CookieJar(),options)).rejects.toMatchObject({
  42. code:'upstream_unavailable',message:`Hermes 请求超时(${seconds} 秒):${stage}。`,
  43. })
  44. await vi.advanceTimersByTimeAsync(seconds*1000+1);await failed
  45. expect(fetchImpl).toHaveBeenCalledTimes(1)
  46. }finally{client.close();vi.clearAllTimers();vi.useRealTimers()}
  47. })
  48. it.each([
  49. {path:'/api/config',options:{search:new URLSearchParams({profile:'yaoer'})},stage:'读取配置',seconds:30,headersDelay:0},
  50. {path:'/api/plugins/yaoyao-bot-bridge/bind',options:{method:'POST',body:{profile:'yaoer'}},stage:'绑定工具桥',seconds:60,headersDelay:0},
  51. {path:'/api/plugins/yaoyao-bot-bridge/bind',options:{method:'POST',body:{profile:'yaoer'}},stage:'绑定工具桥',seconds:60,headersDelay:40_000},
  52. ] satisfies Array<{path:string;options:UpstreamRequestOptions;stage:string;seconds:number;headersDelay:number}>)('identifies a stalled $path body within its deadline (headers after $headersDelay ms)',async({path,options,stage,seconds,headersDelay})=>{
  53. vi.useFakeTimers()
  54. const cancel=vi.fn(),stream=new ReadableStream({cancel})
  55. const client=new UpstreamClient(new URL('http://127.0.0.1:9119'),vi.fn<typeof fetch>(()=>new Promise(resolve=>setTimeout(()=>resolve(new Response(stream)),headersDelay))))
  56. try{
  57. const failed=expect(client.request(path,new CookieJar(),options)).rejects.toMatchObject({
  58. code:'upstream_unavailable',message:`Hermes 请求超时(${seconds} 秒):Profile「yaoer」${stage}。`,
  59. })
  60. await vi.advanceTimersByTimeAsync(seconds*1000-1)
  61. expect(cancel).not.toHaveBeenCalled()
  62. await vi.advanceTimersByTimeAsync(2);await failed
  63. expect(cancel).toHaveBeenCalledOnce()
  64. }finally{client.close();vi.clearAllTimers();vi.useRealTimers()}
  65. })
  66. it.each(['bind','memory-extract'])('allows a slow Hermes %s request without changing normal request deadlines',async endpoint=>{
  67. vi.useFakeTimers()
  68. const fetchImpl=vi.fn<typeof fetch>(()=>new Promise(done=>setTimeout(()=>done(new Response('{"text":"memory"}')),40000)))
  69. const client=new UpstreamClient(new URL('http://127.0.0.1:9119'),fetchImpl)
  70. try{
  71. const normal=client.request('/api/status',new CookieJar()),rejected=expect(normal).rejects.toThrow('request timed out')
  72. await vi.advanceTimersByTimeAsync(30001);await rejected
  73. const memory=client.request(`/api/plugins/yaoyao-bot-bridge/${endpoint}`,new CookieJar(),{method:'POST',body:{profile:'default',prompt:'facts'}})
  74. await vi.advanceTimersByTimeAsync(40001)
  75. expect(JSON.parse((await memory).body.toString())).toEqual({text:'memory'})
  76. }finally{client.close();vi.clearAllTimers();vi.useRealTimers()}
  77. })