Files
dpl/scripts/fuc-xb-acceptance/node-bridge.py
T

56 lines
3.7 KiB
Python

#!/usr/bin/env python3
"""Loopback-only adapter for the staging gate. Native XB node auth stays required."""
import argparse, hashlib, http.server, json, pathlib, ssl, threading, urllib.error, urllib.parse, urllib.request
ALLOWED = {'/api/v1/server/UniProxy/'+x for x in ['config','user','push','alive','alivelist','status']}
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self,*args,**kwargs): return None
def allowed(method,path,node,token):
p=urllib.parse.urlsplit(path);q=urllib.parse.parse_qs(p.query,keep_blank_values=True)
return (not p.scheme and not p.netloc and p.path in ALLOWED and method in ('GET','POST') and
q.get('node_id')==[str(node)] and q.get('token')==[token] and
q.get('node_type',['v2ray']) in (['v2ray'],['vmess']) and
set(q).issubset({'node_id','token','node_type'}))
def main():
parser=argparse.ArgumentParser();parser.add_argument('--config',required=True);args=parser.parse_args()
path=pathlib.Path(args.config);assert path.stat().st_mode & 0o077 == 0
cfg=json.loads(path.read_text());assert cfg['source']=='https://fuc-xb-test.gemcook.net'
opener=urllib.request.build_opener(urllib.request.HTTPSHandler(context=ssl.create_default_context()),NoRedirect())
metrics={'requests':{},'user_counts':[],'nonempty_pushes':0};lock=threading.Lock()
def record(path,status,body):
with lock:
key=path+':'+str(status);metrics['requests'][key]=metrics['requests'].get(key,0)+1
if path.endswith('/user') and status==200:
try:metrics['user_counts']=(metrics['user_counts']+[len(json.loads(body)['users'])])[-20:]
except Exception:pass
(pathlib.Path(args.config).parent/'bridge-metrics.json').write_text(json.dumps(metrics))
class Handler(http.server.BaseHTTPRequestHandler):
def log_message(self,*args):pass
def do_GET(self):self.forward()
def do_POST(self):self.forward()
def forward(self):
if self.client_address[0]!='127.0.0.1' or not allowed(self.command,self.path,cfg['node_id'],cfg['server_token']):
self.send_error(403);return
length=int(self.headers.get('Content-Length','0'))
if length<0 or length>2097152:self.send_error(413);return
payload=self.rfile.read(length) if self.command=='POST' else None
headers={'Cookie':'fuc_stage_access='+cfg['gate_cookie'],'Accept':'application/json'}
if self.command=='POST':headers['Content-Type']='application/json'
if self.headers.get('If-None-Match'):headers['If-None-Match']=self.headers['If-None-Match']
p=urllib.parse.urlsplit(self.path).path
try:
req=urllib.request.Request(cfg['source']+self.path,data=payload,headers=headers,method=self.command)
try:res=opener.open(req,timeout=15)
except urllib.error.HTTPError as e:res=e
with res:status=res.status;body=res.read();response_headers=res.headers
if len(body)>2097152:raise ValueError('oversized upstream')
record(p,status,body)
self.send_response(status)
for key in ['Content-Type','ETag']:
if response_headers.get(key):self.send_header(key,response_headers[key])
self.send_header('Cache-Control','no-store');self.send_header('Content-Length',str(len(body)));self.end_headers();self.wfile.write(body)
except Exception:
self.send_response(502);self.send_header('Content-Length','0');self.end_headers()
server=http.server.ThreadingHTTPServer(('127.0.0.1',28766),Handler)
server.daemon_threads=True;server.serve_forever()
if __name__=='__main__':main()