remote-login.mjs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. /** Native remote login: username/password against a yaoyao Web server.
  2. * Mirrors the browser's CSRF/Origin dance so no server changes are needed,
  3. * and can enroll this Mac as a computer with the logged-in session. */
  4. export function normalizeServerURL(input){
  5. const raw=String(input??'').trim()
  6. if(!raw)throw new Error('请填写夭夭服务器地址')
  7. const withScheme=/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(raw)?raw:`http://${raw}`
  8. let url
  9. try{url=new URL(withScheme)}catch{throw new Error('服务器地址无效')}
  10. if(!['http:','https:'].includes(url.protocol)||url.username||url.password||url.search||url.hash||(url.pathname!==''&&url.pathname!=='/'))throw new Error('服务器地址无效')
  11. return url.origin
  12. }
  13. async function requestServer(fetchImpl,url,options){
  14. try{return await fetchImpl(url,options)}
  15. catch(error){
  16. if(['TimeoutError','AbortError'].includes(error.name))throw new Error('连接超时,请检查服务器地址和网络后重试。')
  17. throw new Error('无法连接服务器,请检查服务器地址和网络后重试。')
  18. }
  19. }
  20. /** Minimal cookie jar across the bootstrap → login dance. */
  21. class CookieJar{
  22. constructor(){this.cookies=new Map();this.details=new Map()}
  23. absorb(response){
  24. for(const line of response.headers.getSetCookie?.()??[]){
  25. const pair=line.split(';')[0],eq=pair.indexOf('=')
  26. if(eq<=0)continue
  27. const name=pair.slice(0,eq).trim(),value=pair.slice(eq+1).trim()
  28. this.cookies.set(name,value)
  29. const attributes=new Map(line.split(';').slice(1).map(part=>{
  30. const index=part.indexOf('=')
  31. return index<0?[part.trim().toLowerCase(),'']:[part.slice(0,index).trim().toLowerCase(),part.slice(index+1).trim()]
  32. }))
  33. const detail={name,value,path:attributes.get('path')||'/',httpOnly:attributes.has('httponly'),secure:attributes.has('secure')}
  34. const sameSite={strict:'strict',lax:'lax',none:'no_restriction'}[attributes.get('samesite')?.toLowerCase()]
  35. if(sameSite)detail.sameSite=sameSite
  36. const maxAge=attributes.get('max-age'),expires=Date.parse(attributes.get('expires'))
  37. if(maxAge!==undefined&&/^-?\d+$/.test(maxAge))detail.expirationDate=Date.now()/1000+Number(maxAge)
  38. else if(Number.isFinite(expires))detail.expirationDate=expires/1000
  39. this.details.set(name,detail)
  40. }
  41. }
  42. header(){return [...this.cookies.entries()].map(([name,value])=>`${name}=${value}`).join('; ')}
  43. }
  44. export async function inspectServer(serverURL,fetchImpl=globalThis.fetch){
  45. const base=normalizeServerURL(serverURL)
  46. const response=await requestServer(fetchImpl,new URL('/api/app/bootstrap',base),{
  47. headers:{accept:'application/json'},redirect:'error',signal:AbortSignal.timeout(10000),
  48. })
  49. if(!response.ok)throw new Error(`无法连接服务器(HTTP ${response.status})`)
  50. const info=await response.json().catch(()=>{throw new Error('服务器响应无效,请确认这是夭夭服务器地址')})
  51. if(typeof info?.csrfToken!=='string'||typeof info?.authenticated!=='boolean'||(info.serverKind&&info.serverKind!=='yaoyao-web'))
  52. throw new Error('服务器响应无效,请确认这是夭夭服务器地址')
  53. return info
  54. }
  55. export async function remoteSession(serverURL,{username,password,setup=false},fetchImpl=globalThis.fetch){
  56. const base=normalizeServerURL(serverURL)
  57. const user=String(username??'').trim(),pass=String(password??'')
  58. if(!user||!pass)throw new Error('请填写用户名和密码')
  59. const jar=new CookieJar()
  60. const bootstrap=await requestServer(fetchImpl,new URL('/api/app/bootstrap',base),{headers:{accept:'application/json'},redirect:'error',signal:AbortSignal.timeout(10000)})
  61. jar.absorb(bootstrap)
  62. if(!bootstrap.ok)throw new Error(`无法连接服务器(HTTP ${bootstrap.status})`)
  63. const info=await bootstrap.json().catch(()=>{throw new Error('服务器响应无效,请确认这是夭夭 Web 地址')})
  64. if(typeof info?.csrfToken!=='string')throw new Error('服务器响应无效,请确认这是夭夭 Web 地址')
  65. const response=await requestServer(fetchImpl,new URL(setup?'/api/app/setup':'/api/app/login',base),{
  66. method:'POST',redirect:'error',signal:AbortSignal.timeout(15000),
  67. headers:{accept:'application/json','content-type':'application/json',cookie:jar.header(),'x-csrf-token':info.csrfToken,origin:base},
  68. body:JSON.stringify({username:user,password:pass}),
  69. })
  70. jar.absorb(response)
  71. if(!setup&&(response.status===401||response.status===403)) {
  72. const body=await response.json().catch(()=>({}))
  73. if(body.code==='account_pending_approval')throw new Error(body.error || '账号尚未开通,请等待管理员开通。')
  74. throw new Error('用户名或密码不正确')
  75. }
  76. if(setup&&!response.ok){const body=await response.json().catch(()=>({}));throw new Error(body.error?.message||body.error||`创建管理员失败(HTTP ${response.status})`)}
  77. if(!response.ok)throw new Error(`登录失败(HTTP ${response.status})`)
  78. const result=await response.json().catch(()=>{throw new Error('登录响应无效')})
  79. if(!result?.user?.id)throw new Error('登录响应无效')
  80. return {origin:base,user:result.user,csrfToken:String(result.csrfToken??info.csrfToken),cookies:[...jar.cookies.entries()],cookieDetails:[...jar.details.values()]}
  81. }
  82. export async function enrollDesktopHost(session,{name,installId,previousHostId},fetchImpl=globalThis.fetch){
  83. const cookie=session.cookies.map(([key,value])=>`${key}=${value}`).join('; ')
  84. const response=await requestServer(fetchImpl,new URL('/api/app/admin/desktop-hosts',session.origin),{
  85. method:'POST',redirect:'error',signal:AbortSignal.timeout(15000),
  86. headers:{accept:'application/json','content-type':'application/json',cookie,'x-csrf-token':session.csrfToken,origin:session.origin},
  87. body:JSON.stringify({name:String(name).slice(0,100),...(installId?{installId}:{}),...(previousHostId?{previousHostId}:{})}),
  88. })
  89. if(response.status===403)throw new Error('需要管理员账号,才能把这台 Mac 注册为可远程控制的电脑')
  90. if(!response.ok)throw new Error(`注册电脑失败(HTTP ${response.status})`)
  91. const result=await response.json()
  92. if(typeof result?.token!=='string'||!result?.host?.id)throw new Error('注册电脑响应无效')
  93. return result
  94. }
  95. /** Registration owns a temporary cookie jar and never activates a desktop session. */
  96. export async function remoteRegistration(serverURL,{username,password},fetchImpl=globalThis.fetch){
  97. const base=normalizeServerURL(serverURL),jar=new CookieJar()
  98. const bootstrap=await requestServer(fetchImpl,new URL('/api/app/bootstrap',base),{redirect:'error',signal:AbortSignal.timeout(10000)})
  99. jar.absorb(bootstrap)
  100. const info=await bootstrap.json().catch(()=>({}))
  101. if(!bootstrap.ok||info.registrationAvailable!==true||info.setupRequired||typeof info.csrfToken!=='string')throw new Error('当前服务器尚不支持子账号注册,请联系管理员初始化或升级。')
  102. const response=await requestServer(fetchImpl,new URL('/api/app/register',base),{
  103. method:'POST',redirect:'error',signal:AbortSignal.timeout(15000),
  104. headers:{'content-type':'application/json',cookie:jar.header(),'x-csrf-token':info.csrfToken,origin:base},
  105. body:JSON.stringify({username:String(username).trim(),password}),
  106. })
  107. const result=await response.json().catch(()=>({}))
  108. if(!response.ok)throw new Error(result.error || `注册失败(HTTP ${response.status})`)
  109. if(result.registrationStatus!=='pending')throw new Error('注册响应无效,请联系管理员确认账号状态。')
  110. }