host-manager.test.mjs 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. import {test} from 'node:test'
  2. import assert from 'node:assert/strict'
  3. import {mkdtemp,readFile,writeFile,stat,rm} from 'node:fs/promises'
  4. import {tmpdir} from 'node:os'
  5. import {join} from 'node:path'
  6. import {createServer} from 'node:http'
  7. import {randomUUID,randomBytes,createCipheriv,createDecipheriv} from 'node:crypto'
  8. import {DesktopHostManager} from './host-manager.mjs'
  9. import {parseDesktopHostConfiguration} from './host-config.mjs'
  10. const sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms))
  11. test('desktop host configuration validation mirrors the runner rules',()=>{
  12. const base={protocol:1,serverURL:'https://yaoyao.example.com',hostId:randomUUID(),token:randomBytes(32).toString('base64url')}
  13. assert.deepEqual(parseDesktopHostConfiguration(base),{...base,allowInsecureLan:false})
  14. assert.deepEqual(parseDesktopHostConfiguration({...base,serverURL:'http://127.0.0.1:15300'}).serverURL,'http://127.0.0.1:15300')
  15. assert.throws(()=>parseDesktopHostConfiguration({...base,protocol:2}),/协议不兼容/)
  16. assert.throws(()=>parseDesktopHostConfiguration({...base,serverURL:'http://192.168.1.4:15300'}),/HTTPS/)
  17. assert.equal(parseDesktopHostConfiguration({...base,serverURL:'http://192.168.1.4:15300',allowInsecureLan:true}).allowInsecureLan,true)
  18. assert.throws(()=>parseDesktopHostConfiguration({...base,serverURL:'https://example.com/path'}),/服务地址/)
  19. assert.throws(()=>parseDesktopHostConfiguration({...base,hostId:'not-a-uuid'}),/主机编号/)
  20. assert.throws(()=>parseDesktopHostConfiguration({...base,token:'short'}),/主机凭据/)
  21. })
  22. async function fixture(config){
  23. const home=await mkdtemp(join(tmpdir(),'yaoyao-desktop-host-')),key=randomBytes(32)
  24. const encrypt=value=>{const iv=randomBytes(12),cipher=createCipheriv('aes-256-gcm',key,iv);const bytes=Buffer.concat([cipher.update(value),cipher.final()]);return Buffer.concat([iv,cipher.getAuthTag(),bytes])}
  25. const decrypt=bytes=>{const cipher=createDecipheriv('aes-256-gcm',key,bytes.subarray(0,12));cipher.setAuthTag(bytes.subarray(12,28));return Buffer.concat([cipher.update(bytes.subarray(28)),cipher.final()]).toString()}
  26. const cores=[],handled=[]
  27. const manager=new DesktopHostManager({home,root:'/app',dataRoot:home,
  28. encrypt,decrypt,
  29. createCore:()=>{const core={id:randomUUID(),closed:false,results:[],exchanges:0,
  30. info(){core.exchanges++;return {id:core.id,name:'测试 Mac',platform:'darwin',screen:true,accessibility:true,approved:[]}},
  31. takeResults(){return core.results.splice(0,core.results.length)},
  32. async handle(commands){handled.push(...commands??[])},
  33. async revoke(){core.id=randomUUID()},
  34. async close(){core.closed=true}}
  35. cores.push(core);return core}})
  36. const configPath=join(home,'desktop-host.json')
  37. if(config)await writeFile(configPath,JSON.stringify(config))
  38. return {manager,home,configPath,cores,handled}
  39. }
  40. test('imports an encrypted config, exchanges with the paired server and stops on revocation',async()=>{
  41. const token=randomBytes(32).toString('base64url'),hostId=randomUUID()
  42. const exchanges=[]
  43. const server=createServer((req,res)=>{
  44. if(!req.url.includes(`/api/desktop-host/v1/${hostId}/exchange`)){res.statusCode=404;res.end();return}
  45. if(req.headers.authorization!==`Bearer ${token}`||req.headers['x-desktop-host-protocol']!=='1'){res.statusCode=403;res.end(JSON.stringify({error:'unauthorized'}));return}
  46. let body='';req.on('data',chunk=>{body+=chunk});req.on('end',()=>{
  47. exchanges.push(JSON.parse(body))
  48. res.setHeader('content-type','application/json')
  49. res.end(JSON.stringify(exchanges.length===1?{commands:[{id:randomUUID(),deadline:Date.now()+30000,mode:'local',owner:'a'.repeat(64),resource:'local',profile:'persistent',operation:'open'}]}:{commands:[]}))
  50. })
  51. })
  52. await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve))
  53. const {manager,home,configPath,cores,handled}=await fixture({protocol:1,serverURL:`http://127.0.0.1:${server.address().port}`,hostId,token})
  54. try{
  55. await manager.importFile(configPath)
  56. const mode=await stat(join(home,'desktop-host.enc'))
  57. assert.equal(mode.mode&0o077,0)
  58. await sleep(1500)
  59. assert.ok(cores.length>=1)
  60. assert.equal(cores[0].closed,false)
  61. assert.equal(exchanges.length>=2,true)
  62. assert.equal(exchanges[0].host.name,'测试 Mac')
  63. assert.equal(handled.length,1)
  64. assert.equal(handled[0].operation,'open')
  65. assert.match(manager.state,/已连接/)
  66. await manager.forget()
  67. assert.equal(cores[0].closed,true)
  68. assert.equal(manager.state,'未配置桌面主机')
  69. await assert.rejects(()=>readFile(join(home,'desktop-host.enc')),{code:'ENOENT'})
  70. }finally{
  71. await manager.stop().catch(()=>{})
  72. server.close();server.closeAllConnections?.()
  73. }
  74. })
  75. test('a revoked token stops the loop with a clear state instead of retrying',async()=>{
  76. const token=randomBytes(32).toString('base64url')
  77. let requests=0
  78. const server=createServer((req,res)=>{requests++;res.statusCode=403;res.end(JSON.stringify({error:'revoked'}))})
  79. await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve))
  80. const {manager,configPath,cores}=await fixture({protocol:1,serverURL:`http://127.0.0.1:${server.address().port}`,hostId:randomUUID(),token})
  81. try{
  82. await manager.importFile(configPath)
  83. await sleep(1200)
  84. assert.match(manager.state,/授权已失效/)
  85. assert.equal(cores[0].closed,true)
  86. const settled=requests
  87. await sleep(1200)
  88. assert.equal(requests,settled)
  89. }finally{
  90. await manager.stop().catch(()=>{})
  91. server.close();server.closeAllConnections?.()
  92. }
  93. })
  94. test('network failures back off but keep retrying',async()=>{
  95. const token=randomBytes(32).toString('base64url')
  96. const {manager,home,configPath,cores}=await fixture({protocol:1,serverURL:'http://127.0.0.1:1',hostId:randomUUID(),token})
  97. try{
  98. await manager.importFile(configPath)
  99. await sleep(900)
  100. assert.match(manager.state,/正在重试/)
  101. assert.equal(cores[0].closed,false)
  102. await manager.stop()
  103. assert.equal(cores[0].closed,true)
  104. }finally{
  105. await rm(home,{recursive:true,force:true})
  106. }
  107. })