diff --git a/scripts/fuc-xb-acceptance/cashier-api.py b/scripts/fuc-xb-acceptance/cashier-api.py index f74f6bd8..48f299bf 100644 --- a/scripts/fuc-xb-acceptance/cashier-api.py +++ b/scripts/fuc-xb-acceptance/cashier-api.py @@ -19,7 +19,7 @@ for kind in ['alipay','wxpay']: p=urllib.parse.urlsplit(url);assert p.scheme=='https' and p.hostname and not p.username and not p.password and (p.port is None or p.port==443) assert p.hostname not in ['fuc-xb-test.gemcook.net','fuc-xb-test.tomtojapan.online'],'Do not follow merchant return' ips={x[4][0] for x in socket.getaddrinfo(p.hostname,443,type=socket.SOCK_STREAM)};assert ips and all(ipaddress.ip_address(ip).is_global for ip in ips) - req=urllib.request.Request(url,headers={'User-Agent':'Mozilla/5.0','Referer':'https://pay.airspay.top/'}) + req=urllib.request.Request(url,headers={'User-Agent':'Mozilla/5.0','Referer':'https://pay.airspay.top/','Accept':'text/html'}) try:res=op.open(req,timeout=25) except urllib.error.HTTPError as e:res=e with res: diff --git a/scripts/fuc-xb-acceptance/cashier.py b/scripts/fuc-xb-acceptance/cashier.py index d8c76b59..c3589891 100644 --- a/scripts/fuc-xb-acceptance/cashier.py +++ b/scripts/fuc-xb-acceptance/cashier.py @@ -18,21 +18,26 @@ class Form(HTMLParser): if self.title:self.titles.append(s.strip()) class NoRedirect(urllib.request.HTTPRedirectHandler): def redirect_request(self,*a,**kw):return None -opener=urllib.request.build_opener(urllib.request.HTTPSHandler(context=ssl.create_default_context()),NoRedirect()) -out=[] -for kind in ['alipay','wxpay']: - p=Form();p.feed((ROOT/('cashier-'+kind+'.html')).read_text());assert len(p.forms)==1 - f=p.forms[0];v=f['fields'];assert f['action']=='https://api.shangri-la.vc/submit.php' and f['method']=='post' - assert set(v).issubset({'pid','type','notify_url','return_url','out_trade_no','name','money','sign','sign_type'}) - assert v['type']==kind and Decimal(v['money'])==Decimal('1') and v['sign_type']=='MD5' - req=urllib.request.Request(f['action'],data=urllib.parse.urlencode(v).encode(),headers={'Content-Type':'application/x-www-form-urlencoded','User-Agent':'FUC-XB-Isolated-Acceptance/1.0'},method='POST') - try:res=opener.open(req,timeout=25) - except urllib.error.HTTPError as e:res=e - with res: - status=res.status;b=res.read(2097152);location=res.headers.get('Location','') - (ROOT/('cashier-final-'+kind+'.html')).write_bytes(b) - parsed=Form();parsed.feed(b.decode('utf-8',errors='replace')) - failures=[x for x in ['签名验证失败','商户不存在','商户已被封禁','商户未开启','支付金额不能','参数错误'] if x in b.decode('utf-8',errors='replace')] - out.append({'type':kind,'observed_processor_host':'api.shangri-la.vc','http_status':status,'tls_verified':True,'title':' '.join(parsed.titles)[:120],'redirect_host':urllib.parse.urlsplit(location).hostname,'error_indicators':failures,'response_bytes':len(b),'body_sha256':hashlib.sha256(b).hexdigest(),'payment_authorization_attempted':False}) -result={'processor_unpaid_auto_post_only':True,'real_money_paid':0,'cases':out,'actual_paid_callback_not_tested':True} -(ROOT/'cashier-final-result.json').write_text(json.dumps(result,ensure_ascii=False,indent=2));print(json.dumps(result,ensure_ascii=False)) +def run(root=ROOT,opener=None): + if opener is None:opener=urllib.request.build_opener(urllib.request.HTTPSHandler(context=ssl.create_default_context()),NoRedirect()) + out=[] + for kind in ['alipay','wxpay']: + p=Form();p.feed((root/('cashier-'+kind+'.html')).read_text());assert len(p.forms)==1 + f=p.forms[0];v=f['fields'];assert f['action']=='https://api.shangri-la.vc/submit.php' and f['method']=='post' + assert set(v).issubset({'pid','type','notify_url','return_url','out_trade_no','name','money','sign','sign_type'}) + assert v['type']==kind and Decimal(v['money'])==Decimal('1') and v['sign_type']=='MD5' + # The processor serves an unrelated 404 page unless HTML content negotiation is explicit. + # Match a browser's navigation semantics; this does not authorize payment. + req=urllib.request.Request(f['action'],data=urllib.parse.urlencode(v).encode(),headers={'Content-Type':'application/x-www-form-urlencoded','User-Agent':'FUC-XB-Isolated-Acceptance/1.0','Accept':'text/html'},method='POST') + try:res=opener.open(req,timeout=25) + except urllib.error.HTTPError as e:res=e + with res: + status=res.status;b=res.read(2097152);location=res.headers.get('Location','') + (root/('cashier-final-'+kind+'.html')).write_bytes(b) + parsed=Form();parsed.feed(b.decode('utf-8',errors='replace')) + failures=[x for x in ['签名验证失败','商户不存在','商户已被封禁','商户未开启','支付金额不能','参数错误','订单已过期','订单不存在','支付参数有变化'] if x in b.decode('utf-8',errors='replace')] + out.append({'type':kind,'observed_processor_host':'api.shangri-la.vc','http_status':status,'tls_verified':True,'title':' '.join(parsed.titles)[:120],'redirect_host':urllib.parse.urlsplit(location).hostname,'error_indicators':failures,'response_bytes':len(b),'body_sha256':hashlib.sha256(b).hexdigest(),'payment_authorization_attempted':False}) + result={'processor_unpaid_auto_post_only':True,'real_money_paid':0,'cases':out,'actual_paid_callback_not_tested':True} + (root/'cashier-final-result.json').write_text(json.dumps(result,ensure_ascii=False,indent=2)) + return result +if __name__=='__main__':print(json.dumps(run(),ensure_ascii=False)) diff --git a/scripts/fuc-xb-acceptance/test_cashier.py b/scripts/fuc-xb-acceptance/test_cashier.py new file mode 100644 index 00000000..00eeccc0 --- /dev/null +++ b/scripts/fuc-xb-acceptance/test_cashier.py @@ -0,0 +1,42 @@ +"""Regression for the observed processor's HTML negotiation and unpaid boundary.""" +import importlib.util,json,pathlib,tempfile,unittest,urllib.parse + +spec=importlib.util.spec_from_file_location('cashier',pathlib.Path(__file__).with_name('cashier.py')) +cashier=importlib.util.module_from_spec(spec);spec.loader.exec_module(cashier) + +class Response: + def __init__(self,status,body):self.status=status;self.body=body;self.headers={} + def __enter__(self):return self + def __exit__(self,*args):return False + def read(self,limit):return self.body[:limit] + +class Processor: + def __init__(self,expired=False):self.requests=[];self.expired=expired + def open(self,req,timeout): + self.requests.append(req) + if req.get_header('Accept')!='text/html':return Response(404,b'404 Not Found') + if self.expired:return Response(200,'支付错误订单已过期'.encode()) + fields=urllib.parse.parse_qs(req.data.decode()) + return Response(200,(''+fields['type'][0]+' cashier').encode()) + +class Cashier(unittest.TestCase): + def fixture(self,root): + for kind in ['alipay','wxpay']: + fields={'pid':'synthetic','type':kind,'out_trade_no':'QA-only','money':'1','sign':'synthetic','sign_type':'MD5'} + html='
'+''.join('' for k,v in fields.items())+'
' + (root/('cashier-'+kind+'.html')).write_text(html) + def test_html_navigation_reaches_both_cashiers_without_payment_or_new_order(self): + with tempfile.TemporaryDirectory()as d: + root=pathlib.Path(d);self.fixture(root);processor=Processor();result=cashier.run(root,processor) + self.assertEqual([c['http_status']for c in result['cases']],[200,200]) + self.assertEqual(len(processor.requests),2) + self.assertTrue(all(req.get_method()=='POST'and req.full_url=='https://api.shangri-la.vc/submit.php'for req in processor.requests)) + self.assertEqual(result['real_money_paid'],0) + self.assertTrue(result['actual_paid_callback_not_tested']) + self.assertEqual(json.loads((root/'cashier-final-result.json').read_text()),result) + def test_expired_200_is_reported_as_business_error(self): + with tempfile.TemporaryDirectory()as d: + root=pathlib.Path(d);self.fixture(root);result=cashier.run(root,Processor(expired=True)) + self.assertTrue(all('订单已过期'in c['error_indicators']for c in result['cases'])) + +if __name__=='__main__':unittest.main() diff --git a/scripts/fuc-xb-refresh/README.md b/scripts/fuc-xb-refresh/README.md new file mode 100644 index 00000000..75f1e527 --- /dev/null +++ b/scripts/fuc-xb-refresh/README.md @@ -0,0 +1,5 @@ +# FUC-XB 2026-11-05隔离刷新 + +仅适用用户明确授权的旧FUC→现有独立测试站重新迁移;源正式站只读、不切正式、不改DPL/HN。project.py只消费同宿主private一致性快照,动态计算人数、权益、完整预购退款及VIP期初,不使用旧11542人/13笔常数。refresh.php只允许fuc_xb_test,要求精确投影SHA、完整备份和恢复核验;拒绝目标存在真实订单、节点、会话或非期初VIP。一次事务替换用户/历史套餐/组和期初,全字段及资金回读通过再提交;保留原合成QA认证,ID按新数据最大值调整,旧账不进入新业务订单。 + +程序文件不包含凭据/用户行,运行私有数据不提交Git。失败先查refresh-intent及数据库实际状态,不删除日志盲重跑。数据库提交与私有QA文件更新为两阶段;未知状态按备份/日志恢复,不能再次给钱包返款。测试节点按Xboard-Node和原生V2机器接口验收,不沿用旧XrayR。 diff --git a/scripts/fuc-xb-refresh/project.py b/scripts/fuc-xb-refresh/project.py new file mode 100644 index 00000000..a6831afe --- /dev/null +++ b/scripts/fuc-xb-refresh/project.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python3 +"""Project a fresh, server-private FUC snapshot; never connects to either database.""" +from pathlib import Path +from collections import defaultdict,Counter +from decimal import Decimal +from datetime import datetime +from zoneinfo import ZoneInfo +import gzip,json,hashlib,os,re +os.umask(0o077) +ROOT=Path('/var/www/wwwroot/fuc-xb-test/private/refresh-20261105') +def main(): + manifest=json.loads((ROOT/'snapshot-manifest.json').read_text());source=ROOT/'snapshot.jsonl.gz' + assert hashlib.sha256(source.read_bytes()).hexdigest()==manifest['sha256'] + target=ROOT/'projection.json';assert not target.exists(),'Existing projection: verify before replacing' + tables=defaultdict(list);head=foot=None + with gzip.open(source,'rt')as f: + for line in f: + v=json.loads(line) + if v['kind']=='header':head=v + elif v['kind']=='footer':foot=v + else:tables[v['table']].append(v['row']) + assert head and foot and head['counts']==foot['counts']=={k:len(tables[k])for k in head['counts']} + def integer(v):return int(v or 0) + def cents(v): + n=Decimal(str(v or 0))*100;assert n==n.to_integral_value(),'Fractional cents';return int(n) + def timestamp(v): + try:return int(datetime.strptime(v,'%Y-%m-%d %H:%M:%S').replace(tzinfo=ZoneInfo('Asia/Shanghai')).timestamp()) + except(ValueError,TypeError):return 0 + users={integer(u['id']):u for u in tables['user']};assert len(users)==len(tables['user']) + # Only explicitly confirmed original identities receive these overrides. + mapping=json.loads((ROOT/'identity-overrides.json').read_text())['users'] + links={} + for link in tables['link']: + uid=integer(link['userid']) + if uid in users:assert uid not in links;links[uid]=link['token'] + invoices=defaultdict(list) + for inv in tables['invoice']:invoices[integer(inv['order_id'])].append(inv) + refunds=[];refunded=Counter() + for o in tables['order']: + if o['status']!='pending' or integer(o['user_id'])not in users:continue + inv=invoices[integer(o['id'])];assert len(inv)==1,'Prepaid invoice cardinality changed';i=inv[0] + assert integer(i['user_id'])==integer(o['user_id'])and i['status']in ['paid_gateway','paid_balance','paid_admin'] + amount=cents(i['price'])+(cents(i['money_use'])if i['status']=='paid_gateway'else 0);assert amount>=0 + v={'order_id':integer(o['id']),'user_id':integer(o['user_id']),'invoice_id':integer(i['id']),'amount_cents':amount};refunds.append(v);refunded[v['user_id']]+=amount + cohorts=sorted({(integer(u['class']),integer(u['node_group']))for u in users.values()if integer(u['class'])>0}) + groups={c:i+1 for i,c in enumerate(cohorts)} + keys=sorted({((integer(u['class']),integer(u['node_group'])),integer(u['transfer_enable']),integer(u['node_speedlimit']))for u in users.values()if integer(u['class'])>0}) + plans={c:i+1 for i,c in enumerate(keys)};clock=int(datetime.fromisoformat(head['snapshot_utc']).timestamp()) + thresholds=sorted((cents(v['amount']),integer(v['rate']))for v in tables['vip_map']) + def discount(n):return max([rate for amount,rate in thresholds if n>=amount]or[0]) + rows=[];openings=[];generated=0 + for uid,u in sorted(users.items()): + email=mapping.get(str(uid),{}).get('target_email',str(u['email']or'').strip().lower());assert re.fullmatch(r'[^\s@]+@[^\s@]+\.[^\s@]+',email),'Unapproved invalid email in new snapshot' + assert re.fullmatch(r'\$2[aby]\$\d\d\$[./A-Za-z0-9]{53}',u['pass']),'Unsupported password' + assert re.fullmatch(r'[0-9a-fA-F]{8}-(?:[0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}',u['uuid']) + cohort=(integer(u['class']),integer(u['node_group']));quota=integer(u['transfer_enable']);speed=integer(u['node_speedlimit']);opening=max(0,cents(u['total_pay'])-refunded[uid]);token=links.get(uid) + if not token:token=os.urandom(16).hex();generated+=1 + row={'id':uid,'email':email,'password':u['pass'],'password_algo':None,'password_salt':None,'uuid':u['uuid'],'token':token,'invite_user_id':integer(u['ref_by'])or None,'transfer_enable':quota,'u':integer(u['u']),'d':integer(u['d']),'expired_at':timestamp(u['class_expire']),'balance':cents(u['money'])+refunded[uid],'commission_balance':cents(u['money_aff']),'banned':int(bool(integer(u['is_banned'])or integer(u['is_shadow_banned']))),'is_admin':0,'is_staff':0,'group_id':groups.get(cohort),'plan_id':plans.get((cohort,quota,speed)),'speed_limit':speed or None,'device_limit':None,'created_at':timestamp(u['reg_date'])or None,'updated_at':clock,'next_reset_at':None,'discount':discount(opening),'remind_expire':0,'remind_traffic':0} + rows.append(row);openings.append({'user_id':uid,'uuid':u['uuid'],'source_cumulative_cents':cents(u['total_pay']),'returned_prepaid_cents':refunded[uid],'opening_cumulative_cents':opening}) + assert len({r['email']for r in rows})==len(rows)and len({r['uuid']for r in rows})==len(rows)and len({r['token']for r in rows})==len(rows) + assert all(not r['invite_user_id']or r['invite_user_id']in users for r in rows),'Orphan referral requires review' + group_rows=[{'id':i,'name':'历史权限组 '+str(i),'created_at':clock,'updated_at':clock}for key,i in groups.items()] + plan_rows=[] + for (cohort,quota,speed),i in plans.items():plan_rows.append({'id':i,'group_id':groups[cohort],'name':'历史权益 '+str(i),'transfer_enable':(quota+1073741823)//1073741824,'speed_limit':speed or None,'show':0,'sell':0,'renew':0,'prices':'{}','reset_traffic_method':2,'content':'迁移保留原始字节额度和到期;禁止直接续售或自动重置','created_at':clock,'updated_at':clock}) + value={'snapshot_sha256':manifest['sha256'],'groups':group_rows,'plans':plan_rows,'users':rows,'vip_openings':openings,'refunds':refunds} + target.write_text(json.dumps(value,ensure_ascii=False,separators=(',',':')));target.chmod(0o600) + summary={'users':len(rows),'groups':len(groups),'hidden_legacy_plans':len(plans),'prepaid_orders':len(refunds),'prepaid_refund_cents':sum(refunded.values()),'wallet_cents':sum(r['balance']for r in rows),'commission_cents':sum(r['commission_balance']for r in rows),'vip_openings':len(openings),'vip_negative_floored':sum(v['source_cumulative_cents']make(Illuminate\Contracts\Console\Kernel::class)->bootstrap(); +use Illuminate\Support\Facades\DB;use App\Models\{User,Plan,Server,ServerMachine}; +if(DB::connection()->getDatabaseName()!=='fuc_xb_test')throw new RuntimeException('Wrong target database'); +$summary=json_decode(file_get_contents($dir.'/projection-summary.json'),true,512,JSON_THROW_ON_ERROR); +if(!hash_equals($summary['projection_sha256'],$options['apply'])||!hash_equals($options['apply'],hash_file('sha256',$dir.'/projection.json')))throw new RuntimeException('Projection checksum changed'); +$backup=json_decode(file_get_contents($private.'/refresh-20261105-before/receipt.json'),true,512,JSON_THROW_ON_ERROR); +if(!$backup['passed']||!$backup['all_table_rows_and_content_hashes_equal']||!hash_equals($backup['backup_sha256'],hash_file('sha256',$private.'/refresh-20261105-before/fuc_xb_test.sql.gz')))throw new RuntimeException('Verified backup required'); +$marker=$dir.'/refresh-applied.json';if(file_exists($marker))throw new RuntimeException('Refresh already journaled; verify before retry'); +$data=json_decode(file_get_contents($dir.'/projection.json'),true,512,JSON_THROW_ON_ERROR); +if(count($data['users'])!==$summary['users']||count($data['vip_openings'])!==$summary['users'])throw new RuntimeException('Projection count mismatch'); +foreach(['v2_order','v2_commission_log','personal_access_tokens','v2_stat_user','v2_stat_server','v2_traffic_reset_logs']as$table)if(DB::table($table)->exists())throw new RuntimeException('Unexpected target business rows: '.$table); +if(Server::count()||ServerMachine::count()||DB::table('fuc_vip_entries')->where('kind','!=','opening')->exists())throw new RuntimeException('Unexpected test node or VIP activity'); +$qaFile=$private.'/qa-credentials.json';$qa=json_decode(file_get_contents($qaFile),true,512,JSON_THROW_ON_ERROR);$qaUser=User::findOrFail($qa['user_id']);$qaPlan=Plan::findOrFail($qa['plan_id']); +if($qaUser->email!=='qa@fuc-xb.invalid'||$qaUser->is_admin||$qaUser->is_staff)throw new RuntimeException('QA identity mismatch'); +$adminRows=array_values(array_filter($data['users'],fn($r)=>$r['email']===$secrets['username']));if(count($adminRows)!==1)throw new RuntimeException('Default admin missing or duplicated');$admin=$adminRows[0]; +if(!App\Utils\Helper::multiPasswordVerify($admin['password_algo'],$admin['password_salt'],$secrets['password'],$admin['password']))throw new RuntimeException('Source default admin credential changed; not overwritten'); +$qaRow=$qaUser->getAttributes();$qaPlanRow=$qaPlan->getAttributes();$qaRow['id']=max(array_column($data['users'],'id'))+1;$qaRow['plan_id']=null;$qaRow['group_id']=null;$qaPlanRow['id']=max(array_column($data['plans'],'id'))+1; +$qaRow['balance']=100000;$qaRow['u']=$qaRow['d']=0;$qaRow['transfer_enable']=0;$qaRow['expired_at']=0;$qaRow['discount']=null; +$qa['user_id']=$qaRow['id'];$qa['plan_id']=$qaPlanRow['id']; +app(App\Services\Plugin\PluginManager::class)->initializeEnabledPlugins(); +$before=['users'=>User::count(),'plans'=>Plan::count(),'groups'=>DB::table('v2_server_group')->count()]; +file_put_contents($dir.'/refresh-intent.json',json_encode(['projection_sha256'=>$options['apply'],'before'=>$before,'backup_sha256'=>$backup['backup_sha256']])); +function normalizeRefresh($r):array{return array_map(fn($v)=>$v===null?null:(string)$v,(array)$r);} +DB::transaction(function()use($data,$summary,$qaRow,$qaPlanRow,$admin){ + foreach(['fuc_vip_entries','fuc_vip_accounts','v2_user','v2_plan','v2_server_group']as$t)DB::table($t)->delete(); + foreach(['v2_server_group'=>'groups','v2_plan'=>'plans','v2_user'=>'users']as$t=>$key){ + foreach($data[$key]as$row)DB::table($t)->insert($row); + foreach($data[$key]as$row){$actual=DB::table($t)->where('id',$row['id'])->first();foreach($row as$k=>$v)if(normalizeRefresh([$v])!==normalizeRefresh([$actual->$k]))throw new RuntimeException('Full-field refresh mismatch: '.$t.'.'.$k);} + } + foreach($data['vip_openings']as$v)app(Plugin\VipLoyalty\Service::class)->opening($v['user_id'],$v['uuid'],$v['opening_cumulative_cents'],$data['snapshot_sha256']); + if((int)User::sum('balance')!==$summary['wallet_cents']||(int)User::sum('commission_balance')!==$summary['commission_cents']||DB::table('fuc_vip_accounts')->count()!==$summary['users'])throw new RuntimeException('Refresh money or VIP mismatch'); + DB::table('v2_user')->where('id',$admin['id'])->update(['is_admin'=>1]);DB::table('v2_user')->insert($qaRow);DB::table('v2_plan')->insert($qaPlanRow); +}); +$temp=$qaFile.'.refresh';file_put_contents($temp,json_encode($qa));chmod($temp,0600);rename($temp,$qaFile); +$result=['passed'=>true,'snapshot_sha256'=>$data['snapshot_sha256'],'migrated_users'=>$summary['users'],'hidden_plans'=>$summary['hidden_legacy_plans'],'groups'=>$summary['groups'],'wallet_cents'=>$summary['wallet_cents'],'commission_cents'=>$summary['commission_cents'],'prepaid_refund_orders'=>$summary['prepaid_orders'],'prepaid_refund_cents'=>$summary['prepaid_refund_cents'],'vip_openings'=>DB::table('fuc_vip_accounts')->count(),'total_users'=>User::count(),'admins'=>User::where('is_admin',1)->count(),'full_field_readback'=>true,'qa_credentials_preserved'=>true,'native_orders'=>DB::table('v2_order')->count(),'source_writes'=>0,'shared_core_changed'=>false]; +file_put_contents($marker,json_encode($result,JSON_PRETTY_PRINT));chmod($marker,0600);echo json_encode($result).PHP_EOL;