host-manager.mjs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. import {readFile,writeFile,rename,mkdir,rm,link} from 'node:fs/promises'
  2. import {join} from 'node:path'
  3. import {randomUUID} from 'node:crypto'
  4. import {request as httpRequest} from 'node:http'
  5. import {request as httpsRequest} from 'node:https'
  6. import {parseDesktopHostConfiguration} from './host-config.mjs'
  7. const FATAL = Symbol('desktop-host-fatal')
  8. export function remoteExchange(config,body){return new Promise((resolve,reject)=>{
  9. const url=new URL(`/api/desktop-host/v1/${config.hostId}/exchange`,config.serverURL)
  10. if(!['http:','https:'].includes(url.protocol))return reject(new Error('夭夭服务地址无效'))
  11. const bytes=Buffer.from(JSON.stringify(body)),send=url.protocol==='https'?httpsRequest:httpRequest
  12. const req=send(url,{method:'POST',headers:{Authorization:`Bearer ${config.token}`,'x-desktop-host-protocol':'1','content-type':'application/json','content-length':bytes.length}},res=>{
  13. let size=0;const chunks=[]
  14. res.on('data',chunk=>{size+=chunk.length;if(size>16*1024*1024)res.destroy(new Error('桌面命令超过限制'));else chunks.push(chunk)})
  15. res.on('error',reject)
  16. res.on('end',()=>{try{
  17. if(res.statusCode===401||res.statusCode===403){const error=new Error('电脑授权已失效,请重新登录授权这台电脑');error[FATAL]=true;throw error}
  18. if(res.statusCode===409){const error=new Error('电脑连接协议不兼容,请更新夭夭后重新授权');error[FATAL]=true;throw error}
  19. if(res.statusCode!==200)throw new Error(`电脑未连接(HTTP ${res.statusCode})`)
  20. resolve(JSON.parse(Buffer.concat(chunks).toString()))
  21. }catch(error){reject(error)}})
  22. })
  23. req.on('error',reject)
  24. req.setTimeout(10000,()=>req.destroy(new Error('电脑连接超时')))
  25. req.end(bytes)
  26. })}
  27. /** Remote computer: imports an encrypted pairing config and exchanges
  28. * commands with the paired server. Native-only; no browser IPC. */
  29. export class DesktopHostManager {
  30. constructor(options){
  31. if(typeof options?.createCore!=='function')throw new Error('电脑需要命令执行核心')
  32. this.options=options
  33. this.path=join(options.home,'desktop-host.enc')
  34. this.createCore=options.createCore
  35. this.state='未配置电脑'
  36. this.core=undefined
  37. this.config=undefined
  38. this.timer=undefined
  39. this.backoff=400
  40. this.chain=Promise.resolve()
  41. this.generation=0
  42. }
  43. publish(message){this.state=message;this.options.onState?.(message)}
  44. async installIdentity(){
  45. const path=join(this.options.home,'desktop-install-id')
  46. const readIdentity=async()=>{
  47. const id=(await readFile(path,'utf8')).trim()
  48. if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id))throw new Error('本机设备标识损坏,请恢复原设备标识后重试')
  49. return id
  50. }
  51. try{return await readIdentity()}catch(error){if(error.code!=='ENOENT')throw error}
  52. const id=randomUUID()
  53. await mkdir(this.options.home,{recursive:true,mode:0o700})
  54. const temporary=`${path}.${id}`
  55. try{
  56. // Publish a complete identity without overwriting a concurrent login's ID.
  57. await writeFile(temporary,id,{flag:'wx',mode:0o600})
  58. try{await link(temporary,path);return id}catch(error){if(error.code!=='EEXIST')throw error}
  59. return await readIdentity()
  60. }finally{await rm(temporary,{force:true})}
  61. }
  62. serial(work){const result=this.chain.catch(()=>{}).then(work);this.chain=result;return result}
  63. async read(){
  64. let encrypted
  65. try{encrypted=await readFile(this.path)}catch(error){if(error.code==='ENOENT')return;throw error}
  66. try{return parseDesktopHostConfiguration(JSON.parse(await this.options.decrypt(encrypted)))}
  67. catch{throw new Error('无法解锁电脑配置,请使用原系统账号或重新登录授权')}
  68. }
  69. importFile(path){
  70. const generation=++this.generation
  71. return this.serial(async()=>{
  72. let config
  73. try{config=parseDesktopHostConfiguration(JSON.parse(await readFile(path,'utf8')))}
  74. catch(error){throw error instanceof Error?error:new Error('电脑配置无效,请从夭夭重新下载配置')}
  75. await this.store(config,generation)
  76. })
  77. }
  78. /** Adopt a config obtained in-process (e.g. after a native remote login). */
  79. adopt(value){
  80. const generation=++this.generation
  81. return this.serial(async()=>{
  82. const config=parseDesktopHostConfiguration(value)
  83. await this.store(config,generation)
  84. })
  85. }
  86. async store(config,generation){
  87. // Encrypt before stopping a working host: failed Keychain access preserves it.
  88. if(generation!==this.generation)return
  89. const bytes=await this.options.encrypt(JSON.stringify(config))
  90. if(generation!==this.generation)return
  91. await this.stopLoop()
  92. if(generation!==this.generation)return
  93. await mkdir(this.options.home,{recursive:true,mode:0o700})
  94. const temporary=`${this.path}.${randomUUID()}`
  95. try{await writeFile(temporary,bytes,{flag:'wx',mode:0o600});await rename(temporary,this.path)}
  96. finally{await rm(temporary,{force:true})}
  97. if(generation!==this.generation)return
  98. await this.startLoop(config)
  99. }
  100. start(){const generation=++this.generation;return this.serial(async()=>{const config=await this.read();if(generation!==this.generation)return;if(config)await this.startLoop(config)})}
  101. async startLoop(config){
  102. await this.stopLoop()
  103. this.config=config
  104. this.core=this.createCore({root:this.options.root,dataRoot:this.options.dataRoot})
  105. this.backoff=400
  106. this.publish(`电脑正在连接 ${new URL(config.serverURL).host}`)
  107. this.timer=setTimeout(()=>void this.cycle(),400)
  108. this.timer.unref?.()
  109. }
  110. async cycle(){
  111. const config=this.config,core=this.core
  112. if(!config||!core||this.core!==core)return
  113. try{
  114. await core.prepareInfo?.()
  115. if(this.config!==config||this.core!==core)return
  116. const value=await remoteExchange(config,{host:core.info(),results:core.takeResults()})
  117. this.backoff=400
  118. if(this.config!==config||this.core!==core)return
  119. this.publish(process.platform==='win32'&&!value.capabilities?.desktopPlatforms?.includes('win32')
  120. ? '已连接;服务器尚不支持 Windows 电脑操作,请升级服务器(聊天可继续使用)'
  121. : `电脑已连接 ${new URL(config.serverURL).host}`)
  122. core.acceptCapabilities?.(value.capabilities)
  123. await core.handle(value.commands??[])
  124. }catch(error){
  125. if(this.config!==config||this.core!==core)return
  126. core.acceptCapabilities?.(undefined)
  127. if(error&&error[FATAL]){this.publish(error.message);await this.stopLoop();return}
  128. this.backoff=Math.min(this.backoff*2,5000)
  129. this.publish(`电脑连接中断,正在重试:${String(error.message).slice(0,120)}`)
  130. }finally{
  131. if(this.core===core){this.timer=setTimeout(()=>void this.cycle(),this.backoff);this.timer.unref?.()}
  132. }
  133. }
  134. async stopLoop(){
  135. clearTimeout(this.timer);this.timer=undefined
  136. const core=this.core
  137. this.core=undefined;this.config=undefined
  138. if(core)await core.close().catch(()=>{})
  139. }
  140. stop(){this.generation++;return this.serial(()=>this.stopLoop())}
  141. forget(){this.generation++;return this.serial(async()=>{await this.stopLoop();await rm(this.path,{force:true});this.publish('未配置电脑')})}
  142. revoke(){return this.serial(async()=>{await this.core?.revoke()})}
  143. }