| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122 |
- import {readFile,writeFile,rename,mkdir,rm} from 'node:fs/promises'
- import {join} from 'node:path'
- import {randomUUID} from 'node:crypto'
- import {request as httpRequest} from 'node:http'
- import {request as httpsRequest} from 'node:https'
- import {parseDesktopHostConfiguration} from './host-config.mjs'
- const FATAL = Symbol('desktop-host-fatal')
- function remoteExchange(config,body){return new Promise((resolve,reject)=>{
- const url=new URL(`/api/desktop-host/v1/${config.hostId}/exchange`,config.serverURL)
- if(!['http:','https:'].includes(url.protocol))return reject(new Error('夭夭服务地址无效'))
- const bytes=Buffer.from(JSON.stringify(body)),send=url.protocol==='https'?httpsRequest:httpRequest
- 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=>{
- let size=0;const chunks=[]
- res.on('data',chunk=>{size+=chunk.length;if(size>256*1024)res.destroy(new Error('桌面命令超过限制'));else chunks.push(chunk)})
- res.on('error',reject)
- res.on('end',()=>{try{
- if(res.statusCode===401||res.statusCode===403){const error=new Error('桌面主机授权已失效,请在夭夭服务中重新注册并导入新配置');error[FATAL]=true;throw error}
- if(res.statusCode===409){const error=new Error('桌面主机协议不兼容,请更新夭夭后重新导入');error[FATAL]=true;throw error}
- if(res.statusCode!==200)throw new Error(`桌面主机服务未连接(HTTP ${res.statusCode})`)
- resolve(JSON.parse(Buffer.concat(chunks).toString()))
- }catch(error){reject(error)}})
- })
- req.on('error',reject)
- req.setTimeout(10000,()=>req.destroy(new Error('桌面主机连接超时')))
- req.end(bytes)
- })}
- /** Remote desktop host: imports an encrypted pairing config and exchanges
- * commands with the paired server. Native-only; no browser IPC. */
- export class DesktopHostManager {
- constructor(options){
- if(typeof options?.createCore!=='function')throw new Error('桌面主机需要命令执行核心')
- this.options=options
- this.path=join(options.home,'desktop-host.enc')
- this.createCore=options.createCore
- this.state='未配置桌面主机'
- this.core=undefined
- this.config=undefined
- this.timer=undefined
- this.backoff=400
- this.chain=Promise.resolve()
- this.generation=0
- }
- publish(message){this.state=message;this.options.onState?.(message)}
- serial(work){const result=this.chain.catch(()=>{}).then(work);this.chain=result;return result}
- async read(){
- let encrypted
- try{encrypted=await readFile(this.path)}catch(error){if(error.code==='ENOENT')return;throw error}
- try{return parseDesktopHostConfiguration(JSON.parse(await this.options.decrypt(encrypted)))}
- catch{throw new Error('无法解锁桌面主机配置,请检查钥匙串或重新导入')}
- }
- importFile(path){
- const generation=++this.generation
- return this.serial(async()=>{
- let config
- try{config=parseDesktopHostConfiguration(JSON.parse(await readFile(path,'utf8')))}
- catch(error){throw error instanceof Error?error:new Error('桌面主机配置无效,请从夭夭重新下载配置')}
- await this.store(config,generation)
- })
- }
- /** Adopt a config obtained in-process (e.g. after a native remote login). */
- adopt(value){
- const generation=++this.generation
- return this.serial(async()=>{
- const config=parseDesktopHostConfiguration(value)
- await this.store(config,generation)
- })
- }
- async store(config,generation){
- // Encrypt before stopping a working host: failed Keychain access preserves it.
- if(generation!==this.generation)return
- const bytes=await this.options.encrypt(JSON.stringify(config))
- if(generation!==this.generation)return
- await this.stopLoop()
- if(generation!==this.generation)return
- await mkdir(this.options.home,{recursive:true,mode:0o700})
- const temporary=`${this.path}.${randomUUID()}`
- try{await writeFile(temporary,bytes,{flag:'wx',mode:0o600});await rename(temporary,this.path)}
- finally{await rm(temporary,{force:true})}
- if(generation!==this.generation)return
- await this.startLoop(config)
- }
- 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)})}
- async startLoop(config){
- await this.stopLoop()
- this.config=config
- this.core=this.createCore({root:this.options.root,dataRoot:this.options.dataRoot})
- this.backoff=400
- this.publish(`桌面主机正在连接 ${new URL(config.serverURL).host}`)
- this.timer=setTimeout(()=>void this.cycle(),400)
- this.timer.unref?.()
- }
- async cycle(){
- const config=this.config,core=this.core
- if(!config||!core||this.core!==core)return
- try{
- const value=await remoteExchange(config,{host:core.info(),results:core.takeResults()})
- this.backoff=400
- if(this.config!==config||this.core!==core)return
- this.publish(`桌面主机已连接 ${new URL(config.serverURL).host}`)
- await core.handle(value.commands??[])
- }catch(error){
- if(this.config!==config||this.core!==core)return
- if(error&&error[FATAL]){this.publish(error.message);await this.stopLoop();return}
- this.backoff=Math.min(this.backoff*2,5000)
- this.publish(`桌面主机连接中断,正在重试:${String(error.message).slice(0,120)}`)
- }finally{
- if(this.core===core){this.timer=setTimeout(()=>void this.cycle(),this.backoff);this.timer.unref?.()}
- }
- }
- async stopLoop(){
- clearTimeout(this.timer);this.timer=undefined
- const core=this.core
- this.core=undefined;this.config=undefined
- if(core)await core.close().catch(()=>{})
- }
- stop(){this.generation++;return this.serial(()=>this.stopLoop())}
- forget(){this.generation++;return this.serial(async()=>{await this.stopLoop();await rm(this.path,{force:true});this.publish('未配置桌面主机')})}
- revoke(){return this.serial(async()=>{await this.core?.revoke()})}
- }
|