host-manager.test.mjs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  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 {HostEnvironmentReporter} from './host-environment.mjs'
  9. import {DesktopHostManager} from './host-manager.mjs'
  10. import {parseDesktopHostConfiguration} from './host-config.mjs'
  11. const sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms))
  12. test('computer configuration validation mirrors the runner rules',()=>{
  13. const base={protocol:1,serverURL:'https://yaoyao.example.com',hostId:randomUUID(),token:randomBytes(32).toString('base64url')}
  14. assert.deepEqual(parseDesktopHostConfiguration(base),{...base,allowInsecureLan:false})
  15. assert.deepEqual(parseDesktopHostConfiguration({...base,serverURL:'http://127.0.0.1:15300'}).serverURL,'http://127.0.0.1:15300')
  16. assert.throws(()=>parseDesktopHostConfiguration({...base,protocol:2}),/协议不兼容/)
  17. assert.throws(()=>parseDesktopHostConfiguration({...base,serverURL:'http://192.168.1.4:15300'}),/HTTPS/)
  18. assert.equal(parseDesktopHostConfiguration({...base,serverURL:'http://192.168.1.4:15300',allowInsecureLan:true}).allowInsecureLan,true)
  19. assert.throws(()=>parseDesktopHostConfiguration({...base,serverURL:'https://example.com/path'}),/服务地址/)
  20. assert.throws(()=>parseDesktopHostConfiguration({...base,hostId:'not-a-uuid'}),/电脑编号/)
  21. assert.throws(()=>parseDesktopHostConfiguration({...base,token:'short'}),/电脑凭据/)
  22. })
  23. async function fixture(config){
  24. const home=await mkdtemp(join(tmpdir(),'yaoyao-desktop-host-')),key=randomBytes(32)
  25. 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])}
  26. 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()}
  27. const cores=[],handled=[]
  28. const manager=new DesktopHostManager({home,root:'/app',dataRoot:home,
  29. encrypt,decrypt,
  30. createCore:()=>{const reporter=new HostEnvironmentReporter('/Users/fixture');const core={id:randomUUID(),closed:false,results:[],exchanges:0,
  31. info(){core.exchanges++;return {id:core.id,name:'测试 Mac',platform:'darwin',screen:true,accessibility:true,approved:[],...reporter.fields()}},
  32. acceptCapabilities(capabilities){reporter.accept(capabilities)},
  33. takeResults(){return core.results.splice(0,core.results.length)},
  34. async handle(commands){handled.push(...commands??[])},
  35. async revoke(){core.id=randomUUID()},
  36. async close(){core.closed=true}}
  37. cores.push(core);return core}})
  38. const configPath=join(home,'desktop-host.json')
  39. if(config)await writeFile(configPath,JSON.stringify(config))
  40. return {manager,home,configPath,cores,handled}
  41. }
  42. test('concurrent first logins share one persistent installation identity',async()=>{
  43. const {manager,home}=await fixture()
  44. try{
  45. const managers=Array.from({length:20},()=>new DesktopHostManager(manager.options))
  46. const ids=await Promise.all(managers.map(item=>item.installIdentity()))
  47. assert.equal(new Set(ids).size,1,'one installation must not register as multiple computers')
  48. assert.equal(await readFile(join(home,'desktop-install-id'),'utf8'),ids[0])
  49. await manager.forget()
  50. assert.equal(await new DesktopHostManager(manager.options).installIdentity(),ids[0])
  51. assert.equal((await stat(join(home,'desktop-install-id'))).mode&0o077,0)
  52. }finally{await rm(home,{recursive:true,force:true})}
  53. })
  54. test('a damaged installation identity is not silently replaced by a new computer',async()=>{
  55. const {manager,home}=await fixture()
  56. try{
  57. await writeFile(join(home,'desktop-install-id'),'damaged')
  58. await assert.rejects(()=>manager.installIdentity(),/设备标识/)
  59. assert.equal(await readFile(join(home,'desktop-install-id'),'utf8'),'damaged')
  60. }finally{await rm(home,{recursive:true,force:true})}
  61. })
  62. test('imports an encrypted config, exchanges with the paired server and stops on revocation',async()=>{
  63. const token=randomBytes(32).toString('base64url'),hostId=randomUUID()
  64. const exchanges=[]
  65. const server=createServer((req,res)=>{
  66. if(!req.url.includes(`/api/desktop-host/v1/${hostId}/exchange`)){res.statusCode=404;res.end();return}
  67. if(req.headers.authorization!==`Bearer ${token}`||req.headers['x-desktop-host-protocol']!=='1'){res.statusCode=403;res.end(JSON.stringify({error:'unauthorized'}));return}
  68. let body='';req.on('data',chunk=>{body+=chunk});req.on('end',()=>{
  69. exchanges.push(JSON.parse(body))
  70. res.setHeader('content-type','application/json')
  71. 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:[]}))
  72. })
  73. })
  74. await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve))
  75. const {manager,home,configPath,cores,handled}=await fixture({protocol:1,serverURL:`http://127.0.0.1:${server.address().port}`,hostId,token})
  76. try{
  77. await manager.importFile(configPath)
  78. const mode=await stat(join(home,'desktop-host.enc'))
  79. assert.equal(mode.mode&0o077,0)
  80. await sleep(1500)
  81. assert.ok(cores.length>=1)
  82. assert.equal(cores[0].closed,false)
  83. assert.equal(exchanges.length>=2,true)
  84. assert.equal(exchanges[0].host.name,'测试 Mac')
  85. assert.equal(handled.length,1)
  86. assert.equal(handled[0].operation,'open')
  87. assert.match(manager.state,/已连接/)
  88. await manager.forget()
  89. assert.equal(cores[0].closed,true)
  90. assert.equal(manager.state,'未配置电脑')
  91. await assert.rejects(()=>readFile(join(home,'desktop-host.enc')),{code:'ENOENT'})
  92. }finally{
  93. await manager.stop().catch(()=>{})
  94. server.close();server.closeAllConnections?.()
  95. }
  96. })
  97. test('a revoked token stops the loop with a clear state instead of retrying',async()=>{
  98. const token=randomBytes(32).toString('base64url')
  99. let requests=0
  100. const server=createServer((req,res)=>{requests++;res.statusCode=403;res.end(JSON.stringify({error:'revoked'}))})
  101. await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve))
  102. const {manager,configPath,cores}=await fixture({protocol:1,serverURL:`http://127.0.0.1:${server.address().port}`,hostId:randomUUID(),token})
  103. try{
  104. await manager.importFile(configPath)
  105. await sleep(1200)
  106. assert.match(manager.state,/授权已失效/)
  107. assert.equal(cores[0].closed,true)
  108. const settled=requests
  109. await sleep(1200)
  110. assert.equal(requests,settled)
  111. }finally{
  112. await manager.stop().catch(()=>{})
  113. server.close();server.closeAllConnections?.()
  114. }
  115. })
  116. test('network failures back off but keep retrying',async()=>{
  117. const token=randomBytes(32).toString('base64url')
  118. const {manager,home,configPath,cores}=await fixture({protocol:1,serverURL:'http://127.0.0.1:1',hostId:randomUUID(),token})
  119. try{
  120. await manager.importFile(configPath)
  121. await sleep(900)
  122. assert.match(manager.state,/正在重试/)
  123. assert.equal(cores[0].closed,false)
  124. await manager.stop()
  125. assert.equal(cores[0].closed,true)
  126. }finally{
  127. await rm(home,{recursive:true,force:true})
  128. }
  129. })
  130. test('negotiates metadata and retries in legacy format when the server stops supporting it',async()=>{
  131. const exchanges=[]
  132. const server=createServer((req,res)=>{let body='';req.on('data',chunk=>body+=chunk);req.on('end',()=>{
  133. exchanges.push(JSON.parse(body));res.setHeader('content-type','application/json')
  134. if(exchanges.length===2){res.statusCode=400;res.end(JSON.stringify({error:'older server'}));return}
  135. res.end(JSON.stringify(exchanges.length===1?{commands:[],capabilities:{environmentMetadata:1}}:{commands:[]}))
  136. })})
  137. await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve))
  138. const f=await fixture({protocol:1,serverURL:`http://127.0.0.1:${server.address().port}`,hostId:randomUUID(),token:randomBytes(32).toString('base64url')})
  139. try{
  140. await f.manager.importFile(f.configPath)
  141. clearTimeout(f.manager.timer)
  142. for(let i=0;i<3;i++){await f.manager.cycle();clearTimeout(f.manager.timer)}
  143. assert.equal(exchanges[0].host.environment,undefined)
  144. assert.equal(exchanges[0].host.fileTransferVersion,undefined)
  145. assert.equal(exchanges[1].host.environment.homeDirectory,'/Users/fixture')
  146. assert.equal(exchanges[1].host.fileTransferVersion,1)
  147. assert.equal(exchanges[2].host.environment,undefined)
  148. assert.equal(exchanges[2].host.fileTransferVersion,undefined)
  149. }finally{await f.manager.stop();await new Promise(resolve=>server.close(resolve));await rm(f.home,{recursive:true,force:true})}
  150. })