Files
dpl/scripts/fuc-xb-acceptance/client.py
T

86 lines
5.7 KiB
Python

#!/usr/bin/env python3
"""Real native subscription import and SOCKS traffic; no local desktop/TUN changes."""
import argparse,copy,gzip,hashlib,json,os,pathlib,socket,ssl,subprocess,time,urllib.error,urllib.parse,urllib.request
DIR=pathlib.Path('/var/www/wwwroot/fuc-xb-test/private/live-acceptance-20261104')
BIN=DIR/'bin/sing-box'
SHA='768d31fa7f68debc067bb4626539498a1e8751d36a7b99e1a54bee6a23815f93'
PANEL='/var/www/wwwroot/fuc-xb-test/acceptance/5a75c839b94709cac1be34d6b12a7e295b5833b0/scripts/fuc-xb-acceptance/node-panel.php'
def run(a,timeout=30):return subprocess.run(a,capture_output=True,timeout=timeout)
def context():
p=run(['php',PANEL,'export']);assert p.returncode==0
return json.loads(p.stdout)
def redact(s,c):
for k in ['server_token','gate_cookie','subscribe_token','qa_uuid']:s=s.replace(str(c[k]),'<redacted>')
return s[:1200]
def fetch(c,flag,token=None):
url=c['alias']+'/api/v1/client/subscribe?'+urllib.parse.urlencode({'token':token if token is not None else c['subscribe_token'],'flag':flag})
r=urllib.request.Request(url,headers={'Cookie':'fuc_stage_access='+c['gate_cookie'],'User-Agent':'sing-box/1.14.3' if flag=='sing-box' else 'clash.meta/1.19.0'})
try:
with urllib.request.urlopen(r,timeout=25)as o:
b=o.read(4194304);h=o.headers
if h.get('Content-Encoding')=='gzip':b=gzip.decompress(b)
return o.status,b
except urllib.error.HTTPError as e:return e.code,e.read(1024)
def prepare(c):
assert hashlib.sha256(BIN.read_bytes()).hexdigest()==SHA,'Client artifact changed'
status,raw=fetch(c,'sing-box');assert status==200,'Native subscription request failed'
cfg=json.loads(raw);nodes=[o for o in cfg['outbounds'] if o.get('type')=='vmess']
assert len(nodes)==1,'Expected exact QA-only VMess subscription'
n=nodes[0];assert n['server']==c['expected_exit'] and n['server_port']==c['port'] and n['uuid']==c['qa_uuid'],'Native subscription identity mismatch'
assert n['tls']['enabled'] and n['tls'].get('insecure') is False and n['tls']['server_name']==c['sni'],'Strict subscription TLS mismatch'
(DIR/'subscription-singbox.json').write_bytes(raw)
status,clash=fetch(c,'meta');assert status==200 and b'vmess' in clash and c['qa_uuid'].encode() in clash,'Native Clash subscription missing QA node'
(DIR/'subscription-clash.yaml').write_bytes(clash)
assert fetch(c,'sing-box','invalid-qa-token')[0]==403,'Invalid subscription token accepted'
cfg['inbounds']=[{'type':'mixed','tag':'qa-local','listen':'127.0.0.1','listen_port':19876}]
(DIR/'client-full.json').write_text(json.dumps(cfg))
check=run([str(BIN),'check','-c',str(DIR/'client-full.json')])
result={'native_subscription_downloaded':True,'exact_qa_node_and_uuid':True,'strict_tls_in_subscription':True,'invalid_token_rejected':True,'clash_native_format_present':True,'only_inbounds_replaced':True,'native_full_config_check_passed':check.returncode==0}
if check.returncode:result['check_error']=redact(check.stderr.decode(errors='replace'),c)
(DIR/'client-prepare-result.json').write_text(json.dumps(result,indent=2))
return result,cfg
def main():
os.umask(0o077);p=argparse.ArgumentParser();p.add_argument('action',choices=['prepare','run','revoked']);args=p.parse_args();c=context()
if args.action=='revoked':
status,_=fetch(c,'sing-box');print(json.dumps({'disabled_qa_subscription_status':status,'revoked':status==403}));return
result,cfg=prepare(c)
if args.action=='prepare' or not result['native_full_config_check_passed']:print(json.dumps(result));return
assert c['expected_exit']=='193.111.31.52'
# A positive TLS handshake is independently verified before starting the application client.
ctx=ssl.create_default_context()
with socket.create_connection((c['expected_exit'],c['port']),timeout=8)as raw:
with ctx.wrap_socket(raw,server_hostname=c['sni'])as tls:result['node_certificate_verified']=True;result['node_tls_version']=tls.version()
s=socket.socket()
try:s.bind(('127.0.0.1',19876))
finally:s.close()
cmd=['systemd-run','--quiet','--collect','--unit=fuc-xb-qa-client','--property=RuntimeMaxSec=600','--property=MemoryMax=384M','--property=CPUQuota=30%','--working-directory='+str(DIR),str(BIN),'run','-D',str(DIR),'-c',str(DIR/'client-full.json')]
started=run(cmd);assert started.returncode==0,'QA client unit failed'
try:
ready=False
for _ in range(50):
try:
with socket.create_connection(('127.0.0.1',19876),timeout=.2):ready=True;break
except OSError:time.sleep(.2)
if not ready:
log=run(['journalctl','-u','fuc-xb-qa-client','-n','8','--no-pager'])
result['client_start_error']=redact(log.stdout.decode(errors='replace'),c)
raise RuntimeError('Native full client did not start')
base=['curl','-sS','--proxy','socks5h://127.0.0.1:19876','--connect-timeout','8','--max-time','25']
ip=run(base+['https://api.ipify.org?format=json'],timeout=30)
assert ip.returncode==0 and json.loads(ip.stdout)['ip']==c['expected_exit'],'Wrong real proxy exit'
result['actual_proxy_exit_matches']=True;result['expected_exit']=c['expected_exit']
down=run(base+['https://speed.cloudflare.com/__down?bytes=65536'],timeout=30)
assert down.returncode==0 and len(down.stdout)==65536,'Real download payload mismatch'
result['download_payload_bytes']=len(down.stdout)
(DIR/'upload-qa.bin').write_bytes(b'FUC-XB-QA-ONLY\n'*2048)
up=run(base+['--data-binary','@'+str(DIR/'upload-qa.bin'),'https://httpbin.org/post'],timeout=30)
assert up.returncode==0 and len(json.loads(up.stdout).get('data',''))==len((DIR/'upload-qa.bin').read_bytes()),'Real upload echo mismatch'
result['upload_payload_bytes']=len((DIR/'upload-qa.bin').read_bytes())
result['real_client_network_passed']=True
finally:
run(['systemctl','stop','fuc-xb-qa-client'])
result['temporary_client_stopped']=True
(DIR/'client-run-result.json').write_text(json.dumps(result,indent=2))
print(json.dumps(result))
if __name__=='__main__':main()