File size: 4,079 Bytes
90d354b
 
 
 
 
 
133b124
90d354b
 
 
 
 
 
133b124
90d354b
 
 
 
133b124
 
 
 
 
 
 
 
 
90d354b
133b124
 
90d354b
 
 
133b124
90d354b
 
133b124
90d354b
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import http from 'node:http'
import path from 'node:path'
import {fileURLToPath} from 'node:url'
import {timingSafeEqual} from 'node:crypto'
import {localApiPlugin} from './local-api.mjs'
import {runtimeContext} from './runtime-context.mjs'
import {appPublic,appToken,appError,AppError} from './app-api.mjs'

const TOKEN=/^[a-f0-9]{64}$/
function same(a,b){const aa=Buffer.from(a||''),bb=Buffer.from(b||'');return aa.length===bb.length&&aa.length>0&&timingSafeEqual(aa,bb)}
export function createCloudHandler({dataDir,internalKey,plannerLimit=12,totalPlannerLimit=120}){
  const workspaces=new Map(),rates=new Map()
  const send=(res,status,error)=>{res.writeHead(status,{'Content-Type':'application/json','Cache-Control':'no-store'});res.end(JSON.stringify({error}))}
  const sendApp=(res,status,code,message)=>{const result=appError(new AppError(status,code,message));res.writeHead(status,{'Content-Type':'application/json','Cache-Control':'no-store'});res.end(JSON.stringify(result.body))}
  const limited=(key,max)=>{const now=Date.now(),old=rates.get(key),row=old&&now-old.start<3600000?old:{start:now,count:0};row.count++;rates.set(key,row);return row.count>max}
  return (req,res)=>{
    if(!same(req.headers['x-home-pulse-internal'],internalKey))return send(res,403,'访问来源无效')
    const url=new URL(req.url,'http://localhost')
    if(req.headers.origin&&req.headers.origin!==`http://${req.headers.host}`&&req.headers.origin!==`https://${req.headers.host}`)return send(res,403,'来源不匹配')
    const native=url.pathname.startsWith('/api/v1/')
    if(native){const result=appPublic(req,url);if(result){res.writeHead(result.status,{'Content-Type':'application/json','Cache-Control':'no-store'});return res.end(JSON.stringify(result.body))}}
    const token=native?appToken(req):String(req.headers['x-home-pulse-workspace']||'')
    if(!token||!TOKEN.test(token)){
      if(native){const result=appError(new AppError(401,'UNAUTHORIZED','请提供 Home Pulse 空间令牌'));res.writeHead(result.status,{'Content-Type':'application/json','Cache-Control':'no-store'});return res.end(JSON.stringify(result.body))}
      return send(res,401,'请刷新页面,重新连接你的空间')
    }
    req.headers['x-home-pulse-workspace']=token
    if(!url.pathname.startsWith('/api/'))return send(res,404,'接口不存在')
    if(req.method==='POST'&&['/api/setup/draft','/api/setup/prepare','/api/plan','/api/v1/setups/draft','/api/v1/setups/prepare'].includes(url.pathname)){
      if(limited(token,plannerLimit)||limited('all',totalPlannerLimit))return native?sendApp(res,429,'PLANNER_RATE_LIMITED','本小时的任务设置次数已用完,请稍后再试。已有任务仍可观察。'):send(res,429,'本小时的任务设置次数已用完,请稍后再试。已有任务仍可观察。')
    }
    let entry=workspaces.get(token)
    if(!entry){
      if(workspaces.size>=2000)return native?sendApp(res,503,'WORKSPACE_LIMIT','当前体验人数较多,请稍后再试'):send(res,503,'当前体验人数较多,请稍后再试')
      let middleware
      const root=path.join(dataDir,'workspaces',token)
      localApiPlugin(root,{appScoped:true}).configureServer({middlewares:{use:m=>middleware=m}})
      entry={middleware};workspaces.set(token,entry)
    }
    const port=Number(req.headers['x-home-pulse-vision-port'])
    const modelBase=Number.isInteger(port)&&port>=1024&&port<=65535?`http://127.0.0.1:${port}`:undefined
    return runtimeContext.run({modelBase},()=>entry.middleware(req,res,()=>send(res,404,'接口不存在')))
  }
}
if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url)){
  if(!process.env.HOME_PULSE_INTERNAL_KEY)throw new Error('Missing internal gateway key')
  const server=http.createServer(createCloudHandler({dataDir:process.env.HOME_PULSE_DATA_DIR||path.resolve('.local/cloud'),internalKey:process.env.HOME_PULSE_INTERNAL_KEY}))
  server.requestTimeout=240000
  server.listen(Number(process.env.HOME_PULSE_API_PORT||7861),'127.0.0.1',()=>console.log('Home Pulse workspace API is ready'))
}