hermesBridge.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. // @vitest-environment node
  2. import {afterEach,beforeEach,expect,it,vi} from 'vitest'
  3. import {mkdtempSync,writeFileSync,rmSync} from 'node:fs'
  4. import {tmpdir} from 'node:os'
  5. import {join,resolve} from 'node:path'
  6. import request from 'supertest'
  7. import {HermesBridgeManager} from '../../src/server/hermesBridge'
  8. import type {ServerConfig} from '../../src/server/config'
  9. import {createAuthenticatedApplication,createUserAuthenticatedApplication} from './authenticatedApplication'
  10. let home:string,config:ServerConfig
  11. beforeEach(()=>{
  12. home=mkdtempSync(join(tmpdir(),'yaoyao-bridge-manager-'));writeFileSync(join(home,'config.yaml'),'{}')
  13. config={host:'127.0.0.1',port:15300,upstream:new URL('http://127.0.0.1:9119'),home,allowedHosts:new Set(),mediaRoot:home,attachmentsRoot:home,imagesRoot:home,mediaOwner:'fixture',allowInsecureLan:false,insecureLan:false,production:false}
  14. })
  15. afterEach(()=>{rmSync(home,{recursive:true,force:true});vi.restoreAllMocks();vi.unstubAllEnvs()})
  16. function fixture(dashboard?:{canRestart:boolean;restart:()=>Promise<void>}){
  17. let disk:any[]=[{profile:'default',exists:true,valid:true,enabled:true,installedVersion:'1.1.0',fingerprint:'old',filesCurrent:false},{profile:'writer',exists:true,valid:true,enabled:false,disabled:true,installedVersion:'1.2.0',fingerprint:'new',filesCurrent:true}]
  18. let live:any={ready:true,native_tools:true,in_process:true,computer_runtime_version:2,plugin_version:'1.1.0',plugin_fingerprint:'old'}
  19. let idle=true,gate:Promise<void>|undefined
  20. const run=vi.fn(async(_python:string,args:string[])=>{
  21. if(args.includes('--check'))return disk.map(row=>JSON.stringify(row)).join('\n')
  22. await gate
  23. const profile=args[args.indexOf('--profile')+1]
  24. disk=disk.map(row=>row.profile===profile?{...row,installedVersion:'1.2.0',fingerprint:'new',filesCurrent:true,enabled:true,disabled:false}:row)
  25. return JSON.stringify({profile,backup:join(home,'backups',profile),disabled:false})
  26. })
  27. const session={invalidateAuthentication:vi.fn(),request:vi.fn(async(path:string)=>({status:200,headers:new Headers(),body:Buffer.from(JSON.stringify(path==='/api/profiles'?{profiles:[{name:'default'},{name:'writer'}]}:live))}))}
  28. const manager=new HermesBridgeManager(config,session,{home,python:process.execPath,assetsRoot:resolve('.'),run,isIdle:()=>idle,dashboard})
  29. return {manager,run,session,setLive:(value:any)=>{live=value},ready:()=>{live={...live,plugin_fingerprint:'new',plugin_version:'1.2.0'}},busy:()=>{idle=false},wait:(value:Promise<void>)=>{gate=value}}
  30. }
  31. it('distinguishes stale files, disabled Profile, pending restart and the actually loaded plugin',async()=>{
  32. const f=fixture()
  33. const before=await f.manager.status();expect(before.profiles.map(p=>p.state)).toEqual(['outdated','disabled'])
  34. expect(before.profiles[1].canInstall).toBe(false)
  35. await expect(f.manager.install({profile:'writer',enable:true})).rejects.toMatchObject({code:'hermes_bridge_host_entry_required'})
  36. await f.manager.install({profile:'default'})
  37. const installed=await f.manager.install({profile:'writer',enable:true})
  38. expect(f.run.mock.calls.at(-2)?.[1]).toContain('--enable')
  39. expect(f.run.mock.calls.at(-2)?.[1]).toContain('--repair-profile-runtime')
  40. expect(installed.status.profiles.find(p=>p.profile==='writer')?.state).toBe('restart-required')
  41. expect(installed.status.profiles.find(p=>p.profile==='default')?.state).toBe('restart-required')
  42. f.ready();expect((await f.manager.status()).profiles.find(p=>p.profile==='writer')?.state).toBe('ready')
  43. expect(installed.backup).toBe(join(home,'backups','writer'))
  44. })
  45. it('restarts the managed Dashboard and verifies every Profile using fresh loaded fingerprints',async()=>{
  46. const dashboard={canRestart:true,restart:vi.fn(async()=>{f.ready()})},f=fixture(dashboard)
  47. await f.manager.install({profile:'default'});await f.manager.install({profile:'writer',enable:true})
  48. expect((await f.manager.status()).dashboard).toMatchObject({managed:true,canRestart:true,restarting:false})
  49. const result=await f.manager.restartDashboard()
  50. expect(dashboard.restart).toHaveBeenCalledTimes(1)
  51. expect(f.session.invalidateAuthentication).toHaveBeenCalledTimes(1)
  52. expect(result.status.profiles.every(p=>p.state==='ready'&&p.canInstall)).toBe(true)
  53. expect(result.status.dashboard).toMatchObject({canRestart:true,restarting:false})
  54. expect(result.message).toContain('工具桥已就绪')
  55. })
  56. it('keeps an unverified bridge pending after restart and releases the lock after failure',async()=>{
  57. const dashboard={canRestart:true,restart:vi.fn(async()=>{})},f=fixture(dashboard)
  58. await f.manager.install({profile:'default'})
  59. const result=await f.manager.restartDashboard()
  60. expect(result.status.profiles[0]!.state).toBe('restart-required')
  61. expect(result.message).toContain('尚未就绪')
  62. dashboard.restart.mockRejectedValueOnce(new Error('private process diagnostics'))
  63. await expect(f.manager.restartDashboard()).rejects.toMatchObject({code:'hermes_dashboard_restart_failed'})
  64. expect(f.manager.dashboardRestarting).toBe(false)
  65. expect(f.manager.idleForUpdate).toBe(true)
  66. expect((await f.manager.status()).dashboard?.canRestart).toBe(true)
  67. })
  68. it('blocks concurrent restart, installation and task admission until verification finishes',async()=>{
  69. let release!:()=>void
  70. const dashboard={canRestart:true,restart:vi.fn(()=>new Promise<void>(done=>{release=done}))},f=fixture(dashboard)
  71. const pending=f.manager.restartDashboard()
  72. expect(f.manager.idleForUpdate).toBe(false)
  73. expect(()=>f.manager.assertDashboardAvailable()).toThrow('正在重启')
  74. expect((await f.manager.status()).dashboard).toMatchObject({managed:true,canRestart:false,restarting:true})
  75. await expect(f.manager.restartDashboard()).rejects.toMatchObject({code:'hermes_dashboard_restarting'})
  76. await expect(f.manager.install({profile:'default'})).rejects.toMatchObject({code:'hermes_dashboard_restarting'})
  77. release();await pending
  78. expect(()=>f.manager.assertDashboardAvailable()).not.toThrow()
  79. expect(dashboard.restart).toHaveBeenCalledTimes(1)
  80. f.busy()
  81. expect((await f.manager.status()).dashboard?.canRestart).toBe(false)
  82. await expect(f.manager.restartDashboard()).rejects.toMatchObject({code:'hermes_bridge_tasks_running'})
  83. })
  84. it('refuses restart during installation and when process ownership is lost after the status check',async()=>{
  85. let release!:()=>void
  86. const dashboard={canRestart:true,restart:vi.fn(async()=>{})},f=fixture(dashboard)
  87. f.wait(new Promise<void>(done=>{release=done}))
  88. const installation=f.manager.install({profile:'default'})
  89. await expect(f.manager.restartDashboard()).rejects.toMatchObject({code:'hermes_bridge_install_busy'})
  90. release();await installation
  91. expect((await f.manager.status()).dashboard?.canRestart).toBe(true)
  92. dashboard.canRestart=false
  93. await expect(f.manager.restartDashboard()).rejects.toMatchObject({code:'hermes_dashboard_restart_unavailable'})
  94. expect(dashboard.restart).not.toHaveBeenCalled()
  95. })
  96. it('does not infer restart permission from local addresses or mounted directories',async()=>{
  97. const dashboard={canRestart:true,restart:vi.fn(async()=>{})},f=fixture()
  98. await expect(f.manager.restartDashboard()).rejects.toMatchObject({code:'hermes_dashboard_restart_unavailable'})
  99. for(const override of [
  100. {upstream:new URL('https://hermes.example')},
  101. {upstream:new URL('http://127.0.0.1:9120')},
  102. {localVmHost:'runner' as const},
  103. {hermesBridgeMount:{home,python:process.execPath}},
  104. ]){
  105. const manager=new HermesBridgeManager({...config,...override},f.session,{home,python:process.execPath,assetsRoot:resolve('.'),run:f.run,dashboard})
  106. expect((await manager.status()).dashboard?.managed).toBe(false)
  107. await expect(manager.restartDashboard()).rejects.toMatchObject({code:'hermes_dashboard_restart_unavailable'})
  108. }
  109. expect(dashboard.restart).not.toHaveBeenCalled()
  110. })
  111. it('requires admin and CSRF for restart, and blocks API and websocket task entry during restart',async()=>{
  112. let release!:()=>void
  113. const dashboard={canRestart:true,restart:vi.fn(()=>new Promise<void>(done=>{release=done}))},f=fixture(dashboard)
  114. const admin=createAuthenticatedApplication({config,hermesBridge:f.manager})
  115. try{
  116. const api=request.agent(admin.app.callback()),host='127.0.0.1:15300',path='/api/app/admin/hermes-bridge/restart'
  117. await api.post(path).set('Host',host).send({}).expect(403)
  118. const csrf=(await api.get('/api/app/bootstrap?csrfOnly=1').set('Host',host).expect(200)).body.csrfToken
  119. const post=(url:string)=>api.post(url).set('Host',host).set('Origin','http://'+host).set('X-CSRF-Token',csrf).send({})
  120. const pending=post(path).expect(200).then(response=>response)
  121. await vi.waitFor(()=>expect(dashboard.restart).toHaveBeenCalledTimes(1))
  122. expect((await post(path).expect(409)).body.code).toBe('hermes_dashboard_restarting')
  123. expect((await post('/api/app/agents').expect(409)).body.code).toBe('hermes_dashboard_restarting')
  124. expect(()=>admin.realtime.broker.command({} as any,'request',{})).toThrow('正在重启')
  125. vi.spyOn(admin.workspaceRuntime,'userActive').mockReturnValue(true)
  126. expect(()=>admin.workspaceRuntime.send('test-admin','unused',{})).toThrow('正在重启')
  127. const owners=vi.spyOn(admin.workspace,'owners');owners.mockClear()
  128. admin.workspaceRoutines.tick();expect(owners).not.toHaveBeenCalled();owners.mockRestore()
  129. release();const response=await pending
  130. expect(response.body.status.dashboard.restarting).toBe(false)
  131. expect(()=>admin.workspaceRuntime.assertCanSubmit()).not.toThrow()
  132. }finally{release?.();admin.close()}
  133. const user=createUserAuthenticatedApplication({config,hermesBridge:f.manager})
  134. try{
  135. const api=request.agent(user.app.callback()),host='127.0.0.1:15300'
  136. const csrf=(await api.get('/api/app/bootstrap?csrfOnly=1').set('Host',host).expect(200)).body.csrfToken
  137. await api.post('/api/app/admin/hermes-bridge/restart').set('Host',host).set('Origin','http://'+host).set('X-CSRF-Token',csrf).send({}).expect(403)
  138. expect(dashboard.restart).toHaveBeenCalledTimes(1)
  139. }finally{user.close()}
  140. })
  141. it('checks runtime activity and already admitted HTTP requests before acquiring the restart lock',async()=>{
  142. vi.stubEnv('HERMES_HOME',home)
  143. const dashboard={canRestart:true,restart:vi.fn(async()=>{})}
  144. const admin=createAuthenticatedApplication({config,dashboardSupervisor:dashboard})
  145. let release!:()=>void,entered=false
  146. const gate=new Promise<void>(done=>{release=done})
  147. admin.app.use(async ctx=>{if(ctx.path==='/restart-admission-fixture'){entered=true;await gate;ctx.body={ok:true}}})
  148. vi.spyOn(admin.upstreamSession,'request').mockImplementation(async()=>({status:200,headers:new Headers(),body:Buffer.from('{"profiles":[]}')}))
  149. try{
  150. const host='127.0.0.1:15300',api=request.agent(admin.app.callback())
  151. const csrf=(await api.get('/api/app/bootstrap?csrfOnly=1').set('Host',host).expect(200)).body.csrfToken
  152. const restart=()=>api.post('/api/app/admin/hermes-bridge/restart').set('Host',host).set('Origin','http://'+host).set('X-CSRF-Token',csrf).send({})
  153. for(const component of [admin.workspaceRuntime,admin.runners,admin.realtime.broker,admin.desktopEnvironments]){
  154. const idle=vi.spyOn(component,'idleForUpdate','get').mockReturnValue(false)
  155. expect((await restart().expect(409)).body.code).toBe('hermes_bridge_tasks_running')
  156. idle.mockRestore()
  157. }
  158. const pending=api.post('/restart-admission-fixture').set('Host',host).send({}).expect(200).then(r=>r)
  159. await vi.waitFor(()=>expect(entered).toBe(true))
  160. expect((await restart().expect(409)).body.code).toBe('hermes_bridge_tasks_running')
  161. expect(dashboard.restart).not.toHaveBeenCalled()
  162. release();await pending
  163. await restart().expect(200)
  164. expect(dashboard.restart).toHaveBeenCalledTimes(1)
  165. }finally{release();admin.close()}
  166. })
  167. it('prevents concurrent installs and rejects path injection, unknown profiles and installation during work',async()=>{
  168. const f=fixture();let release!:()=>void
  169. f.wait(new Promise<void>(done=>{release=done}))
  170. const pending=f.manager.install({profile:'default'})
  171. await vi.waitFor(()=>expect(f.run.mock.calls.some(([,args])=>!args.includes('--check'))).toBe(true))
  172. expect(f.manager.idleForUpdate).toBe(false)
  173. await expect(f.manager.install({profile:'writer'})).rejects.toMatchObject({code:'hermes_bridge_install_busy'})
  174. release();await pending
  175. expect(f.manager.idleForUpdate).toBe(true)
  176. await expect(f.manager.install({profile:'../other'})).rejects.toMatchObject({code:'invalid_bridge_install_request'})
  177. await expect(f.manager.install({profile:'default',home:'/wrong'})).rejects.toMatchObject({code:'invalid_bridge_install_request'})
  178. await expect(f.manager.install({profile:'missing'})).rejects.toMatchObject({code:'hermes_bridge_profile_missing'})
  179. f.busy();await expect(f.manager.install({profile:'default'})).rejects.toMatchObject({code:'hermes_bridge_tasks_running'})
  180. })
  181. it('checks remote Hermes but never invokes the local installer for it',async()=>{
  182. const f=fixture(),run=vi.fn()
  183. const manager=new HermesBridgeManager({...config,upstream:new URL('https://hermes.example')},f.session,{home,python:process.execPath,assetsRoot:resolve('.'),run})
  184. const status=await manager.status();expect(status.local).toBe(false);expect(status.profiles.every(p=>!p.canInstall)).toBe(true)
  185. await expect(manager.install({profile:'default'})).rejects.toMatchObject({code:'hermes_bridge_install_unavailable'})
  186. expect(run).not.toHaveBeenCalled()
  187. })
  188. it('exposes only admin/CSRF-protected management endpoints and returns the verified status after install',async()=>{
  189. const f=fixture(),admin=createAuthenticatedApplication({config,hermesBridge:f.manager})
  190. try{
  191. const api=request.agent(admin.app.callback()),host='127.0.0.1:15300'
  192. await api.get('/api/app/admin/hermes-bridge').set('Host',host).expect(200)
  193. await api.post('/api/app/admin/hermes-bridge/install').set('Host',host).send({profile:'default'}).expect(403)
  194. const csrf=(await api.get('/api/app/bootstrap?csrfOnly=1').set('Host',host).expect(200)).body.csrfToken
  195. const response=await api.post('/api/app/admin/hermes-bridge/install').set('Host',host).set('Origin','http://'+host).set('X-CSRF-Token',csrf).send({profile:'default'}).expect(200)
  196. expect(response.body.status.profiles[0].state).toBe('restart-required')
  197. }finally{admin.close()}
  198. const user=createUserAuthenticatedApplication({config,hermesBridge:f.manager})
  199. try{await request(user.app.callback()).get('/api/app/admin/hermes-bridge').set('Host','127.0.0.1:15300').expect(403)}finally{user.close()}
  200. })
  201. it('does not report an offline Hermes as loaded or expose installer diagnostic secrets',async()=>{
  202. const f=fixture()
  203. await f.manager.install({profile:'default'})
  204. f.session.request.mockRejectedValue(new Error('offline'))
  205. const state=await f.manager.status()
  206. expect(state.profiles[0].state).toBe('unavailable')
  207. expect(state.profiles[0].message).toContain('连接和权限')
  208. f.run.mockRejectedValue(new Error('sensitive diagnostic must stay private'))
  209. await expect(f.manager.install({profile:'default'})).rejects.not.toThrow('sensitive diagnostic')
  210. })
  211. it('uses explicitly mapped Hermes storage and the container interpreter with an external upstream',async()=>{
  212. const f=fixture()
  213. const mapped={...config,localVmHost:'runner' as const,upstream:new URL('http://hermes:9119'),hermesBridgeMount:{home,python:process.execPath}}
  214. const manager=new HermesBridgeManager(mapped,f.session,{assetsRoot:resolve('.'),run:f.run})
  215. expect(manager.home).toBe(home);expect(manager.python).toBe(process.execPath)
  216. const status=await manager.status()
  217. expect(status.mapped).toBe(true);expect(status.local).toBe(true);expect(status.profiles[0].canInstall).toBe(true)
  218. expect(status.message).toContain(home)
  219. await manager.install({profile:'default'})
  220. const call=f.run.mock.calls.find(([,args])=>args.includes('--profile'))!
  221. expect(call[0]).toBe(process.execPath)
  222. expect(call[1]).toContain(home)
  223. expect(call[1].join(' ')).not.toContain('/hermes-agent/venv/')
  224. })